diff --git a/chrome/browser/predictors/resource_prefetch_predictor.cc b/chrome/browser/predictors/resource_prefetch_predictor.cc
index 5bc03cb0..65f3f90 100644
--- a/chrome/browser/predictors/resource_prefetch_predictor.cc
+++ b/chrome/browser/predictors/resource_prefetch_predictor.cc
@@ -1637,8 +1637,18 @@
   if (initialization_state_ != INITIALIZED)
     return;
 
-  if (!config_.is_manifests_enabled ||
-      host.length() > ResourcePrefetchPredictorTables::kMaxStringLength ||
+  if (!config_.is_manifests_enabled)
+    return;
+
+  // The manifest host has "www." prefix stripped, the manifest host could
+  // correspond to two different hosts in the prefetch database.
+  UpdatePrefetchDataByManifest(host, PREFETCH_KEY_TYPE_HOST,
+                               host_table_cache_.get(), manifest);
+  UpdatePrefetchDataByManifest("www." + host, PREFETCH_KEY_TYPE_HOST,
+                               host_table_cache_.get(), manifest);
+
+  // The manifest is too large to store.
+  if (host.length() > ResourcePrefetchPredictorTables::kMaxStringLength ||
       static_cast<uint32_t>(manifest.ByteSize()) > kMaxManifestByteSize) {
     return;
   }
@@ -1661,6 +1671,48 @@
                  host, cache_entry->second));
 }
 
+void ResourcePrefetchPredictor::UpdatePrefetchDataByManifest(
+    const std::string& key,
+    PrefetchKeyType key_type,
+    PrefetchDataMap* data_map,
+    const precache::PrecacheManifest& manifest) {
+  DCHECK_CURRENTLY_ON(BrowserThread::UI);
+  DCHECK_EQ(INITIALIZED, initialization_state_);
+
+  auto resource_entry = data_map->find(key);
+  if (resource_entry == data_map->end())
+    return;
+
+  PrefetchData& data = resource_entry->second;
+  std::map<std::string, int> manifest_index;
+  for (int i = 0; i < manifest.resource_size(); ++i)
+    manifest_index.insert({manifest.resource(i).url(), i});
+
+  bool was_updated = false;
+  base::Optional<std::vector<bool>> unused_bitset =
+      precache::GetResourceBitset(manifest, internal::kUnusedRemovedExperiment);
+  if (unused_bitset.has_value()) {
+    // Remove unused resources from |data|.
+    auto new_end = std::remove_if(
+        data.mutable_resources()->begin(), data.mutable_resources()->end(),
+        [&](const ResourceData& x) {
+          auto it = manifest_index.find(x.resource_url());
+          if (it == manifest_index.end())
+            return false;
+          return !unused_bitset.value()[it->second];
+        });
+    was_updated = new_end != data.mutable_resources()->end();
+    data.mutable_resources()->erase(new_end, data.mutable_resources()->end());
+  }
+
+  if (was_updated) {
+    BrowserThread::PostTask(
+        BrowserThread::DB, FROM_HERE,
+        base::Bind(&ResourcePrefetchPredictorTables::UpdateResourceData,
+                   tables_, data, key_type));
+  }
+}
+
 void ResourcePrefetchPredictor::ConnectToHistoryService() {
   // Register for HistoryServiceLoading if it is not ready.
   history::HistoryService* history_service =
diff --git a/chrome/browser/predictors/resource_prefetch_predictor.h b/chrome/browser/predictors/resource_prefetch_predictor.h
index 242de6b..750ac83b 100644
--- a/chrome/browser/predictors/resource_prefetch_predictor.h
+++ b/chrome/browser/predictors/resource_prefetch_predictor.h
@@ -62,6 +62,8 @@
     "ResourcePrefetchPredictor.PrefetchMissesSizeKB";
 constexpr char kResourcePrefetchPredictorRedirectStatusHistogram[] =
     "ResourcePrefetchPredictor.RedirectStatus";
+
+const uint32_t kUnusedRemovedExperiment = 0xf7f77166;
 }  // namespace internal
 
 class TestObserver;
@@ -276,6 +278,8 @@
   FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, ManifestHostInDB);
   FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
                            ManifestHostNotInDBAndDBFull);
+  FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
+                           ManifestUnusedRemoved);
   FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, OnMainFrameRequest);
   FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest, OnMainFrameRedirect);
   FRIEND_TEST_ALL_PREFIXES(ResourcePrefetchPredictorTest,
@@ -435,6 +439,13 @@
   void OnHistoryServiceLoaded(
       history::HistoryService* history_service) override;
 
+  // Updates list of resources in the |data_map| for the |key| according to the
+  // |manifest|.
+  void UpdatePrefetchDataByManifest(const std::string& key,
+                                    PrefetchKeyType key_type,
+                                    PrefetchDataMap* data_map,
+                                    const precache::PrecacheManifest& manifest);
+
   // Used to connect to HistoryService or register for service loaded
   // notificatioan.
   void ConnectToHistoryService();
diff --git a/chrome/browser/predictors/resource_prefetch_predictor_test_util.cc b/chrome/browser/predictors/resource_prefetch_predictor_test_util.cc
index 4765639..522e507 100644
--- a/chrome/browser/predictors/resource_prefetch_predictor_test_util.cc
+++ b/chrome/browser/predictors/resource_prefetch_predictor_test_util.cc
@@ -76,6 +76,25 @@
   origin_stat->set_accessed_network(accessed_network);
 }
 
+void InitializeExperiment(precache::PrecacheManifest* manifest,
+                          uint32_t experiment_id,
+                          const std::vector<bool>& bitset) {
+  std::string binary_bitset;
+  for (size_t i = 0; i < (bitset.size() + 7) / 8; ++i) {
+    char c = 0;
+    for (size_t j = 0; j < 8; ++j) {
+      if (i * 8 + j < bitset.size() && bitset[i * 8 + j])
+        c |= (1 << j);
+    }
+    binary_bitset.push_back(c);
+  }
+
+  precache::PrecacheResourceSelection prs;
+  prs.set_bitset(binary_bitset);
+  (*manifest->mutable_experiments()
+        ->mutable_resources_by_experiment_group())[experiment_id] = prs;
+}
+
 PrefetchData CreatePrefetchData(const std::string& primary_key,
                                 uint64_t last_visit_time) {
   PrefetchData data;
diff --git a/chrome/browser/predictors/resource_prefetch_predictor_test_util.h b/chrome/browser/predictors/resource_prefetch_predictor_test_util.h
index 4b60bbf..fe328ee 100644
--- a/chrome/browser/predictors/resource_prefetch_predictor_test_util.h
+++ b/chrome/browser/predictors/resource_prefetch_predictor_test_util.h
@@ -43,6 +43,10 @@
                           bool always_access_network,
                           bool accessed_network);
 
+void InitializeExperiment(precache::PrecacheManifest* manifest,
+                          uint32_t experiment_id,
+                          const std::vector<bool>& bitset);
+
 PrefetchData CreatePrefetchData(const std::string& primary_key,
                                 uint64_t last_visit_time = 0);
 RedirectData CreateRedirectData(const std::string& primary_key,
diff --git a/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc b/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
index a67e7da..d9b6f670 100644
--- a/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
+++ b/chrome/browser/predictors/resource_prefetch_predictor_unittest.cc
@@ -1181,6 +1181,33 @@
   predictor_->OnManifestFetched("google.com", manifest_with_unknown_fields);
 }
 
+TEST_F(ResourcePrefetchPredictorTest, ManifestUnusedRemoved) {
+  const std::string& script_url = "http://cdn.google.com/script.js";
+  const std::string& style_url = "http://cdn.google.com/style.css";
+  PrefetchData google = CreatePrefetchData("www.google.com");
+  InitializeResourceData(google.add_resources(), script_url,
+                         content::RESOURCE_TYPE_SCRIPT, 10, 0, 1, 2.1,
+                         net::MEDIUM, false, false);
+  InitializeResourceData(google.add_resources(), style_url,
+                         content::RESOURCE_TYPE_SCRIPT, 10, 0, 1, 2.1,
+                         net::MEDIUM, false, false);
+  predictor_->host_table_cache_->insert({google.primary_key(), google});
+
+  precache::PrecacheManifest manifest = CreateManifestData(1);
+  InitializePrecacheResource(manifest.add_resource(), script_url, 0.9);
+  InitializePrecacheResource(manifest.add_resource(), style_url, 0.75);
+  InitializeExperiment(&manifest, internal::kUnusedRemovedExperiment,
+                       {true, false});
+
+  // style_url should be removed.
+  google.mutable_resources()->RemoveLast();
+  EXPECT_CALL(*mock_tables_.get(),
+              UpdateResourceData(google, PREFETCH_KEY_TYPE_HOST));
+  EXPECT_CALL(*mock_tables_.get(), UpdateManifestData("google.com", manifest));
+
+  predictor_->OnManifestFetched("google.com", manifest);
+}
+
 TEST_F(ResourcePrefetchPredictorTest, DeleteUrls) {
   // Add some dummy entries to cache.
   predictor_->url_table_cache_->insert(
diff --git a/chrome/browser/prerender/prerender_nostate_prefetch_browsertest.cc b/chrome/browser/prerender/prerender_nostate_prefetch_browsertest.cc
index 65551c02..ecd1846 100644
--- a/chrome/browser/prerender/prerender_nostate_prefetch_browsertest.cc
+++ b/chrome/browser/prerender/prerender_nostate_prefetch_browsertest.cc
@@ -3,10 +3,14 @@
 // found in the LICENSE file.
 
 #include "base/command_line.h"
+#include "base/memory/ptr_util.h"
+#include "base/memory/ref_counted.h"
 #include "base/strings/string16.h"
 #include "base/strings/string_split.h"
+#include "base/strings/stringprintf.h"
 #include "base/strings/utf_string_conversions.h"
 #include "base/task_scheduler/post_task.h"
+#include "base/test/simple_test_tick_clock.h"
 #include "chrome/browser/history/history_service_factory.h"
 #include "chrome/browser/history/history_test_utils.h"
 #include "chrome/browser/prerender/prerender_handle.h"
@@ -21,7 +25,9 @@
 #include "chrome/common/chrome_switches.h"
 #include "chrome/grit/generated_resources.h"
 #include "chrome/test/base/ui_test_utils.h"
+#include "content/public/browser/appcache_service.h"
 #include "content/public/browser/render_process_host.h"
+#include "content/public/browser/storage_partition.h"
 #include "content/public/common/result_codes.h"
 #include "content/public/common/url_constants.h"
 #include "content/public/test/browser_test_utils.h"
@@ -40,6 +46,8 @@
 
 // These URLs used for test resources must be relative with the exception of
 // |kPrefetchLoaderPath|.
+const char kPrefetchAppcache[] = "prerender/prefetch_appcache.html";
+const char kPrefetchAppcacheManifest[] = "prerender/appcache.manifest";
 const char kPrefetchImagePage[] = "prerender/prefetch_image.html";
 const char kPrefetchJpeg[] = "prerender/image.jpeg";
 const char kPrefetchLoaderPath[] = "/prerender/prefetch_loader.html";
@@ -89,6 +97,32 @@
                    url_file, counter->AsWeakPtr()));
   }
 
+  base::SimpleTestTickClock* OverridePrerenderManagerTimeTicks() {
+    auto clock = base::MakeUnique<base::SimpleTestTickClock>();
+    auto* clock_ptr = clock.get();
+    // The default zero time causes the prerender manager to do strange things.
+    clock->Advance(base::TimeDelta::FromSeconds(1));
+    GetPrerenderManager()->SetTickClockForTesting(std::move(clock));
+    return clock_ptr;
+  }
+
+  // Block until an AppCache exists for |manifest_url|.
+  void WaitForAppcache(const GURL& manifest_url) {
+    bool found_manifest = false;
+    content::AppCacheService* appcache_service =
+        content::BrowserContext::GetDefaultStoragePartition(
+            current_browser()->profile())
+            ->GetAppCacheService();
+    do {
+      base::RunLoop wait_loop;
+      content::BrowserThread::PostTask(
+          content::BrowserThread::IO, FROM_HERE,
+          base::Bind(WaitForAppcacheOnIO, manifest_url, appcache_service,
+                     wait_loop.QuitClosure(), &found_manifest));
+      wait_loop.Run();
+    } while (!found_manifest);
+  }
+
  protected:
   std::unique_ptr<TestPrerender> PrefetchFromURL(
       const GURL& target_url,
@@ -111,6 +145,45 @@
   }
 
  private:
+  // Schedule a task to retrieve AppCacheInfo from |appcache_service|. This sets
+  // |found_manifest| if an appcache exists for |manifest_url|. |callback| will
+  // be called on the UI thread after the info is retrieved, whether or not the
+  // manifest exists.
+  static void WaitForAppcacheOnIO(const GURL& manifest_url,
+                                  content::AppCacheService* appcache_service,
+                                  base::Closure callback,
+                                  bool* found_manifest) {
+    scoped_refptr<content::AppCacheInfoCollection> info_collection =
+        new content::AppCacheInfoCollection();
+    appcache_service->GetAllAppCacheInfo(
+        info_collection.get(),
+        base::Bind(ProcessAppCacheInfo, manifest_url, callback, found_manifest,
+                   info_collection));
+  }
+
+  // Look through |info_collection| for an entry matching |target_manifest|,
+  // setting |found_manifest| appropriately. Then |callback| will be invoked on
+  // the UI thread.
+  static void ProcessAppCacheInfo(
+      const GURL& target_manifest,
+      base::Closure callback,
+      bool* found_manifest,
+      scoped_refptr<content::AppCacheInfoCollection> info_collection,
+      int status) {
+    if (status == net::OK) {
+      for (const auto& origin_pair : info_collection->infos_by_origin) {
+        for (const auto& info : origin_pair.second) {
+          if (info.manifest_url == target_manifest) {
+            *found_manifest = true;
+            break;
+          }
+        }
+      }
+    }
+    content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
+                                     callback);
+  }
+
   DISALLOW_COPY_AND_ASSIGN(NoStatePrefetchBrowserTest);
 };
 
@@ -185,15 +258,10 @@
 IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, PrefetchImage) {
   RequestCounter image_counter;
   CountRequestFor(kPrefetchJpeg, &image_counter);
-  base::StringPairs replacement_text;
-  replacement_text.push_back(
-      std::make_pair("REPLACE_WITH_IMAGE_URL", MakeAbsolute(kPrefetchJpeg)));
-  std::string main_page_path;
-  net::test_server::GetFilePathWithReplacements(
-      kPrefetchImagePage, replacement_text, &main_page_path);
-  // Note CountRequestFor cannot be used on the main page as the test server
-  // must handling the image url replacement.
-  PrefetchFromFile(main_page_path, FINAL_STATUS_NOSTATE_PREFETCH_FINISHED);
+  GURL main_page_url =
+      GetURLWithReplacement(kPrefetchImagePage, "REPLACE_WITH_IMAGE_URL",
+                            MakeAbsolute(kPrefetchJpeg));
+  PrefetchFromURL(main_page_url, FINAL_STATUS_NOSTATE_PREFETCH_FINISHED);
   image_counter.WaitForCount(1);
 }
 
@@ -405,17 +473,13 @@
   https_server.ServeFilesFromSourceDirectory("chrome/test/data");
   ASSERT_TRUE(https_server.Start());
   GURL https_url = https_server.GetURL("/prerender/image.jpeg");
-  base::StringPairs replacement_text;
-  replacement_text.push_back(
-      std::make_pair("REPLACE_WITH_IMAGE_URL", https_url.spec()));
-  std::string main_page_path;
-  net::test_server::GetFilePathWithReplacements(
-      kPrefetchImagePage, replacement_text, &main_page_path);
+  GURL main_page_url = GetURLWithReplacement(
+      kPrefetchImagePage, "REPLACE_WITH_IMAGE_URL", https_url.spec());
   RequestCounter script_counter;
   CountRequestFor(kPrefetchScript, &script_counter);
 
   std::unique_ptr<TestPrerender> prerender =
-      PrefetchFromFile(main_page_path, FINAL_STATUS_NOSTATE_PREFETCH_FINISHED);
+      PrefetchFromURL(main_page_url, FINAL_STATUS_NOSTATE_PREFETCH_FINISHED);
   // Checks that the presumed failure of the image load didn't affect the script
   // fetch. This assumes waiting for the script load is enough to see any error
   // from the image load.
@@ -603,4 +667,94 @@
   image_counter.WaitForCount(1);
 }
 
+// Checks that prefetching happens if an appcache is mentioned in the html tag
+// but is uninitialized.
+IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, AppCacheHtmlUninitialized) {
+  RequestCounter image_counter;
+  CountRequestFor(kPrefetchPng, &image_counter);
+  PrefetchFromFile(kPrefetchAppcache, FINAL_STATUS_NOSTATE_PREFETCH_FINISHED);
+  image_counter.WaitForCount(1);
+}
+
+// Checks that prefetching does not if an initialized appcache is mentioned in
+// the html tag.
+IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, AppCacheHtmlInitialized) {
+  base::TimeTicks current_time = GetPrerenderManager()->GetCurrentTimeTicks();
+  auto* clock = OverridePrerenderManagerTimeTicks();
+  // Some navigations have already occurred in test setup. In order to track
+  // duplicate prefetches correctly the test clock needs to be beyond those
+  // navigations.
+  clock->SetNowTicks(current_time);
+  clock->Advance(base::TimeDelta::FromSeconds(600));
+
+  // Fill manifest with the image url. The main resource will be cached
+  // implicitly.
+  GURL image_url = src_server()->GetURL(MakeAbsolute(kPrefetchPng));
+  GURL manifest_url = GetURLWithReplacement(
+      kPrefetchAppcacheManifest, "REPLACE_WITH_URL", image_url.spec());
+  GURL appcache_page_url = GetURLWithReplacement(
+      kPrefetchAppcache, "REPLACE_WITH_MANIFEST", manifest_url.spec());
+
+  // Load the page into the appcache.
+  ui_test_utils::NavigateToURL(current_browser(), appcache_page_url);
+
+  WaitForAppcache(manifest_url);
+
+  // If a page is prefetch shortly after being loading, the prefetch is
+  // canceled. Advancing the clock prevents the cancelation.
+  clock->Advance(base::TimeDelta::FromSeconds(6000));
+
+  RequestCounter script_counter;
+  CountRequestFor(kPrefetchScript, &script_counter);
+  // While the prefetch stops when it sees the AppCache manifest, from the point
+  // of view of the prerender manager the prefetch stops normally.
+  PrefetchFromURL(appcache_page_url, FINAL_STATUS_NOSTATE_PREFETCH_FINISHED);
+
+  // The prefetch should have been canceled before the script in
+  // kPrefetchAppcache is loaded (note the script is not mentioned in the
+  // manifest).
+  script_counter.WaitForCount(0);
+}
+
+// If a page has been cached by another AppCache, the prefetch should be
+// canceled.
+IN_PROC_BROWSER_TEST_F(NoStatePrefetchBrowserTest, AppCacheRegistered) {
+  base::TimeTicks current_time = GetPrerenderManager()->GetCurrentTimeTicks();
+  auto* clock = OverridePrerenderManagerTimeTicks();
+  // Some navigations have already occurred in test setup. In order to track
+  // duplicate prefetches correctly the test clock needs to be beyond those
+  // navigations.
+  clock->SetNowTicks(current_time);
+  clock->Advance(base::TimeDelta::FromSeconds(600));
+
+  // Fill manifest with kPrefetchPage so that it is cached without explicitly
+  // listing a manifest.
+  GURL prefetch_page_url = src_server()->GetURL(MakeAbsolute(kPrefetchPage));
+  GURL manifest_url = GetURLWithReplacement(
+      kPrefetchAppcacheManifest, "REPLACE_WITH_URL", prefetch_page_url.spec());
+
+  GURL appcache_page_url = GetURLWithReplacement(
+      kPrefetchAppcache, "REPLACE_WITH_MANIFEST", manifest_url.spec());
+
+  // Load the page into the appcache.
+  ui_test_utils::NavigateToURL(current_browser(), appcache_page_url);
+  // Load the prefetch page so it can be cached.
+  ui_test_utils::NavigateToURL(current_browser(), prefetch_page_url);
+
+  WaitForAppcache(manifest_url);
+
+  // If a page is prefetch shortly after being loading, the prefetch is
+  // canceled. Advancing the clock prevents the cancelation.
+  clock->Advance(base::TimeDelta::FromSeconds(6000));
+
+  RequestCounter page_counter;
+  CountRequestFor(kPrefetchPage, &page_counter);
+  RequestCounter script_counter;
+  CountRequestFor(kPrefetchScript, &script_counter);
+  PrefetchFromURL(prefetch_page_url, FINAL_STATUS_NOSTATE_PREFETCH_FINISHED);
+  // Neither the page nor the script should be prefetched.
+  script_counter.WaitForCount(0);
+  page_counter.WaitForCount(0);
+}
+
 }  // namespace prerender
diff --git a/chrome/browser/prerender/prerender_test_utils.cc b/chrome/browser/prerender/prerender_test_utils.cc
index abded11..9ee543a 100644
--- a/chrome/browser/prerender/prerender_test_utils.cc
+++ b/chrome/browser/prerender/prerender_test_utils.cc
@@ -745,6 +745,18 @@
                                     base::ASCIIToUTF16(page_title));
 }
 
+GURL PrerenderInProcessBrowserTest::GetURLWithReplacement(
+    const std::string& url_file,
+    const std::string& replacement_variable,
+    const std::string& replacement_text) {
+  base::StringPairs replacement_pair;
+  replacement_pair.push_back(make_pair(replacement_variable, replacement_text));
+  std::string replacement_path;
+  net::test_server::GetFilePathWithReplacements(url_file, replacement_pair,
+                                                &replacement_path);
+  return src_server()->GetURL(MakeAbsolute(replacement_path));
+}
+
 std::vector<std::unique_ptr<TestPrerender>>
 PrerenderInProcessBrowserTest::NavigateWithPrerenders(
     const GURL& loader_url,
diff --git a/chrome/browser/prerender/prerender_test_utils.h b/chrome/browser/prerender/prerender_test_utils.h
index 40da70a..cdc266b 100644
--- a/chrome/browser/prerender/prerender_test_utils.h
+++ b/chrome/browser/prerender/prerender_test_utils.h
@@ -355,6 +355,12 @@
   // Returns a string for pattern-matching TaskManager prerender entries.
   base::string16 MatchTaskManagerPrerender(const char* page_title);
 
+  // Returns a GURL for an EmbeddedTestServer that will serves the file
+  // |url_file| with |replacement_text| replacing |replacement_variable|.
+  GURL GetURLWithReplacement(const std::string& url_file,
+                             const std::string& replacement_variable,
+                             const std::string& replacement_text);
+
  protected:
   // For each FinalStatus in |expected_final_status_queue| creates a prerender
   // that is going to verify the correctness of its FinalStatus upon
diff --git a/chrome/browser/printing/printing_layout_browsertest.cc b/chrome/browser/printing/printing_layout_browsertest.cc
deleted file mode 100644
index 3ac9b9bb..0000000
--- a/chrome/browser/printing/printing_layout_browsertest.cc
+++ /dev/null
@@ -1,475 +0,0 @@
-// Copyright (c) 2012 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 "base/command_line.h"
-#include "base/files/file_enumerator.h"
-#include "base/files/file_path.h"
-#include "base/files/file_util.h"
-#include "base/location.h"
-#include "base/macros.h"
-#include "base/message_loop/message_loop.h"
-#include "base/path_service.h"
-#include "base/process/process_handle.h"
-#include "base/single_thread_task_runner.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/test/test_file_util.h"
-#include "base/threading/simple_thread.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "chrome/browser/chrome_notification_types.h"
-#include "chrome/browser/printing/print_job.h"
-#include "chrome/browser/printing/print_view_manager.h"
-#include "chrome/browser/ui/browser.h"
-#include "chrome/browser/ui/browser_commands.h"
-#include "chrome/browser/ui/tabs/tab_strip_model.h"
-#include "chrome/common/chrome_paths.h"
-#include "chrome/common/chrome_switches.h"
-#include "chrome/test/base/in_process_browser_test.h"
-#include "chrome/test/base/ui_test_utils.h"
-#include "content/public/browser/notification_observer.h"
-#include "content/public/browser/notification_registrar.h"
-#include "content/public/browser/notification_service.h"
-#include "net/test/embedded_test_server/embedded_test_server.h"
-#include "printing/image.h"
-#include "printing/printing_test.h"
-
-namespace {
-
-using printing::Image;
-
-const char kGenerateSwitch[] = "print-layout-generate";
-
-class PrintingLayoutTest : public PrintingTest<InProcessBrowserTest>,
-                           public content::NotificationObserver {
- public:
-  PrintingLayoutTest() {
-    base::FilePath browser_directory;
-    PathService::Get(chrome::DIR_APP, &browser_directory);
-    emf_path_ = browser_directory.AppendASCII("metafile_dumps");
-  }
-
-  void SetUp() override {
-    // Make sure there is no left overs.
-    CleanupDumpDirectory();
-    InProcessBrowserTest::SetUp();
-  }
-
-  void TearDown() override {
-    InProcessBrowserTest::TearDown();
-    base::DeleteFile(emf_path_, true);
-  }
-
-  void SetUpCommandLine(base::CommandLine* command_line) override {
-    command_line->AppendSwitchPath(switches::kDebugPrint, emf_path_);
-  }
-
- protected:
-  void PrintNowTab() {
-    registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT,
-                   content::NotificationService::AllSources());
-
-    content::WebContents* web_contents =
-        browser()->tab_strip_model()->GetActiveWebContents();
-    printing::PrintViewManager::FromWebContents(web_contents)->PrintNow();
-    content::RunMessageLoop();
-    registrar_.RemoveAll();
-  }
-
-  virtual void Observe(int type,
-                       const content::NotificationSource& source,
-                       const content::NotificationDetails& details) {
-    ASSERT_EQ(chrome::NOTIFICATION_PRINT_JOB_EVENT, type);
-    switch (content::Details<printing::JobEventDetails>(details)->type()) {
-      case printing::JobEventDetails::JOB_DONE: {
-        // Succeeded.
-        base::ThreadTaskRunnerHandle::Get()->PostTask(
-            FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
-        break;
-      }
-      case printing::JobEventDetails::USER_INIT_CANCELED:
-      case printing::JobEventDetails::FAILED: {
-        // Failed.
-        ASSERT_TRUE(false);
-        base::ThreadTaskRunnerHandle::Get()->PostTask(
-            FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
-        break;
-      }
-      case printing::JobEventDetails::NEW_DOC:
-      case printing::JobEventDetails::USER_INIT_DONE:
-      case printing::JobEventDetails::DEFAULT_INIT_DONE:
-      case printing::JobEventDetails::NEW_PAGE:
-      case printing::JobEventDetails::PAGE_DONE:
-      case printing::JobEventDetails::DOC_DONE:
-      case printing::JobEventDetails::ALL_PAGES_REQUESTED: {
-        // Don't care.
-        break;
-      }
-      default: {
-        NOTREACHED();
-        break;
-      }
-    }
-  }
-
-  // Finds the dump for the last print job and compares it to the data named
-  // |verification_name|. Compares the saved printed job pixels with the test
-  // data pixels and returns the percentage of different pixels; 0 for success,
-  // [0, 100] for failure.
-  double CompareWithResult(const std::wstring& verification_name) {
-    base::FilePath test_result(ScanFiles(verification_name));
-    if (test_result.value().empty()) {
-      // 100% different, the print job buffer is not there.
-      return 100.;
-    }
-
-    base::FilePath base_path(ui_test_utils::GetTestFilePath(
-        base::FilePath().AppendASCII("printing"), base::FilePath()));
-    base::FilePath emf(base_path.Append(verification_name + L".emf"));
-    base::FilePath png(base_path.Append(verification_name + L".png"));
-
-    base::FilePath cleartype(
-        base_path.Append(verification_name + L"_cleartype.png"));
-    // Looks for Cleartype override.
-    if (base::PathExists(cleartype) && IsClearTypeEnabled())
-      png = cleartype;
-
-    if (GenerateFiles()) {
-      // Copy the .emf and generate an .png.
-      base::CopyFile(test_result, emf);
-      Image emf_content(emf);
-      emf_content.SaveToPng(png);
-      // Saving is always fine.
-      return 0;
-    } else {
-      // File compare between test and result.
-      Image emf_content(emf);
-      Image test_content(test_result);
-      Image png_content(png);
-      double diff_emf = emf_content.PercentageDifferent(test_content);
-
-      EXPECT_EQ(0., diff_emf) << base::WideToUTF8(verification_name) <<
-          " original size:" << emf_content.size().ToString() <<
-          " result size:" << test_content.size().ToString();
-      if (diff_emf) {
-        // Backup the result emf file.
-        base::FilePath failed(
-            base_path.Append(verification_name + L"_failed.emf"));
-        base::CopyFile(test_result, failed);
-      }
-
-      // This verification is only to know that the EMF rendering stays
-      // immutable.
-      double diff_png = emf_content.PercentageDifferent(png_content);
-      EXPECT_EQ(0., diff_png) << base::WideToUTF8(verification_name) <<
-          " original size:" << emf_content.size().ToString() <<
-          " result size:" << test_content.size().ToString();
-      if (diff_png) {
-        // Backup the rendered emf file to detect the rendering difference.
-        base::FilePath rendering(
-            base_path.Append(verification_name + L"_rendering.png"));
-        emf_content.SaveToPng(rendering);
-      }
-      return std::max(diff_png, diff_emf);
-    }
-  }
-
-  // Makes sure the directory exists and is empty.
-  void CleanupDumpDirectory() {
-    EXPECT_TRUE(base::DieFileDie(emf_path_, true));
-    EXPECT_TRUE(base::CreateDirectory(emf_path_));
-  }
-
-  // Returns if Clear Type is currently enabled.
-  static bool IsClearTypeEnabled() {
-    BOOL ct_enabled = 0;
-    if (SystemParametersInfo(SPI_GETCLEARTYPE, 0, &ct_enabled, 0) && ct_enabled)
-      return true;
-    UINT smoothing = 0;
-    if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothing, 0) &&
-        smoothing == FE_FONTSMOOTHINGCLEARTYPE)
-      return true;
-    return false;
-  }
-
- private:
-  // Verifies that there is one .emf and one .prn file in the dump directory.
-  // Returns the path of the .emf file and deletes the .prn file.
-  std::wstring ScanFiles(const std::wstring& verification_name) {
-    // Try to 10 seconds.
-    std::wstring emf_file;
-    std::wstring prn_file;
-    bool found_emf = false;
-    bool found_prn = false;
-    for (int i = 0; i < 100; ++i) {
-      base::FileEnumerator enumerator(emf_path_, false,
-                                      base::FileEnumerator::FILES);
-      emf_file.clear();
-      prn_file.clear();
-      found_emf = false;
-      found_prn = false;
-      base::FilePath file;
-      while (!(file = enumerator.Next()).empty()) {
-        std::wstring ext = file.Extension();
-        if (base::EqualsCaseInsensitiveASCII(base::WideToUTF8(ext), ".emf")) {
-          EXPECT_FALSE(found_emf) << "Found a leftover .EMF file: \"" <<
-              emf_file << "\" and \"" << file.value() <<
-              "\" when looking for \"" << verification_name << "\"";
-          found_emf = true;
-          emf_file = file.value();
-          continue;
-        }
-        if (base::EqualsCaseInsensitiveASCII(base::WideToUTF8(ext), ".prn")) {
-          EXPECT_FALSE(found_prn) << "Found a leftover .PRN file: \"" <<
-              prn_file << "\" and \"" << file.value() <<
-              "\" when looking for \"" << verification_name << "\"";
-          prn_file = file.value();
-          found_prn = true;
-          base::DeleteFile(file, false);
-          continue;
-        }
-        EXPECT_TRUE(false);
-      }
-      if (found_emf && found_prn)
-        break;
-      base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100));
-    }
-    EXPECT_TRUE(found_emf) << ".PRN file is: " << prn_file;
-    EXPECT_TRUE(found_prn) << ".EMF file is: " << emf_file;
-    return emf_file;
-  }
-
-  static bool GenerateFiles() {
-    return base::CommandLine::ForCurrentProcess()->HasSwitch(kGenerateSwitch);
-  }
-
-  base::FilePath emf_path_;
-  content::NotificationRegistrar registrar_;
-
-  DISALLOW_COPY_AND_ASSIGN(PrintingLayoutTest);
-};
-
-class PrintingLayoutTextTest : public PrintingLayoutTest {
-  typedef PrintingLayoutTest Parent;
- public:
-  // Returns if the test is disabled.
-  // http://crbug.com/64869 Until the issue is fixed, disable the test if
-  // ClearType is enabled.
-  static bool IsTestCaseDisabled() {
-    return Parent::IsTestCaseDisabled() || IsClearTypeEnabled();
-  }
-};
-
-// Finds the first dialog window owned by owner_process.
-HWND FindDialogWindow(DWORD owner_process) {
-  HWND dialog_window(NULL);
-  for (;;) {
-    dialog_window = FindWindowEx(NULL,
-                                 dialog_window,
-                                 MAKEINTATOM(32770),
-                                 NULL);
-    if (!dialog_window)
-      break;
-
-    // The dialog must be owned by our target process.
-    DWORD process_id = 0;
-    GetWindowThreadProcessId(dialog_window, &process_id);
-    if (process_id == owner_process)
-      break;
-  }
-  return dialog_window;
-}
-
-// Tries to close a dialog window.
-bool CloseDialogWindow(HWND dialog_window) {
-  LRESULT res = SendMessage(dialog_window, DM_GETDEFID, 0, 0);
-  if (!res)
-    return false;
-  EXPECT_EQ(DC_HASDEFID, HIWORD(res));
-  WORD print_button_id = LOWORD(res);
-  res = SendMessage(
-      dialog_window,
-      WM_COMMAND,
-      print_button_id,
-      reinterpret_cast<LPARAM>(GetDlgItem(dialog_window, print_button_id)));
-  return res == 0;
-}
-
-// Dismiss the first dialog box owned by owner_process by "executing" the
-// default button.
-class DismissTheWindow : public base::DelegateSimpleThread::Delegate {
- public:
-  DismissTheWindow()
-      : owner_process_(base::GetCurrentProcId()) {
-  }
-
-  virtual void Run() {
-    HWND dialog_window;
-    for (;;) {
-      // First enumerate the windows.
-      dialog_window = FindDialogWindow(owner_process_);
-
-      // Try to close it.
-      if (dialog_window) {
-        if (CloseDialogWindow(dialog_window)) {
-          break;
-        }
-      }
-      base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
-    }
-
-    // Now verify that it indeed closed itself.
-    while (IsWindow(dialog_window)) {
-      CloseDialogWindow(dialog_window);
-      base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
-    }
-  }
-
-  DWORD owner_process() { return owner_process_; }
-
- private:
-  DWORD owner_process_;
-};
-
-}  // namespace
-
-// Fails, see http://crbug.com/7721.
-IN_PROC_BROWSER_TEST_F(PrintingLayoutTextTest, DISABLED_Complex) {
-  if (IsTestCaseDisabled())
-    return;
-
-  DismissTheWindow dismisser;
-  base::DelegateSimpleThread close_printdlg_thread(&dismisser,
-                                                   "close_printdlg_thread");
-
-  // Print a document, check its output.
-  ASSERT_TRUE(embedded_test_server()->Start());
-
-  ui_test_utils::NavigateToURL(
-      browser(), embedded_test_server()->GetURL("/printing/test1.html"));
-  close_printdlg_thread.Start();
-  PrintNowTab();
-  close_printdlg_thread.Join();
-  EXPECT_EQ(0., CompareWithResult(L"test1"));
-}
-
-struct TestPool {
-  const char* source;
-  const wchar_t* result;
-};
-
-const TestPool kTestPool[] = {
-    // ImagesB&W
-    "/printing/test2.html", L"test2",
-    // ImagesTransparent
-    "/printing/test3.html", L"test3",
-    // ImageColor
-    "/printing/test4.html", L"test4",
-};
-
-// http://crbug.com/7721
-IN_PROC_BROWSER_TEST_F(PrintingLayoutTest, DISABLED_ManyTimes) {
-  if (IsTestCaseDisabled())
-    return;
-
-  ASSERT_TRUE(embedded_test_server()->Start());
-
-  DismissTheWindow dismisser;
-
-  ASSERT_GT(arraysize(kTestPool), 0u);
-  for (int i = 0; i < arraysize(kTestPool); ++i) {
-    if (i)
-      CleanupDumpDirectory();
-    const TestPool& test = kTestPool[i % arraysize(kTestPool)];
-    ui_test_utils::NavigateToURL(browser(),
-                                 embedded_test_server()->GetURL(test.source));
-    base::DelegateSimpleThread close_printdlg_thread1(&dismisser,
-                                                      "close_printdlg_thread");
-    EXPECT_EQ(NULL, FindDialogWindow(dismisser.owner_process()));
-    close_printdlg_thread1.Start();
-    PrintNowTab();
-    close_printdlg_thread1.Join();
-    EXPECT_EQ(0., CompareWithResult(test.result)) << test.result;
-    CleanupDumpDirectory();
-    base::DelegateSimpleThread close_printdlg_thread2(&dismisser,
-                                                      "close_printdlg_thread");
-    EXPECT_EQ(NULL, FindDialogWindow(dismisser.owner_process()));
-    close_printdlg_thread2.Start();
-    PrintNowTab();
-    close_printdlg_thread2.Join();
-    EXPECT_EQ(0., CompareWithResult(test.result)) << test.result;
-    CleanupDumpDirectory();
-    base::DelegateSimpleThread close_printdlg_thread3(&dismisser,
-                                                      "close_printdlg_thread");
-    EXPECT_EQ(NULL, FindDialogWindow(dismisser.owner_process()));
-    close_printdlg_thread3.Start();
-    PrintNowTab();
-    close_printdlg_thread3.Join();
-    EXPECT_EQ(0., CompareWithResult(test.result)) << test.result;
-    CleanupDumpDirectory();
-    base::DelegateSimpleThread close_printdlg_thread4(&dismisser,
-                                                      "close_printdlg_thread");
-    EXPECT_EQ(NULL, FindDialogWindow(dismisser.owner_process()));
-    close_printdlg_thread4.Start();
-    PrintNowTab();
-    close_printdlg_thread4.Join();
-    EXPECT_EQ(0., CompareWithResult(test.result)) << test.result;
-  }
-}
-
-// Prints a popup and immediately closes it. Disabled because it crashes.
-IN_PROC_BROWSER_TEST_F(PrintingLayoutTest, DISABLED_Delayed) {
-  if (IsTestCaseDisabled())
-    return;
-
-  ASSERT_TRUE(embedded_test_server()->Start());
-
-  {
-    bool is_timeout = true;
-    GURL url =
-        embedded_test_server()->GetURL("/printing/popup_delayed_print.htm");
-    ui_test_utils::NavigateToURL(browser(), url);
-
-    DismissTheWindow dismisser;
-    base::DelegateSimpleThread close_printdlg_thread(&dismisser,
-                                                     "close_printdlg_thread");
-    close_printdlg_thread.Start();
-    close_printdlg_thread.Join();
-
-    // Force a navigation elsewhere to verify that it's fine with it.
-    url = embedded_test_server()->GetURL("/printing/test1.html");
-    ui_test_utils::NavigateToURL(browser(), url);
-  }
-  chrome::CloseWindow(browser());
-  content::RunAllPendingInMessageLoop();
-
-  EXPECT_EQ(0., CompareWithResult(L"popup_delayed_print"))
-      << L"popup_delayed_print";
-}
-
-// Prints a popup and immediately closes it. http://crbug.com/7721
-IN_PROC_BROWSER_TEST_F(PrintingLayoutTest, DISABLED_IFrame) {
-  if (IsTestCaseDisabled())
-    return;
-
-  ASSERT_TRUE(embedded_test_server()->Start());
-
-  {
-    GURL url = embedded_test_server()->GetURL("/printing/iframe.htm");
-    ui_test_utils::NavigateToURL(browser(), url);
-
-    DismissTheWindow dismisser;
-    base::DelegateSimpleThread close_printdlg_thread(&dismisser,
-                                                     "close_printdlg_thread");
-    close_printdlg_thread.Start();
-    close_printdlg_thread.Join();
-
-    // Force a navigation elsewhere to verify that it's fine with it.
-    url = embedded_test_server()->GetURL("/printing/test1.html");
-    ui_test_utils::NavigateToURL(browser(), url);
-  }
-  chrome::CloseWindow(browser());
-  content::RunAllPendingInMessageLoop();
-
-  EXPECT_EQ(0., CompareWithResult(L"iframe")) << L"iframe";
-}
diff --git a/chrome/service/cloud_print/print_system_win.cc b/chrome/service/cloud_print/print_system_win.cc
index 7d803c3c..292aa689 100644
--- a/chrome/service/cloud_print/print_system_win.cc
+++ b/chrome/service/cloud_print/print_system_win.cc
@@ -339,13 +339,17 @@
     }
 
     // ServiceUtilityProcessHost::Client implementation.
-    void OnRenderPDFPagesToMetafilePageDone(
-        float scale_factor,
-        const printing::MetafilePlayer& emf) override {
+    bool OnRenderPDFPagesToMetafilePageDone(const std::vector<char>& emf_data,
+                                            float scale_factor) override {
+      printing::Emf emf;
+      if (!emf.InitFromData(emf_data.data(), emf_data.size())) {
+        return false;
+      }
       PreparePageDCForPrinting(printer_dc_.Get(), scale_factor);
       ::StartPage(printer_dc_.Get());
       emf.SafePlayback(printer_dc_.Get());
       ::EndPage(printer_dc_.Get());
+      return true;
     }
 
     // ServiceUtilityProcessHost::Client implementation.
diff --git a/chrome/service/service_utility_process_host.cc b/chrome/service/service_utility_process_host.cc
index 7a9edf7..92f92e4 100644
--- a/chrome/service/service_utility_process_host.cc
+++ b/chrome/service/service_utility_process_host.cc
@@ -37,7 +37,6 @@
 #include "mojo/edk/embedder/named_platform_channel_pair.h"
 #include "mojo/edk/embedder/platform_channel_pair.h"
 #include "mojo/edk/embedder/scoped_platform_handle.h"
-#include "printing/emf_win.h"
 #include "sandbox/win/src/sandbox_policy.h"
 #include "sandbox/win/src/sandbox_types.h"
 #include "ui/base/ui_base_switches.h"
@@ -429,6 +428,12 @@
                             printing::PrinterSemanticCapsAndDefaults()));
 }
 
+bool ServiceUtilityProcessHost::Client::OnRenderPDFPagesToMetafilePageDone(
+    const std::vector<char>&,
+    float) {
+  return false;
+}
+
 bool ServiceUtilityProcessHost::Client::MetafileAvailable(float scale_factor,
                                                           base::File file) {
   file.Seek(base::File::FROM_BEGIN, 0);
@@ -442,11 +447,9 @@
     OnRenderPDFPagesToMetafileDone(false);
     return false;
   }
-  printing::Emf emf;
-  if (!emf.InitFromData(data.data(), data.size())) {
+  if (!OnRenderPDFPagesToMetafilePageDone(data, scale_factor)) {
     OnRenderPDFPagesToMetafileDone(false);
     return false;
   }
-  OnRenderPDFPagesToMetafilePageDone(scale_factor, emf);
   return true;
 }
diff --git a/chrome/service/service_utility_process_host.h b/chrome/service/service_utility_process_host.h
index 7b13f105..d0bd273 100644
--- a/chrome/service/service_utility_process_host.h
+++ b/chrome/service/service_utility_process_host.h
@@ -27,7 +27,6 @@
 }
 
 namespace printing {
-class MetafilePlayer;
 struct PdfRenderSettings;
 struct PrinterCapsAndDefaults;
 struct PrinterSemanticCapsAndDefaults;
@@ -48,9 +47,9 @@
     // Called when the child process died before a reply was receieved.
     virtual void OnChildDied() {}
 
-    virtual void OnRenderPDFPagesToMetafilePageDone(
-        float scale_factor,
-        const printing::MetafilePlayer& emf) {}
+    virtual bool OnRenderPDFPagesToMetafilePageDone(
+        const std::vector<char>& emf_data,
+        float scale_factor);
 
     // Called when at all pages in the PDF has been rendered.
     virtual void OnRenderPDFPagesToMetafileDone(bool success) {}
diff --git a/chrome/test/data/prerender/appcache.manifest b/chrome/test/data/prerender/appcache.manifest
new file mode 100644
index 0000000..a4ca9c2
--- /dev/null
+++ b/chrome/test/data/prerender/appcache.manifest
@@ -0,0 +1,2 @@
+CACHE MANIFEST
+REPLACE_WITH_URL
diff --git a/chrome/test/data/prerender/appcache.manifest.mock-http-headers b/chrome/test/data/prerender/appcache.manifest.mock-http-headers
new file mode 100644
index 0000000..ab2adcb8
--- /dev/null
+++ b/chrome/test/data/prerender/appcache.manifest.mock-http-headers
@@ -0,0 +1,2 @@
+HTTP/1.1 200 OK	
+Content-Type: text/cache-manifest	
diff --git a/chrome/test/data/prerender/prefetch_appcache.html b/chrome/test/data/prerender/prefetch_appcache.html
new file mode 100644
index 0000000..bbe1c09b
--- /dev/null
+++ b/chrome/test/data/prerender/prefetch_appcache.html
@@ -0,0 +1,9 @@
+<html manifest="REPLACE_WITH_MANIFEST">
+<!--
+A stub page used to set up an AppCache manifest.
+--> 
+<body>
+  <script src="prefetch.js"></script>
+  <img src="image.png"/>
+</body>
+</html>
diff --git a/components/printing/test/mock_printer.cc b/components/printing/test/mock_printer.cc
index eb2c9c9c..ede214c9 100644
--- a/components/printing/test/mock_printer.cc
+++ b/components/printing/test/mock_printer.cc
@@ -51,8 +51,8 @@
 
 MockPrinterPage::MockPrinterPage(const void* source_data,
                                  uint32_t source_size,
-                                 const printing::Image& image)
-    : source_size_(source_size), image_(image) {
+                                 printing::Image image)
+    : source_size_(source_size), image_(std::move(image)) {
   // Create copies of the source data
   source_data_.reset(new uint8_t[source_size]);
   if (source_data_.get())
@@ -209,16 +209,9 @@
   EXPECT_GT(params.data_size, 0U);
   base::SharedMemory metafile_data(params.metafile_data_handle, true);
   metafile_data.Map(params.data_size);
-#if defined(OS_MACOSX)
-  printing::PdfMetafileCg metafile;
-#else
-  printing::PdfMetafileSkia metafile(printing::PDF_SKIA_DOCUMENT_TYPE);
-#endif
-  metafile.InitFromData(metafile_data.memory(), params.data_size);
-  printing::Image image(metafile);
-  MockPrinterPage* page_data =
-      new MockPrinterPage(metafile_data.memory(), params.data_size, image);
-  scoped_refptr<MockPrinterPage> page(page_data);
+  printing::Image image(metafile_data.memory(), params.data_size);
+  scoped_refptr<MockPrinterPage> page(new MockPrinterPage(
+      metafile_data.memory(), params.data_size, std::move(image)));
   pages_.push_back(page);
 #endif
 
diff --git a/components/printing/test/mock_printer.h b/components/printing/test/mock_printer.h
index 0adb9af0..41526d5 100644
--- a/components/printing/test/mock_printer.h
+++ b/components/printing/test/mock_printer.h
@@ -31,7 +31,7 @@
  public:
   MockPrinterPage(const void* source_data,
                   uint32_t source_size,
-                  const printing::Image& image);
+                  printing::Image image);
 
   int width() const { return image_.size().width(); }
   int height() const { return image_.size().height(); }
diff --git a/content/public/common/context_menu_params.cc b/content/public/common/context_menu_params.cc
index 2093ead..bfb5430 100644
--- a/content/public/common/context_menu_params.cc
+++ b/content/public/common/context_menu_params.cc
@@ -18,7 +18,7 @@
     : media_type(blink::WebContextMenuData::kMediaTypeNone),
       x(0),
       y(0),
-      has_image_contents(true),
+      has_image_contents(false),
       media_flags(0),
       spellcheck_enabled(false),
       is_editable(false),
diff --git a/ios/chrome/browser/ui/authentication/signin_interaction_controller_egtest.mm b/ios/chrome/browser/ui/authentication/signin_interaction_controller_egtest.mm
index c827e04..67df59d 100644
--- a/ios/chrome/browser/ui/authentication/signin_interaction_controller_egtest.mm
+++ b/ios/chrome/browser/ui/authentication/signin_interaction_controller_egtest.mm
@@ -312,8 +312,7 @@
   TapButtonWithLabelId(IDS_IOS_DISCONNECT_DIALOG_CONTINUE_BUTTON_MOBILE);
 
   // Check that the settings home screen is shown.
-  WaitForMatcher(grey_allOf(grey_accessibilityID(kSettingsSignInCellId),
-                            grey_sufficientlyVisible(), nil));
+  WaitForMatcher(grey_accessibilityID(kSettingsSignInCellId));
 
   // Close Settings.
   TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON);
@@ -358,8 +357,7 @@
   TapButtonWithLabelId(IDS_IOS_MANAGED_DISCONNECT_DIALOG_ACCEPT);
 
   // Check that the settings home screen is shown.
-  WaitForMatcher(grey_allOf(grey_accessibilityID(kSettingsSignInCellId),
-                            grey_sufficientlyVisible(), nil));
+  WaitForMatcher(grey_accessibilityID(kSettingsSignInCellId));
 
   // Close Settings.
   TapButtonWithLabelId(IDS_IOS_NAVIGATION_BAR_DONE_BUTTON);
@@ -502,8 +500,7 @@
   AssertAuthenticatedIdentityInActiveProfile(nil);
 
   // Start sign-in with |identity1|.
-  WaitForMatcher(grey_allOf(grey_accessibilityID(kSettingsSignInCellId),
-                            grey_sufficientlyVisible(), nil));
+  WaitForMatcher(grey_accessibilityID(kSettingsSignInCellId));
   TapViewWithAccessibilityId(kSettingsSignInCellId);
   TapButtonWithAccessibilityLabel(identity1.userEmail);
   TapButtonWithLabelId(IDS_IOS_ACCOUNT_CONSISTENCY_SETUP_SIGNIN_BUTTON);
diff --git a/ios/chrome/browser/ui/history/history_ui_egtest.mm b/ios/chrome/browser/ui/history/history_ui_egtest.mm
index 89bc395..3f20831 100644
--- a/ios/chrome/browser/ui/history/history_ui_egtest.mm
+++ b/ios/chrome/browser/ui/history/history_ui_egtest.mm
@@ -153,9 +153,7 @@
       performAction:grey_tap()];
 
   [[EarlGrey
-      selectElementWithMatcher:grey_allOf(
-                                   grey_accessibilityID(kSettingsSignInCellId),
-                                   grey_sufficientlyVisible(), nil)]
+      selectElementWithMatcher:grey_accessibilityID(kSettingsSignInCellId)]
       performAction:grey_tap()];
   [[EarlGrey
       selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabel(
diff --git a/ios/chrome/browser/ui/settings/accounts_collection_egtest.mm b/ios/chrome/browser/ui/settings/accounts_collection_egtest.mm
index 31040d3..0d9aec4 100644
--- a/ios/chrome/browser/ui/settings/accounts_collection_egtest.mm
+++ b/ios/chrome/browser/ui/settings/accounts_collection_egtest.mm
@@ -126,10 +126,8 @@
       ->ForgetIdentity(identity, nil);
 
   [[EarlGrey
-      selectElementWithMatcher:grey_allOf(
-                                   grey_accessibilityID(kSettingsSignInCellId),
-                                   grey_sufficientlyVisible(), nil)]
-      assertWithMatcher:grey_notNil()];
+      selectElementWithMatcher:grey_accessibilityID(kSettingsSignInCellId)]
+      assertWithMatcher:grey_sufficientlyVisible()];
   AssertAuthenticatedIdentityInActiveProfile(nil);
 
   // Close Settings.
@@ -166,10 +164,8 @@
       ->ForgetIdentity(identity, nil);
 
   [[EarlGrey
-      selectElementWithMatcher:grey_allOf(
-                                   grey_accessibilityID(kSettingsSignInCellId),
-                                   grey_sufficientlyVisible(), nil)]
-      assertWithMatcher:grey_notNil()];
+      selectElementWithMatcher:grey_accessibilityID(kSettingsSignInCellId)]
+      assertWithMatcher:grey_sufficientlyVisible()];
   AssertAuthenticatedIdentityInActiveProfile(nil);
 
   // Close Settings.
@@ -272,10 +268,8 @@
 
   // Check that the user is signed out and the Main Settings screen is shown.
   [[EarlGrey
-      selectElementWithMatcher:grey_allOf(
-                                   grey_accessibilityID(kSettingsSignInCellId),
-                                   grey_sufficientlyVisible(), nil)]
-      assertWithMatcher:grey_notNil()];
+      selectElementWithMatcher:grey_accessibilityID(kSettingsSignInCellId)]
+      assertWithMatcher:grey_sufficientlyVisible()];
   AssertAuthenticatedIdentityInActiveProfile(nil);
 
   // Close Settings.
diff --git a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm
index a582f938..73c8da6 100644
--- a/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm
+++ b/ios/chrome/browser/ui/settings/settings_collection_view_controller.mm
@@ -200,9 +200,6 @@
   // Mediator to configure the sign-in promo cell. Also used to received
   // identity update notifications.
   base::scoped_nsobject<SigninPromoViewMediator> _signinPromoViewMediator;
-  // Item in the Sign-in section. Either CollectionViewAccountItem,
-  // AccountSignInItem or SigninPromoItem.
-  CollectionViewItem* _signinSectionItem;
 
   // Cached resized profile image.
   base::scoped_nsobject<UIImage> _resizedImage;
@@ -314,10 +311,6 @@
 - (void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];
   [self updateSearchCell];
-  // Sign-in section should not be reloaded while the controller is overlaid. So
-  // this section has to be reloaded before reappearing.
-  // See -[SettingsCollectionViewController onSignInStateChanged].
-  [self reloadSigninSectionWithAnimation:NO];
 }
 
 #pragma mark SettingsRootCollectionViewController
@@ -329,8 +322,27 @@
 
   // Sign in/Account section
   [model addSectionWithIdentifier:SectionIdentifierSignIn];
-  [model addItem:[self signinSectionItem]
-      toSectionWithIdentifier:SectionIdentifierSignIn];
+  AuthenticationService* authService =
+      AuthenticationServiceFactory::GetForBrowserState(_mainBrowserState);
+  if (!authService->IsAuthenticated()) {
+    if (!_hasRecordedSigninImpression) {
+      // Once the Settings are open, this button impression will at most be
+      // recorded once until they are closed.
+      base::RecordAction(
+          base::UserMetricsAction("Signin_Impression_FromSettings"));
+      _hasRecordedSigninImpression = YES;
+    }
+    if (experimental_flags::IsSigninPromoEnabled()) {
+      _signinPromoViewMediator.reset([[SigninPromoViewMediator alloc] init]);
+      _signinPromoViewMediator.get().consumer = self;
+    }
+    [model addItem:[self signInTextItem]
+        toSectionWithIdentifier:SectionIdentifierSignIn];
+  } else {
+    _signinPromoViewMediator.reset(nil);
+    [model addItem:[self accountCellItem]
+        toSectionWithIdentifier:SectionIdentifierSignIn];
+  }
 
   // Basics section
   [model addSectionWithIdentifier:SectionIdentifierBasics];
@@ -401,29 +413,6 @@
 #endif  // CHROMIUM_BUILD && !defined(NDEBUG)
 }
 
-- (CollectionViewItem*)signinSectionItem {
-  AuthenticationService* authService =
-      AuthenticationServiceFactory::GetForBrowserState(_mainBrowserState);
-  if (!authService->IsAuthenticated()) {
-    if (!_hasRecordedSigninImpression) {
-      // Once the Settings are open, this button impression will at most be
-      // recorded once until they are closed.
-      base::RecordAction(
-          base::UserMetricsAction("Signin_Impression_FromSettings"));
-      _hasRecordedSigninImpression = YES;
-    }
-    if (experimental_flags::IsSigninPromoEnabled()) {
-      _signinPromoViewMediator.reset([[SigninPromoViewMediator alloc] init]);
-      _signinPromoViewMediator.get().consumer = self;
-    }
-    _signinSectionItem = [self signInTextItem];
-  } else {
-    _signinPromoViewMediator.reset(nil);
-    _signinSectionItem = [self accountCellItem];
-  }
-  return _signinSectionItem;
-}
-
 #pragma mark - Model Items
 
 - (CollectionViewItem*)signInTextItem {
@@ -604,24 +593,6 @@
          inSectionWithIdentifier:SectionIdentifierBasics];
 }
 
-- (void)reloadSigninSectionWithAnimation:(BOOL)animation {
-  CollectionViewModel* model = self.collectionViewModel;
-  NSIndexPath* indexPath = [model indexPathForItem:_signinSectionItem
-                           inSectionWithIdentifier:SectionIdentifierSignIn];
-  [model removeItemWithType:_signinSectionItem.type
-      fromSectionWithIdentifier:SectionIdentifierSignIn];
-  [model addItem:[self signinSectionItem]
-      toSectionWithIdentifier:SectionIdentifierSignIn];
-  void (^reloadItemsBlock)(void) = ^{
-    [self.collectionView reloadItemsAtIndexPaths:@[ indexPath ]];
-  };
-  if (animation) {
-    reloadItemsBlock();
-  } else {
-    [UIView performWithoutAnimation:reloadItemsBlock];
-  }
-}
-
 #pragma mark Item Constructors
 
 - (CollectionViewDetailItem*)detailItemWithType:(NSInteger)type
@@ -1051,17 +1022,9 @@
 #pragma mark NotificationBridgeDelegate
 
 - (void)onSignInStateChanged {
-  // Sign-in section should only be reloaded when
-  // SettingsCollectionViewController is not overlaid.
-  // When clicking on "CONTINUE AS xxx" button, SigninInteractionController
-  // presents a signed-in view and sign-in the user at the same time.
-  // So to avoid having two animations, the sign-in section should only be
-  // reloaded when the settings controler is not overlaid.
-  // The sign-in section will be reloaded when
-  // -[SettingsCollectionViewController viewWillAppear:] is called.
-  if (!self.presentedViewController) {
-    [self reloadSigninSectionWithAnimation:YES];
-  }
+  // Sign in state changes are rare. Just reload the entire collection when this
+  // happens.
+  [self reloadData];
 }
 
 #pragma mark SettingsControllerProtocol
diff --git a/net/BUILD.gn b/net/BUILD.gn
index 29133431..3adf06d 100644
--- a/net/BUILD.gn
+++ b/net/BUILD.gn
@@ -41,7 +41,7 @@
 # in addition to use_openssl_certs or use_nss_certs, in that case byte certs
 # are used internally but OpenSSL or NSS are used for certificate verification.
 # TODO(mattm): crbug.com/671420: Implement and enable this for all platforms.
-use_byte_certs = is_mac || is_android
+use_byte_certs = is_mac
 
 buildflag_header("features") {
   header = "net_features.h"
diff --git a/net/cert/ct_objects_extractor.cc b/net/cert/ct_objects_extractor.cc
index 852bf827..1a6e6e4 100644
--- a/net/cert/ct_objects_extractor.cc
+++ b/net/cert/ct_objects_extractor.cc
@@ -41,9 +41,7 @@
 
 bssl::UniquePtr<X509> OSCertHandleToOpenSSL(
     X509Certificate::OSCertHandle os_handle) {
-#if BUILDFLAG(USE_BYTE_CERTS)
-  return bssl::UniquePtr<X509>(X509_parse_from_buffer(os_handle));
-#elif defined(USE_OPENSSL_CERTS)
+#if defined(USE_OPENSSL_CERTS)
   return bssl::UniquePtr<X509>(X509Certificate::DupOSCertHandle(os_handle));
 #else
   std::string der_encoded;
diff --git a/net/socket/ssl_server_socket_impl.cc b/net/socket/ssl_server_socket_impl.cc
index 5d4bce7..9b3cfd3 100644
--- a/net/socket/ssl_server_socket_impl.cc
+++ b/net/socket/ssl_server_socket_impl.cc
@@ -14,7 +14,6 @@
 #include "net/base/net_errors.h"
 #include "net/cert/cert_verify_result.h"
 #include "net/cert/client_cert_verifier.h"
-#include "net/cert/x509_util.h"
 #include "net/cert/x509_util_openssl.h"
 #include "net/log/net_log_event_type.h"
 #include "net/log/net_log_with_source.h"
@@ -625,8 +624,6 @@
   uint8_t session_ctx_id = 0;
   SSL_CTX_set_session_id_context(ssl_ctx_.get(), &session_ctx_id,
                                  sizeof(session_ctx_id));
-  // Deduplicate all certificates minted from the SSL_CTX in memory.
-  SSL_CTX_set0_buffer_pool(ssl_ctx_.get(), x509_util::GetBufferPool());
 
   int verify_mode = 0;
   switch (ssl_server_config_.client_cert_type) {
@@ -646,26 +643,26 @@
 
   // Set certificate and private key.
   DCHECK(cert_->os_cert_handle());
-  DCHECK(key_->key());
-#if BUILDFLAG(USE_BYTE_CERTS)
-  // On success, SSL_CTX_set_chain_and_key acquires a reference to
-  // |cert_->os_cert_handle()| and |key_->key()|.
-  CRYPTO_BUFFER* cert_buffers[] = {cert_->os_cert_handle()};
-  CHECK(SSL_CTX_set_chain_and_key(ssl_ctx_.get(), cert_buffers,
-                                  arraysize(cert_buffers), key_->key(),
-                                  nullptr /* privkey_method */));
-#elif defined(USE_OPENSSL_CERTS)
+#if defined(USE_OPENSSL_CERTS)
   CHECK(SSL_CTX_use_certificate(ssl_ctx_.get(), cert_->os_cert_handle()));
-  CHECK(SSL_CTX_use_PrivateKey(ssl_ctx_.get(), key_->key()));
 #else
+  // Convert OSCertHandle to X509 structure.
   std::string der_string;
   CHECK(X509Certificate::GetDEREncoded(cert_->os_cert_handle(), &der_string));
-  CHECK(SSL_CTX_use_certificate_ASN1(
-      ssl_ctx_.get(), der_string.length(),
-      reinterpret_cast<const unsigned char*>(der_string.data())));
-  // On success, SSL_CTX_use_PrivateKey acquires a reference to |key_->key()|.
+
+  const unsigned char* der_string_array =
+      reinterpret_cast<const unsigned char*>(der_string.data());
+
+  bssl::UniquePtr<X509> x509(
+      d2i_X509(NULL, &der_string_array, der_string.length()));
+  CHECK(x509);
+
+  // On success, SSL_CTX_use_certificate acquires a reference to |x509|.
+  CHECK(SSL_CTX_use_certificate(ssl_ctx_.get(), x509.get()));
+#endif  // USE_OPENSSL_CERTS
+
+  DCHECK(key_->key());
   CHECK(SSL_CTX_use_PrivateKey(ssl_ctx_.get(), key_->key()));
-#endif  // USE_OPENSSL_CERTS && !USE_BYTE_CERTS
 
   DCHECK_LT(SSL3_VERSION, ssl_server_config_.version_min);
   DCHECK_LT(SSL3_VERSION, ssl_server_config_.version_max);
diff --git a/net/ssl/openssl_client_key_store.cc b/net/ssl/openssl_client_key_store.cc
index 48895e9..295810f 100644
--- a/net/ssl/openssl_client_key_store.cc
+++ b/net/ssl/openssl_client_key_store.cc
@@ -7,7 +7,6 @@
 #include <utility>
 
 #include "base/memory/singleton.h"
-#include "net/cert/asn1_util.h"
 #include "net/cert/x509_certificate.h"
 #include "net/ssl/ssl_private_key.h"
 #include "third_party/boringssl/src/include/openssl/evp.h"
@@ -20,16 +19,6 @@
 
 // Serializes the SubjectPublicKeyInfo for |cert|.
 bool GetCertificateSPKI(const X509Certificate* cert, std::string* spki) {
-#if BUILDFLAG(USE_BYTE_CERTS)
-  base::StringPiece cert_der(
-      reinterpret_cast<const char*>(CRYPTO_BUFFER_data(cert->os_cert_handle())),
-      CRYPTO_BUFFER_len(cert->os_cert_handle()));
-  base::StringPiece spki_tmp;
-  if (!asn1::ExtractSPKIFromDERCert(cert_der, &spki_tmp))
-    return false;
-  spki_tmp.CopyToString(spki);
-  return true;
-#else
   bssl::UniquePtr<EVP_PKEY> pkey(X509_get_pubkey(cert->os_cert_handle()));
   if (!pkey) {
     LOG(ERROR) << "Can't extract private key from certificate!";
@@ -49,7 +38,6 @@
                reinterpret_cast<char*>(der) + der_len);
   OPENSSL_free(der);
   return true;
-#endif
 }
 
 }  // namespace
diff --git a/net/ssl/openssl_ssl_util.cc b/net/ssl/openssl_ssl_util.cc
index 8071da6..c3988b464 100644
--- a/net/ssl/openssl_ssl_util.cc
+++ b/net/ssl/openssl_ssl_util.cc
@@ -227,17 +227,15 @@
 
 bssl::UniquePtr<X509> OSCertHandleToOpenSSL(
     X509Certificate::OSCertHandle os_handle) {
-#if BUILDFLAG(USE_BYTE_CERTS)
-  return bssl::UniquePtr<X509>(X509_parse_from_buffer(os_handle));
-#elif defined(USE_OPENSSL_CERTS)
+#if defined(USE_OPENSSL_CERTS)
   return bssl::UniquePtr<X509>(X509Certificate::DupOSCertHandle(os_handle));
-#else   // !defined(USE_OPENSSL_CERTS) && !BUILDFLAG(USE_BYTE_CERTS)
+#else   // !defined(USE_OPENSSL_CERTS)
   std::string der_encoded;
   if (!X509Certificate::GetDEREncoded(os_handle, &der_encoded))
     return bssl::UniquePtr<X509>();
   const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
   return bssl::UniquePtr<X509>(d2i_X509(NULL, &bytes, der_encoded.size()));
-#endif  // defined(USE_OPENSSL_CERTS) && BUILDFLAG(USE_BYTE_CERTS)
+#endif  // defined(USE_OPENSSL_CERTS)
 }
 
 bssl::UniquePtr<STACK_OF(X509)> OSCertHandlesToOpenSSL(
diff --git a/printing/emf_win.h b/printing/emf_win.h
index c66e9f2..c9a8f60 100644
--- a/printing/emf_win.h
+++ b/printing/emf_win.h
@@ -77,9 +77,19 @@
 
   unsigned int GetPageCount() const override;
   HDC context() const override;
-  bool Playback(HDC hdc, const RECT* rect) const override;
+
   bool SafePlayback(HDC hdc) const override;
 
+  // "Plays" the EMF buffer in a HDC. It is the same effect as calling the
+  // original GDI function that were called when recording the EMF. |rect| is in
+  // "logical units" and is optional. If |rect| is NULL, the natural EMF bounds
+  // are used.
+  // Note: Windows has been known to have stack buffer overflow in its GDI
+  // functions, whether used directly or indirectly through precompiled EMF
+  // data. We have to accept the risk here. Since it is used only for printing,
+  // it requires user intervention.
+  bool Playback(HDC hdc, const RECT* rect) const;
+
   HENHMETAFILE emf() const { return emf_; }
 
   // Returns true if metafile contains alpha blend.
diff --git a/printing/image.cc b/printing/image.cc
index 37c4ced..5e6c276d 100644
--- a/printing/image.cc
+++ b/printing/image.cc
@@ -18,18 +18,13 @@
 
 namespace printing {
 
-Image::Image(const Metafile& metafile)
-    : row_length_(0),
-      ignore_alpha_(true) {
-  LoadMetafile(metafile);
+Image::Image(const void* metafile_src_buffer, size_t metafile_src_buffer_size)
+    : row_length_(0), ignore_alpha_(true) {
+  LoadMetafile(metafile_src_buffer, metafile_src_buffer_size);
 }
 
-Image::Image(const Image& image)
-    : size_(image.size_),
-      row_length_(image.row_length_),
-      data_(image.data_),
-      ignore_alpha_(image.ignore_alpha_) {
-}
+Image::Image(const Image&) = default;
+Image::Image(Image&&) = default;
 
 Image::~Image() {}
 
@@ -60,73 +55,4 @@
   }
   return success;
 }
-
-double Image::PercentageDifferent(const Image& rhs) const {
-  if (size_.width() == 0 || size_.height() == 0 ||
-    rhs.size_.width() == 0 || rhs.size_.height() == 0)
-    return 100.;
-
-  int width = std::min(size_.width(), rhs.size_.width());
-  int height = std::min(size_.height(), rhs.size_.height());
-  // Compute pixels different in the overlap
-  int pixels_different = 0;
-  for (int y = 0; y < height; ++y) {
-    for (int x = 0; x < width; ++x) {
-      uint32_t lhs_pixel = pixel_at(x, y);
-      uint32_t rhs_pixel = rhs.pixel_at(x, y);
-      if (lhs_pixel != rhs_pixel)
-        ++pixels_different;
-    }
-
-    // Look for extra right lhs pixels. They should be white.
-    for (int x = width; x < size_.width(); ++x) {
-      uint32_t lhs_pixel = pixel_at(x, y);
-      if (lhs_pixel != Color(SK_ColorWHITE))
-        ++pixels_different;
-    }
-
-    // Look for extra right rhs pixels. They should be white.
-    for (int x = width; x < rhs.size_.width(); ++x) {
-      uint32_t rhs_pixel = rhs.pixel_at(x, y);
-      if (rhs_pixel != Color(SK_ColorWHITE))
-        ++pixels_different;
-    }
-  }
-
-  // Look for extra bottom lhs pixels. They should be white.
-  for (int y = height; y < size_.height(); ++y) {
-    for (int x = 0; x < size_.width(); ++x) {
-      uint32_t lhs_pixel = pixel_at(x, y);
-      if (lhs_pixel != Color(SK_ColorWHITE))
-        ++pixels_different;
-    }
-  }
-
-  // Look for extra bottom rhs pixels. They should be white.
-  for (int y = height; y < rhs.size_.height(); ++y) {
-    for (int x = 0; x < rhs.size_.width(); ++x) {
-      uint32_t rhs_pixel = rhs.pixel_at(x, y);
-      if (rhs_pixel != Color(SK_ColorWHITE))
-        ++pixels_different;
-    }
-  }
-
-  // Like the WebKit ImageDiff tool, we define percentage different in terms
-  // of the size of the 'actual' bitmap.
-  double total_pixels = static_cast<double>(size_.width()) *
-      static_cast<double>(height);
-  return static_cast<double>(pixels_different) / total_pixels * 100.;
-}
-
-bool Image::LoadPng(const std::string& compressed) {
-  int w;
-  int h;
-  bool success = gfx::PNGCodec::Decode(
-      reinterpret_cast<const unsigned char*>(compressed.c_str()),
-      compressed.size(), gfx::PNGCodec::FORMAT_BGRA, &data_, &w, &h);
-  size_.SetSize(w, h);
-  row_length_ = size_.width() * sizeof(uint32_t);
-  return success;
-}
-
 }  // namespace printing
diff --git a/printing/image.h b/printing/image.h
index e055d189..de949573 100644
--- a/printing/image.h
+++ b/printing/image.h
@@ -21,18 +21,16 @@
 
 namespace printing {
 
-class Metafile;
-
 // Lightweight raw-bitmap management. The image, once initialized, is immutable.
 // The main purpose is testing image contents.
 class PRINTING_EXPORT Image {
  public:
   // Creates the image from the metafile.  Deduces bounds based on bounds in
   // metafile.  If loading fails size().IsEmpty() will be true.
-  explicit Image(const Metafile& metafile);
+  Image(const void* metafile_src_buffer, size_t metafile_src_buffer_size);
 
-  // Copy constructor.
-  explicit Image(const Image& image);
+  Image(const Image& image);
+  Image(Image&& image);
 
   ~Image();
 
@@ -46,33 +44,9 @@
   // Save image as PNG.
   bool SaveToPng(const base::FilePath& filepath) const;
 
-  // Returns % of pixels different
-  double PercentageDifferent(const Image& rhs) const;
-
-  // Returns the 0x0RGB or 0xARGB value of the pixel at the given location.
-  uint32_t Color(uint32_t color) const {
-    if (ignore_alpha_)
-      return color & 0xFFFFFF;  // Strip out A.
-    else
-      return color;
-  }
-
-  uint32_t pixel_at(int x, int y) const {
-    DCHECK(x >= 0 && x < size_.width());
-    DCHECK(y >= 0 && y < size_.height());
-    const uint32_t* data = reinterpret_cast<const uint32_t*>(&*data_.begin());
-    const uint32_t* data_row = data + y * row_length_ / sizeof(uint32_t);
-    return Color(data_row[x]);
-  }
-
  private:
-  // Construct from metafile.  This is kept internal since it's ambiguous what
-  // kind of data is used (png, bmp, metafile etc).
-  Image(const void* data, size_t size);
-
-  bool LoadPng(const std::string& compressed);
-
-  bool LoadMetafile(const Metafile& metafile);
+  bool LoadMetafile(const void* metafile_src_buffer,
+                    size_t metafile_src_buffer_size);
 
   // Pixel dimensions of the image.
   gfx::Size size_;
diff --git a/printing/image_android.cc b/printing/image_android.cc
index 544cf07..1e6582d 100644
--- a/printing/image_android.cc
+++ b/printing/image_android.cc
@@ -6,7 +6,7 @@
 
 namespace printing {
 
-bool Image::LoadMetafile(const Metafile& metafile) {
+bool Image::LoadMetafile(const void*, size_t) {
   return false;
 }
 
diff --git a/printing/image_linux.cc b/printing/image_linux.cc
index d89c4e9..af97960 100644
--- a/printing/image_linux.cc
+++ b/printing/image_linux.cc
@@ -6,7 +6,7 @@
 
 namespace printing {
 
-bool Image::LoadMetafile(const Metafile& metafile) {
+bool Image::LoadMetafile(const void*, size_t) {
   return false;
 }
 
diff --git a/printing/image_mac.cc b/printing/image_mac.cc
index 7edcfd7..695cc453 100644
--- a/printing/image_mac.cc
+++ b/printing/image_mac.cc
@@ -10,13 +10,17 @@
 #include <stdint.h>
 
 #include "base/mac/scoped_cftyperef.h"
-#include "printing/metafile.h"
 #include "printing/pdf_metafile_cg_mac.h"
 #include "ui/gfx/geometry/rect.h"
 
 namespace printing {
 
-bool Image::LoadMetafile(const Metafile& metafile) {
+bool Image::LoadMetafile(const void* metafile_src_buffer,
+                         size_t metafile_src_buffer_size) {
+  PdfMetafileCg metafile;
+  if (!metafile.InitFromData(metafile_src_buffer, metafile_src_buffer_size)) {
+    return false;
+  }
   // The printing system uses single-page metafiles (page indexes are 1-based).
   const unsigned int page_number = 1;
   gfx::Rect rect(metafile.GetPageBounds(page_number));
@@ -44,10 +48,7 @@
   PdfMetafileCg::RenderPageParams params;
   params.shrink_to_fit = true;
   CGRect cg_rect = CGRectMake(0, 0, size_.width(), size_.height());
-  std::vector<char> buffer;
-  return metafile.GetDataAsVector(&buffer) &&
-         PdfMetafileCg::RenderPage(buffer, page_number, bitmap_context, cg_rect,
-                                   params);
+  return metafile.OnRenderPage(page_number, bitmap_context, cg_rect, params);
 }
 
 }  // namespace printing
diff --git a/printing/image_win.cc b/printing/image_win.cc
index 787c24aa..6473740 100644
--- a/printing/image_win.cc
+++ b/printing/image_win.cc
@@ -11,7 +11,7 @@
 #include "base/win/scoped_gdi_object.h"
 #include "base/win/scoped_hdc.h"
 #include "base/win/scoped_select_object.h"
-#include "printing/metafile.h"
+#include "printing/emf_win.h"
 #include "skia/ext/skia_utils_win.h"
 #include "ui/gfx/gdi_util.h"  // EMF support
 #include "ui/gfx/geometry/rect.h"
@@ -53,8 +53,13 @@
 
 namespace printing {
 
-bool Image::LoadMetafile(const Metafile& metafile) {
-    gfx::Rect rect(metafile.GetPageBounds(1));
+bool Image::LoadMetafile(const void* metafile_src_buffer,
+                         size_t metafile_src_buffer_size) {
+  Emf metafile;
+  if (!metafile.InitFromData(metafile_src_buffer, metafile_src_buffer_size)) {
+    return false;
+  }
+  gfx::Rect rect(metafile.GetPageBounds(1));
   DisableFontSmoothing disable_in_this_scope;
 
   // Create a temporary HDC and bitmap to retrieve the rendered data.
diff --git a/printing/metafile.h b/printing/metafile.h
index 98eaa39..88ab032 100644
--- a/printing/metafile.h
+++ b/printing/metafile.h
@@ -14,10 +14,6 @@
 #include "printing/native_drawing_context.h"
 #include "printing/printing_export.h"
 
-#if defined(OS_WIN)
-#include <windows.h>
-#endif
-
 namespace base {
 class File;
 }
@@ -103,19 +99,6 @@
 
   virtual skia::NativeDrawingContext context() const = 0;
 
-#if defined(OS_WIN)
-  // "Plays" the EMF buffer in a HDC. It is the same effect as calling the
-  // original GDI function that were called when recording the EMF. |rect| is in
-  // "logical units" and is optional. If |rect| is NULL, the natural EMF bounds
-  // are used.
-  // Note: Windows has been known to have stack buffer overflow in its GDI
-  // functions, whether used directly or indirectly through precompiled EMF
-  // data. We have to accept the risk here. Since it is used only for printing,
-  // it requires user intervention.
-  virtual bool Playback(skia::NativeDrawingContext hdc,
-                        const RECT* rect) const = 0;
-#endif  // OS_WIN
-
   // MetfilePlayer
   bool GetDataAsVector(std::vector<char>* buffer) const override;
   bool SaveTo(base::File* file) const override;
diff --git a/printing/pdf_metafile_cg_mac.cc b/printing/pdf_metafile_cg_mac.cc
index 898e795..f6a53f5 100644
--- a/printing/pdf_metafile_cg_mac.cc
+++ b/printing/pdf_metafile_cg_mac.cc
@@ -174,7 +174,15 @@
     LOG(ERROR) << "Unable to initialize PDF document from data";
     return false;
   }
-  CGPDFDocumentRef pdf_doc = metafile.GetPDFDocument();
+  return metafile.OnRenderPage(page_number, context, rect, params);
+}
+
+bool PdfMetafileCg::OnRenderPage(
+    unsigned int page_number,
+    CGContextRef context,
+    const CGRect rect,
+    const PdfMetafileCg::RenderPageParams& params) {
+  CGPDFDocumentRef pdf_doc = GetPDFDocument();
   if (!pdf_doc) {
     LOG(ERROR) << "Unable to create PDF document from data";
     return false;
diff --git a/printing/pdf_metafile_cg_mac.h b/printing/pdf_metafile_cg_mac.h
index 8992a8c66..7d64f09e 100644
--- a/printing/pdf_metafile_cg_mac.h
+++ b/printing/pdf_metafile_cg_mac.h
@@ -69,6 +69,14 @@
     bool center_vertically = false;
     bool autorotate = false;
   };
+  // Renders the given page from this metafile into |rect| in the given context.
+  // Pages use a 1-based index. The rendering uses the arguments in
+  // |params| to determine scaling, translation, and rotation.
+  bool OnRenderPage(unsigned int page_number,
+                    CGContextRef context,
+                    const CGRect rect,
+                    const RenderPageParams& params);
+
   // Renders the given page from |src_buffer| into |rect| in the given context.
   // Pages use a 1-based index. The rendering uses the arguments in
   // |params| to determine scaling, translation, and rotation.
diff --git a/printing/pdf_metafile_skia.cc b/printing/pdf_metafile_skia.cc
index 12b24ad..aec4d3f 100644
--- a/printing/pdf_metafile_skia.cc
+++ b/printing/pdf_metafile_skia.cc
@@ -233,12 +233,6 @@
 
 
 #if defined(OS_WIN)
-bool PdfMetafileSkia::Playback(skia::NativeDrawingContext hdc,
-                               const RECT* rect) const {
-  NOTREACHED();
-  return false;
-}
-
 bool PdfMetafileSkia::SafePlayback(skia::NativeDrawingContext hdc) const {
   NOTREACHED();
   return false;
diff --git a/printing/pdf_metafile_skia.h b/printing/pdf_metafile_skia.h
index e27da152..9296acb 100644
--- a/printing/pdf_metafile_skia.h
+++ b/printing/pdf_metafile_skia.h
@@ -54,8 +54,6 @@
   skia::NativeDrawingContext context() const override;
 
 #if defined(OS_WIN)
-  bool Playback(skia::NativeDrawingContext hdc,
-                const RECT* rect) const override;
   bool SafePlayback(skia::NativeDrawingContext hdc) const override;
 #endif
 
diff --git a/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through-expected.txt
deleted file mode 100644
index 9b1cbbf..0000000
--- a/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through-expected.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-This is a testharness.js-based test.
-Harness Error. harness_status.status = 1 , harness_status.message = this rejection should not be reported as unhandled
-PASS Piping through a duck-typed pass-through transform stream should work 
-PASS Piping through a transform errored on the writable end does not cause an unhandled promise rejection 
-PASS pipeThrough generically calls pipeTo with the appropriate args 
-PASS pipeThrough can handle calling a pipeTo that returns a non-promise object 
-PASS pipeThrough can handle calling a pipeTo that returns a non-promise thenable object 
-PASS pipeThrough should mark a real promise from a fake readable as handled 
-PASS pipeThrough should not be fooled by an object whose instanceof Promise returns true 
-Harness: the test ran to completion.
-
diff --git a/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.dedicatedworker-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.dedicatedworker-expected.txt
deleted file mode 100644
index 9b1cbbf..0000000
--- a/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.dedicatedworker-expected.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-This is a testharness.js-based test.
-Harness Error. harness_status.status = 1 , harness_status.message = this rejection should not be reported as unhandled
-PASS Piping through a duck-typed pass-through transform stream should work 
-PASS Piping through a transform errored on the writable end does not cause an unhandled promise rejection 
-PASS pipeThrough generically calls pipeTo with the appropriate args 
-PASS pipeThrough can handle calling a pipeTo that returns a non-promise object 
-PASS pipeThrough can handle calling a pipeTo that returns a non-promise thenable object 
-PASS pipeThrough should mark a real promise from a fake readable as handled 
-PASS pipeThrough should not be fooled by an object whose instanceof Promise returns true 
-Harness: the test ran to completion.
-
diff --git a/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.serviceworker.https-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.serviceworker.https-expected.txt
deleted file mode 100644
index 4bf888f6..0000000
--- a/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.serviceworker.https-expected.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-This is a testharness.js-based test.
-Harness Error. harness_status.status = 1 , harness_status.message = this rejection should not be reported as unhandled
-PASS Service worker test setup 
-PASS Piping through a duck-typed pass-through transform stream should work 
-PASS Piping through a transform errored on the writable end does not cause an unhandled promise rejection 
-PASS pipeThrough generically calls pipeTo with the appropriate args 
-PASS pipeThrough can handle calling a pipeTo that returns a non-promise object 
-PASS pipeThrough can handle calling a pipeTo that returns a non-promise thenable object 
-PASS pipeThrough should mark a real promise from a fake readable as handled 
-PASS pipeThrough should not be fooled by an object whose instanceof Promise returns true 
-Harness: the test ran to completion.
-
diff --git a/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.sharedworker-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.sharedworker-expected.txt
deleted file mode 100644
index 9b1cbbf..0000000
--- a/third_party/WebKit/LayoutTests/external/wpt/streams/piping/pipe-through.sharedworker-expected.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-This is a testharness.js-based test.
-Harness Error. harness_status.status = 1 , harness_status.message = this rejection should not be reported as unhandled
-PASS Piping through a duck-typed pass-through transform stream should work 
-PASS Piping through a transform errored on the writable end does not cause an unhandled promise rejection 
-PASS pipeThrough generically calls pipeTo with the appropriate args 
-PASS pipeThrough can handle calling a pipeTo that returns a non-promise object 
-PASS pipeThrough can handle calling a pipeTo that returns a non-promise thenable object 
-PASS pipeThrough should mark a real promise from a fake readable as handled 
-PASS pipeThrough should not be fooled by an object whose instanceof Promise returns true 
-Harness: the test ran to completion.
-
diff --git a/third_party/WebKit/LayoutTests/plugins/mouse-click-plugin-clears-selection.html b/third_party/WebKit/LayoutTests/plugins/mouse-click-plugin-clears-selection.html
index 9b41982..db74ae95 100644
--- a/third_party/WebKit/LayoutTests/plugins/mouse-click-plugin-clears-selection.html
+++ b/third_party/WebKit/LayoutTests/plugins/mouse-click-plugin-clears-selection.html
@@ -8,7 +8,7 @@
     inputElement.select();
 
     if (!window.testRunner) {
-        output.textContent = "Test that clicking on a plugin clears the selection on the currently focused element. Click on the plugin; the text in the input control should no longer be highlighted. The rendertree for this test should not contain any selection information. See https://bugs.webkit.org/show_bug.cgi?id=30355";
+        output.textContent = "Test that clicking on a plugin clears the selection on the currently focused element. Click on the plugin; the text in the input control should no longer be highlighted. See https://bugs.webkit.org/show_bug.cgi?id=30355";
     } else {
         eventSender.mouseMoveTo(60, 60);
         eventSender.mouseDown();
diff --git a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
index 1f052c5..195bb02 100644
--- a/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
+++ b/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -895,6 +895,10 @@
   const SegmentedString source(input_source);
 
   if (GetDocument()->IsPrefetchOnly()) {
+    // Do not prefetch if there is an appcache.
+    if (GetDocument()->Loader()->GetResponse().AppCacheID() != 0)
+      return;
+
     if (!preload_scanner_)
       preload_scanner_ = CreatePreloadScanner();
 
diff --git a/third_party/WebKit/Source/core/streams/ReadableStream.js b/third_party/WebKit/Source/core/streams/ReadableStream.js
index 241e3ad..bc70cf9e6 100644
--- a/third_party/WebKit/Source/core/streams/ReadableStream.js
+++ b/third_party/WebKit/Source/core/streams/ReadableStream.js
@@ -177,7 +177,10 @@
     }
 
     pipeThrough({writable, readable}, options) {
-      this.pipeTo(writable, options);
+      const promise = this.pipeTo(writable, options);
+      if (v8.isPromise(promise)) {
+        v8.markPromiseAsHandled(promise);
+      }
       return readable;
     }
 
diff --git a/third_party/WebKit/Source/modules/indexeddb/IDBRequest.h b/third_party/WebKit/Source/modules/indexeddb/IDBRequest.h
index cbcff8ba..4f221aeb 100644
--- a/third_party/WebKit/Source/modules/indexeddb/IDBRequest.h
+++ b/third_party/WebKit/Source/modules/indexeddb/IDBRequest.h
@@ -120,7 +120,7 @@
   }
   virtual void OnSuccess(std::unique_ptr<WebIDBDatabase>,
                          const IDBDatabaseMetadata&) {
-    ASSERT_NOT_REACHED();
+    NOTREACHED();
   }
 
   // ScriptWrappable
diff --git a/third_party/WebKit/public/web/WebContextMenuData.h b/third_party/WebKit/public/web/WebContextMenuData.h
index ce07640..9e261cb 100644
--- a/third_party/WebKit/public/web/WebContextMenuData.h
+++ b/third_party/WebKit/public/web/WebContextMenuData.h
@@ -190,7 +190,7 @@
 
   WebContextMenuData()
       : media_type(kMediaTypeNone),
-        has_image_contents(true),
+        has_image_contents(false),
         media_flags(kMediaNone),
         is_spell_checking_enabled(false),
         is_editable(false),