diff --git a/base/callback_unittest.cc b/base/callback_unittest.cc index 455c2740..f76adbc 100644 --- a/base/callback_unittest.cc +++ b/base/callback_unittest.cc
@@ -21,24 +21,13 @@ // based on a type we declared in the anonymous namespace above to remove any // chance of colliding with another instantiation and breaking the // one-definition-rule. -struct FakeBindState1 : internal::BindStateBase { - FakeBindState1() : BindStateBase(&NopInvokeFunc, &Destroy, &IsCancelled) {} - private: - ~FakeBindState1() {} - static void Destroy(const internal::BindStateBase* self) { - delete static_cast<const FakeBindState1*>(self); - } - static bool IsCancelled(const internal::BindStateBase*) { - return false; - } -}; +struct FakeBindState : internal::BindStateBase { + FakeBindState() : BindStateBase(&NopInvokeFunc, &Destroy, &IsCancelled) {} -struct FakeBindState2 : internal::BindStateBase { - FakeBindState2() : BindStateBase(&NopInvokeFunc, &Destroy, &IsCancelled) {} private: - ~FakeBindState2() {} + ~FakeBindState() {} static void Destroy(const internal::BindStateBase* self) { - delete static_cast<const FakeBindState2*>(self); + delete static_cast<const FakeBindState*>(self); } static bool IsCancelled(const internal::BindStateBase*) { return false; @@ -50,9 +39,7 @@ class CallbackTest : public ::testing::Test { public: CallbackTest() - : callback_a_(new FakeBindState1()), - callback_b_(new FakeBindState2()) { - } + : callback_a_(new FakeBindState()), callback_b_(new FakeBindState()) {} ~CallbackTest() override {} @@ -94,7 +81,7 @@ EXPECT_FALSE(callback_b_.Equals(callback_a_)); // We should compare based on instance, not type. - Callback<void()> callback_c(new FakeBindState1()); + Callback<void()> callback_c(new FakeBindState()); Callback<void()> callback_a2 = callback_a_; EXPECT_TRUE(callback_a_.Equals(callback_a2)); EXPECT_FALSE(callback_a_.Equals(callback_c));
diff --git a/base/process/process_metrics.cc b/base/process/process_metrics.cc index a38930a..ad555ae 100644 --- a/base/process/process_metrics.cc +++ b/base/process/process_metrics.cc
@@ -12,6 +12,11 @@ namespace base { +SystemMemoryInfoKB::SystemMemoryInfoKB() = default; + +SystemMemoryInfoKB::SystemMemoryInfoKB(const SystemMemoryInfoKB& other) = + default; + SystemMetrics::SystemMetrics() { committed_memory_ = 0; }
diff --git a/base/process/process_metrics.h b/base/process/process_metrics.h index aa26b902..33cb64e2 100644 --- a/base/process/process_metrics.h +++ b/base/process/process_metrics.h
@@ -268,11 +268,13 @@ // Data about system-wide memory consumption. Values are in KB. Available on // Windows, Mac, Linux, Android and Chrome OS. // -// Total/free memory are available on all platforms that implement +// Total memory are available on all platforms that implement // GetSystemMemoryInfo(). Total/free swap memory are available on all platforms // except on Mac. Buffers/cached/active_anon/inactive_anon/active_file/ -// inactive_file/dirty/pswpin/pswpout/pgmajfault are available on +// inactive_file/dirty/reclaimable/pswpin/pswpout/pgmajfault are available on // Linux/Android/Chrome OS. Shmem/slab/gem_objects/gem_size are Chrome OS only. +// Speculative/file_backed/purgeable are Mac and iOS only. +// Free is absent on Windows (see "avail_phys" below). struct BASE_EXPORT SystemMemoryInfoKB { SystemMemoryInfoKB(); SystemMemoryInfoKB(const SystemMemoryInfoKB& other); @@ -280,44 +282,64 @@ // Serializes the platform specific fields to value. std::unique_ptr<Value> ToValue() const; - int total; - int free; + int total = 0; -#if defined(OS_LINUX) +#if !defined(OS_WIN) + int free = 0; +#endif + +#if defined(OS_WIN) + // "This is the amount of physical memory that can be immediately reused + // without having to write its contents to disk first. It is the sum of the + // size of the standby, free, and zero lists." (MSDN). + // Standby: not modified pages of physical ram (file-backed memory) that are + // not actively being used. + int avail_phys = 0; +#endif + +#if defined(OS_LINUX) || defined(OS_ANDROID) // This provides an estimate of available memory as described here: // https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 // NOTE: this is ONLY valid in kernels 3.14 and up. Its value will always // be 0 in earlier kernel versions. - int available; + // Note: it includes _all_ file-backed memory (active + inactive). + int available = 0; #endif #if !defined(OS_MACOSX) - int swap_total; - int swap_free; + int swap_total = 0; + int swap_free = 0; #endif #if defined(OS_ANDROID) || defined(OS_LINUX) - int buffers; - int cached; - int active_anon; - int inactive_anon; - int active_file; - int inactive_file; - int dirty; + int buffers = 0; + int cached = 0; + int active_anon = 0; + int inactive_anon = 0; + int active_file = 0; + int inactive_file = 0; + int dirty = 0; + int reclaimable = 0; // vmstats data. - unsigned long pswpin; - unsigned long pswpout; - unsigned long pgmajfault; + unsigned long pswpin = 0; + unsigned long pswpout = 0; + unsigned long pgmajfault = 0; #endif // defined(OS_ANDROID) || defined(OS_LINUX) #if defined(OS_CHROMEOS) - int shmem; - int slab; + int shmem = 0; + int slab = 0; // Gem data will be -1 if not supported. - int gem_objects; - long long gem_size; + int gem_objects = -1; + long long gem_size = -1; #endif // defined(OS_CHROMEOS) + +#if defined(OS_MACOSX) + int speculative = 0; + int file_backed = 0; + int purgeable = 0; +#endif // defined(OS_MACOSX) }; // On Linux/Android/Chrome OS, system-wide memory consumption data is parsed
diff --git a/base/process/process_metrics_ios.cc b/base/process/process_metrics_ios.cc index e6b0119..2ed65ab3 100644 --- a/base/process/process_metrics_ios.cc +++ b/base/process/process_metrics_ios.cc
@@ -9,7 +9,9 @@ #include <stddef.h> #include "base/logging.h" +#include "base/mac/scoped_mach_port.h" #include "base/memory/ptr_util.h" +#include "base/numerics/safe_conversions.h" namespace base { @@ -26,11 +28,6 @@ } // namespace -SystemMemoryInfoKB::SystemMemoryInfoKB() : total(0), free(0) {} - -SystemMemoryInfoKB::SystemMemoryInfoKB(const SystemMemoryInfoKB& other) = - default; - ProcessMetrics::ProcessMetrics(ProcessHandle process) {} ProcessMetrics::~ProcessMetrics() {} @@ -91,11 +88,40 @@ return 0; } -// Bytes committed by the system. bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) { - // Unimplemented. Must enable unittest for IOS when this gets implemented. - NOTIMPLEMENTED(); - return false; + struct host_basic_info hostinfo; + mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT; + base::mac::ScopedMachSendRight host(mach_host_self()); + int result = host_info(host.get(), HOST_BASIC_INFO, + reinterpret_cast<host_info_t>(&hostinfo), &count); + if (result != KERN_SUCCESS) + return false; + + DCHECK_EQ(HOST_BASIC_INFO_COUNT, count); + meminfo->total = static_cast<int>(hostinfo.max_mem / 1024); + + vm_statistics64_data_t vm_info; + count = HOST_VM_INFO64_COUNT; + + if (host_statistics64(host.get(), HOST_VM_INFO64, + reinterpret_cast<host_info64_t>(&vm_info), + &count) != KERN_SUCCESS) { + return false; + } + DCHECK_EQ(HOST_VM_INFO64_COUNT, count); + + // Check that PAGE_SIZE is divisible by 1024 (2^10). + CHECK_EQ(PAGE_SIZE, (PAGE_SIZE >> 10) << 10); + meminfo->free = saturated_cast<int>( + PAGE_SIZE / 1024 * (vm_info.free_count - vm_info.speculative_count)); + meminfo->speculative = + saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.speculative_count); + meminfo->file_backed = + saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.external_page_count); + meminfo->purgeable = + saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.purgeable_count); + + return true; } } // namespace base
diff --git a/base/process/process_metrics_linux.cc b/base/process/process_metrics_linux.cc index e507d16..ba0dfa7 100644 --- a/base/process/process_metrics_linux.cc +++ b/base/process/process_metrics_linux.cc
@@ -558,45 +558,12 @@ } // namespace -SystemMemoryInfoKB::SystemMemoryInfoKB() { - total = 0; - free = 0; -#if defined(OS_LINUX) - available = 0; -#endif - buffers = 0; - cached = 0; - active_anon = 0; - inactive_anon = 0; - active_file = 0; - inactive_file = 0; - swap_total = 0; - swap_free = 0; - dirty = 0; - - pswpin = 0; - pswpout = 0; - pgmajfault = 0; - -#ifdef OS_CHROMEOS - shmem = 0; - slab = 0; - gem_objects = -1; - gem_size = -1; -#endif -} - -SystemMemoryInfoKB::SystemMemoryInfoKB(const SystemMemoryInfoKB& other) = - default; - std::unique_ptr<Value> SystemMemoryInfoKB::ToValue() const { std::unique_ptr<DictionaryValue> res(new DictionaryValue()); res->SetInteger("total", total); res->SetInteger("free", free); -#if defined(OS_LINUX) res->SetInteger("available", available); -#endif res->SetInteger("buffers", buffers); res->SetInteger("cached", cached); res->SetInteger("active_anon", active_anon); @@ -607,6 +574,7 @@ res->SetInteger("swap_free", swap_free); res->SetInteger("swap_used", swap_total - swap_free); res->SetInteger("dirty", dirty); + res->SetInteger("reclaimable", reclaimable); res->SetInteger("pswpin", pswpin); res->SetInteger("pswpout", pswpout); res->SetInteger("pgmajfault", pgmajfault); @@ -654,10 +622,8 @@ target = &meminfo->total; else if (tokens[0] == "MemFree:") target = &meminfo->free; -#if defined(OS_LINUX) else if (tokens[0] == "MemAvailable:") target = &meminfo->available; -#endif else if (tokens[0] == "Buffers:") target = &meminfo->buffers; else if (tokens[0] == "Cached:") @@ -676,6 +642,8 @@ target = &meminfo->swap_free; else if (tokens[0] == "Dirty:") target = &meminfo->dirty; + else if (tokens[0] == "SReclaimable:") + target = &meminfo->reclaimable; #if defined(OS_CHROMEOS) // Chrome OS has a tweaked kernel that allows us to query Shmem, which is // usually video memory otherwise invisible to the OS.
diff --git a/base/process/process_metrics_mac.cc b/base/process/process_metrics_mac.cc index 84bf3ea..c52078f 100644 --- a/base/process/process_metrics_mac.cc +++ b/base/process/process_metrics_mac.cc
@@ -16,6 +16,7 @@ #include "base/mac/mach_logging.h" #include "base/mac/scoped_mach_port.h" #include "base/memory/ptr_util.h" +#include "base/numerics/safe_conversions.h" #include "base/sys_info.h" #if !defined(TASK_POWER_INFO) @@ -80,11 +81,6 @@ } // namespace -SystemMemoryInfoKB::SystemMemoryInfoKB() : total(0), free(0) {} - -SystemMemoryInfoKB::SystemMemoryInfoKB(const SystemMemoryInfoKB& other) = - default; - // Getting a mach task from a pid for another process requires permissions in // general, so there doesn't really seem to be a way to do these (and spinning // up ps to fetch each stats seems dangerous to put in a base api for anyone to @@ -392,7 +388,6 @@ return (data.active_count * PAGE_SIZE) / 1024; } -// On Mac, We only get total memory and free memory from the system. bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) { struct host_basic_info hostinfo; mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT; @@ -405,17 +400,25 @@ DCHECK_EQ(HOST_BASIC_INFO_COUNT, count); meminfo->total = static_cast<int>(hostinfo.max_mem / 1024); - vm_statistics_data_t vm_info; - count = HOST_VM_INFO_COUNT; + vm_statistics64_data_t vm_info; + count = HOST_VM_INFO64_COUNT; - if (host_statistics(host.get(), HOST_VM_INFO, - reinterpret_cast<host_info_t>(&vm_info), - &count) != KERN_SUCCESS) { + if (host_statistics64(host.get(), HOST_VM_INFO64, + reinterpret_cast<host_info64_t>(&vm_info), + &count) != KERN_SUCCESS) { return false; } + DCHECK_EQ(HOST_VM_INFO64_COUNT, count); - meminfo->free = static_cast<int>( - (vm_info.free_count - vm_info.speculative_count) * PAGE_SIZE / 1024); + static_assert(PAGE_SIZE % 1024 == 0, "Invalid page size"); + meminfo->free = saturated_cast<int>( + PAGE_SIZE / 1024 * (vm_info.free_count - vm_info.speculative_count)); + meminfo->speculative = + saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.speculative_count); + meminfo->file_backed = + saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.external_page_count); + meminfo->purgeable = + saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.purgeable_count); return true; }
diff --git a/base/process/process_metrics_unittest.cc b/base/process/process_metrics_unittest.cc index 3bb8552..b11a26b 100644 --- a/base/process/process_metrics_unittest.cc +++ b/base/process/process_metrics_unittest.cc
@@ -17,6 +17,7 @@ #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/strings/string_number_conversions.h" +#include "base/sys_info.h" #include "base/test/multiprocess_test.h" #include "base/threading/thread.h" #include "build/build_config.h" @@ -106,6 +107,7 @@ std::string valid_input1 = "MemTotal: 3981504 kB\n" "MemFree: 140764 kB\n" + "MemAvailable: 535413 kB\n" "Buffers: 116480 kB\n" "Cached: 406160 kB\n" "SwapCached: 21304 kB\n" @@ -171,6 +173,7 @@ EXPECT_TRUE(ParseProcMeminfo(valid_input1, &meminfo)); EXPECT_EQ(meminfo.total, 3981504); EXPECT_EQ(meminfo.free, 140764); + EXPECT_EQ(meminfo.available, 535413); EXPECT_EQ(meminfo.buffers, 116480); EXPECT_EQ(meminfo.cached, 406160); EXPECT_EQ(meminfo.active_anon, 2972352); @@ -180,18 +183,29 @@ EXPECT_EQ(meminfo.swap_total, 5832280); EXPECT_EQ(meminfo.swap_free, 3672368); EXPECT_EQ(meminfo.dirty, 184); + EXPECT_EQ(meminfo.reclaimable, 30936); #if defined(OS_CHROMEOS) EXPECT_EQ(meminfo.shmem, 140204); EXPECT_EQ(meminfo.slab, 54212); #endif + EXPECT_EQ(355725, + base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo) / 1024); + // Simulate as if there is no MemAvailable. + meminfo.available = 0; + EXPECT_EQ(374448, + base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo) / 1024); + meminfo = {}; EXPECT_TRUE(ParseProcMeminfo(valid_input2, &meminfo)); EXPECT_EQ(meminfo.total, 255908); EXPECT_EQ(meminfo.free, 69936); + EXPECT_EQ(meminfo.available, 0); EXPECT_EQ(meminfo.buffers, 15812); EXPECT_EQ(meminfo.cached, 115124); EXPECT_EQ(meminfo.swap_total, 524280); EXPECT_EQ(meminfo.swap_free, 524200); EXPECT_EQ(meminfo.dirty, 4); + EXPECT_EQ(69936, + base::SysInfo::AmountOfAvailablePhysicalMemory(meminfo) / 1024); } TEST_F(SystemMetricsTest, ParseVmstat) { @@ -341,15 +355,19 @@ #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) -#if defined(OS_WIN) || (defined(OS_MACOSX) && !defined(OS_IOS)) || \ - defined(OS_LINUX) || defined(OS_ANDROID) +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \ + defined(OS_ANDROID) TEST(SystemMetrics2Test, GetSystemMemoryInfo) { SystemMemoryInfoKB info; EXPECT_TRUE(GetSystemMemoryInfo(&info)); // Ensure each field received a value. EXPECT_GT(info.total, 0); +#if defined(OS_WIN) + EXPECT_GT(info.avail_phys, 0); +#else EXPECT_GT(info.free, 0); +#endif #if defined(OS_LINUX) || defined(OS_ANDROID) EXPECT_GT(info.buffers, 0); EXPECT_GT(info.cached, 0); @@ -360,7 +378,9 @@ #endif // defined(OS_LINUX) || defined(OS_ANDROID) // All the values should be less than the total amount of memory. +#if !defined(OS_WIN) EXPECT_LT(info.free, info.total); +#endif #if defined(OS_LINUX) || defined(OS_ANDROID) EXPECT_LT(info.buffers, info.total); EXPECT_LT(info.cached, info.total); @@ -370,6 +390,10 @@ EXPECT_LT(info.inactive_file, info.total); #endif // defined(OS_LINUX) || defined(OS_ANDROID) +#if defined(OS_MACOSX) || defined(OS_IOS) + EXPECT_GT(info.file_backed, 0); +#endif + #if defined(OS_CHROMEOS) // Chrome OS exposes shmem. EXPECT_GT(info.shmem, 0); @@ -378,8 +402,8 @@ // and gem_size cannot be tested here. #endif } -#endif // defined(OS_WIN) || (defined(OS_MACOSX) && !defined(OS_IOS)) || - // defined(OS_LINUX) || defined(OS_ANDROID) +#endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || + // defined(OS_ANDROID) #if defined(OS_LINUX) || defined(OS_ANDROID) TEST(ProcessMetricsTest, ParseProcStatCPU) {
diff --git a/base/process/process_metrics_win.cc b/base/process/process_metrics_win.cc index 77ac5c62..2476021 100644 --- a/base/process/process_metrics_win.cc +++ b/base/process/process_metrics_win.cc
@@ -31,12 +31,6 @@ } // namespace -SystemMemoryInfoKB::SystemMemoryInfoKB() - : total(0), free(0), swap_total(0), swap_free(0) {} - -SystemMemoryInfoKB::SystemMemoryInfoKB(const SystemMemoryInfoKB& other) = - default; - ProcessMetrics::~ProcessMetrics() { } // static @@ -349,7 +343,7 @@ // This function uses the following mapping between MEMORYSTATUSEX and // SystemMemoryInfoKB: // ullTotalPhys ==> total -// ullAvailPhys ==> free +// ullAvailPhys ==> avail_phys // ullTotalPageFile ==> swap_total // ullAvailPageFile ==> swap_free bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) { @@ -359,7 +353,7 @@ return false; meminfo->total = mem_status.ullTotalPhys / 1024; - meminfo->free = mem_status.ullAvailPhys / 1024; + meminfo->avail_phys = mem_status.ullAvailPhys / 1024; meminfo->swap_total = mem_status.ullTotalPageFile / 1024; meminfo->swap_free = mem_status.ullAvailPageFile / 1024;
diff --git a/base/sys_info.h b/base/sys_info.h index e35feff7..ecaa731 100644 --- a/base/sys_info.h +++ b/base/sys_info.h
@@ -13,11 +13,18 @@ #include "base/base_export.h" #include "base/files/file_path.h" +#include "base/gtest_prod_util.h" #include "base/time/time.h" #include "build/build_config.h" namespace base { +namespace debug { +FORWARD_DECLARE_TEST(SystemMetricsTest, ParseMeminfo); +} + +struct SystemMemoryInfoKB; + class BASE_EXPORT SysInfo { public: // Return the number of logical processors/cores on the current machine. @@ -28,6 +35,9 @@ // Return the number of bytes of current available physical memory on the // machine. + // (The amount of memory that can be allocated without any significant + // impact on the system. It can lead to freeing inactive file-backed + // and/or speculative file-backed memory). static int64_t AmountOfAvailablePhysicalMemory(); // Return the number of bytes of virtual memory of this process. A return @@ -147,6 +157,15 @@ // Low-end device refers to devices having less than 512M memory in the // current implementation. static bool IsLowEndDevice(); + + private: + FRIEND_TEST_ALL_PREFIXES(SysInfoTest, AmountOfAvailablePhysicalMemory); + FRIEND_TEST_ALL_PREFIXES(debug::SystemMetricsTest, ParseMeminfo); + +#if defined(OS_LINUX) || defined(OS_ANDROID) + static int64_t AmountOfAvailablePhysicalMemory( + const SystemMemoryInfoKB& meminfo); +#endif }; } // namespace base
diff --git a/base/sys_info_ios.mm b/base/sys_info_ios.mm index 9a95298..9a329b9 100644 --- a/base/sys_info_ios.mm +++ b/base/sys_info_ios.mm
@@ -15,6 +15,7 @@ #include "base/mac/scoped_mach_port.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/macros.h" +#include "base/process/process_metrics.h" #include "base/strings/sys_string_conversions.h" namespace base { @@ -83,19 +84,12 @@ // static int64_t SysInfo::AmountOfAvailablePhysicalMemory() { - base::mac::ScopedMachSendRight host(mach_host_self()); - vm_statistics_data_t vm_info; - mach_msg_type_number_t count = HOST_VM_INFO_COUNT; - if (host_statistics(host.get(), - HOST_VM_INFO, - reinterpret_cast<host_info_t>(&vm_info), - &count) != KERN_SUCCESS) { - NOTREACHED(); + SystemMemoryInfoKB info; + if (!GetSystemMemoryInfo(&info)) return 0; - } - - return static_cast<int64_t>(vm_info.free_count - vm_info.speculative_count) * - PAGE_SIZE; + // We should add inactive file-backed memory also but there is no such + // information from iOS unfortunately. + return static_cast<int64_t>(info.free + info.speculative) * 1024; } // static
diff --git a/base/sys_info_linux.cc b/base/sys_info_linux.cc index 298d245..0cd05b3 100644 --- a/base/sys_info_linux.cc +++ b/base/sys_info_linux.cc
@@ -13,6 +13,7 @@ #include "base/lazy_instance.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" +#include "base/process/process_metrics.h" #include "base/strings/string_number_conversions.h" #include "base/sys_info_internal.h" #include "build/build_config.h" @@ -42,13 +43,29 @@ namespace base { // static -int64_t SysInfo::AmountOfAvailablePhysicalMemory() { - return AmountOfMemory(_SC_AVPHYS_PAGES); +int64_t SysInfo::AmountOfPhysicalMemory() { + return g_lazy_physical_memory.Get().value(); } // static -int64_t SysInfo::AmountOfPhysicalMemory() { - return g_lazy_physical_memory.Get().value(); +int64_t SysInfo::AmountOfAvailablePhysicalMemory() { + SystemMemoryInfoKB info; + if (!GetSystemMemoryInfo(&info)) + return 0; + return AmountOfAvailablePhysicalMemory(info); +} + +// static +int64_t SysInfo::AmountOfAvailablePhysicalMemory( + const SystemMemoryInfoKB& info) { + // See details here: + // https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 + // The fallback logic (when there is no MemAvailable) would be more precise + // if we had info about zones watermarks (/proc/zoneinfo). + int64_t res_kb = info.available != 0 + ? info.available - info.active_file + : info.free + info.reclaimable + info.inactive_file; + return res_kb * 1024; } // static
diff --git a/base/sys_info_mac.mm b/base/sys_info_mac.mm index aab1103..1141bd55 100644 --- a/base/sys_info_mac.mm +++ b/base/sys_info_mac.mm
@@ -19,6 +19,7 @@ #include "base/mac/scoped_mach_port.h" #import "base/mac/sdk_forward_declarations.h" #include "base/macros.h" +#include "base/process/process_metrics.h" #include "base/strings/stringprintf.h" namespace base { @@ -83,20 +84,12 @@ // static int64_t SysInfo::AmountOfAvailablePhysicalMemory() { - base::mac::ScopedMachSendRight host(mach_host_self()); - vm_statistics_data_t vm_info; - mach_msg_type_number_t count = HOST_VM_INFO_COUNT; - - if (host_statistics(host.get(), - HOST_VM_INFO, - reinterpret_cast<host_info_t>(&vm_info), - &count) != KERN_SUCCESS) { - NOTREACHED(); + SystemMemoryInfoKB info; + if (!GetSystemMemoryInfo(&info)) return 0; - } - - return static_cast<int64_t>(vm_info.free_count - vm_info.speculative_count) * - PAGE_SIZE; + // We should add inactive file-backed memory also but there is no such + // information from Mac OS unfortunately. + return static_cast<int64_t>(info.free + info.speculative) * 1024; } // static
diff --git a/base/sys_info_openbsd.cc b/base/sys_info_openbsd.cc index 531c117..9c98784 100644 --- a/base/sys_info_openbsd.cc +++ b/base/sys_info_openbsd.cc
@@ -48,6 +48,8 @@ // static int64_t SysInfo::AmountOfAvailablePhysicalMemory() { + // We should add inactive file-backed memory also but there is no such + // information from OpenBSD unfortunately. return AmountOfMemory(_SC_AVPHYS_PAGES); }
diff --git a/base/sys_info_unittest.cc b/base/sys_info_unittest.cc index c3b8507..e80884b9 100644 --- a/base/sys_info_unittest.cc +++ b/base/sys_info_unittest.cc
@@ -6,6 +6,7 @@ #include "base/environment.h" #include "base/files/file_util.h" +#include "base/process/process_metrics.h" #include "base/sys_info.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" @@ -13,36 +14,61 @@ #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" -typedef PlatformTest SysInfoTest; -using base::FilePath; +namespace base { + +using SysInfoTest = PlatformTest; TEST_F(SysInfoTest, NumProcs) { // We aren't actually testing that it's correct, just that it's sane. - EXPECT_GE(base::SysInfo::NumberOfProcessors(), 1); + EXPECT_GE(SysInfo::NumberOfProcessors(), 1); } TEST_F(SysInfoTest, AmountOfMem) { // We aren't actually testing that it's correct, just that it's sane. - EXPECT_GT(base::SysInfo::AmountOfPhysicalMemory(), 0); - EXPECT_GT(base::SysInfo::AmountOfPhysicalMemoryMB(), 0); + EXPECT_GT(SysInfo::AmountOfPhysicalMemory(), 0); + EXPECT_GT(SysInfo::AmountOfPhysicalMemoryMB(), 0); // The maxmimal amount of virtual memory can be zero which means unlimited. - EXPECT_GE(base::SysInfo::AmountOfVirtualMemory(), 0); + EXPECT_GE(SysInfo::AmountOfVirtualMemory(), 0); } +#if defined(OS_LINUX) || defined(OS_ANDROID) +TEST_F(SysInfoTest, AmountOfAvailablePhysicalMemory) { + // Note: info is in _K_bytes. + SystemMemoryInfoKB info; + ASSERT_TRUE(GetSystemMemoryInfo(&info)); + EXPECT_GT(info.free, 0); + + if (info.available != 0) { + // If there is MemAvailable from kernel. + EXPECT_LT(info.available, info.total); + const int64_t amount = SysInfo::AmountOfAvailablePhysicalMemory(info); + // We aren't actually testing that it's correct, just that it's sane. + EXPECT_GT(amount, static_cast<int64_t>(info.free) * 1024); + EXPECT_LT(amount / 1024, info.available); + // Simulate as if there is no MemAvailable. + info.available = 0; + } + + // There is no MemAvailable. Check the fallback logic. + const int64_t amount = SysInfo::AmountOfAvailablePhysicalMemory(info); + // We aren't actually testing that it's correct, just that it's sane. + EXPECT_GT(amount, static_cast<int64_t>(info.free) * 1024); + EXPECT_LT(amount / 1024, info.total); +} +#endif // defined(OS_LINUX) || defined(OS_ANDROID) + TEST_F(SysInfoTest, AmountOfFreeDiskSpace) { // We aren't actually testing that it's correct, just that it's sane. FilePath tmp_path; - ASSERT_TRUE(base::GetTempDir(&tmp_path)); - EXPECT_GE(base::SysInfo::AmountOfFreeDiskSpace(tmp_path), 0) - << tmp_path.value(); + ASSERT_TRUE(GetTempDir(&tmp_path)); + EXPECT_GE(SysInfo::AmountOfFreeDiskSpace(tmp_path), 0) << tmp_path.value(); } TEST_F(SysInfoTest, AmountOfTotalDiskSpace) { // We aren't actually testing that it's correct, just that it's sane. FilePath tmp_path; - ASSERT_TRUE(base::GetTempDir(&tmp_path)); - EXPECT_GT(base::SysInfo::AmountOfTotalDiskSpace(tmp_path), 0) - << tmp_path.value(); + ASSERT_TRUE(GetTempDir(&tmp_path)); + EXPECT_GT(SysInfo::AmountOfTotalDiskSpace(tmp_path), 0) << tmp_path.value(); } #if defined(OS_WIN) || defined(OS_MACOSX) @@ -50,9 +76,9 @@ int32_t os_major_version = -1; int32_t os_minor_version = -1; int32_t os_bugfix_version = -1; - base::SysInfo::OperatingSystemVersionNumbers(&os_major_version, - &os_minor_version, - &os_bugfix_version); + SysInfo::OperatingSystemVersionNumbers(&os_major_version, + &os_minor_version, + &os_bugfix_version); EXPECT_GT(os_major_version, -1); EXPECT_GT(os_minor_version, -1); EXPECT_GT(os_bugfix_version, -1); @@ -60,18 +86,18 @@ #endif TEST_F(SysInfoTest, Uptime) { - base::TimeDelta up_time_1 = base::SysInfo::Uptime(); + TimeDelta up_time_1 = SysInfo::Uptime(); // UpTime() is implemented internally using TimeTicks::Now(), which documents // system resolution as being 1-15ms. Sleep a little longer than that. - base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(20)); - base::TimeDelta up_time_2 = base::SysInfo::Uptime(); + PlatformThread::Sleep(TimeDelta::FromMilliseconds(20)); + TimeDelta up_time_2 = SysInfo::Uptime(); EXPECT_GT(up_time_1.InMicroseconds(), 0); EXPECT_GT(up_time_2.InMicroseconds(), up_time_1.InMicroseconds()); } #if defined(OS_MACOSX) && !defined(OS_IOS) TEST_F(SysInfoTest, HardwareModelName) { - std::string hardware_model = base::SysInfo::HardwareModelName(); + std::string hardware_model = SysInfo::HardwareModelName(); EXPECT_FALSE(hardware_model.empty()); } #endif @@ -85,10 +111,10 @@ const char kLsbRelease[] = "FOO=1234123.34.5\n" "CHROMEOS_RELEASE_VERSION=1.2.3.4\n"; - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, base::Time()); - base::SysInfo::OperatingSystemVersionNumbers(&os_major_version, - &os_minor_version, - &os_bugfix_version); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, Time()); + SysInfo::OperatingSystemVersionNumbers(&os_major_version, + &os_minor_version, + &os_bugfix_version); EXPECT_EQ(1, os_major_version); EXPECT_EQ(2, os_minor_version); EXPECT_EQ(3, os_bugfix_version); @@ -101,10 +127,10 @@ const char kLsbRelease[] = "CHROMEOS_RELEASE_VERSION=1.2.3.4\n" "FOO=1234123.34.5\n"; - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, base::Time()); - base::SysInfo::OperatingSystemVersionNumbers(&os_major_version, - &os_minor_version, - &os_bugfix_version); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, Time()); + SysInfo::OperatingSystemVersionNumbers(&os_major_version, + &os_minor_version, + &os_bugfix_version); EXPECT_EQ(1, os_major_version); EXPECT_EQ(2, os_minor_version); EXPECT_EQ(3, os_bugfix_version); @@ -115,10 +141,10 @@ int32_t os_minor_version = -1; int32_t os_bugfix_version = -1; const char kLsbRelease[] = "FOO=1234123.34.5\n"; - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, base::Time()); - base::SysInfo::OperatingSystemVersionNumbers(&os_major_version, - &os_minor_version, - &os_bugfix_version); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, Time()); + SysInfo::OperatingSystemVersionNumbers(&os_major_version, + &os_minor_version, + &os_bugfix_version); EXPECT_EQ(0, os_major_version); EXPECT_EQ(0, os_minor_version); EXPECT_EQ(0, os_bugfix_version); @@ -127,43 +153,45 @@ TEST_F(SysInfoTest, GoogleChromeOSLsbReleaseTime) { const char kLsbRelease[] = "CHROMEOS_RELEASE_VERSION=1.2.3.4"; // Use a fake time that can be safely displayed as a string. - const base::Time lsb_release_time(base::Time::FromDoubleT(12345.6)); - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, lsb_release_time); - base::Time parsed_lsb_release_time = base::SysInfo::GetLsbReleaseTime(); + const Time lsb_release_time(Time::FromDoubleT(12345.6)); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, lsb_release_time); + Time parsed_lsb_release_time = SysInfo::GetLsbReleaseTime(); EXPECT_DOUBLE_EQ(lsb_release_time.ToDoubleT(), parsed_lsb_release_time.ToDoubleT()); } TEST_F(SysInfoTest, IsRunningOnChromeOS) { - base::SysInfo::SetChromeOSVersionInfoForTest("", base::Time()); - EXPECT_FALSE(base::SysInfo::IsRunningOnChromeOS()); + SysInfo::SetChromeOSVersionInfoForTest("", Time()); + EXPECT_FALSE(SysInfo::IsRunningOnChromeOS()); const char kLsbRelease1[] = "CHROMEOS_RELEASE_NAME=Non Chrome OS\n" "CHROMEOS_RELEASE_VERSION=1.2.3.4\n"; - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease1, base::Time()); - EXPECT_FALSE(base::SysInfo::IsRunningOnChromeOS()); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease1, Time()); + EXPECT_FALSE(SysInfo::IsRunningOnChromeOS()); const char kLsbRelease2[] = "CHROMEOS_RELEASE_NAME=Chrome OS\n" "CHROMEOS_RELEASE_VERSION=1.2.3.4\n"; - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease2, base::Time()); - EXPECT_TRUE(base::SysInfo::IsRunningOnChromeOS()); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease2, Time()); + EXPECT_TRUE(SysInfo::IsRunningOnChromeOS()); const char kLsbRelease3[] = "CHROMEOS_RELEASE_NAME=Chromium OS\n"; - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease3, base::Time()); - EXPECT_TRUE(base::SysInfo::IsRunningOnChromeOS()); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease3, Time()); + EXPECT_TRUE(SysInfo::IsRunningOnChromeOS()); } TEST_F(SysInfoTest, GetStrippedReleaseBoard) { const char* kLsbRelease1 = "CHROMEOS_RELEASE_BOARD=Glimmer\n"; - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease1, base::Time()); - EXPECT_EQ("glimmer", base::SysInfo::GetStrippedReleaseBoard()); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease1, Time()); + EXPECT_EQ("glimmer", SysInfo::GetStrippedReleaseBoard()); const char* kLsbRelease2 = "CHROMEOS_RELEASE_BOARD=glimmer-signed-mp-v4keys"; - base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease2, base::Time()); - EXPECT_EQ("glimmer", base::SysInfo::GetStrippedReleaseBoard()); + SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease2, Time()); + EXPECT_EQ("glimmer", SysInfo::GetStrippedReleaseBoard()); } #endif // OS_CHROMEOS + +} // namespace base
diff --git a/base/sys_info_win.cc b/base/sys_info_win.cc index cb184ba..d1c485c 100644 --- a/base/sys_info_win.cc +++ b/base/sys_info_win.cc
@@ -12,6 +12,7 @@ #include "base/files/file_path.h" #include "base/logging.h" +#include "base/process/process_metrics.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_restrictions.h" #include "base/win/windows_version.h" @@ -68,7 +69,10 @@ // static int64_t SysInfo::AmountOfAvailablePhysicalMemory() { - return AmountOfMemory(&MEMORYSTATUSEX::ullAvailPhys); + SystemMemoryInfoKB info; + if (!GetSystemMemoryInfo(&info)) + return 0; + return static_cast<int64_t>(info.avail_phys) * 1024; } // static
diff --git a/cc/paint/paint_canvas.h b/cc/paint/paint_canvas.h index 2d80e930..670fd22 100644 --- a/cc/paint/paint_canvas.h +++ b/cc/paint/paint_canvas.h
@@ -7,6 +7,7 @@ #include "base/compiler_specific.h" #include "base/macros.h" +#include "base/memory/ref_counted.h" #include "build/build_config.h" #include "cc/paint/paint_export.h" #include "cc/paint/paint_record.h" @@ -166,8 +167,7 @@ const PaintFlags& flags) = 0; virtual void drawDisplayItemList( - const SkRect& bounds, - const DisplayItemList* display_item_list) = 0; + scoped_refptr<DisplayItemList> display_item_list) = 0; virtual void drawPicture(sk_sp<const PaintRecord> record, const SkMatrix* matrix,
diff --git a/cc/paint/skia_paint_canvas.cc b/cc/paint/skia_paint_canvas.cc index fa90ec0..41ff72367 100644 --- a/cc/paint/skia_paint_canvas.cc +++ b/cc/paint/skia_paint_canvas.cc
@@ -267,12 +267,8 @@ } void SkiaPaintCanvas::drawDisplayItemList( - const SkRect& bounds, - const DisplayItemList* display_item_list) { - SkPictureRecorder recorder; - SkCanvas* canvas = recorder.beginRecording(bounds); - display_item_list->Raster(canvas, nullptr); - canvas_->drawPicture(recorder.finishRecordingAsPicture()); + scoped_refptr<DisplayItemList> display_item_list) { + display_item_list->Raster(canvas_, nullptr); } void SkiaPaintCanvas::drawPicture(sk_sp<const PaintRecord> record,
diff --git a/cc/paint/skia_paint_canvas.h b/cc/paint/skia_paint_canvas.h index 8dbcc83b..b85badfd 100644 --- a/cc/paint/skia_paint_canvas.h +++ b/cc/paint/skia_paint_canvas.h
@@ -130,8 +130,8 @@ SkScalar y, const PaintFlags& flags) override; - void drawDisplayItemList(const SkRect& bounds, - const DisplayItemList*) override; + void drawDisplayItemList( + scoped_refptr<DisplayItemList> display_item_list) override; void drawPicture(sk_sp<const PaintRecord> record, const SkMatrix* matrix,
diff --git a/chrome/VERSION b/chrome/VERSION index a71060e..3ee38faa 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=59 MINOR=0 -BUILD=3048 +BUILD=3049 PATCH=0
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index d7a4076..0cede831 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -6092,12 +6092,6 @@ <message name="IDS_FLAGS_PUSH_API_BACKGROUND_MODE_DESCRIPTION" desc="Description for the flag to enable background mode for the Push API." translateable="false"> Enable background mode for the Push API. This allows Chrome to continue running after the last window is closed, and to launch at OS startup, if the Push API needs it. </message> - <message name="IDS_FLAGS_ENABLE_STALE_WHILE_REVALIDATE_NAME" desc="Name of the flag to enable the "stale-while-revalidate" cache directive. This message is intended for web developers who are familiar with technical terms. "stale-while-revalidate" here is the literal string sent by the HTTP server, and so should be untranslated where possible. "cache" here refers to an HTTP cache. "directive" here is an instruction sent by an HTTP server to indicate what caching behaviour should be used." translateable="false"> - Enable the "stale-while-revalidate" cache directive - </message> - <message name="IDS_FLAGS_ENABLE_STALE_WHILE_REVALIDATE_DESCRIPTION" desc="Description of the flag to enable the "stale-while-revalidate" cache directive. This message is intended for web developers who are familiar with technical terms. "Cache-Control: stale-while-revalidate" is the literal string sent by the HTTP server, and so should be untranslated where possible. If necessary for translation it can be split into the HTTP header name part "Cache-Control" and the value part "stale-while-revalidate". "directive" here is an instruction sent by an HTTP server to indicate what caching behaviour should be used. The directive is typically configured by the server administrator. "servers" here refers to HTTP server software. "resources" here means individual files served by HTTP servers and cached by the browser. "be revalidated" means "be checked with the HTTP server whether or not the browser has the latest version". "in the background" here means without making the user wait. "latency" here refers to the time the user waits for a web page to be loaded or become usable." translateable="false"> - Enable the experimental implementation of the "Cache-Control: stale-while-revalidate" directive. This permits servers to specify that some resources may be revalidated in the background to improve latency. - </message> <message name="IDS_FLAGS_ENABLE_NAVIGATION_TRACING" desc="Name of the flag to enable navigation tracing" translateable="false"> Enable navigation tracing </message>
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index bebb2998..1410962 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -1192,10 +1192,6 @@ {"trace-upload-url", IDS_FLAGS_TRACE_UPLOAD_URL, IDS_FLAGS_TRACE_UPLOAD_URL_DESCRIPTION, kOsAll, MULTI_VALUE_TYPE(kTraceUploadURL)}, - {"enable-stale-while-revalidate", - IDS_FLAGS_ENABLE_STALE_WHILE_REVALIDATE_NAME, - IDS_FLAGS_ENABLE_STALE_WHILE_REVALIDATE_DESCRIPTION, kOsAll, - FEATURE_VALUE_TYPE(features::kStaleWhileRevalidate)}, {"enable-service-worker-navigation-preload", IDS_FLAGS_SERVICE_WORKER_NAVIGATION_PRELOAD_NAME, IDS_FLAGS_SERVICE_WORKER_NAVIGATION_PRELOAD_DESCRIPTION, kOsAll,
diff --git a/chrome/browser/ui/cocoa/page_info/website_settings_bubble_controller_unittest.mm b/chrome/browser/ui/cocoa/page_info/website_settings_bubble_controller_unittest.mm index 45795a1..ee3762a3 100644 --- a/chrome/browser/ui/cocoa/page_info/website_settings_bubble_controller_unittest.mm +++ b/chrome/browser/ui/cocoa/page_info/website_settings_bubble_controller_unittest.mm
@@ -213,6 +213,7 @@ // Set identity info, specifying that the button should be shown. info.certificate = net::X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(google_der), sizeof(google_der)); + ASSERT_TRUE(info.certificate); info.show_ssl_decision_revoke_button = true; bridge_->SetIdentityInfo(const_cast<WebsiteSettingsUI::IdentityInfo&>(info)); EXPECT_NE([controller_ resetDecisionsButton], nil);
diff --git a/chrome/browser/ui/page_info/website_settings_unittest.cc b/chrome/browser/ui/page_info/website_settings_unittest.cc index 2331dcb..efcb7a6 100644 --- a/chrome/browser/ui/page_info/website_settings_unittest.cc +++ b/chrome/browser/ui/page_info/website_settings_unittest.cc
@@ -505,6 +505,7 @@ scoped_refptr<net::X509Certificate> ev_cert = net::X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(google_der), sizeof(google_der)); + ASSERT_TRUE(ev_cert); security_info_.security_level = security_state::NONE; security_info_.scheme_is_cryptographic = true;
diff --git a/chrome/browser/ui/webui/about_ui.cc b/chrome/browser/ui/webui/about_ui.cc index e2389f1..707b769 100644 --- a/chrome/browser/ui/webui/about_ui.cc +++ b/chrome/browser/ui/webui/about_ui.cc
@@ -30,6 +30,7 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "base/sys_info.h" #include "base/task_scheduler/post_task.h" #include "base/threading/thread.h" #include "base/values.h" @@ -552,7 +553,9 @@ output.append(AddStringRow( "Total", base::IntToString(meminfo.total / 1024))); output.append(AddStringRow( - "Free", base::IntToString(meminfo.free / 1024))); + "Free", + base::IntToString(base::SysInfo::AmountOfAvailablePhysicalMemory() / + 1024 / 1024))); #if defined(OS_CHROMEOS) int mem_allocated_kb = meminfo.active_anon + meminfo.inactive_anon; #if defined(ARCH_CPU_ARM_FAMILY)
diff --git a/chrome/common/safe_browsing/binary_feature_extractor_win_unittest.cc b/chrome/common/safe_browsing/binary_feature_extractor_win_unittest.cc index c4a6d914..63974925 100644 --- a/chrome/common/safe_browsing/binary_feature_extractor_win_unittest.cc +++ b/chrome/common/safe_browsing/binary_feature_extractor_win_unittest.cc
@@ -36,10 +36,12 @@ const ClientDownloadRequest_CertificateChain& chain, std::vector<scoped_refptr<net::X509Certificate> >* certs) { for (int i = 0; i < chain.element_size(); ++i) { - certs->push_back( + scoped_refptr<net::X509Certificate> cert = net::X509Certificate::CreateFromBytes( chain.element(i).certificate().data(), - chain.element(i).certificate().size())); + chain.element(i).certificate().size()); + if (cert) + certs->push_back(cert); } }
diff --git a/chrome/test/data/webui/certificate_viewer_ui_test-inl.h b/chrome/test/data/webui/certificate_viewer_ui_test-inl.h index 10b9417f..684b8838 100644 --- a/chrome/test/data/webui/certificate_viewer_ui_test-inl.h +++ b/chrome/test/data/webui/certificate_viewer_ui_test-inl.h
@@ -42,6 +42,7 @@ scoped_refptr<net::X509Certificate> google_cert( net::X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(google_der), sizeof(google_der))); + ASSERT_TRUE(google_cert); ASSERT_TRUE(browser()); ASSERT_TRUE(browser()->window()); @@ -64,6 +65,7 @@ scoped_refptr<net::X509Certificate> google_cert( net::X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(google_der), sizeof(google_der))); + ASSERT_TRUE(google_cert); ASSERT_TRUE(browser()); ASSERT_TRUE(browser()->window());
diff --git a/chrome/test/data/webui/settings/site_list_tests.js b/chrome/test/data/webui/settings/site_list_tests.js index 87d1b71..1cf8636 100644 --- a/chrome/test/data/webui/settings/site_list_tests.js +++ b/chrome/test/data/webui/settings/site_list_tests.js
@@ -437,6 +437,25 @@ testElement.category = category; } + test('read-only attribute', function() { + setUpCategory( + settings.ContentSettingsTypes.GEOLOCATION, + settings.PermissionValues.ALLOW, prefsVarious); + return browserProxy.whenCalled('getExceptionList') + .then(function(contentType) { + // Flush to be sure list container is populated. + Polymer.dom.flush(); + var dotsMenu = testElement.$.listContainer.querySelector('#dots'); + assertFalse(dotsMenu.hidden); + testElement.setAttribute('read-only-list', true); + Polymer.dom.flush(); + assertTrue(dotsMenu.hidden); + testElement.removeAttribute('read-only-list'); + Polymer.dom.flush(); + assertFalse(dotsMenu.hidden); + }); + }); + test('getExceptionList API used', function() { setUpCategory(settings.ContentSettingsTypes.GEOLOCATION, settings.PermissionValues.ALLOW, prefsEmpty);
diff --git a/chromeos/network/onc/onc_certificate_importer_impl_unittest.cc b/chromeos/network/onc/onc_certificate_importer_impl_unittest.cc index b8e1b0eb..7e2874f 100644 --- a/chromeos/network/onc/onc_certificate_importer_impl_unittest.cc +++ b/chromeos/network/onc/onc_certificate_importer_impl_unittest.cc
@@ -177,8 +177,14 @@ for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list); !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) { - result.push_back(net::X509Certificate::CreateFromHandle( - node->cert, net::X509Certificate::OSCertHandles())); + scoped_refptr<net::X509Certificate> cert = + net::X509Certificate::CreateFromHandle( + node->cert, net::X509Certificate::OSCertHandles()); + if (!cert) { + ADD_FAILURE() << "X509Certificate::CreateFromHandle failed"; + continue; + } + result.push_back(cert); } CERT_DestroyCertList(cert_list);
diff --git a/components/exo/shell_surface.cc b/components/exo/shell_surface.cc index 7016042..38cb702 100644 --- a/components/exo/shell_surface.cc +++ b/components/exo/shell_surface.cc
@@ -1619,14 +1619,16 @@ widget_->IsActive(); float shadow_underlay_opacity = shadow_background_opacity_; + // Put the black background layer behind the window if - // 1) the window is in immersive fullscreen or is active with + // 1) the window is in immersive fullscreen, maximized or is active with // spoken feedback enabled. // 2) the window can control the bounds of the window in fullscreen ( // thus the background can be visible). // 3) the window has no transform (the transformed background may // not cover the entire background, e.g. overview mode). - if ((widget_->IsFullscreen() || underlay_capture_events) && + if ((widget_->IsFullscreen() || widget_->IsMaximized() || + underlay_capture_events) && ash::wm::GetWindowState(window)->allow_set_bounds_in_maximized() && window->layer()->GetTargetTransform().IsIdentity()) { if (shadow_underlay_in_surface_) {
diff --git a/components/exo/shell_surface_unittest.cc b/components/exo/shell_surface_unittest.cc index a7d018e..bc2f48b 100644 --- a/components/exo/shell_surface_unittest.cc +++ b/components/exo/shell_surface_unittest.cc
@@ -854,7 +854,7 @@ shell_surface->GetWidget()->GetWindowBoundsInScreen().width()); } -TEST_F(ShellSurfaceTest, ImmersiveFullscreenBackground) { +TEST_F(ShellSurfaceTest, MaximizedAndImmersiveFullscreenBackground) { const gfx::Size display_size = display::Screen::GetScreen()->GetPrimaryDisplay().size(); const gfx::Size buffer_size(display_size); @@ -877,12 +877,12 @@ EXPECT_EQ(display::Screen::GetScreen()->GetPrimaryDisplay().size(), shell_surface->surface_for_testing()->window()->bounds().size()); - ash::wm::WMEvent event(ash::wm::WM_EVENT_TOGGLE_FULLSCREEN); + ash::wm::WMEvent fullscreen_event(ash::wm::WM_EVENT_TOGGLE_FULLSCREEN); ash::WmWindow* window = ash::WmWindow::Get(shell_surface->GetWidget()->GetNativeWindow()); // Enter immersive fullscreen mode. Shadow underlay is fullscreen. - window->GetWindowState()->OnWMEvent(&event); + window->GetWindowState()->OnWMEvent(&fullscreen_event); EXPECT_TRUE(shell_surface->shadow_underlay()->IsVisible()); EXPECT_EQ(1.f, shell_surface->shadow_underlay()->layer()->opacity()); @@ -890,9 +890,24 @@ shell_surface->shadow_underlay()->bounds().size()); // Leave fullscreen mode. Shadow underlay is restored. - window->GetWindowState()->OnWMEvent(&event); + window->GetWindowState()->OnWMEvent(&fullscreen_event); EXPECT_TRUE(shell_surface->shadow_underlay()->IsVisible()); EXPECT_EQ(shadow_bounds, shell_surface->shadow_underlay()->bounds()); + + ash::wm::WMEvent maximize_event(ash::wm::WM_EVENT_TOGGLE_MAXIMIZE); + + // Enter maximized mode. Shadow underlay is fullscreen. + window->GetWindowState()->OnWMEvent(&maximize_event); + EXPECT_TRUE(shell_surface->shadow_underlay()->IsVisible()); + EXPECT_EQ(1.f, shell_surface->shadow_underlay()->layer()->opacity()); + EXPECT_EQ(display::Screen::GetScreen()->GetPrimaryDisplay().size(), + shell_surface->shadow_underlay()->bounds().size()); + + // Leave maximized mode. Shadow underlay is fullscreen. + window->GetWindowState()->OnWMEvent(&maximize_event); + EXPECT_TRUE(shell_surface->shadow_underlay()->IsVisible()); + EXPECT_EQ(1.f, shell_surface->shadow_underlay()->layer()->opacity()); + EXPECT_EQ(shadow_bounds, shell_surface->shadow_underlay()->bounds()); } TEST_F(ShellSurfaceTest, SpokenFeedbackFullscreenBackground) {
diff --git a/components/memory_pressure/direct_memory_pressure_calculator_win.cc b/components/memory_pressure/direct_memory_pressure_calculator_win.cc index f393b7c..48ae41e 100644 --- a/components/memory_pressure/direct_memory_pressure_calculator_win.cc +++ b/components/memory_pressure/direct_memory_pressure_calculator_win.cc
@@ -65,7 +65,7 @@ return MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE; // How much system memory is actively available for use right now, in MBs. - int phys_free = mem_info.free / kKBperMB; + int phys_free = mem_info.avail_phys / kKBperMB; // TODO(chrisha): This should eventually care about address space pressure, // but the browser process (where this is running) effectively never runs out
diff --git a/components/memory_pressure/direct_memory_pressure_calculator_win_unittest.cc b/components/memory_pressure/direct_memory_pressure_calculator_win_unittest.cc index c7c48e6..a8f0ec5 100644 --- a/components/memory_pressure/direct_memory_pressure_calculator_win_unittest.cc +++ b/components/memory_pressure/direct_memory_pressure_calculator_win_unittest.cc
@@ -59,8 +59,8 @@ // |total| is set in the constructor and not modified. // Set the amount of free memory. - mem_info_.free = phys_left_mb * kKBperMB; - DCHECK_LT(mem_info_.free, mem_info_.total); + mem_info_.avail_phys = phys_left_mb * kKBperMB; + DCHECK_LT(mem_info_.avail_phys, mem_info_.total); } void SetNone() { SetMemoryFree(moderate_threshold_mb() + 1); }
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index f5cd706..ffc33b3 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -264,6 +264,8 @@ "android/content_video_view.cc", "android/content_video_view.h", "android/devtools_auth.cc", + "android/gpu_process_callback.cc", + "android/gpu_process_callback.h", "android/java_interfaces_impl.cc", "android/java_interfaces_impl.h", "android/scoped_surface_request_manager.cc", @@ -807,10 +809,6 @@ "leveldb_wrapper_impl.h", "loader/async_resource_handler.cc", "loader/async_resource_handler.h", - "loader/async_revalidation_driver.cc", - "loader/async_revalidation_driver.h", - "loader/async_revalidation_manager.cc", - "loader/async_revalidation_manager.h", "loader/detachable_resource_handler.cc", "loader/detachable_resource_handler.h", "loader/downloaded_temp_file_impl.cc",
diff --git a/content/browser/android/browser_jni_registrar.cc b/content/browser/android/browser_jni_registrar.cc index eb98ed7..2f02cd0 100644 --- a/content/browser/android/browser_jni_registrar.cc +++ b/content/browser/android/browser_jni_registrar.cc
@@ -18,6 +18,7 @@ #include "content/browser/android/content_view_render_view.h" #include "content/browser/android/content_view_statics.h" #include "content/browser/android/date_time_chooser_android.h" +#include "content/browser/android/gpu_process_callback.h" #include "content/browser/android/interstitial_page_delegate_android.h" #include "content/browser/android/joystick_scroll_provider.h" #include "content/browser/android/load_url_params.h" @@ -44,6 +45,7 @@ {"ContentFeatureList", content::android::RegisterContentFeatureListJni}, {"ContentVideoView", content::ContentVideoView::RegisterContentVideoView}, {"CoreImpl", mojo::android::RegisterCoreImpl}, + {"GpuProcessCallback", content::RegisterGpuProcessCallback}, {"MemoryMonitorAndroid", content::MemoryMonitorAndroid::Register}, {"BackgroundSyncNetworkObserverAndroid", content::BackgroundSyncNetworkObserverAndroid::Observer::
diff --git a/content/browser/android/gpu_process_callback.cc b/content/browser/android/gpu_process_callback.cc new file mode 100644 index 0000000..23ca55a --- /dev/null +++ b/content/browser/android/gpu_process_callback.cc
@@ -0,0 +1,51 @@ +// 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 "content/browser/android/gpu_process_callback.h" + +#include "base/android/scoped_java_ref.h" +#include "base/android/unguessable_token_android.h" +#include "content/browser/android/scoped_surface_request_manager.h" +#include "content/public/browser/browser_thread.h" +#include "gpu/ipc/common/gpu_surface_tracker.h" + +#include "jni/GpuProcessCallback_jni.h" + +namespace content { + +void CompleteScopedSurfaceRequest( + JNIEnv* env, + const base::android::JavaParamRef<jclass>& clazz, + const base::android::JavaParamRef<jobject>& token, + const base::android::JavaParamRef<jobject>& surface) { + base::UnguessableToken requestToken = + base::android::UnguessableTokenAndroid::FromJavaUnguessableToken(env, + token); + if (!requestToken) { + DLOG(ERROR) << "Received invalid surface request token."; + return; + } + + DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); + + base::android::ScopedJavaGlobalRef<jobject> jsurface; + jsurface.Reset(env, surface); + ScopedSurfaceRequestManager::GetInstance()->FulfillScopedSurfaceRequest( + requestToken, gl::ScopedJavaSurface(jsurface)); +} + +base::android::ScopedJavaLocalRef<jobject> GetViewSurface( + JNIEnv* env, + const base::android::JavaParamRef<jclass>& jcaller, + jint surface_id) { + gl::ScopedJavaSurface surface_view = + gpu::GpuSurfaceTracker::GetInstance()->AcquireJavaSurface(surface_id); + return base::android::ScopedJavaLocalRef<jobject>(surface_view.j_surface()); +} + +bool RegisterGpuProcessCallback(JNIEnv* env) { + return RegisterNativesImpl(env); +} + +} // namespace content
diff --git a/content/browser/android/gpu_process_callback.h b/content/browser/android/gpu_process_callback.h new file mode 100644 index 0000000..e113a33 --- /dev/null +++ b/content/browser/android/gpu_process_callback.h
@@ -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. + +#ifndef CONTENT_BROWSER_ANDROID_GPU_PROCESS_CALLBACK_H_ +#define CONTENT_BROWSER_ANDROID_GPU_PROCESS_CALLBACK_H_ + +#include <jni.h> + +namespace content { + +bool RegisterGpuProcessCallback(JNIEnv* env); + +} // namespace content + +#endif // CONTENT_BROWSER_ANDROID_GPU_PROCESS_CALLBACK_H_
diff --git a/content/browser/child_process_launcher_helper_android.cc b/content/browser/child_process_launcher_helper_android.cc index d46d1cf9..233b2ef 100644 --- a/content/browser/child_process_launcher_helper_android.cc +++ b/content/browser/child_process_launcher_helper_android.cc
@@ -9,11 +9,9 @@ #include "base/android/apk_assets.h" #include "base/android/context_utils.h" #include "base/android/jni_array.h" -#include "base/android/unguessable_token_android.h" #include "base/i18n/icu_util.h" #include "base/logging.h" #include "base/metrics/field_trial.h" -#include "content/browser/android/scoped_surface_request_manager.h" #include "content/browser/child_process_launcher_helper.h" #include "content/browser/child_process_launcher_helper_posix.h" #include "content/browser/file_descriptor_info_impl.h" @@ -23,7 +21,6 @@ #include "content/public/common/content_descriptors.h" #include "content/public/common/content_switches.h" #include "gin/v8_initializer.h" -#include "gpu/ipc/common/gpu_surface_tracker.h" #include "jni/ChildProcessLauncher_jni.h" using base::android::AttachCurrentThread; @@ -284,40 +281,11 @@ delete callback; } -void CompleteScopedSurfaceRequest(JNIEnv* env, - const JavaParamRef<jclass>& clazz, - const JavaParamRef<jobject>& token, - const JavaParamRef<jobject>& surface) { - base::UnguessableToken requestToken = - base::android::UnguessableTokenAndroid::FromJavaUnguessableToken(env, - token); - if (!requestToken) { - DLOG(ERROR) << "Received invalid surface request token."; - return; - } - - DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); - - ScopedJavaGlobalRef<jobject> jsurface; - jsurface.Reset(env, surface); - ScopedSurfaceRequestManager::GetInstance()->FulfillScopedSurfaceRequest( - requestToken, gl::ScopedJavaSurface(jsurface)); -} - jboolean IsSingleProcess(JNIEnv* env, const JavaParamRef<jclass>& clazz) { return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSingleProcess); } -base::android::ScopedJavaLocalRef<jobject> GetViewSurface( - JNIEnv* env, - const base::android::JavaParamRef<jclass>& jcaller, - jint surface_id) { - gl::ScopedJavaSurface surface_view = - gpu::GpuSurfaceTracker::GetInstance()->AcquireJavaSurface(surface_id); - return base::android::ScopedJavaLocalRef<jobject>(surface_view.j_surface()); -} - bool RegisterChildProcessLauncher(JNIEnv* env) { return RegisterNativesImpl(env); }
diff --git a/content/browser/loader/DEPS b/content/browser/loader/DEPS index 33dfffd..bc73ddd 100644 --- a/content/browser/loader/DEPS +++ b/content/browser/loader/DEPS
@@ -32,36 +32,6 @@ "+content/common/resource_request_completion_status.h", "+content/common/view_messages.h", ], - "async_revalidation_driver\.(cc|h)": [ - "-content", - "+content/browser/loader/async_revalidation_driver.h", - "+content/common/content_export.h", - "+content/public/browser/resource_throttle.h", - ], - "async_revalidation_driver_unittest\.cc": [ - "-content", - "+content/browser/loader/async_revalidation_driver.h", - - # TODO: these all have to be removed. - # Only one test needs these, so that can stay in content while the other - # tests move. - "+content/public/browser/client_certificate_delegate.h", - "+content/public/common/content_client.h", - "+content/public/test/test_browser_thread_bundle.h", - "+content/test/test_content_browser_client.h", - ], - "async_revalidation_manager\.(cc|h)": [ - "-content", - "+content/browser/loader/async_revalidation_driver.h", - "+content/browser/loader/async_revalidation_manager.h", - "+content/browser/loader/resource_request_info_impl.h", - "+content/browser/loader/resource_scheduler.h", - "+content/public/browser/resource_throttle.h", - - # TODO: To be replaced by mojo. - "+content/common/resource_messages.h", - "+content/common/resource_request.h", - ], "downloaded_temp_file_impl\.(cc|h)": [ "-content", "+content/browser/loader/downloaded_temp_file_impl.h", @@ -145,7 +115,6 @@ "resource_dispatcher_host_impl\.(cc|h)": [ "-content", "+content/browser/loader/async_resource_handler.h", - "+content/browser/loader/async_revalidation_manager.h", "+content/browser/loader/global_routing_id.h", "+content/browser/loader/loader_delegate.h", "+content/browser/loader/mojo_async_resource_handler.h",
diff --git a/content/browser/loader/async_resource_handler_unittest.cc b/content/browser/loader/async_resource_handler_unittest.cc index 293ca999..7ca97f0 100644 --- a/content/browser/loader/async_resource_handler_unittest.cc +++ b/content/browser/loader/async_resource_handler_unittest.cc
@@ -189,7 +189,6 @@ false, // report_raw_headers true, // is_async PREVIEWS_OFF, // previews_state - std::string(), // original_headers nullptr, // body false); // initiated_in_secure_context info->AssociateWithRequest(request.get());
diff --git a/content/browser/loader/async_revalidation_driver.cc b/content/browser/loader/async_revalidation_driver.cc deleted file mode 100644 index 795990e..0000000 --- a/content/browser/loader/async_revalidation_driver.cc +++ /dev/null
@@ -1,264 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/loader/async_revalidation_driver.h" - -#include <utility> - -#include "base/callback_helpers.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "base/metrics/histogram_macros.h" -#include "base/metrics/sparse_histogram.h" -#include "base/single_thread_task_runner.h" -#include "base/threading/thread_task_runner_handle.h" -#include "base/time/time.h" -#include "net/base/net_errors.h" -#include "net/url_request/url_request_status.h" - -namespace content { - -namespace { -// This matches the maximum allocation size of AsyncResourceHandler. -const int kReadBufSize = 32 * 1024; - -// The time to wait for a response. Since this includes the time taken to -// connect, this has been set to match the connect timeout -// kTransportConnectJobTimeoutInSeconds. -const int kResponseTimeoutInSeconds = 240; // 4 minutes. - -// This value should not be too large, as this request may be tying up a socket -// that could be used for something better. However, if it is too small, the -// cache entry will be truncated for no good reason. -// TODO(ricea): Find a more scientific way to set this timeout. -const int kReadTimeoutInSeconds = 30; -} // namespace - -AsyncRevalidationDriver::AsyncRevalidationDriver( - std::unique_ptr<net::URLRequest> request, - std::unique_ptr<ResourceThrottle> throttle, - const base::Closure& completion_callback) - : request_(std::move(request)), - throttle_(std::move(throttle)), - completion_callback_(completion_callback), - weak_ptr_factory_(this) { - request_->set_delegate(this); - throttle_->set_delegate(this); -} - -AsyncRevalidationDriver::~AsyncRevalidationDriver() {} - -void AsyncRevalidationDriver::StartRequest() { - // Give the handler a chance to delay the URLRequest from being started. - bool defer_start = false; - throttle_->WillStartRequest(&defer_start); - - if (defer_start) { - RecordDefer(); - } else { - StartRequestInternal(); - } -} - -void AsyncRevalidationDriver::OnReceivedRedirect( - net::URLRequest* request, - const net::RedirectInfo& redirect_info, - bool* defer) { - DCHECK_EQ(request_.get(), request); - - // The async revalidation should not follow redirects, because caching is - // a property of an individual HTTP resource. - DVLOG(1) << "OnReceivedRedirect: " << request_->url().spec(); - CancelRequestInternal(net::ERR_ABORTED, RESULT_GOT_REDIRECT); -} - -void AsyncRevalidationDriver::OnAuthRequired( - net::URLRequest* request, - net::AuthChallengeInfo* auth_info) { - DCHECK_EQ(request_.get(), request); - // This error code doesn't have exactly the right semantics, but it should - // be sufficient to narrow down the problem in net logs. - CancelRequestInternal(net::ERR_ACCESS_DENIED, RESULT_AUTH_FAILED); -} - -void AsyncRevalidationDriver::OnResponseStarted(net::URLRequest* request) { - DCHECK_EQ(request_.get(), request); - - DVLOG(1) << "OnResponseStarted: " << request_->url().spec(); - - // We have the response. No need to wait any longer. - timer_.Stop(); - - if (!request_->status().is_success()) { - UMA_HISTOGRAM_SPARSE_SLOWLY("Net.AsyncRevalidation.ResponseError", - -request_->status().ToNetError()); - ResponseCompleted(RESULT_NET_ERROR); - // |this| may be deleted after this point. - return; - } - - const net::HttpResponseInfo& response_info = request_->response_info(); - if (!response_info.response_time.is_null() && response_info.was_cached) { - // The cached entry was revalidated. No need to read it in. - ResponseCompleted(RESULT_REVALIDATED); - // |this| may be deleted after this point. - return; - } - - bool defer = false; - throttle_->WillProcessResponse(&defer); - DCHECK(!defer); - - // Set up the timer for reading the body. This use of base::Unretained() is - // guaranteed safe by the semantics of base::OneShotTimer. - timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kReadTimeoutInSeconds), - base::Bind(&AsyncRevalidationDriver::OnTimeout, - base::Unretained(this), RESULT_BODY_TIMEOUT)); - StartReading(false); // Read the first chunk. -} - -void AsyncRevalidationDriver::OnReadCompleted(net::URLRequest* request, - int bytes_read) { - // request_ could be NULL if a timeout happened while OnReadCompleted() was - // queued to run asynchronously. - if (!request_) - return; - DCHECK_EQ(request_.get(), request); - DCHECK(!is_deferred_); - DVLOG(1) << "OnReadCompleted: \"" << request_->url().spec() << "\"" - << " bytes_read = " << bytes_read; - - // bytes_read == 0 is EOF. - if (bytes_read == 0) { - ResponseCompleted(RESULT_LOADED); - return; - } - // bytes_read == -1 is an error. - if (bytes_read == -1 || !request_->status().is_success()) { - UMA_HISTOGRAM_SPARSE_SLOWLY("Net.AsyncRevalidation.ReadError", - -request_->status().ToNetError()); - ResponseCompleted(RESULT_READ_ERROR); - // |this| may be deleted after this point. - return; - } - - DCHECK_GT(bytes_read, 0); - StartReading(true); // Read the next chunk. -} - -void AsyncRevalidationDriver::Resume() { - DCHECK(is_deferred_); - DCHECK(request_); - is_deferred_ = false; - request_->LogUnblocked(); - StartRequestInternal(); -} - -void AsyncRevalidationDriver::Cancel() { - NOTREACHED(); -} - -void AsyncRevalidationDriver::CancelAndIgnore() { - NOTREACHED(); -} - -void AsyncRevalidationDriver::CancelWithError(int error_code) { - NOTREACHED(); -} - -void AsyncRevalidationDriver::StartRequestInternal() { - DCHECK(request_); - DCHECK(!request_->is_pending()); - - // Start the response timer. This use of base::Unretained() is guaranteed safe - // by the semantics of base::OneShotTimer. - timer_.Start(FROM_HERE, - base::TimeDelta::FromSeconds(kResponseTimeoutInSeconds), - base::Bind(&AsyncRevalidationDriver::OnTimeout, - base::Unretained(this), RESULT_RESPONSE_TIMEOUT)); - request_->Start(); -} - -void AsyncRevalidationDriver::CancelRequestInternal( - int error, - AsyncRevalidationResult result) { - DVLOG(1) << "CancelRequestInternal: " << request_->url().spec(); - - // Set the error code since this will be reported to the NetworkDelegate and - // recorded in the NetLog. - request_->CancelWithError(error); - - // The ResourceScheduler needs to be able to examine the request when the - // ResourceThrottle is destroyed, so delete it first. - throttle_.reset(); - - // Destroy the request so that it doesn't try to send an asynchronous - // notification of completion. - request_.reset(); - - // Cancel timer to prevent OnTimeout() being called. - timer_.Stop(); - - ResponseCompleted(result); - // |this| may deleted after this point. -} - -void AsyncRevalidationDriver::StartReading(bool is_continuation) { - int bytes_read = 0; - ReadMore(&bytes_read); - - // If IO is pending, wait for the URLRequest to call OnReadCompleted. - if (request_->status().is_io_pending()) - return; - - if (!is_continuation || bytes_read <= 0) { - OnReadCompleted(request_.get(), bytes_read); - } else { - // Else, trigger OnReadCompleted asynchronously to avoid starving the IO - // thread in case the URLRequest can provide data synchronously. - scoped_refptr<base::SingleThreadTaskRunner> single_thread_task_runner = - base::ThreadTaskRunnerHandle::Get(); - single_thread_task_runner->PostTask( - FROM_HERE, - base::Bind(&AsyncRevalidationDriver::OnReadCompleted, - weak_ptr_factory_.GetWeakPtr(), request_.get(), bytes_read)); - } -} - -void AsyncRevalidationDriver::ReadMore(int* bytes_read) { - DCHECK(!is_deferred_); - - if (!read_buffer_) - read_buffer_ = new net::IOBuffer(kReadBufSize); - - timer_.Reset(); - request_->Read(read_buffer_.get(), kReadBufSize, bytes_read); - - // No need to check the return value here as we'll detect errors by - // inspecting the URLRequest's status. -} - -void AsyncRevalidationDriver::ResponseCompleted( - AsyncRevalidationResult result) { - DVLOG(1) << "ResponseCompleted: " - << (request_ ? request_->url().spec() : "(request deleted)") - << "result = " << result; - UMA_HISTOGRAM_ENUMERATION("Net.AsyncRevalidation.Result", result, RESULT_MAX); - DCHECK(!completion_callback_.is_null()); - base::ResetAndReturn(&completion_callback_).Run(); - // |this| may be deleted after this point. -} - -void AsyncRevalidationDriver::OnTimeout(AsyncRevalidationResult result) { - CancelRequestInternal(net::ERR_TIMED_OUT, result); -} - -void AsyncRevalidationDriver::RecordDefer() { - request_->LogBlockedBy(throttle_->GetNameForLogging()); - DCHECK(!is_deferred_); - is_deferred_ = true; -} - -} // namespace content
diff --git a/content/browser/loader/async_revalidation_driver.h b/content/browser/loader/async_revalidation_driver.h deleted file mode 100644 index b4a0019c..0000000 --- a/content/browser/loader/async_revalidation_driver.h +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_LOADER_ASYNC_REVALIDATION_DRIVER_H_ -#define CONTENT_BROWSER_LOADER_ASYNC_REVALIDATION_DRIVER_H_ - -#include <memory> -#include <string> - -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "base/memory/weak_ptr.h" -#include "base/timer/timer.h" -#include "content/common/content_export.h" -#include "content/public/browser/resource_throttle.h" -#include "net/base/io_buffer.h" -#include "net/url_request/url_request.h" - -namespace content { - -// This class is responsible for driving the URLRequest for an async -// revalidation. It is passed an instance of ResourceThrottle created by -// content::ResourceScheduler to perform throttling on the request. -class CONTENT_EXPORT AsyncRevalidationDriver - : public net::URLRequest::Delegate, - public ResourceThrottle::Delegate { - public: - // |completion_callback| is guaranteed to be called on completion, - // regardless of success or failure. - AsyncRevalidationDriver(std::unique_ptr<net::URLRequest> request, - std::unique_ptr<ResourceThrottle> throttle, - const base::Closure& completion_callback); - ~AsyncRevalidationDriver() override; - - void StartRequest(); - - private: - // This enum is logged as histogram "Net.AsyncRevalidation.Result". Only add - // new entries at the end and update histograms.xml to match. - enum AsyncRevalidationResult { - RESULT_LOADED, - RESULT_REVALIDATED, - RESULT_NET_ERROR, - RESULT_READ_ERROR, - RESULT_GOT_REDIRECT, - RESULT_AUTH_FAILED, - RESULT_RESPONSE_TIMEOUT, - RESULT_BODY_TIMEOUT, - RESULT_MAX - }; - - // net::URLRequest::Delegate implementation: - void OnReceivedRedirect(net::URLRequest* request, - const net::RedirectInfo& redirect_info, - bool* defer) override; - void OnAuthRequired(net::URLRequest* request, - net::AuthChallengeInfo* info) override; - void OnResponseStarted(net::URLRequest* request) override; - void OnReadCompleted(net::URLRequest* request, int bytes_read) override; - - // ResourceThrottle::Delegate implementation: - void Resume() override; - - // For simplicity, this class assumes that ResourceScheduler never cancels - // requests, and so these three methods are never called. - void Cancel() override; - void CancelAndIgnore() override; - void CancelWithError(int error_code) override; - - // Internal methods. - void StartRequestInternal(); - void CancelRequestInternal(int error, AsyncRevalidationResult result); - void StartReading(bool is_continuation); - void ReadMore(int* bytes_read); - // Logs the result histogram, then calls and clears |completion_callback_|. - void ResponseCompleted(AsyncRevalidationResult result); - void OnTimeout(AsyncRevalidationResult result); - void RecordDefer(); - - bool is_deferred_ = false; - - scoped_refptr<net::IOBuffer> read_buffer_; - base::OneShotTimer timer_; - - std::unique_ptr<net::URLRequest> request_; - std::unique_ptr<ResourceThrottle> throttle_; - - base::Closure completion_callback_; - - base::WeakPtrFactory<AsyncRevalidationDriver> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(AsyncRevalidationDriver); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_LOADER_ASYNC_REVALIDATION_DRIVER_H_
diff --git a/content/browser/loader/async_revalidation_driver_unittest.cc b/content/browser/loader/async_revalidation_driver_unittest.cc deleted file mode 100644 index 7543d13..0000000 --- a/content/browser/loader/async_revalidation_driver_unittest.cc +++ /dev/null
@@ -1,403 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/loader/async_revalidation_driver.h" - -#include <string> -#include <type_traits> -#include <utility> -#include <vector> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/location.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/run_loop.h" -#include "base/threading/thread_task_runner_handle.h" -#include "content/public/browser/client_certificate_delegate.h" -#include "content/public/common/content_client.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "content/test/test_content_browser_client.h" -#include "ipc/ipc_message.h" -#include "net/base/net_errors.h" -#include "net/base/network_delegate_impl.h" -#include "net/base/request_priority.h" -#include "net/ssl/ssl_cert_request_info.h" -#include "net/url_request/url_request_job_factory.h" -#include "net/url_request/url_request_job_factory_impl.h" -#include "net/url_request/url_request_status.h" -#include "net/url_request/url_request_test_job.h" -#include "net/url_request/url_request_test_util.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace content { -namespace { - -// Dummy implementation of ResourceThrottle, an instance of which is needed to -// initialize AsyncRevalidationDriver. -class ResourceThrottleStub : public ResourceThrottle { - public: - ResourceThrottleStub() {} - - // If true, defers the request in WillStartRequest. - void set_defer_request_on_will_start_request( - bool defer_request_on_will_start_request) { - defer_request_on_will_start_request_ = defer_request_on_will_start_request; - } - - // ResourceThrottler implementation: - void WillStartRequest(bool* defer) override { - *defer = defer_request_on_will_start_request_; - } - - const char* GetNameForLogging() const override { - return "ResourceThrottleStub"; - } - - private: - bool defer_request_on_will_start_request_ = false; - - DISALLOW_COPY_AND_ASSIGN(ResourceThrottleStub); -}; - -// There are multiple layers of boilerplate needed to use a URLRequestTestJob -// subclass. Subclasses of AsyncRevalidationDriverTest can use -// BindCreateProtocolHandlerCallback() to bypass most of that boilerplate. -using CreateProtocolHandlerCallback = base::Callback< - std::unique_ptr<net::URLRequestJobFactory::ProtocolHandler>()>; - -template <typename T> -CreateProtocolHandlerCallback BindCreateProtocolHandlerCallback() { - static_assert(std::is_base_of<net::URLRequestJob, T>::value, - "Template argument to BindCreateProtocolHandlerCallback() must " - "be a subclass of URLRequestJob."); - - class TemplatedProtocolHandler - : public net::URLRequestJobFactory::ProtocolHandler { - public: - static std::unique_ptr<net::URLRequestJobFactory::ProtocolHandler> - Create() { - return base::MakeUnique<TemplatedProtocolHandler>(); - } - - // URLRequestJobFactory::ProtocolHandler implementation: - net::URLRequestJob* MaybeCreateJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override { - return new T(request, network_delegate); - } - }; - - return base::Bind(&TemplatedProtocolHandler::Create); -} - -// An implementation of NetworkDelegate that captures the status of the last -// URLRequest to be destroyed. -class StatusCapturingNetworkDelegate : public net::NetworkDelegateImpl { - public: - const net::URLRequestStatus& last_status() { return last_status_; } - - private: - // net::NetworkDelegate implementation. - void OnURLRequestDestroyed(net::URLRequest* request) override { - last_status_ = request->status(); - } - - net::URLRequestStatus last_status_; -}; - -class AsyncRevalidationDriverTest : public testing::Test { - protected: - // Constructor for test fixtures that subclass this one. - AsyncRevalidationDriverTest( - const CreateProtocolHandlerCallback& create_protocol_handler_callback) - : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), - create_protocol_handler_callback_(create_protocol_handler_callback), - raw_ptr_resource_throttle_(nullptr), - raw_ptr_request_(nullptr) { - test_url_request_context_.set_job_factory(&job_factory_); - test_url_request_context_.set_network_delegate(&network_delegate_); - } - - // Constructor for tests that use this fixture directly. - AsyncRevalidationDriverTest() - : AsyncRevalidationDriverTest( - base::Bind(net::URLRequestTestJob::CreateProtocolHandler)) {} - - bool async_revalidation_complete_called() const { - return async_revalidation_complete_called_; - } - - const net::URLRequestStatus& last_status() { - return network_delegate_.last_status(); - } - - void SetUpAsyncRevalidationDriverWithRequestToUrl(const GURL& url) { - std::unique_ptr<net::URLRequest> request( - test_url_request_context_.CreateRequest(url, net::DEFAULT_PRIORITY, - nullptr /* delegate */)); - raw_ptr_request_ = request.get(); - raw_ptr_resource_throttle_ = new ResourceThrottleStub(); - // This use of base::Unretained() is safe because |driver_|, and the closure - // passed to it, will be destroyed before this object is. - driver_.reset(new AsyncRevalidationDriver( - std::move(request), base::WrapUnique(raw_ptr_resource_throttle_), - base::Bind(&AsyncRevalidationDriverTest::OnAsyncRevalidationComplete, - base::Unretained(this)))); - } - - void SetUpAsyncRevalidationDriverWithDefaultRequest() { - SetUpAsyncRevalidationDriverWithRequestToUrl( - net::URLRequestTestJob::test_url_1()); - } - - void SetUp() override { - job_factory_.SetProtocolHandler("test", - create_protocol_handler_callback_.Run()); - SetUpAsyncRevalidationDriverWithDefaultRequest(); - } - - void OnAsyncRevalidationComplete() { - EXPECT_FALSE(async_revalidation_complete_called_); - async_revalidation_complete_called_ = true; - driver_.reset(); - } - - TestBrowserThreadBundle thread_bundle_; - net::URLRequestJobFactoryImpl job_factory_; - net::TestURLRequestContext test_url_request_context_; - StatusCapturingNetworkDelegate network_delegate_; - CreateProtocolHandlerCallback create_protocol_handler_callback_; - - // The AsyncRevalidationDriver owns the URLRequest and the ResourceThrottle. - ResourceThrottleStub* raw_ptr_resource_throttle_; - net::URLRequest* raw_ptr_request_; - std::unique_ptr<AsyncRevalidationDriver> driver_; - bool async_revalidation_complete_called_ = false; -}; - -TEST_F(AsyncRevalidationDriverTest, NormalRequestCompletes) { - driver_->StartRequest(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(async_revalidation_complete_called()); -} - -// Verifies that request that should be deferred at start is deferred. -TEST_F(AsyncRevalidationDriverTest, DeferOnStart) { - raw_ptr_resource_throttle_->set_defer_request_on_will_start_request(true); - - driver_->StartRequest(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(raw_ptr_request_->is_pending()); - EXPECT_FALSE(async_revalidation_complete_called()); -} - -// Verifies that resuming a deferred request works. Assumes that DeferOnStart -// passes. -TEST_F(AsyncRevalidationDriverTest, ResumeDeferredRequestWorks) { - raw_ptr_resource_throttle_->set_defer_request_on_will_start_request(true); - - driver_->StartRequest(); - base::RunLoop().RunUntilIdle(); - - ResourceThrottle::Delegate* driver_as_resource_throttle_delegate = - driver_.get(); - driver_as_resource_throttle_delegate->Resume(); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(async_revalidation_complete_called()); -} - -// Verifies that redirects are not followed. -TEST_F(AsyncRevalidationDriverTest, RedirectsAreNotFollowed) { - SetUpAsyncRevalidationDriverWithRequestToUrl( - net::URLRequestTestJob::test_url_redirect_to_url_2()); - - driver_->StartRequest(); - while (net::URLRequestTestJob::ProcessOnePendingMessage()) - base::RunLoop().RunUntilIdle(); - base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(last_status().is_success()); - EXPECT_EQ(net::ERR_ABORTED, last_status().error()); - EXPECT_TRUE(async_revalidation_complete_called()); -} - -// A mock URLRequestJob which simulates an SSL client auth request. -class MockClientCertURLRequestJob : public net::URLRequestTestJob { - public: - MockClientCertURLRequestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate) - : net::URLRequestTestJob(request, network_delegate, true), - weak_factory_(this) {} - - // net::URLRequestTestJob implementation: - void Start() override { - scoped_refptr<net::SSLCertRequestInfo> cert_request_info( - new net::SSLCertRequestInfo); - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&MockClientCertURLRequestJob::NotifyCertificateRequested, - weak_factory_.GetWeakPtr(), - base::RetainedRef(cert_request_info))); - } - - void ContinueWithCertificate( - net::X509Certificate* cert, - net::SSLPrivateKey* client_private_key) override { - ADD_FAILURE() << "Certificate supplied."; - } - - void Kill() override { - weak_factory_.InvalidateWeakPtrs(); - URLRequestJob::Kill(); - } - - private: - base::WeakPtrFactory<MockClientCertURLRequestJob> weak_factory_; -}; - -class AsyncRevalidationDriverClientCertTest - : public AsyncRevalidationDriverTest { - protected: - AsyncRevalidationDriverClientCertTest() - : AsyncRevalidationDriverTest( - BindCreateProtocolHandlerCallback<MockClientCertURLRequestJob>()) {} -}; - -// Test browser client that causes the test to fail if SelectClientCertificate() -// is called. Automatically sets itself as the browser client when constructed -// and restores the old browser client in the destructor. -class ScopedDontSelectCertificateBrowserClient - : public TestContentBrowserClient { - public: - ScopedDontSelectCertificateBrowserClient() { - old_client_ = SetBrowserClientForTesting(this); - } - - ~ScopedDontSelectCertificateBrowserClient() override { - SetBrowserClientForTesting(old_client_); - } - - void SelectClientCertificate( - WebContents* web_contents, - net::SSLCertRequestInfo* cert_request_info, - std::unique_ptr<ClientCertificateDelegate> delegate) override { - ADD_FAILURE() << "SelectClientCertificate was called."; - } - - private: - ContentBrowserClient* old_client_; - - DISALLOW_COPY_AND_ASSIGN(ScopedDontSelectCertificateBrowserClient); -}; - -// Verifies that async revalidation requests do not attempt to provide client -// certificates. -TEST_F(AsyncRevalidationDriverClientCertTest, RequestRejected) { - // Ensure that SelectClientCertificate is not called during this test. - ScopedDontSelectCertificateBrowserClient test_client; - - // Start the request and wait for it to pause. - driver_->StartRequest(); - - // Because TestBrowserThreadBundle only uses one real thread, this is - // sufficient to ensure that tasks posted to the "UI thread" have run. - base::RunLoop().RunUntilIdle(); - - // Check that the request aborted. - EXPECT_FALSE(last_status().is_success()); - EXPECT_EQ(net::ERR_SSL_CLIENT_AUTH_CERT_NEEDED, last_status().error()); - EXPECT_TRUE(async_revalidation_complete_called()); -} - -// A mock URLRequestJob which simulates an SSL certificate error. -class MockSSLErrorURLRequestJob : public net::URLRequestTestJob { - public: - MockSSLErrorURLRequestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate) - : net::URLRequestTestJob(request, network_delegate, true), - weak_factory_(this) {} - - // net::URLRequestTestJob implementation: - void Start() override { - // This SSLInfo isn't really valid, but it is good enough for testing. - net::SSLInfo ssl_info; - ssl_info.SetCertError(net::ERR_CERT_DATE_INVALID); - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&MockSSLErrorURLRequestJob::NotifySSLCertificateError, - weak_factory_.GetWeakPtr(), ssl_info, false)); - } - - void ContinueDespiteLastError() override { - ADD_FAILURE() << "ContinueDespiteLastError called."; - } - - private: - base::WeakPtrFactory<MockSSLErrorURLRequestJob> weak_factory_; -}; - -class AsyncRevalidationDriverSSLErrorTest : public AsyncRevalidationDriverTest { - protected: - AsyncRevalidationDriverSSLErrorTest() - : AsyncRevalidationDriverTest( - BindCreateProtocolHandlerCallback<MockSSLErrorURLRequestJob>()) {} -}; - -// Verifies that async revalidation requests do not attempt to recover from SSL -// certificate errors. -TEST_F(AsyncRevalidationDriverSSLErrorTest, RequestWithSSLErrorRejected) { - // Start the request and wait for it to pause. - driver_->StartRequest(); - base::RunLoop().RunUntilIdle(); - - // Check that the request has been aborted. - EXPECT_FALSE(last_status().is_success()); - EXPECT_EQ(net::ERR_ABORTED, last_status().error()); - EXPECT_TRUE(async_revalidation_complete_called()); -} - -// A URLRequestTestJob that sets |request_time| and |was_cached| on their -// response_info, and causes the test to fail if Read() is called. -class FromCacheURLRequestJob : public net::URLRequestTestJob { - public: - FromCacheURLRequestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate) - : net::URLRequestTestJob(request, network_delegate, true) {} - - void GetResponseInfo(net::HttpResponseInfo* info) override { - URLRequestTestJob::GetResponseInfo(info); - info->request_time = base::Time::Now(); - info->was_cached = true; - } - - int ReadRawData(net::IOBuffer* buf, int buf_size) override { - ADD_FAILURE() << "ReadRawData() was called."; - return URLRequestTestJob::ReadRawData(buf, buf_size); - } - - private: - ~FromCacheURLRequestJob() override {} - - DISALLOW_COPY_AND_ASSIGN(FromCacheURLRequestJob); -}; - -class AsyncRevalidationDriverFromCacheTest - : public AsyncRevalidationDriverTest { - protected: - AsyncRevalidationDriverFromCacheTest() - : AsyncRevalidationDriverTest( - BindCreateProtocolHandlerCallback<FromCacheURLRequestJob>()) {} -}; - -TEST_F(AsyncRevalidationDriverFromCacheTest, - CacheNotReadOnSuccessfulRevalidation) { - driver_->StartRequest(); - base::RunLoop().RunUntilIdle(); - - EXPECT_TRUE(async_revalidation_complete_called()); -} - -} // namespace -} // namespace content
diff --git a/content/browser/loader/async_revalidation_manager.cc b/content/browser/loader/async_revalidation_manager.cc deleted file mode 100644 index 719ae4a..0000000 --- a/content/browser/loader/async_revalidation_manager.cc +++ /dev/null
@@ -1,194 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/loader/async_revalidation_manager.h" - -#include <tuple> -#include <utility> - -#include "base/logging.h" -#include "content/browser/loader/async_revalidation_driver.h" -#include "content/browser/loader/resource_request_info_impl.h" -#include "content/browser/loader/resource_scheduler.h" -#include "content/common/resource_messages.h" -#include "content/common/resource_request.h" -#include "content/public/browser/resource_throttle.h" -#include "net/base/load_flags.h" -#include "net/http/http_transaction_factory.h" -#include "net/http/http_util.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_context.h" -#include "url/gurl.h" - -namespace content { - -AsyncRevalidationManager::AsyncRevalidationKey::AsyncRevalidationKey( - const ResourceContext* resource_context, - const net::HttpCache* http_cache, - const GURL& url) - : resource_context(resource_context), - http_cache(http_cache), - url_key(net::HttpUtil::SpecForRequest(url)) {} - -AsyncRevalidationManager::AsyncRevalidationKey::AsyncRevalidationKey( - const ResourceContext* resource_context) - : resource_context(resource_context), http_cache(nullptr), url_key() {} - -AsyncRevalidationManager::AsyncRevalidationKey::~AsyncRevalidationKey() {} - -bool AsyncRevalidationManager::AsyncRevalidationKey::LessThan::operator()( - const AsyncRevalidationKey& lhs, - const AsyncRevalidationKey& rhs) const { - return std::tie(lhs.resource_context, lhs.http_cache, lhs.url_key) < - std::tie(rhs.resource_context, rhs.http_cache, rhs.url_key); -} - -AsyncRevalidationManager::AsyncRevalidationManager() {} - -AsyncRevalidationManager::~AsyncRevalidationManager() { - DCHECK(in_progress_.empty()); -} - -void AsyncRevalidationManager::BeginAsyncRevalidation( - net::URLRequest* for_request, - ResourceScheduler* scheduler) { - DCHECK_EQ(for_request->url_chain().size(), 1u); - ResourceRequestInfoImpl* info = - ResourceRequestInfoImpl::ForRequest(for_request); - DCHECK(info); - DCHECK(info->requester_info()->IsRenderer()); - if (!info->requester_info()->filter()) { - // The child has gone away and we can no longer get ResourceContext and - // URLRequestContext to perform async revalidation. - // This can happen in the following cases, ordered from bad to not-so-bad - // - // 1. PlzNavigate (but enabling PlzNavigate automatically disables - // stale-while-revalidate; see crbug.com/561609) - // 2. <link rel=prefetch> may read a stale cache entry without a - // revalidation being performed if the original renderer goes away. This - // is a lost optimisation opportunity. - // - // Not an issue: - // 1. Implicit downloads. This method is called before - // MimeTypeResourceHandler calls set_is_download, so the renderer process - // must still exist for the request not to have been canceled. - // 2. Explicit downloads (ie. started via "Save As"). These never use - // stale-while-revalidate. - // 3. Non-PlzNavigate navigations between renderers. The old renderer - // still exists when this method is called. - // 4. <a ping>, navigation.sendBeacon() and Content-Security-Policy reports - // are POST requests, so they never use stale-while-revalidate. - // - // TODO(ricea): Resolve these lifetime issues. crbug.com/561591 - return; - } - - ResourceContext* resource_context = nullptr; - net::URLRequestContext* request_context = nullptr; - - // The embedder of //content needs to ensure that the URLRequestContext object - // remains valid until after the ResourceContext object is destroyed. - info->requester_info()->GetContexts(info->GetResourceType(), - &resource_context, &request_context); - - AsyncRevalidationKey async_revalidation_key( - resource_context, request_context->http_transaction_factory()->GetCache(), - for_request->url()); - std::pair<AsyncRevalidationMap::iterator, bool> insert_result = - in_progress_.insert(AsyncRevalidationMap::value_type( - async_revalidation_key, std::unique_ptr<AsyncRevalidationDriver>())); - if (!insert_result.second) { - // A matching async revalidation is already in progress for this cache; we - // don't need another one. - return; - } - - net::HttpRequestHeaders headers; - headers.AddHeadersFromString(info->original_headers()); - - // Construct the request. - std::unique_ptr<net::URLRequest> new_request = - request_context->CreateRequest(for_request->url(), net::IDLE, nullptr); - - new_request->set_method(for_request->method()); - new_request->set_first_party_for_cookies( - for_request->first_party_for_cookies()); - new_request->set_initiator(for_request->initiator()); - new_request->set_first_party_url_policy( - for_request->first_party_url_policy()); - - new_request->SetReferrer(for_request->referrer()); - new_request->set_referrer_policy(for_request->referrer_policy()); - - new_request->SetExtraRequestHeaders(headers); - - // Remove LOAD_SUPPORT_ASYNC_REVALIDATION and LOAD_MAIN_FRAME_DEPRECATED - // flags. - // Also remove things which shouldn't have been there to begin with, - // and unrecognised flags. - int load_flags = - for_request->load_flags() & - (net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_BYPASS_PROXY | - net::LOAD_VERIFY_EV_CERT | net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SEND_AUTH_DATA | net::LOAD_MAYBE_USER_GESTURE | - net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY); - new_request->SetLoadFlags(load_flags); - - // These values would be -1 if the request was created by PlzNavigate. This - // would cause the async revalidation to start immediately. - // stale-while-revalidate is disabled when PlzNavigate is enabled - // to prevent this and other issues. See crbug.com/561610. - int child_id = info->GetChildID(); - int route_id = info->GetRouteID(); - - std::unique_ptr<ResourceThrottle> throttle = - scheduler->ScheduleRequest(child_id, route_id, false, new_request.get()); - - // AsyncRevalidationDriver does not outlive its entry in |in_progress_|, - // so the iterator and |this| may be passed to base::Bind directly. - insert_result.first->second.reset(new AsyncRevalidationDriver( - std::move(new_request), std::move(throttle), - base::Bind(&AsyncRevalidationManager::OnAsyncRevalidationComplete, - base::Unretained(this), insert_result.first))); - insert_result.first->second->StartRequest(); -} - -void AsyncRevalidationManager::CancelAsyncRevalidationsForResourceContext( - ResourceContext* resource_context) { - // |resource_context| is the first part of the key, so elements to be - // cancelled are contiguous in the map. - AsyncRevalidationKey partial_key(resource_context); - for (auto it = in_progress_.lower_bound(partial_key); - it != in_progress_.end() && - it->first.resource_context == resource_context;) { - it = in_progress_.erase(it); - } -} - -bool AsyncRevalidationManager::QualifiesForAsyncRevalidation( - const ResourceRequest& request) { - if (request.load_flags & - (net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE | - net::LOAD_VALIDATE_CACHE | net::LOAD_SKIP_CACHE_VALIDATION | - net::LOAD_ONLY_FROM_CACHE | net::LOAD_IGNORE_LIMITS | - net::LOAD_PREFETCH)) { - return false; - } - if (request.method != "GET") - return false; - // A GET request should not have a body. - if (request.request_body.get()) - return false; - if (!request.url.SchemeIsHTTPOrHTTPS()) - return false; - - return true; -} - -void AsyncRevalidationManager::OnAsyncRevalidationComplete( - AsyncRevalidationMap::iterator it) { - in_progress_.erase(it); -} - -} // namespace content
diff --git a/content/browser/loader/async_revalidation_manager.h b/content/browser/loader/async_revalidation_manager.h deleted file mode 100644 index facdb2d1..0000000 --- a/content/browser/loader/async_revalidation_manager.h +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CONTENT_BROWSER_LOADER_ASYNC_REVALIDATION_MANAGER_H_ -#define CONTENT_BROWSER_LOADER_ASYNC_REVALIDATION_MANAGER_H_ - -#include <map> -#include <memory> -#include <string> - -#include "base/macros.h" - -class GURL; - -namespace net { -class URLRequest; -class HttpCache; -} - -namespace content { - -class AsyncRevalidationDriver; -class ResourceContext; -class ResourceScheduler; -struct ResourceRequest; - -// One instance of this class manages all active AsyncRevalidationDriver objects -// for all profiles. It is created by and owned by -// ResourceDispatcherHostImpl. It also implements the creation of a new -// net::URLRequest and AsyncRevalidationDriver from an existing net::URLRequest -// that has had the stale-while-revalidate algorithm applied to it. -class AsyncRevalidationManager { - public: - AsyncRevalidationManager(); - ~AsyncRevalidationManager(); - - // Starts an async revalidation by copying |for_request|. |scheduler| must - // remain valid until this object is destroyed. - void BeginAsyncRevalidation(net::URLRequest* for_request, - ResourceScheduler* scheduler); - - // Cancel all pending async revalidations that use ResourceContext. - void CancelAsyncRevalidationsForResourceContext( - ResourceContext* resource_context); - - static bool QualifiesForAsyncRevalidation(const ResourceRequest& request); - - private: - // The key of the map of pending async revalidations. This key has a distinct - // value for every in-progress async revalidation. It is used to avoid - // duplicate async revalidations, and also to cancel affected async - // revalidations when a ResourceContext is removed. - // - // Request headers are intentionally not included in the key for simplicity, - // as they usually don't affect caching. - // - // TODO(ricea): Behave correctly in cases where the request headers do make a - // difference. crbug.com/567721 - struct AsyncRevalidationKey { - AsyncRevalidationKey(const ResourceContext* resource_context, - const net::HttpCache* http_cache, - const GURL& url); - - // Create a prefix key that is used to match all of the - // AsyncRevalidationDrivers using |resource_context| in the map. - explicit AsyncRevalidationKey(const ResourceContext* resource_context); - - // The key for a map needs to be copyable. - AsyncRevalidationKey(const AsyncRevalidationKey& rhs) = default; - ~AsyncRevalidationKey(); - - // No operator= is generated because the struct members are immutable. - - // |resource_context| and |http_cache| are never dereferenced; they are only - // compared to other values. - const ResourceContext* const resource_context; - - // There are multiple independent HttpCache objects per ResourceContext. - const net::HttpCache* const http_cache; - - // Derived from the url via net::HttpUtil::SpecForRequest(). - const std::string url_key; - - struct LessThan { - bool operator()(const AsyncRevalidationKey& lhs, - const AsyncRevalidationKey& rhs) const; - }; - }; - - using AsyncRevalidationMap = - std::map<AsyncRevalidationKey, - std::unique_ptr<AsyncRevalidationDriver>, - AsyncRevalidationKey::LessThan>; - - void OnAsyncRevalidationComplete(AsyncRevalidationMap::iterator it); - - // Map of AsyncRevalidationDriver instances that are currently in-flight: - // either waiting to be scheduled or active on the network. - AsyncRevalidationMap in_progress_; - - DISALLOW_COPY_AND_ASSIGN(AsyncRevalidationManager); -}; - -} // namespace content - -#endif // CONTENT_BROWSER_LOADER_ASYNC_REVALIDATION_MANAGER_H_
diff --git a/content/browser/loader/async_revalidation_manager_browsertest.cc b/content/browser/loader/async_revalidation_manager_browsertest.cc deleted file mode 100644 index 982ecebf..0000000 --- a/content/browser/loader/async_revalidation_manager_browsertest.cc +++ /dev/null
@@ -1,250 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <memory> -#include <string> -#include <utility> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/macros.h" -#include "base/run_loop.h" -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "base/test/scoped_feature_list.h" -#include "content/public/common/browser_side_navigation_policy.h" -#include "content/public/common/content_features.h" -#include "content/public/test/browser_test_utils.h" -#include "content/public/test/content_browser_test.h" -#include "content/public/test/content_browser_test_utils.h" -#include "content/shell/browser/shell.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "net/test/embedded_test_server/http_request.h" -#include "net/test/embedded_test_server/http_response.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" - -namespace content { - -namespace { - -using net::test_server::HttpResponse; -using net::test_server::HttpRequest; -using net::test_server::BasicHttpResponse; - -const char kCountedHtmlPath[] = "/counted.html"; -const char kCookieHtmlPath[] = "/cookie.html"; - -class AsyncRevalidationManagerBrowserTest : public ContentBrowserTest { - protected: - AsyncRevalidationManagerBrowserTest() {} - ~AsyncRevalidationManagerBrowserTest() override {} - - void SetUp() override { - scoped_feature_list_.InitAndEnableFeature(features::kStaleWhileRevalidate); - ContentBrowserTest::SetUp(); - } - - void SetUpOnMainThread() override { - ContentBrowserTest::SetUpOnMainThread(); - run_loop_.reset(new base::RunLoop); - } - - base::RunLoop* run_loop() { - DCHECK(run_loop_); - return run_loop_.get(); - } - - int requests_counted() const { return requests_counted_; } - - // This method lacks diagnostics for the failure case because TitleWatcher - // will just wait until the test times out if |expected_title| does not - // appear. - bool TitleBecomes(const GURL& url, const std::string& expected_title) { - base::string16 expected_title16(base::ASCIIToUTF16(expected_title)); - TitleWatcher title_watcher(shell()->web_contents(), expected_title16); - NavigateToURL(shell(), url); - return title_watcher.WaitAndGetTitle() == expected_title16; - } - - void RegisterCountingRequestHandler() { - embedded_test_server()->RegisterRequestHandler(base::Bind( - &AsyncRevalidationManagerBrowserTest::CountingRequestHandler, - base::Unretained(this))); - } - - void RegisterCookieRequestHandler() { - embedded_test_server()->RegisterRequestHandler(base::Bind( - &AsyncRevalidationManagerBrowserTest::CookieRequestHandler, - base::Unretained(this))); - } - - private: - // A request handler which increases the number in the title tag on every - // request. - std::unique_ptr<HttpResponse> CountingRequestHandler( - const HttpRequest& request) { - if (request.relative_url != kCountedHtmlPath) - return nullptr; - - int version = ++requests_counted_; - - std::unique_ptr<BasicHttpResponse> http_response( - StaleWhileRevalidateHeaders()); - http_response->set_content( - base::StringPrintf("<title>Version %d</title>", version)); - - // The second time this handler is run is the async revalidation. Tests can - // use this for synchronisation. - if (version == 2) { - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - run_loop()->QuitClosure()); - } - return std::move(http_response); - } - - // A request handler which increases a cookie value on every request. - std::unique_ptr<HttpResponse> CookieRequestHandler( - const HttpRequest& request) { - static const char kHtml[] = - "<script>\n" - "var intervalId;\n" - "function checkCookie() {\n" - " if (document.cookie.search(/version=2/) != -1) {\n" - " clearInterval(intervalId);\n" - " document.title = \"PASS\";\n" - " }\n" - "}\n" - "intervalId = setInterval(checkCookie, 10);\n" - "</script>\n" - "<title>Loaded</title>\n"; - - if (request.relative_url != kCookieHtmlPath) - return nullptr; - - int version = ++requests_counted_; - - std::unique_ptr<BasicHttpResponse> http_response( - StaleWhileRevalidateHeaders()); - http_response->AddCustomHeader("Set-Cookie", - base::StringPrintf("version=%d", version)); - http_response->set_content(kHtml); - - return std::move(http_response); - } - - // Generate the standard response headers common to all request handlers. - std::unique_ptr<BasicHttpResponse> StaleWhileRevalidateHeaders() { - std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); - http_response->set_code(net::HTTP_OK); - http_response->set_content_type("text/html; charset=utf-8"); - http_response->AddCustomHeader("Cache-Control", - "max-age=0, stale-while-revalidate=86400"); - // A validator is needed for revalidations, and hence - // stale-while-revalidate, to work. - std::string etag = base::StringPrintf( - "\"AsyncRevalidationManagerBrowserTest%d\"", requests_counted_); - http_response->AddCustomHeader("ETag", etag); - return http_response; - } - - std::unique_ptr<base::RunLoop> run_loop_; - int requests_counted_ = 0; - base::test::ScopedFeatureList scoped_feature_list_; - - DISALLOW_COPY_AND_ASSIGN(AsyncRevalidationManagerBrowserTest); -}; - -// Verify that the "Cache-Control: stale-while-revalidate" directive correctly -// triggers an async revalidation. -IN_PROC_BROWSER_TEST_F(AsyncRevalidationManagerBrowserTest, - StaleWhileRevalidateIsApplied) { - RegisterCountingRequestHandler(); - ASSERT_TRUE(embedded_test_server()->Start()); - - // PlzNavigate: Stale while revalidate is disabled. - // TODO(clamy): Re-enable the test when there is support. - if (IsBrowserSideNavigationEnabled()) - return; - GURL url(embedded_test_server()->GetURL(kCountedHtmlPath)); - - EXPECT_TRUE(TitleBecomes(url, "Version 1")); - - // The first request happens synchronously. - EXPECT_EQ(1, requests_counted()); - - // Force the renderer to be destroyed so that the Blink cache doesn't - // interfere with the result. - NavigateToURL(shell(), GURL("about:blank")); - - // Load the page again. We should get the stale version from the cache. - EXPECT_TRUE(TitleBecomes(url, "Version 1")); - - // Wait for the async revalidation to complete. - run_loop()->Run(); - EXPECT_EQ(2, requests_counted()); -} - -// The fresh cache entry must become visible once the async revalidation request -// has been sent. -IN_PROC_BROWSER_TEST_F(AsyncRevalidationManagerBrowserTest, CacheIsUpdated) { - RegisterCountingRequestHandler(); - ASSERT_TRUE(embedded_test_server()->Start()); - - // PlzNavigate: Stale while revalidate is disabled. - // TODO(clamy): Re-enable the test when there is support. - if (IsBrowserSideNavigationEnabled()) - return; - using base::ASCIIToUTF16; - GURL url(embedded_test_server()->GetURL(kCountedHtmlPath)); - - EXPECT_TRUE(TitleBecomes(url, "Version 1")); - - // Reset the renderer cache. - NavigateToURL(shell(), GURL("about:blank")); - - // Load the page again. We should get the stale version from the cache. - EXPECT_TRUE(TitleBecomes(url, "Version 1")); - - // Wait for the async revalidation request to be processed by the - // EmbeddedTestServer. - run_loop()->Run(); - - // Reset the renderer cache. - NavigateToURL(shell(), GURL("about:blank")); - - // Since the async revalidation request has been sent, the cache can no - // longer return the stale contents. - EXPECT_TRUE(TitleBecomes(url, "Version 2")); -} - -// When the asynchronous revalidation arrives, any cookies it contains must be -// applied immediately. -IN_PROC_BROWSER_TEST_F(AsyncRevalidationManagerBrowserTest, - CookieSetAsynchronously) { - RegisterCookieRequestHandler(); - ASSERT_TRUE(embedded_test_server()->Start()); - - // PlzNavigate: Stale while revalidate is disabled. - // TODO(clamy): Re-enable the test when there is support. - if (IsBrowserSideNavigationEnabled()) - return; - GURL url(embedded_test_server()->GetURL(kCookieHtmlPath)); - - // Set cookie to version=1 - NavigateToURL(shell(), url); - - // Reset render cache. - NavigateToURL(shell(), GURL("about:blank")); - - // The page will load from the cache, then when the async revalidation - // completes the cookie will update. - EXPECT_TRUE(TitleBecomes(url, "PASS")); -} - -} // namespace - -} // namespace content
diff --git a/content/browser/loader/async_revalidation_manager_unittest.cc b/content/browser/loader/async_revalidation_manager_unittest.cc deleted file mode 100644 index 1ad472a..0000000 --- a/content/browser/loader/async_revalidation_manager_unittest.cc +++ /dev/null
@@ -1,558 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "content/browser/loader/async_revalidation_manager.h" - -#include <deque> -#include <string> -#include <utility> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/macros.h" -#include "base/memory/ptr_util.h" -#include "base/memory/shared_memory_handle.h" -#include "base/pickle.h" -#include "base/run_loop.h" -#include "base/strings/string_util.h" -#include "content/browser/child_process_security_policy_impl.h" -#include "content/browser/loader/resource_dispatcher_host_impl.h" -#include "content/browser/loader/resource_message_filter.h" -#include "content/browser/loader_delegate_impl.h" -#include "content/common/child_process_host_impl.h" -#include "content/common/resource_messages.h" -#include "content/common/resource_request.h" -#include "content/public/browser/resource_context.h" -#include "content/public/common/appcache_info.h" -#include "content/public/common/resource_type.h" -#include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "ipc/ipc_param_traits.h" -#include "net/base/load_flags.h" -#include "net/base/network_delegate.h" -#include "net/http/http_util.h" -#include "net/url_request/url_request.h" -#include "net/url_request/url_request_job.h" -#include "net/url_request/url_request_job_factory.h" -#include "net/url_request/url_request_test_job.h" -#include "net/url_request/url_request_test_util.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/page_transition_types.h" -#include "url/gurl.h" -#include "url/url_constants.h" - -namespace content { - -namespace { - -// This class is a variation on URLRequestTestJob that -// returns ERR_IO_PENDING before every read, not just the first one. -class URLRequestTestDelayedCompletionJob : public net::URLRequestTestJob { - public: - URLRequestTestDelayedCompletionJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const std::string& response_headers, - const std::string& response_data) - : net::URLRequestTestJob(request, - network_delegate, - response_headers, - response_data, - false) {} - - private: - bool NextReadAsync() override { return true; } -}; - -// A URLRequestJob implementation which sets the |async_revalidation_required| -// flag on the HttpResponseInfo object to true if the request has the -// LOAD_SUPPORT_ASYNC_REVALIDATION flag. -class AsyncRevalidationRequiredURLRequestTestJob - : public net::URLRequestTestJob { - public: - AsyncRevalidationRequiredURLRequestTestJob( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) - : URLRequestTestJob(request, - network_delegate, - net::URLRequestTestJob::test_headers(), - std::string(), - false) {} - - void GetResponseInfo(net::HttpResponseInfo* info) override { - URLRequestTestJob::GetResponseInfo(info); - if (request()->load_flags() & net::LOAD_SUPPORT_ASYNC_REVALIDATION) - info->async_revalidation_required = true; - } -}; - -// A URLRequestJob implementation which serves a redirect and sets the -// |async_revalidation_required| flag on the HttpResponseInfo object to true if -// the request has the LOAD_SUPPORT_ASYNC_REVALIDATION flag. -class RedirectAndRevalidateURLRequestTestJob : public net::URLRequestTestJob { - public: - RedirectAndRevalidateURLRequestTestJob(net::URLRequest* request, - net::NetworkDelegate* network_delegate) - : URLRequestTestJob(request, - network_delegate, - CreateRedirectHeaders(), - std::string(), - false) {} - - void GetResponseInfo(net::HttpResponseInfo* info) override { - URLRequestTestJob::GetResponseInfo(info); - if (request()->load_flags() & net::LOAD_SUPPORT_ASYNC_REVALIDATION) - info->async_revalidation_required = true; - } - - private: - static std::string CreateRedirectHeaders() { - static const char kRedirectHeaders[] = - "HTTP/1.1 302 MOVED\n" - "Location: http://example.com/async-revalidate/from-redirect\n" - "\n"; - return std::string(kRedirectHeaders, arraysize(kRedirectHeaders) - 1); - } -}; - -class TestURLRequestJobFactory : public net::URLRequestJobFactory { - public: - TestURLRequestJobFactory() = default; - - // Sets the contents of the response. |headers| should have "\n" as line - // breaks and end in "\n\n". - void SetResponse(const std::string& headers, const std::string& data) { - response_headers_ = headers; - response_data_ = data; - } - - net::URLRequestJob* MaybeCreateJobWithProtocolHandler( - const std::string& scheme, - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override { - std::string path = request->url().path(); - if (base::StartsWith(path, "/async-revalidate", - base::CompareCase::SENSITIVE)) { - return new AsyncRevalidationRequiredURLRequestTestJob(request, - network_delegate); - } - if (base::StartsWith(path, "/redirect", base::CompareCase::SENSITIVE)) { - return new RedirectAndRevalidateURLRequestTestJob(request, - network_delegate); - } - return new URLRequestTestDelayedCompletionJob( - request, network_delegate, response_headers_, response_data_); - } - - net::URLRequestJob* MaybeInterceptRedirect( - net::URLRequest* request, - net::NetworkDelegate* network_delegate, - const GURL& location) const override { - return nullptr; - } - - net::URLRequestJob* MaybeInterceptResponse( - net::URLRequest* request, - net::NetworkDelegate* network_delegate) const override { - return nullptr; - } - - bool IsHandledProtocol(const std::string& scheme) const override { - // If non-standard schemes need to be tested in future it will be - // necessary to call ChildProcessSecurityPolicyImpl:: - // RegisterWebSafeScheme() for them. - return scheme == url::kHttpScheme || scheme == url::kHttpsScheme; - } - - bool IsHandledURL(const GURL& url) const override { - return IsHandledProtocol(url.scheme()); - } - - bool IsSafeRedirectTarget(const GURL& location) const override { - return false; - } - - private: - std::string response_headers_; - std::string response_data_; - - DISALLOW_COPY_AND_ASSIGN(TestURLRequestJobFactory); -}; - -// On Windows, ResourceMsg_SetDataBuffer supplies a HANDLE which is not -// automatically released. -// -// See ResourceDispatcher::ReleaseResourcesInDataMessage. -// -// TODO(ricea): Maybe share this implementation with -// resource_dispatcher_host_unittest.cc. -void ReleaseHandlesInMessage(const IPC::Message& message) { - if (message.type() == ResourceMsg_SetDataBuffer::ID) { - base::PickleIterator iter(message); - int request_id; - CHECK(iter.ReadInt(&request_id)); - base::SharedMemoryHandle shm_handle; - if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message, &iter, - &shm_handle)) { - if (base::SharedMemory::IsHandleValid(shm_handle)) - base::SharedMemory::CloseHandle(shm_handle); - } - } -} - -// This filter just deletes any messages that are sent through it. -class BlackholeFilter : public ResourceMessageFilter { - public: - explicit BlackholeFilter(ResourceContext* resource_context) - : ResourceMessageFilter( - ChildProcessHostImpl::GenerateChildProcessUniqueId(), - nullptr, - nullptr, - nullptr, - nullptr, - base::Bind(&BlackholeFilter::GetContexts, base::Unretained(this))), - resource_context_(resource_context) { - InitializeForTest(); - ChildProcessSecurityPolicyImpl::GetInstance()->Add(child_id()); - } - - bool Send(IPC::Message* msg) override { - std::unique_ptr<IPC::Message> take_ownership(msg); - ReleaseHandlesInMessage(*msg); - return true; - } - - private: - ~BlackholeFilter() override { - ChildProcessSecurityPolicyImpl::GetInstance()->Remove(child_id()); - } - - void GetContexts(ResourceType resource_type, - ResourceContext** resource_context, - net::URLRequestContext** request_context) { - *resource_context = resource_context_; - *request_context = resource_context_->GetRequestContext(); - } - - ResourceContext* resource_context_; - - DISALLOW_COPY_AND_ASSIGN(BlackholeFilter); -}; - -ResourceRequest CreateResourceRequest(const char* method, - ResourceType type, - const GURL& url) { - ResourceRequest request; - request.method = std::string(method); - request.url = url; - request.first_party_for_cookies = url; // Bypass third-party cookie blocking. - request.request_initiator = url::Origin(url); // Ensure initiator is set. - request.referrer_policy = blink::WebReferrerPolicyDefault; - request.load_flags = 0; - request.origin_pid = 0; - request.resource_type = type; - request.request_context = 0; - request.appcache_host_id = kAppCacheNoHostId; - request.download_to_file = false; - request.should_reset_appcache = false; - request.is_main_frame = true; - request.parent_is_main_frame = false; - request.parent_render_frame_id = -1; - request.transition_type = ui::PAGE_TRANSITION_LINK; - request.allow_download = true; - return request; -} - -class AsyncRevalidationManagerTest : public ::testing::Test { - protected: - AsyncRevalidationManagerTest( - std::unique_ptr<net::TestNetworkDelegate> network_delegate) - : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), - network_delegate_(std::move(network_delegate)) { - host_.SetLoaderDelegate(&loader_delegate_); - browser_context_.reset(new TestBrowserContext()); - BrowserContext::EnsureResourceContextInitialized(browser_context_.get()); - base::RunLoop().RunUntilIdle(); - ResourceContext* resource_context = browser_context_->GetResourceContext(); - filter_ = new BlackholeFilter(resource_context); - net::URLRequestContext* request_context = - resource_context->GetRequestContext(); - job_factory_.reset(new TestURLRequestJobFactory); - request_context->set_job_factory(job_factory_.get()); - request_context->set_network_delegate(network_delegate_.get()); - host_.EnableStaleWhileRevalidateForTesting(); - } - - AsyncRevalidationManagerTest() - : AsyncRevalidationManagerTest( - base::WrapUnique(new net::TestNetworkDelegate)) {} - - void TearDown() override { - filter_->OnChannelClosing(); - host_.CancelRequestsForProcess(filter_->child_id()); - host_.Shutdown(); - host_.CancelRequestsForContext(browser_context_->GetResourceContext()); - browser_context_.reset(); - base::RunLoop().RunUntilIdle(); - } - - void SetResponse(const std::string& headers, const std::string& data) { - job_factory_->SetResponse(headers, data); - } - - // Creates a request using the current test object as the filter and - // SubResource as the resource type. - void MakeTestRequest(int render_view_id, int request_id, const GURL& url) { - ResourceRequest request = - CreateResourceRequest("GET", RESOURCE_TYPE_SUB_RESOURCE, url); - ResourceHostMsg_RequestResource msg(render_view_id, request_id, request); - filter_->OnMessageReceived(msg); - base::RunLoop().RunUntilIdle(); - } - - void EnsureSchemeIsAllowed(const std::string& scheme) { - ChildProcessSecurityPolicyImpl* policy = - ChildProcessSecurityPolicyImpl::GetInstance(); - if (!policy->IsWebSafeScheme(scheme)) - policy->RegisterWebSafeScheme(scheme); - } - - content::TestBrowserThreadBundle thread_bundle_; - std::unique_ptr<TestBrowserContext> browser_context_; - std::unique_ptr<TestURLRequestJobFactory> job_factory_; - scoped_refptr<BlackholeFilter> filter_; - std::unique_ptr<net::TestNetworkDelegate> network_delegate_; - LoaderDelegateImpl loader_delegate_; - ResourceDispatcherHostImpl host_; -}; - -TEST_F(AsyncRevalidationManagerTest, SupportsAsyncRevalidation) { - SetResponse(net::URLRequestTestJob::test_headers(), "delay complete"); - MakeTestRequest(0, 1, GURL("http://example.com/baz")); - - net::URLRequest* url_request( - host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1))); - ASSERT_TRUE(url_request); - - EXPECT_TRUE(url_request->load_flags() & net::LOAD_SUPPORT_ASYNC_REVALIDATION); -} - -TEST_F(AsyncRevalidationManagerTest, AsyncRevalidationNotSupportedForPOST) { - SetResponse(net::URLRequestTestJob::test_headers(), "delay complete"); - // Create POST request. - ResourceRequest request = CreateResourceRequest( - "POST", RESOURCE_TYPE_SUB_RESOURCE, GURL("http://example.com/baz.php")); - ResourceHostMsg_RequestResource msg(0, 1, request); - filter_->OnMessageReceived(msg); - base::RunLoop().RunUntilIdle(); - - net::URLRequest* url_request( - host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1))); - ASSERT_TRUE(url_request); - - EXPECT_FALSE(url_request->load_flags() & - net::LOAD_SUPPORT_ASYNC_REVALIDATION); -} - -TEST_F(AsyncRevalidationManagerTest, - AsyncRevalidationNotSupportedAfterRedirect) { - static const char kRedirectHeaders[] = - "HTTP/1.1 302 MOVED\n" - "Location: http://example.com/var\n" - "\n"; - SetResponse(kRedirectHeaders, ""); - - MakeTestRequest(0, 1, GURL("http://example.com/baz")); - - net::URLRequest* url_request( - host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1))); - ASSERT_TRUE(url_request); - - EXPECT_FALSE(url_request->load_flags() & - net::LOAD_SUPPORT_ASYNC_REVALIDATION); -} - -// A NetworkDelegate that records the URLRequests as they are created. -class URLRequestRecordingNetworkDelegate : public net::TestNetworkDelegate { - public: - URLRequestRecordingNetworkDelegate() : requests_() {} - - net::URLRequest* NextRequest() { - EXPECT_FALSE(requests_.empty()); - if (requests_.empty()) - return nullptr; - net::URLRequest* request = requests_.front(); - EXPECT_TRUE(request); - requests_.pop_front(); - return request; - } - - bool NextRequestWasDestroyed() { - net::URLRequest* request = requests_.front(); - requests_.pop_front(); - return request == nullptr; - } - - bool IsEmpty() const { return requests_.empty(); } - - int OnBeforeURLRequest(net::URLRequest* request, - const net::CompletionCallback& callback, - GURL* new_url) override { - requests_.push_back(request); - return TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url); - } - - void OnURLRequestDestroyed(net::URLRequest* request) override { - for (auto*& recorded_request : requests_) { - if (recorded_request == request) - recorded_request = nullptr; - } - net::TestNetworkDelegate::OnURLRequestDestroyed(request); - } - - private: - std::deque<net::URLRequest*> requests_; - - DISALLOW_COPY_AND_ASSIGN(URLRequestRecordingNetworkDelegate); -}; - -class AsyncRevalidationManagerRecordingTest - : public AsyncRevalidationManagerTest { - public: - AsyncRevalidationManagerRecordingTest() - : AsyncRevalidationManagerTest( - base::WrapUnique(new URLRequestRecordingNetworkDelegate)) {} - - void TearDown() override { - EXPECT_TRUE(IsEmpty()); - AsyncRevalidationManagerTest::TearDown(); - } - - URLRequestRecordingNetworkDelegate* recording_network_delegate() const { - return static_cast<URLRequestRecordingNetworkDelegate*>( - network_delegate_.get()); - } - - bool NextRequestWasDestroyed() { - return recording_network_delegate()->NextRequestWasDestroyed(); - } - - net::URLRequest* NextRequest() { - return recording_network_delegate()->NextRequest(); - } - - bool IsEmpty() const { return recording_network_delegate()->IsEmpty(); } -}; - -// Verify that an async revalidation is actually created when needed. -TEST_F(AsyncRevalidationManagerRecordingTest, Issued) { - // Create the original request. - MakeTestRequest(0, 1, GURL("http://example.com/async-revalidate")); - - net::URLRequest* initial_request = NextRequest(); - ASSERT_TRUE(initial_request); - EXPECT_TRUE(initial_request->load_flags() & - net::LOAD_SUPPORT_ASYNC_REVALIDATION); - - net::URLRequest* async_request = NextRequest(); - ASSERT_TRUE(async_request); -} - -// Verify the the URL of the async revalidation matches the original request. -TEST_F(AsyncRevalidationManagerRecordingTest, URLMatches) { - // Create the original request. - MakeTestRequest(0, 1, GURL("http://example.com/async-revalidate/u")); - - // Discard the original request. - NextRequest(); - - net::URLRequest* async_request = NextRequest(); - ASSERT_TRUE(async_request); - EXPECT_EQ(GURL("http://example.com/async-revalidate/u"), - async_request->url()); -} - -TEST_F(AsyncRevalidationManagerRecordingTest, - AsyncRevalidationsDoNotSupportAsyncRevalidation) { - // Create the original request. - MakeTestRequest(0, 1, GURL("http://example.com/async-revalidate")); - - // Discard the original request. - NextRequest(); - - // Get the async revalidation request. - net::URLRequest* async_request = NextRequest(); - ASSERT_TRUE(async_request); - EXPECT_FALSE(async_request->load_flags() & - net::LOAD_SUPPORT_ASYNC_REVALIDATION); -} - -TEST_F(AsyncRevalidationManagerRecordingTest, AsyncRevalidationsNotDuplicated) { - // Create the original request. - MakeTestRequest(0, 1, GURL("http://example.com/async-revalidate")); - - // Discard the original request. - NextRequest(); - - // Get the async revalidation request. - net::URLRequest* async_request = NextRequest(); - EXPECT_TRUE(async_request); - - // Start a second request to the same URL. - MakeTestRequest(0, 2, GURL("http://example.com/async-revalidate")); - - // Discard the second request. - NextRequest(); - - // There should not be another async revalidation request. - EXPECT_TRUE(IsEmpty()); -} - -// Async revalidation to different URLs should not be treated as duplicates. -TEST_F(AsyncRevalidationManagerRecordingTest, - AsyncRevalidationsToSeparateURLsAreSeparate) { - // Create two requests to two URLs. - MakeTestRequest(0, 1, GURL("http://example.com/async-revalidate")); - MakeTestRequest(0, 2, GURL("http://example.com/async-revalidate2")); - - net::URLRequest* initial_request = NextRequest(); - ASSERT_TRUE(initial_request); - net::URLRequest* initial_async_revalidation = NextRequest(); - ASSERT_TRUE(initial_async_revalidation); - net::URLRequest* second_request = NextRequest(); - ASSERT_TRUE(second_request); - net::URLRequest* second_async_revalidation = NextRequest(); - ASSERT_TRUE(second_async_revalidation); - - EXPECT_EQ("http://example.com/async-revalidate", - initial_request->url().spec()); - EXPECT_EQ("http://example.com/async-revalidate", - initial_async_revalidation->url().spec()); - EXPECT_EQ("http://example.com/async-revalidate2", - second_request->url().spec()); - EXPECT_EQ("http://example.com/async-revalidate2", - second_async_revalidation->url().spec()); -} - -// Nothing after the first redirect leg has stale-while-revalidate applied. -// TODO(ricea): s-w-r should work with redirects. Change this test when it does. -TEST_F(AsyncRevalidationManagerRecordingTest, NoSWRAfterFirstRedirectLeg) { - MakeTestRequest(0, 1, GURL("http://example.com/redirect")); - - net::URLRequest* initial_request = NextRequest(); - EXPECT_TRUE(initial_request); - - EXPECT_FALSE(initial_request->load_flags() & - net::LOAD_SUPPORT_ASYNC_REVALIDATION); - - // An async revalidation happens for the redirect. It has no body, so it has - // already completed. - EXPECT_TRUE(NextRequestWasDestroyed()); - - // But no others. - EXPECT_TRUE(IsEmpty()); -} - -} // namespace - -} // namespace content
diff --git a/content/browser/loader/netlog_observer_unittest.cc b/content/browser/loader/netlog_observer_unittest.cc index 95ae275..ea03b52 100644 --- a/content/browser/loader/netlog_observer_unittest.cc +++ b/content/browser/loader/netlog_observer_unittest.cc
@@ -90,7 +90,6 @@ true, // report_raw_headers true, // is_async PREVIEWS_OFF, // previews_state - std::string(), // original_headers nullptr, // body false); // initiated_in_secure_context info->AssociateWithRequest(request_.get());
diff --git a/content/browser/loader/resource_dispatcher_host_impl.cc b/content/browser/loader/resource_dispatcher_host_impl.cc index c92db42c..15419f6 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.cc +++ b/content/browser/loader/resource_dispatcher_host_impl.cc
@@ -44,7 +44,6 @@ #include "content/browser/frame_host/navigation_request_info.h" #include "content/browser/frame_host/navigator.h" #include "content/browser/loader/async_resource_handler.h" -#include "content/browser/loader/async_revalidation_manager.h" #include "content/browser/loader/detachable_resource_handler.h" #include "content/browser/loader/intercepting_resource_handler.h" #include "content/browser/loader/loader_delegate.h" @@ -387,17 +386,6 @@ base::Unretained(this))); update_load_states_timer_.reset(new base::RepeatingTimer()); - - // stale-while-revalidate currently doesn't work with browser-side navigation. - // Only enable stale-while-revalidate if browser navigation is not enabled. - // - // TODO(ricea): Make stale-while-revalidate and browser-side navigation work - // together. Or disable stale-while-revalidate completely before browser-side - // navigation becomes the default. crbug.com/561610 - if (!IsBrowserSideNavigationEnabled() && - base::FeatureList::IsEnabled(features::kStaleWhileRevalidate)) { - async_revalidation_manager_.reset(new AsyncRevalidationManager); - } } ResourceDispatcherHostImpl::ResourceDispatcherHostImpl() @@ -495,13 +483,6 @@ #endif loaders_to_cancel.clear(); - - if (async_revalidation_manager_) { - // Cancelling async revalidations should not result in the creation of new - // requests. Do it before the CHECKs to ensure this does not happen. - async_revalidation_manager_->CancelAsyncRevalidationsForResourceContext( - context); - } } void ResourceDispatcherHostImpl::ClearLoginDelegateForRequest( @@ -644,28 +625,6 @@ new_url, loader->request(), info->GetContext(), response); } - net::URLRequest* request = loader->request(); - if (request->response_info().async_revalidation_required) { - // Async revalidation is only supported for the first redirect leg. - DCHECK_EQ(request->url_chain().size(), 1u); - DCHECK(async_revalidation_manager_); - - async_revalidation_manager_->BeginAsyncRevalidation(request, - scheduler_.get()); - } - - // Remove the LOAD_SUPPORT_ASYNC_REVALIDATION flag if it is present. - // It is difficult to create a URLRequest with the correct flags and headers - // for redirect legs other than the first one. Since stale-while-revalidate in - // combination with redirects isn't needed for experimental use, punt on it - // for now. - // TODO(ricea): Fix this before launching the feature. - if (request->load_flags() & net::LOAD_SUPPORT_ASYNC_REVALIDATION) { - int new_load_flags = - request->load_flags() & ~net::LOAD_SUPPORT_ASYNC_REVALIDATION; - request->SetLoadFlags(new_load_flags); - } - // Don't notify WebContents observers for requests known to be // downloads; they aren't really associated with the Webcontents. // Note that not all downloads are known before content sniffing. @@ -673,6 +632,7 @@ return; // Notify the observers on the UI thread. + net::URLRequest* request = loader->request(); std::unique_ptr<ResourceRedirectDetails> detail(new ResourceRedirectDetails( loader->request(), !!request->ssl_info().cert, @@ -693,12 +653,6 @@ info->GetChildID(), info->GetRouteID()); } - if (request->response_info().async_revalidation_required) { - DCHECK(async_revalidation_manager_); - async_revalidation_manager_->BeginAsyncRevalidation(request, - scheduler_.get()); - } - ProcessRequestForLinkHeaders(request); if (delegate_) @@ -1394,13 +1348,6 @@ load_flags |= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY; } - bool support_async_revalidation = - !is_sync_load && async_revalidation_manager_ && - AsyncRevalidationManager::QualifiesForAsyncRevalidation(request_data); - - if (support_async_revalidation) - load_flags |= net::LOAD_SUPPORT_ASYNC_REVALIDATION; - // Sync loads should have maximum priority and should be the only // requets that have the ignore limits flag set. if (is_sync_load) { @@ -1429,7 +1376,6 @@ GetPreviewsState(request_data.previews_state, delegate_, *new_request, resource_context, request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME), - support_async_revalidation ? request_data.headers : std::string(), request_data.request_body, request_data.initiated_in_secure_context); // Request takes ownership. extra_info->AssociateWithRequest(new_request.get()); @@ -1743,7 +1689,6 @@ false, // report_raw_headers true, // is_async previews_state, // previews_state - std::string(), // original_headers nullptr, // body false); // initiated_in_secure_context } @@ -2110,12 +2055,6 @@ true, // is_async GetPreviewsState(info.common_params.previews_state, delegate_, *new_request, resource_context, info.is_main_frame), - // The original_headers field is for stale-while-revalidate but the - // feature doesn't work with PlzNavigate, so it's just a placeholder - // here. - // TODO(ricea): Make the feature work with stale-while-revalidate - // and clean this up. - std::string(), // original_headers info.common_params.post_data, // TODO(mek): Currently initiated_in_secure_context is only used for // subresource requests, so it doesn't matter what value it gets here. @@ -2169,11 +2108,6 @@ BeginRequestInternal(std::move(new_request), std::move(handler)); } -void ResourceDispatcherHostImpl::EnableStaleWhileRevalidateForTesting() { - if (!async_revalidation_manager_) - async_revalidation_manager_.reset(new AsyncRevalidationManager); -} - void ResourceDispatcherHostImpl::SetLoaderDelegate( LoaderDelegate* loader_delegate) { loader_delegate_ = loader_delegate;
diff --git a/content/browser/loader/resource_dispatcher_host_impl.h b/content/browser/loader/resource_dispatcher_host_impl.h index 65f456b..dee74df 100644 --- a/content/browser/loader/resource_dispatcher_host_impl.h +++ b/content/browser/loader/resource_dispatcher_host_impl.h
@@ -58,7 +58,6 @@ namespace content { class AppCacheNavigationHandleCore; class AppCacheService; -class AsyncRevalidationManager; class LoaderDelegate; class NavigationURLLoaderImplCore; class NavigationUIData; @@ -276,10 +275,6 @@ return num_in_flight_requests_; } - // Turns on stale-while-revalidate support, regardless of command-line flags - // or experiment status. For unit tests only. - void EnableStaleWhileRevalidateForTesting(); - // Sets the LoaderDelegate, which must outlive this object. Ownership is not // transferred. The LoaderDelegate should be interacted with on the IO thread. void SetLoaderDelegate(LoaderDelegate* loader_delegate); @@ -759,10 +754,6 @@ bool allow_cross_origin_auth_prompt_; - // AsyncRevalidationManager is non-NULL if and only if - // stale-while-revalidate is enabled. - std::unique_ptr<AsyncRevalidationManager> async_revalidation_manager_; - typedef std::map<GlobalRequestID, base::ObserverList<ResourceMessageDelegate>*> DelegateMap; DelegateMap delegate_map_;
diff --git a/content/browser/loader/resource_request_info_impl.cc b/content/browser/loader/resource_request_info_impl.cc index 06f0521..2f4ffd4 100644 --- a/content/browser/loader/resource_request_info_impl.cc +++ b/content/browser/loader/resource_request_info_impl.cc
@@ -87,7 +87,6 @@ false, // report_raw_headers is_async, // is_async previews_state, // previews_state - std::string(), // original_headers nullptr, // body false); // initiated_in_secure_context info->AssociateWithRequest(request); @@ -154,7 +153,6 @@ bool report_raw_headers, bool is_async, PreviewsState previews_state, - const std::string& original_headers, const scoped_refptr<ResourceRequestBodyImpl> body, bool initiated_in_secure_context) : detachable_handler_(NULL), @@ -185,7 +183,6 @@ report_raw_headers_(report_raw_headers), is_async_(is_async), previews_state_(previews_state), - original_headers_(original_headers), body_(body), initiated_in_secure_context_(initiated_in_secure_context) {}
diff --git a/content/browser/loader/resource_request_info_impl.h b/content/browser/loader/resource_request_info_impl.h index e42630d..f6d4e45 100644 --- a/content/browser/loader/resource_request_info_impl.h +++ b/content/browser/loader/resource_request_info_impl.h
@@ -72,7 +72,6 @@ bool report_raw_headers, bool is_async, PreviewsState previews_state, - const std::string& original_headers, const scoped_refptr<ResourceRequestBodyImpl> body, bool initiated_in_secure_context); ~ResourceRequestInfoImpl() override; @@ -180,7 +179,6 @@ void set_do_not_prompt_for_login(bool do_not_prompt) { do_not_prompt_for_login_ = do_not_prompt; } - const std::string& original_headers() const { return original_headers_; } const scoped_refptr<ResourceRequestBodyImpl>& body() const { return body_; } void ResetBody(); @@ -236,7 +234,6 @@ bool report_raw_headers_; bool is_async_; PreviewsState previews_state_; - const std::string original_headers_; scoped_refptr<ResourceRequestBodyImpl> body_; bool initiated_in_secure_context_; std::unique_ptr<NavigationUIData> navigation_ui_data_;
diff --git a/content/browser/memory/memory_monitor_win.cc b/content/browser/memory/memory_monitor_win.cc index aa38c67..bf336c1 100644 --- a/content/browser/memory/memory_monitor_win.cc +++ b/content/browser/memory/memory_monitor_win.cc
@@ -44,7 +44,7 @@ int MemoryMonitorWin::GetFreeMemoryUntilCriticalMB() { base::SystemMemoryInfoKB mem_info = {}; delegate_->GetSystemMemoryInfo(&mem_info); - int free_mb = mem_info.free / kKBperMB; + int free_mb = mem_info.avail_phys / kKBperMB; free_mb -= target_free_mb_; return free_mb; }
diff --git a/content/browser/memory/memory_monitor_win_unittest.cc b/content/browser/memory/memory_monitor_win_unittest.cc index 0251fde..ea22ac3e 100644 --- a/content/browser/memory/memory_monitor_win_unittest.cc +++ b/content/browser/memory/memory_monitor_win_unittest.cc
@@ -17,7 +17,7 @@ TestMemoryMonitorWinDelegate() {} void SetFreeMemoryKB(int free_memory_kb) { - mem_info_.free = free_memory_kb; + mem_info_.avail_phys = free_memory_kb; } private:
diff --git a/content/public/android/BUILD.gn b/content/public/android/BUILD.gn index ce066f7..f7dce75 100644 --- a/content/public/android/BUILD.gn +++ b/content/public/android/BUILD.gn
@@ -9,8 +9,8 @@ interface_file = "java/src/org/chromium/content/common/common.aidl" import_include = [ "java/src" ] sources = [ - "java/src/org/chromium/content/common/IChildProcessCallback.aidl", "java/src/org/chromium/content/common/IChildProcessService.aidl", + "java/src/org/chromium/content/common/IGpuProcessCallback.aidl", ] } @@ -133,6 +133,7 @@ "java/src/org/chromium/content/browser/ContextSelectionProvider.java", "java/src/org/chromium/content/browser/DeviceUtils.java", "java/src/org/chromium/content/browser/FloatingActionModeCallback.java", + "java/src/org/chromium/content/browser/GpuProcessCallback.java", "java/src/org/chromium/content/browser/InterfaceRegistrarImpl.java", "java/src/org/chromium/content/browser/InterstitialPageDelegateAndroid.java", "java/src/org/chromium/content/browser/JavascriptInterface.java", @@ -332,6 +333,7 @@ "java/src/org/chromium/content/browser/ContentViewCore.java", "java/src/org/chromium/content/browser/ContentViewRenderView.java", "java/src/org/chromium/content/browser/ContentViewStatics.java", + "java/src/org/chromium/content/browser/GpuProcessCallback.java", "java/src/org/chromium/content/browser/InterfaceRegistrarImpl.java", "java/src/org/chromium/content/browser/InterstitialPageDelegateAndroid.java", "java/src/org/chromium/content/browser/MediaResourceGetter.java",
diff --git a/content/public/android/java/src/org/chromium/content/app/ChildProcessServiceImpl.java b/content/public/android/java/src/org/chromium/content/app/ChildProcessServiceImpl.java index 44762fb..a031f58d 100644 --- a/content/public/android/java/src/org/chromium/content/app/ChildProcessServiceImpl.java +++ b/content/public/android/java/src/org/chromium/content/app/ChildProcessServiceImpl.java
@@ -34,8 +34,8 @@ import org.chromium.base.process_launcher.FileDescriptorInfo; import org.chromium.content.browser.ChildProcessConstants; import org.chromium.content.common.ContentSwitches; -import org.chromium.content.common.IChildProcessCallback; import org.chromium.content.common.IChildProcessService; +import org.chromium.content.common.IGpuProcessCallback; import org.chromium.content.common.SurfaceWrapper; import java.util.concurrent.Semaphore; @@ -58,7 +58,7 @@ // Lock that protects the following members. private final Object mBinderLock = new Object(); - private IChildProcessCallback mCallback; + private IGpuProcessCallback mGpuCallback; // PID of the client of this service, set in bindToCaller(). private int mBoundCallingPid; @@ -124,7 +124,7 @@ } @Override - public int setupConnection(Bundle args, IChildProcessCallback callback) { + public int setupConnection(Bundle args, IBinder callback) { int callingPid = Binder.getCallingPid(); synchronized (mBinderLock) { if (mBoundCallingPid != callingPid) { @@ -137,7 +137,8 @@ return -1; } - mCallback = callback; + mGpuCallback = + callback != null ? IGpuProcessCallback.Stub.asInterface(callback) : null; getServiceInfo(args); return Process.myPid(); } @@ -377,7 +378,7 @@ @CalledByNative private void forwardSurfaceTextureForSurfaceRequest( UnguessableToken requestToken, SurfaceTexture surfaceTexture) { - if (mCallback == null) { + if (mGpuCallback == null) { Log.e(TAG, "No callback interface has been provided."); return; } @@ -385,7 +386,7 @@ Surface surface = new Surface(surfaceTexture); try { - mCallback.forwardSurfaceForSurfaceRequest(requestToken, surface); + mGpuCallback.forwardSurfaceForSurfaceRequest(requestToken, surface); } catch (RemoteException e) { Log.e(TAG, "Unable to call forwardSurfaceForSurfaceRequest: %s", e); return; @@ -397,13 +398,13 @@ @SuppressWarnings("unused") @CalledByNative private Surface getViewSurface(int surfaceId) { - if (mCallback == null) { + if (mGpuCallback == null) { Log.e(TAG, "No callback interface has been provided."); return null; } try { - SurfaceWrapper wrapper = mCallback.getViewSurface(surfaceId); + SurfaceWrapper wrapper = mGpuCallback.getViewSurface(surfaceId); return wrapper != null ? wrapper.getSurface() : null; } catch (RemoteException e) { Log.e(TAG, "Unable to call getViewSurface: %s", e);
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildProcessConnection.java b/content/public/android/java/src/org/chromium/content/browser/ChildProcessConnection.java index 7faea6de..901e780 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ChildProcessConnection.java +++ b/content/public/android/java/src/org/chromium/content/browser/ChildProcessConnection.java
@@ -4,11 +4,14 @@ package org.chromium.content.browser; +import android.os.IBinder; + import org.chromium.base.process_launcher.ChildProcessCreationParams; import org.chromium.base.process_launcher.FileDescriptorInfo; -import org.chromium.content.common.IChildProcessCallback; import org.chromium.content.common.IChildProcessService; +import javax.annotation.Nullable; + /** * Manages a connection between the browser activity and a child service. ChildProcessConnection is * responsible for estabilishing the connection (start()), closing it (stop()) and manipulating the @@ -82,12 +85,13 @@ * Setups the connection after it was started with start(). * @param commandLine (optional) will be ignored if the command line was already sent in start() * @param filesToBeMapped a list of file descriptors that should be registered - * @param processCallback used for status updates regarding this process connection + * @param callback optional client specified callbacks that the child can use to communicate + * with the parent process * @param connectionCallback will be called exactly once after the connection is set up or the * setup fails */ void setupConnection(String[] commandLine, FileDescriptorInfo[] filesToBeMapped, - IChildProcessCallback processCallback, ConnectionCallback connectionCallback); + @Nullable IBinder callback, ConnectionCallback connectionCallback); /** * Terminates the connection to IChildProcessService, closing all bindings. It is safe to call
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildProcessConnectionImpl.java b/content/public/android/java/src/org/chromium/content/browser/ChildProcessConnectionImpl.java index f6a0f8e..12bc41c 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ChildProcessConnectionImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/ChildProcessConnectionImpl.java
@@ -22,11 +22,12 @@ import org.chromium.base.VisibleForTesting; import org.chromium.base.process_launcher.ChildProcessCreationParams; import org.chromium.base.process_launcher.FileDescriptorInfo; -import org.chromium.content.common.IChildProcessCallback; import org.chromium.content.common.IChildProcessService; import java.io.IOException; +import javax.annotation.Nullable; + /** * Manages a connection between the browser activity and a child service. */ @@ -90,10 +91,10 @@ private static class ConnectionParams { final String[] mCommandLine; final FileDescriptorInfo[] mFilesToBeMapped; - final IChildProcessCallback mCallback; + final IBinder mCallback; - ConnectionParams(String[] commandLine, FileDescriptorInfo[] filesToBeMapped, - IChildProcessCallback callback) { + ConnectionParams( + String[] commandLine, FileDescriptorInfo[] filesToBeMapped, IBinder callback) { mCommandLine = commandLine; mFilesToBeMapped = filesToBeMapped; mCallback = callback; @@ -349,7 +350,7 @@ @Override public void setupConnection(String[] commandLine, FileDescriptorInfo[] filesToBeMapped, - IChildProcessCallback processCallback, ConnectionCallback connectionCallback) { + @Nullable IBinder callback, ConnectionCallback connectionCallback) { synchronized (mLock) { assert mConnectionParams == null; if (mServiceDisconnected) { @@ -360,8 +361,7 @@ try { TraceEvent.begin("ChildProcessConnectionImpl.setupConnection"); mConnectionCallback = connectionCallback; - mConnectionParams = - new ConnectionParams(commandLine, filesToBeMapped, processCallback); + mConnectionParams = new ConnectionParams(commandLine, filesToBeMapped, callback); // Run the setup if the service is already connected. If not, // doConnectionSetupLocked() will be called from onServiceConnected(). if (mServiceConnectComplete) {
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java index 81675a7..2433d7f0 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java +++ b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java
@@ -10,17 +10,16 @@ import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; +import android.os.IBinder; import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.text.TextUtils; -import android.view.Surface; import org.chromium.base.CommandLine; import org.chromium.base.CpuFeatures; import org.chromium.base.Log; import org.chromium.base.ThreadUtils; import org.chromium.base.TraceEvent; -import org.chromium.base.UnguessableToken; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; @@ -31,8 +30,6 @@ import org.chromium.content.app.PrivilegedProcessService; import org.chromium.content.app.SandboxedProcessService; import org.chromium.content.common.ContentSwitches; -import org.chromium.content.common.IChildProcessCallback; -import org.chromium.content.common.SurfaceWrapper; import java.io.IOException; import java.util.ArrayList; @@ -828,36 +825,8 @@ /** * This implementation is used to receive callbacks from the remote service. */ - private static IChildProcessCallback createCallback( - final int childProcessId, final int callbackType) { - return new IChildProcessCallback.Stub() { - @Override - public void forwardSurfaceForSurfaceRequest( - UnguessableToken requestToken, Surface surface) { - // Do not allow a malicious renderer to connect to a producer. This is only used - // from stream textures managed by the GPU process. - if (callbackType != CALLBACK_FOR_GPU_PROCESS) { - Log.e(TAG, "Illegal callback for non-GPU process."); - return; - } - - nativeCompleteScopedSurfaceRequest(requestToken, surface); - } - - @Override - public SurfaceWrapper getViewSurface(int surfaceId) { - // Do not allow a malicious renderer to get to our view surface. - if (callbackType != CALLBACK_FOR_GPU_PROCESS) { - Log.e(TAG, "Illegal callback for non-GPU process."); - return null; - } - Surface surface = ChildProcessLauncher.nativeGetViewSurface(surfaceId); - if (surface == null) { - return null; - } - return new SurfaceWrapper(surface); - } - }; + private static IBinder createCallback(int childProcessId, int callbackType) { + return callbackType == CALLBACK_FOR_GPU_PROCESS ? new GpuProcessCallback() : null; } static void logPidWarning(int pid, String message) { @@ -969,8 +938,5 @@ } private static native void nativeOnChildProcessStarted(long clientContext, int pid); - private static native void nativeCompleteScopedSurfaceRequest( - UnguessableToken requestToken, Surface surface); private static native boolean nativeIsSingleProcess(); - private static native Surface nativeGetViewSurface(int surfaceId); }
diff --git a/content/public/android/java/src/org/chromium/content/browser/GpuProcessCallback.java b/content/public/android/java/src/org/chromium/content/browser/GpuProcessCallback.java new file mode 100644 index 0000000..472f855 --- /dev/null +++ b/content/public/android/java/src/org/chromium/content/browser/GpuProcessCallback.java
@@ -0,0 +1,35 @@ +// 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. + +package org.chromium.content.browser; + +import android.view.Surface; + +import org.chromium.base.UnguessableToken; +import org.chromium.base.annotations.JNINamespace; +import org.chromium.content.common.IGpuProcessCallback; +import org.chromium.content.common.SurfaceWrapper; + +@JNINamespace("content") +class GpuProcessCallback extends IGpuProcessCallback.Stub { + GpuProcessCallback() {} + + @Override + public void forwardSurfaceForSurfaceRequest(UnguessableToken requestToken, Surface surface) { + nativeCompleteScopedSurfaceRequest(requestToken, surface); + } + + @Override + public SurfaceWrapper getViewSurface(int surfaceId) { + Surface surface = nativeGetViewSurface(surfaceId); + if (surface == null) { + return null; + } + return new SurfaceWrapper(surface); + } + + private static native void nativeCompleteScopedSurfaceRequest( + UnguessableToken requestToken, Surface surface); + private static native Surface nativeGetViewSurface(int surfaceId); +};
diff --git a/content/public/android/java/src/org/chromium/content/common/IChildProcessService.aidl b/content/public/android/java/src/org/chromium/content/common/IChildProcessService.aidl index 1f5ec5c38..ef517468 100644 --- a/content/public/android/java/src/org/chromium/content/common/IChildProcessService.aidl +++ b/content/public/android/java/src/org/chromium/content/common/IChildProcessService.aidl
@@ -4,8 +4,6 @@ package org.chromium.content.common; -import org.chromium.content.common.IChildProcessCallback; - import android.view.Surface; import android.os.Bundle; @@ -16,7 +14,7 @@ boolean bindToCaller(); // Sets up the initial IPC channel and returns the pid of the child process. - int setupConnection(in Bundle args, IChildProcessCallback callback); + int setupConnection(in Bundle args, IBinder callback); // Asks the child service to crash so that we can test the termination logic. void crashIntentionallyForTesting();
diff --git a/content/public/android/java/src/org/chromium/content/common/IChildProcessCallback.aidl b/content/public/android/java/src/org/chromium/content/common/IGpuProcessCallback.aidl similarity index 92% rename from content/public/android/java/src/org/chromium/content/common/IChildProcessCallback.aidl rename to content/public/android/java/src/org/chromium/content/common/IGpuProcessCallback.aidl index 4285e3d9..5b2de4c 100644 --- a/content/public/android/java/src/org/chromium/content/common/IChildProcessCallback.aidl +++ b/content/public/android/java/src/org/chromium/content/common/IGpuProcessCallback.aidl
@@ -7,7 +7,7 @@ import org.chromium.content.common.SurfaceWrapper; import android.view.Surface; -interface IChildProcessCallback { +interface IGpuProcessCallback { void forwardSurfaceForSurfaceRequest( in UnguessableToken requestToken, in Surface surface);
diff --git a/content/public/android/junit/src/org/chromium/content/browser/BindingManagerImplTest.java b/content/public/android/junit/src/org/chromium/content/browser/BindingManagerImplTest.java index e131814..6d74b56 100644 --- a/content/public/android/junit/src/org/chromium/content/browser/BindingManagerImplTest.java +++ b/content/public/android/junit/src/org/chromium/content/browser/BindingManagerImplTest.java
@@ -10,6 +10,7 @@ import android.app.Activity; import android.app.Application; +import android.os.IBinder; import android.util.Pair; import org.junit.Assert; @@ -24,7 +25,6 @@ import org.chromium.base.process_launcher.ChildProcessCreationParams; import org.chromium.base.process_launcher.FileDescriptorInfo; import org.chromium.base.test.util.Feature; -import org.chromium.content.common.IChildProcessCallback; import org.chromium.content.common.IChildProcessService; import org.chromium.testing.local.LocalRobolectricTestRunner; @@ -126,7 +126,7 @@ @Override public void setupConnection(String[] commandLine, FileDescriptorInfo[] filesToBeMapped, - IChildProcessCallback processCallback, ConnectionCallback connectionCallbacks) { + IBinder callback, ConnectionCallback connectionCallbacks) { throw new UnsupportedOperationException(); }
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index e64750b..1658d60 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -202,12 +202,6 @@ const base::Feature kSpeculativeLaunchServiceWorker{ "SpeculativeLaunchServiceWorker", base::FEATURE_DISABLED_BY_DEFAULT}; -// Enables implementation of the Cache-Control: stale-while-revalidate directive -// which permits servers to allow the use of stale resources while revalidation -// proceeds in the background. See http://crbug.com/348877 -const base::Feature kStaleWhileRevalidate{"StaleWhileRevalidate2", - base::FEATURE_DISABLED_BY_DEFAULT}; - // Throttle Blink timers in out-of-view cross origin frames. const base::Feature kTimerThrottlingForHiddenFrames{ "TimerThrottlingForHiddenFrames", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 7cd768b..142fa9cd 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -56,7 +56,6 @@ CONTENT_EXPORT extern const base::Feature kSharedArrayBuffer; CONTENT_EXPORT extern const base::Feature kSlimmingPaintInvalidation; CONTENT_EXPORT extern const base::Feature kSpeculativeLaunchServiceWorker; -CONTENT_EXPORT extern const base::Feature kStaleWhileRevalidate; CONTENT_EXPORT extern const base::Feature kTimerThrottlingForHiddenFrames; CONTENT_EXPORT extern const base::Feature kTokenBinding; CONTENT_EXPORT extern const base::Feature kTouchpadAndWheelScrollLatching;
diff --git a/content/renderer/dom_storage/local_storage_cached_area.cc b/content/renderer/dom_storage/local_storage_cached_area.cc index 77ab50b..2bb78e31 100644 --- a/content/renderer/dom_storage/local_storage_cached_area.cc +++ b/content/renderer/dom_storage/local_storage_cached_area.cc
@@ -24,14 +24,32 @@ namespace { +// Don't change or reorder any of the values in this enum, as these values +// are serialized on disk. +enum class StorageFormat : uint8_t { UTF16 = 0 }; + base::string16 Uint8VectorToString16(const std::vector<uint8_t>& input) { - return base::string16(reinterpret_cast<const base::char16*>(input.data()), - input.size() / sizeof(base::char16)); + // TODO(mek): Better error recovery when corrupt (or otherwise invalid) data + // is detected. + if (input.size() % sizeof(base::char16) != 1 || + input[0] != static_cast<uint8_t>(StorageFormat::UTF16)) { + VLOG(1) << "Corrupt data in localstorage"; + return base::string16(); + } + base::string16 result; + result.resize(input.size() / sizeof(base::char16)); + std::memcpy(reinterpret_cast<void*>(&result[0]), input.data() + 1, + input.size() - 1); + return result; } std::vector<uint8_t> String16ToUint8Vector(const base::string16& input) { const uint8_t* data = reinterpret_cast<const uint8_t*>(input.data()); - return std::vector<uint8_t>(data, data + input.size() * sizeof(base::char16)); + std::vector<uint8_t> result; + result.reserve(input.size() * sizeof(base::char16) + 1); + result.push_back(static_cast<uint8_t>(StorageFormat::UTF16)); + result.insert(result.end(), data, data + input.size() * sizeof(base::char16)); + return result; } class GetAllCallback : public mojom::LevelDBWrapperGetAllCallback {
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 6a03905..568b1c1 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -605,7 +605,6 @@ "../browser/indexed_db/mock_browsertest_indexed_db_class_factory.cc", "../browser/indexed_db/mock_browsertest_indexed_db_class_factory.h", "../browser/loader/async_resource_handler_browsertest.cc", - "../browser/loader/async_revalidation_manager_browsertest.cc", "../browser/loader/cross_site_resource_handler_browsertest.cc", "../browser/loader/reload_cache_control_browsertest.cc", "../browser/loader/resource_dispatcher_host_browsertest.cc", @@ -1140,8 +1139,6 @@ "../browser/indexed_db/mock_indexed_db_factory.h", "../browser/leveldb_wrapper_impl_unittest.cc", "../browser/loader/async_resource_handler_unittest.cc", - "../browser/loader/async_revalidation_driver_unittest.cc", - "../browser/loader/async_revalidation_manager_unittest.cc", "../browser/loader/detachable_resource_handler_unittest.cc", "../browser/loader/intercepting_resource_handler_unittest.cc", "../browser/loader/mime_sniffing_resource_handler_unittest.cc",
diff --git a/device/bluetooth/bluetooth_adapter_android.cc b/device/bluetooth/bluetooth_adapter_android.cc index 2155707..191abadf 100644 --- a/device/bluetooth/bluetooth_adapter_android.cc +++ b/device/bluetooth/bluetooth_adapter_android.cc
@@ -192,8 +192,8 @@ if (iter == devices_.end()) { // New device. is_new_device = true; - device_android_owner.reset( - BluetoothDeviceAndroid::Create(this, bluetooth_device_wrapper)); + device_android_owner = + BluetoothDeviceAndroid::Create(this, bluetooth_device_wrapper); device_android = device_android_owner.get(); } else { // Existing device.
diff --git a/device/bluetooth/bluetooth_device_android.cc b/device/bluetooth/bluetooth_device_android.cc index 22c1a0ef..766bd35 100644 --- a/device/bluetooth/bluetooth_device_android.cc +++ b/device/bluetooth/bluetooth_device_android.cc
@@ -34,14 +34,15 @@ } } // namespace -BluetoothDeviceAndroid* BluetoothDeviceAndroid::Create( +std::unique_ptr<BluetoothDeviceAndroid> BluetoothDeviceAndroid::Create( BluetoothAdapterAndroid* adapter, const JavaRef<jobject>& bluetooth_device_wrapper) { // Java Type: bluetoothDeviceWrapper - BluetoothDeviceAndroid* device = new BluetoothDeviceAndroid(adapter); + std::unique_ptr<BluetoothDeviceAndroid> device( + new BluetoothDeviceAndroid(adapter)); device->j_device_.Reset(Java_ChromeBluetoothDevice_create( - AttachCurrentThread(), reinterpret_cast<intptr_t>(device), + AttachCurrentThread(), reinterpret_cast<intptr_t>(device.get()), bluetooth_device_wrapper)); return device;
diff --git a/device/bluetooth/bluetooth_device_android.h b/device/bluetooth/bluetooth_device_android.h index 23b7fd0..228886d 100644 --- a/device/bluetooth/bluetooth_device_android.h +++ b/device/bluetooth/bluetooth_device_android.h
@@ -29,11 +29,7 @@ // // The ChromeBluetoothDevice instance will hold a Java reference // to |bluetooth_device_wrapper|. - // - // TODO(scheib): Return a std::unique_ptr<>, but then adapter will need to - // handle - // this correctly. http://crbug.com/506416 - static BluetoothDeviceAndroid* Create( + static std::unique_ptr<BluetoothDeviceAndroid> Create( BluetoothAdapterAndroid* adapter, const base::android::JavaRef<jobject>& bluetooth_device_wrapper); // Java Type: bluetoothDeviceWrapper
diff --git a/net/cert/cert_verify_proc_unittest.cc b/net/cert/cert_verify_proc_unittest.cc index 01454c17..fb6d5bb 100644 --- a/net/cert/cert_verify_proc_unittest.cc +++ b/net/cert/cert_verify_proc_unittest.cc
@@ -470,6 +470,7 @@ scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle(ee_cert->os_cert_handle(), intermediates); + ASSERT_TRUE(cert_chain); CertVerifyResult verify_result; int error = Verify(cert_chain.get(), "127.0.0.1", 0, NULL, @@ -525,6 +526,7 @@ intermediates.push_back(extra_cert->os_cert_handle()); scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle( server_cert->os_cert_handle(), intermediates); + ASSERT_TRUE(cert_chain); CertVerifyResult verify_result; int flags = 0; @@ -559,6 +561,7 @@ intermediates.push_back(intermediate_cert->os_cert_handle()); scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle( server_cert->os_cert_handle(), intermediates); + ASSERT_TRUE(cert_chain); CertVerifyResult verify_result; int flags = CertVerifier::VERIFY_REV_CHECKING_ENABLED; @@ -1028,6 +1031,7 @@ X509Certificate::OSCertHandles intermediates; scoped_refptr<X509Certificate> leaf = X509Certificate::CreateFromHandle( cert_list[0]->os_cert_handle(), intermediates); + ASSERT_TRUE(leaf); int flags = 0; CertVerifyResult verify_result; @@ -1085,6 +1089,7 @@ scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle( certs[0]->os_cert_handle(), intermediates); + ASSERT_TRUE(cert_chain); int flags = 0; CertVerifyResult verify_result;
diff --git a/net/cert/ct_objects_extractor_unittest.cc b/net/cert/ct_objects_extractor_unittest.cc index 8f88969..1073645 100644 --- a/net/cert/ct_objects_extractor_unittest.cc +++ b/net/cert/ct_objects_extractor_unittest.cc
@@ -30,6 +30,7 @@ std::string der_test_cert(ct::GetDerEncodedX509Cert()); test_cert_ = X509Certificate::CreateFromBytes(der_test_cert.data(), der_test_cert.length()); + ASSERT_TRUE(test_cert_); log_ = CTLogVerifier::Create(ct::GetTestPublicKey(), "testlog", "https://ct.example.com", "dns.example.com"); @@ -129,10 +130,12 @@ scoped_refptr<X509Certificate> subject_cert = X509Certificate::CreateFromBytes(der_subject_cert.data(), der_subject_cert.length()); + ASSERT_TRUE(subject_cert); std::string der_issuer_cert(ct::GetDerEncodedFakeOCSPResponseIssuerCert()); scoped_refptr<X509Certificate> issuer_cert = X509Certificate::CreateFromBytes(der_issuer_cert.data(), der_issuer_cert.length()); + ASSERT_TRUE(issuer_cert); std::string fake_sct_list = ct::GetFakeOCSPExtensionValue(); ASSERT_FALSE(fake_sct_list.empty()); @@ -151,6 +154,7 @@ scoped_refptr<X509Certificate> issuer_cert = X509Certificate::CreateFromBytes(der_issuer_cert.data(), der_issuer_cert.length()); + ASSERT_TRUE(issuer_cert); std::string ocsp_response = ct::GetDerEncodedFakeOCSPResponse(); @@ -166,6 +170,7 @@ scoped_refptr<X509Certificate> subject_cert = X509Certificate::CreateFromBytes(der_subject_cert.data(), der_subject_cert.length()); + ASSERT_TRUE(subject_cert); std::string ocsp_response = ct::GetDerEncodedFakeOCSPResponse();
diff --git a/net/cert/nss_cert_database_unittest.cc b/net/cert/nss_cert_database_unittest.cc index 4e3b60b4..2bcda9e 100644 --- a/net/cert/nss_cert_database_unittest.cc +++ b/net/cert/nss_cert_database_unittest.cc
@@ -107,8 +107,13 @@ for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list); !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) { - result.push_back(X509Certificate::CreateFromHandle( - node->cert, X509Certificate::OSCertHandles())); + scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle( + node->cert, X509Certificate::OSCertHandles()); + if (!cert) { + ADD_FAILURE() << "X509Certificate::CreateFromHandle failed"; + continue; + } + result.push_back(cert); } CERT_DestroyCertList(cert_list);
diff --git a/net/cert/nss_profile_filter_chromeos_unittest.cc b/net/cert/nss_profile_filter_chromeos_unittest.cc index 2de8039..2443ed3 100644 --- a/net/cert/nss_profile_filter_chromeos_unittest.cc +++ b/net/cert/nss_profile_filter_chromeos_unittest.cc
@@ -46,8 +46,13 @@ for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list); !CERT_LIST_END(node, cert_list); node = CERT_LIST_NEXT(node)) { - result.push_back(X509Certificate::CreateFromHandle( - node->cert, X509Certificate::OSCertHandles())); + scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle( + node->cert, X509Certificate::OSCertHandles()); + if (!cert) { + ADD_FAILURE() << "X509Certificate::CreateFromHandle failed"; + continue; + } + result.push_back(cert); } CERT_DestroyCertList(cert_list);
diff --git a/net/cert/x509_certificate_unittest.cc b/net/cert/x509_certificate_unittest.cc index d2974e56..6b2e04d 100644 --- a/net/cert/x509_certificate_unittest.cc +++ b/net/cert/x509_certificate_unittest.cc
@@ -271,6 +271,7 @@ scoped_refptr<X509Certificate> google_cert( X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(google_der), sizeof(google_der))); + ASSERT_TRUE(google_cert); static const uint8_t google_serial[16] = { 0x01,0x2a,0x39,0x76,0x0d,0x3f,0x4f,0xc9, @@ -287,6 +288,7 @@ X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(paypal_null_der), sizeof(paypal_null_der))); + ASSERT_TRUE(paypal_null_cert); static const uint8_t paypal_null_serial[3] = {0x00, 0xf0, 0x9b}; ASSERT_EQ(sizeof(paypal_null_serial), @@ -298,6 +300,7 @@ TEST(X509CertificateTest, SHA256FingerprintsCorrectly) { scoped_refptr<X509Certificate> google_cert(X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(google_der), sizeof(google_der))); + ASSERT_TRUE(google_cert); const SHA256HashValue google_sha256_fingerprint = { {0x21, 0xaf, 0x58, 0x74, 0xea, 0x6b, 0xad, 0xbd, 0xe4, 0xb3, 0xb1, @@ -328,18 +331,21 @@ scoped_refptr<X509Certificate> cert_chain1 = X509Certificate::CreateFromHandle(server_cert->os_cert_handle(), intermediates); + ASSERT_TRUE(cert_chain1); intermediates.clear(); intermediates.push_back(intermediate_cert2->os_cert_handle()); scoped_refptr<X509Certificate> cert_chain2 = X509Certificate::CreateFromHandle(server_cert->os_cert_handle(), intermediates); + ASSERT_TRUE(cert_chain2); // No intermediate CA certicates. intermediates.clear(); scoped_refptr<X509Certificate> cert_chain3 = X509Certificate::CreateFromHandle(server_cert->os_cert_handle(), intermediates); + ASSERT_TRUE(cert_chain3); SHA256HashValue cert_chain1_ca_fingerprint_256 = { {0x51, 0x15, 0x30, 0x49, 0x97, 0x54, 0xf8, 0xb4, 0x17, 0x41, 0x6b, @@ -530,6 +536,7 @@ scoped_refptr<X509Certificate> cert1(X509Certificate::CreateFromHandle( google_cert_handle, X509Certificate::OSCertHandles())); X509Certificate::FreeOSCertHandle(google_cert_handle); + ASSERT_TRUE(cert1); // Add the same certificate, but as a new handle. google_cert_handle = X509Certificate::CreateOSCertHandleFromBytes( @@ -537,6 +544,7 @@ scoped_refptr<X509Certificate> cert2(X509Certificate::CreateFromHandle( google_cert_handle, X509Certificate::OSCertHandles())); X509Certificate::FreeOSCertHandle(google_cert_handle); + ASSERT_TRUE(cert2); // A new X509Certificate should be returned. EXPECT_NE(cert1.get(), cert2.get()); @@ -558,6 +566,7 @@ google_cert_handle, intermediates)); X509Certificate::FreeOSCertHandle(google_cert_handle); X509Certificate::FreeOSCertHandle(thawte_cert_handle); + ASSERT_TRUE(cert3); // Test that the new certificate, even with intermediates, results in the // same underlying handle being used. @@ -609,10 +618,12 @@ scoped_refptr<X509Certificate> webkit_cert( X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(webkit_der), sizeof(webkit_der))); + ASSERT_TRUE(webkit_cert); scoped_refptr<X509Certificate> thawte_cert( X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(thawte_der), sizeof(thawte_der))); + ASSERT_TRUE(thawte_cert); X509Certificate::OSCertHandle google_handle; // Create object with no intermediates: @@ -621,6 +632,7 @@ X509Certificate::OSCertHandles intermediates1; scoped_refptr<X509Certificate> cert1; cert1 = X509Certificate::CreateFromHandle(google_handle, intermediates1); + ASSERT_TRUE(cert1); EXPECT_EQ(0u, cert1->GetIntermediateCertificates().size()); // Create object with 2 intermediates: @@ -629,6 +641,7 @@ intermediates2.push_back(thawte_cert->os_cert_handle()); scoped_refptr<X509Certificate> cert2; cert2 = X509Certificate::CreateFromHandle(google_handle, intermediates2); + ASSERT_TRUE(cert2); // Verify it has all the intermediates: const X509Certificate::OSCertHandles& cert2_intermediates = @@ -741,6 +754,7 @@ scoped_refptr<X509Certificate> cert_chain = X509Certificate::CreateFromHandle(policy_chain[0]->os_cert_handle(), intermediates); + ASSERT_TRUE(cert_chain); std::vector<std::string> issuers; @@ -907,6 +921,7 @@ // A cert is expected - make sure that one was parsed. ASSERT_LT(i, certs.size()); + ASSERT_TRUE(certs[i]); // Compare the parsed certificate with the expected certificate, by // comparing fingerprints.
diff --git a/net/cert/x509_util_unittest.cc b/net/cert/x509_util_unittest.cc index 51097796..2872051d 100644 --- a/net/cert/x509_util_unittest.cc +++ b/net/cert/x509_util_unittest.cc
@@ -282,6 +282,7 @@ scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(kCertificateDataDER), sizeof(kCertificateDataDER)); + ASSERT_TRUE(cert); std::string channel_bindings; ASSERT_TRUE( @@ -390,6 +391,7 @@ scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(kCertificateDataDER), sizeof(kCertificateDataDER)); + ASSERT_TRUE(cert); std::string channel_bindings; ASSERT_TRUE( @@ -506,6 +508,7 @@ scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(kCertificateDataDER), sizeof(kCertificateDataDER)); + ASSERT_TRUE(cert); std::string channel_bindings; ASSERT_TRUE( @@ -617,6 +620,7 @@ scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(kCertificateDataDER), sizeof(kCertificateDataDER)); + ASSERT_TRUE(cert); std::string channel_bindings; ASSERT_TRUE( @@ -717,6 +721,7 @@ scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(kCertificateDataDER), sizeof(kCertificateDataDER)); + ASSERT_TRUE(cert); std::string channel_bindings; ASSERT_FALSE(
diff --git a/net/socket/ssl_client_socket_pool_unittest.cc b/net/socket/ssl_client_socket_pool_unittest.cc index 26c722f..9f73603 100644 --- a/net/socket/ssl_client_socket_pool_unittest.cc +++ b/net/socket/ssl_client_socket_pool_unittest.cc
@@ -846,6 +846,7 @@ SSLSocketDataProvider ssl(ASYNC, OK); ssl.cert = X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(webkit_der), sizeof(webkit_der)); + ASSERT_TRUE(ssl.cert); ssl.next_proto = kProtoHTTP2; socket_factory_.AddSSLSocketDataProvider(&ssl); @@ -922,6 +923,7 @@ SSLSocketDataProvider ssl(ASYNC, OK); ssl.cert = X509Certificate::CreateFromBytes( reinterpret_cast<const char*>(webkit_der), sizeof(webkit_der)); + ASSERT_TRUE(ssl.cert); ssl.client_cert_sent = true; ssl.next_proto = kProtoHTTP2; TestIPPoolingDisabled(&ssl);
diff --git a/net/socket/ssl_client_socket_unittest.cc b/net/socket/ssl_client_socket_unittest.cc index 6e8ec25..44f4a9d 100644 --- a/net/socket/ssl_client_socket_unittest.cc +++ b/net/socket/ssl_client_socket_unittest.cc
@@ -2347,6 +2347,7 @@ CertVerifyResult verify_result; verify_result.verified_cert = X509Certificate::CreateFromHandle( certs[0]->os_cert_handle(), temp_intermediates); + ASSERT_TRUE(verify_result.verified_cert); // Add a rule that maps the server cert (A) to the chain of A->B->C2 // rather than A->B->C.
diff --git a/remoting/host/token_validator_base_unittest.cc b/remoting/host/token_validator_base_unittest.cc index 94b761a..ddff7557 100644 --- a/remoting/host/token_validator_base_unittest.cc +++ b/remoting/host/token_validator_base_unittest.cc
@@ -96,18 +96,22 @@ scoped_refptr<net::X509Certificate> cert_expired_5_minutes_ago = CreateFakeCert(now - base::TimeDelta::FromMinutes(10), now - base::TimeDelta::FromMinutes(5)); + ASSERT_TRUE(cert_expired_5_minutes_ago); scoped_refptr<net::X509Certificate> cert_start_5min_expire_5min = CreateFakeCert(now - base::TimeDelta::FromMinutes(5), now + base::TimeDelta::FromMinutes(5)); + ASSERT_TRUE(cert_start_5min_expire_5min); scoped_refptr<net::X509Certificate> cert_start_10min_expire_5min = CreateFakeCert(now - base::TimeDelta::FromMinutes(10), now + base::TimeDelta::FromMinutes(5)); + ASSERT_TRUE(cert_start_10min_expire_5min); scoped_refptr<net::X509Certificate> cert_start_5min_expire_10min = CreateFakeCert(now - base::TimeDelta::FromMinutes(5), now + base::TimeDelta::FromMinutes(10)); + ASSERT_TRUE(cert_start_5min_expire_10min); // No certificate. net::CertificateList certificates {};
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index dfb0659b..673bc0f 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -47,14 +47,6 @@ # --- End SPV2 Tests --- crbug.com/309675 compositing/gestures/gesture-tapHighlight-simple-longPress.html [ Failure ] -crbug.com/642581 compositing/direct-image-compositing.html [ NeedsRebaseline ] -crbug.com/642581 compositing/overflow/nested-render-surfaces-with-rotation.html [ NeedsRebaseline ] -crbug.com/642581 compositing/lots-of-img-layers.html [ NeedsRebaseline ] -crbug.com/642581 compositing/lots-of-img-layers-with-opacity.html [ NeedsRebaseline ] -crbug.com/642581 virtual/disable-spinvalidation/compositing/direct-image-compositing.html [ NeedsRebaseline ] -crbug.com/642581 virtual/disable-spinvalidation/compositing/overflow/nested-render-surfaces-with-rotation.html [ NeedsRebaseline ] -crbug.com/642581 virtual/disable-spinvalidation/compositing/lots-of-img-layers.html [ NeedsRebaseline ] -crbug.com/642581 virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity.html [ NeedsRebaseline ] crbug.com/309675 virtual/disable-spinvalidation/compositing/gestures/gesture-tapHighlight-simple-longPress.html [ Failure ] crbug.com/504613 crbug.com/524248 paint/images/image-backgrounds-not-antialiased.html [ Skip ]
diff --git a/third_party/WebKit/LayoutTests/compositing/overflow/nested-render-surfaces-with-rotation-expected.png b/third_party/WebKit/LayoutTests/compositing/overflow/nested-render-surfaces-with-rotation-expected.png index fdbfa36..7e616b7 100644 --- a/third_party/WebKit/LayoutTests/compositing/overflow/nested-render-surfaces-with-rotation-expected.png +++ b/third_party/WebKit/LayoutTests/compositing/overflow/nested-render-surfaces-with-rotation-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/compositing/direct-image-compositing-expected.png b/third_party/WebKit/LayoutTests/platform/linux/compositing/direct-image-compositing-expected.png index 72a1adb..f916069 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/compositing/direct-image-compositing-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/compositing/lots-of-img-layers-expected.png b/third_party/WebKit/LayoutTests/platform/linux/compositing/lots-of-img-layers-expected.png index 18f50143..1d5e388 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/compositing/lots-of-img-layers-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/WebKit/LayoutTests/platform/linux/compositing/lots-of-img-layers-with-opacity-expected.png index 06c334b9..504660f 100644 --- a/third_party/WebKit/LayoutTests/platform/linux/compositing/lots-of-img-layers-with-opacity-expected.png +++ b/third_party/WebKit/LayoutTests/platform/linux/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png new file mode 100644 index 0000000..f916069 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png new file mode 100644 index 0000000..1d5e388 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png new file mode 100644 index 0000000..504660f --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/linux/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/compositing/direct-image-compositing-expected.png b/third_party/WebKit/LayoutTests/platform/mac/compositing/direct-image-compositing-expected.png index d359506..5f3772f 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/compositing/direct-image-compositing-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/compositing/lots-of-img-layers-expected.png b/third_party/WebKit/LayoutTests/platform/mac/compositing/lots-of-img-layers-expected.png index 18f50143..1d5e388 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/compositing/lots-of-img-layers-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/WebKit/LayoutTests/platform/mac/compositing/lots-of-img-layers-with-opacity-expected.png index 06c334b9..504660f 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/compositing/lots-of-img-layers-with-opacity-expected.png +++ b/third_party/WebKit/LayoutTests/platform/mac/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png new file mode 100644 index 0000000..5f3772f --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png new file mode 100644 index 0000000..1d5e388 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png new file mode 100644 index 0000000..504660f --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/compositing/direct-image-compositing-expected.png b/third_party/WebKit/LayoutTests/platform/win/compositing/direct-image-compositing-expected.png index b181eb9..cd93685 100644 --- a/third_party/WebKit/LayoutTests/platform/win/compositing/direct-image-compositing-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/compositing/lots-of-img-layers-expected.png b/third_party/WebKit/LayoutTests/platform/win/compositing/lots-of-img-layers-expected.png index d6d7dee..a8afe292 100644 --- a/third_party/WebKit/LayoutTests/platform/win/compositing/lots-of-img-layers-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/WebKit/LayoutTests/platform/win/compositing/lots-of-img-layers-with-opacity-expected.png index 1c0567e..b9471ee1 100644 --- a/third_party/WebKit/LayoutTests/platform/win/compositing/lots-of-img-layers-with-opacity-expected.png +++ b/third_party/WebKit/LayoutTests/platform/win/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png new file mode 100644 index 0000000..cd93685 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/direct-image-compositing-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png new file mode 100644 index 0000000..a8afe292 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/lots-of-img-layers-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png b/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png new file mode 100644 index 0000000..b9471ee1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/disable-spinvalidation/compositing/lots-of-img-layers-with-opacity-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/virtual/disable-spinvalidation/compositing/overflow/nested-render-surfaces-with-rotation-expected.png b/third_party/WebKit/LayoutTests/virtual/disable-spinvalidation/compositing/overflow/nested-render-surfaces-with-rotation-expected.png new file mode 100644 index 0000000..7e616b7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/disable-spinvalidation/compositing/overflow/nested-render-surfaces-with-rotation-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-custom-sweep-snr.html b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-custom-sweep-snr.html index 9d263d4..12d089bd 100644 --- a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-custom-sweep-snr.html +++ b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-custom-sweep-snr.html
@@ -21,9 +21,8 @@ // The thresholds are experimentally determined. tester.setThresholds({ - snr: 1000, - maxDiff: 0, - diffCount: 0 + snr: 93.450, + maxDiff: 0.00004 }); tester.runTest(context, "custom", "Custom Oscillator with Exponential Sweep", task, should);
diff --git a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-sawtooth-sweep-snr.html b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-sawtooth-sweep-snr.html index e0ec7d8..8d90c61 100644 --- a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-sawtooth-sweep-snr.html +++ b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-sawtooth-sweep-snr.html
@@ -3,7 +3,7 @@ <head> <title>Test Oscillator Node: sawtooth</title> <script src="../../resources/testharness.js"></script> - <script src="../../resources/testharnessreport.js"></script> + <script src="../../resources/testharnessreport.js"></script> <script src="../resources/audit-util.js"></script> <script src="../resources/audit.js"></script> <script src="../resources/buffer-loader.js"></script> @@ -21,13 +21,11 @@ // The thresholds are experimentally determined. tester.setThresholds({ - snr: 1000, - maxDiff: 0, - diffCount: 0 + snr: 92.858, + maxDiff: 0.0001 }); tester.runTest(context, "sawtooth", - "Sawtooth Oscillator with Exponential Sweep", - task, should); + "Sawtooth Oscillator with Exponential Sweep", task, should); }); audit.run();
diff --git a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-sine-sweep-snr.html b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-sine-sweep-snr.html index d56ea415..e5937b7 100644 --- a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-sine-sweep-snr.html +++ b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-sine-sweep-snr.html
@@ -21,13 +21,11 @@ // The thresholds are experimentally determined. tester.setThresholds({ - snr: 1000, - maxDiff: 0, - diffCount: 0 + snr: 94.001, + maxDiff: 0.00006 }); tester.runTest(context, "sine", - "Sine Oscillator with Exponential Sweep", - task, should); + "Sine Oscillator with Exponential Sweep", task, should); }); audit.run();
diff --git a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-square-sweep-snr.html b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-square-sweep-snr.html index 3389a666..2a3d350 100644 --- a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-square-sweep-snr.html +++ b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-square-sweep-snr.html
@@ -21,9 +21,8 @@ // The thresholds are experimentally determined. tester.setThresholds({ - snr: 1000, - maxDiff: 0, - diffCount: 0 + snr: 93.325, + maxDiff: 0.00011 }); tester.runTest(context, "square", "Square Oscillator with Exponential Sweep", task, should);
diff --git a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-triangle-sweep-snr.html b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-triangle-sweep-snr.html index 9728229..5d0366d 100644 --- a/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-triangle-sweep-snr.html +++ b/third_party/WebKit/LayoutTests/webaudio/Oscillator/osc-triangle-sweep-snr.html
@@ -19,12 +19,10 @@ let context = new OfflineAudioContext(1, tester.sampleRate * tester.lengthInSeconds, tester.sampleRate); - // Thresholds for verifying the test passes. The thresholds are - // experimentally determined. + // The thresholds are experimentally determined. tester.setThresholds({ - snr: 1000, - maxDiff: 0, - diffCount: 0 + snr: 93.92, + maxDiff: 0.00005 }); tester.runTest(context, "triangle", "Triangle Oscillator with Exponential Sweep ", task, should);
diff --git a/third_party/WebKit/LayoutTests/webaudio/PeriodicWave/periodicwave-contexts.html b/third_party/WebKit/LayoutTests/webaudio/PeriodicWave/periodicwave-contexts.html index 9e16ba8e..2144ded4f 100644 --- a/third_party/WebKit/LayoutTests/webaudio/PeriodicWave/periodicwave-contexts.html +++ b/third_party/WebKit/LayoutTests/webaudio/PeriodicWave/periodicwave-contexts.html
@@ -33,8 +33,7 @@ // The thresholds are experimentally determined. tester.setThresholds({ snr: 80.00, - maxDiff: 4.06, - diffCount: 15827 + maxDiff: 4.06 }); tester.runTest(context, "sawtooth", "Sawtooth PeriodicWave Test", task, should);
diff --git a/third_party/WebKit/LayoutTests/webaudio/resources/audit.js b/third_party/WebKit/LayoutTests/webaudio/resources/audit.js index bd3051a5..ae615bd 100644 --- a/third_party/WebKit/LayoutTests/webaudio/resources/audit.js +++ b/third_party/WebKit/LayoutTests/webaudio/resources/audit.js
@@ -1191,15 +1191,19 @@ function loadFileFromUrl (fileUrl) { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); - xhr.open('GET', fileUrl); + xhr.open('GET', fileUrl, true); xhr.responseType = 'arraybuffer'; xhr.onload = () => { - if (xhr.status === 200) { + // |status = 0| is a workaround for the run-webkit-test server. We are + // speculating the server quits the transaction prematurely without + // completing the request. + if (xhr.status === 200 || xhr.status === 0) { resolve(xhr.response); } else { let errorMessage = 'loadFile: Request failed when loading ' + - fileUrl + '. (' + xhr.statusText + ')'; + fileUrl + '. ' + xhr.statusText + '. (status = ' + + xhr.status + ')'; if (reject) { reject(errorMessage); } else {
diff --git a/third_party/WebKit/LayoutTests/webaudio/resources/oscillator-testing.js b/third_party/WebKit/LayoutTests/webaudio/resources/oscillator-testing.js index 8454386..f2d8f9c 100644 --- a/third_party/WebKit/LayoutTests/webaudio/resources/oscillator-testing.js +++ b/third_party/WebKit/LayoutTests/webaudio/resources/oscillator-testing.js
@@ -43,10 +43,6 @@ // Max diff must be less than this to pass the test. var thresholdDiff = 0; -// Count the number of differences between the expected and actual result. The tests passes -// if the count is less than this threshold. -var thresholdDiffCount = 0; - // Mostly for debugging // An AudioBuffer for the reference (expected) result. @@ -123,11 +119,6 @@ maxError = Math.abs(diff); errorPosition = k; } - // The reference file is a 16-bit WAV file, so we will almost never get an exact match - // between it and the actual floating-point result. - if (diff > 0) { - diffCount++; - } } var snr = calculateSNR(signalPower, noisePower); @@ -136,11 +127,6 @@ should(maxError, "Maximum difference") .beLessThanOrEqualTo(thresholdDiff); - should(diffCount, - "Number of differences between actual and expected result out of " - + renderedData.length + " frames") - .beLessThanOrEqualTo(thresholdDiffCount); - var filename = "oscillator-" + oscType + "-actual.wav"; if (downloadAudioBuffer(renderedBuffer, filename, true)) should(true, "Saved reference file").message(filename, ""); @@ -161,7 +147,6 @@ lengthInSeconds: lengthInSeconds, thresholdSNR: thresholdSNR, thresholdDiff: thresholdDiff, - thresholdDiffCount: thresholdDiffCount, waveScaleFactor: waveScaleFactor, setThresholds: setThresholds, runTest: runTest,
diff --git a/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-expected.txt b/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-expected.txt index bf82aa1..2f9ec0b0 100644 --- a/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-expected.txt
@@ -33,10 +33,13 @@ PASS Suspending OAC with no argument rejected correctly with TypeError. PASS Start OAC rendering resolved correctly. PASS < [basic] All assertions passed. (total 20 assertions) +PASS > [load-file-in-should] Test Audit.loadFileFromUrl() within |should| assertion. +PASS Loading file within should().beResolved() resolved correctly. +PASS < [load-file-in-should] All assertions passed. (total 1 assertions) PASS > [dummy-label-string] PASS < [dummy-label-string] All assertions passed. (total 0 assertions) PASS > [dummy-label-object] PASS < [dummy-label-object] All assertions passed. (total 0 assertions) -PASS # AUDIT TASK RUNNER FINISHED: 4 tasks ran successfully. +PASS # AUDIT TASK RUNNER FINISHED: 5 tasks ran successfully. Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-failures-expected.txt b/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-failures-expected.txt index 36ff95f..edd8fd8 100644 --- a/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-failures-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-failures-expected.txt
@@ -90,6 +90,9 @@ [6] 7.0000000000000000e+0 8.0000000000000000e+2 7.9300000000000000e+2 9.9124999999999996e-1 0.0000000000000000e+0 assert_true: expected true got false FAIL < [numerical-failures] 11 out of 11 assertions were failed. assert_true: expected true got false -FAIL # AUDIT TASK RUNNER FINISHED: 2 out of 2 tasks were failed. assert_true: expected true got false +PASS > [load-file-in-should] Testing the failure handling of Audit.loadFileFromUrl(). +FAIL X Loading non-existent file within should().beResolved() rejected incorrectly with loadFile: Network failure when loading non-existent-audio-file.wav.. Got undefined. assert_true: expected true got false +FAIL < [load-file-in-should] 1 out of 1 assertions were failed. assert_true: expected true got false +FAIL # AUDIT TASK RUNNER FINISHED: 3 out of 3 tasks were failed. assert_true: expected true got false Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-failures.html b/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-failures.html index ea959d5..ccb863a 100644 --- a/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-failures.html +++ b/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit-failures.html
@@ -85,6 +85,20 @@ task.done(); }); + // Testing the failure handling of Audit.loadFileFromUrl(). + audit.define({ + label: 'load-file-in-should', + description: 'Testing the failure handling of Audit.loadFileFromUrl().' + }, (task, should) => { + let url = 'non-existent-audio-file.wav'; + let promise = should( + Audit.loadFileFromUrl(url), + 'Loading non-existent file within should().beResolved()') + .beResolved(); + promise.then(() => { task.done() }); + } + ); + // With no argument, this executes all tasks in the order defined. audit.run(); </script>
diff --git a/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit.html b/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit.html index 27bc852..adb2d785 100644 --- a/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit.html +++ b/third_party/WebKit/LayoutTests/webaudio/unit-tests/audit.html
@@ -65,6 +65,20 @@ } ); + // Test Audit.loadFileFromUrl() within |should| assertion. + // See: crbug.com/701813 + audit.define({ + label: 'load-file-in-should', + description: 'Test Audit.loadFileFromUrl() within |should| assertion.' + }, (task, should) => { + let url = '../resources/hyper-reality/laughter.wav'; + let promise = should(Audit.loadFileFromUrl(url), + 'Loading file within should().beResolved()') + .beResolved(); + promise.then(() => { task.done() }); + } + ); + // The task headline needs to be printed even if there is no description is // given. @@ -89,7 +103,8 @@ // You can enumerate tasks you want to execute in the order, or simply pass // no argument to run all the defined tasks. - audit.run('numerical', 'basic', 'dummy-label-string', 'dummy-label-object'); + audit.run('numerical', 'basic', 'load-file-in-should', + 'dummy-label-string', 'dummy-label-object'); </script> </body> </html>