diff --git a/DEPS b/DEPS index 8813ee7..324913e 100644 --- a/DEPS +++ b/DEPS
@@ -34,20 +34,20 @@ 'llvm_url': 'http://src.chromium.org/llvm-project', 'llvm_git': 'https://llvm.googlesource.com', 'webkit_trunk': 'http://src.chromium.org/blink/trunk', - 'webkit_revision': 'dd1bddd5a971f4c31bd2b7927e785910df34fbca', # from svn revision 191886 + 'webkit_revision': 'cb8017b2b8cb19a3b65611d715045d96dd2fa637', # from svn revision 191906 'chromium_git': 'https://chromium.googlesource.com', 'chromiumos_git': 'https://chromium.googlesource.com/chromiumos', 'pdfium_git': 'https://pdfium.googlesource.com', 'skia_git': 'https://skia.googlesource.com', 'boringssl_git': 'https://boringssl.googlesource.com', - 'libvpx_revision': '763fe7ad8db602969665be93e7f873a5f6d4862e', + 'libvpx_revision': 'f80cf581e6e56ec3b28b118aebf98499b6bc156d', 'sfntly_revision': '1bdaae8fc788a5ac8936d68bf24f37d977a13dac', - 'skia_revision': '8c6a9778dccc8a717175d3df1ca3105663573df0', + 'skia_revision': 'dfdec78a5d02e8690998741a9fe5b71a08ca3232', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and V8 without interference from each other. 'v8_branch': 'trunk', - 'v8_revision': 'b04b0eada17b5c00446ab1d915d7a4dd2242f45c', + 'v8_revision': '1462eb649673cd78659c1f83dfe5ecbcdab46669', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling WebRTC # and V8 without interference from each other. @@ -107,7 +107,7 @@ deps = { 'src/breakpad/src': - Var('chromium_git') + '/external/google-breakpad/src.git' + '@' + 'd1f8b74d65c28d29e8e75df7d70780ec7f6e9216', # from svn revision 1432 + Var('chromium_git') + '/external/google-breakpad/src.git' + '@' + '2c37c225e729d6ada72d5ffd808406db9c916985', # from svn revision 1434 'src/buildtools': Var('chromium_git') + '/chromium/buildtools.git' + '@' + Var('buildtools_revision'), @@ -128,7 +128,7 @@ Var('chromium_git') + '/external/colorama.git' + '@' + '799604a1041e9b3bc5d2789ecbd7e8db2e18e6b8', 'src/third_party/crashpad/crashpad': - Var('chromium_git') + '/crashpad/crashpad.git' + '@' + '1d022a86db566613c11ff03ad6e791f9c01ffe88', + Var('chromium_git') + '/crashpad/crashpad.git' + '@' + '82bebb11de699550a36bf411737d01880e4a16a7', 'src/third_party/trace-viewer': Var('chromium_git') + '/external/trace-viewer.git' + '@' + 'b3571f53f1bd7870ffd293a4bfca6473a21193d2', @@ -164,7 +164,7 @@ Var('chromium_git') + '/external/grit-i18n.git' + '@' + '0287c187b11ed53590254e4d817e836a44a7a1a7', # from svn revision 186 'src/tools/gyp': - Var('chromium_git') + '/external/gyp.git' + '@' + '4a9b712d5cb4a5ba7a9950128a7219569caf7263', + Var('chromium_git') + '/external/gyp.git' + '@' + 'd174d75bf69c682cb62af9187879e01513b35e52', 'src/tools/swarming_client': Var('chromium_git') + '/external/swarming.client.git' + '@' + Var('swarming_revision'), @@ -209,7 +209,7 @@ Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + 'b3dc5aa44575049edf6b24e34578487dfaade6a4', 'src/third_party/libjingle/source/talk': - Var('chromium_git') + '/external/webrtc/trunk/talk.git' + '@' + '226ac7b3bbda1ceacc16cd2e12d0ad222d657c53', + Var('chromium_git') + '/external/webrtc/trunk/talk.git' + '@' + '98747d0e8f694435b3deb5d833bb8fb93d44673b', 'src/third_party/usrsctp/usrsctplib': Var('chromium_git') + '/external/usrsctplib.git' + '@' + '13718c7b9fd376fde092cbd3c5347d15059ac652', # from svn revision 9167 @@ -233,7 +233,7 @@ Var('chromium_git') + '/native_client/src/third_party/scons-2.0.1.git' + '@' + '1c1550e17fc26355d08627fbdec13d8291227067', 'src/third_party/webrtc': - Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + '44373d2118368d3800313cd1fc64f301aaaf25aa', + Var('chromium_git') + '/external/webrtc/trunk/webrtc.git' + '@' + 'bccd5aa6661524c5ff006b860f2b5fb66508b0d8', 'src/third_party/openmax_dl': Var('chromium_git') + '/external/webrtc/deps/third_party/openmax.git' + '@' + Var('openmax_dl_revision'),
diff --git a/WATCHLISTS b/WATCHLISTS index 2f82d90a..1f70dedf 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -1029,6 +1029,7 @@ 'sync': ['tim+watch@chromium.org', 'maniscalco+watch@chromium.org', 'maxbogue+watch@chromium.org', + 'plaree+watch@chromium.org', 'pvalenzuela+watch@chromium.org', 'zea+watch@chromium.org'], 'syncfs': ['kinuko+fileapi@chromium.org',
diff --git a/android_webview/browser/icon_helper.cc b/android_webview/browser/icon_helper.cc index c4c0c3d..320fcd4 100644 --- a/android_webview/browser/icon_helper.cc +++ b/android_webview/browser/icon_helper.cc
@@ -74,6 +74,7 @@ web_contents()->DownloadImage(i->icon_url, true, // Is a favicon 0, // No maximum size + false, // Normal cache policy base::Bind( &IconHelper::DownloadFaviconCallback, base::Unretained(this))); break;
diff --git a/ash/test/test_suite.cc b/ash/test/test_suite.cc index 1b7eb46..80d61f4 100644 --- a/ash/test/test_suite.cc +++ b/ash/test/test_suite.cc
@@ -52,6 +52,9 @@ // output, it'll pass regardless of the system language. ui::ResourceBundle::InitSharedInstanceWithLocale( "en-US", NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES); + + base::DiscardableMemoryShmemAllocator::SetInstance( + &discardable_memory_allocator_); } void AuraShellTestSuite::Shutdown() {
diff --git a/ash/test/test_suite.h b/ash/test/test_suite.h index 33fcd23..e2e0957 100644 --- a/ash/test/test_suite.h +++ b/ash/test/test_suite.h
@@ -6,6 +6,7 @@ #define ASH_TEST_TEST_SUITE_H_ #include "base/compiler_specific.h" +#include "base/test/test_discardable_memory_shmem_allocator.h" #include "base/test/test_suite.h" #if defined(OS_WIN) @@ -29,6 +30,8 @@ #if defined(OS_WIN) scoped_ptr<base::win::ScopedCOMInitializer> com_initializer_; #endif + + base::TestDiscardableMemoryShmemAllocator discardable_memory_allocator_; }; } // namespace test
diff --git a/base/BUILD.gn b/base/BUILD.gn index bd81cf6..f103446 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -9,6 +9,10 @@ import("//build/config/android/rules.gni") } +config("base_implementation") { + defines = [ "BASE_IMPLEMENTATION" ] +} + source_set("base_paths") { sources = [ "base_paths.cc", @@ -34,7 +38,7 @@ ] } - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ ":base_implementation" ] deps = [ "//base/memory", @@ -607,7 +611,7 @@ "sys_info_openbsd.cc", ] - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ ":base_implementation" ] deps = [ ":base_static", @@ -630,7 +634,7 @@ # Allow more direct string conversions on platforms with native utf8 # strings if (is_mac || is_ios || is_chromeos) { - defines += [ "SYSTEM_NATIVE_UTF8" ] + defines = [ "SYSTEM_NATIVE_UTF8" ] } if (is_android) { @@ -1132,7 +1136,6 @@ "mac/scoped_sending_event_unittest.mm", "md5_unittest.cc", "memory/aligned_memory_unittest.cc", - "memory/discardable_memory_unittest.cc", "memory/discardable_shared_memory_unittest.cc", "memory/linked_ptr_unittest.cc", "memory/ref_counted_memory_unittest.cc", @@ -1280,8 +1283,6 @@ "win/wrapped_window_proc_unittest.cc", ] - defines = [] - deps = [ ":base", ":i18n", @@ -1301,7 +1302,7 @@ # Allow more direct string conversions on platforms with native utf8 # strings if (is_mac || is_ios || is_chromeos) { - defines += [ "SYSTEM_NATIVE_UTF8" ] + defines = [ "SYSTEM_NATIVE_UTF8" ] } if (is_android) {
diff --git a/base/base.gyp b/base/base.gyp index 5f640d8..c7a2481 100644 --- a/base/base.gyp +++ b/base/base.gyp
@@ -541,7 +541,6 @@ 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', - 'memory/discardable_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/ref_counted_memory_unittest.cc', @@ -976,6 +975,8 @@ 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', + 'test/test_discardable_memory_shmem_allocator.cc', + 'test/test_discardable_memory_shmem_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc',
diff --git a/base/debug/BUILD.gn b/base/debug/BUILD.gn index 0de41ad..8ed623b 100644 --- a/base/debug/BUILD.gn +++ b/base/debug/BUILD.gn
@@ -55,7 +55,7 @@ ] } - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ "//base:base_implementation" ] deps = [ "//base/memory", @@ -63,7 +63,7 @@ ] if (is_linux) { - defines += [ "USE_SYMBOLIZE" ] + defines = [ "USE_SYMBOLIZE" ] deps += [ "//base/third_party/symbolize" ] }
diff --git a/base/json/BUILD.gn b/base/json/BUILD.gn index 0310ea9..70830c15 100644 --- a/base/json/BUILD.gn +++ b/base/json/BUILD.gn
@@ -27,7 +27,7 @@ ] } - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ "//base:base_implementation" ] deps = [ "//base/memory",
diff --git a/base/memory/BUILD.gn b/base/memory/BUILD.gn index 7b606d6..3d4c22cd 100644 --- a/base/memory/BUILD.gn +++ b/base/memory/BUILD.gn
@@ -54,7 +54,7 @@ sources -= [ "shared_memory_nacl.cc" ] } - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ "//base:base_implementation" ] visibility = [ "//base/*" ] }
diff --git a/base/memory/discardable_memory_shmem_allocator.cc b/base/memory/discardable_memory_shmem_allocator.cc index 761204f..a87c58d4 100644 --- a/base/memory/discardable_memory_shmem_allocator.cc +++ b/base/memory/discardable_memory_shmem_allocator.cc
@@ -11,45 +11,6 @@ namespace base { namespace { -class DiscardableMemoryShmemChunkImpl : public DiscardableMemoryShmemChunk { - public: - explicit DiscardableMemoryShmemChunkImpl( - scoped_ptr<DiscardableSharedMemory> shared_memory) - : shared_memory_(shared_memory.Pass()) {} - - // Overridden from DiscardableMemoryShmemChunk: - bool Lock() override { return false; } - void Unlock() override { - shared_memory_->Unlock(0, 0); - shared_memory_.reset(); - } - void* Memory() const override { return shared_memory_->memory(); } - - private: - scoped_ptr<DiscardableSharedMemory> shared_memory_; - - DISALLOW_COPY_AND_ASSIGN(DiscardableMemoryShmemChunkImpl); -}; - -// Default allocator implementation that allocates in-process -// DiscardableSharedMemory instances. -class DiscardableMemoryShmemAllocatorImpl - : public DiscardableMemoryShmemAllocator { - public: - // Overridden from DiscardableMemoryShmemAllocator: - scoped_ptr<DiscardableMemoryShmemChunk> - AllocateLockedDiscardableMemory(size_t size) override { - scoped_ptr<DiscardableSharedMemory> memory(new DiscardableSharedMemory); - if (!memory->CreateAndMap(size)) - return nullptr; - - return make_scoped_ptr(new DiscardableMemoryShmemChunkImpl(memory.Pass())); - } -}; - -LazyInstance<DiscardableMemoryShmemAllocatorImpl>::Leaky g_default_allocator = - LAZY_INSTANCE_INITIALIZER; - DiscardableMemoryShmemAllocator* g_allocator = nullptr; } // namespace @@ -69,9 +30,7 @@ // static DiscardableMemoryShmemAllocator* DiscardableMemoryShmemAllocator::GetInstance() { - if (!g_allocator) - g_allocator = g_default_allocator.Pointer(); - + DCHECK(g_allocator); return g_allocator; }
diff --git a/base/memory/discardable_memory_unittest.cc b/base/memory/discardable_memory_unittest.cc deleted file mode 100644 index 60750746..0000000 --- a/base/memory/discardable_memory_unittest.cc +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/memory/discardable_memory.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace base { -namespace { - -const size_t kSize = 1024; - -// Test Lock() and Unlock() functionalities. -TEST(DiscardableMemoryTest, LockAndUnLock) { - const scoped_ptr<DiscardableMemory> memory( - DiscardableMemory::CreateLockedMemory(kSize)); - ASSERT_TRUE(memory); - void* addr = memory->Memory(); - EXPECT_NE(nullptr, addr); - memory->Unlock(); -} - -// Test delete a discardable memory while it is locked. -TEST(DiscardableMemoryTest, DeleteWhileLocked) { - const scoped_ptr<DiscardableMemory> memory( - DiscardableMemory::CreateLockedMemory(kSize)); - ASSERT_TRUE(memory); -} - -#if !defined(NDEBUG) && !defined(OS_ANDROID) -// Death tests are not supported with Android APKs. -TEST(DiscardableMemoryTest, UnlockedMemoryAccessCrashesInDebugMode) { - const scoped_ptr<DiscardableMemory> memory( - DiscardableMemory::CreateLockedMemory(kSize)); - ASSERT_TRUE(memory); - memory->Unlock(); - ASSERT_DEATH_IF_SUPPORTED( - { *static_cast<int*>(memory->Memory()) = 0xdeadbeef; }, ".*"); -} -#endif - -// Test behavior when creating enough instances that could use up a 32-bit -// address space. -// This is disabled under AddressSanitizer on Windows as it crashes (by design) -// on OOM. See http://llvm.org/PR22026 for the details. -#if !defined(ADDRESS_SANITIZER) || !defined(OS_WIN) -TEST(DiscardableMemoryTest, AddressSpace) { - const size_t kLargeSize = 4 * 1024 * 1024; // 4MiB. - const size_t kNumberOfInstances = 1024 + 1; // >4GiB total. - - scoped_ptr<DiscardableMemory> instances[kNumberOfInstances]; - for (auto& memory : instances) { - memory = DiscardableMemory::CreateLockedMemory(kLargeSize); - ASSERT_TRUE(memory); - void* addr = memory->Memory(); - EXPECT_NE(nullptr, addr); - memory->Unlock(); - } -} -#endif - -} // namespace -} // namespace base
diff --git a/base/metrics/BUILD.gn b/base/metrics/BUILD.gn index 804e59b..0202637 100644 --- a/base/metrics/BUILD.gn +++ b/base/metrics/BUILD.gn
@@ -37,7 +37,7 @@ sources -= [ "field_trial.cc" ] } - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ "//base:base_implementation" ] deps = [ "//base/debug",
diff --git a/base/process/BUILD.gn b/base/process/BUILD.gn index 125b4515..e570647e 100644 --- a/base/process/BUILD.gn +++ b/base/process/BUILD.gn
@@ -94,7 +94,7 @@ ] } - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ "//base:base_implementation" ] deps = [ "//base/memory",
diff --git a/base/test/BUILD.gn b/base/test/BUILD.gn index 55e710db..f5d2e4c9 100644 --- a/base/test/BUILD.gn +++ b/base/test/BUILD.gn
@@ -81,6 +81,8 @@ "simple_test_tick_clock.h", "task_runner_test_template.cc", "task_runner_test_template.h", + "test_discardable_memory_shmem_allocator.cc", + "test_discardable_memory_shmem_allocator.h", "test_file_util.cc", "test_file_util.h", "test_file_util_android.cc",
diff --git a/base/test/test_discardable_memory_shmem_allocator.cc b/base/test/test_discardable_memory_shmem_allocator.cc new file mode 100644 index 0000000..24185a2 --- /dev/null +++ b/base/test/test_discardable_memory_shmem_allocator.cc
@@ -0,0 +1,40 @@ +// 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 "base/test/test_discardable_memory_shmem_allocator.h" + +#include <stdint.h> + +namespace base { +namespace { + +class DiscardableMemoryShmemChunkImpl : public DiscardableMemoryShmemChunk { + public: + explicit DiscardableMemoryShmemChunkImpl(size_t size) + : memory_(new uint8_t[size]) {} + + // Overridden from DiscardableMemoryShmemChunk: + bool Lock() override { return false; } + void Unlock() override {} + void* Memory() const override { return memory_.get(); } + + private: + scoped_ptr<uint8_t[]> memory_; +}; + +} // namespace + +TestDiscardableMemoryShmemAllocator::TestDiscardableMemoryShmemAllocator() { +} + +TestDiscardableMemoryShmemAllocator::~TestDiscardableMemoryShmemAllocator() { +} + +scoped_ptr<DiscardableMemoryShmemChunk> +TestDiscardableMemoryShmemAllocator::AllocateLockedDiscardableMemory( + size_t size) { + return make_scoped_ptr(new DiscardableMemoryShmemChunkImpl(size)); +} + +} // namespace base
diff --git a/base/test/test_discardable_memory_shmem_allocator.h b/base/test/test_discardable_memory_shmem_allocator.h new file mode 100644 index 0000000..a40960e --- /dev/null +++ b/base/test/test_discardable_memory_shmem_allocator.h
@@ -0,0 +1,28 @@ +// 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 BASE_TEST_TEST_DISCARDABLE_MEMORY_SHMEM_ALLOCATOR_H_ +#define BASE_TEST_TEST_DISCARDABLE_MEMORY_SHMEM_ALLOCATOR_H_ + +#include "base/memory/discardable_memory_shmem_allocator.h" + +namespace base { + +class TestDiscardableMemoryShmemAllocator + : public DiscardableMemoryShmemAllocator { + public: + TestDiscardableMemoryShmemAllocator(); + ~TestDiscardableMemoryShmemAllocator() override; + + // Overridden from DiscardableMemoryShmemAllocator: + scoped_ptr<DiscardableMemoryShmemChunk> AllocateLockedDiscardableMemory( + size_t size) override; + + private: + DISALLOW_COPY_AND_ASSIGN(TestDiscardableMemoryShmemAllocator); +}; + +} // namespace base + +#endif // BASE_TEST_TEST_DISCARDABLE_MEMORY_SHMEM_ALLOCATOR_H_
diff --git a/base/third_party/nspr/BUILD.gn b/base/third_party/nspr/BUILD.gn index a67e168..034f37b2 100644 --- a/base/third_party/nspr/BUILD.gn +++ b/base/third_party/nspr/BUILD.gn
@@ -12,7 +12,7 @@ # In GYP this project is part of base, so it uses the base implementation # define. TODO(brettw) rename this define. - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ "//base:base_implementation" ] if (is_android && !is_debug) { configs -= [ "//build/config/compiler:optimize" ]
diff --git a/base/trace_event/BUILD.gn b/base/trace_event/BUILD.gn index eec607b..10f7ec9 100644 --- a/base/trace_event/BUILD.gn +++ b/base/trace_event/BUILD.gn
@@ -41,7 +41,7 @@ ] } - defines = [ "BASE_IMPLEMENTATION" ] + configs += [ "//base:base_implementation" ] deps = [ "//base/debug",
diff --git a/build/common.gypi b/build/common.gypi index 515f50a..0b9f1df 100644 --- a/build/common.gypi +++ b/build/common.gypi
@@ -581,7 +581,7 @@ # Use experimental lld linker instead of the platform's default linker. 'use_lld%': 0, - # Enable plug-in installation by default. + # Enable plugin installation by default. 'enable_plugin_installation%': 1, # Specifies whether to use canvas_skia.cc in place of platform
diff --git a/cc/BUILD.gn b/cc/BUILD.gn index bf77c0e..2327db0 100644 --- a/cc/BUILD.gn +++ b/cc/BUILD.gn
@@ -285,6 +285,8 @@ "output/render_surface_filters.h", "output/renderer.cc", "output/renderer.h", + "output/renderer_capabilities.cc", + "output/renderer_capabilities.h", "output/renderer_settings.cc", "output/renderer_settings.h", "output/shader.cc",
diff --git a/cc/cc.gyp b/cc/cc.gyp index bc83b1f..9dbc0f3 100644 --- a/cc/cc.gyp +++ b/cc/cc.gyp
@@ -311,6 +311,8 @@ 'output/render_surface_filters.h', 'output/renderer.cc', 'output/renderer.h', + 'output/renderer_capabilities.cc', + 'output/renderer_capabilities.h', 'output/renderer_settings.cc', 'output/renderer_settings.h', 'output/shader.cc',
diff --git a/cc/layers/picture_layer.cc b/cc/layers/picture_layer.cc index 80d36d8..672aab4 100644 --- a/cc/layers/picture_layer.cc +++ b/cc/layers/picture_layer.cc
@@ -9,6 +9,7 @@ #include "cc/layers/picture_layer_impl.h" #include "cc/resources/display_list_recording_source.h" #include "cc/resources/picture_pile.h" +#include "cc/trees/layer_tree_host.h" #include "cc/trees/layer_tree_impl.h" #include "third_party/skia/include/core/SkPictureRecorder.h" #include "ui/gfx/geometry/rect_conversions.h"
diff --git a/cc/output/overlay_unittest.cc b/cc/output/overlay_unittest.cc index 9090621..75fbb6e 100644 --- a/cc/output/overlay_unittest.cc +++ b/cc/output/overlay_unittest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "cc/base/scoped_ptr_vector.h" +#include "cc/output/compositor_frame_metadata.h" #include "cc/output/gl_renderer.h" #include "cc/output/output_surface.h" #include "cc/output/output_surface_client.h"
diff --git a/cc/output/renderer.h b/cc/output/renderer.h index c92ce6ff..b775285 100644 --- a/cc/output/renderer.h +++ b/cc/output/renderer.h
@@ -8,7 +8,9 @@ #include "base/basictypes.h" #include "cc/base/cc_export.h" #include "cc/base/scoped_ptr_vector.h" -#include "cc/trees/layer_tree_host.h" +#include "cc/output/renderer_capabilities.h" +#include "cc/output/renderer_settings.h" +#include "ui/gfx/geometry/rect.h" namespace cc {
diff --git a/cc/output/renderer_capabilities.cc b/cc/output/renderer_capabilities.cc new file mode 100644 index 0000000..36e012bf --- /dev/null +++ b/cc/output/renderer_capabilities.cc
@@ -0,0 +1,29 @@ +// 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 "cc/output/renderer_capabilities.h" + +namespace cc { + +RendererCapabilities::RendererCapabilities(ResourceFormat best_texture_format, + bool allow_partial_texture_updates, + int max_texture_size, + bool using_shared_memory_resources) + : best_texture_format(best_texture_format), + allow_partial_texture_updates(allow_partial_texture_updates), + max_texture_size(max_texture_size), + using_shared_memory_resources(using_shared_memory_resources) { +} + +RendererCapabilities::RendererCapabilities() + : best_texture_format(RGBA_8888), + allow_partial_texture_updates(false), + max_texture_size(0), + using_shared_memory_resources(false) { +} + +RendererCapabilities::~RendererCapabilities() { +} + +} // namespace cc
diff --git a/cc/output/renderer_capabilities.h b/cc/output/renderer_capabilities.h new file mode 100644 index 0000000..f03d51c --- /dev/null +++ b/cc/output/renderer_capabilities.h
@@ -0,0 +1,32 @@ +// 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 CC_OUTPUT_RENDERER_CAPABILITIES_H_ +#define CC_OUTPUT_RENDERER_CAPABILITIES_H_ + +#include "cc/base/cc_export.h" +#include "cc/resources/resource_format.h" + +namespace cc { + +// Represents the set of capabilities that a particular Renderer has. +struct CC_EXPORT RendererCapabilities { + RendererCapabilities(ResourceFormat best_texture_format, + bool allow_partial_texture_updates, + int max_texture_size, + bool using_shared_memory_resources); + + RendererCapabilities(); + ~RendererCapabilities(); + + // Duplicate any modification to this list to RendererCapabilitiesImpl. + ResourceFormat best_texture_format; + bool allow_partial_texture_updates; + int max_texture_size; + bool using_shared_memory_resources; +}; + +} // namespace cc + +#endif // CC_OUTPUT_RENDERER_CAPABILITIES_H_
diff --git a/cc/quads/yuv_video_draw_quad.h b/cc/quads/yuv_video_draw_quad.h index 358929e..15bce98 100644 --- a/cc/quads/yuv_video_draw_quad.h +++ b/cc/quads/yuv_video_draw_quad.h
@@ -8,7 +8,6 @@ #include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "cc/base/cc_export.h" -#include "cc/layers/video_layer_impl.h" #include "cc/quads/draw_quad.h" namespace cc {
diff --git a/cc/scheduler/scheduler.cc b/cc/scheduler/scheduler.cc index 70d726d4..3b20b79 100644 --- a/cc/scheduler/scheduler.cc +++ b/cc/scheduler/scheduler.cc
@@ -380,8 +380,7 @@ TRACE_EVENT1("cc,benchmark", "Scheduler::BeginFrame", "args", args.AsValue()); // Deliver BeginFrames to children. - if (settings_.forward_begin_frames_to_children && - state_machine_.children_need_begin_frames()) { + if (state_machine_.children_need_begin_frames()) { BeginFrameArgs adjusted_args_for_children(args); // Adjust a deadline for child schedulers. // TODO(simonhong): Once we have commitless update, we can get rid of @@ -431,7 +430,6 @@ } void Scheduler::SetChildrenNeedBeginFrames(bool children_need_begin_frames) { - DCHECK(settings_.forward_begin_frames_to_children); state_machine_.SetChildrenNeedBeginFrames(children_need_begin_frames); ProcessScheduledActions(); }
diff --git a/cc/scheduler/scheduler_settings.cc b/cc/scheduler/scheduler_settings.cc index 600cdfb..39a98b40 100644 --- a/cc/scheduler/scheduler_settings.cc +++ b/cc/scheduler/scheduler_settings.cc
@@ -11,7 +11,6 @@ SchedulerSettings::SchedulerSettings() : use_external_begin_frame_source(false), - forward_begin_frames_to_children(false), main_frame_before_activation_enabled(false), impl_side_painting(false), timeout_and_draw_when_animation_checkerboards(true), @@ -24,8 +23,6 @@ SchedulerSettings::SchedulerSettings(const LayerTreeSettings& settings) : use_external_begin_frame_source(settings.use_external_begin_frame_source), - forward_begin_frames_to_children( - settings.forward_begin_frames_to_children), main_frame_before_activation_enabled( settings.main_frame_before_activation_enabled), impl_side_painting(settings.impl_side_painting), @@ -49,8 +46,6 @@ new base::trace_event::TracedValue(); state->SetBoolean("use_external_begin_frame_source", use_external_begin_frame_source); - state->SetBoolean("forward_begin_frames_to_children", - forward_begin_frames_to_children); state->SetBoolean("main_frame_before_activation_enabled", main_frame_before_activation_enabled); state->SetBoolean("impl_side_painting", impl_side_painting);
diff --git a/cc/scheduler/scheduler_settings.h b/cc/scheduler/scheduler_settings.h index 82a671a..85f64e1 100644 --- a/cc/scheduler/scheduler_settings.h +++ b/cc/scheduler/scheduler_settings.h
@@ -26,7 +26,6 @@ ~SchedulerSettings(); bool use_external_begin_frame_source; - bool forward_begin_frames_to_children; bool main_frame_before_activation_enabled; bool impl_side_painting; bool timeout_and_draw_when_animation_checkerboards;
diff --git a/cc/scheduler/scheduler_state_machine.cc b/cc/scheduler/scheduler_state_machine.cc index f2f6636..189387c 100644 --- a/cc/scheduler/scheduler_state_machine.cc +++ b/cc/scheduler/scheduler_state_machine.cc
@@ -768,7 +768,6 @@ void SchedulerStateMachine::SetChildrenNeedBeginFrames( bool children_need_begin_frames) { - DCHECK(settings_.forward_begin_frames_to_children); children_need_begin_frames_ = children_need_begin_frames; }
diff --git a/cc/scheduler/scheduler_state_machine_unittest.cc b/cc/scheduler/scheduler_state_machine_unittest.cc index ca0e441..98d5b18 100644 --- a/cc/scheduler/scheduler_state_machine_unittest.cc +++ b/cc/scheduler/scheduler_state_machine_unittest.cc
@@ -1804,7 +1804,6 @@ TEST(SchedulerStateMachineTest, TestForwardBeginFramesToChildren) { SchedulerSettings settings; - settings.forward_begin_frames_to_children = true; StateMachine state(settings); SET_UP_STATE(state)
diff --git a/cc/scheduler/scheduler_unittest.cc b/cc/scheduler/scheduler_unittest.cc index 9346536..55f2164 100644 --- a/cc/scheduler/scheduler_unittest.cc +++ b/cc/scheduler/scheduler_unittest.cc
@@ -407,7 +407,6 @@ TEST_F(SchedulerTest, SendBeginFramesToChildren) { scheduler_settings_.use_external_begin_frame_source = true; - scheduler_settings_.forward_begin_frames_to_children = true; SetUpScheduler(true); EXPECT_FALSE(client_->begin_frame_is_sent_to_children()); @@ -428,7 +427,6 @@ TEST_F(SchedulerTest, SendBeginFramesToChildrenWithoutCommit) { scheduler_settings_.use_external_begin_frame_source = true; - scheduler_settings_.forward_begin_frames_to_children = true; SetUpScheduler(true); EXPECT_FALSE(client_->needs_begin_frames()); @@ -503,10 +501,6 @@ scheduler_settings_.use_external_begin_frame_source = true; SetUpScheduler(true); - scheduler_->SetCanStart(); - scheduler_->SetVisible(true); - scheduler_->SetCanDraw(true); - scheduler_->SetDeferCommits(true); scheduler_->SetNeedsCommit(); @@ -539,10 +533,6 @@ scheduler_settings_.use_external_begin_frame_source = true; SetUpScheduler(true); - scheduler_->SetCanStart(); - scheduler_->SetVisible(true); - scheduler_->SetCanDraw(true); - scheduler_->SetDeferCommits(true); scheduler_->SetNeedsCommit();
diff --git a/cc/surfaces/display.h b/cc/surfaces/display.h index ed96d07..30db259 100644 --- a/cc/surfaces/display.h +++ b/cc/surfaces/display.h
@@ -15,6 +15,11 @@ #include "cc/surfaces/surface_id.h" #include "cc/surfaces/surface_manager.h" #include "cc/surfaces/surfaces_export.h" +#include "ui/events/latency_info.h" + +namespace gpu { +class GpuMemoryBufferManager; +} namespace gfx { class Size;
diff --git a/cc/surfaces/surface_display_output_surface.cc b/cc/surfaces/surface_display_output_surface.cc index ac60271..c07eece 100644 --- a/cc/surfaces/surface_display_output_surface.cc +++ b/cc/surfaces/surface_display_output_surface.cc
@@ -4,6 +4,7 @@ #include "cc/surfaces/surface_display_output_surface.h" +#include "base/bind.h" #include "cc/output/compositor_frame.h" #include "cc/output/compositor_frame_ack.h" #include "cc/surfaces/display.h"
diff --git a/cc/test/data/mask_of_background_filter.png b/cc/test/data/mask_of_background_filter.png index 6aeae32..cd1eab61 100644 --- a/cc/test/data/mask_of_background_filter.png +++ b/cc/test/data/mask_of_background_filter.png Binary files differ
diff --git a/cc/test/fake_ui_resource_layer_tree_host_impl.cc b/cc/test/fake_ui_resource_layer_tree_host_impl.cc index c95ad89cc..9e7adde 100644 --- a/cc/test/fake_ui_resource_layer_tree_host_impl.cc +++ b/cc/test/fake_ui_resource_layer_tree_host_impl.cc
@@ -4,6 +4,7 @@ #include "cc/test/fake_ui_resource_layer_tree_host_impl.h" +#include "cc/resources/ui_resource_bitmap.h" #include "cc/test/fake_layer_tree_host_impl.h" namespace cc {
diff --git a/cc/test/pixel_test.h b/cc/test/pixel_test.h index 35626993..08bad369 100644 --- a/cc/test/pixel_test.h +++ b/cc/test/pixel_test.h
@@ -7,6 +7,7 @@ #include "cc/output/software_renderer.h" #include "cc/quads/render_pass.h" #include "cc/test/pixel_comparator.h" +#include "cc/trees/layer_tree_settings.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/size.h" #include "ui/gl/gl_implementation.h"
diff --git a/cc/trees/layer_tree_host.cc b/cc/trees/layer_tree_host.cc index 2ac7ebe5..8a3e644 100644 --- a/cc/trees/layer_tree_host.cc +++ b/cc/trees/layer_tree_host.cc
@@ -51,23 +51,6 @@ namespace cc { -RendererCapabilities::RendererCapabilities(ResourceFormat best_texture_format, - bool allow_partial_texture_updates, - int max_texture_size, - bool using_shared_memory_resources) - : best_texture_format(best_texture_format), - allow_partial_texture_updates(allow_partial_texture_updates), - max_texture_size(max_texture_size), - using_shared_memory_resources(using_shared_memory_resources) {} - -RendererCapabilities::RendererCapabilities() - : best_texture_format(RGBA_8888), - allow_partial_texture_updates(false), - max_texture_size(0), - using_shared_memory_resources(false) {} - -RendererCapabilities::~RendererCapabilities() {} - scoped_ptr<LayerTreeHost> LayerTreeHost::CreateThreaded( LayerTreeHostClient* client, SharedBitmapManager* shared_bitmap_manager,
diff --git a/cc/trees/layer_tree_host.h b/cc/trees/layer_tree_host.h index 840a4fa..1474e6e 100644 --- a/cc/trees/layer_tree_host.h +++ b/cc/trees/layer_tree_host.h
@@ -31,6 +31,7 @@ #include "cc/input/top_controls_state.h" #include "cc/layers/layer_lists.h" #include "cc/output/output_surface.h" +#include "cc/output/renderer_capabilities.h" #include "cc/resources/resource_format.h" #include "cc/resources/scoped_ui_resource.h" #include "cc/surfaces/surface_sequence.h" @@ -67,24 +68,6 @@ struct ScrollAndScaleSet; enum class GpuRasterizationStatus; -// Provides information on an Impl's rendering capabilities back to the -// LayerTreeHost. -struct CC_EXPORT RendererCapabilities { - RendererCapabilities(ResourceFormat best_texture_format, - bool allow_partial_texture_updates, - int max_texture_size, - bool using_shared_memory_resources); - - RendererCapabilities(); - ~RendererCapabilities(); - - // Duplicate any modification to this list to RendererCapabilitiesImpl. - ResourceFormat best_texture_format; - bool allow_partial_texture_updates; - int max_texture_size; - bool using_shared_memory_resources; -}; - class CC_EXPORT LayerTreeHost { public: // The SharedBitmapManager will be used on the compositor thread.
diff --git a/cc/trees/layer_tree_host_impl.h b/cc/trees/layer_tree_host_impl.h index 18250c0..defe796 100644 --- a/cc/trees/layer_tree_host_impl.h +++ b/cc/trees/layer_tree_host_impl.h
@@ -33,8 +33,11 @@ #include "cc/resources/rasterizer.h" #include "cc/resources/resource_provider.h" #include "cc/resources/tile_manager.h" +#include "cc/resources/ui_resource_client.h" #include "cc/scheduler/commit_earlyout_reason.h" #include "cc/scheduler/draw_result.h" +#include "cc/trees/layer_tree_settings.h" +#include "cc/trees/proxy.h" #include "skia/ext/refptr.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/geometry/rect.h" @@ -63,11 +66,13 @@ class ResourcePool; class ScrollElasticityHelper; class ScrollbarLayerImplBase; +class SwapPromise; +class SwapPromiseMonitor; class TextureMailboxDeleter; class TopControlsManager; class UIResourceBitmap; class UIResourceRequest; -struct RendererCapabilitiesImpl; +struct ScrollAndScaleSet; enum class GpuRasterizationStatus { ON,
diff --git a/cc/trees/layer_tree_host_pixeltest_masks.cc b/cc/trees/layer_tree_host_pixeltest_masks.cc index 85e9914..97765bd 100644 --- a/cc/trees/layer_tree_host_pixeltest_masks.cc +++ b/cc/trees/layer_tree_host_pixeltest_masks.cc
@@ -365,24 +365,24 @@ TEST_P(LayerTreeHostMasksForBackgroundFiltersPixelTest, MaskOfLayerWithBackgroundFilter) { scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer( - gfx::Rect(128, 128), SK_ColorWHITE); + gfx::Rect(100, 100), SK_ColorWHITE); - gfx::Size picture_bounds(128, 128); + gfx::Size picture_bounds(100, 100); CheckerContentLayerClient picture_client(picture_bounds, SK_ColorGREEN, true); scoped_refptr<PictureLayer> picture = PictureLayer::Create(&picture_client); picture->SetBounds(picture_bounds); picture->SetIsDrawable(true); scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer( - gfx::Rect(128, 128), SK_ColorTRANSPARENT); + gfx::Rect(100, 100), SK_ColorTRANSPARENT); background->AddChild(picture); background->AddChild(blur); FilterOperations filters; - filters.Append(FilterOperation::CreateBlurFilter(2.f)); + filters.Append(FilterOperation::CreateBlurFilter(1.5f)); blur->SetBackgroundFilters(filters); - gfx::Size mask_bounds(128, 128); + gfx::Size mask_bounds(100, 100); CircleContentLayerClient mask_client(mask_bounds); scoped_refptr<PictureLayer> mask = PictureLayer::Create(&mask_client); mask->SetBounds(mask_bounds); @@ -390,7 +390,7 @@ mask->SetIsMask(true); blur->SetMaskLayer(mask.get()); - float percentage_pixels_large_error = 2.5f; // 2.5%, ~400px / (128*128) + float percentage_pixels_large_error = 2.5f; // 2.5%, ~250px / (100*100) float percentage_pixels_small_error = 0.0f; float average_error_allowed_in_bad_pixels = 100.0f; int large_error_allowed = 256;
diff --git a/cc/trees/layer_tree_host_unittest.cc b/cc/trees/layer_tree_host_unittest.cc index 68a1f58..51f0ff7 100644 --- a/cc/trees/layer_tree_host_unittest.cc +++ b/cc/trees/layer_tree_host_unittest.cc
@@ -5286,10 +5286,6 @@ : begin_frame_sent_to_children_(false) { } - void InitializeSettings(LayerTreeSettings* settings) override { - settings->forward_begin_frames_to_children = true; - } - void BeginTest() override { // Kick off the test with a commit. PostSetNeedsCommitToMainThread(); @@ -5326,7 +5322,6 @@ void InitializeSettings(LayerTreeSettings* settings) override { settings->use_external_begin_frame_source = true; - settings->forward_begin_frames_to_children = true; } void BeginTest() override {
diff --git a/cc/trees/layer_tree_impl.h b/cc/trees/layer_tree_impl.h index 3105e6f4..5aee8352 100644 --- a/cc/trees/layer_tree_impl.h +++ b/cc/trees/layer_tree_impl.h
@@ -14,9 +14,12 @@ #include "cc/base/scoped_ptr_vector.h" #include "cc/base/swap_promise.h" #include "cc/base/synced_property.h" +#include "cc/input/layer_selection_bound.h" #include "cc/layers/layer_impl.h" +#include "cc/output/begin_frame_args.h" #include "cc/output/renderer.h" #include "cc/resources/ui_resource_client.h" +#include "cc/trees/layer_tree_host_impl.h" namespace base { namespace trace_event { @@ -32,7 +35,6 @@ class HeadsUpDisplayLayerImpl; class LayerScrollOffsetDelegateProxy; class LayerTreeDebugState; -class LayerTreeHostImpl; class LayerTreeImpl; class LayerTreeSettings; class MemoryHistory;
diff --git a/cc/trees/layer_tree_settings.cc b/cc/trees/layer_tree_settings.cc index f19f603..96c9d16 100644 --- a/cc/trees/layer_tree_settings.cc +++ b/cc/trees/layer_tree_settings.cc
@@ -19,7 +19,6 @@ throttle_frame_production(true), single_thread_proxy_scheduler(true), use_external_begin_frame_source(false), - forward_begin_frames_to_children(false), main_frame_before_activation_enabled(false), using_synchronous_renderer_compositor(false), report_overscroll_only_for_scrollable_axes(false),
diff --git a/cc/trees/layer_tree_settings.h b/cc/trees/layer_tree_settings.h index f561c562..4554362b 100644 --- a/cc/trees/layer_tree_settings.h +++ b/cc/trees/layer_tree_settings.h
@@ -25,7 +25,6 @@ bool throttle_frame_production; bool single_thread_proxy_scheduler; bool use_external_begin_frame_source; - bool forward_begin_frames_to_children; bool main_frame_before_activation_enabled; bool using_synchronous_renderer_compositor; bool report_overscroll_only_for_scrollable_axes;
diff --git a/cc/trees/single_thread_proxy.h b/cc/trees/single_thread_proxy.h index a986fc2..cfc746a 100644 --- a/cc/trees/single_thread_proxy.h +++ b/cc/trees/single_thread_proxy.h
@@ -23,6 +23,7 @@ class ContextProvider; class LayerTreeHost; class LayerTreeHostSingleThreadClient; +class ResourceUpdateQueue; class CC_EXPORT SingleThreadProxy : public Proxy, NON_EXPORTED_BASE(LayerTreeHostImplClient),
diff --git a/cc/trees/thread_proxy.h b/cc/trees/thread_proxy.h index 927caab..51cc18c 100644 --- a/cc/trees/thread_proxy.h +++ b/cc/trees/thread_proxy.h
@@ -30,6 +30,7 @@ class ContextProvider; class InputHandlerClient; class LayerTreeHost; +class PrioritizedResourceManager; class ResourceUpdateQueue; class Scheduler; class ScopedThreadProxy;
diff --git a/chrome/VERSION b/chrome/VERSION index 2fd1ad0..bea6c2d 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=43 MINOR=0 -BUILD=2333 +BUILD=2335 PATCH=0
diff --git a/chrome/app/chromium_strings.grd b/chrome/app/chromium_strings.grd index efe2b2f..dae424d3 100644 --- a/chrome/app/chromium_strings.grd +++ b/chrome/app/chromium_strings.grd
@@ -247,10 +247,10 @@ https://support.google.com/chrome/?p=ib_chromeframe </message> <message name="IDS_CHROME_FRAME_TURNDOWN_TEXT_IE_OLDER" desc="Text of Chromium Frame turndown prompt for IE 6, 7, and 8"> - This site is using the Chromium Frame plug-in which will soon be unsupported. Please uninstall it and upgrade to a modern browser. + This site is using the Chromium Frame plugin which will soon be unsupported. Please uninstall it and upgrade to a modern browser. </message> <message name="IDS_CHROME_FRAME_TURNDOWN_TEXT_IE_NEWER" desc="Text of Chromium Frame turndown prompt for IE 9 and 10"> - This site is using the Chromium Frame plug-in that will soon be unsupported. Please uninstall it and download a compatible browser. + This site is using the Chromium Frame plugin that will soon be unsupported. Please uninstall it and download a compatible browser. </message> <message name="IDS_SHORTCUT_NEW_WINDOW" desc="The text label of the New window shortcut context menu entry as of Windows 8"> New window
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index faf1161..f30aff92 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -1124,18 +1124,18 @@ <if expr="not use_titlecase"> <message name="IDS_CONTENT_CONTEXT_PLUGIN_RUN" desc="The name of the Run command on the blocked plugin context menu"> - Run this plug-in + Run this plugin </message> <message name="IDS_CONTENT_CONTEXT_PLUGIN_HIDE" desc="The name of the Hide command on the blocked plugin context menu"> - Hide this plug-in + Hide this plugin </message> </if> <if expr="use_titlecase"> <message name="IDS_CONTENT_CONTEXT_PLUGIN_RUN" desc="In Title Case: The name of the Run command on the blocked plugin context menu"> - Run This Plug-in + Run This Plugin </message> <message name="IDS_CONTENT_CONTEXT_PLUGIN_HIDE" desc="In Title Case: The name of the Hide command on the blocked plugin context menu"> - Hide This Plug-in + Hide This Plugin </message> </if> @@ -2675,7 +2675,7 @@ Pop-up blocked </message> <message name="IDS_BLOCKED_PLUGIN_EXPLANATORY_TEXT" desc="Explanatory animated text that appears (and then disappears) in the address line when plugin is blocked"> - Plug-in blocked + Plugin blocked </message> <message name="IDS_BLOCKED_JAVASCRIPT_TITLE" desc="Tooltip and bubble info header text when a page is not allowed to run JavaScript."> JavaScript was blocked on this page. @@ -2689,28 +2689,28 @@ <message name="IDS_BLOCKED_JAVASCRIPT_LINK" desc="Link to JavaScript section of content blocking management dialog, displayed in bubble when a page tries to run JavaScript."> Manage JavaScript blocking... </message> - <message name="IDS_BLOCKED_PLUGINS_TITLE" desc="Bubble info header text when a page is not allowed to display plug-ins."> - The following plug-ins were blocked on this page: + <message name="IDS_BLOCKED_PLUGINS_TITLE" desc="Bubble info header text when a page is not allowed to display plugins."> + The following plugins were blocked on this page: </message> - <message name="IDS_BLOCKED_PLUGINS_MESSAGE" desc="Tooltip and message when a page is not allowed to display plug-ins."> - Plug-ins were blocked on this page. + <message name="IDS_BLOCKED_PLUGINS_MESSAGE" desc="Tooltip and message when a page is not allowed to display plugins."> + Plugins were blocked on this page. </message> - <message name="IDS_BLOCKED_PLUGINS_UNBLOCK_ALL" desc="Radio button choice to unblock a site from using plug-ins, displayed in bubble when a page tries to use plug-ins."> - Always allow plug-ins on <ph name="HOST">$1<ex>mail.google.com</ex></ph> + <message name="IDS_BLOCKED_PLUGINS_UNBLOCK_ALL" desc="Radio button choice to unblock a site from using plugins, displayed in bubble when a page tries to use plugins."> + Always allow plugins on <ph name="HOST">$1<ex>mail.google.com</ex></ph> </message> <if expr="is_macosx"> - <message name="IDS_BLOCKED_PLUGINS_UNBLOCK" desc="Radio button choice to unblock a site from using *a specific set* of plug-ins, displayed in bubble when a page tries to use plug-ins."> - Always allow these plug-ins on <ph name="HOST">$1<ex>mail.google.com</ex></ph> + <message name="IDS_BLOCKED_PLUGINS_UNBLOCK" desc="Radio button choice to unblock a site from using *a specific set* of plugins, displayed in bubble when a page tries to use plugins."> + Always allow these plugins on <ph name="HOST">$1<ex>mail.google.com</ex></ph> </message> </if> - <message name="IDS_BLOCKED_PLUGINS_NO_ACTION" desc="Radio button choice to continue blocking a site from using plug-ins, displayed in bubble when a page tries to use plug-ins."> - Continue blocking plug-ins + <message name="IDS_BLOCKED_PLUGINS_NO_ACTION" desc="Radio button choice to continue blocking a site from using plugins, displayed in bubble when a page tries to use plugins."> + Continue blocking plugins </message> - <message name="IDS_BLOCKED_PLUGINS_LINK" desc="Link to plug-ins section of content blocking management dialog, displayed in bubble when a page tries to display plug-ins."> - Manage plug-in blocking... + <message name="IDS_BLOCKED_PLUGINS_LINK" desc="Link to plugins section of content blocking management dialog, displayed in bubble when a page tries to display plugins."> + Manage plugin blocking... </message> - <message name="IDS_BLOCKED_PLUGINS_LOAD_ALL" desc="Button to load all blocked plugins on a page, displayed in bubble when a page tries to display plug-ins."> - Run all plug-ins this time + <message name="IDS_BLOCKED_PLUGINS_LOAD_ALL" desc="Button to load all blocked plugins on a page, displayed in bubble when a page tries to display plugins."> + Run all plugins this time </message> <!-- Certificate error strings --> @@ -3900,16 +3900,16 @@ Background Page: <ph name="BACKGROUND_PAGE_URL">$1<ex>http://www.google.com</ex></ph> </message> <message name="IDS_TASK_MANAGER_PLUGIN_PREFIX" desc="The prefix for a Task Manager plugin row"> - Plug-in: <ph name="PLUGIN_NAME">$1<ex>Unknown Plug-in</ex></ph> + Plugin: <ph name="PLUGIN_NAME">$1<ex>Unknown Plugin</ex></ph> </message> <message name="IDS_TASK_MANAGER_PLUGIN_BROKER_PREFIX" desc="Task Manager row for PPAPI plugin broker, which provides additional access for PPAPI plugins"> - Plug-in Broker: <ph name="PLUGIN_NAME">$1<ex>Unknown Plug-in</ex></ph> + Plugin Broker: <ph name="PLUGIN_NAME">$1<ex>Unknown Plugin</ex></ph> </message> <message name="IDS_TASK_MANAGER_PRERENDER_PREFIX" desc="The prefix for a Task Manager prerender row"> Prerender: <ph name="PRERENDER_CONTENTS_NAME">$1<ex>http://www.google.com</ex></ph> </message> <message name="IDS_TASK_MANAGER_UNKNOWN_PLUGIN_NAME" desc="The prefix for a Task Manager plugin row"> - Unknown plug-in + Unknown plugin </message> <message name="IDS_TASK_MANAGER_WORKER_PREFIX" desc="The prefix for a Task Manager HTML5 Web Worker process row"> Web Worker: <ph name="WORKER_NAME">$1<ex>http://www.domain.com</ex></ph> @@ -4632,7 +4632,7 @@ Read all text spoken using synthesized speech </message> <message name="IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS" desc="Permission string for access to content settings."> - Change your settings that control websites' access to features such as cookies, JavaScript, plug-ins, geolocation, microphone, camera etc. + Change your settings that control websites' access to features such as cookies, JavaScript, plugins, geolocation, microphone, camera etc. </message> <message name="IDS_EXTENSION_PROMPT_WARNING_PRIVACY" desc="Permission string for access to privacy settings."> Change your privacy-related settings @@ -5561,63 +5561,63 @@ <!-- Plugins --> <if expr="enable_plugins"> <message name="IDS_PLUGINS_TITLE" desc="Title for the chrome://plugins page."> - Plug-ins + Plugins </message> <message name="IDS_PLUGINS_DETAILS_MODE_LINK" desc="Text of the link for details mode."> Details </message> - <message name="IDS_PLUGINS_NONE_INSTALLED" desc="Text that lets the user know that no plug-ins are installed."> - No plug-ins installed. + <message name="IDS_PLUGINS_NONE_INSTALLED" desc="Text that lets the user know that no plugins are installed."> + No plugins installed. </message> - <message name="IDS_PLUGINS_DISABLED_PLUGIN" desc="Text that signifies that the plug-in is currently disabled."> + <message name="IDS_PLUGINS_DISABLED_PLUGIN" desc="Text that signifies that the plugin is currently disabled."> (Disabled) </message> - <message name="IDS_PLUGINS_DISABLED_BY_POLICY_PLUGIN" desc="Text that signifies that the plug-in is currently disabled by enterprise policy."> + <message name="IDS_PLUGINS_DISABLED_BY_POLICY_PLUGIN" desc="Text that signifies that the plugin is currently disabled by enterprise policy."> (Disabled by enterprise policy) </message> - <message name="IDS_PLUGINS_ENABLED_BY_POLICY_PLUGIN" desc="Text that signifies that the plug-in is currently enabled by enterprise policy."> + <message name="IDS_PLUGINS_ENABLED_BY_POLICY_PLUGIN" desc="Text that signifies that the plugin is currently enabled by enterprise policy."> (Enabled by enterprise policy) </message> - <message name="IDS_PLUGINS_GROUP_MANAGED_BY_POLICY" desc="Text that signifies that the plug-in group is currently managed by enterprise policy."> + <message name="IDS_PLUGINS_GROUP_MANAGED_BY_POLICY" desc="Text that signifies that the plugin group is currently managed by enterprise policy."> (Managed by enterprise policy) </message> - <message name="IDS_PLUGINS_VERSION" desc="The label in front of a plug-in version number."> + <message name="IDS_PLUGINS_VERSION" desc="The label in front of a plugin version number."> Version: </message> - <message name="IDS_PLUGINS_DESCRIPTION" desc="The label in front of a plug-in description."> + <message name="IDS_PLUGINS_DESCRIPTION" desc="The label in front of a plugin description."> Description: </message> - <message name="IDS_PLUGINS_PATH" desc="The label in front of a plug-in path (file/location on disk)."> + <message name="IDS_PLUGINS_PATH" desc="The label in front of a plugin path (file/location on disk)."> Location: </message> - <message name="IDS_PLUGINS_TYPE" desc="The label in front of a plug-in type (NPAPI, PPAPI, etc.)."> + <message name="IDS_PLUGINS_TYPE" desc="The label in front of a plugin type (NPAPI, PPAPI, etc.)."> Type: </message> - <message name="IDS_PLUGINS_MIME_TYPES" desc="The label in front of a plug-in's MIME types table."> + <message name="IDS_PLUGINS_MIME_TYPES" desc="The label in front of a plugin's MIME types table."> MIME types: </message> - <message name="IDS_PLUGINS_MIME_TYPES_MIME_TYPE" desc="The label over the MIME type column in a plug-in's MIME types table."> + <message name="IDS_PLUGINS_MIME_TYPES_MIME_TYPE" desc="The label over the MIME type column in a plugin's MIME types table."> MIME type </message> - <message name="IDS_PLUGINS_MIME_TYPES_DESCRIPTION" desc="The label over the description column in a plug-in's MIME types table."> + <message name="IDS_PLUGINS_MIME_TYPES_DESCRIPTION" desc="The label over the description column in a plugin's MIME types table."> Description </message> - <message name="IDS_PLUGINS_MIME_TYPES_FILE_EXTENSIONS" desc="The label over the file extensions column in a plug-in's MIME types table."> + <message name="IDS_PLUGINS_MIME_TYPES_FILE_EXTENSIONS" desc="The label over the file extensions column in a plugin's MIME types table."> File extensions </message> - <message name="IDS_PLUGINS_DISABLE" desc="The link for disabling a plug-in."> + <message name="IDS_PLUGINS_DISABLE" desc="The link for disabling a plugin."> Disable </message> - <message name="IDS_PLUGINS_ENABLE" desc="The link for enabling a plug-in."> + <message name="IDS_PLUGINS_ENABLE" desc="The link for enabling a plugin."> Enable </message> - <message name="IDS_PLUGINS_ALWAYS_ALLOWED" desc="The checkbox label for whitelisting a plug-in for content settings."> + <message name="IDS_PLUGINS_ALWAYS_ALLOWED" desc="The checkbox label for whitelisting a plugin for content settings."> Always allowed to run </message> - <message name="IDS_PLUGINS_DOWNLOAD" desc="The link label to download the latest version of this plug-in"> + <message name="IDS_PLUGINS_DOWNLOAD" desc="The link label to download the latest version of this plugin"> Download Critical Security Update </message> - <message name="IDS_PLUGINS_NAME" desc="The label for the name of this plug-in"> + <message name="IDS_PLUGINS_NAME" desc="The label for the name of this plugin"> Name: </message> <message name="IDS_PLUGINS_NO_PLUGINS" desc="Text that indicates that no plugins are installed"> @@ -7037,7 +7037,7 @@ This feature is temporarily unavailable. <ph name="BEGIN_LINK"><a target="_blank" href="$1"></ph>Help<ph name="END_LINK"></a><ex></a></ex></ph> </message> <message name="IDS_HOTWORD_NACL_DISABLED_ERROR_MESSAGE" desc="The error message text when hotwording fails because NaCl is disabled."> - <ph name="BEGIN_LINK"><a target="_blank" href="chrome://plugins"></ph>Native Client plug-in<ph name="END_LINK"></a><ex></a></ex></ph> needs to be enabled to use this feature. + <ph name="BEGIN_LINK"><a target="_blank" href="chrome://plugins"></ph>Native Client plugin<ph name="END_LINK"></a><ex></a></ex></ph> needs to be enabled to use this feature. </message> <message name="IDS_HOTWORD_MICROPHONE_ERROR_MESSAGE" desc="The error message text when hotwording fails because the microphone isn't working."> Microphone is currently unavailable. <ph name="BEGIN_LINK"><a target="_blank" href="chrome://settings/content#media-stream-settings"></ph>Manage microphone<ph name="END_LINK"></a><ex></a></ex></ph> @@ -7123,77 +7123,77 @@ </if> </if> <!-- is_win --> - <!-- Plug-in placeholders --> - <message name="IDS_PLUGIN_HIDE" desc="The tooltip for hiding a blocked plug-in, displayed in the click to play UI."> - Hide this plug-in + <!-- Plugin placeholders --> + <message name="IDS_PLUGIN_HIDE" desc="The tooltip for hiding a blocked plugin, displayed in the click to play UI."> + Hide this plugin </message> - <message name="IDS_PLUGIN_UPDATE" desc="The link for updating an outdated plug-in."> - Update plug-in... + <message name="IDS_PLUGIN_UPDATE" desc="The link for updating an outdated plugin."> + Update plugin... </message> - <message name="IDS_PLUGIN_NOT_SUPPORTED_METRO" desc="The placeholder text for a plug-in that can't run in Windows Metro mode."> - This plug-in only works on the desktop. + <message name="IDS_PLUGIN_NOT_SUPPORTED_METRO" desc="The placeholder text for a plugin that can't run in Windows Metro mode."> + This plugin only works on the desktop. </message> <if expr="is_macosx"> - <message name="IDS_PLUGIN_BLOCKED" desc="The placeholder text for a blocked plug-in."> + <message name="IDS_PLUGIN_BLOCKED" desc="The placeholder text for a blocked plugin."> Control-click to play <ph name="PLUGIN_NAME">$1<ex>Flash</ex></ph>. </message> </if> <if expr="not is_macosx"> - <message name="IDS_PLUGIN_BLOCKED" desc="The placeholder text for a blocked plug-in."> + <message name="IDS_PLUGIN_BLOCKED" desc="The placeholder text for a blocked plugin."> Right-click to play <ph name="PLUGIN_NAME">$1<ex>Flash</ex></ph>. </message> </if> <if expr="chromeos"> - <message name="IDS_NACL_PLUGIN_BLOCKED" desc="The placeholder text for a blocked plug-in."> + <message name="IDS_NACL_PLUGIN_BLOCKED" desc="The placeholder text for a blocked plugin."> This app is not currently supported on this device but the Chrome gnomes are hard at work to make it work soon. </message> </if> - <message name="IDS_PLUGIN_OUTDATED" desc="The placeholder text for an outdated plug-in."> + <message name="IDS_PLUGIN_OUTDATED" desc="The placeholder text for an outdated plugin."> <ph name="PLUGIN_NAME">$1<ex>Flash</ex></ph> is out of date. </message> - <message name="IDS_PLUGIN_NOT_AUTHORIZED" desc="The placeholder text for a plug-in that requires user permission to run."> + <message name="IDS_PLUGIN_NOT_AUTHORIZED" desc="The placeholder text for a plugin that requires user permission to run."> <ph name="PLUGIN_NAME">$1<ex>Java</ex></ph> needs your permission to run. </message> - <message name="IDS_PLUGIN_NOT_SUPPORTED" desc="The placeholder text for an unsupported plug-in."> - This plug-in is not supported. + <message name="IDS_PLUGIN_NOT_SUPPORTED" desc="The placeholder text for an unsupported plugin."> + This plugin is not supported. </message> - <message name="IDS_PLUGIN_NOT_FOUND" desc="The placeholder text for an unknown plug-in that is not installed."> - No plug-in available to display this content. + <message name="IDS_PLUGIN_NOT_FOUND" desc="The placeholder text for an unknown plugin that is not installed."> + No plugin available to display this content. </message> - <message name="IDS_PLUGIN_SEARCHING" desc="The placeholder text when searching for a missing plug-in."> - Looking for plug-in... + <message name="IDS_PLUGIN_SEARCHING" desc="The placeholder text when searching for a missing plugin."> + Looking for plugin... </message> - <message name="IDS_PLUGIN_DOWNLOADING" desc="The placeholder text when downloading a missing plug-in."> + <message name="IDS_PLUGIN_DOWNLOADING" desc="The placeholder text when downloading a missing plugin."> Downloading <ph name="PLUGIN_NAME">$1<ex>Realplayer</ex></ph>... </message> - <message name="IDS_PLUGIN_DOWNLOAD_ERROR" desc="The placeholder text when there was an error download a missing plug-in."> - There was an error (<ph name="ERROR">$1<ex>net::ERR_TOO_MANY_GOATS</ex></ph>) while downloading the plug-in. + <message name="IDS_PLUGIN_DOWNLOAD_ERROR" desc="The placeholder text when there was an error download a missing plugin."> + There was an error (<ph name="ERROR">$1<ex>net::ERR_TOO_MANY_GOATS</ex></ph>) while downloading the plugin. </message> - <message name="IDS_PLUGIN_DOWNLOAD_ERROR_SHORT" desc="The placeholder text when there was an error download a missing plug-in."> + <message name="IDS_PLUGIN_DOWNLOAD_ERROR_SHORT" desc="The placeholder text when there was an error download a missing plugin."> <ph name="PLUGIN_NAME">$1<ex>Realplayer</ex></ph> download failed. </message> - <message name="IDS_PLUGIN_DOWNLOAD_CANCELLED" desc="The placeholder text when the user canceled downloading the plug-in."> + <message name="IDS_PLUGIN_DOWNLOAD_CANCELLED" desc="The placeholder text when the user canceled downloading the plugin."> <ph name="PLUGIN_NAME">$1<ex>Realplayer</ex></ph> download was canceled. </message> - <message name="IDS_PLUGIN_INSTALLING" desc="The placeholder text when installing a missing plug-in."> + <message name="IDS_PLUGIN_INSTALLING" desc="The placeholder text when installing a missing plugin."> When <ph name="PLUGIN_NAME">$1<ex>Realplayer</ex></ph> has finished installing, reload the page to activate it. </message> - <message name="IDS_PLUGIN_UPDATING" desc="The placeholder text when updating an out-of-date plug-in."> + <message name="IDS_PLUGIN_UPDATING" desc="The placeholder text when updating an out-of-date plugin."> When <ph name="PLUGIN_NAME">$1<ex>Realplayer</ex></ph> has finished updating, reload the page to activate it. </message> - <message name="IDS_PLUGIN_FOUND" desc="The placeholder text for a known plug-in that is not installed."> + <message name="IDS_PLUGIN_FOUND" desc="The placeholder text for a known plugin that is not installed."> <ph name="PLUGIN_NAME">$1<ex>Quicktime</ex></ph> is required to display this content. </message> - <message name="IDS_PLUGIN_CONFIRM_INSTALL_DIALOG_TITLE" desc="Title of the plug-in installation confirmation dialog."> + <message name="IDS_PLUGIN_CONFIRM_INSTALL_DIALOG_TITLE" desc="Title of the plugin installation confirmation dialog."> Install <ph name="PLUGIN_NAME">$1<ex>Realplayer</ex></ph> </message> - <message name="IDS_PLUGIN_CONFIRM_INSTALL_DIALOG_MSG" desc="Message of the plug-in installation confirmation dialog."> - Are you sure you want to install <ph name="PLUGIN_NAME">$1<ex>Realplayer</ex></ph>? You should only install plug-ins that you trust. + <message name="IDS_PLUGIN_CONFIRM_INSTALL_DIALOG_MSG" desc="Message of the plugin installation confirmation dialog."> + Are you sure you want to install <ph name="PLUGIN_NAME">$1<ex>Realplayer</ex></ph>? You should only install plugins that you trust. </message> - <message name="IDS_PLUGIN_CONFIRM_INSTALL_DIALOG_ACCEPT_BUTTON" desc="Button title to install a missing plug-in."> + <message name="IDS_PLUGIN_CONFIRM_INSTALL_DIALOG_ACCEPT_BUTTON" desc="Button title to install a missing plugin."> Install </message> - <message name="IDS_PLUGIN_DISABLED" desc="The placeholder text for a disabled plug-in."> + <message name="IDS_PLUGIN_DISABLED" desc="The placeholder text for a disabled plugin."> <ph name="PLUGIN_NAME">$1<ex>Flash</ex></ph> has been disabled. To re-enable it, please go to <ph name="CHROME_PLUGINS_LINK">chrome://plugins</ph>. </message> @@ -7238,25 +7238,25 @@ Deny </message> <message name="IDS_BLOCKED_PPAPI_BROKER_TITLE" desc="Title for the page action when Pepper broker access was blocked"> - An unsandboxed plug-in was prevented from running on this page. + An unsandboxed plugin was prevented from running on this page. </message> <message name="IDS_ALLOWED_PPAPI_BROKER_TITLE" desc="Title for the page action when Pepper broker access was allowed"> - An unsandboxed plug-in was allowed to run running on this page. + An unsandboxed plugin was allowed to run running on this page. </message> <message name="IDS_BLOCKED_PPAPI_BROKER_UNBLOCK" desc="Radio button to unblock the Pepper broker"> - Always allow unsandboxed plug-ins on <ph name="HOST">$1<ex>example.com</ex></ph> + Always allow unsandboxed plugins on <ph name="HOST">$1<ex>example.com</ex></ph> </message> <message name="IDS_BLOCKED_PPAPI_BROKER_NO_ACTION" desc="Radio button to keep blocking the Pepper broker"> - Continue blocking unsandboxed plug-ins + Continue blocking unsandboxed plugins </message> <message name="IDS_ALLOWED_PPAPI_BROKER_NO_ACTION" desc="Radio button to keep allowing the Pepper broker"> - Continue allowing unsandboxed plug-ins + Continue allowing unsandboxed plugins </message> <message name="IDS_ALLOWED_PPAPI_BROKER_BLOCK" desc="Radio button to block the Pepper broker"> - Never allow unsandboxed plug-ins on <ph name="HOST">$1<ex>example.com</ex></ph> + Never allow unsandboxed plugins on <ph name="HOST">$1<ex>example.com</ex></ph> </message> <message name="IDS_PPAPI_BROKER_BUBBLE_MANAGE_LINK" desc="Link title to manage Pepper broker settings"> - Manage unsandboxed plug-in blocking... + Manage unsandboxed plugin blocking... </message> <!-- Blocked Displaying/Running Insecure Content info bar --> @@ -7607,10 +7607,10 @@ Unknown </message> <message name="IDS_BROWSER_HANGMONITOR_TITLE" desc="Title for the hung plugin message"> - Plug-in Unresponsive + Plugin Unresponsive </message> <message name="IDS_BROWSER_HANGMONITOR" desc="A plugin on a page has hung"> - The following plug-in is unresponsive: <ph name="PLUGIN_NAME">$1 + The following plugin is unresponsive: <ph name="PLUGIN_NAME">$1 <ex>Shockwave </ex></ph>Would you like to stop it? </message> @@ -7628,10 +7628,10 @@ Kill pages </message> <message name="IDS_BROWSER_HANGMONITOR_PLUGIN_INFOBAR" desc="The text of the infobar notifying the user that a plugin has hung"> - A plug-in (<ph name="PLUGIN_NAME">$1<ex>Flash</ex></ph>) isn't responding. + A plugin (<ph name="PLUGIN_NAME">$1<ex>Flash</ex></ph>) isn't responding. </message> <message name="IDS_BROWSER_HANGMONITOR_PLUGIN_INFOBAR_KILLBUTTON" desc="The button on the hung plugin infobar (...PLUGIN_INFOBAR above) to terminate the plugin"> - Stop plug-in + Stop plugin </message> <!-- Passwords and Exceptions Dialog --> @@ -7915,7 +7915,7 @@ Cookies and other site data </message> <message name="IDS_DEL_COOKIES_FLASH_CHKBOX" desc="Checkbox for deleting Cookies and other site data"> - Cookies and other site and plug-in data + Cookies and other site and plugin data </message> <message name="IDS_DEL_PASSWORDS_CHKBOX" desc="Checkbox for deleting Passwords"> Passwords @@ -8120,7 +8120,7 @@ Clear cookies and other site data when you close your browser </message> <message name="IDS_COOKIES_LSO_CLEAR_WHEN_CLOSE_CHKBOX" desc="A checkbox in the Content Settings dialog for removing all cookies on when browser is closed."> - Clear cookies and other site and plug-in data when you close your browser + Clear cookies and other site and plugin data when you close your browser </message> </if> <if expr="is_macosx"> @@ -8128,7 +8128,7 @@ Clear cookies and other site data when you quit your browser </message> <message name="IDS_COOKIES_LSO_CLEAR_WHEN_CLOSE_CHKBOX" desc="A checkbox in the Content Settings dialog for removing all cookies on when browser is quit (Mac)."> - Clear cookies and other site and plug-in data when you quit your browser + Clear cookies and other site and plugin data when you quit your browser </message> </if> <if expr="chromeos"> @@ -8136,7 +8136,7 @@ Clear cookies and other site data when you log out </message> <message name="IDS_COOKIES_LSO_CLEAR_WHEN_CLOSE_CHKBOX" desc="A checkbox in the Content Settings dialog for removing all cookies on when browser is closed."> - Clear cookies and other site and plug-in data when you log out + Clear cookies and other site and plugin data when you log out </message> </if> @@ -8172,23 +8172,23 @@ Pop-ups blocked (<ph name="POP_UP_COUNT">$1<ex>3</ex></ph>) </message> </if> - <message name="IDS_PLUGIN_TAB_LABEL" desc="Label for Plug-ins tab on Content Settings dialog"> - Plug-ins + <message name="IDS_PLUGIN_TAB_LABEL" desc="Label for Plugins tab on Content Settings dialog"> + Plugins </message> <message name="IDS_PLUGIN_HEADER" desc="Header for plugin exception management page on Content Settings dialog"> - Plug-in exceptions + Plugin exceptions </message> - <message name="IDS_PLUGIN_ALLOW_RADIO" desc="A radio button in the Content Settings dialog for allowing plug-ins use on any site."> + <message name="IDS_PLUGIN_ALLOW_RADIO" desc="A radio button in the Content Settings dialog for allowing plugins use on any site."> Run all plugin content (recommended) </message> <message name="IDS_PLUGIN_DETECT_RADIO" desc="A radio button in the Content Settings dialog for detecting and running important plugin content only."> Detect and run important plugin content </message> - <message name="IDS_PLUGIN_BLOCK_RADIO" desc="A radio button in the Content Settings dialog for gating plug-ins on a context menu activation."> + <message name="IDS_PLUGIN_BLOCK_RADIO" desc="A radio button in the Content Settings dialog for gating plugins on a context menu activation."> Let me choose when to run plugin content </message> - <message name="IDS_PLUGIN_MANAGE_INDIVIDUAL" desc="Link to manage individual plug-ins"> - Manage individual plug-ins... + <message name="IDS_PLUGIN_MANAGE_INDIVIDUAL" desc="Link to manage individual plugins"> + Manage individual plugins... </message> <message name="IDS_JAVASCRIPT_TAB_LABEL" desc="Label for JavaScript tab on Content Settings dialog"> JavaScript @@ -8341,19 +8341,19 @@ </message> </if> <message name="IDS_PPAPI_BROKER_TAB_LABEL" desc="Label for PPAPI broker tab on Content Settings dialog"> - Unsandboxed plug-in access + Unsandboxed plugin access </message> <message name="IDS_PPAPI_BROKER_HEADER" desc="Label for PPAPI broker tab exception management page on Content Settings dialog"> - Unsandboxed plug-in access exceptions + Unsandboxed plugin access exceptions </message> <message name="IDS_PPAPI_BROKER_ALLOW_RADIO" desc="A radio button in Content Settings dialog to allow all sites to access the PPAPI broker."> - Allow all sites to use a plug-in to access your computer + Allow all sites to use a plugin to access your computer </message> <message name="IDS_PPAPI_BROKER_BLOCK_RADIO" desc="A radio button in Content Settings dialog to deny all sites to access the PPAPI broker."> - Do not allow any sites to use a plug-in to access your computer + Do not allow any sites to use a plugin to access your computer </message> <message name="IDS_PPAPI_BROKER_ASK_RADIO" desc="A radio button in Content Settings dialog to allow site to query the permision to access the PPAPI broker."> - Ask when a site wants to use a plug-in to access your computer (recommended) + Ask when a site wants to use a plugin to access your computer (recommended) </message> <message name="IDS_EXCEPTIONS_MANAGE" desc="The label on the button that launches the exceptions management page for a given content type"> @@ -12164,7 +12164,7 @@ <ph name="PLUGIN_NAME">$1<ex>Quicktime</ex></ph> is required to display some elements on this page. </message> <message name="IDS_PLUGININSTALLER_INSTALLPLUGIN_BUTTON" desc="Info Bar button to install missing plugin"> - Install plug-in... + Install plugin... </message> <message name="IDS_PLUGININSTALLER_PROBLEMSINSTALLING" desc="Infobar text for link to help center"> Problems installing? @@ -14142,6 +14142,9 @@ <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_BUTTON" desc="Text shown on a button that confirms removal of a user."> Remove This Person </message> + <message name="IDS_CREATE_SUPERVISED_USER_MENU_LABEL" desc="Text shown on a menu option that creates a legacy supervised user."> + Add Supervised Person + </message> </if> <if expr="chromeos"> <message name="IDS_ADD_USER_BUTTON" desc="Text shown on an add user button on login/locker screen"> @@ -14150,6 +14153,9 @@ <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_BUTTON" desc="Text shown on a button that confirms removal of a user."> Remove This User </message> + <message name="IDS_CREATE_SUPERVISED_USER_MENU_LABEL" desc="Text shown on a menu option that creates a legacy supervised user."> + Add Supervised User + </message> </if> <message name="IDS_SCREEN_LOCK_SIGN_OUT"> Sign out @@ -14166,6 +14172,9 @@ <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_BUTTON" desc="Text shown on a button that confirms removal of a user."> Remove this person </message> + <message name="IDS_CREATE_SUPERVISED_USER_MENU_LABEL" desc="Text shown on a menu option that creates a legacy supervised user."> + Add supervised person + </message> </if> <if expr="chromeos"> <message name="IDS_ADD_USER_BUTTON" desc="Text shown on an add user button on login/locker screen"> @@ -14174,6 +14183,9 @@ <message name="IDS_LOGIN_POD_USER_REMOVE_WARNING_BUTTON" desc="Text shown on a button that confirms removal of a user."> Remove this user </message> + <message name="IDS_CREATE_SUPERVISED_USER_MENU_LABEL" desc="Text shown on a menu option that creates a legacy supervised user."> + Add supervised user + </message> </if> <message name="IDS_SCREEN_LOCK_SIGN_OUT"> Sign out
diff --git a/chrome/app/google_chrome_strings.grd b/chrome/app/google_chrome_strings.grd index a9dc0cf..24fce29 100644 --- a/chrome/app/google_chrome_strings.grd +++ b/chrome/app/google_chrome_strings.grd
@@ -170,10 +170,10 @@ https://support.google.com/chrome/?p=ib_chromeframe </message> <message name="IDS_CHROME_FRAME_TURNDOWN_TEXT_IE_OLDER" desc="Text of Chrome Frame turndown prompt for IE 6, 7, and 8"> - This site is using the retired Chrome Frame plug-in which no longer receives security and stability updates. Please uninstall it and upgrade to a modern browser. + This site is using the retired Chrome Frame plugin which no longer receives security and stability updates. Please uninstall it and upgrade to a modern browser. </message> <message name="IDS_CHROME_FRAME_TURNDOWN_TEXT_IE_NEWER" desc="Text of Chrome Frame turndown prompt for IE 9 and 10"> - This site is using the retired Chrome Frame plug-in which no longer receives security and stability updates. Please uninstall it and upgrade to a modern browser. + This site is using the retired Chrome Frame plugin which no longer receives security and stability updates. Please uninstall it and upgrade to a modern browser. </message> <message name="IDS_SHORTCUT_NEW_WINDOW" desc="The text label of the New window shortcut context menu entry as of Windows 8"> New window
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index a12ba30..b2968ddb 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -93,7 +93,7 @@ "//components/domain_reliability", "//components/enhanced_bookmarks", "//components/favicon_base", - "//components/favicon/core", + "//components/favicon/core/browser", "//components/feedback", "//components/gcm_driver", "//components/google/core/browser",
diff --git a/chrome/browser/DEPS b/chrome/browser/DEPS index d4eb584..149a97e 100644 --- a/chrome/browser/DEPS +++ b/chrome/browser/DEPS
@@ -35,6 +35,7 @@ "+components/dom_distiller", "+components/domain_reliability", "+components/enhanced_bookmarks", + "+components/favicon", "+components/favicon_base", "+components/feedback", "+components/gcm_driver",
diff --git a/chrome/browser/android/bookmarks/partner_bookmarks_reader.cc b/chrome/browser/android/bookmarks/partner_bookmarks_reader.cc index 4be9c0ea..a91271f 100644 --- a/chrome/browser/android/bookmarks/partner_bookmarks_reader.cc +++ b/chrome/browser/android/bookmarks/partner_bookmarks_reader.cc
@@ -9,11 +9,11 @@ #include "base/logging.h" #include "chrome/browser/android/bookmarks/partner_bookmarks_shim.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "components/bookmarks/browser/bookmark_model.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_types.h" #include "content/public/browser/browser_thread.h" #include "jni/PartnerBookmarksReader_jni.h"
diff --git a/chrome/browser/android/favicon_helper.cc b/chrome/browser/android/favicon_helper.cc index 50b21d6..871977e 100644 --- a/chrome/browser/android/favicon_helper.cc +++ b/chrome/browser/android/favicon_helper.cc
@@ -13,7 +13,6 @@ #include "base/bind.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_android.h" @@ -21,6 +20,7 @@ #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" +#include "components/favicon/core/browser/favicon_service.h" #include "jni/FaviconHelper_jni.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/android/java_bitmap.h"
diff --git a/chrome/browser/android/provider/chrome_browser_provider.cc b/chrome/browser/android/provider/chrome_browser_provider.cc index 13a5280..d07a08d 100644 --- a/chrome/browser/android/provider/chrome_browser_provider.cc +++ b/chrome/browser/android/provider/chrome_browser_provider.cc
@@ -23,7 +23,6 @@ #include "chrome/browser/bookmarks/chrome_bookmark_client.h" #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/android/sqlite_cursor.h" #include "chrome/browser/history/history_service_factory.h" @@ -33,6 +32,7 @@ #include "chrome/browser/search_engines/template_url_service_factory.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/android/android_history_types.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/top_sites.h"
diff --git a/chrome/browser/android/shortcut_helper.cc b/chrome/browser/android/shortcut_helper.cc index bb6df89..f1f0bf8 100644 --- a/chrome/browser/android/shortcut_helper.cc +++ b/chrome/browser/android/shortcut_helper.cc
@@ -16,7 +16,6 @@ #include "base/task/cancelable_task_tracker.h" #include "base/threading/worker_pool.h" #include "chrome/browser/banners/app_banner_settings_helper.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/manifest/manifest_icon_selector.h" #include "chrome/browser/profiles/profile.h" @@ -24,6 +23,7 @@ #include "chrome/common/render_messages.h" #include "chrome/common/web_application_info.h" #include "components/dom_distiller/core/url_utils.h" +#include "components/favicon/core/browser/favicon_service.h" #include "content/public/browser/user_metrics.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" @@ -130,6 +130,7 @@ web_contents()->DownloadImage(icon_src, false, preferred_icon_size_in_px_, + false, base::Bind(&ShortcutHelper::OnDidDownloadIcon, weak_ptr_factory_.GetWeakPtr())); manifest_icon_status_ = MANIFEST_ICON_STATUS_FETCHING;
diff --git a/chrome/browser/android/tab_android.h b/chrome/browser/android/tab_android.h index 1bb5c7e..9ee1255 100644 --- a/chrome/browser/android/tab_android.h +++ b/chrome/browser/android/tab_android.h
@@ -11,12 +11,12 @@ #include "base/callback_forward.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" -#include "chrome/browser/favicon/favicon_tab_helper_observer.h" #include "chrome/browser/search/instant_service_observer.h" #include "chrome/browser/sync/glue/synced_tab_delegate_android.h" #include "chrome/browser/ui/search/search_tab_helper_delegate.h" #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h" #include "chrome/browser/ui/toolbar/toolbar_model.h" +#include "components/favicon/core/browser/favicon_tab_helper_observer.h" #include "components/sessions/session_id.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h"
diff --git a/chrome/browser/apps/ephemeral_app_launcher.cc b/chrome/browser/apps/ephemeral_app_launcher.cc index 469602c..b480345 100644 --- a/chrome/browser/apps/ephemeral_app_launcher.cc +++ b/chrome/browser/apps/ephemeral_app_launcher.cc
@@ -393,9 +393,7 @@ // Skip the prompt by returning null if the app does not need to display // permission warnings. - extensions::PermissionMessages permissions = - extension->permissions_data()->GetPermissionMessages(); - if (permissions.empty()) + if (extension->permissions_data()->GetPermissionMessageStrings().empty()) return NULL; return make_scoped_refptr(new ExtensionInstallPrompt::Prompt(
diff --git a/chrome/browser/bookmarks/bookmark_html_writer.cc b/chrome/browser/bookmarks/bookmark_html_writer.cc index eda8af0..73fcf38 100644 --- a/chrome/browser/bookmarks/bookmark_html_writer.cc +++ b/chrome/browser/bookmarks/bookmark_html_writer.cc
@@ -17,10 +17,10 @@ #include "base/values.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "components/bookmarks/browser/bookmark_codec.h" #include "components/bookmarks/browser/bookmark_model.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_types.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_source.h"
diff --git a/chrome/browser/bookmarks/bookmark_html_writer_unittest.cc b/chrome/browser/bookmarks/bookmark_html_writer_unittest.cc index 4dcc1937..d4203a16 100644 --- a/chrome/browser/bookmarks/bookmark_html_writer_unittest.cc +++ b/chrome/browser/bookmarks/bookmark_html_writer_unittest.cc
@@ -12,7 +12,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/common/importer/imported_bookmark_entry.h" @@ -21,6 +20,7 @@ #include "chrome/utility/importer/bookmark_html_reader.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/test/bookmark_test_helpers.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_usage_data.h" #include "components/history/core/browser/history_service.h" #include "content/public/test/test_browser_thread_bundle.h"
diff --git a/chrome/browser/bookmarks/chrome_bookmark_client.cc b/chrome/browser/bookmarks/chrome_bookmark_client.cc index 863000e..14e2f1a 100644 --- a/chrome/browser/bookmarks/chrome_bookmark_client.cc +++ b/chrome/browser/bookmarks/chrome_bookmark_client.cc
@@ -8,7 +8,6 @@ #include "base/bind_helpers.h" #include "base/logging.h" #include "base/values.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/policy/profile_policy_connector_factory.h" @@ -16,6 +15,7 @@ #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_node.h" #include "components/bookmarks/browser/bookmark_utils.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/url_database.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/browsing_data/browsing_data_remover.h b/chrome/browser/browsing_data/browsing_data_remover.h index 174458d..84160cb 100644 --- a/chrome/browser/browsing_data/browsing_data_remover.h +++ b/chrome/browser/browsing_data/browsing_data_remover.h
@@ -273,7 +273,7 @@ // clears the respective waiting flag, and invokes NotifyAndDeleteIfDone. void OnKeywordsLoaded(); - // Called when plug-in data has been cleared. Invokes NotifyAndDeleteIfDone. + // Called when plugin data has been cleared. Invokes NotifyAndDeleteIfDone. void OnWaitableEventSignaled(base::WaitableEvent* waitable_event); #if defined(ENABLE_PLUGINS)
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 0bb15bbd..e3ae843 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -64,7 +64,6 @@ #include "chrome/browser/search/instant_service_factory.h" #include "chrome/browser/search/search.h" #include "chrome/browser/search_engines/search_provider_install_state_message_filter.h" -#include "chrome/browser/signin/principals_message_filter.h" #include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h" #include "chrome/browser/speech/tts_controller.h" #include "chrome/browser/speech/tts_message_filter.h" @@ -943,9 +942,6 @@ #if defined(OS_ANDROID) host->AddFilter(new cdm::CdmMessageFilterAndroid()); #endif - if (switches::IsEnableAccountConsistency()) - host->AddFilter(new PrincipalsMessageFilter(id)); - DataReductionProxyChromeSettings* data_reduction_proxy_settings = DataReductionProxyChromeSettingsFactory::GetForBrowserContext(profile); host->AddFilter(new data_reduction_proxy::DataReductionProxyMessageFilter(
diff --git a/chrome/browser/component_updater/pepper_flash_component_installer.cc b/chrome/browser/component_updater/pepper_flash_component_installer.cc index 7fbe733..d334a96 100644 --- a/chrome/browser/component_updater/pepper_flash_component_installer.cc +++ b/chrome/browser/component_updater/pepper_flash_component_installer.cc
@@ -139,7 +139,7 @@ bool IsPepperFlash(const content::WebPluginInfo& plugin) { // We try to recognize Pepper Flash by the following criteria: - // * It is a Pepper plug-in. + // * It is a Pepper plugin. // * It has the special Flash permissions. return plugin.is_pepper_plugin() && (plugin.pepper_permissions & ppapi::PERMISSION_FLASH);
diff --git a/chrome/browser/content_settings/content_settings_browsertest.cc b/chrome/browser/content_settings/content_settings_browsertest.cc index 1ed96bb..1fb1785 100644 --- a/chrome/browser/content_settings/content_settings_browsertest.cc +++ b/chrome/browser/content_settings/content_settings_browsertest.cc
@@ -717,7 +717,7 @@ #endif // defined(ENABLE_PEPPER_CDMS) // The following tests verify that Pepper plugins that use JavaScript settings -// instead of Plug-ins settings still work when Plug-ins are blocked. +// instead of Plugins settings still work when Plugins are blocked. #if defined(ENABLE_PEPPER_CDMS) // The plugin successfully loaded above is blocked.
diff --git a/chrome/browser/download/download_target_determiner_unittest.cc b/chrome/browser/download/download_target_determiner_unittest.cc index 9c2d722a..0418af8 100644 --- a/chrome/browser/download/download_target_determiner_unittest.cc +++ b/chrome/browser/download/download_target_determiner_unittest.cc
@@ -2105,7 +2105,7 @@ GetPathInDownloadDir(kInitialPath), item.get()); EXPECT_FALSE(target_info->is_filetype_handled_safely); - // Now register an unsandboxed PPAPI plug-in. This plugin should not be + // Now register an unsandboxed PPAPI plugin. This plugin should not be // considered secure. ScopedRegisterInternalPlugin ppapi_unsandboxed_plugin( plugin_service,
diff --git a/chrome/browser/download/download_target_info.h b/chrome/browser/download/download_target_info.h index 7d181b6..8380560e 100644 --- a/chrome/browser/download/download_target_info.h +++ b/chrome/browser/download/download_target_info.h
@@ -51,7 +51,7 @@ // Whether the |target_path| would be handled safely by the browser if it were // to be opened with a file:// URL. This can be used later to decide how file // opens should be handled. The file is considered to be handled safely if the - // filetype is supported by the renderer or a sandboxed plug-in. + // filetype is supported by the renderer or a sandboxed plugin. bool is_filetype_handled_safely; };
diff --git a/chrome/browser/extensions/api/log_private/log_private_api.h b/chrome/browser/extensions/api/log_private/log_private_api.h index 4fbeaf8..a3314a0a 100644 --- a/chrome/browser/extensions/api/log_private/log_private_api.h +++ b/chrome/browser/extensions/api/log_private/log_private_api.h
@@ -8,6 +8,7 @@ #include <set> #include <string> +#include "base/files/scoped_file.h" #include "base/scoped_observer.h" #include "chrome/browser/extensions/api/log_private/filter_handler.h" #include "chrome/browser/extensions/api/log_private/log_parser.h" @@ -88,14 +89,12 @@ void PostPendingEntries(); void AddEntriesOnUI(scoped_ptr<base::ListValue> value); - // Initializes a new instance of net::NetLogLogger and passes it back via - // |net_logger| param. - void InitializeNetLogger(const std::string& owner_extension_id, - net::NetLogLogger** net_logger); + // Creates a file for use with a new instance of net::NetLogLogger. + void CreateFileForNetLogger( + const std::string& owner_extension_id, base::ScopedFILE* file); // Starts observing network events with a new |net_logger| instance. - void StartObservingNetEvents(IOThread* io_thread, - net::NetLogLogger** net_logger); + void StartObservingNetEvents(IOThread* io_thread, base::ScopedFILE* file); void MaybeStartNetInternalLogging(const std::string& caller_extension_id, IOThread* io_thread, api::log_private::EventSink event_sink);
diff --git a/chrome/browser/extensions/api/log_private/log_private_api_chromeos.cc b/chrome/browser/extensions/api/log_private/log_private_api_chromeos.cc index 0b6670e..fc9c391b 100644 --- a/chrome/browser/extensions/api/log_private/log_private_api_chromeos.cc +++ b/chrome/browser/extensions/api/log_private/log_private_api_chromeos.cc
@@ -254,10 +254,10 @@ } } -void LogPrivateAPI::InitializeNetLogger(const std::string& owner_extension_id, - net::NetLogLogger** net_log_logger) { +void LogPrivateAPI::CreateFileForNetLogger( + const std::string& owner_extension_id, + base::ScopedFILE* file) { DCHECK(IsRunningOnSequenceThread()); - (*net_log_logger) = NULL; // Create app-specific subdirectory in session logs folder. base::FilePath app_log_dir = GetAppLogDirectory().Append(owner_extension_id); @@ -270,28 +270,27 @@ base::FilePath file_path = app_log_dir.Append(kLogFileNameBase); file_path = logging::GenerateTimestampedName(file_path, base::Time::Now()); - FILE* file = NULL; - file = fopen(file_path.value().c_str(), "w"); - if (file == NULL) { + FILE* file_ptr = fopen(file_path.value().c_str(), "w"); + if (file_ptr == nullptr) { LOG(ERROR) << "Could not open " << file_path.value(); return; } RegisterTempFile(owner_extension_id, file_path); - scoped_ptr<base::Value> constants(net::NetLogLogger::GetConstants()); - *net_log_logger = new net::NetLogLogger(file, *constants); - (*net_log_logger)->set_log_level(net::NetLog::LOG_ALL_BUT_BYTES); + return file->reset(file_ptr); } void LogPrivateAPI::StartObservingNetEvents( IOThread* io_thread, - net::NetLogLogger** net_log_logger) { + base::ScopedFILE* file) { DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (!(*net_log_logger)) + if (!file->get()) return; - net_log_logger_.reset(*net_log_logger); - net_log_logger_->StartObserving(io_thread->net_log()); + net_log_logger_.reset(new net::NetLogLogger()); + net_log_logger_->set_log_level(net::NetLog::LOG_ALL_BUT_BYTES); + net_log_logger_->StartObserving(io_thread->net_log(), file->Pass(), nullptr, + nullptr); } void LogPrivateAPI::MaybeStartNetInternalLogging( @@ -309,19 +308,19 @@ break; } case api::log_private::EVENT_SINK_FILE: { - net::NetLogLogger** net_logger_ptr = new net::NetLogLogger* [1]; - // Initialize net logger on the blocking pool and start observing event - // with in on IO thread. + base::ScopedFILE* file = new base::ScopedFILE(); + // Initialize a FILE on the blocking pool and start observing event + // on IO thread. GetSequencedTaskRunner()->PostTaskAndReply( FROM_HERE, - base::Bind(&LogPrivateAPI::InitializeNetLogger, + base::Bind(&LogPrivateAPI::CreateFileForNetLogger, base::Unretained(this), caller_extension_id, - net_logger_ptr), + file), base::Bind(&LogPrivateAPI::StartObservingNetEvents, base::Unretained(this), io_thread, - base::Owned(net_logger_ptr))); + base::Owned(file))); break; } case api::log_private::EVENT_SINK_NONE: { @@ -360,7 +359,7 @@ net_log()->RemoveThreadSafeObserver(this); break; case api::log_private::EVENT_SINK_FILE: - net_log_logger_->StopObserving(); + net_log_logger_->StopObserving(nullptr); net_log_logger_.reset(); break; case api::log_private::EVENT_SINK_NONE:
diff --git a/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc b/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc index 8b0406ff..5d63af5 100644 --- a/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc +++ b/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc
@@ -10,7 +10,6 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/launch_util.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/safe_json_parser.h" @@ -24,6 +23,7 @@ #include "chrome/common/extensions/extension_metrics.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "chrome/common/web_application_info.h" +#include "components/favicon/core/browser/favicon_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/utility_process_host.h" #include "content/public/browser/utility_process_host_client.h"
diff --git a/chrome/browser/extensions/api/permissions/permissions_api.cc b/chrome/browser/extensions/api/permissions/permissions_api.cc index d7346ec..4618d98 100644 --- a/chrome/browser/extensions/api/permissions/permissions_api.cc +++ b/chrome/browser/extensions/api/permissions/permissions_api.cc
@@ -218,10 +218,11 @@ // We don't need to show the prompt if there are no new warnings, or if // we're skipping the confirmation UI. All extension types but INTERNAL // are allowed to silently increase their permission level. - bool has_no_warnings = PermissionMessageProvider::Get() - ->GetWarningMessages(requested_permissions_.get(), - extension()->GetType()) - .empty(); + bool has_no_warnings = + PermissionMessageProvider::Get() + ->GetLegacyWarningMessages(requested_permissions_.get(), + extension()->GetType()) + .empty(); if (auto_confirm_for_tests == PROCEED || has_no_warnings || extension_->location() == Manifest::COMPONENT) { InstallUIProceed();
diff --git a/chrome/browser/extensions/api/socket/tls_socket_unittest.cc b/chrome/browser/extensions/api/socket/tls_socket_unittest.cc index a427bd0..a0c9cdee 100644 --- a/chrome/browser/extensions/api/socket/tls_socket_unittest.cc +++ b/chrome/browser/extensions/api/socket/tls_socket_unittest.cc
@@ -60,9 +60,6 @@ unsigned char*, unsigned int)); MOCK_METHOD1(GetTLSUniqueChannelBinding, int(std::string*)); - MOCK_CONST_METHOD0(GetSessionCacheKey, std::string()); - MOCK_CONST_METHOD0(InSessionCache, bool()); - MOCK_METHOD1(SetHandshakeCompletionCallback, void(const base::Closure&)); MOCK_METHOD1(GetSSLCertRequestInfo, void(net::SSLCertRequestInfo*)); MOCK_METHOD1(GetNextProto, net::SSLClientSocket::NextProtoStatus(std::string*));
diff --git a/chrome/browser/extensions/extension_disabled_ui.cc b/chrome/browser/extensions/extension_disabled_ui.cc index 3d6ce08..94595af 100644 --- a/chrome/browser/extensions/extension_disabled_ui.cc +++ b/chrome/browser/extensions/extension_disabled_ui.cc
@@ -293,7 +293,7 @@ ExtensionDisabledGlobalError::GetBubbleViewMessages() { std::vector<base::string16> messages; std::vector<base::string16> permission_warnings = - extensions::PermissionMessageProvider::Get()->GetWarningMessages( + extensions::PermissionMessageProvider::Get()->GetLegacyWarningMessages( extension_->permissions_data()->active_permissions().get(), extension_->GetType()); if (is_remote_install_) {
diff --git a/chrome/browser/extensions/extension_install_prompt.cc b/chrome/browser/extensions/extension_install_prompt.cc index e8dea3cb..670d23e 100644 --- a/chrome/browser/extensions/extension_install_prompt.cc +++ b/chrome/browser/extensions/extension_install_prompt.cc
@@ -928,21 +928,23 @@ extension_ ? extension_->GetType() : Manifest::TYPE_UNKNOWN; const extensions::PermissionMessageProvider* message_provider = extensions::PermissionMessageProvider::Get(); - prompt_->SetPermissions(message_provider->GetWarningMessages( + prompt_->SetPermissions(message_provider->GetLegacyWarningMessages( permissions_to_display.get(), type), REGULAR_PERMISSIONS); - prompt_->SetPermissionsDetails(message_provider->GetWarningMessagesDetails( - permissions_to_display.get(), type), - REGULAR_PERMISSIONS); + prompt_->SetPermissionsDetails( + message_provider->GetLegacyWarningMessagesDetails( + permissions_to_display.get(), type), + REGULAR_PERMISSIONS); scoped_refptr<const extensions::PermissionSet> withheld = extension_->permissions_data()->withheld_permissions(); if (!withheld->IsEmpty()) { prompt_->SetPermissions( - message_provider->GetWarningMessages(withheld.get(), type), + message_provider->GetLegacyWarningMessages(withheld.get(), type), PermissionsType::WITHHELD_PERMISSIONS); prompt_->SetPermissionsDetails( - message_provider->GetWarningMessagesDetails(withheld.get(), type), + message_provider->GetLegacyWarningMessagesDetails(withheld.get(), + type), PermissionsType::WITHHELD_PERMISSIONS); } }
diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc index 7eae97d..cc83981 100644 --- a/chrome/browser/extensions/extension_service.cc +++ b/chrome/browser/extensions/extension_service.cc
@@ -109,7 +109,7 @@ using extensions::ManagementPolicy; using extensions::Manifest; using extensions::PermissionMessage; -using extensions::PermissionMessages; +using extensions::PermissionMessageIDs; using extensions::PermissionSet; using extensions::SharedModuleInfo; using extensions::SharedModuleService; @@ -1017,14 +1017,13 @@ PermissionMessage::kEnumBoundary + 1, base::HistogramBase::kUmaTargetedHistogramFlag); - PermissionMessages permissions = - extension->permissions_data()->GetPermissionMessages(); + PermissionMessageIDs permissions = + extension->permissions_data()->GetLegacyPermissionMessageIDs(); if (permissions.empty()) { counter->Add(PermissionMessage::kNone); } else { - for (PermissionMessages::iterator it = permissions.begin(); - it != permissions.end(); ++it) - counter->Add(it->id()); + for (PermissionMessage::ID id : permissions) + counter->Add(id); } }
diff --git a/chrome/browser/extensions/extension_web_ui.cc b/chrome/browser/extensions/extension_web_ui.cc index 3048756..bd7d06b 100644 --- a/chrome/browser/extensions/extension_web_ui.cc +++ b/chrome/browser/extensions/extension_web_ui.cc
@@ -15,11 +15,11 @@ #include "chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/extension_util.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/url_constants.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_util.h" #include "components/pref_registry/pref_registry_syncable.h" #include "content/public/browser/navigation_controller.h"
diff --git a/chrome/browser/extensions/favicon_downloader.cc b/chrome/browser/extensions/favicon_downloader.cc index bc93869..043a509 100644 --- a/chrome/browser/extensions/favicon_downloader.cc +++ b/chrome/browser/extensions/favicon_downloader.cc
@@ -42,6 +42,7 @@ url, true, // is_favicon 0, // no max size + false, // normal cache policy base::Bind(&FaviconDownloader::DidDownloadFavicon, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/extensions/permission_messages_unittest.cc b/chrome/browser/extensions/permission_messages_unittest.cc index 0e9066c..1164f3f 100644 --- a/chrome/browser/extensions/permission_messages_unittest.cc +++ b/chrome/browser/extensions/permission_messages_unittest.cc
@@ -113,8 +113,8 @@ private: std::vector<base::string16> GetMessages( scoped_refptr<const PermissionSet> permissions) { - return message_provider_->GetWarningMessages(permissions.get(), - app_->GetType()); + return message_provider_->GetLegacyWarningMessages(permissions.get(), + app_->GetType()); } extensions::TestExtensionEnvironment env_;
diff --git a/chrome/browser/extensions/plugin_apitest.cc b/chrome/browser/extensions/plugin_apitest.cc index 02f03f3..c6fc2c1 100644 --- a/chrome/browser/extensions/plugin_apitest.cc +++ b/chrome/browser/extensions/plugin_apitest.cc
@@ -166,15 +166,15 @@ #if defined(OS_CHROMEOS) EXPECT_FALSE(result); #else - // TODO(bauerb): This might wrongly fail if the plug-in takes too long - // to load. Extension-private plug-ins don't appear in navigator.plugins, so - // we can't check for the plug-in in Javascript. + // TODO(bauerb): This might wrongly fail if the plugin takes too long + // to load. Extension-private plugins don't appear in navigator.plugins, so + // we can't check for the plugin in Javascript. EXPECT_TRUE(result); #endif - // Regression test for http://crbug.com/131811: The plug-in should be + // Regression test for http://crbug.com/131811: The plugin should be // whitelisted for the extension (and only for the extension), so it should be - // loaded even if content settings are set to block plug-ins. + // loaded even if content settings are set to block plugins. browser()->profile()->GetHostContentSettingsMap()->SetDefaultContentSetting( CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_BLOCK); ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
diff --git a/chrome/browser/extensions/plugin_manager.h b/chrome/browser/extensions/plugin_manager.h index 16a6aa7..b0424ab 100644 --- a/chrome/browser/extensions/plugin_manager.h +++ b/chrome/browser/extensions/plugin_manager.h
@@ -37,7 +37,7 @@ #if !defined(DISABLE_NACL) - // We implement some Pepper plug-ins using NaCl to take advantage of NaCl's + // We implement some Pepper plugins using NaCl to take advantage of NaCl's // strong sandbox. Typically, these NaCl modules are stored in extensions // and registered here. Not all NaCl modules need to register for a MIME // type, just the ones that are responsible for rendering a particular MIME
diff --git a/chrome/browser/favicon/DEPS b/chrome/browser/favicon/DEPS index d80d538..4dcd7ec 100644 --- a/chrome/browser/favicon/DEPS +++ b/chrome/browser/favicon/DEPS
@@ -29,3 +29,10 @@ # Do not add to the list of temporarily-allowed dependencies above, # and please do not introduce more #includes of these files. ] + +specific_include_rules = { + # Browser tests, by definition, need access to the browser objects. + '.*_browsertest\.cc': [ + "+chrome/browser", + ] +}
diff --git a/chrome/browser/favicon/favicon_handler_unittest.cc b/chrome/browser/favicon/favicon_handler_unittest.cc index e8ce4fe1..6074c04 100644 --- a/chrome/browser/favicon/favicon_handler_unittest.cc +++ b/chrome/browser/favicon/favicon_handler_unittest.cc
@@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/favicon/favicon_handler.h" +#include "components/favicon/core/browser/favicon_handler.h" #include "base/memory/scoped_ptr.h" #include "chrome/browser/favicon/chrome_favicon_client.h" #include "chrome/browser/favicon/chrome_favicon_client_factory.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/favicon/favicon_tab_helper.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "components/favicon/core/browser/favicon_service.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/favicon_size.h"
diff --git a/chrome/browser/favicon/favicon_service_factory.cc b/chrome/browser/favicon/favicon_service_factory.cc index 3218fb7..10814b3 100644 --- a/chrome/browser/favicon/favicon_service_factory.cc +++ b/chrome/browser/favicon/favicon_service_factory.cc
@@ -7,9 +7,9 @@ #include "base/memory/singleton.h" #include "base/prefs/pref_service.h" #include "chrome/browser/favicon/chrome_favicon_client_factory.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/history_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h"
diff --git a/chrome/browser/favicon/favicon_tab_helper.cc b/chrome/browser/favicon/favicon_tab_helper.cc index e23deb4..d95ffd1 100644 --- a/chrome/browser/favicon/favicon_tab_helper.cc +++ b/chrome/browser/favicon/favicon_tab_helper.cc
@@ -7,15 +7,15 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/favicon/chrome_favicon_client.h" #include "chrome/browser/favicon/chrome_favicon_client_factory.h" -#include "chrome/browser/favicon/favicon_handler.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" -#include "chrome/browser/favicon/favicon_tab_helper_observer.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/search.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/url_constants.h" +#include "components/favicon/core/browser/favicon_handler.h" +#include "components/favicon/core/browser/favicon_service.h" +#include "components/favicon/core/browser/favicon_tab_helper_observer.h" #include "components/favicon_base/favicon_types.h" #include "components/history/core/browser/history_service.h" #include "content/public/browser/favicon_status.h" @@ -155,11 +155,13 @@ return 0; } + bool bypass_cache = (bypass_cache_page_url_ == GetActiveURL()); + bypass_cache_page_url_ = GURL(); + return web_contents()->DownloadImage( - url, - true, - max_image_size, - base::Bind(&FaviconTabHelper::DidDownloadFavicon,base::Unretained(this))); + url, true, max_image_size, bypass_cache, + base::Bind(&FaviconTabHelper::DidDownloadFavicon, + base::Unretained(this))); } bool FaviconTabHelper::IsOffTheRecord() { @@ -232,6 +234,8 @@ NavigationController::ReloadType reload_type) { if (reload_type != NavigationController::NO_RELOAD && !profile_->IsOffTheRecord()) { + bypass_cache_page_url_ = url; + FaviconService* favicon_service = FaviconServiceFactory::GetForProfile( profile_, ServiceAccessType::IMPLICIT_ACCESS); if (favicon_service) { @@ -246,8 +250,20 @@ const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { favicon_urls_.clear(); + + // Wait till the user navigates to a new URL to start checking the cache + // again. The cache may be ignored for non-reload navigations (e.g. + // history.replace() in-page navigation). This is allowed to increase the + // likelihood that "reloading a page ignoring the cache" redownloads the + // favicon. In particular, a page may do an in-page navigation before + // FaviconHandler has the time to determine that the favicon needs to be + // redownloaded. + GURL url = details.entry->GetURL(); + if (url != bypass_cache_page_url_) + bypass_cache_page_url_ = GURL(); + // Get the favicon, either from history or request it from the net. - FetchFavicon(details.entry->GetURL()); + FetchFavicon(url); } // Returns favicon_base::IconType the given icon_type corresponds to.
diff --git a/chrome/browser/favicon/favicon_tab_helper.h b/chrome/browser/favicon/favicon_tab_helper.h index 97ed230c..f3c3cb9 100644 --- a/chrome/browser/favicon/favicon_tab_helper.h +++ b/chrome/browser/favicon/favicon_tab_helper.h
@@ -95,8 +95,10 @@ const std::vector<gfx::Size>& original_bitmap_sizes); private: - explicit FaviconTabHelper(content::WebContents* web_contents); friend class content::WebContentsUserData<FaviconTabHelper>; + friend class FaviconTabHelperTest; + + explicit FaviconTabHelper(content::WebContents* web_contents); // content::WebContentsObserver overrides. void DidStartNavigationToPendingEntry( @@ -125,6 +127,9 @@ std::vector<content::FaviconURL> favicon_urls_; + // Bypass cache when downloading favicons for this page URL. + GURL bypass_cache_page_url_; + scoped_ptr<FaviconHandler> favicon_handler_; // Handles downloading touchicons. It is NULL if
diff --git a/chrome/browser/favicon/favicon_tab_helper_browsertest.cc b/chrome/browser/favicon/favicon_tab_helper_browsertest.cc new file mode 100644 index 0000000..81bd2265 --- /dev/null +++ b/chrome/browser/favicon/favicon_tab_helper_browsertest.cc
@@ -0,0 +1,228 @@ +// 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 "chrome/browser/favicon/favicon_tab_helper.h" + +#include "base/memory/weak_ptr.h" +#include "base/run_loop.h" +#include "chrome/app/chrome_command_ids.h" +#include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_commands.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" +#include "components/favicon/core/browser/favicon_handler.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" +#include "content/public/browser/notification_types.h" +#include "content/public/browser/resource_dispatcher_host.h" +#include "content/public/browser/resource_dispatcher_host_delegate.h" +#include "net/base/load_flags.h" +#include "net/test/spawned_test_server/spawned_test_server.h" +#include "net/url_request/url_request.h" +#include "url/url_constants.h" + +namespace { + +// Tracks whether the URL passed to the constructor is requested and whether +// the request bypasses the cache. +class TestResourceDispatcherHostDelegate + : public content::ResourceDispatcherHostDelegate { + public: + explicit TestResourceDispatcherHostDelegate(const GURL& url) + : url_(url), was_requested_(false), bypassed_cache_(false) {} + ~TestResourceDispatcherHostDelegate() override {} + + void Reset() { + was_requested_ = false; + bypassed_cache_ = false; + } + + // Resturns whether |url_| was requested. + bool was_requested() const { return was_requested_; } + + // Returns whether any of the requests bypassed the HTTP cache. + bool bypassed_cache() const { return bypassed_cache_; } + + private: + // content::ResourceDispatcherHostDelegate: + bool ShouldBeginRequest(const std::string& method, + const GURL& url, + content::ResourceType resource_type, + content::ResourceContext* resource_context) override { + return true; + } + + void RequestBeginning( + net::URLRequest* request, + content::ResourceContext* resource_context, + content::AppCacheService* appcache_service, + content::ResourceType resource_type, + ScopedVector<content::ResourceThrottle>* throttles) override { + if (request->url() == url_) { + was_requested_ = true; + if (request->load_flags() & net::LOAD_BYPASS_CACHE) + bypassed_cache_ = true; + } + } + + void DownloadStarting( + net::URLRequest* request, + content::ResourceContext* resource_context, + int child_id, + int route_id, + int request_id, + bool is_content_initiated, + bool must_download, + ScopedVector<content::ResourceThrottle>* throttles) override {} + + private: + GURL url_; + bool was_requested_; + bool bypassed_cache_; + + DISALLOW_COPY_AND_ASSIGN(TestResourceDispatcherHostDelegate); +}; + +// Checks whether the FaviconTabHelper is waiting for a download to complete or +// for data from the FaviconService. +class FaviconTabHelperPendingTaskChecker { + public: + virtual ~FaviconTabHelperPendingTaskChecker() {} + + virtual bool HasPendingTasks() = 0; +}; + +// Waits for the following the finish: +// - The pending navigation. +// - FaviconHandler's pending favicon database requests. +// - FaviconHandler's pending downloads. +class PendingTaskWaiter : public content::NotificationObserver { + public: + PendingTaskWaiter(content::WebContents* web_contents, + FaviconTabHelperPendingTaskChecker* checker) + : checker_(checker), load_stopped_(false), weak_factory_(this) { + registrar_.Add(this, chrome::NOTIFICATION_FAVICON_UPDATED, + content::Source<content::WebContents>(web_contents)); + registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, + content::Source<content::NavigationController>( + &web_contents->GetController())); + } + ~PendingTaskWaiter() override {} + + void Wait() { + if (load_stopped_ && !checker_->HasPendingTasks()) + return; + + base::RunLoop run_loop; + quit_closure_ = run_loop.QuitClosure(); + run_loop.Run(); + } + + private: + // content::NotificationObserver: + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override { + if (type == content::NOTIFICATION_LOAD_STOP) + load_stopped_ = true; + + if (!quit_closure_.is_null()) { + // We stop waiting based on changes in state to FaviconHandler which occur + // immediately after NOTIFICATION_FAVICON_UPDATED is sent. Post a task to + // check if we can stop waiting. + base::MessageLoopForUI::current()->PostTask( + FROM_HERE, base::Bind(&PendingTaskWaiter::EndLoopIfCanStopWaiting, + weak_factory_.GetWeakPtr())); + } + } + + void EndLoopIfCanStopWaiting() { + if (!quit_closure_.is_null() && + load_stopped_ && + !checker_->HasPendingTasks()) { + quit_closure_.Run(); + } + } + + FaviconTabHelperPendingTaskChecker* checker_; // Not owned. + bool load_stopped_; + base::Closure quit_closure_; + content::NotificationRegistrar registrar_; + base::WeakPtrFactory<PendingTaskWaiter> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(PendingTaskWaiter); +}; + +} // namespace + +class FaviconTabHelperTest : public InProcessBrowserTest, + public FaviconTabHelperPendingTaskChecker { + public: + FaviconTabHelperTest() {} + ~FaviconTabHelperTest() override {} + + content::WebContents* web_contents() { + return browser()->tab_strip_model()->GetActiveWebContents(); + } + + // FaviconTabHelperPendingTaskChecker: + bool HasPendingTasks() override { + FaviconHandler* favicon_handler = + FaviconTabHelper::FromWebContents(web_contents()) + ->favicon_handler_.get(); + return !favicon_handler->download_requests_.empty() || + favicon_handler->cancelable_task_tracker_.HasTrackedTasks(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(FaviconTabHelperTest); +}; + +// Test that when a user reloads a page ignoring the cache that the favicon is +// is redownloaded and (not returned from either the favicon cache or the HTTP +// cache). +IN_PROC_BROWSER_TEST_F(FaviconTabHelperTest, ReloadIgnoringCache) { + ASSERT_TRUE(test_server()->Start()); + GURL url = test_server()->GetURL("files/favicon/page_with_favicon.html"); + GURL icon_url = test_server()->GetURL("files/favicon/icon.ico"); + + scoped_ptr<TestResourceDispatcherHostDelegate> delegate( + new TestResourceDispatcherHostDelegate(icon_url)); + content::ResourceDispatcherHost::Get()->SetDelegate(delegate.get()); + + // Initial visit in order to populate the cache. + { + PendingTaskWaiter waiter(web_contents(), this); + ui_test_utils::NavigateToURLWithDisposition( + browser(), url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE); + waiter.Wait(); + } + ASSERT_TRUE(delegate->was_requested()); + EXPECT_FALSE(delegate->bypassed_cache()); + delegate->Reset(); + + ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL)); + + // A normal visit should fetch the favicon from either the favicon database or + // the HTTP cache. + { + PendingTaskWaiter waiter(web_contents(), this); + ui_test_utils::NavigateToURLWithDisposition( + browser(), url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE); + waiter.Wait(); + } + EXPECT_FALSE(delegate->bypassed_cache()); + delegate->Reset(); + + // A reload ignoring the cache should refetch the favicon from the website. + { + PendingTaskWaiter waiter(web_contents(), this); + chrome::ExecuteCommand(browser(), IDC_RELOAD_IGNORING_CACHE); + waiter.Wait(); + } + ASSERT_TRUE(delegate->was_requested()); + EXPECT_TRUE(delegate->bypassed_cache()); +}
diff --git a/chrome/browser/history/android/DEPS b/chrome/browser/history/android/DEPS index d4ff1bb..8fdbf32 100644 --- a/chrome/browser/history/android/DEPS +++ b/chrome/browser/history/android/DEPS
@@ -4,4 +4,5 @@ # components/. "+chrome/browser", "+components/bookmarks/browser", + "+components/favicon/core/browser", ]
diff --git a/chrome/browser/history/android/android_history_provider_service.cc b/chrome/browser/history/android/android_history_provider_service.cc index da415064..722d4e5 100644 --- a/chrome/browser/history/android/android_history_provider_service.cc +++ b/chrome/browser/history/android/android_history_provider_service.cc
@@ -4,11 +4,11 @@ #include "chrome/browser/history/android/android_history_provider_service.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/android/android_provider_backend.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/android/android_history_types.h" #include "components/history/core/browser/history_backend.h" #include "components/history/core/browser/history_db_task.h"
diff --git a/chrome/browser/importer/profile_writer.cc b/chrome/browser/importer/profile_writer.cc index 8d514d4..4a46de4 100644 --- a/chrome/browser/importer/profile_writer.cc +++ b/chrome/browser/importer/profile_writer.cc
@@ -15,7 +15,6 @@ #include "base/threading/thread.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/password_manager/password_store_factory.h" @@ -26,6 +25,7 @@ #include "chrome/common/pref_names.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/bookmarks/browser/bookmark_model.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/history_service.h" #include "components/password_manager/core/browser/password_store.h" #include "components/search_engines/template_url.h"
diff --git a/chrome/browser/io_thread.cc b/chrome/browser/io_thread.cc index 54ca50b..841ca780 100644 --- a/chrome/browser/io_thread.cc +++ b/chrome/browser/io_thread.cc
@@ -435,7 +435,6 @@ IOThread::Globals::Globals() : system_request_context_leak_checker(this), - enable_ssl_connect_job_waiting(false), ignore_certificate_errors(false), use_stale_while_revalidate(false), testing_fixed_http_port(0), @@ -729,8 +728,6 @@ command_line.GetSwitchValueASCII(switches::kHostRules)); TRACE_EVENT_END0("startup", "IOThread::InitAsync:SetRulesFromString"); } - if (command_line.HasSwitch(switches::kEnableSSLConnectJobWaiting)) - globals_->enable_ssl_connect_job_waiting = true; if (command_line.HasSwitch(switches::kIgnoreCertificateErrors)) globals_->ignore_certificate_errors = true; globals_->use_stale_while_revalidate = @@ -1091,8 +1088,6 @@ globals.http_server_properties->GetWeakPtr(); params->network_delegate = globals.system_network_delegate.get(); params->host_mapping_rules = globals.host_mapping_rules.get(); - params->enable_ssl_connect_job_waiting = - globals.enable_ssl_connect_job_waiting; params->ignore_certificate_errors = globals.ignore_certificate_errors; params->use_stale_while_revalidate = globals.use_stale_while_revalidate; params->testing_fixed_http_port = globals.testing_fixed_http_port;
diff --git a/chrome/browser/io_thread.h b/chrome/browser/io_thread.h index 2d3327c..0da6e86 100644 --- a/chrome/browser/io_thread.h +++ b/chrome/browser/io_thread.h
@@ -161,7 +161,6 @@ #endif scoped_ptr<net::HostMappingRules> host_mapping_rules; scoped_ptr<net::HttpUserAgentSettings> http_user_agent_settings; - bool enable_ssl_connect_job_waiting; bool ignore_certificate_errors; bool use_stale_while_revalidate; uint16 testing_fixed_http_port;
diff --git a/chrome/browser/jumplist_win.cc b/chrome/browser/jumplist_win.cc index 010b3b14..7745f075 100644 --- a/chrome/browser/jumplist_win.cc +++ b/chrome/browser/jumplist_win.cc
@@ -14,7 +14,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/thread.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/top_sites_factory.h" #include "chrome/browser/metrics/jumplist_metrics_win.h" @@ -27,6 +26,7 @@ #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_types.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/page_usage_data.h"
diff --git a/chrome/browser/media/chrome_webrtc_audio_quality_browsertest.cc b/chrome/browser/media/chrome_webrtc_audio_quality_browsertest.cc index 72b66105..b22bc49 100644 --- a/chrome/browser/media/chrome_webrtc_audio_quality_browsertest.cc +++ b/chrome/browser/media/chrome_webrtc_audio_quality_browsertest.cc
@@ -66,7 +66,7 @@ // 2. For the user who will run the test: # pavucontrol // 3. In a separate terminal, # arecord dummy // 4. In pavucontrol, go to the recording tab. -// 5. For the ALSA plug-in [aplay]: ALSA Capture from, change from <x> to +// 5. For the ALSA plugin [aplay]: ALSA Capture from, change from <x> to // <Monitor of x>, where x is whatever your primary sound device is called. // 6. Try launching chrome as the target user on the target machine, try // playing, say, a YouTube video, and record with # arecord -f dat tmp.dat.
diff --git a/chrome/browser/metrics/plugin_metrics_provider.cc b/chrome/browser/metrics/plugin_metrics_provider.cc index 44491bd8..35c789b 100644 --- a/chrome/browser/metrics/plugin_metrics_provider.cc +++ b/chrome/browser/metrics/plugin_metrics_provider.cc
@@ -301,8 +301,8 @@ ChildProcessStats& stats = child_process_stats_buffer_[plugin.name]; // Initialize the type if this entry is new. if (stats.process_type == content::PROCESS_TYPE_UNKNOWN) { - // The plug-in process might not actually be of type PLUGIN (which means - // NPAPI), but we only care that it is *a* plug-in process. + // The plugin process might not actually be of type PLUGIN (which means + // NPAPI), but we only care that it is *a* plugin process. stats.process_type = content::PROCESS_TYPE_PLUGIN; } else { DCHECK(IsPluginProcess(stats.process_type));
diff --git a/chrome/browser/net/chrome_net_log.cc b/chrome/browser/net/chrome_net_log.cc index 7b9fabd5..de15a301 100644 --- a/chrome/browser/net/chrome_net_log.cc +++ b/chrome/browser/net/chrome_net_log.cc
@@ -7,6 +7,7 @@ #include <stdio.h> #include "base/command_line.h" +#include "base/files/scoped_file.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -32,19 +33,19 @@ // would result in an unbounded buffer size, so not much can be gained by // doing this on another thread. It's only used when debugging Chrome, so // performance is not a big concern. - FILE* file = NULL; + base::ScopedFILE file; #if defined(OS_WIN) - file = _wfopen(log_path.value().c_str(), L"w"); + file.reset(_wfopen(log_path.value().c_str(), L"w")); #elif defined(OS_POSIX) - file = fopen(log_path.value().c_str(), "w"); + file.reset(fopen(log_path.value().c_str(), "w")); #endif - if (file == NULL) { + if (!file) { LOG(ERROR) << "Could not open file " << log_path.value() << " for net logging"; } else { scoped_ptr<base::Value> constants(NetInternalsUI::GetConstants()); - net_log_logger_.reset(new net::NetLogLogger(file, *constants)); + net_log_logger_.reset(new net::NetLogLogger()); if (command_line->HasSwitch(switches::kNetLogLevel)) { std::string log_level_string = command_line->GetSwitchValueASCII(switches::kNetLogLevel); @@ -56,7 +57,8 @@ static_cast<LogLevel>(command_line_log_level)); } } - net_log_logger_->StartObserving(this); + net_log_logger_->StartObserving(this, file.Pass(), constants.get(), + nullptr); } } @@ -68,7 +70,7 @@ net_log_temp_file_.reset(); // Remove the observers we own before we're destroyed. if (net_log_logger_) - RemoveThreadSafeObserver(net_log_logger_.get()); + net_log_logger_->StopObserving(nullptr); if (trace_net_log_observer_) trace_net_log_observer_->StopWatchForTraceStart(); }
diff --git a/chrome/browser/net/net_log_temp_file.cc b/chrome/browser/net/net_log_temp_file.cc index f59b554..d21b0597 100644 --- a/chrome/browser/net/net_log_temp_file.cc +++ b/chrome/browser/net/net_log_temp_file.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/net/net_log_temp_file.h" #include "base/files/file_util.h" +#include "base/files/scoped_file.h" #include "base/values.h" #include "chrome/browser/net/chrome_net_log.h" #include "chrome/browser/ui/webui/net_internals/net_internals_ui.h" @@ -22,7 +23,7 @@ NetLogTempFile::~NetLogTempFile() { if (net_log_logger_) - net_log_logger_->StopObserving(); + net_log_logger_->StopObserving(nullptr); } void NetLogTempFile::ProcessCommand(Command command) { @@ -135,17 +136,18 @@ // Try to make sure we can create the file. // TODO(rtenneti): Find a better for doing the following. Surface some error // to the user if we couldn't create the file. - FILE* file = base::OpenFile(log_path_, "w"); - if (file == NULL) + base::ScopedFILE file(base::OpenFile(log_path_, "w")); + if (!file) return; log_type_ = log_type; state_ = STATE_LOGGING; scoped_ptr<base::Value> constants(NetInternalsUI::GetConstants()); - net_log_logger_.reset(new net::NetLogLogger(file, *constants)); + net_log_logger_.reset(new net::NetLogLogger()); net_log_logger_->set_log_level(GetLogLevelForLogType(log_type)); - net_log_logger_->StartObserving(chrome_net_log_); + net_log_logger_->StartObserving(chrome_net_log_, file.Pass(), constants.get(), + nullptr); } void NetLogTempFile::StopNetLog() { @@ -153,7 +155,7 @@ if (state_ != STATE_LOGGING) return; - net_log_logger_->StopObserving(); + net_log_logger_->StopObserving(nullptr); net_log_logger_.reset(); state_ = STATE_NOT_LOGGING; }
diff --git a/chrome/browser/notifications/message_center_settings_controller.cc b/chrome/browser/notifications/message_center_settings_controller.cc index 89f5e5e..d16c618f 100644 --- a/chrome/browser/notifications/message_center_settings_controller.cc +++ b/chrome/browser/notifications/message_center_settings_controller.cc
@@ -14,7 +14,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/app_icon_loader_impl.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/notifications/desktop_notification_profile_util.h" #include "chrome/browser/notifications/desktop_notification_service.h" @@ -25,6 +24,7 @@ #include "chrome/common/extensions/api/notifications.h" #include "chrome/common/extensions/extension_constants.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_types.h" #include "components/history/core/browser/history_types.h" #include "content/public/browser/notification_service.h"
diff --git a/chrome/browser/password_manager/native_backend_gnome_x.cc b/chrome/browser/password_manager/native_backend_gnome_x.cc index f5d2b15a..4b31ec9 100644 --- a/chrome/browser/password_manager/native_backend_gnome_x.cc +++ b/chrome/browser/password_manager/native_backend_gnome_x.cc
@@ -163,17 +163,15 @@ return form.Pass(); } -// Parse all the results from the given GList into a -// ScopedVector<autofill::PasswordForm>, and free the GList. PasswordForms are -// allocated on the heap, and should be deleted by the consumer. If not NULL, +// Converts native credentials in |found| to PasswordForms. If not NULL, // |lookup_form| is used to filter out results -- only credentials with signon // realms passing the PSL matching against |lookup_form->signon_realm| will be // kept. PSL matched results get their signon_realm, origin, and action // rewritten to those of |lookup_form_|, with the original signon_realm saved // into the result's original_signon_realm data member. -void ConvertFormList(GList* found, - const PasswordForm* lookup_form, - ScopedVector<autofill::PasswordForm>* forms) { +ScopedVector<PasswordForm> ConvertFormList(GList* found, + const PasswordForm* lookup_form) { + ScopedVector<PasswordForm> forms; password_manager::PSLDomainMatchMetric psl_domain_match_metric = password_manager::PSL_DOMAIN_MATCH_NONE; for (GList* element = g_list_first(found); element; @@ -202,7 +200,7 @@ } else { LOG(WARNING) << "Unable to access password from list element!"; } - forms->push_back(form.release()); + forms.push_back(form.release()); } else { LOG(WARNING) << "Could not initialize PasswordForm from attributes!"; } @@ -218,6 +216,7 @@ : password_manager::PSL_DOMAIN_MATCH_NOT_USED, password_manager::PSL_DOMAIN_MATCH_COUNT); } + return forms.Pass(); } // Schema is analagous to the fields in PasswordForm. @@ -284,8 +283,8 @@ GnomeKeyringResult WaitResult(); // Use after AddLoginSearch, UpdateLoginSearch, GetLogins, GetLoginsList, - // GetAllLogins. - GnomeKeyringResult WaitResult(ScopedVector<autofill::PasswordForm>* forms); + // GetAllLogins. Replaces the content of |forms| with found logins. + GnomeKeyringResult WaitResult(ScopedVector<PasswordForm>* forms); private: struct GnomeKeyringAttributeListFreeDeleter { @@ -312,12 +311,15 @@ // All these callbacks are called on UI thread. static void OnOperationDone(GnomeKeyringResult result, gpointer data); + // This is marked as static, but acts on the GKRMethod instance that |data| + // points to. Saves |result| to |result_|. If the result is OK, overwrites + // |forms_| with the found credentials. Clears |forms_| otherwise. static void OnOperationGetList(GnomeKeyringResult result, GList* list, gpointer data); base::WaitableEvent event_; GnomeKeyringResult result_; - ScopedVector<autofill::PasswordForm> forms_; + ScopedVector<PasswordForm> forms_; // If the credential search is specified by a single form and needs to use PSL // matching, then the specifying form is stored in |lookup_form_|. If PSL // matching is used to find a result, then the results signon realm, origin @@ -481,18 +483,10 @@ return result_; } -GnomeKeyringResult GKRMethod::WaitResult( - ScopedVector<autofill::PasswordForm>* forms) { +GnomeKeyringResult GKRMethod::WaitResult(ScopedVector<PasswordForm>* forms) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); event_.Wait(); - if (forms->empty()) { - // Normal case. Avoid extra allocation by swapping. - forms->swap(forms_); - } else { - // Rare case. Append forms_ to *forms. - forms->insert(forms->end(), forms_.begin(), forms_.end()); - forms_.weak_clear(); - } + *forms = forms_.Pass(); return result_; } @@ -529,18 +523,27 @@ gpointer data) { GKRMethod* method = static_cast<GKRMethod*>(data); method->result_ = result; - method->forms_.clear(); // |list| will be freed after this callback returns, so convert it now. - ConvertFormList(list, method->lookup_form_.get(), &method->forms_); + if (result == GNOME_KEYRING_RESULT_OK) + method->forms_ = ConvertFormList(list, method->lookup_form_.get()); + else + method->forms_.clear(); method->lookup_form_.reset(); method->event_.Signal(); } +// Generates a profile-specific app string based on profile_id. +std::string GetProfileSpecificAppString(LocalProfileId profile_id) { + // Originally, the application string was always just "chrome" and used only + // so that we had *something* to search for since GNOME Keyring won't search + // for nothing. Now we use it to distinguish passwords for different profiles. + return base::StringPrintf("%s-%d", kGnomeKeyringAppString, profile_id); +} + } // namespace NativeBackendGnome::NativeBackendGnome(LocalProfileId id) - : profile_id_(id) { - app_string_ = GetProfileSpecificAppString(); + : profile_id_(id), app_string_(GetProfileSpecificAppString(id)) { } NativeBackendGnome::~NativeBackendGnome() { @@ -579,7 +582,7 @@ base::Bind(&GKRMethod::AddLoginSearch, base::Unretained(&method), form, app_string_.c_str())); - ScopedVector<autofill::PasswordForm> forms; + ScopedVector<PasswordForm> forms; GnomeKeyringResult result = method.WaitResult(&forms); if (result != GNOME_KEYRING_RESULT_OK && result != GNOME_KEYRING_RESULT_NO_MATCH) { @@ -623,7 +626,7 @@ base::Bind(&GKRMethod::UpdateLoginSearch, base::Unretained(&method), form, app_string_.c_str())); - ScopedVector<autofill::PasswordForm> forms; + ScopedVector<PasswordForm> forms; GnomeKeyringResult result = method.WaitResult(&forms); if (result != GNOME_KEYRING_RESULT_OK) { LOG(ERROR) << "Keyring find failed: " @@ -683,9 +686,8 @@ return RemoveLoginsBetween(delete_begin, delete_end, SYNC_TIMESTAMP, changes); } -bool NativeBackendGnome::GetLogins( - const PasswordForm& form, - ScopedVector<autofill::PasswordForm>* forms) { +bool NativeBackendGnome::GetLogins(const PasswordForm& form, + ScopedVector<PasswordForm>* forms) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); GKRMethod method; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, @@ -704,18 +706,16 @@ } bool NativeBackendGnome::GetAutofillableLogins( - ScopedVector<autofill::PasswordForm>* forms) { + ScopedVector<PasswordForm>* forms) { return GetLoginsList(true, forms); } -bool NativeBackendGnome::GetBlacklistLogins( - ScopedVector<autofill::PasswordForm>* forms) { +bool NativeBackendGnome::GetBlacklistLogins(ScopedVector<PasswordForm>* forms) { return GetLoginsList(false, forms); } -bool NativeBackendGnome::GetLoginsList( - bool autofillable, - ScopedVector<autofill::PasswordForm>* forms) { +bool NativeBackendGnome::GetLoginsList(bool autofillable, + ScopedVector<PasswordForm>* forms) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); uint32_t blacklisted_by_user = !autofillable; @@ -736,8 +736,7 @@ return true; } -bool NativeBackendGnome::GetAllLogins( - ScopedVector<autofill::PasswordForm>* forms) { +bool NativeBackendGnome::GetAllLogins(ScopedVector<PasswordForm>* forms) { GKRMethod method; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&GKRMethod::GetAllLogins, @@ -754,22 +753,21 @@ return true; } -bool NativeBackendGnome::GetLoginsBetween( - base::Time get_begin, - base::Time get_end, - TimestampToCompare date_to_compare, - ScopedVector<autofill::PasswordForm>* forms) { +bool NativeBackendGnome::GetLoginsBetween(base::Time get_begin, + base::Time get_end, + TimestampToCompare date_to_compare, + ScopedVector<PasswordForm>* forms) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB)); + forms->clear(); // We could walk the list and add items as we find them, but it is much // easier to build the list and then filter the results. - ScopedVector<autofill::PasswordForm> all_forms; + ScopedVector<PasswordForm> all_forms; if (!GetAllLogins(&all_forms)) return false; - base::Time autofill::PasswordForm::*date_member = - date_to_compare == CREATION_TIMESTAMP - ? &autofill::PasswordForm::date_created - : &autofill::PasswordForm::date_synced; + base::Time PasswordForm::*date_member = date_to_compare == CREATION_TIMESTAMP + ? &PasswordForm::date_created + : &PasswordForm::date_synced; for (auto& saved_form : all_forms) { if (get_begin <= saved_form->*date_member && (get_end.is_null() || saved_form->*date_member < get_end)) { @@ -791,7 +789,7 @@ changes->clear(); // We could walk the list and delete items as we find them, but it is much // easier to build the list and use RemoveLogin() to delete them. - ScopedVector<autofill::PasswordForm> forms; + ScopedVector<PasswordForm> forms; if (!GetLoginsBetween(get_begin, get_end, date_to_compare, &forms)) return false; @@ -806,10 +804,3 @@ } return ok; } - -std::string NativeBackendGnome::GetProfileSpecificAppString() const { - // Originally, the application string was always just "chrome" and used only - // so that we had *something* to search for since GNOME Keyring won't search - // for nothing. Now we use it to distinguish passwords for different profiles. - return base::StringPrintf("%s-%d", kGnomeKeyringAppString, profile_id_); -}
diff --git a/chrome/browser/password_manager/native_backend_gnome_x.h b/chrome/browser/password_manager/native_backend_gnome_x.h index 438917a5..9545ef6e 100644 --- a/chrome/browser/password_manager/native_backend_gnome_x.h +++ b/chrome/browser/password_manager/native_backend_gnome_x.h
@@ -20,6 +20,7 @@ #include <string> #include "base/basictypes.h" +#include "base/compiler_specific.h" #include "base/memory/scoped_vector.h" #include "base/time/time.h" #include "chrome/browser/password_manager/password_store_factory.h" @@ -120,19 +121,24 @@ // Adds a login form without checking for one to replace first. bool RawAddLogin(const autofill::PasswordForm& form); - // Reads PasswordForms from the keyring with the given autofillability state. + // Retrieves all autofillable or all blacklisted credentials (depending on + // |autofillable|) from the keyring into |forms|, overwriting the original + // contents of |forms|. Returns true on success. bool GetLoginsList(bool autofillable, - ScopedVector<autofill::PasswordForm>* forms); + ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT; // Helper for GetLoginsCreatedBetween(). - bool GetAllLogins(ScopedVector<autofill::PasswordForm>* forms); + bool GetAllLogins(ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT; // Retrieves password created/synced in the time interval. Returns |true| if // the operation succeeded. bool GetLoginsBetween(base::Time get_begin, base::Time get_end, TimestampToCompare date_to_compare, - ScopedVector<autofill::PasswordForm>* forms); + ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT; // Removes password created/synced in the time interval. Returns |true| if the // operation succeeded. |changes| will contain the changes applied. @@ -141,9 +147,6 @@ TimestampToCompare date_to_compare, password_manager::PasswordStoreChangeList* changes); - // Generates a profile-specific app string based on profile_id_. - std::string GetProfileSpecificAppString() const; - // The local profile id, used to generate the app string. const LocalProfileId profile_id_;
diff --git a/chrome/browser/password_manager/native_backend_gnome_x_unittest.cc b/chrome/browser/password_manager/native_backend_gnome_x_unittest.cc index ff89dbe..bf76e6e 100644 --- a/chrome/browser/password_manager/native_backend_gnome_x_unittest.cc +++ b/chrome/browser/password_manager/native_backend_gnome_x_unittest.cc
@@ -1040,38 +1040,6 @@ CheckMockKeyringItem(&mock_keyring_items[0], form_google_, "chrome-42"); } -TEST_F(NativeBackendGnomeTest, ListLoginsAppends) { - NativeBackendGnome backend(42); - backend.Init(); - - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendGnome::AddLogin), - base::Unretained(&backend), form_google_)); - - // Send the same request twice with the same list both times. - ScopedVector<autofill::PasswordForm> form_list; - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind( - base::IgnoreResult(&NativeBackendGnome::GetAutofillableLogins), - base::Unretained(&backend), &form_list)); - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind( - base::IgnoreResult(&NativeBackendGnome::GetAutofillableLogins), - base::Unretained(&backend), &form_list)); - - RunBothThreads(); - - // Quick check that we got two results back. - EXPECT_EQ(2u, form_list.size()); - - EXPECT_EQ(1u, mock_keyring_items.size()); - if (mock_keyring_items.size() > 0) - CheckMockKeyringItem(&mock_keyring_items[0], form_google_, "chrome-42"); -} - TEST_F(NativeBackendGnomeTest, AndroidCredentials) { NativeBackendGnome backend(42); backend.Init();
diff --git a/chrome/browser/password_manager/native_backend_kwallet_x.cc b/chrome/browser/password_manager/native_backend_kwallet_x.cc index bb3d5f5..7c9a0a9d 100644 --- a/chrome/browser/password_manager/native_backend_kwallet_x.cc +++ b/chrome/browser/password_manager/native_backend_kwallet_x.cc
@@ -27,6 +27,10 @@ namespace { +// In case the fields in the pickle ever change, version them so we can try to +// read old pickles. (Note: do not eat old pickles past the expiration date.) +const int kPickleVersion = 6; + // We could localize this string, but then changing your locale would cause // you to lose access to all your stored passwords. Maybe best not to do that. // Name of the folder to store passwords in. @@ -100,6 +104,171 @@ } } +// Deserializes a list of credentials from the wallet to |forms| (replacing +// the contents of |forms|). |size_32| controls reading the size field within +// the pickle as 32 bits. We used to use Pickle::WriteSize() to write the number +// of password forms, but that has a different size on 32- and 64-bit systems. +// So, now we always write a 64-bit quantity, but we support trying to read it +// as either size when reading old pickles that fail to deserialize using the +// native size. Returns true on success. +bool DeserializeValueSize(const std::string& signon_realm, + const PickleIterator& init_iter, + int version, + bool size_32, + bool warn_only, + ScopedVector<autofill::PasswordForm>* forms) { + PickleIterator iter = init_iter; + + size_t count = 0; + if (size_32) { + uint32_t count_32 = 0; + if (!iter.ReadUInt32(&count_32)) { + LOG(ERROR) << "Failed to deserialize KWallet entry " + << "(realm: " << signon_realm << ")"; + return false; + } + count = count_32; + } else { + if (!iter.ReadSizeT(&count)) { + LOG(ERROR) << "Failed to deserialize KWallet entry " + << "(realm: " << signon_realm << ")"; + return false; + } + } + + if (count > 0xFFFF) { + // Trying to pin down the cause of http://crbug.com/80728 (or fix it). + // This is a very large number of passwords to be saved for a single realm. + // It is almost certainly a corrupt pickle and not real data. Ignore it. + // This very well might actually be http://crbug.com/107701, so if we're + // reading an old pickle, we don't even log this the first time we try to + // read it. (That is, when we're reading the native architecture size.) + if (!warn_only) { + LOG(ERROR) << "Suspiciously large number of entries in KWallet entry " + << "(" << count << "; realm: " << signon_realm << ")"; + } + return false; + } + + // We'll swap |converted_forms| with |*forms| on success, to make sure we + // don't return partial results on failure. + ScopedVector<autofill::PasswordForm> converted_forms; + converted_forms.reserve(count); + for (size_t i = 0; i < count; ++i) { + scoped_ptr<PasswordForm> form(new PasswordForm()); + form->signon_realm.assign(signon_realm); + + int scheme = 0; + int64 date_created = 0; + int type = 0; + int generation_upload_status = 0; + // Note that these will be read back in the order listed due to + // short-circuit evaluation. This is important. + if (!iter.ReadInt(&scheme) || + !ReadGURL(&iter, warn_only, &form->origin) || + !ReadGURL(&iter, warn_only, &form->action) || + !iter.ReadString16(&form->username_element) || + !iter.ReadString16(&form->username_value) || + !iter.ReadString16(&form->password_element) || + !iter.ReadString16(&form->password_value) || + !iter.ReadString16(&form->submit_element) || + !iter.ReadBool(&form->ssl_valid) || + !iter.ReadBool(&form->preferred) || + !iter.ReadBool(&form->blacklisted_by_user) || + !iter.ReadInt64(&date_created)) { + LogDeserializationWarning(version, signon_realm, warn_only); + return false; + } + form->scheme = static_cast<PasswordForm::Scheme>(scheme); + + if (version > 1) { + if (!iter.ReadInt(&type) || + !iter.ReadInt(&form->times_used) || + !autofill::DeserializeFormData(&iter, &form->form_data)) { + LogDeserializationWarning(version, signon_realm, false); + return false; + } + form->type = static_cast<PasswordForm::Type>(type); + } + + if (version > 2) { + int64 date_synced = 0; + if (!iter.ReadInt64(&date_synced)) { + LogDeserializationWarning(version, signon_realm, false); + return false; + } + form->date_synced = base::Time::FromInternalValue(date_synced); + } + + if (version > 3) { + if (!iter.ReadString16(&form->display_name) || + !ReadGURL(&iter, warn_only, &form->avatar_url) || + !ReadGURL(&iter, warn_only, &form->federation_url) || + !iter.ReadBool(&form->skip_zero_click)) { + LogDeserializationWarning(version, signon_realm, false); + return false; + } + } + + if (version > 4) { + form->date_created = base::Time::FromInternalValue(date_created); + } else { + form->date_created = base::Time::FromTimeT(date_created); + } + + if (version > 5) { + if (!iter.ReadInt(&generation_upload_status)) { + LogDeserializationWarning(version, signon_realm, false); + } + form->generation_upload_status = + static_cast<PasswordForm::GenerationUploadStatus>( + generation_upload_status); + } + + converted_forms.push_back(form.release()); + } + + forms->swap(converted_forms); + return true; +} + +// Serializes a list of PasswordForms to be stored in the wallet. +void SerializeValue(const std::vector<autofill::PasswordForm*>& forms, + Pickle* pickle) { + pickle->WriteInt(kPickleVersion); + pickle->WriteSizeT(forms.size()); + for (autofill::PasswordForm* form : forms) { + pickle->WriteInt(form->scheme); + pickle->WriteString(form->origin.spec()); + pickle->WriteString(form->action.spec()); + pickle->WriteString16(form->username_element); + pickle->WriteString16(form->username_value); + pickle->WriteString16(form->password_element); + pickle->WriteString16(form->password_value); + pickle->WriteString16(form->submit_element); + pickle->WriteBool(form->ssl_valid); + pickle->WriteBool(form->preferred); + pickle->WriteBool(form->blacklisted_by_user); + pickle->WriteInt64(form->date_created.ToInternalValue()); + pickle->WriteInt(form->type); + pickle->WriteInt(form->times_used); + autofill::SerializeFormData(form->form_data, pickle); + pickle->WriteInt64(form->date_synced.ToInternalValue()); + pickle->WriteString16(form->display_name); + pickle->WriteString(form->avatar_url.spec()); + pickle->WriteString(form->federation_url.spec()); + pickle->WriteBool(form->skip_zero_click); + } +} + +// Moves the content of |second| to the end of |first|. +void AppendSecondToFirst(ScopedVector<autofill::PasswordForm>* first, + ScopedVector<autofill::PasswordForm> second) { + first->reserve(first->size() + second.size()); + first->insert(first->end(), second.begin(), second.end()); + second.weak_clear(); +} + } // namespace NativeBackendKWallet::NativeBackendKWallet(LocalProfileId id) @@ -272,7 +441,8 @@ return password_manager::PasswordStoreChangeList(); ScopedVector<autofill::PasswordForm> forms; - GetLoginsList(form.signon_realm, wallet_handle, &forms); + if (!GetLoginsList(form.signon_realm, wallet_handle, &forms)) + return password_manager::PasswordStoreChangeList(); // We search for a login to update, rather than unconditionally appending the // login, because in some cases (especially involving sync) we can be asked to @@ -311,7 +481,8 @@ return false; ScopedVector<autofill::PasswordForm> forms; - GetLoginsList(form.signon_realm, wallet_handle, &forms); + if (!GetLoginsList(form.signon_realm, wallet_handle, &forms)) + return false; bool updated = false; for (size_t i = 0; i < forms.size(); ++i) { @@ -338,7 +509,8 @@ return false; ScopedVector<autofill::PasswordForm> all_forms; - GetLoginsList(form.signon_realm, wallet_handle, &all_forms); + if (!GetLoginsList(form.signon_realm, wallet_handle, &all_forms)) + return false; ScopedVector<autofill::PasswordForm> kept_forms; kept_forms.reserve(all_forms.size()); @@ -382,7 +554,7 @@ int wallet_handle = WalletHandle(); if (wallet_handle == kInvalidKWalletHandle) return false; - return GetLoginsList(true, wallet_handle, forms); + return GetLoginsList(BlacklistOptions::AUTOFILLABLE, wallet_handle, forms); } bool NativeBackendKWallet::GetBlacklistLogins( @@ -390,13 +562,14 @@ int wallet_handle = WalletHandle(); if (wallet_handle == kInvalidKWalletHandle) return false; - return GetLoginsList(false, wallet_handle, forms); + return GetLoginsList(BlacklistOptions::BLACKLISTED, wallet_handle, forms); } bool NativeBackendKWallet::GetLoginsList( const std::string& signon_realm, int wallet_handle, ScopedVector<autofill::PasswordForm>* forms) { + forms->clear(); // Is there an entry in the wallet? { dbus::MethodCall method_call(kKWalletInterface, "hasEntry"); @@ -459,24 +632,26 @@ // Can't we all just agree on whether bytes are signed or not? Please? Pickle pickle(reinterpret_cast<const char*>(bytes), length); - DeserializeValue(signon_realm, pickle, forms); + *forms = DeserializeValue(signon_realm, pickle); } return true; } bool NativeBackendKWallet::GetLoginsList( - bool autofillable, + BlacklistOptions options, int wallet_handle, ScopedVector<autofill::PasswordForm>* forms) { + forms->clear(); ScopedVector<autofill::PasswordForm> all_forms; if (!GetAllLogins(wallet_handle, &all_forms)) return false; // We have to read all the entries, and then filter them here. - forms->reserve(forms->size() + all_forms.size()); + forms->reserve(all_forms.size()); for (auto& saved_form : all_forms) { - if (saved_form->blacklisted_by_user == !autofillable) { + if (saved_form->blacklisted_by_user == + (options == BlacklistOptions::BLACKLISTED)) { forms->push_back(saved_form); saved_form = nullptr; } @@ -511,8 +686,8 @@ } } - for (size_t i = 0; i < realm_list.size(); ++i) { - const std::string& signon_realm = realm_list[i]; + forms->clear(); + for (const std::string& signon_realm : realm_list) { dbus::MethodCall method_call(kKWalletInterface, "readEntry"); dbus::MessageWriter builder(&method_call); builder.AppendInt32(wallet_handle); // handle @@ -539,7 +714,7 @@ // Can't we all just agree on whether bytes are signed or not? Please? Pickle pickle(reinterpret_cast<const char*>(bytes), length); - DeserializeValue(signon_realm, pickle, forms); + AppendSecondToFirst(forms, DeserializeValue(signon_realm, pickle)); } return true; } @@ -676,8 +851,8 @@ // Can't we all just agree on whether bytes are signed or not? Please? Pickle pickle(reinterpret_cast<const char*>(bytes), length); - ScopedVector<autofill::PasswordForm> all_forms; - DeserializeValue(signon_realm, pickle, &all_forms); + ScopedVector<autofill::PasswordForm> all_forms = + DeserializeValue(signon_realm, pickle); ScopedVector<autofill::PasswordForm> kept_forms; kept_forms.reserve(all_forms.size()); @@ -705,160 +880,9 @@ } // static -void NativeBackendKWallet::SerializeValue( - const std::vector<autofill::PasswordForm*>& forms, - Pickle* pickle) { - pickle->WriteInt(kPickleVersion); - pickle->WriteSizeT(forms.size()); - for (autofill::PasswordForm* form : forms) { - pickle->WriteInt(form->scheme); - pickle->WriteString(form->origin.spec()); - pickle->WriteString(form->action.spec()); - pickle->WriteString16(form->username_element); - pickle->WriteString16(form->username_value); - pickle->WriteString16(form->password_element); - pickle->WriteString16(form->password_value); - pickle->WriteString16(form->submit_element); - pickle->WriteBool(form->ssl_valid); - pickle->WriteBool(form->preferred); - pickle->WriteBool(form->blacklisted_by_user); - pickle->WriteInt64(form->date_created.ToInternalValue()); - pickle->WriteInt(form->type); - pickle->WriteInt(form->times_used); - autofill::SerializeFormData(form->form_data, pickle); - pickle->WriteInt64(form->date_synced.ToInternalValue()); - pickle->WriteString16(form->display_name); - pickle->WriteString(form->avatar_url.spec()); - pickle->WriteString(form->federation_url.spec()); - pickle->WriteBool(form->skip_zero_click); - pickle->WriteInt(form->generation_upload_status); - } -} - -// static -bool NativeBackendKWallet::DeserializeValueSize( +ScopedVector<autofill::PasswordForm> NativeBackendKWallet::DeserializeValue( const std::string& signon_realm, - const PickleIterator& init_iter, - int version, - bool size_32, - bool warn_only, - ScopedVector<autofill::PasswordForm>* forms) { - PickleIterator iter = init_iter; - - size_t count = 0; - if (size_32) { - uint32_t count_32 = 0; - if (!iter.ReadUInt32(&count_32)) { - LOG(ERROR) << "Failed to deserialize KWallet entry " - << "(realm: " << signon_realm << ")"; - return false; - } - count = count_32; - } else { - if (!iter.ReadSizeT(&count)) { - LOG(ERROR) << "Failed to deserialize KWallet entry " - << "(realm: " << signon_realm << ")"; - return false; - } - } - - if (count > 0xFFFF) { - // Trying to pin down the cause of http://crbug.com/80728 (or fix it). - // This is a very large number of passwords to be saved for a single realm. - // It is almost certainly a corrupt pickle and not real data. Ignore it. - // This very well might actually be http://crbug.com/107701, so if we're - // reading an old pickle, we don't even log this the first time we try to - // read it. (That is, when we're reading the native architecture size.) - if (!warn_only) { - LOG(ERROR) << "Suspiciously large number of entries in KWallet entry " - << "(" << count << "; realm: " << signon_realm << ")"; - } - return false; - } - - forms->reserve(forms->size() + count); - for (size_t i = 0; i < count; ++i) { - scoped_ptr<PasswordForm> form(new PasswordForm()); - form->signon_realm.assign(signon_realm); - - int scheme = 0; - int64 date_created = 0; - int type = 0; - int generation_upload_status = 0; - // Note that these will be read back in the order listed due to - // short-circuit evaluation. This is important. - if (!iter.ReadInt(&scheme) || - !ReadGURL(&iter, warn_only, &form->origin) || - !ReadGURL(&iter, warn_only, &form->action) || - !iter.ReadString16(&form->username_element) || - !iter.ReadString16(&form->username_value) || - !iter.ReadString16(&form->password_element) || - !iter.ReadString16(&form->password_value) || - !iter.ReadString16(&form->submit_element) || - !iter.ReadBool(&form->ssl_valid) || - !iter.ReadBool(&form->preferred) || - !iter.ReadBool(&form->blacklisted_by_user) || - !iter.ReadInt64(&date_created)) { - LogDeserializationWarning(version, signon_realm, warn_only); - return false; - } - form->scheme = static_cast<PasswordForm::Scheme>(scheme); - - if (version > 1) { - if (!iter.ReadInt(&type) || - !iter.ReadInt(&form->times_used) || - !autofill::DeserializeFormData(&iter, &form->form_data)) { - LogDeserializationWarning(version, signon_realm, false); - return false; - } - form->type = static_cast<PasswordForm::Type>(type); - } - - if (version > 2) { - int64 date_synced = 0; - if (!iter.ReadInt64(&date_synced)) { - LogDeserializationWarning(version, signon_realm, false); - return false; - } - form->date_synced = base::Time::FromInternalValue(date_synced); - } - - if (version > 3) { - if (!iter.ReadString16(&form->display_name) || - !ReadGURL(&iter, warn_only, &form->avatar_url) || - !ReadGURL(&iter, warn_only, &form->federation_url) || - !iter.ReadBool(&form->skip_zero_click)) { - LogDeserializationWarning(version, signon_realm, false); - return false; - } - } - - if (version > 4) { - form->date_created = base::Time::FromInternalValue(date_created); - } else { - form->date_created = base::Time::FromTimeT(date_created); - } - - if (version > 5) { - if (!iter.ReadInt(&generation_upload_status)) { - LogDeserializationWarning(version, signon_realm, false); - } - form->generation_upload_status = - static_cast<PasswordForm::GenerationUploadStatus>( - generation_upload_status); - } - - forms->push_back(form.release()); - } - - return true; -} - -// static -void NativeBackendKWallet::DeserializeValue( - const std::string& signon_realm, - const Pickle& pickle, - ScopedVector<autofill::PasswordForm>* forms) { + const Pickle& pickle) { PickleIterator iter(pickle); int version = -1; @@ -866,26 +890,26 @@ version < 0 || version > kPickleVersion) { LOG(ERROR) << "Failed to deserialize KWallet entry " << "(realm: " << signon_realm << ")"; - return; + return ScopedVector<autofill::PasswordForm>(); } + ScopedVector<autofill::PasswordForm> forms; if (version > 0) { // In current pickles, we expect 64-bit sizes. Failure is an error. - DeserializeValueSize(signon_realm, iter, version, false, false, forms); - return; + DeserializeValueSize(signon_realm, iter, version, false, false, &forms); + return forms.Pass(); } - const size_t saved_forms_size = forms->size(); const bool size_32 = sizeof(size_t) == sizeof(uint32_t); if (!DeserializeValueSize( - signon_realm, iter, version, size_32, true, forms)) { + signon_realm, iter, version, size_32, true, &forms)) { // We failed to read the pickle using the native architecture of the system. // Try again with the opposite architecture. Note that we do this even on // 32-bit machines, in case we're reading a 64-bit pickle. (Probably rare, // since mostly we expect upgrades, not downgrades, but both are possible.) - forms->resize(saved_forms_size); - DeserializeValueSize(signon_realm, iter, version, !size_32, false, forms); + DeserializeValueSize(signon_realm, iter, version, !size_32, false, &forms); } + return forms.Pass(); } int NativeBackendKWallet::WalletHandle() {
diff --git a/chrome/browser/password_manager/native_backend_kwallet_x.h b/chrome/browser/password_manager/native_backend_kwallet_x.h index 6e98a41..6227269 100644 --- a/chrome/browser/password_manager/native_backend_kwallet_x.h +++ b/chrome/browser/password_manager/native_backend_kwallet_x.h
@@ -8,6 +8,7 @@ #include <string> #include "base/basictypes.h" +#include "base/compiler_specific.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_vector.h" #include "base/time/time.h" @@ -68,9 +69,9 @@ bool InitWithBus(scoped_refptr<dbus::Bus> optional_bus); // Deserializes a list of PasswordForms from the wallet. - static void DeserializeValue(const std::string& signon_realm, - const Pickle& pickle, - ScopedVector<autofill::PasswordForm>* forms); + static ScopedVector<autofill::PasswordForm> DeserializeValue( + const std::string& signon_realm, + const Pickle& pickle); private: enum InitResult { @@ -84,6 +85,8 @@ SYNC_TIMESTAMP, }; + enum class BlacklistOptions { AUTOFILLABLE, BLACKLISTED }; + // Initialization. bool StartKWalletd(); InitResult InitWallet(); @@ -91,19 +94,24 @@ base::WaitableEvent* event, bool* success); - // Reads PasswordForms from the wallet that match the given signon_realm. + // Overwrites |forms| with all credentials matching |signon_realm|. Returns + // true on success. bool GetLoginsList(const std::string& signon_realm, int wallet_handle, - ScopedVector<autofill::PasswordForm>* forms); + ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT; - // Reads PasswordForms from the wallet with the given autofillability state. - bool GetLoginsList(bool autofillable, + // Overwrites |forms| with all credentials matching |options|. Returns true on + // success. + bool GetLoginsList(BlacklistOptions options, int wallet_handle, - ScopedVector<autofill::PasswordForm>* forms); + ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT; - // Helper for some of the above GetLoginsList() methods. + // Overwrites |forms| with all stored credentials. Returns true on success. bool GetAllLogins(int wallet_handle, - ScopedVector<autofill::PasswordForm>* forms); + ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT; // Writes a list of PasswordForms to the wallet with the given signon_realm. // Overwrites any existing list for this signon_realm. Removes the entry if @@ -123,27 +131,6 @@ // Returns kInvalidWalletHandle on error. int WalletHandle(); - // Serializes a list of PasswordForms to be stored in the wallet. - static void SerializeValue(const std::vector<autofill::PasswordForm*>& forms, - Pickle* pickle); - - // Deserializes a list of PasswordForms from the wallet. - // |size_32| controls reading the size field within the pickle as 32 bits. - // We used to use Pickle::WriteSize() to write the number of password forms, - // but that has a different size on 32- and 64-bit systems. So, now we always - // write a 64-bit quantity, but we support trying to read it as either size - // when reading old pickles that fail to deserialize using the native size. - static bool DeserializeValueSize(const std::string& signon_realm, - const PickleIterator& iter, - int version, - bool size_32, - bool warn_only, - ScopedVector<autofill::PasswordForm>* forms); - - // In case the fields in the pickle ever change, version them so we can try to - // read old pickles. (Note: do not eat old pickles past the expiration date.) - static const int kPickleVersion = 6; - // Generates a profile-specific folder name based on profile_id_. std::string GetProfileSpecificFolderName() const;
diff --git a/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc b/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc index 4105ed7..297a765c1 100644 --- a/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc +++ b/chrome/browser/password_manager/native_backend_kwallet_x_unittest.cc
@@ -606,8 +606,8 @@ TestKWallet::Blob value; EXPECT_TRUE(wallet_.readEntry(folder, entries[i], &value)); Pickle pickle(reinterpret_cast<const char*>(value.data()), value.size()); - ScopedVector<autofill::PasswordForm> forms; - NativeBackendKWalletStub::DeserializeValue(entries[i], pickle, &forms); + ScopedVector<autofill::PasswordForm> forms = + NativeBackendKWalletStub::DeserializeValue(entries[i], pickle); const std::vector<const PasswordForm*>& expect = sorted_expected[i].second; EXPECT_EQ(expect.size(), forms.size()); for (size_t j = 0; j < forms.size() && j < expect.size(); ++j) @@ -881,42 +881,6 @@ CheckPasswordForms("Chrome Form Data (42)", expected); } -TEST_F(NativeBackendKWalletTest, ListLoginsAppends) { - NativeBackendKWalletStub backend(42); - EXPECT_TRUE(backend.InitWithBus(mock_session_bus_)); - - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind(base::IgnoreResult(&NativeBackendKWalletStub::AddLogin), - base::Unretained(&backend), form_google_)); - - // Send the same request twice with the same list both times. - ScopedVector<autofill::PasswordForm> form_list; - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind( - base::IgnoreResult(&NativeBackendKWalletStub::GetAutofillableLogins), - base::Unretained(&backend), &form_list)); - BrowserThread::PostTask( - BrowserThread::DB, FROM_HERE, - base::Bind( - base::IgnoreResult(&NativeBackendKWalletStub::GetAutofillableLogins), - base::Unretained(&backend), &form_list)); - - RunDBThread(); - - // Quick check that we got two results back. - EXPECT_EQ(2u, form_list.size()); - - EXPECT_FALSE(wallet_.hasFolder("Chrome Form Data")); - - std::vector<const PasswordForm*> forms; - forms.push_back(&form_google_); - ExpectationArray expected; - expected.push_back(make_pair(std::string(form_google_.signon_realm), forms)); - CheckPasswordForms("Chrome Form Data (42)", expected); -} - TEST_F(NativeBackendKWalletTest, AndroidCredentials) { NativeBackendKWalletStub backend(42); EXPECT_TRUE(backend.InitWithBus(mock_session_bus_)); @@ -1085,9 +1049,8 @@ form.generation_upload_status = PasswordForm::NEGATIVE_SIGNAL_SENT; CreateVersion6Pickle(form, &pickle); - ScopedVector<PasswordForm> form_list; - NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle, - &form_list); + ScopedVector<PasswordForm> form_list = + NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle); EXPECT_EQ(1u, form_list.size()); if (form_list.size() > 0) @@ -1100,9 +1063,8 @@ PasswordForm form = form_google_; CreateVersion5Pickle(form, &pickle); - ScopedVector<PasswordForm> form_list; - NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle, - &form_list); + ScopedVector<PasswordForm> form_list = + NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle); EXPECT_EQ(1u, form_list.size()); if (form_list.size() > 0) @@ -1119,9 +1081,8 @@ form.skip_zero_click = false; CreateVersion3Pickle(form, &pickle); - ScopedVector<PasswordForm> form_list; - NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle, - &form_list); + ScopedVector<PasswordForm> form_list = + NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle); EXPECT_EQ(1u, form_list.size()); if (form_list.size() > 0) @@ -1136,9 +1097,8 @@ form.form_data = form_google_.form_data; CreateVersion2Pickle(form, &pickle); - ScopedVector<PasswordForm> form_list; - NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle, - &form_list); + ScopedVector<PasswordForm> form_list = + NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle); EXPECT_EQ(1u, form_list.size()); if (form_list.size() > 0) @@ -1151,9 +1111,8 @@ PasswordForm form = form_google_; CreateVersion1Pickle(form, &pickle); - ScopedVector<autofill::PasswordForm> form_list; - NativeBackendKWalletStub::DeserializeValue(form.signon_realm, - pickle, &form_list); + ScopedVector<autofill::PasswordForm> form_list = + NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle); // This will match |old_form_google_| because not all the fields present in // |form_google_| will be deserialized. @@ -1168,9 +1127,8 @@ PasswordForm form = old_form_google_; form.scheme = scheme; CreateVersion0Pickle(size_32, form, &pickle); - ScopedVector<autofill::PasswordForm> form_list; - NativeBackendKWalletStub::DeserializeValue(form.signon_realm, - pickle, &form_list); + ScopedVector<autofill::PasswordForm> form_list = + NativeBackendKWalletStub::DeserializeValue(form.signon_realm, pickle); EXPECT_EQ(1u, form_list.size()); if (form_list.size() > 0) CheckPasswordForm(form, *form_list[0], false);
diff --git a/chrome/browser/password_manager/native_backend_libsecret.cc b/chrome/browser/password_manager/native_backend_libsecret.cc index 3aaca6d3..86db71a 100644 --- a/chrome/browser/password_manager/native_backend_libsecret.cc +++ b/chrome/browser/password_manager/native_backend_libsecret.cc
@@ -236,6 +236,14 @@ Append(name, base::Int64ToString(value)); } +// Generates a profile-specific app string based on profile_id_. +std::string GetProfileSpecificAppString(LocalProfileId id) { + // Originally, the application string was always just "chrome" and used only + // so that we had *something* to search for since GNOME Keyring won't search + // for nothing. Now we use it to distinguish passwords for different profiles. + return base::StringPrintf("%s-%d", kLibsecretAppString, id); +} + } // namespace bool LibsecretLoader::LibsecretIsAvailable() { @@ -280,8 +288,8 @@ // element, and signon_realm first, remove that, and then add the new entry. // We'd add the new one first, and then delete the original, but then the // delete might actually delete the newly-added entry! - ScopedVector<autofill::PasswordForm> forms; - AddUpdateLoginSearch(form, SEARCH_USE_SUBMIT, &forms); + ScopedVector<autofill::PasswordForm> forms = + AddUpdateLoginSearch(form, SEARCH_USE_SUBMIT); password_manager::PasswordStoreChangeList changes; if (forms.size() > 0) { if (forms.size() > 1) { @@ -313,8 +321,8 @@ DCHECK(changes); changes->clear(); - ScopedVector<autofill::PasswordForm> forms; - AddUpdateLoginSearch(form, SEARCH_IGNORE_SUBMIT, &forms); + ScopedVector<autofill::PasswordForm> forms = + AddUpdateLoginSearch(form, SEARCH_IGNORE_SUBMIT); bool removed = false; for (size_t i = 0; i < forms.size(); ++i) { @@ -375,10 +383,10 @@ return GetLoginsList(&form, ALL_LOGINS, forms); } -void NativeBackendLibsecret::AddUpdateLoginSearch( +ScopedVector<autofill::PasswordForm> +NativeBackendLibsecret::AddUpdateLoginSearch( const autofill::PasswordForm& lookup_form, - AddUpdateLoginSearchOptions options, - ScopedVector<autofill::PasswordForm>* forms) { + AddUpdateLoginSearchOptions options) { LibsecretAttributesBuilder attrs; attrs.Append("origin_url", lookup_form.origin.spec()); attrs.Append("username_element", UTF16ToUTF8(lookup_form.username_element)); @@ -400,10 +408,10 @@ g_error_free(error); if (found) g_list_free(found); - return; + return ScopedVector<autofill::PasswordForm>(); } - ConvertFormList(found, &lookup_form, forms); + return ConvertFormList(found, &lookup_form); } bool NativeBackendLibsecret::RawAddLogin(const PasswordForm& form) { @@ -492,12 +500,8 @@ return false; } - return ConvertFormList(found, lookup_form, forms); -} - -bool NativeBackendLibsecret::GetAllLogins( - ScopedVector<autofill::PasswordForm>* forms) { - return GetLoginsList(nullptr, ALL_LOGINS, forms); + *forms = ConvertFormList(found, lookup_form); + return true; } bool NativeBackendLibsecret::GetLoginsBetween( @@ -505,8 +509,9 @@ base::Time get_end, TimestampToCompare date_to_compare, ScopedVector<autofill::PasswordForm>* forms) { + forms->clear(); ScopedVector<autofill::PasswordForm> all_forms; - if (!GetAllLogins(&all_forms)) + if (!GetLoginsList(nullptr, ALL_LOGINS, &all_forms)) return false; base::Time autofill::PasswordForm::*date_member = @@ -547,10 +552,10 @@ return ok; } -bool NativeBackendLibsecret::ConvertFormList( +ScopedVector<autofill::PasswordForm> NativeBackendLibsecret::ConvertFormList( GList* found, - const PasswordForm* lookup_form, - ScopedVector<autofill::PasswordForm>* forms) { + const PasswordForm* lookup_form) { + ScopedVector<autofill::PasswordForm> forms; password_manager::PSLDomainMatchMetric psl_domain_match_metric = password_manager::PSL_DOMAIN_MATCH_NONE; GError* error = nullptr; @@ -588,7 +593,7 @@ } else { VLOG(1) << "Unable to access password from list element!"; } - forms->push_back(form.release()); + forms.push_back(form.release()); } else { VLOG(1) << "Could not initialize PasswordForm from attributes!"; } @@ -606,13 +611,5 @@ password_manager::PSL_DOMAIN_MATCH_COUNT); } g_list_free(found); - return true; -} - -std::string NativeBackendLibsecret::GetProfileSpecificAppString( - LocalProfileId id) { - // Originally, the application string was always just "chrome" and used only - // so that we had *something* to search for since GNOME Keyring won't search - // for nothing. Now we use it to distinguish passwords for different profiles. - return base::StringPrintf("%s-%d", kLibsecretAppString, id); + return forms.Pass(); }
diff --git a/chrome/browser/password_manager/native_backend_libsecret.h b/chrome/browser/password_manager/native_backend_libsecret.h index 15dfc39..76574a98 100644 --- a/chrome/browser/password_manager/native_backend_libsecret.h +++ b/chrome/browser/password_manager/native_backend_libsecret.h
@@ -10,6 +10,7 @@ #include <string> #include "base/basictypes.h" +#include "base/compiler_specific.h" #include "base/memory/scoped_vector.h" #include "base/time/time.h" #include "chrome/browser/password_manager/password_store_factory.h" @@ -86,10 +87,10 @@ SEARCH_IGNORE_SUBMIT, }; - // Search that is used in AddLogin and UpdateLogin methods - void AddUpdateLoginSearch(const autofill::PasswordForm& lookup_form, - AddUpdateLoginSearchOptions options, - ScopedVector<autofill::PasswordForm>* forms); + // Returns credentials matching |lookup_form| and |options|. + ScopedVector<autofill::PasswordForm> AddUpdateLoginSearch( + const autofill::PasswordForm& lookup_form, + AddUpdateLoginSearchOptions options); // Adds a login form without checking for one to replace first. bool RawAddLogin(const autofill::PasswordForm& form); @@ -100,20 +101,21 @@ BLACKLISTED_LOGINS, }; - // Reads PasswordForms from the keyring with the given autofillability state. + // Retrieves credentials matching |options| from the keyring into |forms|, + // overwriting the original contents of |forms|. If |lookup_form| is not NULL, + // only retrieves credentials PSL-matching it. Returns true on success. bool GetLoginsList(const autofill::PasswordForm* lookup_form, GetLoginsListOptions options, - ScopedVector<autofill::PasswordForm>* forms); + ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT; - // Helper for GetLoginsCreatedBetween(). - bool GetAllLogins(ScopedVector<autofill::PasswordForm>* forms); - - // Retrieves password created/synced in the time interval. Returns |true| if - // the operation succeeded. + // Retrieves password created/synced in the time interval into |forms|, + // overwriting the original contents of |forms|. Returns true on success. bool GetLoginsBetween(base::Time get_begin, base::Time get_end, TimestampToCompare date_to_compare, - ScopedVector<autofill::PasswordForm>* forms); + ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT; // Removes password created/synced in the time interval. Returns |true| if the // operation succeeded. |changes| will contain the changes applied. @@ -123,12 +125,9 @@ password_manager::PasswordStoreChangeList* changes); // convert data get from Libsecret to Passwordform - bool ConvertFormList(GList* found, - const autofill::PasswordForm* lookup_form, - ScopedVector<autofill::PasswordForm>* forms); - - // Generates a profile-specific app string based on profile_id_. - static std::string GetProfileSpecificAppString(LocalProfileId id); + ScopedVector<autofill::PasswordForm> ConvertFormList( + GList* found, + const autofill::PasswordForm* lookup_form); // The app string, possibly based on the local profile id. std::string app_string_;
diff --git a/chrome/browser/password_manager/native_backend_libsecret_unittest.cc b/chrome/browser/password_manager/native_backend_libsecret_unittest.cc index 40fbbc4..9ebd4f6 100644 --- a/chrome/browser/password_manager/native_backend_libsecret_unittest.cc +++ b/chrome/browser/password_manager/native_backend_libsecret_unittest.cc
@@ -151,13 +151,17 @@ g_hash_table_insert(attributes, g_strdup(name), value); } va_end(ap); - for (uint32_t i = 0; i < global_mock_libsecret_items->size();) - if (Matches((*global_mock_libsecret_items)[i], attributes)) { - global_mock_libsecret_items->erase(global_mock_libsecret_items->begin() + - i); - } else { - ++i; + + ScopedVector<MockSecretItem> kept_mock_libsecret_items; + kept_mock_libsecret_items.reserve(global_mock_libsecret_items->size()); + for (auto& item : *global_mock_libsecret_items) { + if (!Matches(item, attributes)) { + kept_mock_libsecret_items.push_back(item); + item = nullptr; } + } + global_mock_libsecret_items->swap(kept_mock_libsecret_items); + g_hash_table_unref(attributes); return true; } @@ -796,26 +800,6 @@ "chrome-42"); } -TEST_F(NativeBackendLibsecretTest, ListLoginsAppends) { - NativeBackendLibsecret backend(42); - - backend.AddLogin(form_google_); - - // Send the same request twice with the same list both times. - ScopedVector<autofill::PasswordForm> form_list; - backend.GetAutofillableLogins(&form_list); - backend.GetAutofillableLogins(&form_list); - - // Quick check that we got two results back. - EXPECT_EQ(2u, form_list.size()); - form_list.clear(); - - EXPECT_EQ(1u, global_mock_libsecret_items->size()); - if (!global_mock_libsecret_items->empty()) - CheckMockSecretItem((*global_mock_libsecret_items)[0], form_google_, - "chrome-42"); -} - TEST_F(NativeBackendLibsecretTest, AndroidCredentials) { NativeBackendLibsecret backend(42); backend.Init(); @@ -838,7 +822,6 @@ EXPECT_EQ(saved_android_form, *form_list[0]); } - TEST_F(NativeBackendLibsecretTest, RemoveLoginsCreatedBetween) { CheckRemoveLoginsBetween(CREATED); }
diff --git a/chrome/browser/password_manager/password_store_mac.cc b/chrome/browser/password_manager/password_store_mac.cc index 31c0d2b4..a0eb2a1 100644 --- a/chrome/browser/password_manager/password_store_mac.cc +++ b/chrome/browser/password_manager/password_store_mac.cc
@@ -1062,11 +1062,11 @@ chrome::ScopedSecKeychainSetUserInteractionAllowed user_interaction_allowed( prompt_policy == ALLOW_PROMPT); - if (!login_metadata_db_) - return ScopedVector<autofill::PasswordForm>(); - ScopedVector<PasswordForm> database_forms; - login_metadata_db_->GetLogins(form, &database_forms); + if (!login_metadata_db_ || + !login_metadata_db_->GetLogins(form, &database_forms)) { + return ScopedVector<autofill::PasswordForm>(); + } // Let's gather all signon realms we want to match with keychain entries. std::set<std::string> realm_set; @@ -1110,21 +1110,24 @@ void PasswordStoreMac::GetBlacklistLoginsImpl( scoped_ptr<PasswordStore::GetLoginsRequest> request) { - ScopedVector<autofill::PasswordForm> obtained_forms; - FillBlacklistLogins(&obtained_forms); + ScopedVector<PasswordForm> obtained_forms; + if (!FillBlacklistLogins(&obtained_forms)) + obtained_forms.clear(); request->NotifyConsumerWithResults(obtained_forms.Pass()); } void PasswordStoreMac::GetAutofillableLoginsImpl( scoped_ptr<PasswordStore::GetLoginsRequest> request) { - ScopedVector<autofill::PasswordForm> obtained_forms; - FillAutofillableLogins(&obtained_forms); + ScopedVector<PasswordForm> obtained_forms; + if (!FillAutofillableLogins(&obtained_forms)) + obtained_forms.clear(); request->NotifyConsumerWithResults(obtained_forms.Pass()); } bool PasswordStoreMac::FillAutofillableLogins( - ScopedVector<autofill::PasswordForm>* forms) { - DCHECK(thread_->message_loop() == base::MessageLoop::current()); + ScopedVector<PasswordForm>* forms) { + DCHECK_EQ(thread_->message_loop(), base::MessageLoop::current()); + forms->clear(); ScopedVector<PasswordForm> database_forms; if (!login_metadata_db_ || @@ -1142,9 +1145,8 @@ return true; } -bool PasswordStoreMac::FillBlacklistLogins( - ScopedVector<autofill::PasswordForm>* forms) { - DCHECK(thread_->message_loop() == base::MessageLoop::current()); +bool PasswordStoreMac::FillBlacklistLogins(ScopedVector<PasswordForm>* forms) { + DCHECK_EQ(thread_->message_loop(), base::MessageLoop::current()); return login_metadata_db_ && login_metadata_db_->GetBlacklistLogins(forms); } @@ -1161,7 +1163,8 @@ DCHECK(login_metadata_db_); bool has_match = false; ScopedVector<autofill::PasswordForm> database_forms; - login_metadata_db_->GetLogins(form, &database_forms); + if (!login_metadata_db_->GetLogins(form, &database_forms)) + return false; for (const autofill::PasswordForm* db_form : database_forms) { // Below we filter out forms with non-empty original_signon_realm, because // those signal fuzzy matches, and we are only interested in exact ones. @@ -1204,7 +1207,8 @@ DCHECK(login_metadata_db_); ScopedVector<autofill::PasswordForm> database_forms; - login_metadata_db_->GetAutofillableLogins(&database_forms); + if (!login_metadata_db_->GetAutofillableLogins(&database_forms)) + return; // Filter forms with corresponding Keychain entry out of |database_forms|. ScopedVector<PasswordForm> forms_with_keychain_entry;
diff --git a/chrome/browser/password_manager/password_store_mac_unittest.cc b/chrome/browser/password_manager/password_store_mac_unittest.cc index 71ac708..6cd6013 100644 --- a/chrome/browser/password_manager/password_store_mac_unittest.cc +++ b/chrome/browser/password_manager/password_store_mac_unittest.cc
@@ -491,7 +491,6 @@ keychain_adapter.PasswordsFillingForm(query_form->signon_realm, query_form->scheme); EXPECT_EQ(test_data[i].expected_fill_matches, matching_items.size()); - matching_items.clear(); // Check matches treating the form as a merging target. EXPECT_EQ(test_data[i].expected_merge_matches > 0, @@ -1247,9 +1246,8 @@ } else { EXPECT_EQ(0U, matching_items.size()) << "iteration " << i; } - matching_items.clear(); - login_db()->GetLogins(*query_form, &matching_items); + EXPECT_TRUE(login_db()->GetLogins(*query_form, &matching_items)); EXPECT_EQ(updates[i].password ? 1U : 0U, matching_items.size()) << "iteration " << i; } @@ -1312,13 +1310,13 @@ owned_keychain_adapter.PasswordsFillingForm(www_form->signon_realm, www_form->scheme); EXPECT_EQ(0u, matching_items.size()); - login_db()->GetLogins(*www_form, &matching_items); + EXPECT_TRUE(login_db()->GetLogins(*www_form, &matching_items)); EXPECT_EQ(0u, matching_items.size()); // No trace of m.facebook.com. matching_items = owned_keychain_adapter.PasswordsFillingForm( m_form.signon_realm, m_form.scheme); EXPECT_EQ(0u, matching_items.size()); - login_db()->GetLogins(m_form, &matching_items); + EXPECT_TRUE(login_db()->GetLogins(m_form, &matching_items)); EXPECT_EQ(0u, matching_items.size()); } @@ -1486,15 +1484,14 @@ FinishAsyncProcessing(); ScopedVector<PasswordForm> matching_items; - login_db()->GetLogins(*www_form, &matching_items); + EXPECT_TRUE(login_db()->GetLogins(*www_form, &matching_items)); EXPECT_EQ(1u, matching_items.size()); - matching_items.clear(); store_->RemoveLoginsCreatedBetween(base::Time(), base::Time()); FinishAsyncProcessing(); // Check the second facebook form is gone. - login_db()->GetLogins(*www_form, &matching_items); + EXPECT_TRUE(login_db()->GetLogins(*www_form, &matching_items)); EXPECT_EQ(0u, matching_items.size()); // Check the first facebook form is still there. @@ -1502,7 +1499,6 @@ www_form->signon_realm, www_form->scheme); ASSERT_EQ(1u, matching_items.size()); EXPECT_EQ(ASCIIToUTF16("joe_user"), matching_items[0]->username_value); - matching_items.clear(); // Check the third-party password is still there. owned_keychain_adapter.SetFindsOnlyOwnedItems(false); @@ -1641,7 +1637,6 @@ ScopedVector<autofill::PasswordForm> all_forms; EXPECT_TRUE(login_db()->GetAutofillableLogins(&all_forms)); EXPECT_EQ(1u, all_forms.size()); - all_forms.clear(); ::testing::Mock::VerifyAndClearExpectations(&mock_observer); // 3. Get a password for www.facebook.com. The form is implicitly removed and
diff --git a/chrome/browser/password_manager/password_store_x.cc b/chrome/browser/password_manager/password_store_x.cc index 71694ad..f490fb3 100644 --- a/chrome/browser/password_manager/password_store_x.cc +++ b/chrome/browser/password_manager/password_store_x.cc
@@ -146,13 +146,13 @@ // The native backend may succeed and return no data even while locked, if // the query did not match anything stored. So we continue to allow fallback // until we perform a write operation, or until a read returns actual data. - if (matched_forms.size() > 0) + if (!matched_forms.empty()) allow_fallback_ = false; - } else if (allow_default_store()) { - DCHECK(matched_forms.empty()); - return PasswordStoreDefault::FillMatchingLogins(form, prompt_policy); + return matched_forms.Pass(); } - return matched_forms.Pass(); + if (allow_default_store()) + return PasswordStoreDefault::FillMatchingLogins(form, prompt_policy); + return ScopedVector<autofill::PasswordForm>(); } bool PasswordStoreX::FillAutofillableLogins( @@ -221,8 +221,12 @@ ssize_t PasswordStoreX::MigrateLogins() { DCHECK(backend_.get()); ScopedVector<autofill::PasswordForm> forms; + ScopedVector<autofill::PasswordForm> blacklist_forms; bool ok = PasswordStoreDefault::FillAutofillableLogins(&forms) && - PasswordStoreDefault::FillBlacklistLogins(&forms); + PasswordStoreDefault::FillBlacklistLogins(&blacklist_forms); + forms.reserve(forms.size() + blacklist_forms.size()); + forms.insert(forms.end(), blacklist_forms.begin(), blacklist_forms.end()); + blacklist_forms.weak_clear(); if (ok) { // We add all the passwords (and blacklist entries) to the native backend // before attempting to remove any from the login database, to make sure we
diff --git a/chrome/browser/password_manager/password_store_x.h b/chrome/browser/password_manager/password_store_x.h index 7ae07eda..96ff384 100644 --- a/chrome/browser/password_manager/password_store_x.h +++ b/chrome/browser/password_manager/password_store_x.h
@@ -58,12 +58,16 @@ base::Time delete_end, password_manager::PasswordStoreChangeList* changes) = 0; + // The three methods below overwrite |forms| with all stored credentials + // matching |form|, all stored non-blacklisted credentials, and all stored + // blacklisted credentials, respectively. On success, they return true. virtual bool GetLogins(const autofill::PasswordForm& form, - ScopedVector<autofill::PasswordForm>* forms) = 0; + ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT = 0; virtual bool GetAutofillableLogins( - ScopedVector<autofill::PasswordForm>* forms) = 0; - virtual bool GetBlacklistLogins( - ScopedVector<autofill::PasswordForm>* forms) = 0; + ScopedVector<autofill::PasswordForm>* forms) WARN_UNUSED_RESULT = 0; + virtual bool GetBlacklistLogins(ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT = 0; }; // Takes ownership of |login_db| and |backend|. |backend| may be NULL in which
diff --git a/chrome/browser/password_manager/password_store_x_unittest.cc b/chrome/browser/password_manager/password_store_x_unittest.cc index 737353c..307098b 100644 --- a/chrome/browser/password_manager/password_store_x_unittest.cc +++ b/chrome/browser/password_manager/password_store_x_unittest.cc
@@ -80,17 +80,36 @@ return false; } + // Use this as a landmine to check whether results of failed Get*Logins calls + // get ignored. + static ScopedVector<autofill::PasswordForm> CreateTrashForms() { + ScopedVector<autofill::PasswordForm> forms; + PasswordForm trash; + trash.username_element = base::ASCIIToUTF16("trash u. element"); + trash.username_value = base::ASCIIToUTF16("trash u. value"); + trash.password_element = base::ASCIIToUTF16("trash p. element"); + trash.password_value = base::ASCIIToUTF16("trash p. value"); + for (size_t i = 0; i < 3; ++i) { + trash.origin = GURL(base::StringPrintf("http://trash%zu.com", i)); + forms.push_back(new PasswordForm(trash)); + } + return forms.Pass(); + } + bool GetLogins(const PasswordForm& form, ScopedVector<autofill::PasswordForm>* forms) override { + *forms = CreateTrashForms(); return false; } bool GetAutofillableLogins( ScopedVector<autofill::PasswordForm>* forms) override { + *forms = CreateTrashForms(); return false; } bool GetBlacklistLogins( ScopedVector<autofill::PasswordForm>* forms) override { + *forms = CreateTrashForms(); return false; } }; @@ -207,9 +226,9 @@ MockLoginDatabaseReturn* mock_return) { ScopedVector<autofill::PasswordForm> forms; if (autofillable) - login_db->GetAutofillableLogins(&forms); + EXPECT_TRUE(login_db->GetAutofillableLogins(&forms)); else - login_db->GetBlacklistLogins(&forms); + EXPECT_TRUE(login_db->GetBlacklistLogins(&forms)); mock_return->OnLoginDatabaseQueryDone(forms.get()); }
diff --git a/chrome/browser/pepper_broker_infobar_delegate.h b/chrome/browser/pepper_broker_infobar_delegate.h index c5f247e4..885ce6a 100644 --- a/chrome/browser/pepper_broker_infobar_delegate.h +++ b/chrome/browser/pepper_broker_infobar_delegate.h
@@ -18,7 +18,7 @@ class WebContents; } -// Shows an infobar that asks the user whether a Pepper plug-in is allowed +// Shows an infobar that asks the user whether a Pepper plugin is allowed // to connect to its (privileged) broker. The user decision is made "sticky" // by storing a content setting for the site. class PepperBrokerInfoBarDelegate : public ConfirmInfoBarDelegate {
diff --git a/chrome/browser/plugins/chrome_plugin_service_filter.cc b/chrome/browser/plugins/chrome_plugin_service_filter.cc index 03cd341..82296fd 100644 --- a/chrome/browser/plugins/chrome_plugin_service_filter.cc +++ b/chrome/browser/plugins/chrome_plugin_service_filter.cc
@@ -141,7 +141,7 @@ bool ChromePluginServiceFilter::CanLoadPlugin(int render_process_id, const base::FilePath& path) { - // The browser itself sometimes loads plug-ins to e.g. clear plug-in data. + // The browser itself sometimes loads plugins to e.g. clear plugin data. // We always grant the browser permission. if (!render_process_id) return true;
diff --git a/chrome/browser/plugins/chrome_plugin_service_filter.h b/chrome/browser/plugins/chrome_plugin_service_filter.h index bab42e0..31de3cb 100644 --- a/chrome/browser/plugins/chrome_plugin_service_filter.h +++ b/chrome/browser/plugins/chrome_plugin_service_filter.h
@@ -52,14 +52,14 @@ Profile* profile, const GURL& url); - // Lifts a restriction on a plug-in. + // Lifts a restriction on a plugin. void UnrestrictPlugin(const base::FilePath& plugin_path); - // Authorizes a given plug-in for a given process. + // Authorizes a given plugin for a given process. void AuthorizePlugin(int render_process_id, const base::FilePath& plugin_path); - // Authorizes all plug-ins for a given WebContents. If |load_blocked| is true, + // Authorizes all plugins for a given WebContents. If |load_blocked| is true, // then the renderer is told to load the plugin with given |identifier| (or // pllugins if |identifier| is empty). // This method can only be called on the UI thread.
diff --git a/chrome/browser/plugins/plugin_finder.cc b/chrome/browser/plugins/plugin_finder.cc index 5521c01..626b0a3 100644 --- a/chrome/browser/plugins/plugin_finder.cc +++ b/chrome/browser/plugins/plugin_finder.cc
@@ -33,7 +33,7 @@ typedef std::map<std::string, PluginMetadata*> PluginMap; -// Gets the full path of the plug-in file as the identifier. +// Gets the full path of the plugin file as the identifier. std::string GetLongIdentifier(const content::WebPluginInfo& plugin) { return plugin.path.AsUTF8Unsafe(); } @@ -43,7 +43,7 @@ return plugin.path.BaseName().AsUTF8Unsafe(); } -// Gets the plug-in group name as the plug-in name if it is not empty or +// Gets the plugin group name as the plugin name if it is not empty or // the filename without extension if the name is empty. static base::string16 GetGroupName(const content::WebPluginInfo& plugin) { if (!plugin.name.empty()) @@ -148,7 +148,7 @@ void PluginFinder::Init() { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - // Load the built-in plug-in list first. If we have a newer version stored + // Load the built-in plugin list first. If we have a newer version stored // locally or download one, we will replace this one with it. scoped_ptr<base::DictionaryValue> plugin_list(LoadBuiltInPluginList()); DCHECK(plugin_list); @@ -280,7 +280,7 @@ return it->second->Clone(); } - // The plug-in metadata was not found, create a dummy one holding + // The plugin metadata was not found, create a dummy one holding // the name, identifier and group name only. std::string identifier = GetIdentifier(plugin); PluginMetadata* metadata = new PluginMetadata(identifier,
diff --git a/chrome/browser/plugins/plugin_finder.h b/chrome/browser/plugins/plugin_finder.h index 41c5fc63..2940dbb 100644 --- a/chrome/browser/plugins/plugin_finder.h +++ b/chrome/browser/plugins/plugin_finder.h
@@ -43,7 +43,7 @@ void ReinitializePlugins(const base::DictionaryValue* json_metadata); #if defined(ENABLE_PLUGIN_INSTALLATION) - // Finds a plug-in for the given MIME type and language (specified as an IETF + // Finds a plugin for the given MIME type and language (specified as an IETF // language tag, i.e. en-US). If found, sets |installer| to the // corresponding PluginInstaller and |plugin_metadata| to a copy of the // corresponding PluginMetadata. @@ -52,7 +52,7 @@ PluginInstaller** installer, scoped_ptr<PluginMetadata>* plugin_metadata); - // Finds the plug-in with the given identifier. If found, sets |installer| + // Finds the plugin with the given identifier. If found, sets |installer| // to the corresponding PluginInstaller and |plugin_metadata| to a copy // of the corresponding PluginMetadata. |installer| may be NULL. bool FindPluginWithIdentifier(const std::string& identifier, @@ -60,10 +60,10 @@ scoped_ptr<PluginMetadata>* plugin_metadata); #endif - // Returns the plug-in name with the given identifier. + // Returns the plugin name with the given identifier. base::string16 FindPluginNameWithIdentifier(const std::string& identifier); - // Gets plug-in metadata using |plugin|. + // Gets plugin metadata using |plugin|. scoped_ptr<PluginMetadata> GetPluginMetadata( const content::WebPluginInfo& plugin); @@ -76,8 +76,8 @@ PluginFinder(); ~PluginFinder(); - // Loads the plug-in information from the browser resources and parses it. - // Returns NULL if the plug-in list couldn't be parsed. + // Loads the plugin information from the browser resources and parses it. + // Returns NULL if the plugin list couldn't be parsed. static base::DictionaryValue* LoadBuiltInPluginList(); #if defined(ENABLE_PLUGIN_INSTALLATION)
diff --git a/chrome/browser/plugins/plugin_info_message_filter.cc b/chrome/browser/plugins/plugin_info_message_filter.cc index 259f0d7..bb2c2cd 100644 --- a/chrome/browser/plugins/plugin_info_message_filter.cc +++ b/chrome/browser/plugins/plugin_info_message_filter.cc
@@ -351,8 +351,8 @@ ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; bool is_managed = false; - // Check plug-in content settings. The primary URL is the top origin URL and - // the secondary URL is the plug-in URL. + // Check plugin content settings. The primary URL is the top origin URL and + // the secondary URL is the plugin URL. GetPluginContentSetting(plugin, params.top_origin_url, params.url, plugin_metadata->identifier(), &plugin_setting, &uses_default_content_setting, &is_managed); @@ -361,7 +361,7 @@ PluginMetadata::SecurityStatus plugin_status = plugin_metadata->GetSecurityStatus(plugin); #if defined(ENABLE_PLUGIN_INSTALLATION) - // Check if the plug-in is outdated. + // Check if the plugin is outdated. if (plugin_status == PluginMetadata::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { @@ -373,13 +373,13 @@ return; } #endif - // Check if the plug-in or its group is enabled by policy. + // Check if the plugin or its group is enabled by policy. PluginPrefs::PolicyStatus plugin_policy = plugin_prefs_->PolicyStatusForPlugin(plugin.name); PluginPrefs::PolicyStatus group_policy = plugin_prefs_->PolicyStatusForPlugin(plugin_metadata->name()); - // Check if the plug-in requires authorization. + // Check if the plugin requires authorization. if (plugin_status == PluginMetadata::SECURITY_STATUS_REQUIRES_AUTHORIZATION && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && @@ -396,7 +396,7 @@ return; } - // Check if the plug-in is crashing too much. + // Check if the plugin is crashing too much. if (PluginService::GetInstance()->IsPluginUnstable(plugin.path) && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && @@ -473,10 +473,10 @@ } } - // If we broke out of the loop, we have found an enabled plug-in. + // If we broke out of the loop, we have found an enabled plugin. bool enabled = i < matching_plugins.size(); if (!enabled) { - // Otherwise, we only found disabled plug-ins, so we take the first one. + // Otherwise, we only found disabled plugins, so we take the first one. i = 0; status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled; }
diff --git a/chrome/browser/plugins/plugin_info_message_filter.h b/chrome/browser/plugins/plugin_info_message_filter.h index 7df942b..a9d29a9 100644 --- a/chrome/browser/plugins/plugin_info_message_filter.h +++ b/chrome/browser/plugins/plugin_info_message_filter.h
@@ -34,7 +34,7 @@ class ExtensionRegistry; } -// This class filters out incoming IPC messages requesting plug-in information. +// This class filters out incoming IPC messages requesting plugin information. class PluginInfoMessageFilter : public content::BrowserMessageFilter { public: struct GetPluginInfo_Params;
diff --git a/chrome/browser/plugins/plugin_info_message_filter_unittest.cc b/chrome/browser/plugins/plugin_info_message_filter_unittest.cc index 59bd2ba..a1cf28a0 100644 --- a/chrome/browser/plugins/plugin_info_message_filter_unittest.cc +++ b/chrome/browser/plugins/plugin_info_message_filter_unittest.cc
@@ -64,7 +64,7 @@ std::map<base::FilePath, bool>::iterator it = plugin_state_.find(plugin->path); if (it == plugin_state_.end()) { - ADD_FAILURE() << "No plug-in state for '" << plugin->path.value() << "'"; + ADD_FAILURE() << "No plugin state for '" << plugin->path.value() << "'"; return false; } return it->second; @@ -86,10 +86,10 @@ } void SetUp() override { - content::WebPluginInfo foo_plugin(base::ASCIIToUTF16("Foo Plug-in"), + content::WebPluginInfo foo_plugin(base::ASCIIToUTF16("Foo Plugin"), foo_plugin_path_, base::ASCIIToUTF16("1"), - base::ASCIIToUTF16("The Foo plug-in.")); + base::ASCIIToUTF16("The Foo plugin.")); content::WebPluginMimeType mime_type; mime_type.mime_type = "foo/bar"; foo_plugin.mime_types.push_back(mime_type); @@ -97,10 +97,10 @@ PluginService::GetInstance()->Init(); PluginService::GetInstance()->RegisterInternalPlugin(foo_plugin, false); - content::WebPluginInfo bar_plugin(base::ASCIIToUTF16("Bar Plug-in"), + content::WebPluginInfo bar_plugin(base::ASCIIToUTF16("Bar Plugin"), bar_plugin_path_, base::ASCIIToUTF16("1"), - base::ASCIIToUTF16("The Bar plug-in.")); + base::ASCIIToUTF16("The Bar plugin.")); mime_type.mime_type = "foo/bar"; bar_plugin.mime_types.push_back(mime_type); bar_plugin.type = content::WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS;
diff --git a/chrome/browser/plugins/plugin_infobar_delegates.h b/chrome/browser/plugins/plugin_infobar_delegates.h index b342141..5753031 100644 --- a/chrome/browser/plugins/plugin_infobar_delegates.h +++ b/chrome/browser/plugins/plugin_infobar_delegates.h
@@ -21,7 +21,7 @@ class WebContents; } -// Base class for blocked plug-in infobars. +// Base class for blocked plugin infobars. class PluginInfoBarDelegate : public ConfirmInfoBarDelegate { protected: explicit PluginInfoBarDelegate(const std::string& identifier); @@ -45,7 +45,7 @@ }; #if defined(ENABLE_PLUGIN_INSTALLATION) -// Infobar that's shown when a plug-in is out of date. +// Infobar that's shown when a plugin is out of date. class OutdatedPluginInfoBarDelegate : public PluginInfoBarDelegate, public WeakPluginInstallerObserver { public: @@ -99,7 +99,7 @@ // Shows an infobar asking whether to install the plugin represented by // |installer|. When the user accepts, |callback| is called. - // During installation of the plug-in, the infobar will change to reflect the + // During installation of the plugin, the infobar will change to reflect the // installation state. static void Create(InfoBarService* infobar_service, PluginInstaller* installer, @@ -148,7 +148,7 @@ InstallCallback callback_; - // True iff the plug-in isn't installed yet. + // True iff the plugin isn't installed yet. bool new_install_; base::string16 message_;
diff --git a/chrome/browser/plugins/plugin_metadata.cc b/chrome/browser/plugins/plugin_metadata.cc index 33f83a02..e79df9e 100644 --- a/chrome/browser/plugins/plugin_metadata.cc +++ b/chrome/browser/plugins/plugin_metadata.cc
@@ -61,7 +61,7 @@ bool PluginMetadata::MatchesPlugin(const content::WebPluginInfo& plugin) { for (size_t i = 0; i < matching_mime_types_.size(); ++i) { // To have a match, every one of the |matching_mime_types_| - // must be handled by the plug-in. + // must be handled by the plugin. size_t j = 0; for (; j < plugin.mime_types.size(); ++j) { if (plugin.mime_types[j].mime_type == matching_mime_types_[i])
diff --git a/chrome/browser/plugins/plugin_metadata.h b/chrome/browser/plugins/plugin_metadata.h index 261e6e87..d2be9e7 100644 --- a/chrome/browser/plugins/plugin_metadata.h +++ b/chrome/browser/plugins/plugin_metadata.h
@@ -18,7 +18,7 @@ class PluginMetadata { public: - // Information about a certain version of the plug-in. + // Information about a certain version of the plugin. enum SecurityStatus { SECURITY_STATUS_UP_TO_DATE, SECURITY_STATUS_OUT_OF_DATE, @@ -44,15 +44,15 @@ const std::string& language); ~PluginMetadata(); - // Unique identifier for the plug-in. + // Unique identifier for the plugin. const std::string& identifier() const { return identifier_; } - // Human-readable name of the plug-in. + // Human-readable name of the plugin. const base::string16& name() const { return name_; } // If |url_for_display| is false, |plugin_url| is the URL of the download page - // for the plug-in, which should be opened in a new tab. If it is true, - // |plugin_url| is the URL of the plug-in installer binary, which can be + // for the plugin, which should be opened in a new tab. If it is true, + // |plugin_url| is the URL of the plugin installer binary, which can be // directly downloaded. bool url_for_display() const { return url_for_display_; } const GURL& plugin_url() const { return plugin_url_; } @@ -66,7 +66,7 @@ void AddMimeType(const std::string& mime_type); void AddMatchingMimeType(const std::string& mime_type); - // Adds information about a plug-in version. + // Adds information about a plugin version. void AddVersion(const Version& version, SecurityStatus status); // Checks if |plugin| mime types match all |matching_mime_types_|. @@ -79,7 +79,7 @@ static bool ParseSecurityStatus(const std::string& status_str, SecurityStatus* status); - // Returns the security status for the given plug-in (i.e. whether it is + // Returns the security status for the given plugin (i.e. whether it is // considered out-of-date, etc.) SecurityStatus GetSecurityStatus(const content::WebPluginInfo& plugin) const;
diff --git a/chrome/browser/plugins/plugin_metadata_unittest.cc b/chrome/browser/plugins/plugin_metadata_unittest.cc index 03d57a7..fe9e2e65 100644 --- a/chrome/browser/plugins/plugin_metadata_unittest.cc +++ b/chrome/browser/plugins/plugin_metadata_unittest.cc
@@ -14,10 +14,10 @@ PluginMetadata* plugin_metadata, const char* version) { content::WebPluginInfo plugin( - base::ASCIIToUTF16("Foo plug-in"), + base::ASCIIToUTF16("Foo plugin"), base::FilePath(FILE_PATH_LITERAL("/tmp/plugin.so")), base::ASCIIToUTF16(version), - base::ASCIIToUTF16("Foo plug-in.")); + base::ASCIIToUTF16("Foo plugin.")); return plugin_metadata->GetSecurityStatus(plugin); }
diff --git a/chrome/browser/plugins/plugin_observer.cc b/chrome/browser/plugins/plugin_observer.cc index 53b96a03..23ba08b 100644 --- a/chrome/browser/plugins/plugin_observer.cc +++ b/chrome/browser/plugins/plugin_observer.cc
@@ -382,8 +382,8 @@ NOTREACHED(); } #else - // If we don't support third-party plug-in installation, we shouldn't have - // outdated plug-ins. + // If we don't support third-party plugin installation, we shouldn't have + // outdated plugins. NOTREACHED(); #endif // defined(ENABLE_PLUGIN_INSTALLATION) }
diff --git a/chrome/browser/plugins/plugin_prefs.cc b/chrome/browser/plugins/plugin_prefs.cc index 1dd8d77..97dcf993 100644 --- a/chrome/browser/plugins/plugin_prefs.cc +++ b/chrome/browser/plugins/plugin_prefs.cc
@@ -121,7 +121,7 @@ // Set the desired state for the group. plugin_group_state_[group_name] = enabled; - // Update the state for all plug-ins in the group. + // Update the state for all plugins in the group. for (size_t i = 0; i < plugins.size(); ++i) { scoped_ptr<PluginMetadata> plugin(finder->GetPluginMetadata(plugins[i])); if (group_name != plugin->name()) @@ -175,7 +175,7 @@ const base::Callback<void(bool)>& callback, const std::vector<content::WebPluginInfo>& plugins) { { - // Set the desired state for the plug-in. + // Set the desired state for the plugin. base::AutoLock auto_lock(lock_); plugin_state_.Set(path, enabled); } @@ -185,7 +185,7 @@ if (plugins[i].path == path) { scoped_ptr<PluginMetadata> plugin_metadata( plugin_finder->GetPluginMetadata(plugins[i])); - // set the group name for this plug-in. + // set the group name for this plugin. group_name = plugin_metadata->name(); DCHECK_EQ(enabled, IsPluginEnabled(plugins[i])); break; @@ -203,7 +203,7 @@ } if (!group_name.empty()) { - // Update the state for the corresponding plug-in group. + // Update the state for the corresponding plugin group. base::AutoLock auto_lock(lock_); plugin_group_state_[group_name] = !all_disabled; } @@ -234,13 +234,13 @@ PluginFinder::GetInstance()->GetPluginMetadata(plugin)); base::string16 group_name = plugin_metadata->name(); - // Check if the plug-in or its group is enabled by policy. + // Check if the plugin or its group is enabled by policy. PolicyStatus plugin_status = PolicyStatusForPlugin(plugin.name); PolicyStatus group_status = PolicyStatusForPlugin(group_name); if (plugin_status == POLICY_ENABLED || group_status == POLICY_ENABLED) return true; - // Check if the plug-in or its group is disabled by policy. + // Check if the plugin or its group is disabled by policy. if (plugin_status == POLICY_DISABLED || group_status == POLICY_DISABLED) return false; @@ -257,12 +257,12 @@ #endif base::AutoLock auto_lock(lock_); - // Check user preferences for the plug-in. + // Check user preferences for the plugin. bool plugin_enabled = false; if (plugin_state_.Get(plugin.path, &plugin_enabled)) return plugin_enabled; - // Check user preferences for the plug-in group. + // Check user preferences for the plugin group. std::map<base::string16, bool>::const_iterator group_it( plugin_group_state_.find(group_name)); if (group_it != plugin_group_state_.end()) @@ -563,7 +563,7 @@ group_names.insert(plugin_metadata->name()); } - // Add the plug-in groups. + // Add the plugin groups. for (std::set<base::string16>::const_iterator it = group_names.begin(); it != group_names.end(); ++it) { base::DictionaryValue* summary = new base::DictionaryValue();
diff --git a/chrome/browser/plugins/plugin_prefs.h b/chrome/browser/plugins/plugin_prefs.h index 7a797c0..d95db2d 100644 --- a/chrome/browser/plugins/plugin_prefs.h +++ b/chrome/browser/plugins/plugin_prefs.h
@@ -27,7 +27,7 @@ struct WebPluginInfo; } -// This class stores information about whether a plug-in or a plug-in group is +// This class stores information about whether a plugin or a plugin group is // enabled or disabled. // Except where otherwise noted, it can be used on every thread. class PluginPrefs : public RefcountedKeyedService { @@ -57,15 +57,15 @@ // Enable or disable a plugin group. void EnablePluginGroup(bool enable, const base::string16& group_name); - // Enables or disables a specific plug-in file, if possible. - // If the plug-in state can't be changed (because of a policy for example) - // then enabling/disabling the plug-in is ignored and |callback| is run - // with 'false' passed to it. Otherwise the plug-in state is changed + // Enables or disables a specific plugin file, if possible. + // If the plugin state can't be changed (because of a policy for example) + // then enabling/disabling the plugin is ignored and |callback| is run + // with 'false' passed to it. Otherwise the plugin state is changed // and |callback| is run with 'true' passed to it. void EnablePlugin(bool enable, const base::FilePath& file_path, const base::Callback<void(bool)>& callback); - // Returns whether there is a policy enabling or disabling plug-ins of the + // Returns whether there is a policy enabling or disabling plugins of the // given name. PolicyStatus PolicyStatusForPlugin(const base::string16& name) const; @@ -107,7 +107,7 @@ void UpdatePatternsAndNotify(std::set<base::string16>* patterns, const std::string& pref_name); - // Allows unit tests to directly set enforced plug-in patterns. + // Allows unit tests to directly set enforced plugin patterns. void SetPolicyEnforcedPluginPatterns( const std::set<base::string16>& disabled_patterns, const std::set<base::string16>& disabled_exception_patterns,
diff --git a/chrome/browser/plugins/plugin_status_pref_setter.h b/chrome/browser/plugins/plugin_status_pref_setter.h index ee7c975..ee08c2e3 100644 --- a/chrome/browser/plugins/plugin_status_pref_setter.h +++ b/chrome/browser/plugins/plugin_status_pref_setter.h
@@ -33,7 +33,7 @@ // Binds the preferences in the profile's PrefService, notifying |observer| if // any value changes. // This asynchronously calls the PluginService to get the list of installed - // plug-ins. + // plugins. void Init(Profile* profile, const BooleanPrefMember::NamedChangeCallback& observer);
diff --git a/chrome/browser/plugins/plugins_resource_service.h b/chrome/browser/plugins/plugins_resource_service.h index eb4074d1..6a123a3 100644 --- a/chrome/browser/plugins/plugins_resource_service.h +++ b/chrome/browser/plugins/plugins_resource_service.h
@@ -10,7 +10,7 @@ class PrefService; class PrefRegistrySimple; -// This resource service periodically fetches plug-in metadata +// This resource service periodically fetches plugin metadata // from a remote server and updates local state and PluginFinder. class PluginsResourceService : public ChromeWebResourceService { public:
diff --git a/chrome/browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc b/chrome/browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc index fff3e38..4f1db25 100644 --- a/chrome/browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc +++ b/chrome/browser/printing/cloud_print/test/cloud_print_proxy_process_browsertest.cc
@@ -216,6 +216,11 @@ base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); content::RegisterPathProvider(); + base::FilePath user_data_dir = + command_line->GetSwitchValuePath(switches::kUserDataDir); + CHECK(!user_data_dir.empty()); + CHECK(test_launcher_utils::OverrideUserDataDir(user_data_dir)); + #if defined(OS_MACOSX) if (!command_line->HasSwitch(kTestExecutablePath)) return kMissingSwitch; @@ -226,10 +231,6 @@ Launchd::ScopedInstance use_mock(&mock_launchd); #endif - base::FilePath user_data_dir = - command_line->GetSwitchValuePath(switches::kUserDataDir); - CHECK(!user_data_dir.empty()); - CHECK(test_launcher_utils::OverrideUserDataDir(user_data_dir)); ServiceProcessState* state(new ServiceProcessState); bool service_process_state_initialized = state->Initialize(); @@ -390,19 +391,6 @@ content::SetBrowserClientForTesting(browser_content_client_.get()); TestingBrowserProcess::CreateInstance(); -#if defined(OS_MACOSX) - EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); - EXPECT_TRUE(MockLaunchd::MakeABundle(temp_dir_.path(), - "CloudPrintProxyTest", - &bundle_path_, - &executable_path_)); - mock_launchd_.reset(new MockLaunchd(executable_path_, - base::MessageLoopForUI::current(), - true, false)); - scoped_launchd_instance_.reset( - new Launchd::ScopedInstance(mock_launchd_.get())); -#endif - // Ensure test does not use the standard profile directory. This is copied // from InProcessBrowserTest::SetUp(). These tests require a more complex // process startup so they are unable to just inherit from @@ -420,6 +408,19 @@ command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir); } ASSERT_TRUE(test_launcher_utils::OverrideUserDataDir(user_data_dir)); + +#if defined(OS_MACOSX) + EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); + EXPECT_TRUE(MockLaunchd::MakeABundle(temp_dir_.path(), + "CloudPrintProxyTest", + &bundle_path_, + &executable_path_)); + mock_launchd_.reset(new MockLaunchd(executable_path_, + base::MessageLoopForUI::current(), + true, false)); + scoped_launchd_instance_.reset( + new Launchd::ScopedInstance(mock_launchd_.get())); +#endif } void CloudPrintProxyPolicyStartupTest::TearDown() {
diff --git a/chrome/browser/profiles/profile_io_data.cc b/chrome/browser/profiles/profile_io_data.cc index 9f0443e..8457344 100644 --- a/chrome/browser/profiles/profile_io_data.cc +++ b/chrome/browser/profiles/profile_io_data.cc
@@ -473,22 +473,6 @@ prefs::kGoogleServicesUserAccountId, pref_service); google_services_user_account_id_.MoveToThread(io_message_loop_proxy); - google_services_username_.Init( - prefs::kGoogleServicesUsername, pref_service); - google_services_username_.MoveToThread(io_message_loop_proxy); - - google_services_username_pattern_.Init( - prefs::kGoogleServicesUsernamePattern, local_state_pref_service); - google_services_username_pattern_.MoveToThread(io_message_loop_proxy); - - reverse_autologin_enabled_.Init( - prefs::kReverseAutologinEnabled, pref_service); - reverse_autologin_enabled_.MoveToThread(io_message_loop_proxy); - - one_click_signin_rejected_email_list_.Init( - prefs::kReverseAutologinRejectedEmailList, pref_service); - one_click_signin_rejected_email_list_.MoveToThread(io_message_loop_proxy); - sync_disabled_.Init(sync_driver::prefs::kSyncManaged, pref_service); sync_disabled_.MoveToThread(io_message_loop_proxy); @@ -1246,10 +1230,6 @@ signin_names_->ReleaseResourcesOnUIThread(); google_services_user_account_id_.Destroy(); - google_services_username_.Destroy(); - google_services_username_pattern_.Destroy(); - reverse_autologin_enabled_.Destroy(); - one_click_signin_rejected_email_list_.Destroy(); enable_referrers_.Destroy(); enable_do_not_track_.Destroy(); force_safesearch_.Destroy();
diff --git a/chrome/browser/profiles/profile_io_data.h b/chrome/browser/profiles/profile_io_data.h index 1cbb9be..c1268a2 100644 --- a/chrome/browser/profiles/profile_io_data.h +++ b/chrome/browser/profiles/profile_io_data.h
@@ -148,30 +148,6 @@ return &google_services_user_account_id_; } - StringPrefMember* google_services_username() const { - return &google_services_username_; - } - - StringPrefMember* google_services_username_pattern() const { - return &google_services_username_pattern_; - } - - BooleanPrefMember* reverse_autologin_enabled() const { - return &reverse_autologin_enabled_; - } - - const std::string& reverse_autologin_pending_email() const { - return reverse_autologin_pending_email_; - } - - void set_reverse_autologin_pending_email(const std::string& email) { - reverse_autologin_pending_email_ = email; - } - - StringListPrefMember* one_click_signin_rejected_email_list() const { - return &one_click_signin_rejected_email_list_; - } - net::URLRequestContext* extensions_request_context() const { return extensions_request_context_.get(); } @@ -522,15 +498,6 @@ client_cert_store_factory_; mutable StringPrefMember google_services_user_account_id_; - mutable StringPrefMember google_services_username_; - mutable StringPrefMember google_services_username_pattern_; - mutable BooleanPrefMember reverse_autologin_enabled_; - - // During the reverse autologin request chain processing, this member saves - // the email of the google account that is being signed into. - std::string reverse_autologin_pending_email_; - - mutable StringListPrefMember one_click_signin_rejected_email_list_; mutable scoped_refptr<MediaDeviceIDSalt> media_device_id_salt_;
diff --git a/chrome/browser/resources/about_memory.html b/chrome/browser/resources/about_memory.html index 4636232..6b670a19 100644 --- a/chrome/browser/resources/about_memory.html +++ b/chrome/browser/resources/about_memory.html
@@ -178,7 +178,7 @@ not just Chrome. </div> <div class="otherbrowsers" jsdisplay="browsers.length > 1"> - Note: Chrome includes memory used by plug-ins, other browsers may not. + Note: Chrome includes memory used by plugins, other browsers may not. </div> <br><br><br>
diff --git a/chrome/browser/resources/about_memory_linux.html b/chrome/browser/resources/about_memory_linux.html index a204a02..63a17128 100644 --- a/chrome/browser/resources/about_memory_linux.html +++ b/chrome/browser/resources/about_memory_linux.html
@@ -103,7 +103,7 @@ </div> <div class="otherbrowsers" jsdisplay="show_other_browsers && browsers.length > 1"> - Note: Chrome includes memory used by plug-ins, other browsers may not. + Note: Chrome includes memory used by plugins, other browsers may not. </div> <br><br><br>
diff --git a/chrome/browser/resources/about_memory_mac.html b/chrome/browser/resources/about_memory_mac.html index 58f698e..6662ee0 100644 --- a/chrome/browser/resources/about_memory_mac.html +++ b/chrome/browser/resources/about_memory_mac.html
@@ -136,7 +136,7 @@ not just Chrome. </div> <div class="otherbrowsers" jsdisplay="browsers.length > 1"> - Note: Chrome includes memory used by plug-ins, other browsers may not. + Note: Chrome includes memory used by plugins, other browsers may not. </div> <div class="otherbrowsers"> (Bug: We seriously overcount our own memory usage: <a href="http://crbug.com/25454">Issue 25454</a>.)
diff --git a/chrome/browser/resources/chromeos/about_os_credits.html b/chrome/browser/resources/chromeos/about_os_credits.html index 578d476..efac743b 100644 --- a/chrome/browser/resources/chromeos/about_os_credits.html +++ b/chrome/browser/resources/chromeos/about_os_credits.html
@@ -23196,7 +23196,7 @@ Questions, comments, and bug reports should be directed to the `distutils-sig mailing list`_. If you have written (or know of) any tutorials, documentation, - plug-ins, or other resources for setuptools users, please let us know about + plugins, or other resources for setuptools users, please let us know about them there, so this reference list can be updated. If you have working, *tested* patches to correct problems or add features, you may submit them to the `setuptools bug tracker`_. @@ -23232,10 +23232,10 @@ * Phillip J. Eby is the principal author and maintainer of setuptools, and first proposed the idea of an importable binary distribution format for - Python application plug-ins. + Python application plugins. * Significant parts of the implementation of setuptools were funded by the Open - Source Applications Foundation, to provide a plug-in infrastructure for the + Source Applications Foundation, to provide a plugin infrastructure for the Chandler PIM application. In addition, many OSAF staffers (such as Mike "Code Bear" Taylor) contributed their time and stress as guinea pigs for the use of eggs and setuptools, even before eggs were "cool". (Thanks, guys!) @@ -24234,7 +24234,7 @@ Questions, comments, and bug reports should be directed to the `distutils-sig mailing list`_. If you have written (or know of) any tutorials, documentation, - plug-ins, or other resources for setuptools users, please let us know about + plugins, or other resources for setuptools users, please let us know about them there, so this reference list can be updated. If you have working, *tested* patches to correct problems or add features, you may submit them to the `setuptools bug tracker`_. @@ -24270,10 +24270,10 @@ * Phillip J. Eby is the principal author and maintainer of setuptools, and first proposed the idea of an importable binary distribution format for - Python application plug-ins. + Python application plugins. * Significant parts of the implementation of setuptools were funded by the Open - Source Applications Foundation, to provide a plug-in infrastructure for the + Source Applications Foundation, to provide a plugin infrastructure for the Chandler PIM application. In addition, many OSAF staffers (such as Mike "Code Bear" Taylor) contributed their time and stress as guinea pigs for the use of eggs and setuptools, even before eggs were "cool". (Thanks, guys!)
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/braille_table_test.extjs b/chrome/browser/resources/chromeos/chromevox/braille/braille_table_test.extjs index f629941..6adae04 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/braille_table_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/braille/braille_table_test.extjs
@@ -13,7 +13,9 @@ * @constructor * @extends {ChromeVoxE2ETest} */ -function CvoxBrailleTableTest() {} +function CvoxBrailleTableTest() { + ChromeVoxE2ETest.call(this); +} CvoxBrailleTableTest.prototype = { __proto__: ChromeVoxE2ETest.prototype, @@ -24,7 +26,7 @@ * NOTE: This will need to be adjusted when more tables are added. */ TEST_F('CvoxBrailleTableTest', 'testGetAllAndValidate', function() { - cvox.BrailleTable.getAll(function(tables) { + cvox.BrailleTable.getAll(this.newCallback(function(tables) { expectEquals(68, tables.length); assertNotNullNorUndefined( cvox.BrailleTable.forId(tables, 'en-US-g1'), @@ -34,13 +36,12 @@ expectTrue(table.dots === '6' || table.dots === '8'); expectTrue(cvox.BrailleTable.getDisplayName(table).length > 0); } - testDone(); - }); + })); }); /** Tests getDisplayName for some specific representative cases. */ TEST_F('CvoxBrailleTableTest', 'testGetDisplayName', function() { - cvox.BrailleTable.getAll(function(tables) { + cvox.BrailleTable.getAll(this.newCallback(function(tables) { var table = cvox.BrailleTable.forId(tables, 'bg-comp8'); expectEquals('Bulgarian', cvox.BrailleTable.getDisplayName(table)); table = cvox.BrailleTable.forId(tables, 'ar-g1'); @@ -48,15 +49,14 @@ table = cvox.BrailleTable.forId(tables, 'en-UEB-g1'); expectEquals('English (UEB), Grade 1', cvox.BrailleTable.getDisplayName(table)); - testDone(); - }); + })); }); /** * Tests the getUncontracted function. */ TEST_F('CvoxBrailleTableTest', 'testGetUncontracted', function() { - cvox.BrailleTable.getAll(function(tables) { + cvox.BrailleTable.getAll(this.newCallback(function(tables) { function expectUncontracted(uncontractedId, idToCheck) { var checkedTable = cvox.BrailleTable.forId(tables, idToCheck); var uncontractedTable = cvox.BrailleTable.getUncontracted( @@ -70,6 +70,5 @@ expectUncontracted('sv-comp8', 'sv-g1'); expectUncontracted('ar-g1', 'ar-g1'); expectUncontracted('de-comp8', 'de-CH-g2'); - testDone(); - }); + })); });
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/braille_translator_manager_test.extjs b/chrome/browser/resources/chromeos/chromevox/braille/braille_translator_manager_test.extjs index 7e7ef9f..24a414f9 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/braille_translator_manager_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/braille/braille_translator_manager_test.extjs
@@ -13,7 +13,9 @@ * @constructor * @extends {ChromeVoxE2ETest} */ -function CvoxBrailleTranslatorManagerTest() {} +function CvoxBrailleTranslatorManagerTest() { + ChromeVoxE2ETest.call(this); +} CvoxBrailleTranslatorManagerTest.prototype = { __proto__: ChromeVoxE2ETest.prototype, @@ -29,8 +31,7 @@ }, addChangeListener: function(callback) { - return this.manager.addChangeListener(this.continueTest( - WhenTestDone.ASSERT, callback)); + return this.manager.addChangeListener(callOnce(this.newCallback(callback))); }, }; @@ -71,8 +72,8 @@ var called = false; return function() { if (!called) { - callback.apply(null, arguments); called = true; + callback.apply(null, arguments); } }; } @@ -85,34 +86,31 @@ assertNotEquals(null, this.manager.getExpandingTranslator()); assertEquals('en-US-comp8', this.manager.getDefaultTranslator().table.id); assertEquals(null, this.manager.getUncontractedTranslator()); - testDone(); - }.bind(this)); + }); }); TEST_F('CvoxBrailleTranslatorManagerTest', 'testRefreshWithoutChange', function() { - this.addChangeListener(callOnce(function() { + this.addChangeListener(function() { assertNotEquals(null, this.manager.getExpandingTranslator()); // This works because the fake liblouis is actually not asynchonous. - this.addChangeListener(function() { - throw Error('Should not be called.'); + this.manager.addChangeListener(function() { + assertNotReached('Refresh should not be called without a change.'); }); this.manager.refresh(); - testDone(); - }.bind(this))); + }); }); TEST_F('CvoxBrailleTranslatorManagerTest', 'testRefreshWithChange', function() { - this.addChangeListener(callOnce(function() { + this.addChangeListener(function() { assertNotEquals(null, this.manager.getExpandingTranslator()); this.addChangeListener(function() { assertEquals('en-UEB-g2', this.manager.getDefaultTranslator().table.id); assertEquals('en-US-comp8', this.manager.getUncontractedTranslator().table.id); - testDone(); - }.bind(this)); + }); localStorage['brailleTable'] = 'en-UEB-g2'; this.manager.refresh(); - }.bind(this))); + }); });
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/liblouis.js b/chrome/browser/resources/chromeos/chromevox/braille/liblouis.js index efa3e11e..2d66b84 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/liblouis.js +++ b/chrome/browser/resources/chromeos/chromevox/braille/liblouis.js
@@ -235,6 +235,7 @@ cvox.LibLouis.Translator.prototype.translate = function(text, callback) { if (!this.instance_.isAttached()) { callback(null /*cells*/, null /*textToBraille*/, null /*brailleToText*/); + return; } var message = { 'table_names': this.tableNames_, 'text': text }; this.instance_.rpc_('Translate', message, function(reply) { @@ -268,6 +269,7 @@ function(cells, callback) { if (!this.instance_.isAttached()) { callback(null /*text*/); + return; } if (cells.byteLength == 0) { // liblouis doesn't handle empty input, so handle that trivially
diff --git a/chrome/browser/resources/chromeos/chromevox/braille/liblouis_test.extjs b/chrome/browser/resources/chromeos/chromevox/braille/liblouis_test.extjs index 66491f4..38d1e4b 100644 --- a/chrome/browser/resources/chromeos/chromevox/braille/liblouis_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/braille/liblouis_test.extjs
@@ -15,7 +15,9 @@ * @constructor * @extends {ChromeVoxE2ETest} */ -function CvoxLibLouisTest() {} +function CvoxLibLouisTest() { + ChromeVoxE2ETest.call(this); +} CvoxLibLouisTest.prototype = { __proto__: ChromeVoxE2ETest.prototype, @@ -33,8 +35,7 @@ }, withTranslator: function(liblouis, tableNames, callback) { - liblouis.getTranslator(tableNames, - this.continueTest(WhenTestDone.ASSERT, callback)); + liblouis.getTranslator(tableNames, this.newCallback(callback)); }, }; @@ -49,7 +50,7 @@ TEST_F('CvoxLibLouisTest', 'checkAllTables', function() { var liblouis = this.createAndAttachLiblouis(); - var continuation = this.continueTest(WhenTestDone.ASSERT, function(tables) { + cvox.BrailleTable.getAll(this.newCallback(function(tables) { var i = 0; var checkNextTable = function() { var table = tables[i++]; @@ -59,26 +60,21 @@ 'Table ' + table + ' should be valid'); checkNextTable(); }); - } else { - testDone(); } }.bind(this); checkNextTable(); - }.bind(this)); - cvox.BrailleTable.getAll(continuation); + }.bind(this))); }); TEST_F('CvoxLibLouisTest', 'testTranslateComputerBraille', function() { var liblouis = this.createAndAttachLiblouis(); this.withTranslator(liblouis, 'en-us-comp8.ctb', function(translator) { - var continuation = this.continueTest( - WhenTestDone.ALWAYS, + translator.translate('Hello!', this.newCallback( function(cells, textToBraille, brailleToText) { assertEqualsUint8Array([0x53, 0x11, 0x07, 0x07, 0x15, 0x2e], cells); assertEqualsJSON([0, 1, 2, 3, 4, 5], textToBraille); assertEqualsJSON([0, 1, 2, 3, 4, 5], brailleToText); - }); - translator.translate('Hello!', continuation); + })); }); }); @@ -86,10 +82,9 @@ var liblouis = this.createAndAttachLiblouis(); this.withTranslator(liblouis, 'en-us-comp8.ctb', function(translator) { var cells = new Uint8Array([0x53, 0x11, 0x07, 0x07, 0x15, 0x2e]); - var continuation = this.continueTest(WhenTestDone.ALWAYS, function(text) { + translator.backTranslate(cells.buffer, this.newCallback(function(text) { assertEquals('Hello!', text); - }); - translator.backTranslate(cells.buffer, continuation); + })); }); }); @@ -97,13 +92,12 @@ var liblouis = this.createAndAttachLiblouis(); // This is one of the moderately large tables. this.withTranslator(liblouis, 'de-de-g2.ctb', function(translator) { - var continuation = this.continueTest( - WhenTestDone.ALWAYS, function(cells, textToBraille, brailleToText) { + translator.translate('München', this.newCallback( + function(cells, textToBraille, brailleToText) { assertEqualsUint8Array([0x0d, 0x33, 0x1d, 0x39, 0x09], cells); assertEqualsJSON([0, 1, 2, 3, 3, 4, 4], textToBraille); assertEqualsJSON([0, 1, 2, 3, 5], brailleToText); - }); - translator.translate('München', continuation); + })); }); }); @@ -111,21 +105,21 @@ var liblouis = this.createAndAttachLiblouis(); this.withTranslator(liblouis, 'de-de-comp8.ctb', function(translator) { var cells = new Uint8Array([0xb3]); - var continuation = this.continueTest(WhenTestDone.ALWAYS, function(text) { + translator.backTranslate(cells.buffer, this.newCallback(function(text) { assertEquals('ü', text); - }); - translator.backTranslate(cells.buffer, continuation); + })); }); }); TEST_F('CvoxLibLouisTest', 'testBackTranslateEmptyCells', function() { var liblouis = this.createAndAttachLiblouis(); this.withTranslator(liblouis, 'de-de-comp8.ctb', function(translator) { - var continuation = this.continueTest(WhenTestDone.ALWAYS, function(text) { - assertNotEquals(null, text); - assertEquals(0, text.length); - }); - translator.backTranslate(new Uint8Array().buffer, continuation); + translator.backTranslate( + new Uint8Array().buffer, + this.newCallback(function(text) { + assertNotEquals(null, text); + assertEquals(0, text.length); + })); }); }); @@ -134,7 +128,6 @@ assertFalse(liblouis.isAttached()); this.withTranslator(liblouis, 'en-us-comp8.ctb', function(translator) { assertEquals(null, translator); - testDone(); }); }); @@ -142,7 +135,6 @@ var liblouis = this.createAndAttachLiblouis(); this.withTranslator(liblouis, 'nonexistant-table', function(translator) { assertEquals(null, translator); - testDone(); }); }); @@ -150,28 +142,27 @@ var liblouis = this.createAndAttachLiblouis(); this.withTranslator(liblouis, 'de-de-comp8.ctb', function(translator) { liblouis.detach(); - var continuation = this.continueTest( - WhenTestDone.ALWAYS, + translator.translate('Hamburg', this.newCallback( function(cells, textToBraille, brailleToText) { assertEquals(null, cells); assertEquals(null, textToBraille); assertEquals(null, brailleToText); - }); - translator.translate('Hamburg', continuation); + })); }); }); TEST_F('CvoxLibLouisTest', 'testDetachWithOutstandingCallbacks', function() { var liblouis = this.createAndAttachLiblouis(); this.withTranslator(liblouis, 'de-de-comp8.ctb', function(translator) { - var continuation = this.continueTest( - WhenTestDone.ALWAYS, + var called = false; + translator.translate('Berlin', this.newCallback( function(cells, textToBraille, brailleToText) { assertEquals(null, cells); assertEquals(null, textToBraille); assertEquals(null, brailleToText); - }); - translator.translate('Berlin', continuation); + called = true; + })); + assertFalse(called); liblouis.detach(); }); });
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher_test.unitjs b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher_test.unitjs index ce462921..88bcc51 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher_test.unitjs +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/event_watcher_test.unitjs
@@ -10,7 +10,9 @@ * @constructor * @extends {ChromeVoxUnitTestBase} */ -function CvoxEventWatcherUnitTest() {} +function CvoxEventWatcherUnitTest() { + ChromeVoxUnitTestBase.call(this); +} CvoxEventWatcherUnitTest.prototype = { __proto__: ChromeVoxUnitTestBase.prototype, @@ -85,8 +87,7 @@ TEST_F('CvoxEventWatcherUnitTest', 'ButtonFocusFeedback', function() { this.loadHtml('<div> <button id="alpha">Alpha</button> </div>'); this.setFocus('alpha'); - this.waitForCalm(this.assertSpoken, 'Alpha Button') - .waitForCalm(testDone); + this.waitForCalm(this.assertSpoken, 'Alpha Button'); }); /** @@ -106,8 +107,7 @@ .waitForCalm(this.setFocus, 'l1') .waitForCalm(this.assertSpoken, '1 Internal link 2 Internal link 3 Internal link ' + - '2 Internal link 1 Internal link') - .waitForCalm(testDone); + '2 Internal link 1 Internal link'); }); /** @@ -120,8 +120,7 @@ '</div>'); this.setFocus('mytext'); - this.waitForCalm(this.assertSpoken, 'Label Value Edit text') - .waitForCalm(testDone); + this.waitForCalm(this.assertSpoken, 'Label Value Edit text'); }); /** @@ -134,8 +133,7 @@ '</div>'); this.setFocus('mytext'); - this.waitForCalm(this.assertSpoken, 'Label This is editable Edit text') - .waitForCalm(testDone); + this.waitForCalm(this.assertSpoken, 'Label This is editable Edit text'); }); /** @@ -162,8 +160,7 @@ }) .waitForCalm(this.assertSpoken, 'OK Button') .waitForCalm(this.setFocus, 'show') - .waitForCalm(this.assertSpoken, 'Exited dialog. Show Button') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'Exited dialog. Show Button'); }); /** @@ -182,8 +179,7 @@ this.waitForCalm(this.assertSpoken, 'Entered dialog ' + 'Are you sure you want to install Windows? Yes Button No Button ' + - 'No Button') - .waitForCalm(testDone); + 'No Button'); }); /** @@ -214,8 +210,7 @@ .queue('Yes') .queue('Button')) .waitForCalm(this.setFocus, 'outside') - .waitForCalm(this.assertSpoken, 'Exited dialog. Outside Button') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'Exited dialog. Outside Button'); }); /** @@ -246,8 +241,7 @@ .waitForCalm(this.assertSpoken, 'invalid after click') .waitForCalm(displayNone) .waitForCalm(this.userCommand, 'forward') - .waitForCalm(this.assertSpoken, 'valid text after') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'valid text after'); }); /** @@ -278,8 +272,7 @@ { 'target': listbox, 'type': 'keydown' })); }) - .waitForCalm(this.assertSpoken, 'Yellow 2 of 3') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'Yellow 2 of 3'); }); /** @@ -302,8 +295,7 @@ this.waitForCalm(this.assertSpoken, 'List box Yellow 2 of 3') .waitForCalm(this.setFocus, 'red') - .waitForCalm(this.assertSpoken, 'Red Selected 1 of 3') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'Red Selected 1 of 3'); }); /** @@ -333,8 +325,7 @@ .waitForCalm(this.setFocus, 'green') .waitForCalm(this.assertSpoken, 'Green 3 of 4') .waitForCalm(this.userCommand, 'forward') - .waitForCalm(this.assertSpoken, 'Blue 4 of 4') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'Blue 4 of 4'); }); /** @@ -369,8 +360,7 @@ .queue('abc') .queue('Edit text') .flush('d') - .flush('e')) - .waitForCalm(testDone); + .flush('e')); }); /** @@ -403,8 +393,7 @@ input.setAttribute('aria-activedescendant', 'option1'); this.changeTextField(input, '', 0, 0, 40); // 'down' }) - .waitForCalm(this.assertSpoken, 'First pick 1 of 2') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'First pick 1 of 2'); }); /** @@ -438,8 +427,7 @@ input.setAttribute('aria-activedescendant', 'option1'); this.changeTextField(input, 'First pick', 9, 9, 40); // 'down' }) - .waitForCalm(this.assertSpoken, 'First pick') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'First pick'); }); /** @@ -482,8 +470,7 @@ .waitForCalm(setAreaCursor, 9) .waitForCalm(this.assertSpoken, 'Blank') .waitForCalm(setAreaCursor, 10) - .waitForCalm(this.assertSpoken, 'three') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'three'); }); TEST_F('CvoxEventWatcherUnitTest', 'ShouldWaitToProcess', function() { @@ -529,8 +516,7 @@ .waitForCalm(this.setFocus, 'button3') .waitForCalm(this.assertSpoken, '') .waitForCalm(this.setFocus, 'button4') - .waitForCalm(this.assertSpoken, 'Button 4 Button') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'Button 4 Button'); }); /** @@ -571,8 +557,7 @@ 'green Radio button selected green Radio button selected') .waitForCalm(performKeyDown, 'Left') // left arrow // Arrowed beyond beginning. Should be quiet. - .waitForCalm(this.assertSpoken, '') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, ''); }); /** @@ -635,8 +620,7 @@ this.waitForCalm(performKeyDown, 'Down') // down arrow .waitForCalm(performKeyUp, 'Down') // down arrow .waitForCalm(this.assertSpoken, - 'PM') - .waitForCalm(testDone); + 'PM'); }); /** @@ -696,8 +680,7 @@ .waitForCalm(performKeyDown, 'Down') // down arrow .waitForCalm(performKeyUp, 'Down') // down arrow .waitForCalm(this.assertSpoken, - '1998') - .waitForCalm(testDone); + '1998'); }); /** @@ -735,8 +718,7 @@ this.waitForCalm(keyupSpaceAndMarkPressed) .waitForCalm(this.assertSpoken, 'Pressed') .waitForCalm(keyupSpaceAndMarkNotPressed) - .waitForCalm(this.assertSpoken, 'Not pressed') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'Not pressed'); }); /** @@ -769,6 +751,5 @@ assertEquals('Exited dialog.', ulist[1]); assertEquals('Final focus', ulist[2]); assertEquals('Button', ulist[3]); - testDone(); }); });
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/live_regions_test.unitjs b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/live_regions_test.unitjs index 8f0e3df..ded94e0 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/live_regions_test.unitjs +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/live_regions_test.unitjs
@@ -10,7 +10,9 @@ * @constructor * @extends {ChromeVoxUnitTestBase} */ -function CvoxLiveRegionsUnitTest() {} +function CvoxLiveRegionsUnitTest() { + ChromeVoxUnitTestBase.call(this); +} CvoxLiveRegionsUnitTest.prototype = { __proto__: ChromeVoxUnitTestBase.prototype, @@ -42,7 +44,6 @@ this.waitForCalm(function() { assertEquals(0, cvox.ChromeVoxTester.getUtteranceList().length); - testDone(); }); }); @@ -59,7 +60,6 @@ var utterances = cvox.ChromeVoxTester.getUtteranceList(); assertEquals('Alpha', utterances[0]); assertEquals('Alert', utterances[1]); - testDone(); }); }); @@ -86,7 +86,6 @@ this.waitForCalm(function() { var utterances = cvox.ChromeVoxTester.getUtteranceList(); assertEquals('I just appeared!', utterances[0]); - testDone(); }); }); @@ -102,7 +101,6 @@ this.waitForCalm(function() { var utterances = cvox.ChromeVoxTester.getUtteranceList(); assertEquals('Beta', utterances[0]); - testDone(); }); }); @@ -122,7 +120,6 @@ this.waitForCalm(function() { var utterances = cvox.ChromeVoxTester.getUtteranceList(); assertEquals('Delta', utterances[utterances.length - 1]); - testDone(); }); }); }); @@ -156,7 +153,6 @@ var utterances = cvox.ChromeVoxTester.getUtteranceList(); assertEquals('Eric', utterances[utterances.length - 2]); assertEquals('Larry Sergey Eric', utterances[utterances.length - 1]); - testDone(); }); }); }); @@ -181,7 +177,6 @@ var utterances = cvox.ChromeVoxTester.getUtteranceList(); assertEquals(1, utterances.length); assertEquals('removed:, Jack', utterances[0]); - testDone(); }); }); @@ -203,7 +198,6 @@ this.waitForCalm(function() { var utterances = cvox.ChromeVoxTester.getUtteranceList(); assertEquals('Progress bar 2', utterances[utterances.length - 1]); - testDone(); }); }); @@ -251,8 +245,7 @@ .categoryFlush('Address') .queue('Edit text') .categoryFlush('Not a valid name!') - .queue('Alert')) - .waitForCalm(testDone); + .queue('Alert')); }); @@ -272,8 +265,7 @@ new cvox.SpokenListBuilder() .categoryFlush('Button To Focus') .queue('Button') - .categoryFlush('Live region text')) - .waitForCalm(testDone); + .categoryFlush('Live region text')); }); @@ -295,8 +287,7 @@ new cvox.SpokenListBuilder() .categoryFlush('Live region text') .categoryFlush('Button To Focus') - .queue('Button')) - .waitForCalm(testDone); + .queue('Button')); }); @@ -317,6 +308,5 @@ $('hidden').style.display = 'block'; this.waitForCalm(this.assertSpokenList, new cvox.SpokenListBuilder() - .categoryFlush('L1, L2')) - .waitForCalm(testDone); + .categoryFlush('L1, L2')); });
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_manager_test.unitjs b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_manager_test.unitjs index 3af5bd2..c2e4723 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_manager_test.unitjs +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/navigation_manager_test.unitjs
@@ -10,7 +10,9 @@ * @constructor * @extends {ChromeVoxUnitTestBase} */ -function CvoxNavigationManagerUnitTest() {} +function CvoxNavigationManagerUnitTest() { + ChromeVoxUnitTestBase.call(this); +} CvoxNavigationManagerUnitTest.prototype = { __proto__: ChromeVoxUnitTestBase.prototype, @@ -47,7 +49,7 @@ */ checkNavSequence: function(strategies, commandsAndExpectations) { if (strategies.length == 0) - testDone(); + return; var strategy = strategies.shift(); this.waitForCalm(cvox.ChromeVoxTester.setStrategy, strategy) @@ -322,7 +324,6 @@ this.waitForCalm(this.userCommand, 'backward'); this.waitForCalm(this.assertSpoken, 'Some text.'); - this.waitForCalm(testDone); }); @@ -1266,8 +1267,7 @@ .waitForCalm(cvox.ChromeVoxTester.syncToFirstNode) .waitForCalm(cvox.ChromeVoxTester.readFromHere) .waitForCalm(this.assertSpoken, - 'Before Some text. First Second Third Internal link After') - .waitForCalm(testDone); + 'Before Some text. First Second Third Internal link After'); }); @@ -1391,6 +1391,5 @@ this.waitForCalm(this.userCommand, 'forward') .waitForCalm(this.assertSpoken, 'Math a times x squared plus b times x plus c equals 0') .waitForCalm(this.userCommand, 'forward') - .waitForCalm(this.assertSpoken, 'Math square root of n cube') - .waitForCalm(testDone); + .waitForCalm(this.assertSpoken, 'Math square root of n cube'); });
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/pdf_processor.js b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/pdf_processor.js index b6ca6d1f..c0b11887 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/pdf_processor.js +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/pdf_processor.js
@@ -11,7 +11,7 @@ goog.require('cvox.QueueMode'); /** - * Process PDFs created with Chrome's built-in PDF plug-in, which has an + * Process PDFs created with Chrome's built-in PDF plugin, which has an * accessibility hook. */ cvox.PdfProcessor.processEmbeddedPdfs = function() {
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_commands_test.unitjs b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_commands_test.unitjs index cb122e6..8459a35 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_commands_test.unitjs +++ b/chrome/browser/resources/chromeos/chromevox/chromevox/injected/user_commands_test.unitjs
@@ -10,7 +10,9 @@ * @constructor * @extends {ChromeVoxUnitTestBase} */ -function CvoxUserCommandsUnitTest() {} +function CvoxUserCommandsUnitTest() { + ChromeVoxUnitTestBase.call(this); +} CvoxUserCommandsUnitTest.prototype = { __proto__: ChromeVoxUnitTestBase.prototype, @@ -57,7 +59,6 @@ var id = document.activeElement.nextSibling.id; assertEquals('foo', id); }); - this.waitForCalm(testDone); }); /**
diff --git a/chrome/browser/resources/chromeos/chromevox/chromevox_tests.gypi b/chrome/browser/resources/chromeos/chromevox/chromevox_tests.gypi index ee02218..1c4119a 100644 --- a/chrome/browser/resources/chromeos/chromevox/chromevox_tests.gypi +++ b/chrome/browser/resources/chromeos/chromevox/chromevox_tests.gypi
@@ -113,7 +113,9 @@ '<(mock_js)', '<(test_api_js)', '<(js2gtest)', + 'testing/callback_helper.js', 'testing/chromevox_e2e_test_base.js', + 'testing/chromevox_next_e2e_test_base.js', 'testing/assert_additions.js', ], 'outputs': [
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_util_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_util_test.extjs index 90d76a8..2c75b9f 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_util_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/automation_util_test.extjs
@@ -10,7 +10,9 @@ * @constructor * @extends {ChromeVoxE2ETestBase} */ -function AutomationUtilE2ETest() {} +function AutomationUtilE2ETest() { + ChromeVoxNextE2ETest.call(this); +} AutomationUtilE2ETest.prototype = { __proto__: ChromeVoxNextE2ETest.prototype, @@ -27,16 +29,14 @@ }; TEST_F('AutomationUtilE2ETest', 'GetAncestors', function() { - this.runWithLoadedTree(this.basicDoc, - function(root) { - var expectedLength = 1; - while (root) { - var ancestors = AutomationUtil.getAncestors(root); - assertEquals(expectedLength++, ancestors.length); - root = root.firstChild; - } - testDone(); - }.bind(this)); + this.runWithLoadedTree(this.basicDoc, function(root) { + var expectedLength = 1; + while (root) { + var ancestors = AutomationUtil.getAncestors(root); + assertEquals(expectedLength++, ancestors.length); + root = root.firstChild; + } + }); }); TEST_F('AutomationUtilE2ETest', 'GetUniqueAncestors', function() { @@ -78,8 +78,7 @@ assertEquals( 1, AutomationUtil.getUniqueAncestors(leftmost, leftmost).length); - testDone(); - }.bind(this)); + }); }); TEST_F('AutomationUtilE2ETest', 'GetDirection', function() { @@ -99,6 +98,5 @@ assertEquals(Dir.BACKWARD, AutomationUtil.getDirection(right, left)); assertEquals(Dir.FORWARD, AutomationUtil.getDirection(left, right)); - testDone(); - }.bind(this)); + }); });
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs index 9c4b4356..0d336cb5 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/background_test.extjs
@@ -12,7 +12,9 @@ * @constructor * @extends {ChromeVoxNextE2ETest} */ -function BackgroundTest() {} +function BackgroundTest() { + ChromeVoxNextE2ETest.call(this); +} BackgroundTest.prototype = { __proto__: ChromeVoxNextE2ETest.prototype, @@ -83,16 +85,16 @@ return null; } - chrome.automation.getDesktop(function(root) { + chrome.automation.getDesktop(this.newCallback(function(root) { var testButton = findStatusTray(root); - cvox.ChromeVox.tts.expectSpeech('Status tray', testDone); + cvox.ChromeVox.tts.expectSpeech('Status tray', this.newCallback()); testButton.focus(); - }); + })); }); /** Tests feedback once a page loads. */ TEST_F('BackgroundTest', 'MANUAL_InitialFeedback', function() { - cvox.ChromeVox.tts.expectSpeech('start', testDone); + cvox.ChromeVox.tts.expectSpeech('start', this.newCallback()); this.runWithTab(function() {/*! <p>start @@ -103,74 +105,73 @@ /** Tests consistency of navigating forward and backward. */ TEST_F('BackgroundTest', 'MANUAL_ForwardBackwardNavigation', function() { this.runWithLoadedTree(this.linksAndHeadingsDoc, function() { - var doCmd = this.doCmd.bind(this); - var expectAfter = - cvox.ChromeVox.tts.expectSpeechAfter.bind(cvox.ChromeVox.tts); + var doCmd = this.doCmd.bind(this); + var expectAfter = + cvox.ChromeVox.tts.expectSpeechAfter.bind(cvox.ChromeVox.tts); - expectAfter('alpha', doCmd('nextLink')); - expectAfter('beta', doCmd('nextLink')); - expectAfter('delta', doCmd('nextLink')); - expectAfter('beta', doCmd('previousLink')); + expectAfter('alpha', doCmd('nextLink')); + expectAfter('beta', doCmd('nextLink')); + expectAfter('delta', doCmd('nextLink')); + expectAfter('beta', doCmd('previousLink')); - expectAfter('charlie', doCmd('nextHeading')); - expectAfter('foxtraut', doCmd('nextHeading')); - expectAfter('charlie', doCmd('previousHeading')); + expectAfter('charlie', doCmd('nextHeading')); + expectAfter('foxtraut', doCmd('nextHeading')); + expectAfter('charlie', doCmd('previousHeading')); - expectAfter('delta', doCmd('nextElement')); - expectAfter('echo', doCmd('nextElement')); - expectAfter('foxtraut', doCmd('nextElement')); - expectAfter('end', doCmd('nextElement')); - expectAfter('foxtraut', doCmd('previousElement')); - expectAfter('end of test', doCmd('nextLine')); + expectAfter('delta', doCmd('nextElement')); + expectAfter('echo', doCmd('nextElement')); + expectAfter('foxtraut', doCmd('nextElement')); + expectAfter('end', doCmd('nextElement')); + expectAfter('foxtraut', doCmd('previousElement')); + expectAfter('end of test', doCmd('nextLine')); - expectAfter('start', doCmd('goToBeginning')); - expectAfter('of test', doCmd('goToEnd')); + expectAfter('start', doCmd('goToBeginning')); + expectAfter('of test', doCmd('goToEnd')); - cvox.ChromeVox.tts.finishExpectations(); - }.bind(this) - ); + cvox.ChromeVox.tts.finishExpectations(this.newCallback()); + }); }); TEST_F('BackgroundTest', 'MANUAL_CaretNavigation', function() { this.runWithLoadedTree(this.linksAndHeadingsDoc, function() { - var doCmd = this.doCmd.bind(this); - var expectAfter = - cvox.ChromeVox.tts.expectSpeechAfter.bind(cvox.ChromeVox.tts); + var doCmd = this.doCmd.bind(this); + var expectAfter = + cvox.ChromeVox.tts.expectSpeechAfter.bind(cvox.ChromeVox.tts); - expectAfter('t', doCmd('nextCharacter'), true); - expectAfter('a', doCmd('nextCharacter'), true); - expectAfter('Link alpha', doCmd('nextWord'), true); - expectAfter('Link beta', doCmd('nextWord'), true); - expectAfter('Heading charlie', doCmd('nextWord'), true); - expectAfter('Link delta', doCmd('nextLine'), true); - expectAfter('Link echo', doCmd('nextLine'), true); - expectAfter('Heading foxtraut', doCmd('nextLine'), true); - expectAfter( - 'end of test', doCmd('nextLine'), true); - expectAfter('n', doCmd('nextCharacter'), true); - expectAfter('e', doCmd('previousCharacter'), true); - expectAfter('Heading t', doCmd('previousCharacter'), true); - expectAfter('foxtraut', doCmd('previousWord'), true); - expectAfter('Link echo', doCmd('previousWord'), true); - expectAfter('Link a', doCmd('previousCharacter'), true); - expectAfter('t', doCmd('previousCharacter'), true); - expectAfter('Link echo', doCmd('nextWord'), true); + expectAfter('t', doCmd('nextCharacter'), true); + expectAfter('a', doCmd('nextCharacter'), true); + expectAfter('Link alpha', doCmd('nextWord'), true); + expectAfter('Link beta', doCmd('nextWord'), true); + expectAfter('Heading charlie', doCmd('nextWord'), true); + expectAfter('Link delta', doCmd('nextLine'), true); + expectAfter('Link echo', doCmd('nextLine'), true); + expectAfter('Heading foxtraut', doCmd('nextLine'), true); + expectAfter( + 'end of test', doCmd('nextLine'), true); + expectAfter('n', doCmd('nextCharacter'), true); + expectAfter('e', doCmd('previousCharacter'), true); + expectAfter('Heading t', doCmd('previousCharacter'), true); + expectAfter('foxtraut', doCmd('previousWord'), true); + expectAfter('Link echo', doCmd('previousWord'), true); + expectAfter('Link a', doCmd('previousCharacter'), true); + expectAfter('t', doCmd('previousCharacter'), true); + expectAfter('Link echo', doCmd('nextWord'), true); - cvox.ChromeVox.tts.finishExpectations(); - }.bind(this)); + cvox.ChromeVox.tts.finishExpectations(this.newCallback()); + }); }); // Flaky: http://crbug.com/451362 TEST_F('BackgroundTest', 'DISABLED_SelectSingleBasic', function() { - this.runWithLoadedTree(this.formsDoc, function(tabId) { + this.runWithLoadedTree(this.formsDoc, function() { var sendDownToSelect = - this.sendKeyToElement.bind(this, tabId, 'Down', '#fruitSelect'); + this.sendKeyToElement.bind(this, undefined, 'Down', '#fruitSelect'); var expect = cvox.ChromeVox.tts.expectSpeech.bind(cvox.ChromeVox.tts); expect('apple Menu item 1 of 3 ', sendDownToSelect, true); expect('grape 2 of 3 ', sendDownToSelect, true); - expect('banana 3 of 3 ', testDone, true); - cvox.ChromeVox.tts.finishExpectations(); - }.bind(this)); + expect('banana 3 of 3 ', function() {}, true); + cvox.ChromeVox.tts.finishExpectations(this.newCallback()); + }); }); TEST_F('BackgroundTest', 'MANUAL_ContinuousRead', function() { @@ -179,7 +180,7 @@ cvox.ChromeVox.tts.expectSpeechAfter('start', this.doCmd('continuousRead')); cvox.ChromeVox.tts.expectSpeech('alpha Link'); cvox.ChromeVox.tts.expectSpeech('beta Link'); - cvox.ChromeVox.tts.expectSpeech('Heading charlie', testDone); - cvox.ChromeVox.tts.finishExpectations(); - }.bind(this)); + cvox.ChromeVox.tts.expectSpeech('Heading charlie', function() {}); + cvox.ChromeVox.tts.finishExpectations(this.newCallback()); + }); });
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors_test.extjs index 669c605..5f045757 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/cursors_test.extjs
@@ -10,7 +10,9 @@ * @constructor * @extends {ChromeVoxNextE2ETest} */ -function CursorsTest() {} +function CursorsTest() { + ChromeVoxNextE2ETest.call(this); +} CursorsTest.prototype = { __proto__: ChromeVoxNextE2ETest.prototype, @@ -107,13 +109,11 @@ if (!opt_testType || opt_testType == this.CURSOR) { var cursor = new cursors.Cursor(start, 0); this.cursorMoveAndAssert(cursor, moves); - testDone(); } else if (opt_testType == this.RANGE) { var range = new cursors.Range(cursor, cursor); this.rangeMoveAndAssert(range, moves); - testDone(); } - }.bind(this)); + }); }, simpleDoc: function() {/*!
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output_test.extjs b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output_test.extjs index c6238ea..443885c 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/output_test.extjs +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/output_test.extjs
@@ -10,7 +10,9 @@ * @constructor * @extends {ChromeVoxNextE2ETestBase} */ -function OutputE2ETest() {} +function OutputE2ETest() { + ChromeVoxNextE2ETest.call(this); +} OutputE2ETest.prototype = { __proto__: ChromeVoxNextE2ETest.prototype, @@ -33,6 +35,5 @@ {value: {}, start: 11, end: 15} ]}, o.getBuffer()); - testDone(); - }.bind(this)); + }); });
diff --git a/chrome/browser/resources/chromeos/chromevox/host/chrome/braille_integration_test.unitjs b/chrome/browser/resources/chromeos/chromevox/host/chrome/braille_integration_test.unitjs index 1ccbd06..ce91f82 100644 --- a/chrome/browser/resources/chromeos/chromevox/host/chrome/braille_integration_test.unitjs +++ b/chrome/browser/resources/chromeos/chromevox/host/chrome/braille_integration_test.unitjs
@@ -14,7 +14,9 @@ * @constructor * @extends {ChromeVoxUnitTestBase} */ -function CvoxBrailleIntegrationUnitTest() {} +function CvoxBrailleIntegrationUnitTest() { + ChromeVoxUnitTestBase.call(this); +} CvoxBrailleIntegrationUnitTest.prototype = { __proto__: ChromeVoxUnitTestBase.prototype, @@ -31,6 +33,9 @@ ], /** @override */ + isAsync: true, + + /** @override */ setUp: function() { this.displayManager = new FakeDisplayManager(); this.inputHandler = new FakeInputHandler(); @@ -63,6 +68,25 @@ sendCommand: function(command, content) { this.displayManager.commandListener(command, content); + }, + + /** + * Waits for {@code document} to gain focus, arranging to call + * {@code testDone} afterwards. + * @param {Function()} callback Called when focus is gained + */ + awaitDocumentFocused: function(callback) { + callback = this.newCallback(callback); + if (!document.hasFocus()) { + var listener = this.newCallback(function() { + assertTrue(document.hasFocus()); + window.removeEventListener('focus', listener); + callback(); + }); + window.addEventListener('focus', listener); + } else { + callback(); + } } }; @@ -144,6 +168,7 @@ TEST_F('CvoxBrailleIntegrationUnitTest', 'Write', function() { this.braille.write(this.content1); assertEqualsJSON(this.content1, this.displayManager.content); + testDone(); }); TEST_F('CvoxBrailleIntegrationUnitTest', 'WriteWithSpans', function() { @@ -159,73 +184,72 @@ this.braille.write(toSend); assertEqualsJSON(expected, this.displayManager.content); + testDone(); }); -// Disabled due to Linux ChromiumOS Tests (1) flakes; http://crbug.com/462294. -TEST_F('CvoxBrailleIntegrationUnitTest', 'DISABLED_CommandNoContent', - function() { +TEST_F('CvoxBrailleIntegrationUnitTest', 'CommandNoContent', function() { // Commands are only delivered to the content script if the window has focus. - window.focus(); - this.sendCommand(this.command1, null); - assertEqualsJSON(this.command1, this.lastCommand); - assertEquals(null, this.lastCommandContent); + this.awaitDocumentFocused(function() { + this.sendCommand(this.command1, null); + assertEqualsJSON(this.command1, this.lastCommand); + assertEquals(null, this.lastCommandContent); + }); }); -// Disabled due to Linux ChromiumOS Tests (1) flakes; http://crbug.com/462294. TEST_F('CvoxBrailleIntegrationUnitTest', - 'DISABLED_InterleavedWritesAndCommands', + 'InterleavedWritesAndCommands', function() { - window.focus(); - this.braille.write(this.content1); - this.sendCommand(this.command1, this.displayManager.content); - assertEqualsJSON(this.command1, this.lastCommand); - assertEqualsJSON(this.content1, this.lastCommandContent); + this.awaitDocumentFocused(function() { + this.braille.write(this.content1); + this.sendCommand(this.command1, this.displayManager.content); + assertEqualsJSON(this.command1, this.lastCommand); + assertEqualsJSON(this.content1, this.lastCommandContent); - var savedContent1 = this.displayManager.content; - this.braille.write(this.content2); - // Old content still on display. - this.sendCommand(this.command1, savedContent1); - assertEqualsJSON(this.command1, this.lastCommand); - assertEquals(null, this.lastCommandContent); - this.sendCommand(this.command2, this.displayManager.content); - assertEqualsJSON(this.command2, this.lastCommand); - assertEqualsJSON(this.content2, this.lastCommandContent); - + var savedContent1 = this.displayManager.content; + this.braille.write(this.content2); + // Old content still on display. + this.sendCommand(this.command1, savedContent1); + assertEqualsJSON(this.command1, this.lastCommand); + assertEquals(null, this.lastCommandContent); + this.sendCommand(this.command2, this.displayManager.content); + assertEqualsJSON(this.command2, this.lastCommand); + assertEqualsJSON(this.content2, this.lastCommandContent); + }); }); -// Disabled due to Linux ChromiumOS Tests (1) flakes; http://crbug.com/462294. -TEST_F('CvoxBrailleIntegrationUnitTest', 'DISABLED_CommandAfterBackgroundWrite', +TEST_F('CvoxBrailleIntegrationUnitTest', 'CommandAfterBackgroundWrite', function() { - window.focus(); - this.braille.write(this.content1); - this.sendCommand(this.command1, this.displayManager.content); - assertEqualsJSON(this.command1, this.lastCommand); - assertEqualsJSON(this.content1, this.lastCommandContent); + this.awaitDocumentFocused(function() { + this.braille.write(this.content1); + this.sendCommand(this.command1, this.displayManager.content); + assertEqualsJSON(this.command1, this.lastCommand); + assertEqualsJSON(this.content1, this.lastCommandContent); - this.brailleBackground.write(this.content2); - assertEqualsJSON(this.content2, this.displayManager.content); - this.sendCommand(this.command2, this.displayManager.content); - assertEqualsJSON(this.command2, this.lastCommand); - assertEquals(null, this.lastCommandContent); + this.brailleBackground.write(this.content2); + assertEqualsJSON(this.content2, this.displayManager.content); + this.sendCommand(this.command2, this.displayManager.content); + assertEqualsJSON(this.command2, this.lastCommand); + assertEquals(null, this.lastCommandContent); + }); }); -// Disabled due to Linux ChromiumOS Tests (1) flakes; http://crbug.com/462294. -TEST_F('CvoxBrailleIntegrationUnitTest', 'DISABLED_CommandAfterOtherTabWrite', +TEST_F('CvoxBrailleIntegrationUnitTest', 'CommandAfterOtherTabWrite', function() { - window.focus(); - // Ignore the listener of the braille from the second 'tab'. - cvox.ExtensionBridge.addMessageListener = function() {} - // Create another content script braille object, presumably from another - // tab. - var anotherBraille = new cvox.ChromeBraille(); - this.braille.write(this.content1); - this.sendCommand(this.command1, this.displayManager.content); - // Now, this other braille gets a different unique id. - cvox.ExtensionBridge.uniqueId = function() { return 2; } - anotherBraille.write(this.content2); - this.sendCommand(this.command2, this.displayManager.content); - // The first 'tab' still gets the command, but since the second 'tab's\ - // braille was on the display, it gets null content. - assertEqualsJSON(this.command2, this.lastCommand); - assertEquals(null, this.lastCommandContent); + this.awaitDocumentFocused(function() { + // Ignore the listener of the braille from the second 'tab'. + cvox.ExtensionBridge.addMessageListener = function() {} + // Create another content script braille object, presumably from another + // tab. + var anotherBraille = new cvox.ChromeBraille(); + this.braille.write(this.content1); + this.sendCommand(this.command1, this.displayManager.content); + // Now, this other braille gets a different unique id. + cvox.ExtensionBridge.uniqueId = function() { return 2; } + anotherBraille.write(this.content2); + this.sendCommand(this.command2, this.displayManager.content); + // The first 'tab' still gets the command, but since the second 'tab's\ + // braille was on the display, it gets null content. + assertEqualsJSON(this.command2, this.lastCommand); + assertEquals(null, this.lastCommandContent); + }); });
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/callback_helper.js b/chrome/browser/resources/chromeos/chromevox/testing/callback_helper.js new file mode 100644 index 0000000..fba23c3 --- /dev/null +++ b/chrome/browser/resources/chromeos/chromevox/testing/callback_helper.js
@@ -0,0 +1,45 @@ +// 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. + +/** + * Creates wrappers for callbacks and calls testDone() when all callbacks + * have been invoked. + * @param {testing.Test} fixture + */ +function CallbackHelper(fixture) { + /** @type {Object} fixture */ + this.fixture_ = fixture; + /** @type {number} */ + this.pendingCallbacks_ = 0; +} + +CallbackHelper.prototype = { + /** + * @param {Function=} opt_callback + * @return {Function} + */ + wrap: function(opt_callback) { + var callback = opt_callback || function() {}; + var savedArgs = new SaveMockArguments(); + var lastCall = null; + var completionAction = callFunctionWithSavedArgs(savedArgs, function() { + if (lastCall) { + throw new Error('Called more than once, first call here: ' + lastCall); + } else { + lastCall = new Error().stack; + } + callback.apply(this.fixture_, arguments); + if (--this.pendingCallbacks_ <= 0) + testDone(); + }.bind(this)); + // runAllActionsAsync catches exceptions and puts them in the test + // framework's list of errors and fails the test. + var runAll = runAllActionsAsync(WhenTestDone.ASSERT, completionAction); + ++this.pendingCallbacks_; + return function() { + savedArgs.arguments = Array.prototype.slice.call(arguments); + runAll.invoke(); + } + } +};
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_e2e_test_base.js b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_e2e_test_base.js index 9b797cb..16a0a5a 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_e2e_test_base.js
@@ -3,7 +3,8 @@ // found in the LICENSE file. GEN_INCLUDE([ - 'chrome/browser/resources/chromeos/chromevox/testing/common.js']); + 'chrome/browser/resources/chromeos/chromevox/testing/common.js', + 'chrome/browser/resources/chromeos/chromevox/testing/callback_helper.js']); /** * Base test fixture for ChromeVox end to end tests. @@ -12,7 +13,9 @@ * background page context. * @constructor */ -function ChromeVoxE2ETest() {} +function ChromeVoxE2ETest() { + this.callbackHelper_ = new CallbackHelper(this); +} ChromeVoxE2ETest.prototype = { __proto__: testing.Test.prototype, @@ -101,6 +104,18 @@ */}, [key, elementQueryString]); chrome.tabs.executeScript(tabId, {code: code}); + }, + + /** + * Creates a callback that optionally calls {@code opt_callback} when + * called. If this method is called one or more times, then + * {@code testDone()} will be called when all callbacks have been called. + * @param {Function=} opt_callback Wrapped callback that will have its this + * reference bound to the test fixture. + * @return {Function} + */ + newCallback: function(opt_callback) { + return this.callbackHelper_.wrap(opt_callback); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js index 5eebf0b..4493cec5 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_next_e2e_test_base.js
@@ -14,38 +14,32 @@ * @constructor * @extends {ChromeVoxE2ETest} */ -function ChromeVoxNextE2ETest() {} +function ChromeVoxNextE2ETest() { + ChromeVoxE2ETest.call(this); +} ChromeVoxNextE2ETest.prototype = { __proto__: ChromeVoxE2ETest.prototype, /** - * This method is called without |this| bound to an instance of - * ChromeVoxNextE2ETest. - * @override - */ - testGenCppIncludes: function() { - ChromeVoxE2ETest.prototype.testGenCppIncludes.call(this); - GEN('#include "base/command_line.h"'); - }, - - /** * Launches a new tab with the given document, and runs callback when a load * complete fires. * @param {function() : void} doc Snippet wrapped inside of a function. * @param {function()} opt_callback Called once the document is ready. */ runWithLoadedTree: function(doc, callback) { + callback = this.newCallback(callback); chrome.automation.getDesktop(function(r) { - function callbackInternal(evt) { + var listener = function(evt) { if (!evt.target.attributes.url || evt.target.attributes.url.indexOf('test') == -1) return; - r.removeEventListener(callbackInternal); - callback(evt.target); - } - r.addEventListener('loadComplete', callbackInternal, true); + r.removeEventListener(listener); + callback && callback(evt.target); + callback = null; + }; + r.addEventListener('loadComplete', listener, true); this.runWithTab(doc); }.bind(this)); }
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_unittest_base.js b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_unittest_base.js index 869a0c3..759591e1 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/chromevox_unittest_base.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/chromevox_unittest_base.js
@@ -5,7 +5,8 @@ GEN_INCLUDE([ 'chrome/browser/resources/chromeos/chromevox/testing/assert_additions.js']); GEN_INCLUDE([ - 'chrome/browser/resources/chromeos/chromevox/testing/common.js']); + 'chrome/browser/resources/chromeos/chromevox/testing/common.js', + 'chrome/browser/resources/chromeos/chromevox/testing/callback_helper.js']); /** * Base test fixture for ChromeVox unit tests. @@ -17,7 +18,11 @@ * @constructor * @extends {testing.Test} */ -function ChromeVoxUnitTestBase() {} +function ChromeVoxUnitTestBase() { + if (this.isAsync) { + this.callbackHelper_ = new CallbackHelper(this); + } +} ChromeVoxUnitTestBase.prototype = { __proto__: testing.Test.prototype, @@ -115,12 +120,11 @@ * @return {ChromeVoxUnitTestBase} this. */ waitForCalm: function(func, var_args) { - var me = this; var calmArguments = Array.prototype.slice.call(arguments); calmArguments.shift(); - cvox.ChromeVoxEventWatcher.addReadyCallback(function() { - func.apply(me, calmArguments); - }); + cvox.ChromeVoxEventWatcher.addReadyCallback(this.newCallback(function() { + func.apply(this, calmArguments); + })); return this; // for chaining. }, @@ -190,5 +194,24 @@ */ spokenList: function() { return new cvox.SpokenListBuilder(); + }, + + /** + * @type {CallbackHelper} + * @private + */ + callbackHelper_: null, + + /** + * Creates a callback that optionally calls {@code opt_callback} when + * called. If this method is called one or more times, then + * {@code testDone()} will be called when all callbacks have been called. + * @param {Function=} opt_callback Wrapped callback that will have its this + * reference bound to the test fixture. + * @return {Function} + */ + newCallback: function(opt_callback) { + assertNotEquals(null, this.callbackHelper_); + return this.callbackHelper_.wrap(opt_callback); } };
diff --git a/chrome/browser/resources/chromeos/chromevox/testing/mock_tts.js b/chrome/browser/resources/chromeos/chromevox/testing/mock_tts.js index 3308992..3f32d0c 100644 --- a/chrome/browser/resources/chromeos/chromevox/testing/mock_tts.js +++ b/chrome/browser/resources/chromeos/chromevox/testing/mock_tts.js
@@ -62,10 +62,11 @@ }, /** - * Finishes expectations and calls testDone. + * Finishes expectations and calls {@code callback} afterwards. + * @param {Function} callback */ - finishExpectations: function() { - this.expectSpeechAfter('', testDone); + finishExpectations: function(callback) { + this.expectSpeechAfter('', callback); }, /**
diff --git a/chrome/browser/resources/chromeos/login/header_bar.css b/chrome/browser/resources/chromeos/login/header_bar.css index c199d22..a1fd095 100644 --- a/chrome/browser/resources/chromeos/login/header_bar.css +++ b/chrome/browser/resources/chromeos/login/header_bar.css
@@ -69,16 +69,19 @@ display: none; } -#more-settings-header-bar-item.active .add-supervised-user-menu { +#more-settings-header-bar-item.active button.add-supervised-user-menu { background-color: white; border: 1px solid lightgray; border-radius: 2px; bottom: 15px; + color: black !important; display: block; font-size: 13px; left: 15px; + margin: 0 0 -10px -10px; position: absolute; - width: 220px; + text-align: center; + width: 180px; } html[dir=rtl] .header-bar-item {
diff --git a/chrome/browser/resources/chromeos/login/header_bar.html b/chrome/browser/resources/chromeos/login/header_bar.html index a106c250..62cbc116 100644 --- a/chrome/browser/resources/chromeos/login/header_bar.html +++ b/chrome/browser/resources/chromeos/login/header_bar.html
@@ -23,9 +23,10 @@ </div> <div id="more-settings-header-bar-item" class="header-bar-item"> <button id="more-settings-button" class="custom-appearance"></button> - <div class="add-supervised-user-menu" aria-label="Add supervised user"> - <span class="add-supervised-user-command">Add supervised user</span> - </div> + <button class="add-supervised-user-menu custom-appearance" + id="add-supervised-user-menu" tabindex="0" + i18n-content="addSupervisedUser"> + </button> </div> <div id="sign-out-user-item" class="header-bar-item" hidden> <button id="sign-out-user-button" class="custom-appearance"
diff --git a/chrome/browser/resources/chromeos/login/header_bar.js b/chrome/browser/resources/chromeos/login/header_bar.js index 2a3b622f9..6c6a759 100644 --- a/chrome/browser/resources/chromeos/login/header_bar.js +++ b/chrome/browser/resources/chromeos/login/header_bar.js
@@ -147,6 +147,7 @@ handleMoreSettingsClick_: function(e) { this.isMoreSettingsActive = !this.isMoreSettingsActive; + this.addSupervisedUserMenu.focus(); e.stopPropagation(); }, @@ -158,6 +159,7 @@ chrome.send('showSupervisedUserCreationScreen'); e.preventDefault(); }, + /** * Cancel add user button click handler. * @@ -329,8 +331,8 @@ $('add-user-button').hidden = !accountPickerIsActive || isMultiProfilesUI || isLockScreen; $('more-settings-header-bar-item').hidden = !this.isMinuteMaid_ || - !gaiaIsActive || - !this.showCreateSupervised_; + !this.showCreateSupervised_ || + !accountPickerIsActive; $('cancel-add-user-button').hidden = (gaiaIsActive && this.isMinuteMaid_) || accountPickerIsActive ||
diff --git a/chrome/browser/resources/downloads/downloads.html b/chrome/browser/resources/downloads/downloads.html index 5272cfc..40d968d 100644 --- a/chrome/browser/resources/downloads/downloads.html +++ b/chrome/browser/resources/downloads/downloads.html
@@ -57,22 +57,26 @@ <canvas class="progress"></canvas> <img class="icon" alt=""> <div class="title-area"> - <a is="action-link" class="name"></a> + <a is="action-link" class="name" column-type="name"></a> <span class="name"></span> <span class="status"></span> </div> <div class="url-container"> - <a class="src-url" target="_blank"></a> + <a class="src-url" target="_blank" column-type="url"></a> </div> <div class="controls"> - <a is="action-link" class="show" + <a is="action-link" class="show" column-type="show" i18n-content="control_showinfolder"></a> - <a class="retry" i18n-content="control_retry" download></a> - <a is="action-link" class="pause" i18n-content="control_pause"></a> - <a is="action-link" class="resume" i18n-content="control_resume"></a> - <a is="action-link" class="remove" + <a class="retry" column-type="retry" i18n-content="control_retry" + download></a> + <a is="action-link" class="pause" column-type="pause" + i18n-content="control_pause"></a> + <a is="action-link" class="resume" column-type="resume" + i18n-content="control_resume"></a> + <a is="action-link" class="remove" column-type="remove" i18n-content="control_removefromlist"></a> - <a is="action-link" class="cancel" i18n-content="control_cancel"></a> + <a is="action-link" class="cancel" column-type="cancel" + i18n-content="control_cancel"></a> <span class="controlled-by" i18n-values=".innerHTML:control_by_extension"></span> </div> @@ -81,13 +85,15 @@ <img class="icon" alt=""> <div class="description"></div> <div class="controls"> - <a is="action-link" class="restore" + <a is="action-link" class="restore" column-type="save" i18n-content="danger_restore"></a> - <a is="action-link" class="remove" + <a is="action-link" class="remove" column-type="discard" i18n-content="control_removefromlist"></a> </div> - <button class="save" i18n-content="danger_save"></button> - <button class="discard" i18n-content="danger_discard"></button> + <button class="save" column-type="save" + i18n-content="danger_save"></button> + <button class="discard" column-type="discard" + i18n-content="danger_discard"></button> </div> </div> </div>
diff --git a/chrome/browser/resources/downloads/focus_row.js b/chrome/browser/resources/downloads/focus_row.js index 71f7b85..063b8ccf 100644 --- a/chrome/browser/resources/downloads/focus_row.js +++ b/chrome/browser/resources/downloads/focus_row.js
@@ -20,21 +20,7 @@ FocusRow.decorate = function(focusRow, itemView, boundary) { focusRow.__proto__ = FocusRow.prototype; focusRow.decorate(boundary); - - // Add all clickable elements as a row into the grid. - focusRow.addElementIfFocusable_(itemView.fileLink, 'name'); - focusRow.addElementIfFocusable_(itemView.srcUrl, 'url'); - focusRow.addElementIfFocusable_(itemView.show, 'show'); - focusRow.addElementIfFocusable_(itemView.retry, 'retry'); - focusRow.addElementIfFocusable_(itemView.pause, 'pause'); - focusRow.addElementIfFocusable_(itemView.resume, 'resume'); - focusRow.addElementIfFocusable_(itemView.safeRemove, 'remove'); - focusRow.addElementIfFocusable_(itemView.cancel, 'cancel'); - focusRow.addElementIfFocusable_(itemView.restore, 'save'); - focusRow.addElementIfFocusable_(itemView.save, 'save'); - focusRow.addElementIfFocusable_(itemView.dangerRemove, 'discard'); - focusRow.addElementIfFocusable_(itemView.discard, 'discard'); - focusRow.addElementIfFocusable_(itemView.controlledBy, 'extension'); + focusRow.addFocusableElements_(); }; FocusRow.prototype = { @@ -50,6 +36,7 @@ var equivalent = this.querySelector('[column-type=' + columnType + ']'); if (this.focusableElements.indexOf(equivalent) < 0) { + equivalent = null; var equivalentTypes = ['show', 'retry', 'pause', 'resume', 'remove', 'cancel']; if (equivalentTypes.indexOf(columnType) != -1) { @@ -64,15 +51,13 @@ return assert(equivalent || this.focusableElements[0]); }, - /** - * @param {Element} element The element that should be added. - * @param {string} type The column type to use for the element. - * @private - */ - addElementIfFocusable_: function(element, type) { - if (this.shouldFocus_(element)) { - this.addFocusableElement(element); - element.setAttribute('column-type', type); + /** @private */ + addFocusableElements_: function() { + var possiblyFocusableElements = this.querySelectorAll('[column-type]'); + for (var i = 0; i < possiblyFocusableElements.length; ++i) { + var possiblyFocusableElement = possiblyFocusableElements[i]; + if (this.shouldFocus_(possiblyFocusableElement)) + this.addFocusableElement(possiblyFocusableElement); } },
diff --git a/chrome/browser/resources/downloads/item_view.js b/chrome/browser/resources/downloads/item_view.js index 3724d5af..f6112270 100644 --- a/chrome/browser/resources/downloads/item_view.js +++ b/chrome/browser/resources/downloads/item_view.js
@@ -23,39 +23,39 @@ this.safeImg_ = /** @type !HTMLImageElement */( this.queryRequired_('.safe img')); this.fileName_ = this.queryRequired_('span.name'); - this.fileLink = this.queryRequired_('[is="action-link"].name'); + this.fileLink_ = this.queryRequired_('[is="action-link"].name'); this.status_ = this.queryRequired_('.status'); - this.srcUrl = this.queryRequired_('.src-url'); - this.show = this.queryRequired_('.show'); - this.retry = this.queryRequired_('.retry'); - this.pause = this.queryRequired_('.pause'); - this.resume = this.queryRequired_('.resume'); - this.safeRemove = this.queryRequired_('.safe .remove'); - this.cancel = this.queryRequired_('.cancel'); - this.controlledBy = this.queryRequired_('.controlled-by'); + this.srcUrl_ = this.queryRequired_('.src-url'); + this.show_ = this.queryRequired_('.show'); + this.retry_ = this.queryRequired_('.retry'); + this.pause_ = this.queryRequired_('.pause'); + this.resume_ = this.queryRequired_('.resume'); + this.safeRemove_ = this.queryRequired_('.safe .remove'); + this.cancel_ = this.queryRequired_('.cancel'); + this.controlledBy_ = this.queryRequired_('.controlled-by'); this.dangerous_ = this.queryRequired_('.dangerous'); this.dangerImg_ = /** @type {!HTMLImageElement} */( this.queryRequired_('.dangerous img')); this.description_ = this.queryRequired_('.description'); this.malwareControls_ = this.queryRequired_('.dangerous .controls'); - this.restore = this.queryRequired_('.restore'); - this.dangerRemove = this.queryRequired_('.dangerous .remove'); - this.save = this.queryRequired_('.save'); - this.discard = this.queryRequired_('.discard'); + this.restore_ = this.queryRequired_('.restore'); + this.dangerRemove_ = this.queryRequired_('.dangerous .remove'); + this.save_ = this.queryRequired_('.save'); + this.discard_ = this.queryRequired_('.discard'); // Event handlers (bound once on creation). this.safe_.ondragstart = this.onSafeDragstart_.bind(this); - this.fileLink.onclick = this.onFileLinkClick_.bind(this); - this.show.onclick = this.onShowClick_.bind(this); - this.pause.onclick = this.onPauseClick_.bind(this); - this.resume.onclick = this.onResumeClick_.bind(this); - this.safeRemove.onclick = this.onSafeRemoveClick_.bind(this); - this.cancel.onclick = this.onCancelClick_.bind(this); - this.restore.onclick = this.onRestoreClick_.bind(this); - this.save.onclick = this.onSaveClick_.bind(this); - this.dangerRemove.onclick = this.onDangerRemoveClick_.bind(this); - this.discard.onclick = this.onDiscardClick_.bind(this); + this.fileLink_.onclick = this.onFileLinkClick_.bind(this); + this.show_.onclick = this.onShowClick_.bind(this); + this.pause_.onclick = this.onPauseClick_.bind(this); + this.resume_.onclick = this.onResumeClick_.bind(this); + this.safeRemove_.onclick = this.onSafeRemoveClick_.bind(this); + this.cancel_.onclick = this.onCancelClick_.bind(this); + this.restore_.onclick = this.onRestoreClick_.bind(this); + this.save_.onclick = this.onSaveClick_.bind(this); + this.dangerRemove_.onclick = this.onDangerRemoveClick_.bind(this); + this.discard_.onclick = this.onDiscardClick_.bind(this); } /** Progress meter constants. */ @@ -186,8 +186,8 @@ data.danger_type == Item.DangerType.POTENTIALLY_UNWANTED; this.malwareControls_.hidden = !showMalwareControls; - this.discard.hidden = showMalwareControls; - this.save.hidden = showMalwareControls; + this.discard_.hidden = showMalwareControls; + this.save_.hidden = showMalwareControls; } else { var path = encodeURIComponent(data.file_path); ItemView.loadScaledIcon(this.safeImg_, 'chrome://fileicon/' + path); @@ -198,44 +198,45 @@ /** @const */ var completelyOnDisk = data.state == Item.States.COMPLETE && !data.file_externally_removed; - this.fileLink.href = data.url; - this.ensureTextIs_(this.fileLink, data.file_name); - this.fileLink.hidden = !completelyOnDisk; + this.fileLink_.href = data.url; + this.ensureTextIs_(this.fileLink_, data.file_name); + this.fileLink_.hidden = !completelyOnDisk; /** @const */ var isInterrupted = data.state == Item.States.INTERRUPTED; this.fileName_.classList.toggle('interrupted', isInterrupted); this.ensureTextIs_(this.fileName_, data.file_name); this.fileName_.hidden = completelyOnDisk; - this.show.hidden = !completelyOnDisk; + this.show_.hidden = !completelyOnDisk; - this.retry.href = data.url; - this.retry.hidden = !data.retry; + this.retry_.href = data.url; + this.retry_.hidden = !data.retry; - this.pause.hidden = !isInProgress; + this.pause_.hidden = !isInProgress; - this.resume.hidden = !data.resume; + this.resume_.hidden = !data.resume; /** @const */ var isPaused = data.state == Item.States.PAUSED; /** @const */ var showCancel = isPaused || isInProgress; - this.cancel.hidden = !showCancel; + this.cancel_.hidden = !showCancel; - this.safeRemove.hidden = showCancel || + this.safeRemove_.hidden = showCancel || !loadTimeData.getBoolean('allow_deleting_history'); /** @const */ var controlledByExtension = data.by_ext_id && data.by_ext_name; - this.controlledBy.hidden = !controlledByExtension; + this.controlledBy_.hidden = !controlledByExtension; if (controlledByExtension) { - var link = this.controlledBy.querySelector('a'); + var link = this.controlledBy_.querySelector('a'); link.href = 'chrome://extensions#' + data.by_ext_id; + link.setAttribute('column-type', 'controlled-by'); link.textContent = data.by_ext_name; } this.ensureTextIs_(this.since_, data.since_string); this.ensureTextIs_(this.date_, data.date_string); - this.ensureTextIs_(this.srcUrl, data.url); - this.srcUrl.href = data.url; + this.ensureTextIs_(this.srcUrl_, data.url); + this.srcUrl_.href = data.url; this.ensureTextIs_(this.status_, this.getStatusText_(data)); this.foregroundProgress_.hidden = !isInProgress;
diff --git a/chrome/browser/resources/downloads/manager.js b/chrome/browser/resources/downloads/manager.js index 89a5aac..36b2fa0a 100644 --- a/chrome/browser/resources/downloads/manager.js +++ b/chrome/browser/resources/downloads/manager.js
@@ -102,7 +102,14 @@ /** @param {!downloads.Data} data Info about the item to update. */ updateItem: function(data) { - this.idMap_[data.id].render(data); + var activeElement = document.activeElement; + + var item = this.idMap_[data.id]; + item.render(data); + var focusRow = this.decorateItem_(item); + + if (activeElement != document.activeElement) + focusRow.getEquivalentElement(activeElement).focus(); }, /** @@ -117,17 +124,25 @@ this.focusGrid_.destroy(); this.items_.forEach(function(item) { - downloads.FocusRow.decorate(item.view.node, item.view, this.node_); - var focusRow = assertInstanceof(item.view.node, downloads.FocusRow); + var focusRow = this.decorateItem_(item); this.focusGrid_.addRow(focusRow); - // Focus the equivalent element in the focusRow because the active - // element may no longer be visible. - if (focusRow.contains(activeElement)) + if (activeElement != document.activeElement && + focusRow.contains(activeElement)) { focusRow.getEquivalentElement(activeElement).focus(); + } }, this); }, + /** + * @param {!downloads.Item} item An item to decorate as a FocusRow. + * @return {!downloads.FocusRow} |item| decorated as a FocusRow. + */ + decorateItem_: function(item) { + downloads.FocusRow.decorate(item.view.node, item.view, this.node_); + return assertInstanceof(item.view.node, downloads.FocusRow); + }, + /** @return {number} The number of downloads shown on the page. */ size: function() { return this.items_.length;
diff --git a/chrome/browser/resources/options/content_settings.html b/chrome/browser/resources/options/content_settings.html index ecdbc4e2..a674881f 100644 --- a/chrome/browser/resources/options/content_settings.html +++ b/chrome/browser/resources/options/content_settings.html
@@ -172,7 +172,7 @@ </div> </div> </section> - <!-- Plug-ins filter --> + <!-- Plugins filter --> <section> <h3 i18n-content="pluginsTabLabel"></h3> <div class="replace-with-website-settings">
diff --git a/chrome/browser/resources/plugin_metadata/plugins_mac.json b/chrome/browser/resources/plugin_metadata/plugins_mac.json index b0831c1..35534d2 100644 --- a/chrome/browser/resources/plugin_metadata/plugins_mac.json +++ b/chrome/browser/resources/plugin_metadata/plugins_mac.json
@@ -99,7 +99,7 @@ { "version": "0", "status": "requires_authorization", - "comment": "The Real Player plug-in for mac doesn't expose a version at all." + "comment": "The Real Player plugin for mac doesn't expose a version at all." } ], "lang": "en-US",
diff --git a/chrome/browser/resources/plugin_metadata/plugins_win.json b/chrome/browser/resources/plugin_metadata/plugins_win.json index 5317809..1f86f25 100644 --- a/chrome/browser/resources/plugin_metadata/plugins_win.json +++ b/chrome/browser/resources/plugin_metadata/plugins_win.json
@@ -366,7 +366,7 @@ { "version": "0", "status": "requires_authorization", - "comment": "Google Update plug-in is versioned but kept automatically up-to-date" + "comment": "Google Update plugin is versioned but kept automatically up-to-date" } ], "name": "Google Update",
diff --git a/chrome/browser/service_process/service_process_control_mac.mm b/chrome/browser/service_process/service_process_control_mac.mm index e7ae3b4..0e26eb29 100644 --- a/chrome/browser/service_process/service_process_control_mac.mm +++ b/chrome/browser/service_process/service_process_control_mac.mm
@@ -6,6 +6,7 @@ #include "base/bind.h" #include "base/command_line.h" +#include "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" #include "chrome/common/service_process_util_posix.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/signin/principals_message_filter.cc b/chrome/browser/signin/principals_message_filter.cc deleted file mode 100644 index ef8dd50..0000000 --- a/chrome/browser/signin/principals_message_filter.cc +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/signin/principals_message_filter.h" - -#include "chrome/common/render_messages.h" -#include "content/public/browser/browser_thread.h" - -PrincipalsMessageFilter::PrincipalsMessageFilter(int render_process_id) - : BrowserMessageFilter(ChromeMsgStart), - render_process_id_(render_process_id) {} - -PrincipalsMessageFilter::~PrincipalsMessageFilter(){} - -void PrincipalsMessageFilter::OverrideThreadForMessage( - const IPC::Message& message, - content::BrowserThread::ID* thread) { - // GetManagedAccounts message is synchronous, it must be handled in the IO - // thread, so no need to change thread, otherwise switch to UI thread - if (message.type() == ChromeViewHostMsg_ShowBrowserAccountManagementUI::ID) - *thread = content::BrowserThread::UI; -} - -bool PrincipalsMessageFilter::OnMessageReceived(const IPC::Message& message) { - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(PrincipalsMessageFilter, message) - IPC_MESSAGE_HANDLER( - ChromeViewHostMsg_GetManagedAccounts, OnMsgGetManagedAccounts) - IPC_MESSAGE_HANDLER( - ChromeViewHostMsg_ShowBrowserAccountManagementUI, - OnMsgShowBrowserAccountManagementUI) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} - - - -void PrincipalsMessageFilter::OnMsgShowBrowserAccountManagementUI(){ - // TODO(guohui) -} - -void PrincipalsMessageFilter::OnMsgGetManagedAccounts( - const GURL& url, std::vector<std::string>* managed_accounts) { - // TODO(guohui) -} -
diff --git a/chrome/browser/signin/principals_message_filter.h b/chrome/browser/signin/principals_message_filter.h deleted file mode 100644 index 5d378646..0000000 --- a/chrome/browser/signin/principals_message_filter.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SIGNIN_PRINCIPALS_MESSAGE_FILTER_H_ -#define CHROME_BROWSER_SIGNIN_PRINCIPALS_MESSAGE_FILTER_H_ - -#include "content/public/browser/browser_message_filter.h" - -class GURL; -class Profile; - -// A message filter implementation that receives messages for browser account -// management from the renderer. -class PrincipalsMessageFilter : public content::BrowserMessageFilter { - public: - explicit PrincipalsMessageFilter(int render_process_id); - - // content::BrowserMessageFilter implementation. - void OverrideThreadForMessage(const IPC::Message& message, - content::BrowserThread::ID* thread) override; - bool OnMessageReceived(const IPC::Message& message) override; - - private: - ~PrincipalsMessageFilter() override; - - void OnMsgShowBrowserAccountManagementUI(); - void OnMsgGetManagedAccounts(const GURL& url, - std::vector<std::string>* managed_accounts); - - int render_process_id_; - - DISALLOW_COPY_AND_ASSIGN(PrincipalsMessageFilter); -}; - -#endif // CHROME_BROWSER_SIGNIN_PRINCIPALS_MESSAGE_FILTER_H_
diff --git a/chrome/browser/signin/signin_header_helper.cc b/chrome/browser/signin/signin_header_helper.cc index 674a59f..0387202 100644 --- a/chrome/browser/signin/signin_header_helper.cc +++ b/chrome/browser/signin/signin_header_helper.cc
@@ -202,10 +202,13 @@ int route_id) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)); - if (io_data->IsOffTheRecord() || - io_data->google_services_username()->GetValue().empty()) { + if (io_data->IsOffTheRecord()) return false; - } + + std::string account_id(io_data->google_services_account_id()->GetValue()); + + if (account_id.empty()) + return false; // If signin cookies are not allowed, don't add the header. if (!ChromeSigninClient::SettingsAllowSigninCookies( @@ -251,8 +254,6 @@ return false; #endif // !OS_ANDROID && !OS_IOS - std::string account_id(io_data->google_services_account_id()->GetValue()); - int profile_mode_mask = PROFILE_MODE_DEFAULT; if (io_data->incognito_availibility()->GetValue() == IncognitoModePrefs::DISABLED ||
diff --git a/chrome/browser/sync/glue/bookmark_change_processor.cc b/chrome/browser/sync/glue/bookmark_change_processor.cc index cc110dfb..cc6340f 100644 --- a/chrome/browser/sync/glue/bookmark_change_processor.cc +++ b/chrome/browser/sync/glue/bookmark_change_processor.cc
@@ -14,7 +14,6 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" @@ -25,6 +24,7 @@ #include "components/bookmarks/browser/bookmark_client.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/history_service.h" #include "content/public/browser/browser_thread.h" #include "sync/internal_api/public/change_record.h"
diff --git a/chrome/browser/sync/glue/favicon_cache.cc b/chrome/browser/sync/glue/favicon_cache.cc index d2611de..1237a95 100644 --- a/chrome/browser/sync/glue/favicon_cache.cc +++ b/chrome/browser/sync/glue/favicon_cache.cc
@@ -6,9 +6,9 @@ #include "base/message_loop/message_loop.h" #include "base/metrics/histogram.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/history_service_factory.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/history_types.h" #include "sync/api/time.h"
diff --git a/chrome/browser/sync/test/integration/bookmarks_helper.cc b/chrome/browser/sync/test/integration/bookmarks_helper.cc index 92cdaa94..c51e9269 100644 --- a/chrome/browser/sync/test/integration/bookmarks_helper.cc +++ b/chrome/browser/sync/test/integration/bookmarks_helper.cc
@@ -21,7 +21,6 @@ #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/bookmarks/chrome_bookmark_client.h" #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" @@ -35,6 +34,7 @@ #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_model_observer.h" #include "components/bookmarks/browser/bookmark_utils.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_util.h" #include "components/history/core/browser/history_db_task.h" #include "components/history/core/browser/history_service.h"
diff --git a/chrome/browser/task_manager/child_process_resource_provider.cc b/chrome/browser/task_manager/child_process_resource_provider.cc index d4714b3..e46d182 100644 --- a/chrome/browser/task_manager/child_process_resource_provider.cc +++ b/chrome/browser/task_manager/child_process_resource_provider.cc
@@ -49,7 +49,7 @@ private: // Returns a localized title for the child process. For example, a plugin - // process would be "Plug-in: Flash" when name is "Flash". + // process would be "Plugin: Flash" when name is "Flash". base::string16 GetLocalizedTitle() const; int process_type_;
diff --git a/chrome/browser/ui/android/navigation_popup.cc b/chrome/browser/ui/android/navigation_popup.cc index d23655a..f7369c53 100644 --- a/chrome/browser/ui/android/navigation_popup.cc +++ b/chrome/browser/ui/android/navigation_popup.cc
@@ -8,11 +8,11 @@ #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/url_constants.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/history_types.h" #include "jni/NavigationPopup_jni.h" #include "third_party/skia/include/core/SkBitmap.h"
diff --git a/chrome/browser/ui/app_list/search/suggestions/suggestions_search_provider.cc b/chrome/browser/ui/app_list/search/suggestions/suggestions_search_provider.cc index b31768b..18515bb 100644 --- a/chrome/browser/ui/app_list/search/suggestions/suggestions_search_provider.cc +++ b/chrome/browser/ui/app_list/search/suggestions/suggestions_search_provider.cc
@@ -6,13 +6,13 @@ #include "base/memory/scoped_ptr.h" #include "base/strings/string16.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/suggestions/suggestions_service_factory.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/app_list/search/suggestions/url_suggestion_result.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/suggestions/proto/suggestions.pb.h" #include "components/suggestions/suggestions_service.h" #include "components/suggestions/suggestions_utils.h"
diff --git a/chrome/browser/ui/app_list/search/suggestions/url_suggestion_result.cc b/chrome/browser/ui/app_list/search/suggestions/url_suggestion_result.cc index d7668c5..6535b14 100644 --- a/chrome/browser/ui/app_list/search/suggestions/url_suggestion_result.cc +++ b/chrome/browser/ui/app_list/search/suggestions/url_suggestion_result.cc
@@ -5,10 +5,10 @@ #include "chrome/browser/ui/app_list/search/suggestions/url_suggestion_result.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/app_list_controller_delegate.h" #include "chrome/browser/ui/app_list/search/search_util.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_callback.h" #include "components/favicon_base/favicon_types.h" #include "components/suggestions/suggestions_service.h"
diff --git a/chrome/browser/ui/ash/launcher/launcher_favicon_loader.cc b/chrome/browser/ui/ash/launcher/launcher_favicon_loader.cc index b490727..fccb2db 100644 --- a/chrome/browser/ui/ash/launcher/launcher_favicon_loader.cc +++ b/chrome/browser/ui/ash/launcher/launcher_favicon_loader.cc
@@ -107,8 +107,9 @@ pending_requests_.insert(*iter); web_contents()->DownloadImage( *iter, - true, // is a favicon - 0, // no maximum size + true, // is a favicon + 0, // no maximum size + false, // normal cache policy base::Bind(&FaviconRawBitmapHandler::DidDownloadFavicon, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/ui/cocoa/content_settings/content_setting_bubble_cocoa.h b/chrome/browser/ui/cocoa/content_settings/content_setting_bubble_cocoa.h index c63e0977..fb72749 100644 --- a/chrome/browser/ui/cocoa/content_settings/content_setting_bubble_cocoa.h +++ b/chrome/browser/ui/cocoa/content_settings/content_setting_bubble_cocoa.h
@@ -81,7 +81,7 @@ // Callback for "info" link. - (IBAction)showMoreInfo:(id)sender; -// Callback for "load" (plug-ins, mixed script) button. +// Callback for "load" (plugins, mixed script) button. - (IBAction)load:(id)sender; // Callback for "Learn More" link.
diff --git a/chrome/browser/ui/cocoa/history_menu_bridge.h b/chrome/browser/ui/cocoa/history_menu_bridge.h index 1af14a1..1f9cc2d 100644 --- a/chrome/browser/ui/cocoa/history_menu_bridge.h +++ b/chrome/browser/ui/cocoa/history_menu_bridge.h
@@ -13,10 +13,10 @@ #include "base/memory/ref_counted.h" #include "base/scoped_observer.h" #include "base/task/cancelable_task_tracker.h" -#import "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/sessions/tab_restore_service.h" #include "chrome/browser/sessions/tab_restore_service_observer.h" #import "chrome/browser/ui/cocoa/main_menu_item.h" +#import "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/browser/history_service_observer.h" #include "components/sessions/session_id.h"
diff --git a/chrome/browser/ui/content_settings/content_setting_bubble_model.cc b/chrome/browser/ui/content_settings/content_setting_bubble_model.cc index 23c1275..8154cb2a 100644 --- a/chrome/browser/ui/content_settings/content_setting_bubble_model.cc +++ b/chrome/browser/ui/content_settings/content_setting_bubble_model.cc
@@ -510,7 +510,7 @@ if (!web_contents()) return; #if defined(ENABLE_PLUGINS) - // TODO(bauerb): We should send the identifiers of blocked plug-ins here. + // TODO(bauerb): We should send the identifiers of blocked plugins here. ChromePluginServiceFilter::GetInstance()->AuthorizeAllPlugins( web_contents(), true, std::string()); #endif
diff --git a/chrome/browser/ui/exclusive_access/exclusive_access_controller_base.cc b/chrome/browser/ui/exclusive_access/exclusive_access_controller_base.cc index bbc7545..3559f37 100644 --- a/chrome/browser/ui/exclusive_access/exclusive_access_controller_base.cc +++ b/chrome/browser/ui/exclusive_access/exclusive_access_controller_base.cc
@@ -6,8 +6,7 @@ #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_service.h"
diff --git a/chrome/browser/ui/metro_pin_tab_helper_win.cc b/chrome/browser/ui/metro_pin_tab_helper_win.cc index 6082893..202c39b7 100644 --- a/chrome/browser/ui/metro_pin_tab_helper_win.cc +++ b/chrome/browser/ui/metro_pin_tab_helper_win.cc
@@ -400,6 +400,7 @@ web_contents()->DownloadImage(iter->icon_url, true, max_image_size, + false, base::Bind(&MetroPinTabHelper::DidDownloadFavicon, base::Unretained(this)))); }
diff --git a/chrome/browser/ui/pdf/pdf_unsupported_feature.cc b/chrome/browser/ui/pdf/pdf_unsupported_feature.cc index eca5db3..dc40e45 100644 --- a/chrome/browser/ui/pdf/pdf_unsupported_feature.cc +++ b/chrome/browser/ui/pdf/pdf_unsupported_feature.cc
@@ -206,7 +206,7 @@ } else if (command == "2") { content::RecordAction( UserMetricsAction("PDF_ReaderInterstitialIgnore")); - // Pretend that the plug-in is up-to-date so that we don't block it. + // Pretend that the plugin is up-to-date so that we don't block it. reader_webplugininfo_.version = base::ASCIIToUTF16("11.0.0.0"); OpenUsingReader(web_contents_, reader_webplugininfo_, NULL); } else {
diff --git a/chrome/browser/ui/search_engines/template_url_table_model.cc b/chrome/browser/ui/search_engines/template_url_table_model.cc index b4201e6..f0799d57 100644 --- a/chrome/browser/ui/search_engines/template_url_table_model.cc +++ b/chrome/browser/ui/search_engines/template_url_table_model.cc
@@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/i18n/rtl.h" #include "base/task/cancelable_task_tracker.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/grit/generated_resources.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_types.h" #include "components/search_engines/template_url.h" #include "components/search_engines/template_url_service.h"
diff --git a/chrome/browser/ui/toolbar/back_forward_menu_model.h b/chrome/browser/ui/toolbar/back_forward_menu_model.h index 68dbec1..60265bba 100644 --- a/chrome/browser/ui/toolbar/back_forward_menu_model.h +++ b/chrome/browser/ui/toolbar/back_forward_menu_model.h
@@ -12,7 +12,7 @@ #include "base/gtest_prod_util.h" #include "base/strings/string16.h" #include "base/task/cancelable_task_tracker.h" -#include "chrome/browser/favicon/favicon_service.h" +#include "components/favicon/core/browser/favicon_service.h" #include "ui/base/models/menu_model.h" #include "ui/base/window_open_disposition.h"
diff --git a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h index d4a8efe4..17d2818 100644 --- a/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h +++ b/chrome/browser/ui/toolbar/recent_tabs_sub_menu_model.h
@@ -10,10 +10,10 @@ #include "base/memory/weak_ptr.h" #include "base/task/cancelable_task_tracker.h" #include "base/timer/elapsed_timer.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/sessions/tab_restore_service.h" #include "chrome/browser/sessions/tab_restore_service_observer.h" #include "chrome/browser/sync/glue/synced_session.h" +#include "components/favicon/core/browser/favicon_service.h" #include "ui/base/accelerators/accelerator.h" #include "ui/base/models/simple_menu_model.h"
diff --git a/chrome/browser/ui/views/create_application_shortcut_view.cc b/chrome/browser/ui/views/create_application_shortcut_view.cc index 6361d20..50c09a6 100644 --- a/chrome/browser/ui/views/create_application_shortcut_view.cc +++ b/chrome/browser/ui/views/create_application_shortcut_view.cc
@@ -474,6 +474,7 @@ unprocessed_icons_.back().url, true, // is a favicon 0, // no maximum size + false, // normal cache policy base::Bind(&CreateUrlApplicationShortcutView::DidDownloadFavicon, weak_ptr_factory_.GetWeakPtr(), preferred_size));
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 4cb13b9..597d766b 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc
@@ -14,7 +14,6 @@ #include "chrome/browser/about_flags.h" #include "chrome/browser/bookmarks/enhanced_bookmarks_features.h" #include "chrome/browser/dom_distiller/dom_distiller_service_factory.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/about_ui.h" @@ -61,6 +60,7 @@ #include "components/dom_distiller/core/dom_distiller_service.h" #include "components/dom_distiller/core/url_constants.h" #include "components/dom_distiller/webui/dom_distiller_ui.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon_base/favicon_util.h" #include "components/favicon_base/select_favicon_frames.h" #include "components/history/core/browser/history_types.h"
diff --git a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc index 9b0ed48..9d4b8d1 100644 --- a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc
@@ -245,6 +245,8 @@ command_line->AppendSwitchASCII(switches::kGaiaEndpointChromeOS, kMinuteMaidPath); } + } else { + params.SetBoolean("useMinuteMaid", false); } if (!command_line->HasSwitch(::switches::kGaiaUrl) &&
diff --git a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc index 6d72a2da..c5dc415c 100644 --- a/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/signin_screen_handler.cc
@@ -359,6 +359,7 @@ builder->Add("shutDown", IDS_SHUTDOWN_BUTTON); builder->Add("addUser", IDS_ADD_USER_BUTTON); builder->Add("browseAsGuest", IDS_GO_INCOGNITO_BUTTON); + builder->Add("addSupervisedUser", IDS_CREATE_SUPERVISED_USER_MENU_LABEL); builder->Add("cancel", IDS_CANCEL); builder->Add("signOutUser", IDS_SCREEN_LOCK_SIGN_OUT); builder->Add("offlineLogin", IDS_OFFLINE_LOGIN_HTML);
diff --git a/chrome/browser/ui/webui/extensions/extension_icon_source.h b/chrome/browser/ui/webui/extensions/extension_icon_source.h index 2d00c56..5f25cbc 100644 --- a/chrome/browser/ui/webui/extensions/extension_icon_source.h +++ b/chrome/browser/ui/webui/extensions/extension_icon_source.h
@@ -11,7 +11,7 @@ #include "base/basictypes.h" #include "base/memory/weak_ptr.h" #include "base/task/cancelable_task_tracker.h" -#include "chrome/browser/favicon/favicon_service.h" +#include "components/favicon/core/browser/favicon_service.h" #include "content/public/browser/url_data_source.h" #include "extensions/common/extension_icon_set.h" #include "extensions/common/extension_resource.h"
diff --git a/chrome/browser/ui/webui/extensions/extension_settings_browsertest.js b/chrome/browser/ui/webui/extensions/extension_settings_browsertest.js index d7d258c2..9f1b867 100644 --- a/chrome/browser/ui/webui/extensions/extension_settings_browsertest.js +++ b/chrome/browser/ui/webui/extensions/extension_settings_browsertest.js
@@ -95,7 +95,9 @@ this.enableDeveloperMode(testDone); }); -TEST_F('AsyncExtensionSettingsWebUITest', 'testErrorListButtonVisibility', +// Often times out on all platforms: http://crbug.com/467528 +TEST_F('AsyncExtensionSettingsWebUITest', + 'DISABLED_testErrorListButtonVisibility', function() { this.enableDeveloperMode(function() { // 2 extensions are loaded:
diff --git a/chrome/browser/ui/webui/favicon_source.h b/chrome/browser/ui/webui/favicon_source.h index 16c0bbd..ef4df8d5 100644 --- a/chrome/browser/ui/webui/favicon_source.h +++ b/chrome/browser/ui/webui/favicon_source.h
@@ -11,7 +11,7 @@ #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/task/cancelable_task_tracker.h" -#include "chrome/browser/favicon/favicon_service.h" +#include "components/favicon/core/browser/favicon_service.h" #include "content/public/browser/url_data_source.h" #include "ui/gfx/favicon_size.h"
diff --git a/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc b/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc index c4317bf..96ad578 100644 --- a/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc +++ b/chrome/browser/ui/webui/net_internals/net_internals_ui_browsertest.cc
@@ -9,6 +9,7 @@ #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/files/scoped_file.h" #include "base/prefs/pref_service.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -277,20 +278,21 @@ base::FilePath temp_file; ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_directory.path(), &temp_file)); - FILE* temp_file_handle = base::OpenFile(temp_file, "w"); + base::ScopedFILE temp_file_handle(base::OpenFile(temp_file, "w")); ASSERT_TRUE(temp_file_handle); scoped_ptr<base::Value> constants(NetInternalsUI::GetConstants()); - scoped_ptr<net::NetLogLogger> net_log_logger(new net::NetLogLogger( - temp_file_handle, *constants)); - net_log_logger->StartObserving(g_browser_process->net_log()); + scoped_ptr<net::NetLogLogger> net_log_logger(new net::NetLogLogger()); + net_log_logger->StartObserving( + g_browser_process->net_log(), temp_file_handle.Pass(), constants.get(), + nullptr); g_browser_process->net_log()->AddGlobalEntry( net::NetLog::TYPE_NETWORK_IP_ADDRESSES_CHANGED); net::BoundNetLog bound_net_log = net::BoundNetLog::Make( g_browser_process->net_log(), net::NetLog::SOURCE_URL_REQUEST); bound_net_log.BeginEvent(net::NetLog::TYPE_REQUEST_ALIVE); - net_log_logger->StopObserving(); + net_log_logger->StopObserving(nullptr); net_log_logger.reset(); std::string log_contents;
diff --git a/chrome/browser/ui/webui/ntp/app_launcher_handler.h b/chrome/browser/ui/webui/ntp/app_launcher_handler.h index 832108b..daf392b5 100644 --- a/chrome/browser/ui/webui/ntp/app_launcher_handler.h +++ b/chrome/browser/ui/webui/ntp/app_launcher_handler.h
@@ -13,9 +13,9 @@ #include "base/prefs/pref_change_registrar.h" #include "base/task/cancelable_task_tracker.h" #include "chrome/browser/extensions/extension_uninstall_dialog.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/ui/extensions/extension_enable_flow_delegate.h" #include "chrome/common/extensions/extension_constants.h" +#include "components/favicon/core/browser/favicon_service.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_ui_message_handler.h"
diff --git a/chrome/browser/ui/webui/ntp/favicon_webui_handler.cc b/chrome/browser/ui/webui/ntp/favicon_webui_handler.cc index a07e6599..2a999110 100644 --- a/chrome/browser/ui/webui/ntp/favicon_webui_handler.cc +++ b/chrome/browser/ui/webui/ntp/favicon_webui_handler.cc
@@ -11,11 +11,11 @@ #include "base/strings/stringprintf.h" #include "base/values.h" #include "chrome/browser/extensions/extension_icon_manager.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/top_sites_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/core/browser/top_sites.h" #include "content/public/browser/web_ui.h" #include "extensions/browser/extension_registry.h"
diff --git a/chrome/browser/ui/webui/options/content_settings_handler.cc b/chrome/browser/ui/webui/options/content_settings_handler.cc index 650861f..b568f01 100644 --- a/chrome/browser/ui/webui/options/content_settings_handler.cc +++ b/chrome/browser/ui/webui/options/content_settings_handler.cc
@@ -316,7 +316,7 @@ {"javascript_header", IDS_JAVASCRIPT_HEADER}, {"javascriptAllow", IDS_JS_ALLOW_RADIO}, {"javascriptBlock", IDS_JS_DONOTALLOW_RADIO}, - // Plug-ins filter. + // Plugins filter. {"pluginsTabLabel", IDS_PLUGIN_TAB_LABEL}, {"plugins_header", IDS_PLUGIN_HEADER}, {"pluginsAllow", IDS_PLUGIN_ALLOW_RADIO},
diff --git a/chrome/browser/ui/webui/plugins_ui.cc b/chrome/browser/ui/webui/plugins_ui.cc index 4224902..de945d1 100644 --- a/chrome/browser/ui/webui/plugins_ui.cc +++ b/chrome/browser/ui/webui/plugins_ui.cc
@@ -174,8 +174,8 @@ content::NotificationRegistrar registrar_; - // Holds grouped plug-ins. The key is the group identifier and - // the value is the list of plug-ins belonging to the group. + // Holds grouped plugins. The key is the group identifier and + // the value is the list of plugins belonging to the group. typedef base::hash_map<std::string, std::vector<const WebPluginInfo*> > PluginGroups; @@ -226,7 +226,7 @@ void PluginsDOMHandler::HandleEnablePluginMessage(const base::ListValue* args) { Profile* profile = Profile::FromWebUI(web_ui()); - // Be robust in accepting badness since plug-ins display HTML (hence + // Be robust in accepting badness since plugins display HTML (hence // JavaScript). if (args->GetSize() != 3) { NOTREACHED(); @@ -310,7 +310,7 @@ plugin, allowed ? CONTENT_SETTING_ALLOW : CONTENT_SETTING_DEFAULT); - // Keep track of the whitelist separately, so that we can distinguish plug-ins + // Keep track of the whitelist separately, so that we can distinguish plugins // whitelisted by the user from automatically whitelisted ones. DictionaryPrefUpdate update(profile->GetPrefs(), prefs::kContentSettingsPluginWhitelist); @@ -341,8 +341,8 @@ ContentSettingsPattern wildcard = ContentSettingsPattern::Wildcard(); PluginFinder* plugin_finder = PluginFinder::GetInstance(); - // Group plug-ins by identifier. This is done to be able to display - // the plug-ins in UI in a grouped fashion. + // Group plugins by identifier. This is done to be able to display + // the plugins in UI in a grouped fashion. PluginGroups groups; for (size_t i = 0; i < plugins.size(); ++i) { scoped_ptr<PluginMetadata> plugin(
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc b/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc index b821530..f39fd8a 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc
@@ -567,13 +567,13 @@ // If some profile, not just the current one, is already connected to this // account, don't show the infobar. if (g_browser_process && !same_email) { - ProfileManager* manager = g_browser_process->profile_manager(); - if (manager) { - ProfileInfoCache& cache = manager->GetProfileInfoCache(); + ProfileManager* profile_manager = g_browser_process->profile_manager(); + if (profile_manager) { + ProfileInfoCache& cache = profile_manager->GetProfileInfoCache(); for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i) { - std::string current_email = + std::string profile_email = base::UTF16ToUTF8(cache.GetUserNameOfProfileAtIndex(i)); - if (gaia::AreEmailsSame(email, current_email)) { + if (gaia::AreEmailsSame(email, profile_email)) { if (error_message) { error_message->assign( l10n_util::GetStringUTF8(IDS_SYNC_USER_NAME_IN_USE_ERROR));
diff --git a/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc b/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc index 1a4afa6..186dd0e 100644 --- a/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc +++ b/chrome/browser/ui/webui/signin/user_manager_screen_handler.cc
@@ -626,6 +626,8 @@ l10n_util::GetStringUTF16(IDS_GO_INCOGNITO_BUTTON)); localized_strings->SetString("signOutUser", l10n_util::GetStringUTF16(IDS_SCREEN_LOCK_SIGN_OUT)); + localized_strings->SetString("addSupervisedUser", + l10n_util::GetStringUTF16(IDS_CREATE_SUPERVISED_USER_MENU_LABEL)); // For AccountPickerScreen. localized_strings->SetString("screenType", "login-add-user");
diff --git a/chrome/browser/web_applications/update_shortcut_worker_win.cc b/chrome/browser/web_applications/update_shortcut_worker_win.cc index 395c4eb..a1f5985 100644 --- a/chrome/browser/web_applications/update_shortcut_worker_win.cc +++ b/chrome/browser/web_applications/update_shortcut_worker_win.cc
@@ -89,6 +89,7 @@ unprocessed_icons_.back().url, true, // favicon 0, // no maximum size + false, // normal cache policy base::Bind(&UpdateShortcutWorker::DidDownloadFavicon, base::Unretained(this), preferred_size));
diff --git a/chrome/chrome_browser.gypi b/chrome/chrome_browser.gypi index 58357d19..f55705689 100644 --- a/chrome/chrome_browser.gypi +++ b/chrome/chrome_browser.gypi
@@ -594,10 +594,10 @@ 'browser/push_messaging/push_messaging_permission_context.h', 'browser/push_messaging/push_messaging_permission_context_factory.cc', 'browser/push_messaging/push_messaging_permission_context_factory.h', + 'browser/push_messaging/push_messaging_service_factory.cc', + 'browser/push_messaging/push_messaging_service_factory.h', 'browser/push_messaging/push_messaging_service_impl.cc', 'browser/push_messaging/push_messaging_service_impl.h', - 'browser/push_messaging/push_messaging_service_factory.h', - 'browser/push_messaging/push_messaging_service_factory.cc', 'browser/renderer_context_menu/context_menu_content_type_factory.cc', 'browser/renderer_context_menu/context_menu_content_type_factory.h', 'browser/renderer_context_menu/context_menu_content_type_panel.cc', @@ -900,10 +900,10 @@ 'browser/download/download_shelf.h', 'browser/download/download_shelf_context_menu.cc', 'browser/download/download_shelf_context_menu.h', - 'browser/download/notification/download_notification_item.h', 'browser/download/notification/download_notification_item.cc', - 'browser/download/notification/download_notification_manager.h', + 'browser/download/notification/download_notification_item.h', 'browser/download/notification/download_notification_manager.cc', + 'browser/download/notification/download_notification_manager.h', 'browser/external_protocol/external_protocol_observer.cc', 'browser/external_protocol/external_protocol_observer.h', 'browser/feedback/feedback_profile_observer.cc', @@ -1531,15 +1531,10 @@ 'browser/favicon/chrome_favicon_client.h', 'browser/favicon/chrome_favicon_client_factory.cc', 'browser/favicon/chrome_favicon_client_factory.h', - 'browser/favicon/favicon_handler.cc', - 'browser/favicon/favicon_handler.h', - 'browser/favicon/favicon_service.cc', - 'browser/favicon/favicon_service.h', 'browser/favicon/favicon_service_factory.cc', 'browser/favicon/favicon_service_factory.h', 'browser/favicon/favicon_tab_helper.cc', 'browser/favicon/favicon_tab_helper.h', - 'browser/favicon/favicon_tab_helper_observer.h', ], 'chrome_browser_gnome_keyring_sources': [ 'browser/password_manager/native_backend_gnome_x.cc', @@ -2546,8 +2541,6 @@ 'browser/signin/chrome_signin_client_factory.h', 'browser/signin/local_auth.cc', 'browser/signin/local_auth.h', - 'browser/signin/principals_message_filter.cc', - 'browser/signin/principals_message_filter.h', 'browser/signin/profile_identity_provider.cc', 'browser/signin/profile_identity_provider.h', 'browser/signin/profile_oauth2_token_service_factory.cc', @@ -2928,7 +2921,7 @@ '../components/components.gyp:domain_reliability', '../components/components.gyp:enhanced_bookmarks', '../components/components.gyp:favicon_base', - '../components/components.gyp:favicon_core', + '../components/components.gyp:favicon_core_browser', '../components/components.gyp:feedback_component', '../components/components.gyp:gcm_driver', '../components/components.gyp:google_core_browser',
diff --git a/chrome/chrome_dll_bundle.gypi b/chrome/chrome_dll_bundle.gypi index 5a7ed541..18996b9 100644 --- a/chrome/chrome_dll_bundle.gypi +++ b/chrome/chrome_dll_bundle.gypi
@@ -183,7 +183,7 @@ }, { # This file is used by the component installer. - # It is not a complete plug-in on its own. + # It is not a complete plugin on its own. 'destination': '<(PRODUCT_DIR)/$(CONTENTS_FOLDER_PATH)/Internet Plug-Ins/', 'files': [], 'conditions': [
diff --git a/chrome/chrome_renderer.gypi b/chrome/chrome_renderer.gypi index b60c629b..fc7ea3a6 100644 --- a/chrome/chrome_renderer.gypi +++ b/chrome/chrome_renderer.gypi
@@ -52,8 +52,6 @@ 'renderer/prerender/prerender_helper.h', 'renderer/prerender/prerenderer_client.cc', 'renderer/prerender/prerenderer_client.h', - 'renderer/principals_extension_bindings.cc', - 'renderer/principals_extension_bindings.h', 'renderer/searchbox/search_bouncer.cc', 'renderer/searchbox/search_bouncer.h', 'renderer/searchbox/searchbox.cc',
diff --git a/chrome/chrome_tests.gypi b/chrome/chrome_tests.gypi index d5fc5c7..eeb311b 100644 --- a/chrome/chrome_tests.gypi +++ b/chrome/chrome_tests.gypi
@@ -290,6 +290,7 @@ 'browser/extensions/window_open_apitest.cc', 'browser/external_extension_browsertest.cc', 'browser/fast_shutdown_browsertest.cc', + 'browser/favicon/favicon_tab_helper_browsertest.cc', 'browser/first_run/first_run_browsertest.cc', 'browser/first_run/try_chrome_dialog_view_browsertest.cc', 'browser/geolocation/access_token_store_browsertest.cc',
diff --git a/chrome/common/chrome_switches.cc b/chrome/common/chrome_switches.cc index a8d9094..94905fe 100644 --- a/chrome/common/chrome_switches.cc +++ b/chrome/common/chrome_switches.cc
@@ -54,7 +54,7 @@ // Don't block outdated plugins. const char kAllowOutdatedPlugins[] = "allow-outdated-plugins"; -// By default, an https page cannot run JavaScript, CSS or plug-ins from http +// By default, an https page cannot run JavaScript, CSS or plugins from http // URLs. This provides an override to get the old insecure behavior. const char kAllowRunningInsecureContent[] = "allow-running-insecure-content"; @@ -65,7 +65,7 @@ "alternate-protocol-probability-threshold"; // Prevents Chrome from requiring authorization to run certain widely installed -// but less commonly used plug-ins. +// but less commonly used plugins. const char kAlwaysAuthorizePlugins[] = "always-authorize-plugins"; // Specifies that the extension-app with the specified id should be launched @@ -565,10 +565,6 @@ // Enable SPDY/4, aka HTTP/2. This is a temporary testing flag. const char kEnableSpdy4[] = "enable-spdy4"; -// Enables a feature that holds back some SSLConnectJobs in order to -// minimize the number of full SSL handshakes completed. -const char kEnableSSLConnectJobWaiting[] = "enable-ssl-connect-job-waiting"; - // 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.
diff --git a/chrome/common/chrome_switches.h b/chrome/common/chrome_switches.h index bc85333..71d3b416 100644 --- a/chrome/common/chrome_switches.h +++ b/chrome/common/chrome_switches.h
@@ -165,7 +165,6 @@ extern const char kEnableSettingsWindow[]; extern const char kDisableSettingsWindow[]; extern const char kEnableSpdy4[]; -extern const char kEnableSSLConnectJobWaiting[]; extern const char kEnableStaleWhileRevalidate[]; extern const char kEnableSuggestionsService[]; extern const char kEnableSupervisedUserBlacklist[];
diff --git a/chrome/common/extensions/api/content_settings.json b/chrome/common/extensions/api/content_settings.json index a8b70da..b44bff59f 100644 --- a/chrome/common/extensions/api/content_settings.json +++ b/chrome/common/extensions/api/content_settings.json
@@ -5,7 +5,7 @@ [ { "namespace": "contentSettings", - "description": "Use the <code>chrome.contentSettings</code> API to change settings that control whether websites can use features such as cookies, JavaScript, and plug-ins. More generally speaking, content settings allow you to customize Chrome's behavior on a per-site basis instead of globally.", + "description": "Use the <code>chrome.contentSettings</code> API to change settings that control whether websites can use features such as cookies, JavaScript, and plugins. More generally speaking, content settings allow you to customize Chrome's behavior on a per-site basis instead of globally.", "compiler_options": { "generate_type_functions": true }, @@ -207,7 +207,7 @@ }, "plugins": { "$ref": "ContentSetting", - "description": "Whether to run plug-ins. One of<br><var>allow</var>: Run plug-ins automatically,<br><var>block</var>: Don't run plug-ins automatically. <br>Default is <var>allow</var>.<br>The primary URL is the URL of the top-level frame. The secondary URL is not used.", + "description": "Whether to run plugins. One of<br><var>allow</var>: Run plugins automatically,<br><var>block</var>: Don't run plugins automatically. <br>Default is <var>allow</var>.<br>The primary URL is the URL of the top-level frame. The secondary URL is not used.", "value": [ "plugins", {"type":"string", "enum": ["allow", "block"]} @@ -247,7 +247,7 @@ }, "unsandboxedPlugins": { "$ref": "ContentSetting", - "description": "Whether to allow sites to run plug-ins unsandboxed. One of <br><var>allow</var>: Allow sites to run plug-ins unsandboxed,<br><var>block</var>: Don't allow sites to run plug-ins unsandboxed,<br><var>ask</var>: Ask when a site wants to run a plug-in unsandboxed. <br>Default is <var>ask</var>.<br>The primary URL is the URL of the top-level frame. The secondary URL is not used.", + "description": "Whether to allow sites to run plugins unsandboxed. One of <br><var>allow</var>: Allow sites to run plugins unsandboxed,<br><var>block</var>: Don't allow sites to run plugins unsandboxed,<br><var>ask</var>: Ask when a site wants to run a plugin unsandboxed. <br>Default is <var>ask</var>.<br>The primary URL is the URL of the top-level frame. The secondary URL is not used.", "value": [ "ppapi-broker", {"type":"string", "enum": ["allow", "block", "ask"]}
diff --git a/chrome/common/extensions/docs/examples/api/contentSettings/popup.html b/chrome/common/extensions/docs/examples/api/contentSettings/popup.html index bbc62c52..71b9ce3f 100644 --- a/chrome/common/extensions/docs/examples/api/contentSettings/popup.html +++ b/chrome/common/extensions/docs/examples/api/contentSettings/popup.html
@@ -32,7 +32,7 @@ <option value="ask">Ask</option> <option value="block">Block</option> </select></dd> - <dt><label for="plugins">Plug-ins: </label></dt> + <dt><label for="plugins">Plugins: </label></dt> <dd><select id="plugins" disabled> <option value="allow">Allow</option> <option value="block">Block</option> @@ -71,7 +71,7 @@ <option value="ask">Ask</option> <option value="block">Block</option> </select></dd> - <dt><label for="unsandboxedPlugins">Unsandboxed plug-in access: </label></dt> + <dt><label for="unsandboxedPlugins">Unsandboxed plugin access: </label></dt> <dd><select id="unsandboxedPlugins" disabled> <option value="allow">Allow</option> <option value="ask">Ask</option>
diff --git a/chrome/common/extensions/docs/examples/extensions/plugin_settings/_locales/en/messages.json b/chrome/common/extensions/docs/examples/extensions/plugin_settings/_locales/en/messages.json index 95524bd..f2bd7f5 100644 --- a/chrome/common/extensions/docs/examples/extensions/plugin_settings/_locales/en/messages.json +++ b/chrome/common/extensions/docs/examples/extensions/plugin_settings/_locales/en/messages.json
@@ -3,7 +3,7 @@ "message": "Per-plugin content settings" }, "extDescription": { - "message": "Customize your content setting for different plug-ins." + "message": "Customize your content setting for different plugins." }, "patternColumnHeader": { "message": "Hostname Pattern"
diff --git a/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/chrome_stubs.js b/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/chrome_stubs.js index 51058d68..63e61b2 100644 --- a/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/chrome_stubs.js +++ b/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/chrome_stubs.js
@@ -48,7 +48,7 @@ } /** - * Creates a new Settings object with a set of rules for a dummy plug-in. + * Creates a new Settings object with a set of rules for a dummy plugin. * Because we provide stub implementations for the Chrome contentSettings * extension API, we know that the methods will execute immediately instead of * asynchronously.
diff --git a/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/main.js b/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/main.js index d86c9f5..c731ff737 100644 --- a/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/main.js +++ b/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/main.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. /** - * @fileoverview Main entry point that creates a new plug-in list on document + * @fileoverview Main entry point that creates a new plugin list on document * load. */
diff --git a/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/plugin_list.js b/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/plugin_list.js index 050cacce..a0dff4c7 100644 --- a/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/plugin_list.js +++ b/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/plugin_list.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. /** - * @fileoverview Defines a list of plug-ins that shows for each plug-in a list + * @fileoverview Defines a list of plugins that shows for each plugin a list * of content setting rules. */ @@ -24,27 +24,27 @@ HIDDEN: 'hidden', /** - * A plug-in list. + * A plugin list. */ PLUGIN_LIST: 'plugin-list', /** - * Set on a plug-in list entry to show details about the plug-in. + * Set on a plugin list entry to show details about the plugin. */ PLUGIN_SHOW_DETAILS: 'plugin-show-details', /** - * The plug-in name. + * The plugin name. */ PLUGIN_NAME: 'plugin-name', /** - * The number of rules set for a plug-in. + * The number of rules set for a plugin. */ NUM_RULES: 'num-rules', /** - * The element containing details about a plug-in. + * The element containing details about a plugin. */ PLUGIN_DETAILS: 'plugin-details', @@ -82,9 +82,9 @@ } /** - * Creates a new plug-in list item element. - * @param {!PluginList} list The plug-in list containing this item. - * @param {!Object} info Information about the plug-in. + * Creates a new plugin list item element. + * @param {!PluginList} list The plugin list containing this item. + * @param {!Object} info Information about the plugin. * @constructor * @extends {cr.ui.ListItem} */ @@ -92,14 +92,14 @@ var el = cr.doc.createElement('li'); /** - * The plug-in list containing this item. + * The plugin list containing this item. * @type {!PluginList} * @private */ el.list_ = list; /** - * Information about the plug-in. + * Information about the plugin. * @type {!Object} * @private */ @@ -114,7 +114,7 @@ __proto__: ListItem.prototype, /** - * The element containing details about the plug-in. This is only null in + * The element containing details about the plugin. This is only null in * the prototype. * @type {?HTMLDivElement} * @private @@ -175,7 +175,7 @@ }, /** - * Create the list of content setting rules applying to this plug-in. + * Create the list of content setting rules applying to this plugin. * @param {!pluginSettings.Settings} The settings object storing the content * setting rules. * @private @@ -237,7 +237,7 @@ }; /** - * Creates a new plug-in list. + * Creates a new plugin list. * @constructor * @extends {cr.ui.List} */ @@ -259,8 +259,8 @@ }, /** - * Creates a new plug-in list item. - * @param {!Object} info Information about the plug-in. + * Creates a new plugin list item. + * @param {!Object} info Information about the plugin. */ createItem: function(info) { return new PluginListItem(this, info);
diff --git a/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/plugin_settings.js b/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/plugin_settings.js index 0b2923e6..1727356 100644 --- a/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/plugin_settings.js +++ b/chrome/common/extensions/docs/examples/extensions/plugin_settings/js/plugin_settings.js
@@ -12,14 +12,14 @@ /** * Creates a new content settings model. - * @param {string} plugin Identifies the plug-in for which this object stores + * @param {string} plugin Identifies the plugin for which this object stores * settings. * @constructor * @extends {cr.EventTarget} */ function Settings(plugin) { /** - * Identifies the plug-in for which this object stores settings. + * Identifies the plugin for which this object stores settings. * @type {string} * @private */ @@ -195,7 +195,7 @@ }, /** - * @return {!Array} A list of all content setting rules for this plug-in. + * @return {!Array} A list of all content setting rules for this plugin. */ getAll: function() { var rules = [];
diff --git a/chrome/common/extensions/docs/templates/articles/permission_warnings.html b/chrome/common/extensions/docs/templates/articles/permission_warnings.html index 6079fac5..ad5bf62 100644 --- a/chrome/common/extensions/docs/templates/articles/permission_warnings.html +++ b/chrome/common/extensions/docs/templates/articles/permission_warnings.html
@@ -216,7 +216,7 @@ <tr> <td style="font-weight:bold"> <!-- IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS --> - Manipulate settings that specify whether websites can use features such as cookies, JavaScript, plug-ins, geolocation, microphone, camera etc. + Manipulate settings that specify whether websites can use features such as cookies, JavaScript, plugins, geolocation, microphone, camera etc. </td> <td> <!-- HasEffectiveBrowsingHistoryPermission -->
diff --git a/chrome/common/extensions/docs/templates/intros/contentSettings.html b/chrome/common/extensions/docs/templates/intros/contentSettings.html index 343b0a7..02a480e 100644 --- a/chrome/common/extensions/docs/templates/intros/contentSettings.html +++ b/chrome/common/extensions/docs/templates/intros/contentSettings.html
@@ -115,10 +115,10 @@ Resource identifiers allow you to specify content settings for specific subtypes of a content type. Currently, the only content type that supports resource identifiers is $(ref:contentSettings.plugins), -where a resource identifier identifies a specific plug-in. When applying content -settings, first the settings for the specific plug-in are checked. If there are -no settings found for the specific plug-in, the general content settings for -plug-ins are checked. +where a resource identifier identifies a specific plugin. When applying content +settings, first the settings for the specific plugin are checked. If there are +no settings found for the specific plugin, the general content settings for +plugins are checked. </p> <p> For example, if a content setting rule has the resource identifier @@ -129,8 +129,8 @@ <p> You can get a list of resource identifiers for a content type by calling the $(ref:contentSettings.ContentSetting.getResourceIdentifiers) method. The returned list -can change with the set of installed plug-ins on the user's machine, but Chrome -tries to keep the identifiers stable across plug-in updates. +can change with the set of installed plugins on the user's machine, but Chrome +tries to keep the identifiers stable across plugin updates. </p> <h2 id="examples">Examples</h2>
diff --git a/chrome/common/extensions/permissions/chrome_permission_message_provider.cc b/chrome/common/extensions/permissions/chrome_permission_message_provider.cc index d5ceeea..0ed371e 100644 --- a/chrome/common/extensions/permissions/chrome_permission_message_provider.cc +++ b/chrome/common/extensions/permissions/chrome_permission_message_provider.cc
@@ -5,6 +5,7 @@ #include "chrome/common/extensions/permissions/chrome_permission_message_provider.h" #include "base/memory/scoped_vector.h" +#include "base/metrics/field_trial.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -24,6 +25,12 @@ namespace { +bool IsNewPermissionMessageSystemEnabled() { + const std::string group_name = + base::FieldTrialList::FindFullName("PermissionMessageSystem"); + return group_name == "NewSystem"; +} + typedef std::set<PermissionMessage> PermissionMsgSet; template<typename T> @@ -155,6 +162,40 @@ return messages; } +PermissionMessageStrings +ChromePermissionMessageProvider::GetPermissionMessageStrings( + const PermissionSet* permissions, + Manifest::Type extension_type) const { + PermissionMessageStrings strings; + if (IsNewPermissionMessageSystemEnabled()) { + CoalescedPermissionMessages messages = GetCoalescedPermissionMessages( + GetAllPermissionIDs(permissions, extension_type)); + for (const CoalescedPermissionMessage& msg : messages) + strings.push_back(PermissionMessageString(msg)); + } else { + std::vector<base::string16> messages = + GetLegacyWarningMessages(permissions, extension_type); + std::vector<base::string16> details = + GetLegacyWarningMessagesDetails(permissions, extension_type); + DCHECK_EQ(messages.size(), details.size()); + for (size_t i = 0; i < messages.size(); i++) + strings.push_back(PermissionMessageString(messages[i], details[i])); + } + return strings; +} + +PermissionMessageIDs +ChromePermissionMessageProvider::GetLegacyPermissionMessageIDs( + const PermissionSet* permissions, + Manifest::Type extension_type) const { + PermissionMessageIDs ids; + for (const PermissionMessage& msg : + GetPermissionMessages(permissions, extension_type)) { + ids.push_back(msg.id()); + } + return ids; +} + CoalescedPermissionMessages ChromePermissionMessageProvider::GetCoalescedPermissionMessages( const PermissionIDSet& permissions) const { @@ -185,7 +226,8 @@ return messages; } -std::vector<base::string16> ChromePermissionMessageProvider::GetWarningMessages( +std::vector<base::string16> +ChromePermissionMessageProvider::GetLegacyWarningMessages( const PermissionSet* permissions, Manifest::Type extension_type) const { std::vector<base::string16> message_strings; @@ -198,7 +240,7 @@ } std::vector<base::string16> -ChromePermissionMessageProvider::GetWarningMessagesDetails( +ChromePermissionMessageProvider::GetLegacyWarningMessagesDetails( const PermissionSet* permissions, Manifest::Type extension_type) const { std::vector<base::string16> message_strings;
diff --git a/chrome/common/extensions/permissions/chrome_permission_message_provider.h b/chrome/common/extensions/permissions/chrome_permission_message_provider.h index 068d8bd..a734ab0 100644 --- a/chrome/common/extensions/permissions/chrome_permission_message_provider.h +++ b/chrome/common/extensions/permissions/chrome_permission_message_provider.h
@@ -26,15 +26,21 @@ ~ChromePermissionMessageProvider() override; // PermissionMessageProvider implementation. - PermissionMessages GetPermissionMessages( + // See comments in permission_message_provider.h. TL;DR: You want to use only + // GetPermissionMessageStrings to get messages, not the *Legacy* or + // *Coalesced* methods. + PermissionMessageStrings GetPermissionMessageStrings( + const PermissionSet* permissions, + Manifest::Type extension_type) const override; + PermissionMessageIDs GetLegacyPermissionMessageIDs( const PermissionSet* permissions, Manifest::Type extension_type) const override; CoalescedPermissionMessages GetCoalescedPermissionMessages( const PermissionIDSet& permissions) const override; - std::vector<base::string16> GetWarningMessages( + std::vector<base::string16> GetLegacyWarningMessages( const PermissionSet* permissions, Manifest::Type extension_type) const override; - std::vector<base::string16> GetWarningMessagesDetails( + std::vector<base::string16> GetLegacyWarningMessagesDetails( const PermissionSet* permissions, Manifest::Type extension_type) const override; bool IsPrivilegeIncrease(const PermissionSet* old_permissions, @@ -45,6 +51,10 @@ Manifest::Type extension_type) const override; private: + // TODO(treib): Remove this once we've switched to the new system. + PermissionMessages GetPermissionMessages(const PermissionSet* permissions, + Manifest::Type extension_type) const; + // Gets the permission messages for the API permissions. Also adds any // permission IDs from API Permissions to |permission_ids|. // TODO(sashab): Deprecate the |permissions| argument, and rename this to
diff --git a/chrome/common/extensions/permissions/chrome_permission_message_provider_unittest.cc b/chrome/common/extensions/permissions/chrome_permission_message_provider_unittest.cc index e36e4bc..d215b84 100644 --- a/chrome/common/extensions/permissions/chrome_permission_message_provider_unittest.cc +++ b/chrome/common/extensions/permissions/chrome_permission_message_provider_unittest.cc
@@ -36,15 +36,16 @@ Manifest::Type type) { scoped_refptr<const PermissionSet> permission_set = new PermissionSet( permissions, ManifestPermissionSet(), URLPatternSet(), URLPatternSet()); - return message_provider_->GetWarningMessages(permission_set.get(), type); + return message_provider_->GetLegacyWarningMessages(permission_set.get(), + type); } std::vector<base::string16> GetDetails(const APIPermissionSet& permissions, Manifest::Type type) { scoped_refptr<const PermissionSet> permission_set = new PermissionSet( permissions, ManifestPermissionSet(), URLPatternSet(), URLPatternSet()); - return message_provider_->GetWarningMessagesDetails(permission_set.get(), - type); + return message_provider_->GetLegacyWarningMessagesDetails( + permission_set.get(), type); } private:
diff --git a/chrome/common/extensions/permissions/permission_set_unittest.cc b/chrome/common/extensions/permissions/permission_set_unittest.cc index e101bff2..c5b42e9 100644 --- a/chrome/common/extensions/permissions/permission_set_unittest.cc +++ b/chrome/common/extensions/permissions/permission_set_unittest.cc
@@ -802,17 +802,11 @@ scoped_refptr<PermissionSet> permissions( new PermissionSet(api_permissions, ManifestPermissionSet(), URLPatternSet(), URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_PLATFORM_APP); - ASSERT_EQ(1u, messages.size()); - std::sort(messages.begin(), messages.end()); - std::set<PermissionMessage::ID> ids; - for (PermissionMessages::const_iterator it = messages.begin(); - it != messages.end(); ++it) { - ids.insert(it->id()); - } - EXPECT_TRUE(ContainsKey(ids, PermissionMessage::kFileSystemDirectory)); + ASSERT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kFileSystemDirectory, ids[0]); } // The file system permissions have a special-case hack to show a warning for @@ -855,11 +849,11 @@ scoped_refptr<PermissionSet> permissions( new PermissionSet(api_permissions, ManifestPermissionSet(), URLPatternSet(), URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_PLATFORM_APP); - ASSERT_EQ(1u, messages.size()); - EXPECT_EQ(PermissionMessage::kFileSystemWriteDirectory, messages[0].id()); + ASSERT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kFileSystemWriteDirectory, ids[0]); } TEST(PermissionsTest, SuppressedPermissionMessages) { @@ -873,11 +867,11 @@ scoped_refptr<PermissionSet> permissions( new PermissionSet(api_permissions, ManifestPermissionSet(), hosts, URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_EXTENSION); - EXPECT_EQ(1u, messages.size()); - EXPECT_EQ(PermissionMessage::kTabs, messages[0].id()); + EXPECT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kTabs, ids[0]); } { // History warning suppresses favicon warning. @@ -889,11 +883,11 @@ scoped_refptr<PermissionSet> permissions( new PermissionSet(api_permissions, ManifestPermissionSet(), hosts, URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_EXTENSION); - EXPECT_EQ(1u, messages.size()); - EXPECT_EQ(PermissionMessage::kBrowsingHistory, messages[0].id()); + EXPECT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kBrowsingHistory, ids[0]); } { // All sites warning suppresses tabs warning. @@ -903,11 +897,11 @@ api_permissions.insert(APIPermission::kTab); scoped_refptr<PermissionSet> permissions(new PermissionSet( api_permissions, ManifestPermissionSet(), hosts, URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_EXTENSION); - EXPECT_EQ(1u, messages.size()); - EXPECT_EQ(PermissionMessage::kHostsAll, messages[0].id()); + EXPECT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kHostsAll, ids[0]); } { // All sites warning suppresses topSites warning. @@ -917,11 +911,11 @@ api_permissions.insert(APIPermission::kTopSites); scoped_refptr<PermissionSet> permissions(new PermissionSet( api_permissions, ManifestPermissionSet(), hosts, URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_EXTENSION); - EXPECT_EQ(1u, messages.size()); - EXPECT_EQ(PermissionMessage::kHostsAll, messages[0].id()); + EXPECT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kHostsAll, ids[0]); } { // All sites warning suppresses declarativeWebRequest warning. @@ -931,11 +925,11 @@ api_permissions.insert(APIPermission::kDeclarativeWebRequest); scoped_refptr<PermissionSet> permissions(new PermissionSet( api_permissions, ManifestPermissionSet(), hosts, URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_EXTENSION); - EXPECT_EQ(1u, messages.size()); - EXPECT_EQ(PermissionMessage::kHostsAll, messages[0].id()); + EXPECT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kHostsAll, ids[0]); } { // BrowsingHistory warning suppresses all history read/write warnings. @@ -948,11 +942,11 @@ scoped_refptr<PermissionSet> permissions( new PermissionSet(api_permissions, ManifestPermissionSet(), URLPatternSet(), URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_EXTENSION); - EXPECT_EQ(1u, messages.size()); - EXPECT_EQ(PermissionMessage::kBrowsingHistory, messages[0].id()); + EXPECT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kBrowsingHistory, ids[0]); } { // Tabs warning suppresses all read-only history warnings. @@ -964,11 +958,11 @@ scoped_refptr<PermissionSet> permissions( new PermissionSet(api_permissions, ManifestPermissionSet(), URLPatternSet(), URLPatternSet())); - PermissionMessages messages = - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageIDs ids = + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_EXTENSION); - EXPECT_EQ(1u, messages.size()); - EXPECT_EQ(PermissionMessage::kTabs, messages[0].id()); + EXPECT_EQ(1u, ids.size()); + EXPECT_EQ(PermissionMessage::kTabs, ids[0]); } } @@ -982,7 +976,7 @@ URLPatternSet(), URLPatternSet())); std::vector<base::string16> messages = - PermissionMessageProvider::Get()->GetWarningMessages( + PermissionMessageProvider::Get()->GetLegacyWarningMessages( permissions.get(), Manifest::TYPE_EXTENSION); EXPECT_EQ(1u, messages.size()); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_SERIAL), @@ -999,7 +993,7 @@ URLPatternSet(), URLPatternSet())); std::vector<base::string16> messages = - PermissionMessageProvider::Get()->GetWarningMessages( + PermissionMessageProvider::Get()->GetLegacyWarningMessages( permissions.get(), Manifest::TYPE_EXTENSION); EXPECT_EQ(1u, messages.size()); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_SERIAL), @@ -1013,14 +1007,14 @@ PermissionSet* set = const_cast<PermissionSet*>( extension->permissions_data()->active_permissions().get()); std::vector<base::string16> warnings = - provider->GetWarningMessages(set, extension->GetType()); + provider->GetLegacyWarningMessages(set, extension->GetType()); EXPECT_EQ(1u, warnings.size()); EXPECT_EQ(l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT_WARNING_BLUETOOTH), warnings[0]); // Test Bluetooth and Serial set->apis_.insert(APIPermission::kSerial); - warnings = provider->GetWarningMessages(set, extension->GetType()); + warnings = provider->GetLegacyWarningMessages(set, extension->GetType()); EXPECT_EQ(1u, warnings.size()); EXPECT_EQ(l10n_util::GetStringUTF16( IDS_EXTENSION_PROMPT_WARNING_BLUETOOTH_SERIAL), @@ -1113,7 +1107,7 @@ PermissionSet* set = const_cast<PermissionSet*>( extension->permissions_data()->active_permissions().get()); std::vector<base::string16> warnings = - provider->GetWarningMessages(set, extension->GetType()); + provider->GetLegacyWarningMessages(set, extension->GetType()); EXPECT_FALSE(Contains(warnings, "Use your microphone")); EXPECT_FALSE(Contains(warnings, "Use your camera")); EXPECT_TRUE(Contains(warnings, "Use your microphone and camera")); @@ -1122,7 +1116,7 @@ // Just audio present. set->apis_.erase(APIPermission::kVideoCapture); - warnings = provider->GetWarningMessages(set, extension->GetType()); + warnings = provider->GetLegacyWarningMessages(set, extension->GetType()); EXPECT_EQ(combined_size, warnings.size()); EXPECT_EQ(combined_index, IndexOf(warnings, "Use your microphone")); EXPECT_FALSE(Contains(warnings, "Use your camera")); @@ -1131,7 +1125,7 @@ // Just video present. set->apis_.erase(APIPermission::kAudioCapture); set->apis_.insert(APIPermission::kVideoCapture); - warnings = provider->GetWarningMessages(set, extension->GetType()); + warnings = provider->GetLegacyWarningMessages(set, extension->GetType()); EXPECT_EQ(combined_size, warnings.size()); EXPECT_FALSE(Contains(warnings, "Use your microphone")); EXPECT_FALSE(Contains(warnings, "Use your microphone and camera")); @@ -1150,7 +1144,7 @@ new PermissionSet(api_permissions, ManifestPermissionSet(), URLPatternSet(), URLPatternSet())); std::vector<base::string16> messages = - PermissionMessageProvider::Get()->GetWarningMessages( + PermissionMessageProvider::Get()->GetLegacyWarningMessages( permissions.get(), Manifest::TYPE_EXTENSION); EXPECT_EQ(1u, messages.size()); EXPECT_EQ(l10n_util::GetStringUTF16( @@ -1169,7 +1163,7 @@ new PermissionSet(api_permissions, ManifestPermissionSet(), URLPatternSet(), URLPatternSet())); std::vector<base::string16> messages = - PermissionMessageProvider::Get()->GetWarningMessages( + PermissionMessageProvider::Get()->GetLegacyWarningMessages( permissions.get(), Manifest::TYPE_EXTENSION); EXPECT_EQ(1u, messages.size()); EXPECT_EQ(l10n_util::GetStringUTF16( @@ -1196,7 +1190,7 @@ const PermissionSet* set = extension->permissions_data()->active_permissions().get(); std::vector<base::string16> warnings = - provider->GetWarningMessages(set, extension->GetType()); + provider->GetLegacyWarningMessages(set, extension->GetType()); EXPECT_TRUE(Contains(warnings, "Block parts of web pages")); EXPECT_FALSE(Contains( warnings, "Read and change all your data on the websites you visit")); @@ -1206,7 +1200,7 @@ extension = LoadManifest("permissions", "web_request_all_host_permissions.json"); set = extension->permissions_data()->active_permissions().get(); - warnings = provider->GetWarningMessages(set, extension->GetType()); + warnings = provider->GetLegacyWarningMessages(set, extension->GetType()); EXPECT_FALSE(Contains(warnings, "Block parts of web pages")); EXPECT_TRUE(Contains( warnings, "Read and change all your data on the websites you visit")); @@ -1772,7 +1766,7 @@ scoped_refptr<PermissionSet> permissions( new PermissionSet(APIPermissionSet(), ManifestPermissionSet(), allowed_hosts, URLPatternSet())); - PermissionMessageProvider::Get()->GetPermissionMessages( + PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( permissions.get(), Manifest::TYPE_EXTENSION); }
diff --git a/chrome/common/logging_chrome.cc b/chrome/common/logging_chrome.cc index 04ad0e3e9..7d26587 100644 --- a/chrome/common/logging_chrome.cc +++ b/chrome/common/logging_chrome.cc
@@ -26,10 +26,11 @@ #include <windows.h> #endif -#include <fstream> - #include "chrome/common/logging_chrome.h" +#include <fstream> // NOLINT +#include <string> // NOLINT + #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/debug/debugger.h" @@ -37,14 +38,12 @@ #include "base/environment.h" #include "base/files/file_path.h" #include "base/files/file_util.h" -#include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" -#include "base/time/time.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" @@ -392,35 +391,6 @@ bool DialogsAreSuppressed() { return dialogs_are_suppressed_; } - -size_t GetFatalAssertions(AssertionList* assertions) { - // In this function, we don't assume that assertions is non-null, so - // that if you just want an assertion count, you can pass in NULL. - if (assertions) - assertions->clear(); - size_t assertion_count = 0; - - std::ifstream log_file; - log_file.open(GetLogFileName().value().c_str()); - if (!log_file.is_open()) - return 0; - - std::string utf8_line; - std::wstring wide_line; - while (!log_file.eof()) { - getline(log_file, utf8_line); - if (utf8_line.find(":FATAL:") != std::string::npos) { - wide_line = base::UTF8ToWide(utf8_line); - if (assertions) - assertions->push_back(wide_line); - ++assertion_count; - } - } - log_file.close(); - - return assertion_count; -} - base::FilePath GenerateTimestampedName(const base::FilePath& base_path, base::Time timestamp) { base::Time::Exploded time_deets;
diff --git a/chrome/common/logging_chrome.h b/chrome/common/logging_chrome.h index 07a97df..1e2f29ce 100644 --- a/chrome/common/logging_chrome.h +++ b/chrome/common/logging_chrome.h
@@ -5,9 +5,6 @@ #ifndef CHROME_COMMON_LOGGING_CHROME_H__ #define CHROME_COMMON_LOGGING_CHROME_H__ -#include <string> -#include <vector> - #include "base/logging.h" #include "base/time/time.h" @@ -51,22 +48,10 @@ // Returns the fully-qualified name of the log file. base::FilePath GetLogFileName(); -// Returns true when error/assertion dialogs are to be shown, -// false otherwise. +// Returns true when error/assertion dialogs are not to be shown, false +// otherwise. bool DialogsAreSuppressed(); -typedef std::vector<std::wstring> AssertionList; - -// Gets the list of fatal assertions in the current log file, and -// returns the number of fatal assertions. (If you don't care -// about the actual list of assertions, you can pass in NULL.) -// NOTE: Since this reads the log file to determine the assertions, -// this operation is O(n) over the length of the log. -// NOTE: This can fail if the file is locked for writing. However, -// this is unlikely as this function is most useful after -// the program writing the log has terminated. -size_t GetFatalAssertions(AssertionList* assertions); - // Inserts timestamp before file extension in the format // "_yymmdd-hhmmss". base::FilePath GenerateTimestampedName(const base::FilePath& base_path,
diff --git a/chrome/common/mac/cfbundle_blocker.h b/chrome/common/mac/cfbundle_blocker.h index 4222035..44d8677 100644 --- a/chrome/common/mac/cfbundle_blocker.h +++ b/chrome/common/mac/cfbundle_blocker.h
@@ -15,7 +15,7 @@ namespace common { namespace mac { -// Arranges to block loading of some third-party plug-in code that might try +// Arranges to block loading of some third-party plugin code that might try // to inject itself into the process. Modules loaded by CFBundle are blocked // if located within specific directories. Because NSBundle uses CFBundle // behind the scenes, this also blocks modules loaded by NSBundle when located
diff --git a/chrome/common/mac/cfbundle_blocker.mm b/chrome/common/mac/cfbundle_blocker.mm index b593ebb..3b8f69a 100644 --- a/chrome/common/mac/cfbundle_blocker.mm +++ b/chrome/common/mac/cfbundle_blocker.mm
@@ -40,7 +40,7 @@ namespace { -// Returns an autoreleased array of paths that contain plug-ins that should be +// Returns an autoreleased array of paths that contain plugins that should be // forbidden to load. Each element of the array will be a string containing // an absolute pathname ending in '/'. NSArray* BlockedPaths() { @@ -62,9 +62,9 @@ // loading things contained in these directories. NSString* const blocked_suffixes[] = { #if !defined(__LP64__) - // Contextual menu manager plug-ins are unavailable to 64-bit processes. + // Contextual menu manager plugins are unavailable to 64-bit processes. // http://developer.apple.com/library/mac/releasenotes/Cocoa/AppKitOlderNotes.html#NSMenu - // Contextual menu plug-ins are loaded when a contextual menu is opened, + // Contextual menu plugins are loaded when a contextual menu is opened, // for example, from within // +[NSMenu popUpContextMenu:withEvent:forView:]. @"Contextual Menu Items/", @@ -83,7 +83,7 @@ @"ScriptingAdditions/" // This list is intentionally incomplete. For example, it doesn't block - // printer drivers or Internet plug-ins. + // printer drivers or Internet plugins. }; NSUInteger blocked_paths_count = [blocked_prefixes count] *
diff --git a/chrome/common/mac/launchd.h b/chrome/common/mac/launchd.h index 46d4080..c43341c9 100644 --- a/chrome/common/mac/launchd.h +++ b/chrome/common/mac/launchd.h
@@ -33,9 +33,6 @@ virtual ~Launchd(); - // Return a dictionary with the launchd export settings. - virtual CFDictionaryRef CopyExports(); - // Return a dictionary with the launchd entries for job labeled |name|. virtual CFDictionaryRef CopyJobDictionary(CFStringRef label);
diff --git a/chrome/common/mac/launchd.mm b/chrome/common/mac/launchd.mm index 2474cc6..de433df 100644 --- a/chrome/common/mac/launchd.mm +++ b/chrome/common/mac/launchd.mm
@@ -87,10 +87,6 @@ Launchd::~Launchd() { } -CFDictionaryRef Launchd::CopyExports() { - return GTMCopyLaunchdExports(); -} - CFDictionaryRef Launchd::CopyJobDictionary(CFStringRef label) { return GTMSMJobCopyDictionary(label); }
diff --git a/chrome/common/mac/mock_launchd.cc b/chrome/common/mac/mock_launchd.cc index e463733e..8aebf44 100644 --- a/chrome/common/mac/mock_launchd.cc +++ b/chrome/common/mac/mock_launchd.cc
@@ -97,6 +97,7 @@ bool create_socket, bool as_service) : file_(file), + pipe_name_(GetServiceProcessChannel().name), message_loop_(loop), create_socket_(create_socket), as_service_(as_service), @@ -105,40 +106,11 @@ checkin_called_(false), write_called_(false), delete_called_(false) { - std::string pipe_suffix("_SOCKET"); - base::FilePath socket_path = file_; - while (socket_path.value().length() + pipe_suffix.length() > - kMaxPipeNameLength - 2) { - socket_path = socket_path.DirName(); - } - pipe_name_ = socket_path.value() + pipe_suffix; } MockLaunchd::~MockLaunchd() { } -CFDictionaryRef MockLaunchd::CopyExports() { - if (!create_socket_) { - ADD_FAILURE(); - return NULL; - } - - CFStringRef env_var = - base::mac::NSToCFCast(GetServiceProcessLaunchDSocketEnvVar()); - base::ScopedCFTypeRef<CFStringRef> socket_path(CFStringCreateWithCString( - kCFAllocatorDefault, pipe_name_.c_str(), kCFStringEncodingUTF8)); - const void *keys[] = { env_var }; - const void *values[] = { socket_path }; - static_assert(arraysize(keys) == arraysize(values), - "keys must have the same number of elements as values"); - return CFDictionaryCreate(kCFAllocatorDefault, - keys, - values, - arraysize(keys), - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); -} - CFDictionaryRef MockLaunchd::CopyJobDictionary(CFStringRef label) { if (!as_service_) { scoped_ptr<MultiProcessLock> running_lock(
diff --git a/chrome/common/mac/mock_launchd.h b/chrome/common/mac/mock_launchd.h index ba82009..64d37ac 100644 --- a/chrome/common/mac/mock_launchd.h +++ b/chrome/common/mac/mock_launchd.h
@@ -32,7 +32,6 @@ bool create_socket, bool as_service); ~MockLaunchd() override; - CFDictionaryRef CopyExports() override; CFDictionaryRef CopyJobDictionary(CFStringRef label) override; CFDictionaryRef CopyDictionaryByCheckingIn(CFErrorRef* error) override; bool RemoveJob(CFStringRef label, CFErrorRef* error) override;
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 61151eb1..8fd3fc5 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -954,10 +954,10 @@ const char kPluginsAlwaysAuthorize[] = "plugins.always_authorize"; #if defined(ENABLE_PLUGIN_INSTALLATION) -// Dictionary holding plug-ins metadata. +// Dictionary holding plugins metadata. const char kPluginsMetadata[] = "plugins.metadata"; -// Last update time of plug-ins resource cache. +// Last update time of plugins resource cache. const char kPluginsResourceCacheUpdate[] = "plugins.resource_cache_update"; #endif @@ -1524,7 +1524,7 @@ // Whether Extensions are enabled. const char kDisableExtensions[] = "extensions.disabled"; -// Whether the plugin finder that lets you install missing plug-ins is enabled. +// Whether the plugin finder that lets you install missing plugins is enabled. const char kDisablePluginFinder[] = "plugins.disable_plugin_finder"; // Customized app page names that appear on the New Tab Page.
diff --git a/chrome/common/render_messages.h b/chrome/common/render_messages.h index 4a000c6..6fe1581 100644 --- a/chrome/common/render_messages.h +++ b/chrome/common/render_messages.h
@@ -450,7 +450,7 @@ // Return information about a plugin for the given URL and MIME type. // In contrast to ViewHostMsg_GetPluginInfo in content/, this IPC call knows -// about specific reasons why a plug-in can't be used, for example because it's +// about specific reasons why a plugin can't be used, for example because it's // disabled. IPC_SYNC_MESSAGE_CONTROL4_1(ChromeViewHostMsg_GetPluginInfo, int /* render_frame_id */, @@ -475,42 +475,42 @@ #endif #if defined(ENABLE_PLUGIN_INSTALLATION) -// Tells the browser to search for a plug-in that can handle the given MIME +// Tells the browser to search for a plugin that can handle the given MIME // type. The result will be sent asynchronously to the routing ID // |placeholder_id|. IPC_MESSAGE_ROUTED2(ChromeViewHostMsg_FindMissingPlugin, int /* placeholder_id */, std::string /* mime_type */) -// Notifies the browser that a missing plug-in placeholder has been removed, so +// Notifies the browser that a missing plugin placeholder has been removed, so // the corresponding PluginPlaceholderHost can be deleted. IPC_MESSAGE_ROUTED1(ChromeViewHostMsg_RemovePluginPlaceholderHost, int /* placeholder_id */) -// Notifies a missing plug-in placeholder that a plug-in with name |plugin_name| +// Notifies a missing plugin placeholder that a plugin with name |plugin_name| // has been found. IPC_MESSAGE_ROUTED1(ChromeViewMsg_FoundMissingPlugin, base::string16 /* plugin_name */) -// Notifies a missing plug-in placeholder that no plug-in has been found. +// Notifies a missing plugin placeholder that no plugin has been found. IPC_MESSAGE_ROUTED0(ChromeViewMsg_DidNotFindMissingPlugin) -// Notifies a missing plug-in placeholder that we have started downloading -// the plug-in. +// Notifies a missing plugin placeholder that we have started downloading +// the plugin. IPC_MESSAGE_ROUTED0(ChromeViewMsg_StartedDownloadingPlugin) -// Notifies a missing plug-in placeholder that we have finished downloading -// the plug-in. +// Notifies a missing plugin placeholder that we have finished downloading +// the plugin. IPC_MESSAGE_ROUTED0(ChromeViewMsg_FinishedDownloadingPlugin) -// Notifies a missing plug-in placeholder that there was an error downloading -// the plug-in. +// Notifies a missing plugin placeholder that there was an error downloading +// the plugin. IPC_MESSAGE_ROUTED1(ChromeViewMsg_ErrorDownloadingPlugin, std::string /* message */) #endif // defined(ENABLE_PLUGIN_INSTALLATION) -// Notifies a missing plug-in placeholder that the user cancelled downloading -// the plug-in. +// Notifies a missing plugin placeholder that the user cancelled downloading +// the plugin. IPC_MESSAGE_ROUTED0(ChromeViewMsg_CancelledDownloadingPlugin) // Tells the browser to open chrome://plugins in a new tab. We use a separate @@ -518,11 +518,11 @@ // chrome:// URLs. IPC_MESSAGE_ROUTED0(ChromeViewHostMsg_OpenAboutPlugins) -// Tells the browser that there was an error loading a plug-in. +// Tells the browser that there was an error loading a plugin. IPC_MESSAGE_ROUTED1(ChromeViewHostMsg_CouldNotLoadPlugin, base::FilePath /* plugin_path */) -// Tells the browser that we blocked a plug-in because NPAPI is not supported. +// Tells the browser that we blocked a plugin because NPAPI is not supported. IPC_MESSAGE_ROUTED1(ChromeViewHostMsg_NPAPINotSupported, std::string /* identifer */) @@ -557,13 +557,13 @@ // Notifies when a plugin couldn't be loaded because it's outdated. IPC_MESSAGE_ROUTED2(ChromeViewHostMsg_BlockedOutdatedPlugin, int /* placeholder ID */, - std::string /* plug-in group identifier */) + std::string /* plugin group identifier */) // Notifies when a plugin couldn't be loaded because it requires // user authorization. IPC_MESSAGE_ROUTED2(ChromeViewHostMsg_BlockedUnauthorizedPlugin, base::string16 /* name */, - std::string /* plug-in group identifier */) + std::string /* plugin group identifier */) // Provide the browser process with information about the WebCore resource // cache and current renderer framerate.
diff --git a/chrome/common/service_process_util.cc b/chrome/common/service_process_util.cc index 6f9844d6..f9a990a4 100644 --- a/chrome/common/service_process_util.cc +++ b/chrome/common/service_process_util.cc
@@ -96,21 +96,6 @@ } // namespace -// Return a name that is scoped to this instance of the service process. We -// use the hash of the user-data-dir as a scoping prefix. We can't use -// the user-data-dir itself as we have limits on the size of the lock names. -std::string GetServiceProcessScopedName(const std::string& append_str) { - base::FilePath user_data_dir; - PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); -#if defined(OS_WIN) - std::string user_data_dir_path = base::WideToUTF8(user_data_dir.value()); -#elif defined(OS_POSIX) - std::string user_data_dir_path = user_data_dir.value(); -#endif // defined(OS_WIN) - std::string hash = base::SHA1HashString(user_data_dir_path); - std::string hex_hash = base::HexEncode(hash.c_str(), hash.length()); - return hex_hash + "." + append_str; -} // Return a name that is scoped to this instance of the service process. We // use the user-data-dir and the version as a scoping prefix. @@ -148,6 +133,22 @@ #endif // !OS_MACOSX +// Return a name that is scoped to this instance of the service process. We +// use the hash of the user-data-dir as a scoping prefix. We can't use +// the user-data-dir itself as we have limits on the size of the lock names. +std::string GetServiceProcessScopedName(const std::string& append_str) { + base::FilePath user_data_dir; + PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); +#if defined(OS_WIN) + std::string user_data_dir_path = base::WideToUTF8(user_data_dir.value()); +#elif defined(OS_POSIX) + std::string user_data_dir_path = user_data_dir.value(); +#endif // defined(OS_WIN) + std::string hash = base::SHA1HashString(user_data_dir_path); + std::string hex_hash = base::HexEncode(hash.c_str(), hash.length()); + return hex_hash + "." + append_str; +} + scoped_ptr<base::CommandLine> CreateServiceProcessCommandLine() { base::FilePath exe_path; PathService::Get(content::CHILD_PROCESS_EXE, &exe_path);
diff --git a/chrome/common/service_process_util.h b/chrome/common/service_process_util.h index 9c759d7..9067623 100644 --- a/chrome/common/service_process_util.h +++ b/chrome/common/service_process_util.h
@@ -32,21 +32,15 @@ // Return the IPC channel to connect to the service process. IPC::ChannelHandle GetServiceProcessChannel(); -#if !defined(OS_MACOSX) // Return a name that is scoped to this instance of the service process. We // use the user-data-dir as a scoping prefix. std::string GetServiceProcessScopedName(const std::string& append_str); +#if !defined(OS_MACOSX) // Return a name that is scoped to this instance of the service process. We // use the user-data-dir and the version as a scoping prefix. std::string GetServiceProcessScopedVersionedName(const std::string& append_str); -#endif // OS_MACOSX - -#if defined(OS_MACOSX) -// Return the name that is used to extract the socket path out of the -// dictionary provided by launchd. -NSString* GetServiceProcessLaunchDSocketEnvVar(); -#endif +#endif // !OS_MACOSX #if defined(OS_POSIX) // Attempts to take a lock named |name|. If |waiting| is true then this will
diff --git a/chrome/common/service_process_util_mac.mm b/chrome/common/service_process_util_mac.mm index bf68feb..d6d1c3b 100644 --- a/chrome/common/service_process_util_mac.mm +++ b/chrome/common/service_process_util_mac.mm
@@ -17,6 +17,7 @@ #include "base/mac/mac_util.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/mac/scoped_nsobject.h" +#include "base/metrics/histogram_macros.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -27,6 +28,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/mac/launchd.h" +#include "ipc/unix_domain_socket_util.h" using ::base::FilePathWatcher; @@ -44,11 +46,11 @@ NSString* GetServiceProcessLaunchDLabel() { base::scoped_nsobject<NSString> name( base::mac::CFToNSCast(CopyServiceProcessLaunchDName())); - NSString *label = [name stringByAppendingString:@".service_process"]; + NSString* label = [name stringByAppendingString:@".service_process"]; base::FilePath user_data_dir; PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); std::string user_data_dir_path = user_data_dir.value(); - NSString *ns_path = base::SysUTF8ToNSString(user_data_dir_path); + NSString* ns_path = base::SysUTF8ToNSString(user_data_dir_path); ns_path = [ns_path stringByReplacingOccurrencesOfString:@" " withString:@"_"]; label = [label stringByAppendingString:ns_path]; @@ -84,29 +86,27 @@ FSRef executable_fsref_; }; -} // namespace - -NSString* GetServiceProcessLaunchDSocketEnvVar() { - NSString *label = GetServiceProcessLaunchDLabel(); - NSString *env_var = [label stringByReplacingOccurrencesOfString:@"." - withString:@"_"]; - env_var = [env_var stringByAppendingString:@"_SOCKET"]; - env_var = [env_var uppercaseString]; - return env_var; +base::FilePath GetServiceProcessSocketName() { + base::FilePath socket_name; + PathService::Get(base::DIR_TEMP, &socket_name); + std::string pipe_name = GetServiceProcessScopedName("srv"); + socket_name = socket_name.Append(pipe_name); + UMA_HISTOGRAM_CUSTOM_COUNTS("CloudPrint.ServiceProcessSocketLength", + socket_name.value().size(), 75, 124, 50); + if (socket_name.value().size() < IPC::kMaxSocketNameLength) + return socket_name; + // Fallback to /tmp if $TMPDIR is too long. + // TODO(vitalybuka): Investigate how often we get there. + // See http://crbug.com/466644 + return base::FilePath("/tmp").Append(pipe_name); } -// Gets the name of the service process IPC channel. +} // namespace + IPC::ChannelHandle GetServiceProcessChannel() { - base::mac::ScopedNSAutoreleasePool pool; - std::string socket_path; - base::scoped_nsobject<NSDictionary> dictionary( - base::mac::CFToNSCast(Launchd::GetInstance()->CopyExports())); - NSString *ns_socket_path = - [dictionary objectForKey:GetServiceProcessLaunchDSocketEnvVar()]; - if (ns_socket_path) { - socket_path = base::SysNSStringToUTF8(ns_socket_path); - } - return IPC::ChannelHandle(socket_path); + base::FilePath socket_name = GetServiceProcessSocketName(); + VLOG(1) << "ServiceProcessChannel: " << socket_name.value(); + return IPC::ChannelHandle(socket_name.value()); } bool ForceServiceProcessShutdown(const std::string& /* version */, @@ -135,14 +135,14 @@ // to be a service process of some sort registered with launchd. if (version) { *version = "0"; - NSString *exe_path = [launchd_conf objectForKey:@ LAUNCH_JOBKEY_PROGRAM]; + NSString* exe_path = [launchd_conf objectForKey:@ LAUNCH_JOBKEY_PROGRAM]; if (exe_path) { - NSString *bundle_path = [[[exe_path stringByDeletingLastPathComponent] + NSString* bundle_path = [[[exe_path stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByDeletingLastPathComponent]; - NSBundle *bundle = [NSBundle bundleWithPath:bundle_path]; + NSBundle* bundle = [NSBundle bundleWithPath:bundle_path]; if (bundle) { - NSString *ns_version = + NSString* ns_version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; if (ns_version) { *version = base::SysNSStringToUTF8(ns_version); @@ -186,7 +186,7 @@ IPC::ChannelHandle ServiceProcessState::GetServiceProcessChannel() { DCHECK(state_); - NSDictionary *ns_launchd_conf = base::mac::CFToNSCast(state_->launchd_conf); + NSDictionary* ns_launchd_conf = base::mac::CFToNSCast(state_->launchd_conf); NSDictionary* socket_dict = [ns_launchd_conf objectForKey:@ LAUNCH_JOBKEY_SOCKETS]; NSArray* sockets = @@ -231,11 +231,11 @@ bool for_auto_launch) { base::mac::ScopedNSAutoreleasePool pool; - NSString *program = + NSString* program = base::SysUTF8ToNSString(cmd_line->GetProgram().value()); std::vector<std::string> args = cmd_line->argv(); - NSMutableArray *ns_args = [NSMutableArray arrayWithCapacity:args.size()]; + NSMutableArray* ns_args = [NSMutableArray arrayWithCapacity:args.size()]; for (std::vector<std::string>::iterator iter = args.begin(); iter < args.end(); @@ -243,20 +243,23 @@ [ns_args addObject:base::SysUTF8ToNSString(*iter)]; } - NSDictionary *socket = - [NSDictionary dictionaryWithObject:GetServiceProcessLaunchDSocketEnvVar() - forKey:@ LAUNCH_JOBSOCKETKEY_SECUREWITHKEY]; - NSDictionary *sockets = + NSString* socket_name = + base::SysUTF8ToNSString(GetServiceProcessSocketName().value()); + + NSDictionary* socket = + [NSDictionary dictionaryWithObject:socket_name + forKey:@LAUNCH_JOBSOCKETKEY_PATHNAME]; + NSDictionary* sockets = [NSDictionary dictionaryWithObject:socket forKey:GetServiceProcessLaunchDSocketKey()]; // See the man page for launchd.plist. - NSMutableDictionary *launchd_plist = + NSMutableDictionary* launchd_plist = [[NSMutableDictionary alloc] initWithObjectsAndKeys: - GetServiceProcessLaunchDLabel(), @ LAUNCH_JOBKEY_LABEL, - program, @ LAUNCH_JOBKEY_PROGRAM, - ns_args, @ LAUNCH_JOBKEY_PROGRAMARGUMENTS, - sockets, @ LAUNCH_JOBKEY_SOCKETS, + GetServiceProcessLaunchDLabel(), @LAUNCH_JOBKEY_LABEL, + program, @LAUNCH_JOBKEY_PROGRAM, + ns_args, @LAUNCH_JOBKEY_PROGRAMARGUMENTS, + sockets, @LAUNCH_JOBKEY_SOCKETS, nil]; if (for_auto_launch) { @@ -264,16 +267,16 @@ // enabled. With a value of NO in the SuccessfulExit key, launchd will // relaunch the service automatically in any other case than exiting // cleanly with a 0 return code. - NSDictionary *keep_alive = - [NSDictionary - dictionaryWithObject:[NSNumber numberWithBool:NO] - forKey:@ LAUNCH_JOBKEY_KEEPALIVE_SUCCESSFULEXIT]; - NSDictionary *auto_launchd_plist = - [[NSDictionary alloc] initWithObjectsAndKeys: - [NSNumber numberWithBool:YES], @ LAUNCH_JOBKEY_RUNATLOAD, - keep_alive, @ LAUNCH_JOBKEY_KEEPALIVE, - @ kServiceProcessSessionType, @ LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE, - nil]; + NSDictionary* keep_alive = + [NSDictionary + dictionaryWithObject:[NSNumber numberWithBool:NO] + forKey:@LAUNCH_JOBKEY_KEEPALIVE_SUCCESSFULEXIT]; + NSDictionary* auto_launchd_plist = + [[NSDictionary alloc] initWithObjectsAndKeys: + [NSNumber numberWithBool:YES], @LAUNCH_JOBKEY_RUNATLOAD, + keep_alive, @LAUNCH_JOBKEY_KEEPALIVE, + @kServiceProcessSessionType, @LAUNCH_JOBKEY_LIMITLOADTOSESSIONTYPE, + nil]; [launchd_plist addEntriesFromDictionary:auto_launchd_plist]; } return reinterpret_cast<CFDictionaryRef>(launchd_plist);
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 9d7e88c..3daf113 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -48,7 +48,6 @@ #include "chrome/renderer/prerender/prerender_helper.h" #include "chrome/renderer/prerender/prerender_media_load_deferrer.h" #include "chrome/renderer/prerender/prerenderer_client.h" -#include "chrome/renderer/principals_extension_bindings.h" #include "chrome/renderer/safe_browsing/malware_dom_details.h" #include "chrome/renderer/safe_browsing/phishing_classifier_delegate.h" #include "chrome/renderer/searchbox/search_bouncer.h" @@ -437,11 +436,6 @@ thread->RegisterExtension(extensions_v8::PlaybackExtension::Get()); } - // TODO(guohui): needs to forward the new-profile-management switch to - // renderer processes. - if (switches::IsEnableAccountConsistency()) - thread->RegisterExtension(extensions_v8::PrincipalsExtension::Get()); - // chrome:, chrome-search:, chrome-devtools:, and chrome-distiller: pages // should not be accessible by normal content, and should also be unable to // script anything but themselves (to help limit the damage that a corrupt
diff --git a/chrome/renderer/content_settings_observer.cc b/chrome/renderer/content_settings_observer.cc index f1787b3..1158539e 100644 --- a/chrome/renderer/content_settings_observer.cc +++ b/chrome/renderer/content_settings_observer.cc
@@ -194,7 +194,7 @@ bool ContentSettingsObserver::IsPluginTemporarilyAllowed( const std::string& identifier) { - // If the empty string is in here, it means all plug-ins are allowed. + // If the empty string is in here, it means all plugins are allowed. // TODO(bauerb): Remove this once we only pass in explicit identifiers. return (temporarily_allowed_plugins_.find(identifier) != temporarily_allowed_plugins_.end()) ||
diff --git a/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc b/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc index 813d090..8121346 100644 --- a/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc +++ b/chrome/renderer/extensions/chrome_extensions_dispatcher_delegate.cc
@@ -215,8 +215,6 @@ source_map->RegisterSource("chromeWebViewInternal", IDR_CHROME_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS); source_map->RegisterSource("chromeWebView", IDR_CHROME_WEB_VIEW_JS); - source_map->RegisterSource("chromeWebViewExperimental", - IDR_CHROME_WEB_VIEW_EXPERIMENTAL_JS); source_map->RegisterSource("injectAppTitlebar", IDR_INJECT_APP_TITLEBAR_JS); } @@ -241,10 +239,6 @@ // The API will be automatically set up when first used. if (context->GetAvailability("webViewInternal").is_available()) { module_system->Require("chromeWebView"); - if (context->GetAvailability("webViewExperimentalInternal") - .is_available()) { - module_system->Require("chromeWebViewExperimental"); - } } }
diff --git a/chrome/renderer/extensions/webstore_bindings.cc b/chrome/renderer/extensions/webstore_bindings.cc index c46a23c..876f736 100644 --- a/chrome/renderer/extensions/webstore_bindings.cc +++ b/chrome/renderer/extensions/webstore_bindings.cc
@@ -14,6 +14,7 @@ #include "extensions/renderer/script_context.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebNode.h" #include "third_party/WebKit/public/web/WebNodeList.h" #include "third_party/WebKit/public/web/WebUserGestureIndicator.h" @@ -22,7 +23,6 @@ using blink::WebDocument; using blink::WebElement; -using blink::WebFrame; using blink::WebNode; using blink::WebNodeList; using blink::WebUserGestureIndicator; @@ -79,7 +79,7 @@ std::string webstore_item_id; std::string error; - WebFrame* frame = context()->web_frame(); + blink::WebLocalFrame* frame = context()->web_frame(); if (!GetWebstoreItemIdFromFrame( frame, preferred_store_link_url, &webstore_item_id, &error)) { @@ -102,8 +102,10 @@ // static bool WebstoreBindings::GetWebstoreItemIdFromFrame( - WebFrame* frame, const std::string& preferred_store_link_url, - std::string* webstore_item_id, std::string* error) { + blink::WebLocalFrame* frame, + const std::string& preferred_store_link_url, + std::string* webstore_item_id, + std::string* error) { if (frame != frame->top()) { *error = kNotInTopFrameError; return false;
diff --git a/chrome/renderer/extensions/webstore_bindings.h b/chrome/renderer/extensions/webstore_bindings.h index 13baaa6..cdffce7 100644 --- a/chrome/renderer/extensions/webstore_bindings.h +++ b/chrome/renderer/extensions/webstore_bindings.h
@@ -9,7 +9,10 @@ #include "chrome/common/extensions/webstore_install_result.h" #include "chrome/renderer/extensions/chrome_v8_extension_handler.h" #include "extensions/renderer/object_backed_native_handler.h" -#include "third_party/WebKit/public/web/WebFrame.h" + +namespace blink { +class WebLocalFrame; +} namespace extensions { @@ -42,8 +45,10 @@ // parameter will be populated with the ID. On failure, false will be returned // and |error| will be populated with the error. static bool GetWebstoreItemIdFromFrame( - blink::WebFrame* frame, const std::string& preferred_store_link_url, - std::string* webstore_item_id, std::string* error); + blink::WebLocalFrame* frame, + const std::string& preferred_store_link_url, + std::string* webstore_item_id, + std::string* error); DISALLOW_COPY_AND_ASSIGN(WebstoreBindings); };
diff --git a/chrome/renderer/principals_extension_bindings.cc b/chrome/renderer/principals_extension_bindings.cc deleted file mode 100644 index 9118c8d6..0000000 --- a/chrome/renderer/principals_extension_bindings.cc +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/renderer/principals_extension_bindings.h" - -#include "chrome/common/render_messages.h" -#include "content/public/renderer/render_view.h" -#include "third_party/WebKit/public/web/WebDocument.h" -#include "third_party/WebKit/public/web/WebLocalFrame.h" -#include "third_party/WebKit/public/web/WebView.h" -#include "v8/include/v8.h" - -using blink::WebLocalFrame; -using blink::WebView; -using content::RenderView; - -namespace { - -class PrincipalsExtensionWrapper : public v8::Extension { - public: - PrincipalsExtensionWrapper(); - - private: - // v8::Extension overrides. - v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate( - v8::Isolate* isolate, - v8::Handle<v8::String> name) override; - - static RenderView* GetRenderView(); - - static void GetManagedAccounts( - const v8::FunctionCallbackInfo<v8::Value>& args); - static void ShowBrowserAccountManagementUI( - const v8::FunctionCallbackInfo<v8::Value>& args); - - DISALLOW_COPY_AND_ASSIGN(PrincipalsExtensionWrapper); -}; - -const char kPrincipalsExtensionName[] = "v8/Principals"; -const char kPrincipalsExtensionCode[] = - "var chrome;" - "if (!chrome)" - " chrome = {};" - "if (!chrome.principals)" - " chrome.principals = {};" - "chrome.principals.getManagedAccounts = function() {" - " native function NativeGetManagedAccounts();" - " return NativeGetManagedAccounts();" - "};" - "chrome.principals.showBrowserAccountManagementUI = function() {" - " native function ShowBrowserAccountManagementUI();" - " ShowBrowserAccountManagementUI();" - "};"; - -PrincipalsExtensionWrapper::PrincipalsExtensionWrapper() : v8::Extension( - kPrincipalsExtensionName, kPrincipalsExtensionCode) {} - -v8::Handle<v8::FunctionTemplate> - PrincipalsExtensionWrapper::GetNativeFunctionTemplate( - v8::Isolate* isolate, v8::Handle<v8::String> name) { - if (name->Equals(v8::String::NewFromUtf8( - isolate, "NativeGetManagedAccounts"))) { - return v8::FunctionTemplate::New(isolate, GetManagedAccounts); - } else if (name->Equals(v8::String::NewFromUtf8( - isolate, "ShowBrowserAccountManagementUI"))) { - return v8::FunctionTemplate::New(isolate, ShowBrowserAccountManagementUI); - } - return v8::Handle<v8::FunctionTemplate>(); -} - -void PrincipalsExtensionWrapper::GetManagedAccounts( - const v8::FunctionCallbackInfo<v8::Value>& args) { - RenderView* render_view = GetRenderView(); - if (!render_view) { - args.GetReturnValue().SetNull(); - return; - } - - std::vector<std::string> accounts; - render_view->Send(new ChromeViewHostMsg_GetManagedAccounts( - WebLocalFrame::frameForCurrentContext()->document().url(), - &accounts)); - - v8::Isolate* isolate = args.GetIsolate(); - v8::Local<v8::Array> v8_result = v8::Array::New(isolate); - int v8_index = 0; - for (std::vector<std::string>::const_iterator it = accounts.begin(); - it != accounts.end(); ++it) { - v8_result->Set(v8::Integer::New(isolate, v8_index++), - v8::String::NewFromUtf8(isolate, it->c_str(), - v8::String::kNormalString, it->length())); - } - args.GetReturnValue().Set(v8_result); -} - -void PrincipalsExtensionWrapper::ShowBrowserAccountManagementUI( - const v8::FunctionCallbackInfo<v8::Value>& args) { - // TODO(guohui): need to figure out how to prevent abuse. - RenderView* render_view = GetRenderView(); - if (!render_view) return; - - render_view->Send(new ChromeViewHostMsg_ShowBrowserAccountManagementUI()); -} - -RenderView* PrincipalsExtensionWrapper::GetRenderView() { - WebLocalFrame* webframe = WebLocalFrame::frameForCurrentContext(); - DCHECK(webframe) << "There should be an active frame since we just got " - "a native function called."; - if (!webframe) - return NULL; - - WebView* webview = webframe->view(); - if (!webview) // can happen during closing - return NULL; - - return RenderView::FromWebView(webview); -} - -} // namespace - -namespace extensions_v8 { - -v8::Extension* PrincipalsExtension::Get() { - return new PrincipalsExtensionWrapper(); -} - -} // namespace extensions_v8
diff --git a/chrome/renderer/principals_extension_bindings.h b/chrome/renderer/principals_extension_bindings.h deleted file mode 100644 index 0884896..0000000 --- a/chrome/renderer/principals_extension_bindings.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2013 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. - -// A v8 extension to expose Chrome account management functions. - -#ifndef CHROME_RENDERER_PRINCIPALS_EXTENSION_BINDINGS_H_ -#define CHROME_RENDERER_PRINCIPALS_EXTENSION_BINDINGS_H_ - -namespace v8 { -class Extension; -} - -namespace extensions_v8 { - -class PrincipalsExtension { - public: - static v8::Extension* Get(); -}; - -} // namespace extensions_v8 - -#endif // CHROME_RENDERER_PRINCIPALS_EXTENSION_BINDINGS_H_
diff --git a/chrome/renderer/resources/extensions/web_view/chrome_web_view.js b/chrome/renderer/resources/extensions/web_view/chrome_web_view.js index 14eca5b..a91a239 100644 --- a/chrome/renderer/resources/extensions/web_view/chrome_web_view.js +++ b/chrome/renderer/resources/extensions/web_view/chrome_web_view.js
@@ -3,11 +3,17 @@ // found in the LICENSE file. // This module implements chrome-specific <webview> API. +// See web_view_api_methods.js for details. var ChromeWebView = require('chromeWebViewInternal').ChromeWebView; +var ChromeWebViewSchema = + requireNative('schema_registry').GetSchema('chromeWebViewInternal'); var CreateEvent = require('guestViewEvents').CreateEvent; var EventBindings = require('event_bindings'); +var idGeneratorNatives = requireNative('id_generator'); +var Utils = require('utils'); var WebViewEvents = require('webViewEvents').WebViewEvents; +var WebViewImpl = require('webView').WebViewImpl; var CHROME_WEB_VIEW_EVENTS = { 'contextmenushown': { @@ -18,20 +24,161 @@ } }; -/** - * Calls to show contextmenu right away instead of dispatching a 'contextmenu' - * event. - * This will be overridden in chrome_web_view_experimental.js to implement - * contextmenu API. - */ -WebViewEvents.prototype.handleContextMenu = function(event) { - var requestId = event.requestId; - // Setting |params| = undefined will show the context menu unmodified, hence - // the 'contextmenu' API is disabled for stable channel. - var params = undefined; - ChromeWebView.showContextMenu(this.view.guest.getId(), requestId, params); +// This is the only "webViewInternal.onClicked" named event for this renderer. +// +// Since we need an event per <webview>, we define events with suffix +// (subEventName) in each of the <webview>. Behind the scenes, this event is +// registered as a ContextMenusEvent, with filter set to the webview's +// |viewInstanceId|. Any time a ContextMenusEvent is dispatched, we re-dispatch +// it to the subEvent's listeners. This way +// <webview>.contextMenus.onClicked behave as a regular chrome Event type. +var ContextMenusEvent = CreateEvent('chromeWebViewInternal.onClicked'); + +// ----------------------------------------------------------------------------- +// ContextMenusOnClickedEvent object. + +// This event is exposed as <webview>.contextMenus.onClicked. +function ContextMenusOnClickedEvent(opt_eventName, + opt_argSchemas, + opt_eventOptions, + opt_webViewInstanceId) { + var subEventName = GetUniqueSubEventName(opt_eventName); + EventBindings.Event.call(this, + subEventName, + opt_argSchemas, + opt_eventOptions, + opt_webViewInstanceId); + + // TODO(lazyboy): When do we dispose this listener? + ContextMenusEvent.addListener(function() { + // Re-dispatch to subEvent's listeners. + $Function.apply(this.dispatch, this, $Array.slice(arguments)); + }.bind(this), {instanceId: opt_webViewInstanceId || 0}); +} + +ContextMenusOnClickedEvent.prototype.__proto__ = EventBindings.Event.prototype; + +// ----------------------------------------------------------------------------- +// WebViewContextMenusImpl object. + +// An instance of this class is exposed as <webview>.contextMenus. +function WebViewContextMenusImpl(viewInstanceId) { + this.viewInstanceId_ = viewInstanceId; +} + +WebViewContextMenusImpl.prototype.create = function() { + var args = $Array.concat([this.viewInstanceId_], $Array.slice(arguments)); + return $Function.apply(ChromeWebView.contextMenusCreate, null, args); }; +WebViewContextMenusImpl.prototype.remove = function() { + var args = $Array.concat([this.viewInstanceId_], $Array.slice(arguments)); + return $Function.apply(ChromeWebView.contextMenusRemove, null, args); +}; + +WebViewContextMenusImpl.prototype.removeAll = function() { + var args = $Array.concat([this.viewInstanceId_], $Array.slice(arguments)); + return $Function.apply(ChromeWebView.contextMenusRemoveAll, null, args); +}; + +WebViewContextMenusImpl.prototype.update = function() { + var args = $Array.concat([this.viewInstanceId_], $Array.slice(arguments)); + return $Function.apply(ChromeWebView.contextMenusUpdate, null, args); +}; + +var WebViewContextMenus = Utils.expose( + 'WebViewContextMenus', WebViewContextMenusImpl, + { functions: ['create', 'remove', 'removeAll', 'update'] }); + +// ----------------------------------------------------------------------------- + +WebViewImpl.prototype.maybeSetupContextMenus = function() { + var createContextMenus = function() { + return function() { + if (this.contextMenus_) { + return this.contextMenus_; + } + + this.contextMenus_ = new WebViewContextMenus(this.viewInstanceId); + + // Define 'onClicked' event property on |this.contextMenus_|. + var getOnClickedEvent = function() { + return function() { + if (!this.contextMenusOnClickedEvent_) { + var eventName = 'chromeWebViewInternal.onClicked'; + // TODO(lazyboy): Find event by name instead of events[0]. + var eventSchema = ChromeWebViewSchema.events[0]; + var eventOptions = {supportsListeners: true}; + var onClickedEvent = new ContextMenusOnClickedEvent( + eventName, eventSchema, eventOptions, this.viewInstanceId); + this.contextMenusOnClickedEvent_ = onClickedEvent; + return onClickedEvent; + } + return this.contextMenusOnClickedEvent_; + }.bind(this); + }.bind(this); + Object.defineProperty( + this.contextMenus_, + 'onClicked', + {get: getOnClickedEvent(), enumerable: true}); + + return this.contextMenus_; + }.bind(this); + }.bind(this); + + // Expose <webview>.contextMenus object. + Object.defineProperty( + this.element, + 'contextMenus', + { + get: createContextMenus(), + enumerable: true + }); +}; + +WebViewEvents.prototype.handleContextMenu = function(event, eventName) { + var webViewEvent = this.makeDomEvent(event, eventName); + var requestId = event.requestId; + // Construct the event.menu object. + var actionTaken = false; + var validateCall = function() { + var ERROR_MSG_CONTEXT_MENU_ACTION_ALREADY_TAKEN = '<webview>: ' + + 'An action has already been taken for this "contextmenu" event.'; + + if (actionTaken) { + throw new Error(ERROR_MSG_CONTEXT_MENU_ACTION_ALREADY_TAKEN); + } + actionTaken = true; + }; + var menu = { + show: function(items) { + validateCall(); + // TODO(lazyboy): WebViewShowContextFunction doesn't do anything useful + // with |items|, implement. + ChromeWebView.showContextMenu(this.view.guest.getId(), requestId, items); + }.bind(this) + }; + webViewEvent.menu = menu; + var element = this.view.element; + var defaultPrevented = !element.dispatchEvent(webViewEvent); + if (actionTaken) { + return; + } + if (!defaultPrevented) { + actionTaken = true; + // The default action is equivalent to just showing the context menu as is. + ChromeWebView.showContextMenu( + this.view.guest.getId(), requestId, undefined); + + // TODO(lazyboy): Figure out a way to show warning message only when + // listeners are registered for this event. + } // else we will ignore showing the context menu completely. +}; + +function GetUniqueSubEventName(eventName) { + return eventName + '/' + idGeneratorNatives.GetNextId(); +} + // Exposes |CHROME_WEB_VIEW_EVENTS| when the ChromeWebView API is available. (function() { for (var eventName in CHROME_WEB_VIEW_EVENTS) {
diff --git a/chrome/renderer/resources/extensions/web_view/chrome_web_view_experimental.js b/chrome/renderer/resources/extensions/web_view/chrome_web_view_experimental.js deleted file mode 100644 index db4a130c..0000000 --- a/chrome/renderer/resources/extensions/web_view/chrome_web_view_experimental.js +++ /dev/null
@@ -1,180 +0,0 @@ -// Copyright 2013 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. - -// This module implements experimental API for <webview>. -// See web_view.js for details. -// -// <webview> Chrome Experimental API is only available on canary and dev -// channels of Chrome. - -var ChromeWebView = require('chromeWebViewInternal').ChromeWebView; -var ChromeWebViewSchema = - requireNative('schema_registry').GetSchema('chromeWebViewInternal'); -var ContextMenusSchema = - requireNative('schema_registry').GetSchema('contextMenus'); -var CreateEvent = require('guestViewEvents').CreateEvent; -var EventBindings = require('event_bindings'); -var idGeneratorNatives = requireNative('id_generator'); -var MessagingNatives = requireNative('messaging_natives'); -var utils = require('utils'); -var WebViewEvents = require('webViewEvents').WebViewEvents; -var WebViewImpl = require('webView').WebViewImpl; - -function GetUniqueSubEventName(eventName) { - return eventName + '/' + idGeneratorNatives.GetNextId(); -} - -// This is the only "webViewInternal.onClicked" named event for this renderer. -// -// Since we need an event per <webview>, we define events with suffix -// (subEventName) in each of the <webview>. Behind the scenes, this event is -// registered as a ContextMenusEvent, with filter set to the webview's -// |viewInstanceId|. Any time a ContextMenusEvent is dispatched, we re-dispatch -// it to the subEvent's listeners. This way -// <webview>.contextMenus.onClicked behave as a regular chrome Event type. -var ContextMenusEvent = CreateEvent('chromeWebViewInternal.onClicked'); - -/** - * This event is exposed as <webview>.contextMenus.onClicked. - * - * @constructor - */ -function ContextMenusOnClickedEvent(opt_eventName, - opt_argSchemas, - opt_eventOptions, - opt_webViewInstanceId) { - var subEventName = GetUniqueSubEventName(opt_eventName); - EventBindings.Event.call(this, - subEventName, - opt_argSchemas, - opt_eventOptions, - opt_webViewInstanceId); - - // TODO(lazyboy): When do we dispose this listener? - ContextMenusEvent.addListener(function() { - // Re-dispatch to subEvent's listeners. - $Function.apply(this.dispatch, this, $Array.slice(arguments)); - }.bind(this), {instanceId: opt_webViewInstanceId || 0}); -} - -ContextMenusOnClickedEvent.prototype = { - __proto__: EventBindings.Event.prototype -}; - -/** - * An instance of this class is exposed as <webview>.contextMenus. - * @constructor - */ -function WebViewContextMenusImpl(viewInstanceId) { - this.viewInstanceId_ = viewInstanceId; -} - -WebViewContextMenusImpl.prototype.create = function() { - var args = $Array.concat([this.viewInstanceId_], $Array.slice(arguments)); - return $Function.apply(ChromeWebView.contextMenusCreate, null, args); -}; - -WebViewContextMenusImpl.prototype.remove = function() { - var args = $Array.concat([this.viewInstanceId_], $Array.slice(arguments)); - return $Function.apply(ChromeWebView.contextMenusRemove, null, args); -}; - -WebViewContextMenusImpl.prototype.removeAll = function() { - var args = $Array.concat([this.viewInstanceId_], $Array.slice(arguments)); - return $Function.apply(ChromeWebView.contextMenusRemoveAll, null, args); -}; - -WebViewContextMenusImpl.prototype.update = function() { - var args = $Array.concat([this.viewInstanceId_], $Array.slice(arguments)); - return $Function.apply(ChromeWebView.contextMenusUpdate, null, args); -}; - -var WebViewContextMenus = utils.expose( - 'WebViewContextMenus', WebViewContextMenusImpl, - { functions: ['create', 'remove', 'removeAll', 'update'] }); - -/** @private */ -WebViewEvents.prototype.handleContextMenu = function(event, eventName) { - var webViewEvent = this.makeDomEvent(event, eventName); - var requestId = event.requestId; - // Construct the event.menu object. - var actionTaken = false; - var validateCall = function() { - var ERROR_MSG_CONTEXT_MENU_ACTION_ALREADY_TAKEN = '<webview>: ' + - 'An action has already been taken for this "contextmenu" event.'; - - if (actionTaken) { - throw new Error(ERROR_MSG_CONTEXT_MENU_ACTION_ALREADY_TAKEN); - } - actionTaken = true; - }; - var menu = { - show: function(items) { - validateCall(); - // TODO(lazyboy): WebViewShowContextFunction doesn't do anything useful - // with |items|, implement. - ChromeWebView.showContextMenu(this.view.guest.getId(), requestId, items); - }.bind(this) - }; - webViewEvent.menu = menu; - var element = this.view.element; - var defaultPrevented = !element.dispatchEvent(webViewEvent); - if (actionTaken) { - return; - } - if (!defaultPrevented) { - actionTaken = true; - // The default action is equivalent to just showing the context menu as is. - ChromeWebView.showContextMenu( - this.view.guest.getId(), requestId, undefined); - - // TODO(lazyboy): Figure out a way to show warning message only when - // listeners are registered for this event. - } // else we will ignore showing the context menu completely. -}; - -/** @private */ -WebViewImpl.prototype.setupExperimentalContextMenus = function() { - var createContextMenus = function() { - return function() { - if (this.contextMenus_) { - return this.contextMenus_; - } - - this.contextMenus_ = new WebViewContextMenus(this.viewInstanceId); - - // Define 'onClicked' event property on |this.contextMenus_|. - var getOnClickedEvent = function() { - return function() { - if (!this.contextMenusOnClickedEvent_) { - var eventName = 'chromeWebViewInternal.onClicked'; - // TODO(lazyboy): Find event by name instead of events[0]. - var eventSchema = ChromeWebViewSchema.events[0]; - var eventOptions = {supportsListeners: true}; - var onClickedEvent = new ContextMenusOnClickedEvent( - eventName, eventSchema, eventOptions, this.viewInstanceId); - this.contextMenusOnClickedEvent_ = onClickedEvent; - return onClickedEvent; - } - return this.contextMenusOnClickedEvent_; - }.bind(this); - }.bind(this); - Object.defineProperty( - this.contextMenus_, - 'onClicked', - {get: getOnClickedEvent(), enumerable: true}); - - return this.contextMenus_; - }.bind(this); - }.bind(this); - - // Expose <webview>.contextMenus object. - Object.defineProperty( - this.element, - 'contextMenus', - { - get: createContextMenus(), - enumerable: true - }); -};
diff --git a/chrome/renderer/resources/renderer_resources.grd b/chrome/renderer/resources/renderer_resources.grd index 009dd16..4a54580 100644 --- a/chrome/renderer/resources/renderer_resources.grd +++ b/chrome/renderer/resources/renderer_resources.grd
@@ -44,7 +44,6 @@ file="extensions\chrome_direct_setting.js" type="BINDATA" /> <include name="IDR_CHROME_SETTING_JS" file="extensions\chrome_setting.js" type="BINDATA" /> <include name="IDR_CHROME_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS" file="extensions\web_view\chrome_web_view_internal_custom_bindings.js" type="BINDATA" /> - <include name="IDR_CHROME_WEB_VIEW_EXPERIMENTAL_JS" file="extensions\web_view\chrome_web_view_experimental.js" type="BINDATA" /> <include name="IDR_CHROME_WEB_VIEW_JS" file="extensions\web_view\chrome_web_view.js" type="BINDATA" /> <include name="IDR_CONTENT_SETTING_JS" file="extensions\content_setting.js" type="BINDATA" /> <include name="IDR_DECLARATIVE_CONTENT_CUSTOM_BINDINGS_JS" file="extensions\declarative_content_custom_bindings.js" type="BINDATA" />
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/TabTitleObserver.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/TabTitleObserver.java new file mode 100644 index 0000000..386a2c1b2 --- /dev/null +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/TabTitleObserver.java
@@ -0,0 +1,65 @@ +// 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. +package org.chromium.chrome.test.util.browser; + +import android.text.TextUtils; + +import org.chromium.base.ThreadUtils; +import org.chromium.chrome.browser.EmptyTabObserver; +import org.chromium.chrome.browser.Tab; +import org.chromium.content.browser.test.util.CallbackHelper; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * A utility class to get notified of title change in a tab. + */ +public class TabTitleObserver extends EmptyTabObserver { + private final String mExpectedTitle; + private final CallbackHelper mCallback; + + /** + * A constructor. + * + * @param tab The tab to be observed. + * @param expectedTitle The expected title to wait for. + */ + public TabTitleObserver(final Tab tab, final String expectedTitle) { + mExpectedTitle = expectedTitle; + mCallback = new CallbackHelper(); + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + if (!notifyCallbackIfTitleMatches(tab)) { + tab.addObserver(TabTitleObserver.this); + } + } + }); + } + + /** + * Wait for title update up to the given number of seconds. + * + * @param seconds The number of seconds to wait. + * @throws InterruptedException + * @throws TimeoutException + */ + public void waitForTitleUpdate(int seconds) throws InterruptedException, TimeoutException { + mCallback.waitForCallback(0, 1, seconds, TimeUnit.SECONDS); + } + + private boolean notifyCallbackIfTitleMatches(Tab tab) { + if (TextUtils.equals(tab.getTitle(), mExpectedTitle)) { + mCallback.notifyCalled(); + return true; + } + return false; + } + + @Override + public void onTitleUpdated(Tab tab) { + notifyCallbackIfTitleMatches(tab); + } +} \ No newline at end of file
diff --git a/chrome/test/base/chrome_unit_test_suite.cc b/chrome/test/base/chrome_unit_test_suite.cc index c78d463..2ce04bd0 100644 --- a/chrome/test/base/chrome_unit_test_suite.cc +++ b/chrome/test/base/chrome_unit_test_suite.cc
@@ -110,6 +110,9 @@ // This needs to run after ChromeTestSuite::Initialize which calls content's // intialization which calls base's which initializes ICU. InitializeResourceBundle(); + + base::DiscardableMemoryShmemAllocator::SetInstance( + &discardable_memory_allocator_); } void ChromeUnitTestSuite::Shutdown() {
diff --git a/chrome/test/base/chrome_unit_test_suite.h b/chrome/test/base/chrome_unit_test_suite.h index a8bb208..404c59f0 100644 --- a/chrome/test/base/chrome_unit_test_suite.h +++ b/chrome/test/base/chrome_unit_test_suite.h
@@ -8,6 +8,7 @@ #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" +#include "base/test/test_discardable_memory_shmem_allocator.h" #include "chrome/test/base/chrome_test_suite.h" // Test suite for unit tests. Creates additional stub services that are not @@ -28,6 +29,7 @@ static void InitializeResourceBundle(); private: + base::TestDiscardableMemoryShmemAllocator discardable_memory_allocator_; DISALLOW_COPY_AND_ASSIGN(ChromeUnitTestSuite); };
diff --git a/chrome/test/base/testing_profile.cc b/chrome/test/base/testing_profile.cc index a2c5cd1..d95fe15 100644 --- a/chrome/test/base/testing_profile.cc +++ b/chrome/test/base/testing_profile.cc
@@ -21,7 +21,6 @@ #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/favicon/chrome_favicon_client_factory.h" -#include "chrome/browser/favicon/favicon_service.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/history/chrome_history_client.h" #include "chrome/browser/history/chrome_history_client_factory.h" @@ -55,6 +54,7 @@ #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/common/bookmark_constants.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/history/content/browser/content_visit_delegate.h" #include "components/history/content/browser/history_database_helper.h" #include "components/history/core/browser/history_backend.h"
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index 6a8d32dd..c2dbbf5 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -157,6 +157,7 @@ 'PerformanceLoggerTest.testPerformanceLogger', 'ChromeDriverTest.testShadowDom*', # WebView doesn't support emulating network conditions. + 'ChromeDriverTest.testEmulateNetworkConditions', 'ChromeDriverTest.testEmulateNetworkConditionsOffline', ] )
diff --git a/chrome/test/data/extensions/api_test/permissions/nacl_enabled/background.html b/chrome/test/data/extensions/api_test/permissions/nacl_enabled/background.html index 663b024..1600274e 100644 --- a/chrome/test/data/extensions/api_test/permissions/nacl_enabled/background.html +++ b/chrome/test/data/extensions/api_test/permissions/nacl_enabled/background.html
@@ -5,7 +5,7 @@ --> <script src="background.js"></script> -<h1>Native Client SRPC Simple Plug-in</h1> +<h1>Native Client SRPC Simple Plugin</h1> <p> <embed name="nacl_module" id="pluginobj"
diff --git a/chrome/test/data/favicon/icon.ico b/chrome/test/data/favicon/icon.ico new file mode 100644 index 0000000..ab0e984 --- /dev/null +++ b/chrome/test/data/favicon/icon.ico Binary files differ
diff --git a/chrome/test/data/favicon/page_with_favicon.html b/chrome/test/data/favicon/page_with_favicon.html new file mode 100644 index 0000000..c70ce5a6 --- /dev/null +++ b/chrome/test/data/favicon/page_with_favicon.html
@@ -0,0 +1,5 @@ +<html> +<head> +<link rel="icon" href="icon.ico"/> +</head> +</html>
diff --git a/chrome/test/ppapi/ppapi_browsertest.cc b/chrome/test/ppapi/ppapi_browsertest.cc index aec526d..77ad95e 100644 --- a/chrome/test/ppapi/ppapi_browsertest.cc +++ b/chrome/test/ppapi/ppapi_browsertest.cc
@@ -1219,8 +1219,8 @@ TEST_PPAPI_NACL_SUBTESTS(MAYBE_Compositor0, RUN_COMPOSITOR_SUBTESTS_0) TEST_PPAPI_NACL_SUBTESTS(MAYBE_Compositor1, RUN_COMPOSITOR_SUBTESTS_1) -#if defined(OS_WIN) -// Flaky on Windows (crbug.com/438729) +#if defined(OS_LINUX) || defined(OS_WIN) +// Flaky on Linux and Windows (crbug.com/438729) #define MAYBE_MediaStreamAudioTrack DISABLED_MediaStreamAudioTrack #else #define MAYBE_MediaStreamAudioTrack MediaStreamAudioTrack
diff --git a/chromecast/base/metrics/cast_histograms.h b/chromecast/base/metrics/cast_histograms.h index 941242e..19cb98e 100644 --- a/chromecast/base/metrics/cast_histograms.h +++ b/chromecast/base/metrics/cast_histograms.h
@@ -39,10 +39,4 @@ base::LinearHistogram::FactoryGet(name, 1, boundary_value, \ boundary_value + 1, base::Histogram::kUmaTargetedHistogramFlag)) -#define UMA_HISTOGRAM_ENUMERATION_COUNT_NO_CACHE(name, sample, count, \ - boundary_value) \ - STATIC_HISTOGRAM_POINTER_BLOCK_NO_CACHE(name, AddCount(sample, count), \ - base::LinearHistogram::FactoryGet(name, 1, boundary_value, \ - boundary_value + 1, base::HistogramBase::kUmaTargetedHistogramFlag)) - #endif // CHROMECAST_BASE_METRICS_CAST_HISTOGRAMS_H_
diff --git a/chromecast/chromecast_tests.gypi b/chromecast/chromecast_tests.gypi index a3171b39..0909430 100644 --- a/chromecast/chromecast_tests.gypi +++ b/chromecast/chromecast_tests.gypi
@@ -45,8 +45,7 @@ # Run net_unittests first to avoid random failures due to slow python startup # KeygenHandlerTest.SmokeTest and KeygenHandlerTest.ConcurrencyTest fail due to # readonly certdb (b/8153161) - # Disable EndToEndTests/EndToEndTest (b/19100148) - 'net_unittests --gtest_filter=-KeygenHandlerTest.SmokeTest:KeygenHandlerTest.ConcurrencyTest:EndToEndTests/EndToEndTest.*', + 'net_unittests --gtest_filter=-KeygenHandlerTest.SmokeTest:KeygenHandlerTest.ConcurrencyTest', # Disable OutOfMemoryDeathTest.ViaSharedLibraries due to gTrusty eglibc incompatibility (crbug/428211) # Disable ProcessMetricsTest.GetNumberOfThreads (b/15610509) # Disable ProcessUtilTest.* (need to define OS_ANDROID)
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index d8ce98e0..a24afec 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -6879.0.0 \ No newline at end of file +6882.0.0 \ No newline at end of file
diff --git a/components/BUILD.gn b/components/BUILD.gn index 12e023a..ed5b887d 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -38,7 +38,7 @@ "//components/dom_distiller/core", "//components/domain_reliability", "//components/enhanced_bookmarks", - "//components/favicon/core", + "//components/favicon/core/browser", "//components/favicon_base", "//components/feedback", "//components/gcm_driver", @@ -162,8 +162,9 @@ "//components/data_reduction_proxy/core/common", # Should work, needs checking. "//components/dom_distiller/core", # Blocked on content. "//components/domain_reliability", # Blocked on content. + "//components/favicon/core/browser", # Blocked on keyed service. "//components/favicon_base", # Should work, needs checking. - "//components/favicon/core", # Blocked on keyed service. + "//components/feedback", # Blocked on content. "//components/gcm_driver", # Should work, needs checking. "//components/google/core/browser", # Should work, needs checking. "//components/history/core/browser", # Should work, needs checking.
diff --git a/components/components.gyp b/components/components.gyp index bbf2571..5160960 100644 --- a/components/components.gyp +++ b/components/components.gyp
@@ -27,7 +27,6 @@ 'domain_reliability.gypi', 'enhanced_bookmarks.gypi', 'error_page.gypi', - 'favicon.gypi', 'favicon_base.gypi', 'feedback.gypi', 'google.gypi', @@ -129,6 +128,7 @@ # Android WebView fails to build if a dependency on these targets is # introduced. 'includes': [ + 'favicon.gypi', 'gcm_driver.gypi', 'history.gypi', 'omnibox.gypi',
diff --git a/components/content_settings/core/browser/host_content_settings_map.cc b/components/content_settings/core/browser/host_content_settings_map.cc index fa67b20..0f22c831 100644 --- a/components/content_settings/core/browser/host_content_settings_map.cc +++ b/components/content_settings/core/browser/host_content_settings_map.cc
@@ -69,7 +69,7 @@ "kProviderSourceMap should have NUM_PROVIDER_TYPES elements"); // Returns true if the |content_type| supports a resource identifier. -// Resource identifiers are supported (but not required) for plug-ins. +// Resource identifiers are supported (but not required) for plugins. bool SupportsResourceIdentifier(ContentSettingsType content_type) { return content_type == CONTENT_SETTINGS_TYPE_PLUGINS; }
diff --git a/components/cronet/android/cronet_url_request_context_adapter.cc b/components/cronet/android/cronet_url_request_context_adapter.cc index 8679594..843d9a9 100644 --- a/components/cronet/android/cronet_url_request_context_adapter.cc +++ b/components/cronet/android/cronet_url_request_context_adapter.cc
@@ -8,6 +8,7 @@ #include "base/android/jni_string.h" #include "base/bind.h" #include "base/files/file_util.h" +#include "base/files/scoped_file.h" #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/values.h" @@ -285,21 +286,20 @@ // Do nothing if already logging to a file. if (net_log_logger_) return; - base::FilePath file_path(file_name); - FILE* file = base::OpenFile(file_path, "w"); + base::ScopedFILE file(base::OpenFile(file_path, "w")); if (!file) return; - scoped_ptr<base::Value> constants(net::NetLogLogger::GetConstants()); - net_log_logger_.reset(new net::NetLogLogger(file, *constants)); - net_log_logger_->StartObserving(context_->net_log()); + net_log_logger_.reset(new net::NetLogLogger()); + net_log_logger_->StartObserving(context_->net_log(), file.Pass(), nullptr, + context_.get()); } void CronetURLRequestContextAdapter::StopNetLogOnNetworkThread() { DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread()); if (net_log_logger_) { - net_log_logger_->StopObserving(); + net_log_logger_->StopObserving(context_.get()); net_log_logger_.reset(); } }
diff --git a/components/cronet/android/url_request_context_adapter.cc b/components/cronet/android/url_request_context_adapter.cc index 00daf65..97f22b8 100644 --- a/components/cronet/android/url_request_context_adapter.cc +++ b/components/cronet/android/url_request_context_adapter.cc
@@ -8,6 +8,7 @@ #include "base/bind.h" #include "base/files/file_util.h" +#include "base/files/scoped_file.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "components/cronet/url_request_context_config.h" @@ -280,19 +281,19 @@ return; base::FilePath file_path(file_name); - FILE* file = base::OpenFile(file_path, "w"); + base::ScopedFILE file(base::OpenFile(file_path, "w")); if (!file) return; - scoped_ptr<base::Value> constants(net::NetLogLogger::GetConstants()); - net_log_logger_.reset(new net::NetLogLogger(file, *constants)); - net_log_logger_->StartObserving(context_->net_log()); + net_log_logger_.reset(new net::NetLogLogger()); + net_log_logger_->StartObserving(context_->net_log(), file.Pass(), nullptr, + context_.get()); } void URLRequestContextAdapter::StopNetLogHelper() { DCHECK(GetNetworkTaskRunner()->BelongsToCurrentThread()); if (net_log_logger_) { - net_log_logger_->StopObserving(); + net_log_logger_->StopObserving(context_.get()); net_log_logger_.reset(); } }
diff --git a/components/favicon.gypi b/components/favicon.gypi index 262bd2b4..09a78f2 100644 --- a/components/favicon.gypi +++ b/components/favicon.gypi
@@ -10,15 +10,41 @@ 'type': 'static_library', 'dependencies': [ '../ui/gfx/gfx.gyp:gfx_geometry', + '../url/url.gyp:url_lib', 'favicon_base', + ], + 'sources': [ + # Note: sources list duplicated in GN build. + 'favicon/core/favicon_driver.h', + 'favicon/core/favicon_url.cc', + 'favicon/core/favicon_url.h', + ], + 'include_dirs': [ + '..', + ], + }, + { + # GN version: //components/favicon/core/browser + 'target_name': 'favicon_core_browser', + 'type': 'static_library', + 'dependencies': [ + '../skia/skia.gyp:skia', + '../ui/gfx/gfx.gyp:gfx', + '../url/url.gyp:url_lib', + 'bookmarks_browser', + 'favicon_base', + 'favicon_core', + 'history_core_browser', 'keyed_service_core', ], 'sources': [ # Note: sources list duplicated in GN build. 'favicon/core/browser/favicon_client.h', - 'favicon/core/favicon_driver.h', - 'favicon/core/favicon_url.cc', - 'favicon/core/favicon_url.h', + 'favicon/core/browser/favicon_handler.cc', + 'favicon/core/browser/favicon_handler.h', + 'favicon/core/browser/favicon_service.cc', + 'favicon/core/browser/favicon_service.h', + 'favicon/core/browser/favicon_tab_helper_observer.h', ], 'include_dirs': [ '..',
diff --git a/components/favicon/DEPS b/components/favicon/DEPS index 9b38a85..b6ea2b38 100644 --- a/components/favicon/DEPS +++ b/components/favicon/DEPS
@@ -1,5 +1,4 @@ include_rules = [ "+components/favicon_base", - "+components/keyed_service/core", - "+ui/gfx/geometry", + "+ui/gfx", ]
diff --git a/components/favicon/core/BUILD.gn b/components/favicon/core/BUILD.gn index 0f834cb..05bd40bf 100644 --- a/components/favicon/core/BUILD.gn +++ b/components/favicon/core/BUILD.gn
@@ -4,7 +4,6 @@ static_library("core") { sources = [ - "browser/favicon_client.h", "favicon_driver.h", "favicon_url.cc", "favicon_url.h", @@ -12,7 +11,7 @@ deps = [ "//components/favicon_base", - "//components/keyed_service/core", "//ui/gfx/geometry", + "//url", ] }
diff --git a/components/favicon/core/browser/BUILD.gn b/components/favicon/core/browser/BUILD.gn new file mode 100644 index 0000000..22e1246 --- /dev/null +++ b/components/favicon/core/browser/BUILD.gn
@@ -0,0 +1,25 @@ +# 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. + +static_library("browser") { + sources = [ + "favicon_client.h", + "favicon_handler.cc", + "favicon_handler.h", + "favicon_service.cc", + "favicon_service.h", + "favicon_tab_helper_observer.h", + ] + + deps = [ + "//components/bookmarks/browser", + "//components/favicon/core", + "//components/favicon_base", + "//components/history/core/browser", + "//components/keyed_service/core", + "//skia", + "//ui/gfx", + "//url", + ] +}
diff --git a/components/favicon/core/browser/DEPS b/components/favicon/core/browser/DEPS new file mode 100644 index 0000000..8a86e5b --- /dev/null +++ b/components/favicon/core/browser/DEPS
@@ -0,0 +1,7 @@ +include_rules = [ + "+components/bookmarks/browser", + "+components/history/core/browser", + "+components/keyed_service/core", + "+skia", + "+third_party/skia", +]
diff --git a/chrome/browser/favicon/favicon_handler.cc b/components/favicon/core/browser/favicon_handler.cc similarity index 97% rename from chrome/browser/favicon/favicon_handler.cc rename to components/favicon/core/browser/favicon_handler.cc index 1db27226..1cff52c 100644 --- a/chrome/browser/favicon/favicon_handler.cc +++ b/components/favicon/core/browser/favicon_handler.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/favicon/favicon_handler.h" +#include "components/favicon/core/browser/favicon_handler.h" #include <algorithm> #include <cmath> @@ -12,8 +12,8 @@ #include "base/bind_helpers.h" #include "base/memory/ref_counted_memory.h" #include "build/build_config.h" -#include "chrome/browser/favicon/favicon_service.h" #include "components/favicon/core/browser/favicon_client.h" +#include "components/favicon/core/browser/favicon_service.h" #include "components/favicon/core/favicon_driver.h" #include "components/favicon_base/favicon_util.h" #include "components/favicon_base/select_favicon_frames.h" @@ -124,12 +124,12 @@ // Returns the index of the entry with the largest area. int GetLargestSizeIndex(const std::vector<gfx::Size>& sizes) { DCHECK(!sizes.empty()); - int ret = 0; + size_t ret = 0; for (size_t i = 1; i < sizes.size(); ++i) { if (sizes[ret].GetArea() < sizes[i].GetArea()) ret = i; } - return ret; + return static_cast<int>(ret); } // Return the index of a size which is same as the given |size|, -1 returned if @@ -381,8 +381,13 @@ return; } + DownloadRequest download_request = i->second; + download_requests_.erase(i); + if (current_candidate() && - DoUrlAndIconMatch(*current_candidate(), image_url, i->second.icon_type)) { + DoUrlAndIconMatch(*current_candidate(), + image_url, + download_request.icon_type)) { bool request_next_icon = true; float score = 0.0f; gfx::ImageSkia image_skia; @@ -412,7 +417,8 @@ // during the downloading. if (!bitmaps.empty()) { request_next_icon = !UpdateFaviconCandidate( - i->second.url, image_url, image, score, i->second.icon_type); + download_request.url, image_url, image, score, + download_request.icon_type); } } if (request_next_icon && !PageChangedSinceFaviconWasRequested() && @@ -429,10 +435,10 @@ best_favicon_candidate_.icon_type); // Reset candidate. image_urls_.clear(); + download_requests_.clear(); best_favicon_candidate_ = FaviconCandidate(); } } - download_requests_.erase(i); } bool FaviconHandler::PageChangedSinceFaviconWasRequested() {
diff --git a/chrome/browser/favicon/favicon_handler.h b/components/favicon/core/browser/favicon_handler.h similarity index 95% rename from chrome/browser/favicon/favicon_handler.h rename to components/favicon/core/browser/favicon_handler.h index 9af7de86..5d890c0e9 100644 --- a/chrome/browser/favicon/favicon_handler.h +++ b/components/favicon/core/browser/favicon_handler.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_FAVICON_FAVICON_HANDLER_H_ -#define CHROME_BROWSER_FAVICON_FAVICON_HANDLER_H_ +#ifndef COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_HANDLER_H_ +#define COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_HANDLER_H_ #include <deque> #include <map> @@ -148,7 +148,9 @@ virtual bool ShouldSaveFavicon(const GURL& url); private: - friend class TestFaviconHandler; // For testing + // For testing: + friend class FaviconTabHelperTest; + friend class TestFaviconHandler; // Represents an in progress download of an image from the renderer. struct DownloadRequest { @@ -257,7 +259,10 @@ // URL of the page we're requesting the favicon for. GURL url_; - // Whether we got the initial response for the favicon back from the renderer. + // Whether we are waiting for data from the FaviconService. + bool waiting_for_favicon_service_data_; + + // Whether we got data back for the initial request to the FaviconService. bool got_favicon_from_history_; // Whether the favicon is out of date or the favicon data in @@ -301,4 +306,4 @@ DISALLOW_COPY_AND_ASSIGN(FaviconHandler); }; -#endif // CHROME_BROWSER_FAVICON_FAVICON_HANDLER_H_ +#endif // COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_HANDLER_H_
diff --git a/chrome/browser/favicon/favicon_service.cc b/components/favicon/core/browser/favicon_service.cc similarity index 99% rename from chrome/browser/favicon/favicon_service.cc rename to components/favicon/core/browser/favicon_service.cc index 98dadea..f0173e4 100644 --- a/chrome/browser/favicon/favicon_service.cc +++ b/components/favicon/core/browser/favicon_service.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/favicon/favicon_service.h" +#include "components/favicon/core/browser/favicon_service.h" #include <cmath>
diff --git a/chrome/browser/favicon/favicon_service.h b/components/favicon/core/browser/favicon_service.h similarity index 98% rename from chrome/browser/favicon/favicon_service.h rename to components/favicon/core/browser/favicon_service.h index 64eb458..41493449 100644 --- a/chrome/browser/favicon/favicon_service.h +++ b/components/favicon/core/browser/favicon_service.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_FAVICON_FAVICON_SERVICE_H_ -#define CHROME_BROWSER_FAVICON_FAVICON_SERVICE_H_ +#ifndef COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_SERVICE_H_ +#define COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_SERVICE_H_ #include <vector> @@ -251,4 +251,4 @@ DISALLOW_COPY_AND_ASSIGN(FaviconService); }; -#endif // CHROME_BROWSER_FAVICON_FAVICON_SERVICE_H_ +#endif // COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_SERVICE_H_
diff --git a/chrome/browser/favicon/favicon_tab_helper_observer.h b/components/favicon/core/browser/favicon_tab_helper_observer.h similarity index 71% rename from chrome/browser/favicon/favicon_tab_helper_observer.h rename to components/favicon/core/browser/favicon_tab_helper_observer.h index 7e28b5e..bc109ff3 100644 --- a/chrome/browser/favicon/favicon_tab_helper_observer.h +++ b/components/favicon/core/browser/favicon_tab_helper_observer.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_FAVICON_FAVICON_TAB_HELPER_OBSERVER_H_ -#define CHROME_BROWSER_FAVICON_FAVICON_TAB_HELPER_OBSERVER_H_ +#ifndef COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_TAB_HELPER_OBSERVER_H_ +#define COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_TAB_HELPER_OBSERVER_H_ namespace gfx { class Image; @@ -21,4 +21,4 @@ virtual ~FaviconTabHelperObserver() {} }; -#endif // CHROME_BROWSER_FAVICON_FAVICON_TAB_HELPER_OBSERVER_H_ +#endif // COMPONENTS_FAVICON_CORE_BROWSER_FAVICON_TAB_HELPER_OBSERVER_H_
diff --git a/components/nacl/renderer/nexe_load_manager.cc b/components/nacl/renderer/nexe_load_manager.cc index bb1f415..b7c99689 100644 --- a/components/nacl/renderer/nexe_load_manager.cc +++ b/components/nacl/renderer/nexe_load_manager.cc
@@ -49,7 +49,7 @@ // JSON matching ISAs with .nexe URLs). const char* const kSrcManifestAttribute = "src"; // The "nacl" attribute of the <embed> tag. We use the value of this attribute -// to find the manifest file when NaCl is registered as a plug-in for another +// to find the manifest file when NaCl is registered as a plugin for another // MIME type because the "src" attribute is used to supply us with the resource // of that MIME type that we're supposed to display. const char* const kNaClManifestAttribute = "nacl";
diff --git a/components/password_manager/core/browser/login_database.cc b/components/password_manager/core/browser/login_database.cc index 99a138f..65ffff7 100644 --- a/components/password_manager/core/browser/login_database.cc +++ b/components/password_manager/core/browser/login_database.cc
@@ -671,9 +671,10 @@ return s.Run(); } +// static LoginDatabase::EncryptionResult LoginDatabase::InitPasswordFormFromStatement( PasswordForm* form, - sql::Statement& s) const { + sql::Statement& s) { std::string encrypted_password; s.ColumnBlobAsString(COLUMN_PASSWORD_VALUE, &encrypted_password); base::string16 decrypted_password; @@ -751,7 +752,6 @@ sql::Statement s; const GURL signon_realm(form.signon_realm); std::string registered_domain = GetRegistryControlledDomain(signon_realm); - PSLDomainMatchMetric psl_domain_match_metric = PSL_DOMAIN_MATCH_NONE; const bool should_PSL_matching_apply = form.scheme == PasswordForm::SCHEME_HTML && ShouldPSLDomainMatchingApply(registered_domain); @@ -786,49 +786,15 @@ s.BindString(0, form.signon_realm); s.BindString(1, regexp); } else { - psl_domain_match_metric = PSL_DOMAIN_MATCH_NOT_USED; + UMA_HISTOGRAM_ENUMERATION("PasswordManager.PslDomainMatchTriggering", + PSL_DOMAIN_MATCH_NOT_USED, + PSL_DOMAIN_MATCH_COUNT); s.Assign(db_.GetCachedStatement(SQL_FROM_HERE, sql_query.c_str())); s.BindString(0, form.signon_realm); } - while (s.Step()) { - scoped_ptr<PasswordForm> new_form(new PasswordForm()); - EncryptionResult result = InitPasswordFormFromStatement(new_form.get(), s); - if (result == ENCRYPTION_RESULT_SERVICE_FAILURE) - return false; - if (result == ENCRYPTION_RESULT_ITEM_FAILURE) - continue; - DCHECK(result == ENCRYPTION_RESULT_SUCCESS); - if (should_PSL_matching_apply) { - if (!IsPublicSuffixDomainMatch(new_form->signon_realm, - form.signon_realm)) { - // The database returned results that should not match. Skipping result. - continue; - } - if (form.signon_realm != new_form->signon_realm) { - // Ignore non-HTML matches. - if (new_form->scheme != PasswordForm::SCHEME_HTML) - continue; - - psl_domain_match_metric = PSL_DOMAIN_MATCH_FOUND; - // This is not a perfect match, so we need to create a new valid result. - // We do this by copying over origin, signon realm and action from the - // observed form and setting the original signon realm to what we found - // in the database. We use the fact that |original_signon_realm| is - // non-empty to communicate that this match was found using public - // suffix matching. - new_form->original_signon_realm = new_form->signon_realm; - new_form->origin = form.origin; - new_form->signon_realm = form.signon_realm; - new_form->action = form.action; - } - } - forms->push_back(new_form.release()); - } - UMA_HISTOGRAM_ENUMERATION("PasswordManager.PslDomainMatchTriggering", - psl_domain_match_metric, - PSL_DOMAIN_MATCH_COUNT); - return s.Succeeded(); + return StatementToForms(&s, should_PSL_matching_apply ? &form : nullptr, + forms); } bool LoginDatabase::GetLoginsCreatedBetween( @@ -851,17 +817,7 @@ s.BindInt64(1, end.is_null() ? std::numeric_limits<int64>::max() : end.ToInternalValue()); - while (s.Step()) { - scoped_ptr<PasswordForm> new_form(new PasswordForm()); - EncryptionResult result = InitPasswordFormFromStatement(new_form.get(), s); - if (result == ENCRYPTION_RESULT_SERVICE_FAILURE) - return false; - if (result == ENCRYPTION_RESULT_ITEM_FAILURE) - continue; - DCHECK(result == ENCRYPTION_RESULT_SUCCESS); - forms->push_back(new_form.release()); - } - return s.Succeeded(); + return StatementToForms(&s, nullptr, forms); } bool LoginDatabase::GetLoginsSyncedBetween( @@ -884,17 +840,7 @@ end.is_null() ? base::Time::Max().ToInternalValue() : end.ToInternalValue()); - while (s.Step()) { - scoped_ptr<PasswordForm> new_form(new PasswordForm()); - EncryptionResult result = InitPasswordFormFromStatement(new_form.get(), s); - if (result == ENCRYPTION_RESULT_SERVICE_FAILURE) - return false; - if (result == ENCRYPTION_RESULT_ITEM_FAILURE) - continue; - DCHECK(result == ENCRYPTION_RESULT_SUCCESS); - forms->push_back(new_form.release()); - } - return s.Succeeded(); + return StatementToForms(&s, nullptr, forms); } bool LoginDatabase::GetAutofillableLogins( @@ -924,17 +870,7 @@ "WHERE blacklisted_by_user == ? ORDER BY origin_url")); s.BindInt(0, blacklisted ? 1 : 0); - while (s.Step()) { - scoped_ptr<PasswordForm> new_form(new PasswordForm()); - EncryptionResult result = InitPasswordFormFromStatement(new_form.get(), s); - if (result == ENCRYPTION_RESULT_SERVICE_FAILURE) - return false; - if (result == ENCRYPTION_RESULT_ITEM_FAILURE) - continue; - DCHECK(result == ENCRYPTION_RESULT_SUCCESS); - forms->push_back(new_form.release()); - } - return s.Succeeded(); + return StatementToForms(&s, nullptr, forms); } bool LoginDatabase::DeleteAndRecreateDatabaseFile() { @@ -945,4 +881,55 @@ return Init(); } +// static +bool LoginDatabase::StatementToForms( + sql::Statement* statement, + const autofill::PasswordForm* psl_match, + ScopedVector<autofill::PasswordForm>* forms) { + PSLDomainMatchMetric psl_domain_match_metric = PSL_DOMAIN_MATCH_NONE; + + forms->clear(); + while (statement->Step()) { + scoped_ptr<PasswordForm> new_form(new PasswordForm()); + EncryptionResult result = + InitPasswordFormFromStatement(new_form.get(), *statement); + if (result == ENCRYPTION_RESULT_SERVICE_FAILURE) + return false; + if (result == ENCRYPTION_RESULT_ITEM_FAILURE) + continue; + DCHECK(result == ENCRYPTION_RESULT_SUCCESS); + if (psl_match && psl_match->signon_realm != new_form->signon_realm) { + if (new_form->scheme != PasswordForm::SCHEME_HTML) + continue; // Ignore non-HTML matches. + + if (!IsPublicSuffixDomainMatch(new_form->signon_realm, + psl_match->signon_realm)) { + continue; + } + + psl_domain_match_metric = PSL_DOMAIN_MATCH_FOUND; + // This is not a perfect match, so we need to create a new valid result. + // We do this by copying over origin, signon realm and action from the + // observed form and setting the original signon realm to what we found + // in the database. We use the fact that |original_signon_realm| is + // non-empty to communicate that this match was found using public + // suffix matching. + new_form->original_signon_realm = new_form->signon_realm; + new_form->origin = psl_match->origin; + new_form->signon_realm = psl_match->signon_realm; + new_form->action = psl_match->action; + } + forms->push_back(new_form.Pass()); + } + + if (psl_match) { + UMA_HISTOGRAM_ENUMERATION("PasswordManager.PslDomainMatchTriggering", + psl_domain_match_metric, PSL_DOMAIN_MATCH_COUNT); + } + + if (!statement->Succeeded()) + return false; + return true; +} + } // namespace password_manager
diff --git a/components/password_manager/core/browser/login_database.h b/components/password_manager/core/browser/login_database.h index f2adacdb..008afa35 100644 --- a/components/password_manager/core/browser/login_database.h +++ b/components/password_manager/core/browser/login_database.h
@@ -69,34 +69,37 @@ bool RemoveLoginsSyncedBetween(base::Time delete_begin, base::Time delete_end); - // Loads a list of matching password forms into the specified vector |forms|. - // The list will contain all possibly relevant entries to the observed |form|, - // including blacklisted matches. - bool GetLogins(const autofill::PasswordForm& form, - ScopedVector<autofill::PasswordForm>* forms) const; + // All Get* methods below overwrite |forms| with the returned credentials. On + // success, those methods return true. - // Loads all logins created from |begin| onwards (inclusive) and before |end|. + // Gets a list of credentials matching |form|, including blacklisted matches. + bool GetLogins(const autofill::PasswordForm& form, + ScopedVector<autofill::PasswordForm>* forms) const + WARN_UNUSED_RESULT; + + // Gets all logins created from |begin| onwards (inclusive) and before |end|. // You may use a null Time value to do an unbounded search in either // direction. bool GetLoginsCreatedBetween( base::Time begin, base::Time end, - ScopedVector<autofill::PasswordForm>* forms) const; + ScopedVector<autofill::PasswordForm>* forms) const WARN_UNUSED_RESULT; - // Loads all logins synced from |begin| onwards (inclusive) and before |end|. + // Gets all logins synced from |begin| onwards (inclusive) and before |end|. // You may use a null Time value to do an unbounded search in either // direction. - bool GetLoginsSyncedBetween( - base::Time begin, - base::Time end, - ScopedVector<autofill::PasswordForm>* forms) const; + bool GetLoginsSyncedBetween(base::Time begin, + base::Time end, + ScopedVector<autofill::PasswordForm>* forms) const + WARN_UNUSED_RESULT; - // Loads the complete list of autofillable password forms (i.e., not blacklist - // entries) into |forms|. - bool GetAutofillableLogins(ScopedVector<autofill::PasswordForm>* forms) const; + // Gets the complete list of not blacklisted credentials. + bool GetAutofillableLogins(ScopedVector<autofill::PasswordForm>* forms) const + WARN_UNUSED_RESULT; - // Loads the complete list of blacklist forms into |forms|. - bool GetBlacklistLogins(ScopedVector<autofill::PasswordForm>* forms) const; + // Gets the complete list of blacklisted credentials. + bool GetBlacklistLogins(ScopedVector<autofill::PasswordForm>* forms) const + WARN_UNUSED_RESULT; // Deletes the login database file on disk, and creates a new, empty database. // This can be used after migrating passwords to some other store, to ensure @@ -124,15 +127,15 @@ // successful, or returning false and leaving cipher_text unchanged if // encryption fails (e.g., if the underlying OS encryption system is // temporarily unavailable). - EncryptionResult EncryptedString(const base::string16& plain_text, - std::string* cipher_text) const; + static EncryptionResult EncryptedString(const base::string16& plain_text, + std::string* cipher_text); // Decrypts cipher_text, setting the value of plain_text and returning true if // successful, or returning false and leaving plain_text unchanged if // decryption fails (e.g., if the underlying OS encryption system is // temporarily unavailable). - EncryptionResult DecryptedString(const std::string& cipher_text, - base::string16* plain_text) const; + static EncryptionResult DecryptedString(const std::string& cipher_text, + base::string16* plain_text); bool InitLoginsTable(); bool MigrateOldVersionsAsNeeded(); @@ -141,15 +144,24 @@ // be of the form used by the Get*Logins methods). // Returns the EncryptionResult from decrypting the password in |s|; if not // ENCRYPTION_RESULT_SUCCESS, |form| is not filled. - EncryptionResult InitPasswordFormFromStatement(autofill::PasswordForm* form, - sql::Statement& s) const; + static EncryptionResult InitPasswordFormFromStatement( + autofill::PasswordForm* form, + sql::Statement& s); - // Loads all logins whose blacklist setting matches |blacklisted| into - // |forms|. + // Gets all blacklisted or all non-blacklisted (depending on |blacklisted|) + // credentials. On success returns true and overwrites |forms| with the + // result. bool GetAllLoginsWithBlacklistSetting( bool blacklisted, ScopedVector<autofill::PasswordForm>* forms) const; + // Overwrites |forms| with credentials retrieved from |statement|. If + // |psl_match| is not null, filters out all results but thos PSL-matching + // |*psl_match|. On success returns true. + static bool StatementToForms(sql::Statement* statement, + const autofill::PasswordForm* psl_match, + ScopedVector<autofill::PasswordForm>* forms); + base::FilePath db_path_; mutable sql::Connection db_; sql::MetaTable meta_table_;
diff --git a/components/password_manager/core/browser/login_database_mac.cc b/components/password_manager/core/browser/login_database_mac.cc index a957457..ad6eaa5 100644 --- a/components/password_manager/core/browser/login_database_mac.cc +++ b/components/password_manager/core/browser/login_database_mac.cc
@@ -10,16 +10,18 @@ namespace password_manager { +// static LoginDatabase::EncryptionResult LoginDatabase::EncryptedString( const base::string16& plain_text, - std::string* cipher_text) const { + std::string* cipher_text) { *cipher_text = std::string(); return ENCRYPTION_RESULT_SUCCESS; } +// static LoginDatabase::EncryptionResult LoginDatabase::DecryptedString( const std::string& cipher_text, - base::string16* plain_text) const { + base::string16* plain_text) { *plain_text = base::string16(); return ENCRYPTION_RESULT_SUCCESS; }
diff --git a/components/password_manager/core/browser/login_database_posix.cc b/components/password_manager/core/browser/login_database_posix.cc index a042612..a700d9c 100644 --- a/components/password_manager/core/browser/login_database_posix.cc +++ b/components/password_manager/core/browser/login_database_posix.cc
@@ -10,16 +10,18 @@ // TODO: Actually encrypt passwords on Linux. +// static LoginDatabase::EncryptionResult LoginDatabase::EncryptedString( const base::string16& plain_text, - std::string* cipher_text) const { + std::string* cipher_text) { *cipher_text = base::UTF16ToUTF8(plain_text); return ENCRYPTION_RESULT_SUCCESS; } +// static LoginDatabase::EncryptionResult LoginDatabase::DecryptedString( const std::string& cipher_text, - base::string16* plain_text) const { + base::string16* plain_text) { *plain_text = base::UTF8ToUTF16(cipher_text); return ENCRYPTION_RESULT_SUCCESS; }
diff --git a/components/password_manager/core/browser/login_database_win.cc b/components/password_manager/core/browser/login_database_win.cc index 19fd7dfe..2b2b272 100644 --- a/components/password_manager/core/browser/login_database_win.cc +++ b/components/password_manager/core/browser/login_database_win.cc
@@ -9,17 +9,19 @@ namespace password_manager { +// static LoginDatabase::EncryptionResult LoginDatabase::EncryptedString( const base::string16& plain_text, - std::string* cipher_text) const { + std::string* cipher_text) { if (OSCrypt::EncryptString16(plain_text, cipher_text)) return ENCRYPTION_RESULT_SUCCESS; return ENCRYPTION_RESULT_ITEM_FAILURE; } +// static LoginDatabase::EncryptionResult LoginDatabase::DecryptedString( const std::string& cipher_text, - base::string16* plain_text) const { + base::string16* plain_text) { if (OSCrypt::DecryptString16(cipher_text, plain_text)) return ENCRYPTION_RESULT_SUCCESS; return ENCRYPTION_RESULT_ITEM_FAILURE;
diff --git a/components/password_manager/core/browser/password_store_default.cc b/components/password_manager/core/browser/password_store_default.cc index 88f6e9e..4e24ad1 100644 --- a/components/password_manager/core/browser/password_store_default.cc +++ b/components/password_manager/core/browser/password_store_default.cc
@@ -115,33 +115,35 @@ const autofill::PasswordForm& form, AuthorizationPromptPolicy prompt_policy) { ScopedVector<autofill::PasswordForm> matched_forms; - if (login_db_) - login_db_->GetLogins(form, &matched_forms); + if (login_db_ && !login_db_->GetLogins(form, &matched_forms)) + return ScopedVector<autofill::PasswordForm>(); return matched_forms.Pass(); } void PasswordStoreDefault::GetAutofillableLoginsImpl( scoped_ptr<GetLoginsRequest> request) { - ScopedVector<autofill::PasswordForm> logins; - FillAutofillableLogins(&logins); + ScopedVector<PasswordForm> logins; + if (!FillAutofillableLogins(&logins)) + logins.clear(); request->NotifyConsumerWithResults(logins.Pass()); } void PasswordStoreDefault::GetBlacklistLoginsImpl( scoped_ptr<GetLoginsRequest> request) { - ScopedVector<autofill::PasswordForm> logins; - FillBlacklistLogins(&logins); + ScopedVector<PasswordForm> logins; + if (!FillBlacklistLogins(&logins)) + logins.clear(); request->NotifyConsumerWithResults(logins.Pass()); } bool PasswordStoreDefault::FillAutofillableLogins( - ScopedVector<autofill::PasswordForm>* forms) { + ScopedVector<PasswordForm>* forms) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); return login_db_ && login_db_->GetAutofillableLogins(forms); } bool PasswordStoreDefault::FillBlacklistLogins( - ScopedVector<autofill::PasswordForm>* forms) { + ScopedVector<PasswordForm>* forms) { DCHECK(GetBackgroundTaskRunner()->BelongsToCurrentThread()); return login_db_ && login_db_->GetBlacklistLogins(forms); }
diff --git a/components/password_manager/core/browser/password_store_sync.h b/components/password_manager/core/browser/password_store_sync.h index bed837a..731d338 100644 --- a/components/password_manager/core/browser/password_store_sync.h +++ b/components/password_manager/core/browser/password_store_sync.h
@@ -5,6 +5,7 @@ #ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_SYNC_INTERFACE_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_SYNC_INTERFACE_H_ +#include "base/compiler_specific.h" #include "base/memory/scoped_vector.h" #include "components/password_manager/core/browser/password_store_change.h" @@ -16,13 +17,15 @@ // thread only. class PasswordStoreSync { public: - // Finds all non-blacklist PasswordForms, and fills the vector. + // Overwrites |forms| with all stored non-blacklisted credentials. Returns + // true on success. virtual bool FillAutofillableLogins( - ScopedVector<autofill::PasswordForm>* forms) = 0; + ScopedVector<autofill::PasswordForm>* forms) WARN_UNUSED_RESULT = 0; - // Finds all blacklist PasswordForms, and fills the vector. - virtual bool FillBlacklistLogins( - ScopedVector<autofill::PasswordForm>* forms) = 0; + // Overwrites |forms| with all stored blacklisted credentials. Returns true on + // success. + virtual bool FillBlacklistLogins(ScopedVector<autofill::PasswordForm>* forms) + WARN_UNUSED_RESULT = 0; // Synchronous implementation to add the given login. virtual PasswordStoreChangeList AddLoginImpl(
diff --git a/components/password_manager/core/browser/password_syncable_service.cc b/components/password_manager/core/browser/password_syncable_service.cc index b036b50..870aecb 100644 --- a/components/password_manager/core/browser/password_syncable_service.cc +++ b/components/password_manager/core/browser/password_syncable_service.cc
@@ -303,8 +303,9 @@ ScopedVector<autofill::PasswordForm>* password_entries, PasswordEntryMap* passwords_entry_map) const { DCHECK(password_entries); + ScopedVector<autofill::PasswordForm> blacklist_entries; if (!password_store_->FillAutofillableLogins(password_entries) || - !password_store_->FillBlacklistLogins(password_entries)) { + !password_store_->FillBlacklistLogins(&blacklist_entries)) { // Password store often fails to load passwords. Track failures with UMA. // (http://crbug.com/249000) UMA_HISTOGRAM_ENUMERATION("Sync.LocalDataFailedToLoad", @@ -312,6 +313,12 @@ syncer::MODEL_TYPE_COUNT); return false; } + // Move |blacklist_entries| to |password_entries|. + password_entries->reserve(password_entries->size() + + blacklist_entries.size()); + password_entries->insert(password_entries->end(), blacklist_entries.begin(), + blacklist_entries.end()); + blacklist_entries.weak_clear(); if (!passwords_entry_map) return true;
diff --git a/components/plugins/renderer/loadable_plugin_placeholder.cc b/components/plugins/renderer/loadable_plugin_placeholder.cc index 8a5a0aa..f4e0369f 100644 --- a/components/plugins/renderer/loadable_plugin_placeholder.cc +++ b/components/plugins/renderer/loadable_plugin_placeholder.cc
@@ -128,20 +128,20 @@ if (!new_plugin) return; WebPluginContainer* container = plugin()->container(); - // Set the new plug-in on the container before initializing it. + // Set the new plugin on the container before initializing it. container->setPlugin(new_plugin); - // Save the element in case the plug-in is removed from the page during + // Save the element in case the plugin is removed from the page during // initialization. WebElement element = container->element(); bool plugin_needs_initialization = !premade_throttler_ || new_plugin != premade_throttler_->GetWebPlugin(); if (plugin_needs_initialization && !new_plugin->initialize(container)) { - // We couldn't initialize the new plug-in. Restore the old one and abort. + // We couldn't initialize the new plugin. Restore the old one and abort. container->setPlugin(plugin()); return; } - // The plug-in has been removed from the page. Destroy the old plug-in. We + // The plugin has been removed from the page. Destroy the old plugin. We // will be destroyed as soon as V8 garbage collects us. if (!element.pluginContainer()) { plugin()->destroy(); @@ -150,8 +150,8 @@ placeholder_was_replaced_ = true; - // During initialization, the new plug-in might have replaced itself in turn - // with another plug-in. Make sure not to use the passed in |new_plugin| after + // During initialization, the new plugin might have replaced itself in turn + // with another plugin. Make sure not to use the passed in |new_plugin| after // this point. new_plugin = container->plugin(); @@ -312,7 +312,7 @@ void LoadablePluginPlaceholder::LoadCallback() { RenderThread::Get()->RecordAction(UserMetricsAction("Plugin_Load_Click")); #if defined(ENABLE_PLUGINS) - // If the user specifically clicks on the plug-in content's placeholder, + // If the user specifically clicks on the plugin content's placeholder, // disable power saver throttling for this instance. MarkPluginEssential(PluginInstanceThrottler::UNTHROTTLE_METHOD_BY_CLICK); #endif
diff --git a/components/plugins/renderer/loadable_plugin_placeholder.h b/components/plugins/renderer/loadable_plugin_placeholder.h index bc09b73f..e67c861 100644 --- a/components/plugins/renderer/loadable_plugin_placeholder.h +++ b/components/plugins/renderer/loadable_plugin_placeholder.h
@@ -11,7 +11,7 @@ #include "content/public/renderer/plugin_instance_throttler.h" namespace plugins { -// Placeholders can be used if a plug-in is missing or not available +// Placeholders can be used if a plugin is missing or not available // (blocked or disabled). class LoadablePluginPlaceholder : public PluginPlaceholder, @@ -30,7 +30,7 @@ power_saver_enabled_ = power_saver_enabled; } - // Defer loading of plug-in, and instead show the Power Saver poster image. + // Defer loading of plugin, and instead show the Power Saver poster image. void BlockForPowerSaverPoster(); #endif
diff --git a/components/plugins/renderer/webview_plugin.h b/components/plugins/renderer/webview_plugin.h index cb3f5a6..3b7cd67c9 100644 --- a/components/plugins/renderer/webview_plugin.h +++ b/components/plugins/renderer/webview_plugin.h
@@ -60,9 +60,9 @@ blink::WebView* web_view() { return web_view_; } - // When loading a plug-in document (i.e. a full page plug-in not embedded in + // When loading a plugin document (i.e. a full page plugin not embedded in // another page), we save all data that has been received, and replay it with - // this method on the actual plug-in. + // this method on the actual plugin. void ReplayReceivedData(blink::WebPlugin* plugin); void RestoreTitleText();
diff --git a/components/test/data/password_manager/automated_tests/environment.py b/components/test/data/password_manager/automated_tests/environment.py index 71eca92..dddd8944 100644 --- a/components/test/data/password_manager/automated_tests/environment.py +++ b/components/test/data/password_manager/automated_tests/environment.py
@@ -276,7 +276,7 @@ return False def CheckForNewMessage(self, log_message, message_should_show_up, - error_message, timeout=3): + error_message, timeout=15): """Detects whether the save password prompt is shown. Args:
diff --git a/components/test/data/password_manager/automated_tests/tests.py b/components/test/data/password_manager/automated_tests/tests.py index 5388b3a..f8ecd2a9 100644 --- a/components/test/data/password_manager/automated_tests/tests.py +++ b/components/test/data/password_manager/automated_tests/tests.py
@@ -55,6 +55,15 @@ self.Submit("[name='pass']") +class Github(WebsiteTest): + + def Login(self): + self.GoTo("https://github.com/login") + self.FillUsernameInto("[name='login']") + self.FillPasswordInto("[name='password']") + self.Submit("[name='commit']") + + class Google(WebsiteTest): def Login(self): @@ -154,6 +163,15 @@ self.Submit("#signin-password") +class Vkontakte(WebsiteTest): + + def Login(self): + self.GoTo("https:///vk.com") + self.FillUsernameInto("[name='email']") + self.FillPasswordInto("[name='pass']") + self.Submit("[name='pass']") + + class Wikia(WebsiteTest): def Login(self): @@ -216,6 +234,39 @@ self.Click("#fm-login-submit") +# Fails to save password. +class Adobe(WebsiteTest): + + def Login(self): + self.GoTo("https://adobeid-na1.services.adobe.com/renga-idprovider/pages/l" + "ogin?callback=https%3A%2F%2Fims-na1.adobelogin.com%2Fims%2Fadob" + "eid%2Fadobedotcom2%2FAdobeID%2Ftoken%3Fredirect_uri%3Dhttps%253" + "A%252F%252Fwww.adobe.com%252F%2523from_ims%253Dtrue%2526old_has" + "h%253D%2526client_id%253Dadobedotcom2%2526scope%253Dcreative_cl" + "oud%25252CAdobeID%25252Copenid%25252Cgnav%25252Cread_organizati" + "ons%25252Cadditional_info.projectedProductContext%2526api%253Da" + "uthorize&client_id=adobedotcom2&scope=creative_cloud%2CAdobeID%" + "2Copenid%2Cgnav%2Cread_organizations%2Cadditional_info.projecte" + "dProductContext&display=web_v2&denied_callback=https%3A%2F%2Fim" + "s-na1.adobelogin.com%2Fims%2Fdenied%2Fadobedotcom2%3Fredirect_u" + "ri%3Dhttps%253A%252F%252Fwww.adobe.com%252F%2523from_ims%253Dtr" + "ue%2526old_hash%253D%2526client_id%253Dadobedotcom2%2526scope%2" + "53Dcreative_cloud%25252CAdobeID%25252Copenid%25252Cgnav%25252Cr" + "ead_organizations%25252Cadditional_info.projectedProductContext" + "%2526api%253Dauthorize%26response_type%3Dtoken&relay=afebfef8-e" + "2b3-4c0e-9c94-07baf205bae8&locale=en_US&flow_type=token&dc=fals" + "e&client_redirect=https%3A%2F%2Fims-na1.adobelogin.com%2Fims%2F" + "redirect%2Fadobedotcom2%3Fclient_redirect%3Dhttps%253A%252F%252" + "Fwww.adobe.com%252F%2523from_ims%253Dtrue%2526old_hash%253D%252" + "6client_id%253Dadobedotcom2%2526scope%253Dcreative_cloud%25252C" + "AdobeID%25252Copenid%25252Cgnav%25252Cread_organizations%25252C" + "additional_info.projectedProductContext%2526api%253Dauthorize&i" + "dp_flow_type=login") + self.FillUsernameInto("[name='username']") + self.FillPasswordInto("[name='password']") + self.Submit("#sign_in") + + # Bug not reproducible without test. class Amazon(WebsiteTest): @@ -396,6 +447,7 @@ "alexa": Alexa("alexa"), "dropbox": Dropbox("dropbox"), "facebook": Facebook("facebook"), + "github": Github("github"), "google": Google("google"), "imgur": Imgur("imgur"), "liveinternet": Liveinternet("liveinternet"), @@ -407,6 +459,7 @@ "reddit": Reddit("reddit", username_not_auto=True), "tumblr": Tumblr("tumblr", username_not_auto=True), "twitter": Twitter("twitter"), + "vkontakte": Vkontakte("vkontakte"), "wikia": Wikia("wikia"), "wikipedia": Wikipedia("wikipedia", username_not_auto=True), "wordpress": Wordpress("wordpress"), @@ -415,6 +468,7 @@ } disabled_tests = { + "adobe": Adobe("adobe"), # Password saving not offered. "aliexpress": Aliexpress("aliexpress"), # Fails due to test framework issue. "amazon": Amazon("amazon"), # Bug not reproducible without test. "ask": Ask("ask"), # Password not saved. @@ -429,7 +483,7 @@ "live": Live("live", username_not_auto=True), # http://crbug.com/367768 "163": One63("163"), # http://crbug.com/368690 "vube": Vube("vube"), # http://crbug.com/368690 - "ziddu": Ziddu("ziddu"), #Password not saved + "ziddu": Ziddu("ziddu"), # Password not saved. } if tests_to_run:
diff --git a/content/app/strings/content_strings.grd b/content/app/strings/content_strings.grd index f8667ec6..24deef1 100644 --- a/content/app/strings/content_strings.grd +++ b/content/app/strings/content_strings.grd
@@ -743,8 +743,8 @@ Please lengthen this text to <ph name="MIN_CHARACTERS">$2<ex>101</ex></ph> characters or more (you are currently using <ph name="CURRENT_LENGTH">$1<ex>100</ex></ph> characters). </message> - <message name="IDS_PLUGIN_INITIALIZATION_ERROR" desc="A message displayed when a plug-in failed to load"> - Couldn't load plug-in. + <message name="IDS_PLUGIN_INITIALIZATION_ERROR" desc="A message displayed when a plugin failed to load"> + Couldn't load plugin. </message> </messages>
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 294fe13..36d59a8 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -121,7 +121,10 @@ ] } - configs += [ "//content:content_implementation" ] + configs += [ + "//content:content_implementation", + "//third_party/WebKit/public:debug_devtools", + ] if (toolkit_views) { deps += [ "//ui/events" ]
diff --git a/content/browser/DEPS b/content/browser/DEPS index f7d65fb..956e503 100644 --- a/content/browser/DEPS +++ b/content/browser/DEPS
@@ -68,6 +68,7 @@ "+third_party/WebKit/public/web/WebCompositionUnderline.h", "+third_party/WebKit/public/web/WebConsoleMessage.h", "+third_party/WebKit/public/web/WebContentSecurityPolicy.h", + "+third_party/WebKit/public/web/WebDeviceEmulationParams.h", "+third_party/WebKit/public/web/WebDragOperation.h", "+third_party/WebKit/public/web/WebDragStatus.h", "+third_party/WebKit/public/web/WebFindOptions.h",
diff --git a/content/browser/browser_main_loop.cc b/content/browser/browser_main_loop.cc index cbb70ac6..bf495b9a 100644 --- a/content/browser/browser_main_loop.cc +++ b/content/browser/browser_main_loop.cc
@@ -41,6 +41,7 @@ #include "content/browser/webui/content_web_ui_controller_factory.h" #include "content/browser/webui/url_data_manager.h" #include "content/common/content_switches_internal.h" +#include "content/common/host_discardable_shared_memory_manager.h" #include "content/public/browser/browser_main_parts.h" #include "content/public/browser/browser_shutdown.h" #include "content/public/browser/content_browser_client.h" @@ -460,6 +461,9 @@ gfx::GpuMemoryBuffer::SCANOUT); #endif + base::DiscardableMemoryShmemAllocator::SetInstance( + HostDiscardableSharedMemoryManager::current()); + if (parts_) parts_->PostEarlyInitialization(); }
diff --git a/content/browser/browser_side_navigation_browsertest.cc b/content/browser/browser_side_navigation_browsertest.cc index c22dc7ef..4bba0ee 100644 --- a/content/browser/browser_side_navigation_browsertest.cc +++ b/content/browser/browser_side_navigation_browsertest.cc
@@ -154,8 +154,8 @@ EXPECT_TRUE(observer.last_navigation_succeeded()); } - // The RenderFrameHost should have changed. - EXPECT_NE(initial_rfh, static_cast<WebContentsImpl*>(shell()->web_contents()) + // The RenderFrameHost should not have changed. + EXPECT_EQ(initial_rfh, static_cast<WebContentsImpl*>(shell()->web_contents()) ->GetFrameTree()->root()->current_frame_host()); }
diff --git a/content/browser/devtools/protocol/page_handler.cc b/content/browser/devtools/protocol/page_handler.cc index 009f7e73..8bb70eeb 100644 --- a/content/browser/devtools/protocol/page_handler.cc +++ b/content/browser/devtools/protocol/page_handler.cc
@@ -9,6 +9,7 @@ #include "base/base64.h" #include "base/bind.h" #include "base/strings/string16.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/worker_pool.h" #include "content/browser/devtools/protocol/color_picker.h" @@ -106,6 +107,7 @@ PageHandler::PageHandler() : enabled_(false), touch_emulation_enabled_(false), + device_emulation_enabled_(false), screencast_enabled_(false), screencast_quality_(kDefaultScreenshotQuality), screencast_max_width_(-1), @@ -133,6 +135,7 @@ frame_recorder_->SetRenderViewHost(host); host_ = host; UpdateTouchEventEmulationState(); + UpdateDeviceEmulationState(); } void PageHandler::SetClient(scoped_ptr<Client> client) { @@ -183,7 +186,9 @@ enabled_ = false; touch_emulation_enabled_ = false; screencast_enabled_ = false; + device_emulation_enabled_ = false; UpdateTouchEventEmulationState(); + UpdateDeviceEmulationState(); color_picker_->SetEnabled(false); return Response::FallThrough(); } @@ -342,7 +347,10 @@ #else if (host_) { if (WebContents* web_contents = WebContents::FromRenderViewHost(host_)) { - *result = !web_contents->GetVisibleURL().SchemeIs(kChromeDevToolsScheme); + *result = web_contents->GetMainFrame()->GetRenderViewHost() == host_; +#if defined(DEBUG_DEVTOOLS) + *result &= !web_contents->GetVisibleURL().SchemeIs(kChromeDevToolsScheme); +#endif // defined(DEBUG_DEVTOOLS) } else { *result = true; } @@ -357,11 +365,54 @@ int width, int height, double device_scale_factor, bool mobile, bool fit_window, const double* optional_scale, const double* optional_offset_x, const double* optional_offset_y) { - return Response::FallThrough(); + const static int max_size = 10000000; + const static double max_scale = 10; + + if (!host_) + return Response::InternalError("Could not connect to view"); + + if (width < 0 || height < 0 || width > max_size || height > max_size) { + return Response::InvalidParams( + "Width and height values must be positive, not greater than " + + base::IntToString(max_size)); + } + + if (device_scale_factor < 0) + return Response::InvalidParams("deviceScaleFactor must be non-negative"); + + if (optional_scale && (*optional_scale <= 0 || *optional_scale > max_scale)) { + return Response::InvalidParams( + "scale must be positive, not greater than " + + base::IntToString(max_scale)); + } + + blink::WebDeviceEmulationParams params; + params.screenPosition = mobile ? blink::WebDeviceEmulationParams::Mobile : + blink::WebDeviceEmulationParams::Desktop; + params.deviceScaleFactor = device_scale_factor; + params.viewSize = blink::WebSize(width, height); + params.fitToView = fit_window; + params.scale = optional_scale ? *optional_scale : 1; + params.offset = blink::WebFloatPoint( + optional_offset_x ? *optional_offset_x : 0.f, + optional_offset_y ? *optional_offset_y : 0.f); + + if (device_emulation_enabled_ && params == device_emulation_params_) + return Response::OK(); + + device_emulation_enabled_ = true; + device_emulation_params_ = params; + UpdateDeviceEmulationState(); + return Response::OK(); } Response PageHandler::ClearDeviceMetricsOverride() { - return Response::FallThrough(); + if (!device_emulation_enabled_) + return Response::OK(); + + device_emulation_enabled_ = false; + UpdateDeviceEmulationState(); + return Response::OK(); } Response PageHandler::StartScreencast(const std::string* format, @@ -464,6 +515,17 @@ web_contents->SetForceDisableOverscrollContent(enabled); } +void PageHandler::UpdateDeviceEmulationState() { + if (!host_) + return; + if (device_emulation_enabled_) { + host_->Send(new ViewMsg_EnableDeviceEmulation( + host_->GetRoutingID(), device_emulation_params_)); + } else { + host_->Send(new ViewMsg_DisableDeviceEmulation(host_->GetRoutingID())); + } +} + void PageHandler::NotifyScreencastVisibility(bool visible) { if (visible) capture_retry_count_ = kCaptureRetryLimit;
diff --git a/content/browser/devtools/protocol/page_handler.h b/content/browser/devtools/protocol/page_handler.h index 4b5b14c6..6777a6a 100644 --- a/content/browser/devtools/protocol/page_handler.h +++ b/content/browser/devtools/protocol/page_handler.h
@@ -12,6 +12,7 @@ #include "cc/output/compositor_frame_metadata.h" #include "content/browser/devtools/protocol/devtools_protocol_handler.h" #include "content/public/browser/readback_types.h" +#include "third_party/WebKit/public/web/WebDeviceEmulationParams.h" class SkBitmap; @@ -99,6 +100,7 @@ private: void UpdateTouchEventEmulationState(); + void UpdateDeviceEmulationState(); void NotifyScreencastVisibility(bool visible); void InnerSwapCompositorFrame(); @@ -120,9 +122,13 @@ scoped_refptr<StopRecordingFramesResponse> response_data); bool enabled_; + bool touch_emulation_enabled_; std::string touch_emulation_configuration_; + bool device_emulation_enabled_; + blink::WebDeviceEmulationParams device_emulation_params_; + bool screencast_enabled_; std::string screencast_format_; int screencast_quality_;
diff --git a/content/browser/frame_host/frame_navigation_entry.cc b/content/browser/frame_host/frame_navigation_entry.cc index 712fc63d..a33f973 100644 --- a/content/browser/frame_host/frame_navigation_entry.cc +++ b/content/browser/frame_host/frame_navigation_entry.cc
@@ -18,4 +18,14 @@ FrameNavigationEntry::~FrameNavigationEntry() { } +FrameNavigationEntry* FrameNavigationEntry::Clone() const { + FrameNavigationEntry* copy = new FrameNavigationEntry(); + + copy->site_instance_ = site_instance_; + copy->url_ = url_; + copy->referrer_ = referrer_; + + return copy; +} + } // namespace content
diff --git a/content/browser/frame_host/frame_navigation_entry.h b/content/browser/frame_host/frame_navigation_entry.h index 622b682..2d38a25 100644 --- a/content/browser/frame_host/frame_navigation_entry.h +++ b/content/browser/frame_host/frame_navigation_entry.h
@@ -14,19 +14,24 @@ // Represents a session history item for a particular frame. // -// This class is currently owned by a single NavigationEntry and only tracks the -// main frame. +// This class is refcounted and can be shared across multiple NavigationEntries. +// For now, it is owned by a single NavigationEntry and only tracks the main +// frame. // -// TODO(creis): Keep a tree of FrameNavigationEntries in each NavigationEntry, -// one per frame. FrameNavigationEntries may be shared across NavigationEntries -// if the frame hasn't changed. -class CONTENT_EXPORT FrameNavigationEntry { +// TODO(creis): In --site-per-process, fill in a tree of FrameNavigationEntries +// in each NavigationEntry, one per frame. FrameNavigationEntries may be shared +// across NavigationEntries if the frame hasn't changed. +class CONTENT_EXPORT FrameNavigationEntry + : public base::RefCounted<FrameNavigationEntry> { public: FrameNavigationEntry(); FrameNavigationEntry(SiteInstanceImpl* site_instance, const GURL& url, const Referrer& referrer); - virtual ~FrameNavigationEntry(); + + // Creates a copy of this FrameNavigationEntry that can be modified + // independently from the original. + FrameNavigationEntry* Clone() const; // The SiteInstance responsible for rendering this frame. All frames sharing // a SiteInstance must live in the same process. This is a refcounted pointer @@ -39,7 +44,6 @@ // The actual URL loaded in the frame. This is in contrast to the virtual // URL, which is shown to the user. - // TODO(creis): Move virtual URL and related members to FrameNavigationEntry. void set_url(const GURL& url) { url_ = url; } const GURL& url() const { return url_; } @@ -48,15 +52,21 @@ const Referrer& referrer() const { return referrer_; } private: + friend class base::RefCounted<FrameNavigationEntry>; + virtual ~FrameNavigationEntry(); + + // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING + // For all new fields, update |Clone|. // TODO(creis): These fields have implications for session restore. This is // currently managed by NavigationEntry, but the logic will move here. + // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING // See the accessors above for descriptions. scoped_refptr<SiteInstanceImpl> site_instance_; GURL url_; Referrer referrer_; - // Copy and assignment is explicitly allowed for this class. + DISALLOW_COPY_AND_ASSIGN(FrameNavigationEntry); }; } // namespace content
diff --git a/content/browser/frame_host/navigation_controller_impl_unittest.cc b/content/browser/frame_host/navigation_controller_impl_unittest.cc index e5ce4932..63e14bc6 100644 --- a/content/browser/frame_host/navigation_controller_impl_unittest.cc +++ b/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -787,9 +787,12 @@ kExistingURL2, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); EXPECT_EQ(0U, notifications.size()); - // After the beforeunload but before it commits, do a new navigation. + // After the beforeunload but before it commits... main_test_rfh()->PrepareForCommit(); + + // ... Do a new navigation. const GURL kNewURL("http://see"); + main_test_rfh()->SendRendererInitiatedNavigationRequest(kNewURL, true); main_test_rfh()->PrepareForCommit(); contents()->GetMainFrame()->SendNavigate(3, kNewURL); @@ -1009,6 +1012,7 @@ const GURL kNewURL("http://eh"); controller.LoadURL( kNewURL, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); + main_test_rfh()->PrepareForCommit(); EXPECT_EQ(0U, notifications.size()); EXPECT_EQ(-1, controller.GetPendingEntryIndex()); EXPECT_TRUE(controller.GetPendingEntry()); @@ -1635,11 +1639,13 @@ const GURL url1("http://foo1"); const GURL url2("http://foo2"); + main_test_rfh()->SendRendererInitiatedNavigationRequest(url1, true); main_test_rfh()->PrepareForCommit(); main_test_rfh()->SendNavigate(0, url1); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; + main_test_rfh()->SendRendererInitiatedNavigationRequest(url2, true); main_test_rfh()->PrepareForCommit(); main_test_rfh()->SendNavigate(1, url2); EXPECT_EQ(1U, navigation_entry_committed_counter_); @@ -1704,10 +1710,12 @@ const GURL url2("http://foo2"); const GURL url3("http://foo3"); + main_test_rfh()->SendRendererInitiatedNavigationRequest(url1, true); main_test_rfh()->PrepareForCommit(); main_test_rfh()->SendNavigate(0, url1); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; + main_test_rfh()->SendRendererInitiatedNavigationRequest(url2, true); main_test_rfh()->PrepareForCommit(); main_test_rfh()->SendNavigate(1, url2); EXPECT_EQ(1U, navigation_entry_committed_counter_);
diff --git a/content/browser/frame_host/navigation_entry_impl.cc b/content/browser/frame_host/navigation_entry_impl.cc index 5f156cd..c7a84de7 100644 --- a/content/browser/frame_host/navigation_entry_impl.cc +++ b/content/browser/frame_host/navigation_entry_impl.cc
@@ -25,6 +25,22 @@ int NavigationEntryImpl::kInvalidBindings = -1; +NavigationEntryImpl::TreeNode::TreeNode(FrameNavigationEntry* frame_entry) + : frame_entry(frame_entry) { +} + +NavigationEntryImpl::TreeNode::~TreeNode() { +} + +NavigationEntryImpl::TreeNode* NavigationEntryImpl::TreeNode::Clone() const { + // Clone the tree using a copy of the FrameNavigationEntry, without sharing. + NavigationEntryImpl::TreeNode* copy = + new NavigationEntryImpl::TreeNode(frame_entry->Clone()); + + // TODO(creis): Clone children once we add them. + return copy; +} + NavigationEntry* NavigationEntry::Create() { return new NavigationEntryImpl(); } @@ -46,7 +62,8 @@ const base::string16& title, ui::PageTransition transition_type, bool is_renderer_initiated) - : frame_entry_(instance, url, referrer), + : frame_tree_( + new TreeNode(new FrameNavigationEntry(instance, url, referrer))), unique_id_(GetUniqueIDInConstructor()), bindings_(kInvalidBindings), page_type_(PAGE_TYPE_NORMAL), @@ -78,12 +95,12 @@ } void NavigationEntryImpl::SetURL(const GURL& url) { - frame_entry_.set_url(url); + frame_tree_->frame_entry->set_url(url); cached_display_title_.clear(); } const GURL& NavigationEntryImpl::GetURL() const { - return frame_entry_.url(); + return frame_tree_->frame_entry->url(); } void NavigationEntryImpl::SetBaseURLForDataURL(const GURL& url) { @@ -95,11 +112,11 @@ } void NavigationEntryImpl::SetReferrer(const Referrer& referrer) { - frame_entry_.set_referrer(referrer); + frame_tree_->frame_entry->set_referrer(referrer); } const Referrer& NavigationEntryImpl::GetReferrer() const { - return frame_entry_.referrer(); + return frame_tree_->frame_entry->referrer(); } void NavigationEntryImpl::SetVirtualURL(const GURL& url) { @@ -137,7 +154,8 @@ } void NavigationEntryImpl::set_site_instance(SiteInstanceImpl* site_instance) { - frame_entry_.set_site_instance(site_instance); + // TODO(creis): Update all callers and remove this method. + frame_tree_->frame_entry->set_site_instance(site_instance); } void NavigationEntryImpl::set_source_site_instance( @@ -326,10 +344,9 @@ NavigationEntryImpl* NavigationEntryImpl::Clone() const { NavigationEntryImpl* copy = new NavigationEntryImpl(); - // TODO(creis): Once we have a tree of FrameNavigationEntries, make a deep - // copy. Only share the same FrameNavigationEntries if cloning within the - // same tab. - copy->frame_entry_ = frame_entry_; + // TODO(creis): Only share the same FrameNavigationEntries if cloning within + // the same tab. + copy->frame_tree_.reset(frame_tree_->Clone()); // Copy all state over, unless cleared in ResetForCommit. copy->unique_id_ = unique_id_;
diff --git a/content/browser/frame_host/navigation_entry_impl.h b/content/browser/frame_host/navigation_entry_impl.h index d680e9b..0528da0d 100644 --- a/content/browser/frame_host/navigation_entry_impl.h +++ b/content/browser/frame_host/navigation_entry_impl.h
@@ -27,6 +27,25 @@ class CONTENT_EXPORT NavigationEntryImpl : public NON_EXPORTED_BASE(NavigationEntry) { public: + // Represents a tree of FrameNavigationEntries that make up this joint session + // history item. The tree currently only tracks the main frame. + // TODO(creis): Populate the tree with subframe entries in --site-per-process. + struct TreeNode { + TreeNode(FrameNavigationEntry* frame_entry); + ~TreeNode(); + + // Returns a deep copy of the tree with copies of each node's + // FrameNavigationEntries. We do not yet share FrameNavigationEntries + // across trees. + // TODO(creis): For --site-per-process, share FrameNavigationEntries between + // NavigationEntries of the same tab. + TreeNode* Clone() const; + + // Ref counted pointer that keeps the FrameNavigationEntry alive as long as + // it is needed by this node's NavigationEntry. + scoped_refptr<FrameNavigationEntry> frame_entry; + }; + static NavigationEntryImpl* FromNavigationEntry(NavigationEntry* entry); // The value of bindings() before it is set during commit. @@ -121,7 +140,7 @@ // different SiteInstance. void set_site_instance(SiteInstanceImpl* site_instance); SiteInstanceImpl* site_instance() const { - return frame_entry_.site_instance(); + return frame_tree_->frame_entry->site_instance(); } // The |source_site_instance| is used to identify the SiteInstance of the @@ -271,9 +290,11 @@ // For all new fields, update |Clone| and possibly |ResetForCommit|. // WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING - // The FrameNavigationEntry for the main frame. - // TODO(creis): Make this a tree with nodes for each frame in the page. - FrameNavigationEntry frame_entry_; + // Tree of FrameNavigationEntries, one for each frame on the page. + // TODO(creis): Once FrameNavigationEntries can be shared across multiple + // NavigationEntries, we will need to update Session/Tab restore. For now, + // each NavigationEntry's tree has its own unshared FrameNavigationEntries. + scoped_ptr<TreeNode> frame_tree_; // See the accessors above for descriptions. int unique_id_;
diff --git a/content/browser/frame_host/navigator_impl_unittest.cc b/content/browser/frame_host/navigator_impl_unittest.cc index d7e41e5..d5b9da6 100644 --- a/content/browser/frame_host/navigator_impl_unittest.cc +++ b/content/browser/frame_host/navigator_impl_unittest.cc
@@ -154,7 +154,7 @@ // PlzNavigate: Test a complete renderer-initiated same-site navigation. TEST_F(NavigatorTestWithBrowserSideNavigation, - SimpleRendererInitiatedNavigation) { + SimpleRendererInitiatedSameSiteNavigation) { const GURL kUrl1("http://www.chromium.org/"); const GURL kUrl2("http://www.chromium.org/Home"); @@ -194,6 +194,52 @@ EXPECT_FALSE(node->render_manager()->pending_frame_host()); } +// PlzNavigate: Test a complete renderer-initiated navigation that should be +// cross-site but does not result in a SiteInstance swap because its +// renderer-initiated. +TEST_F(NavigatorTestWithBrowserSideNavigation, + SimpleRendererInitiatedCrossSiteNavigation) { + const GURL kUrl1("http://www.chromium.org/"); + const GURL kUrl2("http://www.google.com"); + + contents()->NavigateAndCommit(kUrl1); + EXPECT_TRUE(main_test_rfh()->IsRenderFrameLive()); + int32 site_instance_id_1 = main_test_rfh()->GetSiteInstance()->GetId(); + + // Start a renderer-initiated non-user-initiated navigation. + process()->sink().ClearMessages(); + main_test_rfh()->SendRendererInitiatedNavigationRequest(kUrl2, false); + FrameTreeNode* node = main_test_rfh()->frame_tree_node(); + NavigationRequest* request = GetNavigationRequestForFrameTreeNode(node); + ASSERT_TRUE(request); + + // The navigation is immediately started as there's no need to wait for + // beforeUnload to be executed. + EXPECT_EQ(NavigationRequest::STARTED, request->state()); + EXPECT_FALSE(request->begin_params().has_user_gesture); + EXPECT_EQ(kUrl2, request->common_params().url); + EXPECT_FALSE(request->browser_initiated()); + EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)); + + // Have the current RenderFrameHost commit the navigation. + scoped_refptr<ResourceResponse> response(new ResourceResponse); + GetLoaderForNavigationRequest(request) + ->CallOnResponseStarted(response, MakeEmptyStream()); + EXPECT_TRUE(DidRenderFrameHostRequestCommit(main_test_rfh())); + EXPECT_EQ(NavigationRequest::RESPONSE_STARTED, request->state()); + + // Commit the navigation. + main_test_rfh()->SendNavigate(0, kUrl2); + EXPECT_EQ(RenderFrameHostImpl::STATE_DEFAULT, main_test_rfh()->rfh_state()); + EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL()); + EXPECT_FALSE(GetNavigationRequestForFrameTreeNode(node)); + EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)); + EXPECT_FALSE(node->render_manager()->pending_frame_host()); + + // The SiteInstance did not change. + EXPECT_EQ(site_instance_id_1, main_test_rfh()->GetSiteInstance()->GetId()); +} + // PlzNavigate: Test that a beforeUnload denial cancels the navigation. TEST_F(NavigatorTestWithBrowserSideNavigation, BeforeUnloadDenialCancelNavigation) { @@ -542,10 +588,8 @@ GetLoaderForNavigationRequest(request1)->AsWeakPtr(); EXPECT_TRUE(loader1); - // Confirm a speculative RenderFrameHost was created. - TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node); - ASSERT_TRUE(speculative_rfh); - int32 site_instance_id_1 = speculative_rfh->GetSiteInstance()->GetId(); + // Confirm that a speculative RenderFrameHost was created. + ASSERT_TRUE(GetSpeculativeRenderFrameHost(node)); // Now receive a renderer-initiated user-initiated request. It should replace // the current NavigationRequest. @@ -559,28 +603,21 @@ // Confirm that the first loader got destroyed. EXPECT_FALSE(loader1); - // Confirm that a new speculative RenderFrameHost was created. - speculative_rfh = GetSpeculativeRenderFrameHost(node); - ASSERT_TRUE(speculative_rfh); - int32 site_instance_id_2 = speculative_rfh->GetSiteInstance()->GetId(); - EXPECT_NE(site_instance_id_1, site_instance_id_2); + // Confirm that the speculative RenderFrameHost was destroyed. + EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)); // Have the RenderFrameHost commit the navigation. scoped_refptr<ResourceResponse> response(new ResourceResponse); GetLoaderForNavigationRequest(request2) ->CallOnResponseStarted(response, MakeEmptyStream()); - EXPECT_TRUE(DidRenderFrameHostRequestCommit(speculative_rfh)); - EXPECT_FALSE(DidRenderFrameHostRequestCommit(main_test_rfh())); + EXPECT_TRUE(DidRenderFrameHostRequestCommit(main_test_rfh())); // Commit the navigation. - speculative_rfh->SendNavigate(0, kUrl2); + main_test_rfh()->SendNavigate(0, kUrl2); // Confirm that the commit corresponds to the new request. ASSERT_TRUE(main_test_rfh()); EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL()); - - // Confirm that the committed RenderFrameHost is the latest speculative one. - EXPECT_EQ(site_instance_id_2, main_test_rfh()->GetSiteInstance()->GetId()); } // PlzNavigate: Test that a renderer-initiated user-initiated navigation is NOT @@ -604,7 +641,7 @@ EXPECT_EQ(kUrl1, request1->common_params().url); EXPECT_FALSE(request1->browser_initiated()); EXPECT_TRUE(request1->begin_params().has_user_gesture); - EXPECT_TRUE(GetSpeculativeRenderFrameHost(node)); + EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)); // Now receive a renderer-initiated non-user-initiated request. Nothing should // change. @@ -615,18 +652,16 @@ EXPECT_EQ(kUrl1, request2->common_params().url); EXPECT_FALSE(request2->browser_initiated()); EXPECT_TRUE(request2->begin_params().has_user_gesture); - TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node); - ASSERT_TRUE(speculative_rfh); + EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)); // Have the RenderFrameHost commit the navigation. scoped_refptr<ResourceResponse> response(new ResourceResponse); GetLoaderForNavigationRequest(request2) ->CallOnResponseStarted(response, MakeEmptyStream()); - EXPECT_TRUE(DidRenderFrameHostRequestCommit(speculative_rfh)); - EXPECT_FALSE(DidRenderFrameHostRequestCommit(main_test_rfh())); + EXPECT_TRUE(DidRenderFrameHostRequestCommit(main_test_rfh())); // Commit the navigation. - speculative_rfh->SendNavigate(0, kUrl1); + main_test_rfh()->SendNavigate(0, kUrl1); EXPECT_EQ(kUrl1, contents()->GetLastCommittedURL()); } @@ -689,6 +724,7 @@ // Initialization. contents()->NavigateAndCommit(kUrl0); FrameTreeNode* node = main_test_rfh()->frame_tree_node(); + int32 site_instance_id_0 = main_test_rfh()->GetSiteInstance()->GetId(); // Start a renderer-initiated non-user-initiated navigation to the 1st URL. process()->sink().ClearMessages(); @@ -698,7 +734,7 @@ EXPECT_EQ(kUrl1, request1->common_params().url); EXPECT_FALSE(request1->browser_initiated()); EXPECT_FALSE(request1->begin_params().has_user_gesture); - EXPECT_TRUE(GetSpeculativeRenderFrameHost(node)); + EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)); base::WeakPtr<TestNavigationURLLoader> loader1 = GetLoaderForNavigationRequest(request1)->AsWeakPtr(); EXPECT_TRUE(loader1); @@ -709,8 +745,7 @@ EXPECT_EQ(kUrl2, request2->common_params().url); EXPECT_FALSE(request2->browser_initiated()); EXPECT_FALSE(request2->begin_params().has_user_gesture); - TestRenderFrameHost* speculative_rfh = GetSpeculativeRenderFrameHost(node); - ASSERT_TRUE(speculative_rfh); + EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)); // Confirm that the first loader got destroyed. EXPECT_FALSE(loader1); @@ -719,12 +754,14 @@ scoped_refptr<ResourceResponse> response(new ResourceResponse); GetLoaderForNavigationRequest(request2) ->CallOnResponseStarted(response, MakeEmptyStream()); - EXPECT_TRUE(DidRenderFrameHostRequestCommit(speculative_rfh)); - EXPECT_FALSE(DidRenderFrameHostRequestCommit(main_test_rfh())); + EXPECT_TRUE(DidRenderFrameHostRequestCommit(main_test_rfh())); // Commit the navigation. - speculative_rfh->SendNavigate(0, kUrl2); + main_test_rfh()->SendNavigate(0, kUrl2); EXPECT_EQ(kUrl2, contents()->GetLastCommittedURL()); + + // The SiteInstance did not change. + EXPECT_EQ(site_instance_id_0, main_test_rfh()->GetSiteInstance()->GetId()); } // PlzNavigate: Test that a reload navigation is properly signaled to the @@ -968,10 +1005,7 @@ EXPECT_EQ(NavigationRequest::RESPONSE_STARTED, navigation_request->state()); EXPECT_FALSE(navigation_request->loader_for_testing()); - speculative_rfh = GetSpeculativeRenderFrameHost(node); - ASSERT_TRUE(speculative_rfh); - speculative_rfh->SendNavigate(0, kUrl2); - EXPECT_EQ(main_test_rfh(), speculative_rfh); + EXPECT_FALSE(GetSpeculativeRenderFrameHost(node)); } } // namespace content
diff --git a/content/browser/frame_host/render_frame_host_impl_browsertest.cc b/content/browser/frame_host/render_frame_host_impl_browsertest.cc index f80f7ee..a704d16c 100644 --- a/content/browser/frame_host/render_frame_host_impl_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_impl_browsertest.cc
@@ -114,8 +114,14 @@ // Test that a frame is visible/hidden depending on its WebContents visibility // state. +// Flaky on Mac. http://crbug.com/467670 +#if defined(OS_MACOSX) +#define MAYBE_GetVisibilityState_Basic DISABLED_GetVisibilityState_Basic +#else +#define MAYBE_GetVisibilityState_Basic GetVisibilityState_Basic +#endif IN_PROC_BROWSER_TEST_F(RenderFrameHostImplBrowserTest, - GetVisibilityState_Basic) { + MAYBE_GetVisibilityState_Basic) { EXPECT_TRUE(NavigateToURL(shell(), GURL("data:text/html,foo"))); WebContents* web_contents = shell()->web_contents();
diff --git a/content/browser/frame_host/render_frame_host_manager.cc b/content/browser/frame_host/render_frame_host_manager.cc index c0d72bb6..3344f3d 100644 --- a/content/browser/frame_host/render_frame_host_manager.cc +++ b/content/browser/frame_host/render_frame_host_manager.cc
@@ -751,9 +751,16 @@ // The appropriate RenderFrameHost to commit the navigation. RenderFrameHostImpl* navigation_rfh = nullptr; - // TODO(carlosk): do not swap processes for renderer initiated navigations - // (see crbug.com/440266). + // Renderer-initiated navigations that may require a SiteInstance swap are + // sent to the browser via the OpenURL IPC and are afterwards treated as + // browser-initiated navigations. NavigationRequests marked as + // renderer-initiated are created by receiving a BeginNavigation IPC, and will + // then proceed in the same renderer that sent the IPC due to the condition + // below. + // TODO(carlosk): Once there is support for cross-process scripting check for + // non-browser-initiated navigations should be removed (see crbug.com/440266). if (current_site_instance == dest_site_instance.get() || + !request.browser_initiated() || (!frame_tree_node_->IsMainFrame() && !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kSitePerProcess))) {
diff --git a/content/browser/notifications/notification_database.cc b/content/browser/notifications/notification_database.cc index 4d8b4f9..2200a77e 100644 --- a/content/browser/notifications/notification_database.cc +++ b/content/browser/notifications/notification_database.cc
@@ -8,15 +8,23 @@ #include "base/files/file_util.h" #include "base/strings/string_number_conversions.h" +#include "base/strings/stringprintf.h" +#include "content/browser/notifications/notification_database_data.h" #include "content/public/browser/browser_thread.h" +#include "storage/common/database/database_identifier.h" #include "third_party/leveldatabase/src/helpers/memenv/memenv.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/env.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" +#include "url/gurl.h" // Notification LevelDB database schema (in alphabetized order) // ======================= // +// key: "DATA:" <origin identifier> '\x00' <notification_id> +// value: String containing the NotificationDatabaseDataProto protocol buffer +// in serialized form. +// // key: "NEXT_NOTIFICATION_ID" // value: Decimal string which fits into an int64_t. // @@ -26,6 +34,10 @@ // Keys of the fields defined in the database. const char kNextNotificationIdKey[] = "NEXT_NOTIFICATION_ID"; +const char kDataKeyPrefix[] = "DATA:"; + +// Separates the components of compound keys. +const char kKeySeparator = '\x00'; // The first notification id which to be handed out by the database. const int64_t kFirstNotificationId = 1; @@ -43,12 +55,19 @@ return NotificationDatabase::STATUS_ERROR_FAILED; } +// Creates the compound data key in which notification data is stored. +std::string CreateDataKey(int64_t notification_id, const GURL& origin) { + return base::StringPrintf("%s%s%c%s", + kDataKeyPrefix, + storage::GetIdentifierFromOrigin(origin).c_str(), + kKeySeparator, + base::Int64ToString(notification_id).c_str()); +} + } // namespace NotificationDatabase::NotificationDatabase(const base::FilePath& path) - : path_(path), - state_(STATE_UNINITIALIZED) { - sequence_checker_.DetachFromSequence(); + : path_(path) { } NotificationDatabase::~NotificationDatabase() { @@ -85,37 +104,79 @@ state_ = STATE_INITIALIZED; db_.reset(db); - return STATUS_OK; + return ReadNextNotificationId(); } -NotificationDatabase::Status NotificationDatabase::GetNextNotificationId( - int64_t* notification_id) const { +NotificationDatabase::Status NotificationDatabase::ReadNotificationData( + int64_t notification_id, + const GURL& origin, + NotificationDatabaseData* notification_database_data) const { DCHECK(sequence_checker_.CalledOnValidSequencedThread()); - DCHECK_EQ(state_, STATE_INITIALIZED); - DCHECK(notification_id); + DCHECK_EQ(STATE_INITIALIZED, state_); + DCHECK_GE(notification_id, kFirstNotificationId); + DCHECK(origin.is_valid()); + DCHECK(notification_database_data); - std::string value; + std::string key = CreateDataKey(notification_id, origin); + std::string serialized_data; + Status status = LevelDBStatusToStatus( - db_->Get(leveldb::ReadOptions(), kNextNotificationIdKey, &value)); - - if (status == STATUS_ERROR_NOT_FOUND) { - *notification_id = kFirstNotificationId; - return STATUS_OK; - } - + db_->Get(leveldb::ReadOptions(), key, &serialized_data)); if (status != STATUS_OK) return status; - int64_t next_notification_id; - if (!base::StringToInt64(value, &next_notification_id) || - next_notification_id < kFirstNotificationId) { - return STATUS_ERROR_CORRUPTED; + if (notification_database_data->ParseFromString(serialized_data)) + return STATUS_OK; + + DLOG(ERROR) << "Unable to deserialize data for notification " + << notification_id << " belonging to " << origin << "."; + return STATUS_ERROR_CORRUPTED; +} + +NotificationDatabase::Status NotificationDatabase::WriteNotificationData( + const GURL& origin, + const NotificationDatabaseData& notification_database_data, + int64_t* notification_id) { + DCHECK(sequence_checker_.CalledOnValidSequencedThread()); + DCHECK_EQ(STATE_INITIALIZED, state_); + DCHECK(notification_id); + DCHECK(origin.is_valid()); + + std::string serialized_data; + if (!notification_database_data.SerializeToString(&serialized_data)) { + DLOG(ERROR) << "Unable to serialize data for a notification belonging " + << "to: " << origin; + return STATUS_ERROR_FAILED; } - *notification_id = next_notification_id; + DCHECK_GE(next_notification_id_, kFirstNotificationId); + + leveldb::WriteBatch batch; + batch.Put(CreateDataKey(next_notification_id_, origin), serialized_data); + batch.Put(kNextNotificationIdKey, + base::Int64ToString(next_notification_id_ + 1)); + + Status status = LevelDBStatusToStatus( + db_->Write(leveldb::WriteOptions(), &batch)); + if (status != STATUS_OK) + return status; + + *notification_id = next_notification_id_++; return STATUS_OK; } +NotificationDatabase::Status NotificationDatabase::DeleteNotificationData( + int64_t notification_id, + const GURL& origin) { + DCHECK(sequence_checker_.CalledOnValidSequencedThread()); + DCHECK_EQ(STATE_INITIALIZED, state_); + DCHECK_GE(notification_id, kFirstNotificationId); + DCHECK(origin.is_valid()); + + std::string key = CreateDataKey(notification_id, origin); + return LevelDBStatusToStatus(db_->Delete(leveldb::WriteOptions(), key)); +} + NotificationDatabase::Status NotificationDatabase::Destroy() { DCHECK(sequence_checker_.CalledOnValidSequencedThread()); @@ -134,13 +195,25 @@ leveldb::DestroyDB(path_.AsUTF8Unsafe(), options)); } -void NotificationDatabase::WriteNextNotificationId( - leveldb::WriteBatch* batch, - int64_t next_notification_id) const { - DCHECK_GE(next_notification_id, kFirstNotificationId); - DCHECK(batch); +NotificationDatabase::Status NotificationDatabase::ReadNextNotificationId() { + std::string value; + Status status = LevelDBStatusToStatus( + db_->Get(leveldb::ReadOptions(), kNextNotificationIdKey, &value)); - batch->Put(kNextNotificationIdKey, base::Int64ToString(next_notification_id)); + if (status == STATUS_ERROR_NOT_FOUND) { + next_notification_id_ = kFirstNotificationId; + return STATUS_OK; + } + + if (status != STATUS_OK) + return status; + + if (!base::StringToInt64(value, &next_notification_id_) || + next_notification_id_ < kFirstNotificationId) { + return STATUS_ERROR_CORRUPTED; + } + + return STATUS_OK; } } // namespace content
diff --git a/content/browser/notifications/notification_database.h b/content/browser/notifications/notification_database.h index 85b855a..1d9a0d7 100644 --- a/content/browser/notifications/notification_database.h +++ b/content/browser/notifications/notification_database.h
@@ -7,11 +7,12 @@ #include <stdint.h> -#include "base/callback.h" #include "base/files/file_path.h" #include "base/sequence_checker.h" #include "content/common/content_export.h" +class GURL; + namespace leveldb { class DB; class Env; @@ -20,11 +21,17 @@ namespace content { +struct NotificationDatabaseData; + // Implementation of the persistent notification database. // -// This class can be constructed on any thread, but method calls must only be -// made on a thread or sequenced task runner that allows file I/O. The same -// thread or task runner must be used for all method calls. +// The database is built on top of a LevelDB database, either in memory or on +// the filesystem depending on the path passed to the constructor. When writing +// a new notification, it will be assigned an id guaranteed to be unique for the +// lifetime of the database. +// +// This class must only be used on a thread or sequenced task runner that allows +// file I/O. The same thread or task runner must be used for all method calls. class CONTENT_EXPORT NotificationDatabase { public: // Result status codes for interations with the database. Will be used for @@ -32,8 +39,8 @@ enum Status { STATUS_OK = 0, - // The database, or the key associated with the operation, could not be - // found. + // The database, a notification, or a LevelDB key associated with the + // operation could not be found. STATUS_ERROR_NOT_FOUND = 1, // The database, or data in the database, could not be parsed as valid data. @@ -52,9 +59,27 @@ // |create_if_missing| determines whether to create the database if necessary. Status Open(bool create_if_missing); - // Returns whether the next available notification id could be read, and - // stores the id in |notification_id| if the read was successful. - Status GetNextNotificationId(int64_t* notification_id) const; + // Reads the notification data for the notification identified by + // |notification_id| and belonging to |origin| from the database, and stores + // it in |notification_database_data|. Returns the status code. + Status ReadNotificationData( + int64_t notification_id, + const GURL& origin, + NotificationDatabaseData* notification_database_data) const; + + // Writes the |notification_database_data| for a new notification belonging to + // |origin| to the database, and returns the status code of the writing + // operation. The id of the new notification will be set in |notification_id|. + Status WriteNotificationData( + const GURL& origin, + const NotificationDatabaseData& notification_database_data, + int64_t* notification_id); + + // Deletes all data associated with the notification identified by + // |notification_id| belonging to |origin| from the database. Returns the + // status code of the deletion operation. Note that it is not considered a + // failure if the to-be-deleted notification does not exist. + Status DeleteNotificationData(int64_t notification_id, const GURL& origin); // Completely destroys the contents of this database. Status Destroy(); @@ -70,9 +95,10 @@ STATE_DISABLED, }; - // Writes the next available notification id as a put operation to |batch|. - void WriteNextNotificationId(leveldb::WriteBatch* batch, - int64_t next_notification_id) const; + // Reads the next available notification id from the database and returns + // the status code of the reading operation. The value will be stored in + // the |next_notification_id_| member. + Status ReadNextNotificationId(); // Returns whether the database has been opened. bool IsOpen() const { return db_ != nullptr; } @@ -86,12 +112,14 @@ base::FilePath path_; + int64_t next_notification_id_ = 0; + // The declaration order for these members matters, as |db_| depends on |env_| // and thus has to be destructed first. scoped_ptr<leveldb::Env> env_; scoped_ptr<leveldb::DB> db_; - State state_; + State state_ = STATE_UNINITIALIZED; base::SequenceChecker sequence_checker_;
diff --git a/content/browser/notifications/notification_database_unittest.cc b/content/browser/notifications/notification_database_unittest.cc index 35ea1a3..7bd835b2 100644 --- a/content/browser/notifications/notification_database_unittest.cc +++ b/content/browser/notifications/notification_database_unittest.cc
@@ -5,9 +5,14 @@ #include "content/browser/notifications/notification_database.h" #include "base/files/scoped_temp_dir.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "content/browser/notifications/notification_database_data.h" +#include "content/public/common/platform_notification_data.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" +#include "url/gurl.h" namespace content { @@ -43,25 +48,6 @@ database->GetDBForTesting()->Put(leveldb::WriteOptions(), key, value); ASSERT_TRUE(status.ok()); } - - // Increments the next notification id value in the database. Normally this - // is managed by the NotificationDatabase when writing notification data. - // - // TODO(peter): Stop doing this manually when writing notification data will - // do this for us, except for tests verifying corruption behavior. - void IncrementNextNotificationId(NotificationDatabase* database) { - int64_t next_notification_id; - ASSERT_EQ(NotificationDatabase::STATUS_OK, - database->GetNextNotificationId(&next_notification_id)); - - leveldb::WriteBatch batch; - database->WriteNextNotificationId(&batch, next_notification_id + 1); - - leveldb::Status status = - database->GetDBForTesting()->Write(leveldb::WriteOptions(), &batch); - - ASSERT_TRUE(status.ok()); - } }; TEST_F(NotificationDatabaseTest, OpenCloseMemory) { @@ -132,7 +118,7 @@ database->Open(false /* create_if_missing */)); } -TEST_F(NotificationDatabaseTest, GetNextNotificationIdIncrements) { +TEST_F(NotificationDatabaseTest, NotificationIdIncrements) { base::ScopedTempDir database_dir; ASSERT_TRUE(database_dir.CreateUniqueTempDir()); @@ -142,21 +128,24 @@ ASSERT_EQ(NotificationDatabase::STATUS_OK, database->Open(true /* create_if_missing */)); + GURL origin("https://example.com"); + + NotificationDatabaseData database_data; int64_t notification_id = 0; // Verify that getting two ids on the same database instance results in // incrementing values. Notification ids will start at 1. ASSERT_EQ(NotificationDatabase::STATUS_OK, - database->GetNextNotificationId(¬ification_id)); - EXPECT_EQ(1, notification_id); - - ASSERT_NO_FATAL_FAILURE(IncrementNextNotificationId(database.get())); + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); + EXPECT_EQ(notification_id, 1); ASSERT_EQ(NotificationDatabase::STATUS_OK, - database->GetNextNotificationId(¬ification_id)); - EXPECT_EQ(2, notification_id); - - ASSERT_NO_FATAL_FAILURE(IncrementNextNotificationId(database.get())); + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); + EXPECT_EQ(notification_id, 2); database.reset(CreateDatabaseOnFileSystem(database_dir.path())); ASSERT_EQ(NotificationDatabase::STATUS_OK, @@ -165,30 +154,255 @@ // Verify that the next notification id was stored in the database, and // continues where we expect it to be, even after closing and opening it. ASSERT_EQ(NotificationDatabase::STATUS_OK, - database->GetNextNotificationId(¬ification_id)); - EXPECT_EQ(3, notification_id); + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); + EXPECT_EQ(notification_id, 3); } -TEST_F(NotificationDatabaseTest, GetNextNotificationIdCorruption) { +TEST_F(NotificationDatabaseTest, NotificationIdCorruption) { + base::ScopedTempDir database_dir; + ASSERT_TRUE(database_dir.CreateUniqueTempDir()); + + scoped_ptr<NotificationDatabase> database( + CreateDatabaseOnFileSystem(database_dir.path())); + + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->Open(true /* create_if_missing */)); + + GURL origin("https://example.com"); + + NotificationDatabaseData database_data; + int64_t notification_id = 0; + + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); + EXPECT_EQ(notification_id, 1); + + // Deliberately write an invalid value as the next notification id. When + // re-opening the database, the Open() method should realize that an invalid + // value is being read, and mark the database as corrupted. + ASSERT_NO_FATAL_FAILURE(WriteLevelDBKeyValuePair(database.get(), + "NEXT_NOTIFICATION_ID", + "-42")); + + database.reset(CreateDatabaseOnFileSystem(database_dir.path())); + EXPECT_EQ(NotificationDatabase::STATUS_ERROR_CORRUPTED, + database->Open(false /* create_if_missing */)); +} + +TEST_F(NotificationDatabaseTest, ReadInvalidNotificationData) { + scoped_ptr<NotificationDatabase> database(CreateDatabaseInMemory()); + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->Open(true /* create_if_missing */)); + + NotificationDatabaseData database_data; + + // Reading the notification data for a notification that does not exist should + // return the ERROR_NOT_FOUND status code. + EXPECT_EQ(NotificationDatabase::STATUS_ERROR_NOT_FOUND, + database->ReadNotificationData(9001, + GURL("https://chrome.com"), + &database_data)); +} + +TEST_F(NotificationDatabaseTest, ReadNotificationDataDifferentOrigin) { + scoped_ptr<NotificationDatabase> database(CreateDatabaseInMemory()); + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->Open(true /* create_if_missing */)); + + int64_t notification_id = 0; + GURL origin("https://example.com"); + + NotificationDatabaseData database_data, read_database_data; + database_data.notification_data.title = base::UTF8ToUTF16("My Notification"); + + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); + + // Reading the notification from the database when given a different origin + // should return the ERROR_NOT_FOUND status code. + EXPECT_EQ(NotificationDatabase::STATUS_ERROR_NOT_FOUND, + database->ReadNotificationData(notification_id, + GURL("https://chrome.com"), + &read_database_data)); + + // However, reading the notification from the database with the same origin + // should return STATUS_OK and the associated notification data. + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->ReadNotificationData(notification_id, + origin, + &read_database_data)); + + EXPECT_EQ(database_data.notification_data.title, + read_database_data.notification_data.title); +} + +TEST_F(NotificationDatabaseTest, ReadNotificationDataReflection) { scoped_ptr<NotificationDatabase> database(CreateDatabaseInMemory()); ASSERT_EQ(NotificationDatabase::STATUS_OK, database->Open(true /* create_if_missing */)); int64_t notification_id = 0; + GURL origin("https://example.com"); + + PlatformNotificationData notification_data; + notification_data.title = base::UTF8ToUTF16("My Notification"); + notification_data.direction = + PlatformNotificationData::NotificationDirectionRightToLeft; + notification_data.lang = "nl-NL"; + notification_data.body = base::UTF8ToUTF16("Hello, world!"); + notification_data.tag = "replace id"; + notification_data.icon = GURL("https://example.com/icon.png"); + notification_data.silent = true; + + NotificationDatabaseData database_data; + database_data.notification_id = notification_id; + database_data.origin = origin; + database_data.service_worker_registration_id = 42; + database_data.notification_data = notification_data; + + // Write the constructed notification to the database, and then immediately + // read it back from the database again as well. ASSERT_EQ(NotificationDatabase::STATUS_OK, - database->GetNextNotificationId(¬ification_id)); - EXPECT_EQ(1, notification_id); + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); - // Deliberately write an invalid value as the next notification id to the - // database, which should cause GetNextNotificationId to realize that - // something is wrong with the data it's reading. - ASSERT_NO_FATAL_FAILURE(WriteLevelDBKeyValuePair(database.get(), - "NEXT_NOTIFICATION_ID", - "-42")); + NotificationDatabaseData read_database_data; + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->ReadNotificationData(notification_id, + origin, + &read_database_data)); - EXPECT_EQ(NotificationDatabase::STATUS_ERROR_CORRUPTED, - database->GetNextNotificationId(¬ification_id)); + // Verify that all members retrieved from the database are exactly the same + // as the ones that were written to it. This tests the serialization behavior. + + EXPECT_EQ(database_data.notification_id, read_database_data.notification_id); + EXPECT_EQ(database_data.origin, read_database_data.origin); + EXPECT_EQ(database_data.service_worker_registration_id, + read_database_data.service_worker_registration_id); + + const PlatformNotificationData& read_notification_data = + read_database_data.notification_data; + + EXPECT_EQ(notification_data.title, read_notification_data.title); + EXPECT_EQ(notification_data.direction, read_notification_data.direction); + EXPECT_EQ(notification_data.lang, read_notification_data.lang); + EXPECT_EQ(notification_data.body, read_notification_data.body); + EXPECT_EQ(notification_data.tag, read_notification_data.tag); + EXPECT_EQ(notification_data.icon, read_notification_data.icon); + EXPECT_EQ(notification_data.silent, read_notification_data.silent); +} + +TEST_F(NotificationDatabaseTest, ReadWriteMultipleNotificationData) { + scoped_ptr<NotificationDatabase> database(CreateDatabaseInMemory()); + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->Open(true /* create_if_missing */)); + + NotificationDatabaseData database_data; + GURL origin("https://example.com"); + + // Write ten notifications to the database, each with a unique title and + // notification id (it is the responsibility of the user to increment this). + for (int i = 1; i <= 10; ++i) { + database_data.notification_id = i; + database_data.notification_data.title = base::IntToString16(i); + + int64_t notification_id = 0; + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); + EXPECT_EQ(notification_id, i); + } + + // Read the ten notifications from the database, and verify that the titles + // of each of them matches with how they were created. + for (int i = 1; i <= 10; ++i) { + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->ReadNotificationData(i /* notification_id */, + origin, + &database_data)); + + EXPECT_EQ(base::IntToString16(i), database_data.notification_data.title); + } +} + +TEST_F(NotificationDatabaseTest, DeleteInvalidNotificationData) { + scoped_ptr<NotificationDatabase> database(CreateDatabaseInMemory()); + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->Open(true /* create_if_missing */)); + + // Deleting non-existing notifications is not considered to be a failure. + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->DeleteNotificationData(9001, + GURL("https://chrome.com"))); +} + +TEST_F(NotificationDatabaseTest, DeleteNotificationDataSameOrigin) { + scoped_ptr<NotificationDatabase> database(CreateDatabaseInMemory()); + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->Open(true /* create_if_missing */)); + + int64_t notification_id = 0; + + NotificationDatabaseData database_data; + GURL origin("https://example.com"); + + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); + + // Reading a notification after writing one should succeed. + EXPECT_EQ(NotificationDatabase::STATUS_OK, + database->ReadNotificationData(notification_id, + origin, + &database_data)); + + // Delete the notification which was just written to the database, and verify + // that reading it again will fail. + EXPECT_EQ(NotificationDatabase::STATUS_OK, + database->DeleteNotificationData(notification_id, origin)); + EXPECT_EQ(NotificationDatabase::STATUS_ERROR_NOT_FOUND, + database->ReadNotificationData(notification_id, + origin, + &database_data)); +} + +TEST_F(NotificationDatabaseTest, DeleteNotificationDataDifferentOrigin) { + scoped_ptr<NotificationDatabase> database(CreateDatabaseInMemory()); + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->Open(true /* create_if_missing */)); + + int64_t notification_id = 0; + + NotificationDatabaseData database_data; + GURL origin("https://example.com"); + + ASSERT_EQ(NotificationDatabase::STATUS_OK, + database->WriteNotificationData(origin, + database_data, + ¬ification_id)); + + // Attempting to delete the notification with a different origin, but with the + // same |notification_id|, should not return an error (the notification could + // not be found, but that's not considered a failure). However, it should not + // remove the notification either. + EXPECT_EQ(NotificationDatabase::STATUS_OK, + database->DeleteNotificationData(notification_id, + GURL("https://chrome.com"))); + + EXPECT_EQ(NotificationDatabase::STATUS_OK, + database->ReadNotificationData(notification_id, + origin, + &database_data)); } } // namespace content
diff --git a/content/browser/notifications/platform_notification_context.cc b/content/browser/notifications/platform_notification_context.cc new file mode 100644 index 0000000..cc82d33 --- /dev/null +++ b/content/browser/notifications/platform_notification_context.cc
@@ -0,0 +1,176 @@ +// 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/notifications/platform_notification_context.h" + +#include "base/threading/sequenced_worker_pool.h" +#include "content/browser/notifications/notification_database.h" +#include "content/browser/notifications/notification_database_data.h" +#include "content/public/browser/browser_thread.h" + +namespace content { + +// Name of the directory in the user's profile directory where the notification +// database files should be stored. +const base::FilePath::CharType kPlatformNotificationsDirectory[] = + FILE_PATH_LITERAL("Platform Notifications"); + +PlatformNotificationContext::PlatformNotificationContext( + const base::FilePath& path) + : path_(path) { +} + +PlatformNotificationContext::~PlatformNotificationContext() { + // If the database has been initialized, it must be deleted on the task runner + // thread as closing it may cause file I/O. + if (database_) { + DCHECK(task_runner_); + task_runner_->DeleteSoon(FROM_HERE, database_.release()); + } +} + +void PlatformNotificationContext::ReadNotificationData( + int64_t notification_id, + const GURL& origin, + const ReadResultCallback& callback) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + LazyInitialize( + base::Bind(&PlatformNotificationContext::DoReadNotificationData, + this, notification_id, origin, callback), + base::Bind(callback, false /* success */, NotificationDatabaseData())); +} + +void PlatformNotificationContext::DoReadNotificationData( + int64_t notification_id, + const GURL& origin, + const ReadResultCallback& callback) { + DCHECK(task_runner_->RunsTasksOnCurrentThread()); + + NotificationDatabaseData database_data; + NotificationDatabase::Status status = + database_->ReadNotificationData(notification_id, + origin, + &database_data); + + if (status == NotificationDatabase::STATUS_OK) { + BrowserThread::PostTask(BrowserThread::IO, + FROM_HERE, + base::Bind(callback, + true /* success */, + database_data)); + return; + } + + // TODO(peter): Record UMA on |status| for reading from the database. + // TODO(peter): Do the DeleteAndStartOver dance for STATUS_ERROR_CORRUPTED. + + BrowserThread::PostTask( + BrowserThread::IO, + FROM_HERE, + base::Bind(callback, false /* success */, NotificationDatabaseData())); +} + +void PlatformNotificationContext::WriteNotificationData( + const GURL& origin, + const NotificationDatabaseData& database_data, + const WriteResultCallback& callback) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + LazyInitialize( + base::Bind(&PlatformNotificationContext::DoWriteNotificationData, + this, origin, database_data, callback), + base::Bind(callback, false /* success */, 0 /* notification_id */)); +} + +void PlatformNotificationContext::DoWriteNotificationData( + const GURL& origin, + const NotificationDatabaseData& database_data, + const WriteResultCallback& callback) { + DCHECK(task_runner_->RunsTasksOnCurrentThread()); + + int64_t notification_id = 0; + NotificationDatabase::Status status = + database_->WriteNotificationData(origin, + database_data, + ¬ification_id); + + DCHECK_GT(notification_id, 0); + + if (status == NotificationDatabase::STATUS_OK) { + BrowserThread::PostTask(BrowserThread::IO, + FROM_HERE, + base::Bind(callback, + true /* success */, + notification_id)); + return; + } + + // TODO(peter): Record UMA on |status| for reading from the database. + // TODO(peter): Do the DeleteAndStartOver dance for STATUS_ERROR_CORRUPTED. + + BrowserThread::PostTask( + BrowserThread::IO, + FROM_HERE, + base::Bind(callback, false /* success */, 0 /* notification_id */)); +} + +void PlatformNotificationContext::LazyInitialize( + const base::Closure& success_closure, + const base::Closure& failure_closure) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + + if (!task_runner_) { + base::SequencedWorkerPool* pool = BrowserThread::GetBlockingPool(); + base::SequencedWorkerPool::SequenceToken token = pool->GetSequenceToken(); + + task_runner_ = pool->GetSequencedTaskRunner(token); + } + + task_runner_->PostTask( + FROM_HERE, + base::Bind(&PlatformNotificationContext::OpenDatabase, + this, success_closure, failure_closure)); +} + +void PlatformNotificationContext::OpenDatabase( + const base::Closure& success_closure, + const base::Closure& failure_closure) { + DCHECK(task_runner_->RunsTasksOnCurrentThread()); + + if (database_) { + success_closure.Run(); + return; + } + + database_.reset(new NotificationDatabase(GetDatabasePath())); + + // TODO(peter): Record UMA on |status| for opening the database. + // TODO(peter): Do the DeleteAndStartOver dance for STATUS_ERROR_CORRUPTED. + + NotificationDatabase::Status status = + database_->Open(true /* create_if_missing */); + + if (status == NotificationDatabase::STATUS_OK) { + success_closure.Run(); + return; + } + + // TODO(peter): Properly handle failures when opening the database. + database_.reset(); + + BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, failure_closure); +} + +base::FilePath PlatformNotificationContext::GetDatabasePath() const { + if (path_.empty()) + return path_; + + return path_.Append(kPlatformNotificationsDirectory); +} + +void PlatformNotificationContext::SetTaskRunnerForTesting( + const scoped_refptr<base::SequencedTaskRunner>& task_runner) { + task_runner_ = task_runner; +} + +} // namespace content
diff --git a/content/browser/notifications/platform_notification_context.h b/content/browser/notifications/platform_notification_context.h new file mode 100644 index 0000000..0f0255c --- /dev/null +++ b/content/browser/notifications/platform_notification_context.h
@@ -0,0 +1,111 @@ +// 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_NOTIFICATIONS_PLATFORM_NOTIFICATION_CONTEXT_H_ +#define CONTENT_BROWSER_NOTIFICATIONS_PLATFORM_NOTIFICATION_CONTEXT_H_ + +#include <stdint.h> + +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "content/common/content_export.h" + +class GURL; + +namespace base { +class SequencedTaskRunner; +} + +namespace content { + +class NotificationDatabase; +struct NotificationDatabaseData; + +// Implementation of the Web Notification storage context. +// +// Represents the storage context for persistent Web Notifications, specific to +// the storage partition owning the instance. The public methods defined in this +// interface must only be called on the IO thread. +class CONTENT_EXPORT PlatformNotificationContext + : public base::RefCountedThreadSafe<PlatformNotificationContext> { + public: + // Constructs a new platform notification context. If |path| is non-empty, the + // database will be initialized in the "Platform Notifications" subdirectory + // of |path|. Otherwise, the database will be initialized in memory. + explicit PlatformNotificationContext(const base::FilePath& path); + + using ReadResultCallback = + base::Callback<void(bool /* success */, + const NotificationDatabaseData&)>; + + using WriteResultCallback = + base::Callback<void(bool /* success */, + int64_t /* notification_id */)>; + + // Reads the data associated with |notification_id| belonging to |origin| + // from the database. |callback| will be invoked with the success status + // and a reference to the notification database data when completed. + void ReadNotificationData(int64_t notification_id, + const GURL& origin, + const ReadResultCallback& callback); + + // Writes the data associated with a notification to a database. When this + // action completed, |callback| will be invoked with the success status and + // the persistent notification id when written successfully. + void WriteNotificationData(const GURL& origin, + const NotificationDatabaseData& database_data, + const WriteResultCallback& callback); + + private: + friend class base::RefCountedThreadSafe<PlatformNotificationContext>; + friend class PlatformNotificationContextTest; + + virtual ~PlatformNotificationContext(); + + // Initializes the database if neccesary. Must be called on the IO thread. + // |success_closure| will be invoked on a the |task_runner_| thread when + // everything is available, or |failure_closure_| will be invoked on the + // IO thread when initialization fails. + void LazyInitialize(const base::Closure& success_closure, + const base::Closure& failure_closure); + + // Opens the database. Must be called on the |task_runner_| thread. When the + // database has been opened, |success_closure| will be invoked on the task + // thread, otherwise |failure_closure_| will be invoked on the IO thread. + void OpenDatabase(const base::Closure& success_closure, + const base::Closure& failure_closure); + + // Actually reads the notification data from the database. Must only be + // called on the |task_runner_| thread. Will post a task to |callback| on + // the IO thread when the operation has completed. + void DoReadNotificationData(int64_t notification_id, + const GURL& origin, + const ReadResultCallback& callback); + + // Actually writes the notification database to the database. Must only be + // called on the |task_runner_| thread. Will post a task to |callback| on + // the IO thread when the operation has completed. + void DoWriteNotificationData(const GURL& origin, + const NotificationDatabaseData& database_data, + const WriteResultCallback& callback); + + // Returns the path in which the database should be initialized. May be empty. + base::FilePath GetDatabasePath() const; + + // Sets the task runner to use for testing purposes. + void SetTaskRunnerForTesting( + const scoped_refptr<base::SequencedTaskRunner>& task_runner); + + base::FilePath path_; + + scoped_refptr<base::SequencedTaskRunner> task_runner_; + scoped_ptr<NotificationDatabase> database_; + + DISALLOW_COPY_AND_ASSIGN(PlatformNotificationContext); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_NOTIFICATIONS_PLATFORM_NOTIFICATION_CONTEXT_H_
diff --git a/content/browser/notifications/platform_notification_context_unittest.cc b/content/browser/notifications/platform_notification_context_unittest.cc new file mode 100644 index 0000000..3067271 --- /dev/null +++ b/content/browser/notifications/platform_notification_context_unittest.cc
@@ -0,0 +1,118 @@ +// 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/notifications/platform_notification_context.h" + +#include "base/bind.h" +#include "base/run_loop.h" +#include "content/browser/notifications/notification_database_data.h" +#include "content/public/test/test_browser_thread_bundle.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +namespace content { + +class PlatformNotificationContextTest : public ::testing::Test { + public: + PlatformNotificationContextTest() + : thread_bundle_(TestBrowserThreadBundle::IO_MAINLOOP), + success_(false) {} + + // Callback to provide when reading a single notification from the database. + void DidReadNotificationData( + bool success, const NotificationDatabaseData& database_data) { + success_ = success; + database_data_ = database_data; + } + + // Callback to provide when writing a notification to the database. + void DidWriteNotificationData(bool success, int64_t notification_id) { + success_ = success; + notification_id_ = notification_id; + } + + protected: + // Creates a new PlatformNotificationContext instance. When using this method, + // the underlying database will always be created in memory. The current + // message loop proxy will be used as the task runner. + PlatformNotificationContext* CreatePlatformNotificationContext() { + PlatformNotificationContext* context = + new PlatformNotificationContext(base::FilePath()); + + context->SetTaskRunnerForTesting(base::MessageLoopProxy::current()); + return context; + } + + // Returns whether the last invoked callback finished successfully. + bool success() const { return success_; } + + // Returns the NotificationDatabaseData associated with the last invoked + // ReadNotificationData callback. + const NotificationDatabaseData& database_data() const { + return database_data_; + } + + // Returns the notification id of the notification last written. + int64_t notification_id() const { return notification_id_; } + + private: + TestBrowserThreadBundle thread_bundle_; + + bool success_; + NotificationDatabaseData database_data_; + int64_t notification_id_; +}; + +TEST_F(PlatformNotificationContextTest, ReadNonExistentNotification) { + scoped_refptr<PlatformNotificationContext> context = + CreatePlatformNotificationContext(); + + context->ReadNotificationData( + 42 /* notification_id */, + GURL("https://example.com"), + base::Bind(&PlatformNotificationContextTest::DidReadNotificationData, + base::Unretained(this))); + + base::RunLoop().RunUntilIdle(); + + // The read operation should have failed, as it does not exist. + ASSERT_FALSE(success()); +} + +TEST_F(PlatformNotificationContextTest, WriteReadNotification) { + scoped_refptr<PlatformNotificationContext> context = + CreatePlatformNotificationContext(); + + GURL origin("https://example.com"); + NotificationDatabaseData notification_database_data; + notification_database_data.origin = origin; + + context->WriteNotificationData( + origin, + notification_database_data, + base::Bind(&PlatformNotificationContextTest::DidWriteNotificationData, + base::Unretained(this))); + + base::RunLoop().RunUntilIdle(); + + // The write operation should have succeeded with a notification id. + ASSERT_TRUE(success()); + EXPECT_GT(notification_id(), 0); + + context->ReadNotificationData( + notification_id(), + origin, + base::Bind(&PlatformNotificationContextTest::DidReadNotificationData, + base::Unretained(this))); + + base::RunLoop().RunUntilIdle(); + + // The read operation should have succeeded, with the right notification. + ASSERT_TRUE(success()); + + const NotificationDatabaseData& read_database_data = database_data(); + EXPECT_EQ(notification_database_data.origin, read_database_data.origin); +} + +} // namespace content
diff --git a/content/browser/plugin_data_remover_impl.cc b/content/browser/plugin_data_remover_impl.cc index f74b3783..019f4b02 100644 --- a/content/browser/plugin_data_remover_impl.cc +++ b/content/browser/plugin_data_remover_impl.cc
@@ -212,7 +212,7 @@ kClearAllData, max_age); } - // Connects the client side of a newly opened plug-in channel. + // Connects the client side of a newly opened plugin channel. void ConnectToChannel(const IPC::ChannelHandle& handle, bool is_ppapi) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); @@ -288,7 +288,7 @@ // The name of the plugin. Use only on the I/O thread. std::string plugin_name_; - // The channel is NULL until we have opened a connection to the plug-in + // The channel is NULL until we have opened a connection to the plugin // process. scoped_ptr<IPC::Channel> channel_; };
diff --git a/content/browser/plugin_data_remover_impl.h b/content/browser/plugin_data_remover_impl.h index 704ebaaa..ed2b7ea 100644 --- a/content/browser/plugin_data_remover_impl.h +++ b/content/browser/plugin_data_remover_impl.h
@@ -22,9 +22,9 @@ // PluginDataRemover implementation: base::WaitableEvent* StartRemoving(base::Time begin_time) override; - // The plug-in whose data should be removed (usually Flash) is specified via + // The plugin whose data should be removed (usually Flash) is specified via // its MIME type. This method sets a different MIME type in order to call a - // different plug-in (for example in tests). + // different plugin (for example in tests). void set_mime_type(const std::string& mime_type) { mime_type_ = mime_type; } private:
diff --git a/content/browser/plugin_process_host.cc b/content/browser/plugin_process_host.cc index 3257ac3..3d45743a 100644 --- a/content/browser/plugin_process_host.cc +++ b/content/browser/plugin_process_host.cc
@@ -189,8 +189,8 @@ browser_command_line.GetSwitchValueNative(switches::kPluginLauncher); #if defined(OS_MACOSX) - // Run the plug-in process in a mode tolerant of heap execution without - // explicit mprotect calls. Some plug-ins still rely on this quaint and + // Run the plugin process in a mode tolerant of heap execution without + // explicit mprotect calls. Some plugins still rely on this quaint and // archaic "feature." See http://crbug.com/93551. int flags = ChildProcessHost::CHILD_ALLOW_HEAP_EXECUTION; #elif defined(OS_LINUX)
diff --git a/content/browser/plugin_service_impl.h b/content/browser/plugin_service_impl.h index 6b25ed4b..326eb4fd 100644 --- a/content/browser/plugin_service_impl.h +++ b/content/browser/plugin_service_impl.h
@@ -154,7 +154,7 @@ // Cancels opening a channel to a NPAPI plugin. void CancelOpenChannelToNpapiPlugin(PluginProcessHost::Client* client); - // Used to monitor plug-in stability. + // Used to monitor plugin stability. void RegisterPluginCrash(const base::FilePath& plugin_path); private: @@ -240,14 +240,14 @@ std::set<PluginProcessHost::Client*> pending_plugin_clients_; - // Used to sequentialize loading plug-ins from disk. + // Used to sequentialize loading plugins from disk. base::SequencedWorkerPool::SequenceToken plugin_list_token_; #if defined(OS_POSIX) scoped_refptr<PluginLoaderPosix> plugin_loader_; #endif - // Used to detect if a given plug-in is crashing over and over. + // Used to detect if a given plugin is crashing over and over. std::map<base::FilePath, std::vector<base::Time> > crash_times_; DISALLOW_COPY_AND_ASSIGN(PluginServiceImpl);
diff --git a/content/browser/resources/media/stats_table.js b/content/browser/resources/media/stats_table.js index a9d2ab0..8ad804a0 100644 --- a/content/browser/resources/media/stats_table.js +++ b/content/browser/resources/media/stats_table.js
@@ -142,7 +142,7 @@ trElement.cells[1].textContent = value; // Highlights the table for the active connection. - if (rowName == 'googActiveConnection' && value == 'true') + if (rowName == 'googActiveConnection' && value == true) statsTable.parentElement.classList.add('stats-table-active-connection'); } };
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 97813f7..1f753882 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -134,13 +134,15 @@ static int StartDownload(RenderFrameHost* rfh, const GURL& url, bool is_favicon, - uint32_t max_bitmap_size) { + uint32_t max_bitmap_size, + bool bypass_cache) { static int g_next_image_download_id = 0; rfh->Send(new ImageMsg_DownloadImage(rfh->GetRoutingID(), ++g_next_image_download_id, url, is_favicon, - max_bitmap_size)); + max_bitmap_size, + bypass_cache)); return g_next_image_download_id; } @@ -2566,8 +2568,10 @@ int WebContentsImpl::DownloadImage(const GURL& url, bool is_favicon, uint32_t max_bitmap_size, + bool bypass_cache, const ImageDownloadCallback& callback) { - int id = StartDownload(GetMainFrame(), url, is_favicon, max_bitmap_size); + int id = StartDownload(GetMainFrame(), url, is_favicon, max_bitmap_size, + bypass_cache); image_download_map_[id] = callback; return id; }
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 0cd2bdb..3a86786b 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -339,6 +339,7 @@ int DownloadImage(const GURL& url, bool is_favicon, uint32_t max_bitmap_size, + bool bypass_cache, const ImageDownloadCallback& callback) override; bool IsSubframe() const override; void Find(int request_id,
diff --git a/content/browser/web_contents/web_contents_impl_unittest.cc b/content/browser/web_contents/web_contents_impl_unittest.cc index dfba444..d56e218 100644 --- a/content/browser/web_contents/web_contents_impl_unittest.cc +++ b/content/browser/web_contents/web_contents_impl_unittest.cc
@@ -50,7 +50,7 @@ WebUIController* CreateWebUIControllerForURL(WebUI* web_ui, const GURL& url) const override { if (!UseWebUI(url)) - return NULL; + return nullptr; return new WebUIController(web_ui); } @@ -129,7 +129,7 @@ state_(state), deleted_(deleted), command_received_count_(0), - delegate_(NULL) { + delegate_(nullptr) { *state_ = UNDECIDED; *deleted_ = false; } @@ -177,9 +177,9 @@ } void ClearStates() { - state_ = NULL; - deleted_ = NULL; - delegate_ = NULL; + state_ = nullptr; + deleted_ = nullptr; + delegate_ = nullptr; } void CommandReceived() { @@ -191,7 +191,7 @@ } protected: - WebContentsView* CreateWebContentsView() override { return NULL; } + WebContentsView* CreateWebContentsView() override { return nullptr; } private: InterstitialState* state_; @@ -228,7 +228,7 @@ void TestInterstitialPageDeleted( TestInterstitialPage* interstitial) override { DCHECK(interstitial_page_ == interstitial); - interstitial_page_ = NULL; + interstitial_page_ = nullptr; } private: @@ -300,7 +300,7 @@ // a fullscreened state. class FakeFullscreenDelegate : public WebContentsDelegate { public: - FakeFullscreenDelegate() : fullscreened_contents_(NULL) {} + FakeFullscreenDelegate() : fullscreened_contents_(nullptr) {} ~FakeFullscreenDelegate() override {} void EnterFullscreenModeForTab(WebContents* web_contents, @@ -309,7 +309,7 @@ } void ExitFullscreenModeForTab(WebContents* web_contents) override { - fullscreened_contents_ = NULL; + fullscreened_contents_ = nullptr; } bool IsFullscreenForTabOrPending( @@ -409,7 +409,7 @@ // Test to ensure UpdateMaxPageID is working properly. TEST_F(WebContentsImplTest, UpdateMaxPageID) { SiteInstance* instance1 = contents()->GetSiteInstance(); - scoped_refptr<SiteInstance> instance2(SiteInstance::Create(NULL)); + scoped_refptr<SiteInstance> instance2(SiteInstance::Create(nullptr)); // Starts at -1. EXPECT_EQ(-1, contents()->GetMaxPageID()); @@ -433,7 +433,7 @@ TEST_F(WebContentsImplTest, SimpleNavigation) { TestRenderFrameHost* orig_rfh = contents()->GetMainFrame(); SiteInstance* instance1 = contents()->GetSiteInstance(); - EXPECT_TRUE(contents()->GetPendingMainFrame() == NULL); + EXPECT_EQ(nullptr, contents()->GetPendingMainFrame()); // Navigate to URL const GURL url("http://www.google.com"); @@ -441,11 +441,12 @@ url, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); EXPECT_FALSE(contents()->cross_navigation_pending()); EXPECT_EQ(instance1, orig_rfh->GetSiteInstance()); - // Controller's pending entry will have a NULL site instance until we assign + // Controller's pending entry will have a null site instance until we assign // it in DidNavigate. - EXPECT_TRUE( + EXPECT_EQ( + nullptr, NavigationEntryImpl::FromNavigationEntry(controller().GetVisibleEntry())-> - site_instance() == NULL); + site_instance()); // DidNavigate from the page contents()->TestDidNavigate(orig_rfh, 1, url, ui::PAGE_TRANSITION_TYPED); @@ -468,7 +469,7 @@ controller().LoadURL( url, Referrer(), ui::PAGE_TRANSITION_GENERATED, std::string()); - EXPECT_TRUE(controller().GetVisibleEntry() == NULL); + EXPECT_EQ(nullptr, controller().GetVisibleEntry()); } // Test that navigating across a site boundary creates a new RenderViewHost @@ -534,7 +535,7 @@ EXPECT_EQ(url2, contents()->GetLastCommittedURL()); EXPECT_EQ(url2, contents()->GetVisibleURL()); EXPECT_NE(instance1, instance2); - EXPECT_TRUE(contents()->GetPendingMainFrame() == NULL); + EXPECT_EQ(nullptr, contents()->GetPendingMainFrame()); // We keep the original RFH around, swapped out. EXPECT_TRUE(contents()->GetRenderManagerForTesting()->IsOnSwappedOutList( orig_rfh)); @@ -607,7 +608,7 @@ contents()->GetMainFrame()->PrepareForCommit(); TestRenderFrameHost* new_rfh = contents()->GetMainFrame(); EXPECT_FALSE(contents()->cross_navigation_pending()); - EXPECT_TRUE(contents()->GetPendingMainFrame() == NULL); + EXPECT_EQ(nullptr, contents()->GetPendingMainFrame()); EXPECT_NE(orig_rfh, new_rfh); EXPECT_EQ(orig_rvh_delete_count, 1); @@ -618,7 +619,7 @@ EXPECT_FALSE(contents()->cross_navigation_pending()); EXPECT_EQ(new_rfh, main_rfh()); EXPECT_NE(instance1, instance2); - EXPECT_TRUE(contents()->GetPendingMainFrame() == NULL); + EXPECT_EQ(nullptr, contents()->GetPendingMainFrame()); // Close contents and ensure RVHs are deleted. DeleteContents(); @@ -670,7 +671,7 @@ TestRenderFrameHost* rfh2 = contents2->GetMainFrame(); rfh2->PrepareForCommit(); TestRenderFrameHost* pending_rfh_b = contents2->GetPendingMainFrame(); - EXPECT_TRUE(pending_rfh_b != NULL); + EXPECT_NE(nullptr, pending_rfh_b); EXPECT_TRUE(contents2->cross_navigation_pending()); // NOTE(creis): We used to be in danger of showing a crash page here if the @@ -1000,7 +1001,7 @@ EXPECT_FALSE(contents()->cross_navigation_pending()); EXPECT_EQ(pending_rfh, contents()->GetMainFrame()); EXPECT_NE(instance1, instance2); - EXPECT_TRUE(contents()->GetPendingMainFrame() == NULL); + EXPECT_EQ(nullptr, contents()->GetPendingMainFrame()); } // Test that during a slow cross-site navigation, the original renderer can @@ -1036,7 +1037,7 @@ EXPECT_FALSE(contents()->cross_navigation_pending()); EXPECT_EQ(orig_rfh, contents()->GetMainFrame()); EXPECT_EQ(instance1, instance2); - EXPECT_TRUE(contents()->GetPendingMainFrame() == NULL); + EXPECT_EQ(nullptr, contents()->GetPendingMainFrame()); } TEST_F(WebContentsImplTest, CrossSiteNavigationBackPreempted) { @@ -1248,7 +1249,7 @@ EXPECT_EQ(orig_rfh, contents()->GetMainFrame()); EXPECT_EQ(RenderFrameHostImpl::STATE_DEFAULT, orig_rfh->rfh_state()); EXPECT_EQ(instance1, instance2); - EXPECT_TRUE(contents()->GetPendingMainFrame() == NULL); + EXPECT_EQ(nullptr, contents()->GetPendingMainFrame()); } // Test that NavigationEntries have the correct page state after going @@ -1261,7 +1262,7 @@ controller().LoadURL( url, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); NavigationEntry* entry = controller().GetLastCommittedEntry(); - EXPECT_TRUE(entry == NULL); + EXPECT_EQ(nullptr, entry); // Committed entry should have page state after DidNavigate. contents()->TestDidNavigate(orig_rfh, 1, url, ui::PAGE_TRANSITION_TYPED); @@ -1362,7 +1363,7 @@ EXPECT_FALSE(contents()->IsFullscreenForCurrentTab()); EXPECT_FALSE(fake_delegate.IsFullscreenForTabOrPending(contents())); - contents()->SetDelegate(NULL); + contents()->SetDelegate(nullptr); } // Tests that fullscreen is exited throughout the object hierarchy when @@ -1417,7 +1418,7 @@ EXPECT_FALSE(fake_delegate.IsFullscreenForTabOrPending(contents())); } - contents()->SetDelegate(NULL); + contents()->SetDelegate(nullptr); } TEST_F(WebContentsImplTest, TerminateHidesValidationMessage) { @@ -1433,7 +1434,7 @@ // Confirm HideValidationMessage was called. EXPECT_TRUE(fake_delegate.hide_validation_message_was_called()); - contents()->SetDelegate(NULL); + contents()->SetDelegate(nullptr); } // Tests that fullscreen is exited throughout the object hierarchy on a renderer @@ -1469,7 +1470,7 @@ EXPECT_FALSE(contents()->IsFullscreenForCurrentTab()); EXPECT_FALSE(fake_delegate.IsFullscreenForTabOrPending(contents())); - contents()->SetDelegate(NULL); + contents()->SetDelegate(nullptr); } //////////////////////////////////////////////////////////////////////////////// @@ -1502,23 +1503,23 @@ // The interstitial should not show until its navigation has committed. EXPECT_FALSE(interstitial->is_showing()); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); // Let's commit the interstitial navigation. interstitial->TestDidNavigate(1, url2); EXPECT_TRUE(interstitial->is_showing()); EXPECT_TRUE(contents()->ShowingInterstitialPage()); EXPECT_TRUE(contents()->GetInterstitialPage() == interstitial); NavigationEntry* entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url2); // Now don't proceed. interstitial->DontProceed(); EXPECT_EQ(TestInterstitialPage::CANCELED, state); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url1); EXPECT_EQ(1, controller().GetEntryCount()); @@ -1549,23 +1550,23 @@ // The interstitial should not show until its navigation has committed. EXPECT_FALSE(interstitial->is_showing()); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); // Let's commit the interstitial navigation. interstitial->TestDidNavigate(1, url2); EXPECT_TRUE(interstitial->is_showing()); EXPECT_TRUE(contents()->ShowingInterstitialPage()); EXPECT_TRUE(contents()->GetInterstitialPage() == interstitial); NavigationEntry* entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url2); // Now don't proceed. interstitial->DontProceed(); EXPECT_EQ(TestInterstitialPage::CANCELED, state); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url1); EXPECT_EQ(1, controller().GetEntryCount()); @@ -1594,14 +1595,14 @@ // The interstitial should not show until its navigation has committed. EXPECT_FALSE(interstitial->is_showing()); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); // Let's commit the interstitial navigation. interstitial->TestDidNavigate(1, url2); EXPECT_TRUE(interstitial->is_showing()); EXPECT_TRUE(contents()->ShowingInterstitialPage()); EXPECT_TRUE(contents()->GetInterstitialPage() == interstitial); NavigationEntry* entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); // The URL specified to the interstitial should have been ignored. EXPECT_TRUE(entry->GetURL() == url1); @@ -1609,9 +1610,9 @@ interstitial->DontProceed(); EXPECT_EQ(TestInterstitialPage::CANCELED, state); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url1); EXPECT_EQ(1, controller().GetEntryCount()); @@ -1645,14 +1646,14 @@ // The interstitial should not show until its navigation has committed. EXPECT_FALSE(interstitial->is_showing()); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); // Let's commit the interstitial navigation. interstitial->TestDidNavigate(1, url2); EXPECT_TRUE(interstitial->is_showing()); EXPECT_TRUE(contents()->ShowingInterstitialPage()); EXPECT_TRUE(contents()->GetInterstitialPage() == interstitial); NavigationEntry* entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url2); // Then proceed. @@ -1670,9 +1671,9 @@ contents()->GetMainFrame()->SendNavigate(2, url3); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url3); EXPECT_EQ(2, controller().GetEntryCount()); @@ -1703,14 +1704,14 @@ // The interstitial should not show until its navigation has committed. EXPECT_FALSE(interstitial->is_showing()); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); // Let's commit the interstitial navigation. interstitial->TestDidNavigate(1, url2); EXPECT_TRUE(interstitial->is_showing()); EXPECT_TRUE(contents()->ShowingInterstitialPage()); EXPECT_TRUE(contents()->GetInterstitialPage() == interstitial); NavigationEntry* entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url2); // Then proceed. @@ -1728,9 +1729,9 @@ contents()->GetMainFrame()->SendNavigate(2, url3); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url3); EXPECT_EQ(2, controller().GetEntryCount()); @@ -1760,14 +1761,14 @@ // The interstitial should not show until its navigation has committed. EXPECT_FALSE(interstitial->is_showing()); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); // Let's commit the interstitial navigation. interstitial->TestDidNavigate(1, url2); EXPECT_TRUE(interstitial->is_showing()); EXPECT_TRUE(contents()->ShowingInterstitialPage()); EXPECT_TRUE(contents()->GetInterstitialPage() == interstitial); NavigationEntry* entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); // The URL specified to the interstitial should have been ignored. EXPECT_TRUE(entry->GetURL() == url1); @@ -1777,9 +1778,9 @@ // away and shows the original page. EXPECT_EQ(TestInterstitialPage::OKED, state); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == url1); EXPECT_EQ(1, controller().GetEntryCount()); @@ -2043,9 +2044,9 @@ contents()->GetMainFrame()->SendNavigate(2, landing_url); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); NavigationEntry* entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == landing_url); EXPECT_EQ(2, controller().GetEntryCount()); RunAllPendingInMessageLoop(); @@ -2102,9 +2103,9 @@ RunAllPendingInMessageLoop(); EXPECT_TRUE(deleted2); EXPECT_FALSE(contents()->ShowingInterstitialPage()); - EXPECT_TRUE(contents()->GetInterstitialPage() == NULL); + EXPECT_EQ(nullptr, contents()->GetInterstitialPage()); NavigationEntry* entry = controller().GetVisibleEntry(); - ASSERT_TRUE(entry != NULL); + ASSERT_NE(nullptr, entry); EXPECT_TRUE(entry->GetURL() == landing_url); EXPECT_EQ(2, controller().GetEntryCount()); } @@ -2414,7 +2415,7 @@ contents()->AddPendingContents(other_contents.get()); int route_id = other_contents->GetRenderViewHost()->GetRoutingID(); other_contents.reset(); - EXPECT_EQ(NULL, contents()->GetCreatedWindow(route_id)); + EXPECT_EQ(nullptr, contents()->GetCreatedWindow(route_id)); } TEST_F(WebContentsImplTest, CapturerOverridesPreferredSize) { @@ -2630,7 +2631,7 @@ EXPECT_EQ(0, delegate->GetAndResetContentsZoomChangedCallCount()); // Ensure pointers to the delegate aren't kept beyond its lifetime. - contents()->SetDelegate(NULL); + contents()->SetDelegate(nullptr); } // Tests that GetRelatedActiveContentsCount is shared between related
diff --git a/content/child/npapi/plugin_host.cc b/content/child/npapi/plugin_host.cc index c2d68aa..cdda9e4 100644 --- a/content/child/npapi/plugin_host.cc +++ b/content/child/npapi/plugin_host.cc
@@ -618,12 +618,12 @@ // Before a windowless plugin can refresh part of its drawing area, it must // first invalidate it. This function causes the NPP_HandleEvent method to - // pass an update event or a paint message to the plug-in. After calling - // this method, the plug-in receives a paint message asynchronously. + // pass an update event or a paint message to the plugin. After calling + // this method, the plugin receives a paint message asynchronously. // The browser redraws invalid areas of the document and any windowless - // plug-ins at regularly timed intervals. To force a paint message, the - // plug-in can call NPN_ForceRedraw after calling this method. + // plugins at regularly timed intervals. To force a paint message, the + // plugin can call NPN_ForceRedraw after calling this method. scoped_refptr<PluginInstance> plugin(FindInstance(id)); if (plugin.get() && plugin->webplugin()) { @@ -665,7 +665,7 @@ } void NPN_ForceRedraw(NPP id) { - // Forces repaint for a windowless plug-in. + // Forces repaint for a windowless plugin. // // We deliberately do not implement this; we don't want plugins forcing // synchronous paints. @@ -678,7 +678,7 @@ // NPNVxDisplay (unix only) // NPNVxtAppContext (unix only) // NPNVnetscapeWindow (win only) - Gets the native window on which the - // plug-in drawing occurs, returns HWND + // plugin drawing occurs, returns HWND // NPNVjavascriptEnabledBool: tells whether Javascript is enabled // NPNVasdEnabledBool: tells whether SmartUpdate is enabled // NPNVOfflineBool: tells whether offline-mode is enabled
diff --git a/content/child/npapi/plugin_url_fetcher.cc b/content/child/npapi/plugin_url_fetcher.cc index a99f2e1..372c3b5 100644 --- a/content/child/npapi/plugin_url_fetcher.cc +++ b/content/child/npapi/plugin_url_fetcher.cc
@@ -204,7 +204,7 @@ // Currently this check is just to catch an https -> http redirect when // loading the main plugin src URL. Longer term, we could investigate // firing mixed diplay or scripting issues for subresource loads - // initiated by plug-ins. + // initiated by plugins. if (is_plugin_src_load_ && !plugin_stream_->instance()->webplugin()->CheckIfRunInsecureContent( redirect_info.new_url)) {
diff --git a/content/child/npapi/webplugin_delegate_impl.cc b/content/child/npapi/webplugin_delegate_impl.cc index 4041db42..9d76054 100644 --- a/content/child/npapi/webplugin_delegate_impl.cc +++ b/content/child/npapi/webplugin_delegate_impl.cc
@@ -81,14 +81,14 @@ creation_succeeded_ = instance_->Start( url, argn.get(), argv.get(), argc, load_manually); if (!creation_succeeded_) { - VLOG(1) << "Couldn't start plug-in instance"; + VLOG(1) << "Couldn't start plugin instance"; return false; } windowless_ = instance_->windowless(); if (!windowless_) { if (!WindowedCreatePlugin()) { - VLOG(1) << "Couldn't create windowed plug-in"; + VLOG(1) << "Couldn't create windowed plugin"; return false; } }
diff --git a/content/child/npapi/webplugin_delegate_impl.h b/content/child/npapi/webplugin_delegate_impl.h index df705843..91eddfa 100644 --- a/content/child/npapi/webplugin_delegate_impl.h +++ b/content/child/npapi/webplugin_delegate_impl.h
@@ -145,7 +145,7 @@ void SetContentAreaHasFocus(bool has_focus); #if defined(OS_WIN) - // Informs the plug-in that an IME has changed its status. + // Informs the plugin that an IME has changed its status. void ImeCompositionUpdated(const base::string16& text, const std::vector<int>& clauses, const std::vector<int>& target, @@ -155,7 +155,7 @@ // IME was cancelled. void ImeCompositionCompleted(const base::string16& text); - // Returns the IME status retrieved from a plug-in. + // Returns the IME status retrieved from a plugin. bool GetIMEStatus(int* input_type, gfx::Rect* caret_rect); #endif @@ -304,7 +304,7 @@ uint32 last_message_; bool is_calling_wndproc; - // An IME emulator used by a windowless plug-in to retrieve IME data through + // An IME emulator used by a windowless plugin to retrieve IME data through // IMM32 functions. scoped_ptr<WebPluginIMEWin> plugin_ime_; #endif // defined(OS_WIN) @@ -386,13 +386,13 @@ // Informs the browser about the updated accelerated drawing surface. void UpdateAcceleratedSurface(); - // Uses a CARenderer to draw the plug-in's layer in our OpenGL surface. + // Uses a CARenderer to draw the plugin's layer in our OpenGL surface. void DrawLayerInSurface(); bool use_buffer_context_; CGContextRef buffer_context_; // Weak ref. - CALayer* layer_; // Used for CA drawing mode. Weak, retained by plug-in. + CALayer* layer_; // Used for CA drawing mode. Weak, retained by plugin. WebPluginAcceleratedSurface* surface_; // Weak ref. CARenderer* renderer_; // Renders layer_ to surface_. scoped_ptr<base::RepeatingTimer<WebPluginDelegateImpl> > redraw_timer_;
diff --git a/content/child/npapi/webplugin_delegate_impl_mac.mm b/content/child/npapi/webplugin_delegate_impl_mac.mm index 8dd549cf..4dad117 100644 --- a/content/child/npapi/webplugin_delegate_impl_mac.mm +++ b/content/child/npapi/webplugin_delegate_impl_mac.mm
@@ -205,7 +205,7 @@ break; case NPDrawingModelCoreAnimation: case NPDrawingModelInvalidatingCoreAnimation: { - // Ask the plug-in for the CALayer it created for rendering content. + // Ask the plugin for the CALayer it created for rendering content. // Create a surface to host it, and request a "window" handle to identify // the surface. CALayer* layer = nil; @@ -702,7 +702,7 @@ surface_->EndDrawing(); } -// Update the size of the surface to match the current size of the plug-in. +// Update the size of the surface to match the current size of the plugin. void WebPluginDelegateImpl::UpdateAcceleratedSurface() { if (!surface_ || !layer_) return;
diff --git a/content/child/npapi/webplugin_delegate_impl_win.cc b/content/child/npapi/webplugin_delegate_impl_win.cc index 97d1f83..c7efff72 100644 --- a/content/child/npapi/webplugin_delegate_impl_win.cc +++ b/content/child/npapi/webplugin_delegate_impl_win.cc
@@ -500,7 +500,7 @@ DCHECK(result == TRUE) << "SetProp failed, last error = " << GetLastError(); // Calling SetWindowLongPtrA here makes the window proc ASCII, which is - // required by at least the Shockwave Director plug-in. + // required by at least the Shockwave Director plugin. SetWindowLongPtrA(windowed_handle_, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(DefWindowProcA)); @@ -872,7 +872,7 @@ // window messages when its first parameter is a handle representing the // DefWindowProc() function. To avoid this problem, this code creates a // wrapper function which just encapsulates the DefWindowProc() function - // and set it as the window procedure of a windowed plug-in. + // and set it as the window procedure of a windowed plugin. return DefWindowProc(hWnd, message, wParam, lParam); } @@ -1207,8 +1207,8 @@ return false; } - // Allow this plug-in to access this IME emulator through IMM32 API while the - // plug-in is processing this event. + // Allow this plugin to access this IME emulator through IMM32 API while the + // plugin is processing this event. if (GetQuirks() & PLUGIN_QUIRK_EMULATE_IME) { if (!plugin_ime_) plugin_ime_.reset(new WebPluginIMEWin);
diff --git a/content/child/npapi/webplugin_ime_win.cc b/content/child/npapi/webplugin_ime_win.cc index 9b03ab7..7ff6a5d 100644 --- a/content/child/npapi/webplugin_ime_win.cc +++ b/content/child/npapi/webplugin_ime_win.cc
@@ -19,7 +19,7 @@ namespace content { -// A critical section that prevents two or more plug-ins from accessing a +// A critical section that prevents two or more plugins from accessing a // WebPluginIMEWin instance through our patch function. base::LazyInstance<base::Lock>::Leaky g_webplugin_ime_lock = LAZY_INSTANCE_INITIALIZER; @@ -65,10 +65,10 @@ events_.push_back(np_event); // Converts this event to the IMM32 data so we do not have to convert it every - // time when a plug-in call an IMM32 function. + // time when a plugin call an IMM32 function. composition_text_ = text; - // Create the composition clauses returned when a plug-in calls + // Create the composition clauses returned when a plugin calls // ImmGetCompositionString() with GCS_COMPCLAUSE. composition_clauses_.clear(); for (size_t i = 0; i < clauses.size(); ++i) @@ -107,8 +107,8 @@ np_event.lParam = 0; events_.push_back(np_event); - // If the target plug-in does not seem to support IME messages, we send - // each character in IME text with a WM_CHAR message so the plug-in can + // If the target plugin does not seem to support IME messages, we send + // each character in IME text with a WM_CHAR message so the plugin can // insert the IME text. if (!support_ime_messages_) { np_event.event = WM_CHAR; @@ -133,7 +133,7 @@ bool WebPluginIMEWin::SendEvents(PluginInstance* instance) { // We allow the patch functions to access this WebPluginIMEWin instance only - // while we send IME events to the plug-in. + // while we send IME events to the plugin. ScopedLock lock(this); bool ret = true; @@ -266,8 +266,8 @@ // Call the original ImmGetContext() function if the given window is the one // created in WebPluginDelegateImpl::WindowedCreatePlugin(). (We attached IME // context only with the windows created in this function.) On the other hand, - // some windowless plug-ins (such as Flash) call this function with a dummy - // window handle. We return our dummy IME context for these plug-ins so they + // some windowless plugins (such as Flash) call this function with a dummy + // window handle. We return our dummy IME context for these plugins so they // can use our IME emulator. if (IsWindow(window)) { wchar_t name[128];
diff --git a/content/child/npapi/webplugin_ime_win.h b/content/child/npapi/webplugin_ime_win.h index eca9ab29..b24e75a 100644 --- a/content/child/npapi/webplugin_ime_win.h +++ b/content/child/npapi/webplugin_ime_win.h
@@ -17,14 +17,14 @@ class PluginInstance; -// A class that emulates an IME for windowless plug-ins. A windowless plug-in +// A class that emulates an IME for windowless plugins. A windowless plugin // does not have a window. Therefore, we cannot attach an IME to a windowless -// plug-in. To allow such windowless plug-ins to use IMEs without any changes to +// plugin. To allow such windowless plugins to use IMEs without any changes to // them, this class receives the IME data from a browser and patches IMM32 -// functions to return the IME data when a windowless plug-in calls IMM32 +// functions to return the IME data when a windowless plugin calls IMM32 // functions. I would not Flash retrieves pointers to IMM32 functions with // GetProcAddress(), this class also needs a hook to GetProcAddress() to -// dispatch IMM32 function calls from a plug-in to this class as listed in the +// dispatch IMM32 function calls from a plugin to this class as listed in the // following snippet. // // FARPROC WINAPI GetProcAddressPatch(HMODULE module, LPCSTR name) { @@ -39,13 +39,13 @@ // GetPluginPath().value().c_str(), "kernel32.dll", "GetProcAddress", // GetProcAddressPatch); // -// After we successfuly dispatch IMM32 calls from a plug-in to this class, we -// need to update its IME data so the class can return it to the plug-in through +// After we successfuly dispatch IMM32 calls from a plugin to this class, we +// need to update its IME data so the class can return it to the plugin through // its IMM32 calls. To update the IME data, we call CompositionUpdated() or // CompositionCompleted() BEFORE sending an IMM32 Window message to the plugin -// with a SendEvents() call as listed in the following snippet. (Plug-ins call +// with a SendEvents() call as listed in the following snippet. (Plugins call // IMM32 functions when it receives IMM32 window messages. We need to update the -// IME data of this class before sending IMM32 messages so the plug-ins can get +// IME data of this class before sending IMM32 messages so the plugins can get // the latest data.) // // WebPluginIMEWin ime; @@ -63,12 +63,12 @@ // ime.SendEvents(instance()); // // This class also provides GetStatus() so we can retrieve the IME status -// changed by a plug-in with IMM32 functions. This function is mainly used for +// changed by a plugin with IMM32 functions. This function is mainly used for // retrieving the position of a caret. // class WebPluginIMEWin { public: - // A simple class that allows a plug-in to access a WebPluginIMEWin instance + // A simple class that allows a plugin to access a WebPluginIMEWin instance // only in a scope. class ScopedLock { public: @@ -89,17 +89,17 @@ ~WebPluginIMEWin(); // Sends raw IME events sent from a browser to this IME emulator and updates - // the list of Windows events to be sent to a plug-in. A raw IME event is + // the list of Windows events to be sent to a plugin. A raw IME event is // mapped to two or more Windows events and it is not so trivial to send these - // Windows events to a plug-in. This function inserts Windows events in the - // order expected by a plug-in. + // Windows events to a plugin. This function inserts Windows events in the + // order expected by a plugin. void CompositionUpdated(const base::string16& text, std::vector<int> clauses, std::vector<int> target, int cursor_position); void CompositionCompleted(const base::string16& text); - // Send all the events added in Update() to a plug-in. + // Send all the events added in Update() to a plugin. bool SendEvents(PluginInstance* instance); // Retrieves the status of this IME emulator. @@ -114,7 +114,7 @@ // Allow (or disallow) the patch functions to use this WebPluginIMEWin // instance through our patch functions. Our patch functions need a static // member variable |instance_| to access a WebPluginIMEWIn instance. We lock - // this static variable to prevent two or more plug-ins from accessing a + // this static variable to prevent two or more plugins from accessing a // WebPluginIMEWin instance. void Lock(); void Unlock(); @@ -136,7 +136,7 @@ CANDIDATEFORM* candidate); static BOOL WINAPI ImmSetOpenStatus(HIMC context, BOOL open); - // a list of NPEvents to be sent to a plug-in. + // a list of NPEvents to be sent to a plugin. std::vector<NPEvent> events_; // The return value for GCS_COMPSTR. @@ -164,12 +164,12 @@ // WM_IME_STARTCOMPOSITION message when we start composing IME text. bool composing_text_; - // Whether a plug-in supports IME messages. When a plug-in cannot handle + // Whether a plugin supports IME messages. When a plugin cannot handle // IME messages, we need to send the IME text with WM_CHAR messages as Windows // does. bool support_ime_messages_; - // The IME status received from a plug-in. + // The IME status received from a plugin. bool status_updated_; int input_type_; gfx::Rect caret_rect_;
diff --git a/content/child/plugin_messages.h b/content/child/plugin_messages.h index 1f1a656..25d4545 100644 --- a/content/child/plugin_messages.h +++ b/content/child/plugin_messages.h
@@ -305,11 +305,11 @@ HANDLE /* modal_loop_pump_messages_event */, gfx::NativeViewId /* dummy_activation_window*/) -// Send the IME status retrieved from a windowless plug-in. A windowless plug-in -// uses the IME attached to a browser process as a renderer does. A plug-in +// Send the IME status retrieved from a windowless plugin. A windowless plugin +// uses the IME attached to a browser process as a renderer does. A plugin // sends this message to control the IME status of a browser process. I would -// note that a plug-in sends this message to a renderer process that hosts this -// plug-in (not directly to a browser process) so the renderer process can +// note that a plugin sends this message to a renderer process that hosts this +// plugin (not directly to a browser process) so the renderer process can // update its IME status. IPC_MESSAGE_ROUTED2(PluginHostMsg_NotifyIMEStatus, int /* input_type */,
diff --git a/content/common/DEPS b/content/common/DEPS index 36e2048..30297ed 100644 --- a/content/common/DEPS +++ b/content/common/DEPS
@@ -44,6 +44,7 @@ "+third_party/WebKit/public/web/WebAXEnums.h", "+third_party/WebKit/public/web/WebCompositionUnderline.h", "+third_party/WebKit/public/web/WebContentSecurityPolicy.h", + "+third_party/WebKit/public/web/WebDeviceEmulationParams.h", "+third_party/WebKit/public/web/WebDragOperation.h", "+third_party/WebKit/public/web/WebDragStatus.h", "+third_party/WebKit/public/web/WebFindOptions.h",
diff --git a/content/common/cc_messages_unittest.cc b/content/common/cc_messages_unittest.cc index 1807f96..3be3adec 100644 --- a/content/common/cc_messages_unittest.cc +++ b/content/common/cc_messages_unittest.cc
@@ -39,7 +39,6 @@ using cc::TileDrawQuad; using cc::TransferableResource; using cc::StreamVideoDrawQuad; -using cc::VideoLayerImpl; using cc::YUVVideoDrawQuad; using gfx::Transform;
diff --git a/content/common/gpu/media/vaapi_h264_decoder_unittest.cc b/content/common/gpu/media/vaapi_h264_decoder_unittest.cc index 4d20c233..09c3333 100644 --- a/content/common/gpu/media/vaapi_h264_decoder_unittest.cc +++ b/content/common/gpu/media/vaapi_h264_decoder_unittest.cc
@@ -8,14 +8,20 @@ // See http://code.google.com/p/googletest/issues/detail?id=371 #include "testing/gtest/include/gtest/gtest.h" +#include "base/at_exit.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/logging.h" +#include "base/message_loop/message_loop.h" #include "content/common/gpu/media/vaapi_h264_decoder.h" #include "media/base/video_decoder_config.h" #include "third_party/libyuv/include/libyuv.h" +#if defined(USE_OZONE) +#include "ui/ozone/public/ozone_platform.h" +#endif + // This program is run like this: // DISPLAY=:0 ./vaapi_h264_decoder_unittest --input_file input.h264 // [--output_file output.i420] [--md5sum expected_md5_hex] @@ -335,6 +341,8 @@ testing::InitGoogleTest(&argc, argv); // Removes gtest-specific args. base::CommandLine::Init(argc, argv); + base::ShadowingAtExitManager at_exit_manager; + // Needed to enable DVLOG through --vmodule. logging::LoggingSettings settings; settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; @@ -362,8 +370,16 @@ } if (it->first == "v" || it->first == "vmodule") continue; + if (it->first == "ozone-platform") + continue; LOG(FATAL) << "Unexpected switch: " << it->first << ":" << it->second; } +#if defined(USE_OZONE) + base::MessageLoopForUI main_loop; + ui::OzonePlatform::InitializeForUI(); + ui::OzonePlatform::InitializeForGPU(); +#endif + return RUN_ALL_TESTS(); }
diff --git a/content/common/host_discardable_shared_memory_manager.cc b/content/common/host_discardable_shared_memory_manager.cc index e150fc63..3d2be9d 100644 --- a/content/common/host_discardable_shared_memory_manager.cc +++ b/content/common/host_discardable_shared_memory_manager.cc
@@ -18,6 +18,46 @@ namespace content { namespace { +class DiscardableMemoryShmemChunkImpl + : public base::DiscardableMemoryShmemChunk { + public: + explicit DiscardableMemoryShmemChunkImpl( + scoped_ptr<base::DiscardableSharedMemory> shared_memory) + : shared_memory_(shared_memory.Pass()), is_locked_(true) {} + ~DiscardableMemoryShmemChunkImpl() override { + if (is_locked_) + shared_memory_->Unlock(0, 0); + shared_memory_->Purge(base::Time::Now()); + } + + // Overridden from base::DiscardableMemoryShmemChunk: + bool Lock() override { + DCHECK(!is_locked_); + + if (shared_memory_->Lock(0, 0) != base::DiscardableSharedMemory::SUCCESS) + return false; + + is_locked_ = true; + return true; + } + void Unlock() override { + DCHECK(is_locked_); + + shared_memory_->Unlock(0, 0); + is_locked_ = false; + } + void* Memory() const override { + DCHECK(is_locked_); + return shared_memory_->memory(); + } + + private: + scoped_ptr<base::DiscardableSharedMemory> shared_memory_; + bool is_locked_; + + DISALLOW_COPY_AND_ASSIGN(DiscardableMemoryShmemChunkImpl); +}; + base::LazyInstance<HostDiscardableSharedMemoryManager> g_discardable_shared_memory_manager = LAZY_INSTANCE_INITIALIZER; @@ -61,10 +101,16 @@ scoped_ptr<base::DiscardableMemoryShmemChunk> HostDiscardableSharedMemoryManager::AllocateLockedDiscardableMemory( size_t size) { - // TODO(reveman): Need to implement this for discardable memory support in - // the browser process. - NOTIMPLEMENTED(); - return nullptr; + // Note: Use DiscardableSharedMemoryHeap for in-process allocation + // of discardable memory if the cost of each allocation is too high. + base::SharedMemoryHandle handle; + AllocateLockedDiscardableSharedMemory(base::GetCurrentProcessHandle(), size, + &handle); + CHECK(base::SharedMemory::IsHandleValid(handle)); + scoped_ptr<base::DiscardableSharedMemory> memory( + new base::DiscardableSharedMemory(handle)); + CHECK(memory->Map(size)); + return make_scoped_ptr(new DiscardableMemoryShmemChunkImpl(memory.Pass())); } void HostDiscardableSharedMemoryManager:: @@ -72,86 +118,8 @@ base::ProcessHandle process_handle, size_t size, base::SharedMemoryHandle* shared_memory_handle) { - // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 - // is fixed. - tracked_objects::ScopedTracker tracking_profile1( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466405 AllocateLockedDiscardableSharedMemoryForChild::Start")); - base::AutoLock lock(lock_); - - // Memory usage must be reduced to prevent the addition of |size| from - // taking usage above the limit. Usage should be reduced to 0 in cases - // where |size| is greater than the limit. - size_t limit = 0; - // Note: the actual mapped size can be larger than requested and cause - // |bytes_allocated_| to temporarily be larger than |memory_limit_|. The - // error is minimized by incrementing |bytes_allocated_| with the actual - // mapped size rather than |size| below. - if (size < memory_limit_) - limit = memory_limit_ - size; - - // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 - // is fixed. - tracked_objects::ScopedTracker tracking_profile2( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466405 " - "AllocateLockedDiscardableSharedMemoryForChild::ReduceMemoryUsage")); - if (bytes_allocated_ > limit) - ReduceMemoryUsageUntilWithinLimit(limit); - - // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 - // is fixed. - tracked_objects::ScopedTracker tracking_profile3( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466405 AllocateLockedDiscardableSharedMemoryForChild::NewMemory")); - linked_ptr<base::DiscardableSharedMemory> memory( - new base::DiscardableSharedMemory); - if (!memory->CreateAndMap(size)) { - *shared_memory_handle = base::SharedMemory::NULLHandle(); - return; - } - - // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 - // is fixed. - tracked_objects::ScopedTracker tracking_profile4( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466405 " - "AllocateLockedDiscardableSharedMemoryForChild::ShareToProcess")); - if (!memory->ShareToProcess(process_handle, shared_memory_handle)) { - LOG(ERROR) << "Cannot share discardable memory segment"; - *shared_memory_handle = base::SharedMemory::NULLHandle(); - return; - } - - base::CheckedNumeric<size_t> checked_bytes_allocated = bytes_allocated_; - checked_bytes_allocated += memory->mapped_size(); - if (!checked_bytes_allocated.IsValid()) { - *shared_memory_handle = base::SharedMemory::NULLHandle(); - return; - } - - // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 - // is fixed. - tracked_objects::ScopedTracker tracking_profile5( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466405 " - "AllocateLockedDiscardableSharedMemoryForChild::" - "BytesAllocatedChanged")); - bytes_allocated_ = checked_bytes_allocated.ValueOrDie(); - BytesAllocatedChanged(bytes_allocated_); - - segments_.push_back(MemorySegment(memory, process_handle)); - std::push_heap(segments_.begin(), segments_.end(), CompareMemoryUsageTime); - - // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 - // is fixed. - tracked_objects::ScopedTracker tracking_profile6( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "466405 " - "AllocateLockedDiscardableSharedMemoryForChild::" - "ScheduleEnforceMemoryPolicy")); - if (bytes_allocated_ > memory_limit_) - ScheduleEnforceMemoryPolicy(); + AllocateLockedDiscardableSharedMemory(process_handle, size, + shared_memory_handle); } void HostDiscardableSharedMemoryManager::ProcessRemoved( @@ -195,6 +163,89 @@ ReduceMemoryUsageUntilWithinMemoryLimit(); } +void HostDiscardableSharedMemoryManager::AllocateLockedDiscardableSharedMemory( + base::ProcessHandle process_handle, + size_t size, + base::SharedMemoryHandle* shared_memory_handle) { + // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 + // is fixed. + tracked_objects::ScopedTracker tracking_profile1( + FROM_HERE_WITH_EXPLICIT_FUNCTION( + "466405 AllocateLockedDiscardableSharedMemory::Start")); + base::AutoLock lock(lock_); + + // Memory usage must be reduced to prevent the addition of |size| from + // taking usage above the limit. Usage should be reduced to 0 in cases + // where |size| is greater than the limit. + size_t limit = 0; + // Note: the actual mapped size can be larger than requested and cause + // |bytes_allocated_| to temporarily be larger than |memory_limit_|. The + // error is minimized by incrementing |bytes_allocated_| with the actual + // mapped size rather than |size| below. + if (size < memory_limit_) + limit = memory_limit_ - size; + + // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 + // is fixed. + tracked_objects::ScopedTracker tracking_profile2( + FROM_HERE_WITH_EXPLICIT_FUNCTION( + "466405 AllocateLockedDiscardableSharedMemory::ReduceMemoryUsage")); + if (bytes_allocated_ > limit) + ReduceMemoryUsageUntilWithinLimit(limit); + + // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 + // is fixed. + tracked_objects::ScopedTracker tracking_profile3( + FROM_HERE_WITH_EXPLICIT_FUNCTION( + "466405 AllocateLockedDiscardableSharedMemory::NewMemory")); + linked_ptr<base::DiscardableSharedMemory> memory( + new base::DiscardableSharedMemory); + if (!memory->CreateAndMap(size)) { + *shared_memory_handle = base::SharedMemory::NULLHandle(); + return; + } + + // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 + // is fixed. + tracked_objects::ScopedTracker tracking_profile4( + FROM_HERE_WITH_EXPLICIT_FUNCTION( + "466405 AllocateLockedDiscardableSharedMemory::ShareToProcess")); + if (!memory->ShareToProcess(process_handle, shared_memory_handle)) { + LOG(ERROR) << "Cannot share discardable memory segment"; + *shared_memory_handle = base::SharedMemory::NULLHandle(); + return; + } + + base::CheckedNumeric<size_t> checked_bytes_allocated = bytes_allocated_; + checked_bytes_allocated += memory->mapped_size(); + if (!checked_bytes_allocated.IsValid()) { + *shared_memory_handle = base::SharedMemory::NULLHandle(); + return; + } + + // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 + // is fixed. + tracked_objects::ScopedTracker tracking_profile5( + FROM_HERE_WITH_EXPLICIT_FUNCTION( + "466405 " + "AllocateLockedDiscardableSharedMemory::BytesAllocatedChanged")); + bytes_allocated_ = checked_bytes_allocated.ValueOrDie(); + BytesAllocatedChanged(bytes_allocated_); + + segments_.push_back(MemorySegment(memory, process_handle)); + std::push_heap(segments_.begin(), segments_.end(), CompareMemoryUsageTime); + + // TODO(erikchen): Remove ScopedTracker below once http://crbug.com/466405 + // is fixed. + tracked_objects::ScopedTracker tracking_profile6( + FROM_HERE_WITH_EXPLICIT_FUNCTION( + "466405 " + "AllocateLockedDiscardableSharedMemory::" + "ScheduleEnforceMemoryPolicy")); + if (bytes_allocated_ > memory_limit_) + ScheduleEnforceMemoryPolicy(); +} + void HostDiscardableSharedMemoryManager::OnMemoryPressure( base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) { base::AutoLock lock(lock_);
diff --git a/content/common/host_discardable_shared_memory_manager.h b/content/common/host_discardable_shared_memory_manager.h index 624dd2fd..6998f0d0 100644 --- a/content/common/host_discardable_shared_memory_manager.h +++ b/content/common/host_discardable_shared_memory_manager.h
@@ -71,6 +71,10 @@ return a.memory->last_known_usage() > b.memory->last_known_usage(); } + void AllocateLockedDiscardableSharedMemory( + base::ProcessHandle process_handle, + size_t size, + base::SharedMemoryHandle* shared_memory_handle); void OnMemoryPressure( base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level); void ReduceMemoryUsageUntilWithinMemoryLimit();
diff --git a/content/common/image_messages.h b/content/common/image_messages.h index b8869087..8e8279f 100644 --- a/content/common/image_messages.h +++ b/content/common/image_messages.h
@@ -17,7 +17,7 @@ // Requests the renderer to download the specified image, decode it, // and send the image data back via ImageHostMsg_DidDownloadImage. -IPC_MESSAGE_ROUTED4(ImageMsg_DownloadImage, +IPC_MESSAGE_ROUTED5(ImageMsg_DownloadImage, int /* Identifier for the request */, GURL /* URL of the image */, bool /* is favicon (turn off cookies) */, @@ -26,7 +26,8 @@ bitmaps at the passed in GURL <= max size, the smallest bitmap is resized to the max size and is the only result. A max size of zero means - that the max size is unlimited. */) + that the max size is unlimited. */, + bool /* bypass cache */) // Messages sent from the renderer to the browser.
diff --git a/content/common/plugin_list.cc b/content/common/plugin_list.cc index a0f9507..7e8d1c2 100644 --- a/content/common/plugin_list.cc +++ b/content/common/plugin_list.cc
@@ -278,7 +278,7 @@ void PluginList::SetPlugins(const std::vector<WebPluginInfo>& plugins) { base::AutoLock lock(lock_); - // If we haven't been invalidated in the mean time, mark the plug-in list as + // If we haven't been invalidated in the mean time, mark the plugin list as // up-to-date. if (loading_state_ != LOADING_STATE_NEEDS_REFRESH) loading_state_ = LOADING_STATE_UP_TO_DATE; @@ -340,11 +340,11 @@ } // Add in plugins by url. - // We do not permit URL-sniff based plug-in MIME type overrides aside from + // We do not permit URL-sniff based plugin MIME type overrides aside from // the case where the "type" was initially missing. // We collected stats to determine this approach isn't a major compat issue, // and we defend against content confusion attacks in various cases, such - // as when the user doesn't have the Flash plug-in enabled. + // as when the user doesn't have the Flash plugin enabled. std::string path = url.path(); std::string::size_type last_dot = path.rfind('.'); if (last_dot != std::string::npos && mime_type.empty()) {
diff --git a/content/common/plugin_list.h b/content/common/plugin_list.h index 9ad67fc..26a2aa64 100644 --- a/content/common/plugin_list.h +++ b/content/common/plugin_list.h
@@ -103,7 +103,7 @@ void GetPlugins(std::vector<WebPluginInfo>* plugins, bool include_npapi); - // Copies the list of plug-ins into |plugins| without loading them. + // Copies the list of plugins into |plugins| without loading them. // Returns true if the list of plugins is up-to-date. bool GetPluginsNoRefresh(std::vector<WebPluginInfo>* plugins); @@ -116,9 +116,9 @@ // returns plugins which support wildcard mime types (* as the mime // type). The |info| parameter is required to be non-NULL. The // list is in order of "most desirable" to "least desirable". - // If |use_stale| is NULL, this will load the plug-in list if necessary. - // If it is not NULL, the plug-in list will not be loaded, and |*use_stale| - // will be true iff the plug-in list was stale. + // If |use_stale| is NULL, this will load the plugin list if necessary. + // If it is not NULL, the plugin list will not be loaded, and |*use_stale| + // will be true iff the plugin list was stale. void GetPluginInfoArray(const GURL& url, const std::string& mime_type, bool allow_wildcard, @@ -127,7 +127,7 @@ std::vector<WebPluginInfo>* info, std::vector<std::string>* actual_mime_types); - // Load a specific plugin with full path. Return true iff loading the plug-in + // Load a specific plugin with full path. Return true iff loading the plugin // was successful. bool LoadPluginIntoPluginList(const base::FilePath& filename, std::vector<WebPluginInfo>* plugins, @@ -212,7 +212,7 @@ // Internals // - // States whether we will load the plug-in list the next time we try to access + // States whether we will load the plugin list the next time we try to access // it, whether we are currently in the process of loading it, or whether we // consider it up-to-date. LoadingState loading_state_; @@ -226,7 +226,7 @@ // Holds information about internal plugins. std::vector<WebPluginInfo> internal_plugins_; - // A list holding all plug-ins. + // A list holding all plugins. std::vector<WebPluginInfo> plugins_list_; // Callback that is invoked whenever the PluginList will reload the plugins.
diff --git a/content/common/process_type.cc b/content/common/process_type.cc index d3c6894..34019d4 100644 --- a/content/common/process_type.cc +++ b/content/common/process_type.cc
@@ -16,7 +16,7 @@ case PROCESS_TYPE_RENDERER: return "Tab"; case PROCESS_TYPE_PLUGIN: - return "Plug-in"; + return "Plugin"; case PROCESS_TYPE_UTILITY: return "Utility"; case PROCESS_TYPE_ZYGOTE:
diff --git a/content/common/sandbox_init_mac.h b/content/common/sandbox_init_mac.h index 5407081..4bbabb39 100644 --- a/content/common/sandbox_init_mac.h +++ b/content/common/sandbox_init_mac.h
@@ -7,7 +7,7 @@ namespace content { -// Initialize the sandbox for renderer, gpu, utility, worker, and plug-in +// Initialize the sandbox for renderer, gpu, utility, worker, and plugin // processes, depending on the command line flags. For the browser process which // is not sandboxed, this call is a no-op. // Returns true if the sandbox was initialized succesfully, false if an error
diff --git a/content/common/view_messages.h b/content/common/view_messages.h index db273e7..5b423d3 100644 --- a/content/common/view_messages.h +++ b/content/common/view_messages.h
@@ -42,6 +42,7 @@ #include "third_party/WebKit/public/platform/WebFloatPoint.h" #include "third_party/WebKit/public/platform/WebFloatRect.h" #include "third_party/WebKit/public/platform/WebScreenInfo.h" +#include "third_party/WebKit/public/web/WebDeviceEmulationParams.h" #include "third_party/WebKit/public/web/WebFindOptions.h" #include "third_party/WebKit/public/web/WebMediaPlayerAction.h" #include "third_party/WebKit/public/web/WebPluginAction.h" @@ -73,6 +74,8 @@ #define IPC_MESSAGE_START ViewMsgStart +IPC_ENUM_TRAITS_MAX_VALUE(blink::WebDeviceEmulationParams::ScreenPosition, + blink::WebDeviceEmulationParams::ScreenPositionLast) IPC_ENUM_TRAITS_MAX_VALUE(blink::WebMediaPlayerAction::Type, blink::WebMediaPlayerAction::Type::TypeLast) IPC_ENUM_TRAITS_MAX_VALUE(blink::WebPluginAction::Type, @@ -139,6 +142,20 @@ IPC_STRUCT_TRAITS_MEMBER(height) IPC_STRUCT_TRAITS_END() +IPC_STRUCT_TRAITS_BEGIN(blink::WebSize) + IPC_STRUCT_TRAITS_MEMBER(width) + IPC_STRUCT_TRAITS_MEMBER(height) +IPC_STRUCT_TRAITS_END() + +IPC_STRUCT_TRAITS_BEGIN(blink::WebDeviceEmulationParams) + IPC_STRUCT_TRAITS_MEMBER(screenPosition) + IPC_STRUCT_TRAITS_MEMBER(deviceScaleFactor) + IPC_STRUCT_TRAITS_MEMBER(viewSize) + IPC_STRUCT_TRAITS_MEMBER(fitToView) + IPC_STRUCT_TRAITS_MEMBER(offset) + IPC_STRUCT_TRAITS_MEMBER(scale) +IPC_STRUCT_TRAITS_END() + IPC_STRUCT_TRAITS_BEGIN(blink::WebScreenInfo) IPC_STRUCT_TRAITS_MEMBER(deviceScaleFactor) IPC_STRUCT_TRAITS_MEMBER(depth) @@ -619,6 +636,13 @@ IPC_MESSAGE_ROUTED1(ViewMsg_Resize, ViewMsg_Resize_Params /* params */) +// Enables device emulation. See WebDeviceEmulationParams for description. +IPC_MESSAGE_ROUTED1(ViewMsg_EnableDeviceEmulation, + blink::WebDeviceEmulationParams /* params */) + +// Disables device emulation, enabled previously by EnableDeviceEmulation. +IPC_MESSAGE_ROUTED0(ViewMsg_DisableDeviceEmulation) + // Sent to inform the renderer of its screen device color profile. An empty // profile tells the renderer use the default sRGB color profile. IPC_MESSAGE_ROUTED1(ViewMsg_ColorProfile,
diff --git a/content/content_browser.gypi b/content/content_browser.gypi index 48543ee..23a5f01 100644 --- a/content/content_browser.gypi +++ b/content/content_browser.gypi
@@ -1003,6 +1003,8 @@ 'browser/notifications/notification_message_filter.h', 'browser/notifications/page_notification_delegate.cc', 'browser/notifications/page_notification_delegate.h', + 'browser/notifications/platform_notification_context.cc', + 'browser/notifications/platform_notification_context.h', 'browser/permissions/permission_service_context.cc', 'browser/permissions/permission_service_context.h', 'browser/permissions/permission_service_impl.cc', @@ -1715,6 +1717,11 @@ '../third_party/mojo/mojo_public.gyp:mojo_cpp_bindings', ], }], + ['debug_devtools==1', { + 'defines': [ + 'DEBUG_DEVTOOLS=1', + ], + }], ['enable_basic_printing==1 or enable_print_preview==1', { 'dependencies': [ '../printing/printing.gyp:printing',
diff --git a/content/content_tests.gypi b/content/content_tests.gypi index a9178d6..8a67c4ba 100644 --- a/content/content_tests.gypi +++ b/content/content_tests.gypi
@@ -474,6 +474,7 @@ 'browser/net/sqlite_persistent_cookie_store_unittest.cc', 'browser/notifications/notification_database_data_unittest.cc', 'browser/notifications/notification_database_unittest.cc', + 'browser/notifications/platform_notification_context_unittest.cc', 'browser/notification_service_impl_unittest.cc', 'browser/power_monitor_message_broadcaster_unittest.cc', 'browser/power_profiler/power_profiler_service_unittest.cc', @@ -1663,6 +1664,7 @@ '../testing/gtest.gyp:gtest', '../third_party/libyuv/libyuv.gyp:libyuv', '../ui/gfx/gfx.gyp:gfx_geometry', + '../ui/ozone/ozone.gyp:ozone', ], 'sources': [ 'common/gpu/media/vaapi_h264_decoder_unittest.cc',
diff --git a/content/plugin/webplugin_proxy.cc b/content/plugin/webplugin_proxy.cc index 81003fc..21f76ea 100644 --- a/content/plugin/webplugin_proxy.cc +++ b/content/plugin/webplugin_proxy.cc
@@ -605,8 +605,8 @@ #if defined(OS_WIN) && !defined(USE_AURA) void WebPluginProxy::UpdateIMEStatus() { - // Retrieve the IME status from a plug-in and send it to a renderer process - // when the plug-in has updated it. + // Retrieve the IME status from a plugin and send it to a renderer process + // when the plugin has updated it. int input_type; gfx::Rect caret_rect; if (!delegate_->GetIMEStatus(&input_type, &caret_rect))
diff --git a/content/plugin/webplugin_proxy.h b/content/plugin/webplugin_proxy.h index e1fb45d..458921af 100644 --- a/content/plugin/webplugin_proxy.h +++ b/content/plugin/webplugin_proxy.h
@@ -131,7 +131,7 @@ void OnResourceCreated(int resource_id, WebPluginResourceClient* client); #if defined(OS_WIN) && !defined(USE_AURA) - // Retrieves the IME status from a windowless plug-in and sends it to a + // Retrieves the IME status from a windowless plugin and sends it to a // renderer process. A renderer process will convert the coordinates from // local to the window coordinates and send the converted coordinates to a // browser process.
diff --git a/content/public/browser/plugin_data_remover.h b/content/public/browser/plugin_data_remover.h index 02d3acd..e242cf2 100644 --- a/content/public/browser/plugin_data_remover.h +++ b/content/public/browser/plugin_data_remover.h
@@ -24,10 +24,10 @@ static PluginDataRemover* Create(content::BrowserContext* browser_context); virtual ~PluginDataRemover() {} - // Starts removing plug-in data stored since |begin_time|. + // Starts removing plugin data stored since |begin_time|. virtual base::WaitableEvent* StartRemoving(base::Time begin_time) = 0; - // Returns a list of all plug-ins that support removing LSO data. This method + // Returns a list of all plugins that support removing LSO data. This method // will use cached plugin data. Call PluginService::GetPlugins() if the latest // data is needed. static void GetSupportedPlugins(std::vector<WebPluginInfo>* plugins);
diff --git a/content/public/browser/plugin_service.h b/content/public/browser/plugin_service.h index 9121e68..9420f3e 100644 --- a/content/public/browser/plugin_service.h +++ b/content/public/browser/plugin_service.h
@@ -53,7 +53,7 @@ // Must be called on the instance to finish initialization. virtual void Init() = 0; - // Starts watching for changes in the list of installed plug-ins. + // Starts watching for changes in the list of installed plugins. virtual void StartWatchingPlugins() = 0; // Gets the plugin in the list of plugins that matches the given url and mime @@ -108,7 +108,7 @@ // If the plugin with the given path is running, cleanly shuts it down. virtual void ForcePluginShutdown(const base::FilePath& plugin_path) = 0; - // Used to monitor plug-in stability. An unstable plug-in is one that has + // Used to monitor plugin stability. An unstable plugin is one that has // crashed more than a set number of times in a set time period. virtual bool IsPluginUnstable(const base::FilePath& plugin_path) = 0;
diff --git a/content/public/browser/plugin_service_filter.h b/content/public/browser/plugin_service_filter.h index fda9d33..b6266c12 100644 --- a/content/public/browser/plugin_service_filter.h +++ b/content/public/browser/plugin_service_filter.h
@@ -14,7 +14,7 @@ namespace content { struct WebPluginInfo; -// Callback class to let the client filter the list of all installed plug-ins +// Callback class to let the client filter the list of all installed plugins // and block them from being loaded. // This class is called on the FILE thread. class PluginServiceFilter {
diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h index abdda45..4380412 100644 --- a/content/public/browser/web_contents.h +++ b/content/public/browser/web_contents.h
@@ -584,15 +584,19 @@ // Sends a request to download the given image |url| and returns the unique // id of the download request. When the download is finished, |callback| will - // be called with the bitmaps received from the renderer. If |is_favicon| is - // true, the cookies are not sent and not accepted during download. + // be called with the bitmaps received from the renderer. + // If |is_favicon| is true, the cookies are not sent and not accepted during + // download. // Bitmaps with pixel sizes larger than |max_bitmap_size| are filtered out // from the bitmap results. If there are no bitmap results <= // |max_bitmap_size|, the smallest bitmap is resized to |max_bitmap_size| and // is the only result. A |max_bitmap_size| of 0 means unlimited. + // If |bypass_cache| is true, |url| is requested from the server even if it + // is present in the browser cache. virtual int DownloadImage(const GURL& url, bool is_favicon, uint32_t max_bitmap_size, + bool bypass_cache, const ImageDownloadCallback& callback) = 0; // Returns true if the WebContents is responsible for displaying a subframe
diff --git a/content/public/common/child_process_host.h b/content/public/common/child_process_host.h index 67a39ac7..c79938b 100644 --- a/content/public/common/child_process_host.h +++ b/content/public/common/child_process_host.h
@@ -64,7 +64,7 @@ // Requests that the child run in a process that does not protect the // heap against execution. Normally, heap pages may be made executable // with mprotect, so this mode should be used sparingly. It is intended - // for processes that may host plug-ins that expect an executable heap + // for processes that may host plugins that expect an executable heap // without having to call mprotect. This option is currently incompatible // with CHILD_NO_PIE. CHILD_ALLOW_HEAP_EXECUTION = 1 << 2,
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index df52d509..b32db22d 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc
@@ -212,7 +212,7 @@ // Disables compositor-accelerated touch-screen pinch gestures. const char kDisablePinch[] = "disable-pinch"; -// Disable discovering third-party plug-ins. Effectively loading only +// Disable discovering third-party plugins. Effectively loading only // ones shipped with the browser plus third-party ones as specified by // --extra-plugin-dir and --load-plugin switches. const char kDisablePluginsDiscovery[] = "disable-plugins-discovery";
diff --git a/content/public/common/sandbox_init.h b/content/public/common/sandbox_init.h index 34f366a..bd12ff89 100644 --- a/content/public/common/sandbox_init.h +++ b/content/public/common/sandbox_init.h
@@ -28,7 +28,7 @@ #if defined(OS_WIN) -// Initialize the sandbox for renderer, gpu, utility, worker, nacl, and plug-in +// Initialize the sandbox for renderer, gpu, utility, worker, nacl, and plugin // processes, depending on the command line flags. Although The browser process // is not sandboxed, this also needs to be called because it will initialize // the broker code.
diff --git a/content/public/common/webplugininfo.h b/content/public/common/webplugininfo.h index 2912cefb..c84b924 100644 --- a/content/public/common/webplugininfo.h +++ b/content/public/common/webplugininfo.h
@@ -68,7 +68,7 @@ (type == PLUGIN_TYPE_PEPPER_UNSANDBOXED)); } - // Parse a version string as used by a plug-in. This method is more lenient + // Parse a version string as used by a plugin. This method is more lenient // in accepting weird version strings than base::Version::GetFromString() static void CreateVersionFromString(const base::string16& version_string, base::Version* parsed_version);
diff --git a/content/public/renderer/content_renderer_client.h b/content/public/renderer/content_renderer_client.h index 27dca47b..45176ab3 100644 --- a/content/public/renderer/content_renderer_client.h +++ b/content/public/renderer/content_renderer_client.h
@@ -106,7 +106,7 @@ const blink::WebPluginParams& params, blink::WebPlugin** plugin); - // Creates a replacement plug-in that is shown when the plug-in at |file_path| + // Creates a replacement plugin that is shown when the plugin at |file_path| // couldn't be loaded. This allows the embedder to show a custom placeholder. virtual blink::WebPlugin* CreatePluginReplacement( RenderFrame* render_frame,
diff --git a/content/public/renderer/render_process_observer.h b/content/public/renderer/render_process_observer.h index de23dae..582a60f 100644 --- a/content/public/renderer/render_process_observer.h +++ b/content/public/renderer/render_process_observer.h
@@ -30,7 +30,7 @@ // Called right after the WebKit API is initialized. virtual void WebKitInitialized() {} - // Called when the renderer cache of the plug-in list has changed. + // Called when the renderer cache of the plugin list has changed. virtual void PluginListChanged() {} virtual void IdleNotification() {}
diff --git a/content/public/renderer/resource_fetcher.h b/content/public/renderer/resource_fetcher.h index d0e9062..2c402aa 100644 --- a/content/public/renderer/resource_fetcher.h +++ b/content/public/renderer/resource_fetcher.h
@@ -48,12 +48,14 @@ static ResourceFetcher* Create(const GURL& url); // Set the corresponding parameters of the request. Must be called before - // Start. By default, requests are GETs with no body. + // Start. By default, requests are GETs with no body and respect the default + // cache policy. virtual void SetMethod(const std::string& method) = 0; virtual void SetBody(const std::string& body) = 0; virtual void SetHeader(const std::string& header, const std::string& value) = 0; virtual void SetSkipServiceWorker(bool skip_service_worker) = 0; + virtual void SetCachePolicy(blink::WebURLRequest::CachePolicy policy) = 0; // Associate the corresponding WebURLLoaderOptions to the loader. Must be // called before Start. Used if the LoaderType is FRAME_ASSOCIATED_LOADER.
diff --git a/content/renderer/devtools/devtools_agent.cc b/content/renderer/devtools/devtools_agent.cc index 57f4337..dca9b863 100644 --- a/content/renderer/devtools/devtools_agent.cc +++ b/content/renderer/devtools/devtools_agent.cc
@@ -201,15 +201,6 @@ } } -void DevToolsAgent::enableDeviceEmulation( - const blink::WebDeviceEmulationParams& params) { - GetRenderViewImpl()->EnableScreenMetricsEmulation(params); -} - -void DevToolsAgent::disableDeviceEmulation() { - GetRenderViewImpl()->DisableScreenMetricsEmulation(); -} - // static DevToolsAgent* DevToolsAgent::FromRoutingId(int routing_id) { IdToAgentMap::iterator it = g_agent_for_routing_id.Get().find(routing_id);
diff --git a/content/renderer/devtools/devtools_agent.h b/content/renderer/devtools/devtools_agent.h index 8e0502fd..e2f9531 100644 --- a/content/renderer/devtools/devtools_agent.h +++ b/content/renderer/devtools/devtools_agent.h
@@ -72,10 +72,6 @@ void enableTracing(const blink::WebString& category_filter) override; void disableTracing() override; - void enableDeviceEmulation( - const blink::WebDeviceEmulationParams& params) override; - void disableDeviceEmulation() override; - void OnAttach(const std::string& host_id); void OnReattach(const std::string& host_id, const std::string& agent_state);
diff --git a/content/renderer/external_popup_menu.cc b/content/renderer/external_popup_menu.cc index 3a635e5..f2363e3 100644 --- a/content/renderer/external_popup_menu.cc +++ b/content/renderer/external_popup_menu.cc
@@ -23,7 +23,7 @@ } void ExternalPopupMenu::SetOriginScaleAndOffsetForEmulation( - float scale, const gfx::Point& offset) { + float scale, const gfx::PointF& offset) { origin_scale_for_emulation_ = scale; origin_offset_for_emulation_ = offset; }
diff --git a/content/renderer/external_popup_menu.h b/content/renderer/external_popup_menu.h index da73747..ccd4fdc 100644 --- a/content/renderer/external_popup_menu.h +++ b/content/renderer/external_popup_menu.h
@@ -10,7 +10,7 @@ #include "base/basictypes.h" #include "third_party/WebKit/public/web/WebExternalPopupMenu.h" #include "third_party/WebKit/public/web/WebPopupMenuInfo.h" -#include "ui/gfx/geometry/point.h" +#include "ui/gfx/geometry/point_f.h" namespace blink { class WebExternalPopupMenuClient; @@ -28,7 +28,7 @@ virtual ~ExternalPopupMenu() {} void SetOriginScaleAndOffsetForEmulation( - float scale, const gfx::Point& offset); + float scale, const gfx::PointF& offset); #if defined(OS_MACOSX) // Called when the user has selected an item. |selected_item| is -1 if the @@ -53,7 +53,7 @@ // Popups may be displaced when screen metrics emulation is enabled. // These scale and offset are used to properly adjust popup position. float origin_scale_for_emulation_; - gfx::Point origin_offset_for_emulation_; + gfx::PointF origin_offset_for_emulation_; DISALLOW_COPY_AND_ASSIGN(ExternalPopupMenu); };
diff --git a/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc b/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc index 3deb00b..fa88aa9 100644 --- a/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc +++ b/content/renderer/fetchers/multi_resolution_image_resource_fetcher.cc
@@ -26,6 +26,7 @@ WebFrame* frame, int id, WebURLRequest::RequestContext request_context, + blink::WebURLRequest::CachePolicy cache_policy, const Callback& callback) : callback_(callback), id_(id), @@ -45,6 +46,8 @@ if (request_context == WebURLRequest::RequestContextFavicon) fetcher_->SetSkipServiceWorker(true); + fetcher_->SetCachePolicy(cache_policy); + fetcher_->Start( frame, request_context,
diff --git a/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h b/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h index c968a87..de44ace 100644 --- a/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h +++ b/content/renderer/fetchers/multi_resolution_image_resource_fetcher.h
@@ -37,6 +37,7 @@ blink::WebFrame* frame, int id, blink::WebURLRequest::RequestContext request_context, + blink::WebURLRequest::CachePolicy cache_policy, const Callback& callback); virtual ~MultiResolutionImageResourceFetcher();
diff --git a/content/renderer/fetchers/resource_fetcher_impl.cc b/content/renderer/fetchers/resource_fetcher_impl.cc index 152e71b..e296937 100644 --- a/content/renderer/fetchers/resource_fetcher_impl.cc +++ b/content/renderer/fetchers/resource_fetcher_impl.cc
@@ -76,6 +76,14 @@ request_.setSkipServiceWorker(skip_service_worker); } +void ResourceFetcherImpl::SetCachePolicy( + blink::WebURLRequest::CachePolicy policy) { + DCHECK(!request_.isNull()); + DCHECK(!loader_); + + request_.setCachePolicy(policy); +} + void ResourceFetcherImpl::SetLoaderOptions( const blink::WebURLLoaderOptions& options) { DCHECK(!request_.isNull());
diff --git a/content/renderer/fetchers/resource_fetcher_impl.h b/content/renderer/fetchers/resource_fetcher_impl.h index d73127d..4e22ff0 100644 --- a/content/renderer/fetchers/resource_fetcher_impl.h +++ b/content/renderer/fetchers/resource_fetcher_impl.h
@@ -35,6 +35,7 @@ void SetBody(const std::string& body) override; void SetHeader(const std::string& header, const std::string& value) override; void SetSkipServiceWorker(bool skip_service_worker) override; + void SetCachePolicy(blink::WebURLRequest::CachePolicy policy) override; void SetLoaderOptions(const blink::WebURLLoaderOptions& options) override; void Start(blink::WebFrame* frame, blink::WebURLRequest::RequestContext request_context,
diff --git a/content/renderer/image_loading_helper.cc b/content/renderer/image_loading_helper.cc index 7b7982a..afd0fee 100644 --- a/content/renderer/image_loading_helper.cc +++ b/content/renderer/image_loading_helper.cc
@@ -104,10 +104,12 @@ ImageLoadingHelper::~ImageLoadingHelper() { } -void ImageLoadingHelper::OnDownloadImage(int id, - const GURL& image_url, - bool is_favicon, - uint32_t max_image_size) { +void ImageLoadingHelper::OnDownloadImage( + int id, + const GURL& image_url, + bool is_favicon, + uint32_t max_image_size, + bool bypass_cache) { std::vector<SkBitmap> result_images; std::vector<gfx::Size> result_original_image_sizes; if (image_url.SchemeIs(url::kDataScheme)) { @@ -118,7 +120,8 @@ gfx::Size(data_image.width(), data_image.height())); } } else { - if (DownloadImage(id, image_url, is_favicon, max_image_size)) { + if (DownloadImage(id, image_url, is_favicon, max_image_size, + bypass_cache)) { // Will complete asynchronously via ImageLoadingHelper::DidDownloadImage return; } @@ -132,19 +135,20 @@ result_original_image_sizes)); } -bool ImageLoadingHelper::DownloadImage(int id, - const GURL& image_url, - bool is_favicon, - uint32_t max_image_size) { +bool ImageLoadingHelper::DownloadImage( + int id, + const GURL& image_url, + bool is_favicon, + uint32_t max_image_size, + bool bypass_cache) { // Create an image resource fetcher and assign it with a call back object. image_fetchers_.push_back(new MultiResolutionImageResourceFetcher( - image_url, - render_frame()->GetWebFrame(), - id, + image_url, render_frame()->GetWebFrame(), id, is_favicon ? WebURLRequest::RequestContextFavicon : WebURLRequest::RequestContextImage, - base::Bind(&ImageLoadingHelper::DidDownloadImage, - base::Unretained(this), + bypass_cache ? WebURLRequest::ReloadBypassingCache + : WebURLRequest::UseProtocolCachePolicy, + base::Bind(&ImageLoadingHelper::DidDownloadImage, base::Unretained(this), max_image_size))); return true; }
diff --git a/content/renderer/image_loading_helper.h b/content/renderer/image_loading_helper.h index 185f3b7..d5daf8fa 100644 --- a/content/renderer/image_loading_helper.h +++ b/content/renderer/image_loading_helper.h
@@ -31,7 +31,8 @@ void OnDownloadImage(int id, const GURL& image_url, bool is_favicon, - uint32_t max_image_size); + uint32_t max_image_size, + bool bypass_cache); // Requests to download an image. When done, the ImageLoadingHelper // is notified by way of DidDownloadImage. Returns true if the @@ -46,7 +47,8 @@ bool DownloadImage(int id, const GURL& image_url, bool is_favicon, - uint32_t max_image_size); + uint32_t max_image_size, + bool bypass_cache); // This callback is triggered when DownloadImage completes, either // succesfully or with a failure. See DownloadImage for more
diff --git a/content/renderer/media/peer_connection_tracker.cc b/content/renderer/media/peer_connection_tracker.cc index 46eeee9..728f218 100644 --- a/content/renderer/media/peer_connection_tracker.cc +++ b/content/renderer/media/peer_connection_tracker.cc
@@ -22,6 +22,8 @@ using std::string; using webrtc::MediaConstraintsInterface; +using webrtc::StatsReport; +using webrtc::StatsReports; using blink::WebRTCPeerConnectionHandlerClient; namespace content { @@ -204,8 +206,7 @@ // Note: // The format must be consistent with what webrtc_internals.js expects. // If you change it here, you must change webrtc_internals.js as well. -static base::DictionaryValue* GetDictValueStats( - const webrtc::StatsReport& report) { +static base::DictionaryValue* GetDictValueStats(const StatsReport& report) { if (report.values().empty()) return NULL; @@ -216,8 +217,30 @@ dict->Set("values", values); for (const auto& v : report.values()) { - values->AppendString(v.second->display_name()); - values->AppendString(v.second->ToString()); + const StatsReport::ValuePtr& value = v.second; + values->AppendString(value->display_name()); + switch (value->type()) { + case StatsReport::Value::kInt: + values->AppendInteger(value->int_val()); + break; + case StatsReport::Value::kFloat: + values->AppendDouble(value->float_val()); + break; + case StatsReport::Value::kString: + values->AppendString(value->string_val()); + break; + case StatsReport::Value::kStaticString: + values->AppendString(value->static_string_val()); + break; + case StatsReport::Value::kBool: + values->AppendBoolean(value->bool_val()); + break; + case StatsReport::Value::kInt64: // int64 isn't supported, so use string. + case StatsReport::Value::kId: + default: + values->AppendString(value->ToString()); + break; + } } return dict; @@ -225,7 +248,7 @@ // Builds a DictionaryValue from the StatsReport. // The caller takes the ownership of the returned value. -static base::DictionaryValue* GetDictValue(const webrtc::StatsReport& report) { +static base::DictionaryValue* GetDictValue(const StatsReport& report) { scoped_ptr<base::DictionaryValue> stats, result; stats.reset(GetDictValueStats(report)); @@ -248,7 +271,7 @@ InternalStatsObserver(int lid) : lid_(lid), main_thread_(base::ThreadTaskRunnerHandle::Get()) {} - void OnComplete(const webrtc::StatsReports& reports) override { + void OnComplete(const StatsReports& reports) override { scoped_ptr<base::ListValue> list(new base::ListValue()); for (const auto* r : reports) {
diff --git a/content/renderer/media/rtc_peer_connection_handler.cc b/content/renderer/media/rtc_peer_connection_handler.cc index 57a7de3..20288bb 100644 --- a/content/renderer/media/rtc_peer_connection_handler.cc +++ b/content/renderer/media/rtc_peer_connection_handler.cc
@@ -406,10 +406,19 @@ int idx = response->addReport(blink::WebString::fromUTF8(report.id), blink::WebString::fromUTF8(report.type), report.timestamp); + blink::WebString name, value_str; for (const auto& value : report.values) { - response->addStatistic(idx, - blink::WebString::fromUTF8(value.second->display_name()), - blink::WebString::fromUTF8(value.second->ToString())); + const StatsReport::ValuePtr& v = value.second; + name = blink::WebString::fromUTF8(value.second->display_name()); + + if (v->type() == StatsReport::Value::kString) + value_str = blink::WebString::fromUTF8(v->string_val()); + if (v->type() == StatsReport::Value::kStaticString) + value_str = blink::WebString::fromUTF8(v->static_string_val()); + else + value_str = blink::WebString::fromUTF8(v->ToString()); + + response->addStatistic(idx, name, value_str); } }
diff --git a/content/renderer/npapi/webplugin_delegate_proxy.cc b/content/renderer/npapi/webplugin_delegate_proxy.cc index 66bc3627..8e83b86 100644 --- a/content/renderer/npapi/webplugin_delegate_proxy.cc +++ b/content/renderer/npapi/webplugin_delegate_proxy.cc
@@ -311,13 +311,13 @@ if (!info_.path.empty()) { render_view_->GetMainRenderFrame()->PluginCrashed( info_.path, base::kNullProcessId); - LOG(ERROR) << "Plug-in crashed on start"; + LOG(ERROR) << "Plugin crashed on start"; // Return true so that the plugin widget is created and we can paint the // crashed plugin there. return true; } - LOG(ERROR) << "Plug-in couldn't be found"; + LOG(ERROR) << "Plugin couldn't be found"; return false; } @@ -801,7 +801,7 @@ const std::vector<int>& target, int cursor_position, int plugin_id) { - // Dispatch the raw IME data if this plug-in is the focused one. + // Dispatch the raw IME data if this plugin is the focused one. if (instance_id_ != plugin_id) return; @@ -813,7 +813,7 @@ void WebPluginDelegateProxy::ImeCompositionCompleted(const base::string16& text, int plugin_id) { - // Dispatch the IME text if this plug-in is the focused one. + // Dispatch the IME text if this plugin is the focused one. if (instance_id_ != plugin_id) return;
diff --git a/content/renderer/npapi/webplugin_impl.cc b/content/renderer/npapi/webplugin_impl.cc index bb92c76..9a447fe 100644 --- a/content/renderer/npapi/webplugin_impl.cc +++ b/content/renderer/npapi/webplugin_impl.cc
@@ -917,7 +917,7 @@ // Currently this check is just to catch an https -> http redirect when // loading the main plugin src URL. Longer term, we could investigate // firing mixed diplay or scripting issues for subresource loads - // initiated by plug-ins. + // initiated by plugins. if (client_info->is_plugin_src_load && webframe_ && !webframe_->checkIfRunInsecureContent(request.url())) {
diff --git a/content/renderer/pepper/plugin_instance_throttler_impl.cc b/content/renderer/pepper/plugin_instance_throttler_impl.cc index 1ff6248f..097480de 100644 --- a/content/renderer/pepper/plugin_instance_throttler_impl.cc +++ b/content/renderer/pepper/plugin_instance_throttler_impl.cc
@@ -157,7 +157,7 @@ bool PluginInstanceThrottlerImpl::ConsumeInputEvent( const blink::WebInputEvent& event) { - // Always allow right-clicks through so users may verify it's a plug-in. + // Always allow right-clicks through so users may verify it's a plugin. // TODO(tommycli): We should instead show a custom context menu (probably // using PluginPlaceholder) so users aren't confused and try to click the // Flash-internal 'Play' menu item. This is a stopgap solution.
diff --git a/content/renderer/pepper/plugin_power_saver_helper.cc b/content/renderer/pepper/plugin_power_saver_helper.cc index 9eec693f..2891980 100644 --- a/content/renderer/pepper/plugin_power_saver_helper.cc +++ b/content/renderer/pepper/plugin_power_saver_helper.cc
@@ -32,13 +32,13 @@ const char kPeripheralHeuristicHistogram[] = "Plugin.PowerSaver.PeripheralHeuristic"; -// Maximum dimensions plug-in content may have while still being considered +// Maximum dimensions plugin content may have while still being considered // peripheral content. These match the sizes used by Safari. const int kPeripheralContentMaxWidth = 400; const int kPeripheralContentMaxHeight = 300; -// Plug-in content below this size in height and width is considered "tiny". -// Tiny content is never peripheral, as tiny plug-ins often serve a critical +// Plugin content below this size in height and width is considered "tiny". +// Tiny content is never peripheral, as tiny plugins often serve a critical // purpose, and the user often cannot find and click to unthrottle it. const int kPeripheralContentTinySize = 5;
diff --git a/content/renderer/pepper/ppb_broker_impl.h b/content/renderer/pepper/ppb_broker_impl.h index 0f748553..b43d3a6 100644 --- a/content/renderer/pepper/ppb_broker_impl.h +++ b/content/renderer/pepper/ppb_broker_impl.h
@@ -40,7 +40,7 @@ scoped_refptr<ppapi::TrackedCallback> connect_callback) override; int32_t GetHandle(int32_t* handle) override; - // Returns the URL of the document this plug-in runs in. This is necessary to + // Returns the URL of the document this plugin runs in. This is necessary to // decide whether to grant access to the PPAPI broker. GURL GetDocumentUrl();
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 437e8c98..7e92305 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -952,6 +952,11 @@ #endif bool RenderFrameImpl::OnMessageReceived(const IPC::Message& msg) { + // We may get here while detaching, when the WebFrame has been deleted. Do + // not process any messages in this state. + if (!frame_) + return false; + // TODO(kenrb): document() should not be null, but as a transitional step // we have RenderFrameProxy 'wrapping' a RenderFrameImpl, passing messages // to this method. This happens for a top-level remote frame, where a @@ -2104,8 +2109,11 @@ if (is_subframe) frame->parent()->removeChild(frame); - // |frame| is invalid after here. + // |frame| is invalid after here. Be sure to clear frame_ as well, since this + // object may not be deleted immediately and other methods may try to access + // it. frame->close(); + frame_ = nullptr; if (is_subframe) { delete this;
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 4863460..6a3daa7 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -738,7 +738,10 @@ RendererCdmManager* GetCdmManager(); #endif - // Stores the WebLocalFrame we are associated with. + // Stores the WebLocalFrame we are associated with. This is null from the + // constructor until SetWebFrame is called, and it is null after + // frameDetached is called until destruction (which is asynchronous in the + // case of the main frame, but not subframes). blink::WebLocalFrame* frame_; base::WeakPtr<RenderViewImpl> render_view_;
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 41137e5..a3068614 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -656,8 +656,12 @@ #endif } - base::DiscardableMemoryShmemAllocator::SetInstance( - ChildThreadImpl::discardable_shared_memory_manager()); + // In single process, browser main loop set up the discardable memory + // allocator. + if (!command_line.HasSwitch(switches::kSingleProcess)) { + base::DiscardableMemoryShmemAllocator::SetInstance( + ChildThreadImpl::discardable_shared_memory_manager()); + } service_registry()->AddService<RenderFrameSetup>( base::Bind(CreateRenderFrameSetup)); @@ -772,10 +776,10 @@ bool RenderThreadImpl::Send(IPC::Message* msg) { // Certain synchronous messages cannot always be processed synchronously by // the browser, e.g., putting up UI and waiting for the user. This could cause - // a complete hang of Chrome if a windowed plug-in is trying to communicate + // a complete hang of Chrome if a windowed plugin is trying to communicate // with the renderer thread since the browser's UI thread could be stuck // (within a Windows API call) trying to synchronously communicate with the - // plug-in. The remedy is to pump messages on this thread while the browser + // plugin. The remedy is to pump messages on this thread while the browser // is processing this request. This creates an opportunity for re-entrancy // into WebKit, so we need to take care to disable callbacks, timers, and // pending network loads that could trigger such callbacks. @@ -874,9 +878,10 @@ scoped_refptr<PendingRenderFrameConnect> connection(it->second); mojo::InterfaceRequest<mojo::ServiceProvider> services( - connection->services.Pass()); + connection->services().Pass()); mojo::ServiceProviderPtr exposed_services( - connection->exposed_services.Pass()); + connection->exposed_services().Pass()); + exposed_services.set_error_handler(nullptr); pending_render_frame_connects_.erase(it); frame->BindServiceRegistry(services.Pass(), exposed_services.Pass()); @@ -911,8 +916,7 @@ pending_render_frame_connects_.insert(std::make_pair( routing_id, make_scoped_refptr(new PendingRenderFrameConnect( - services.Pass(), - exposed_services.Pass())))); + routing_id, services.Pass(), exposed_services.Pass())))); CHECK(result.second) << "Inserting a duplicate item."; } @@ -1790,13 +1794,26 @@ } RenderThreadImpl::PendingRenderFrameConnect::PendingRenderFrameConnect( + int routing_id, mojo::InterfaceRequest<mojo::ServiceProvider> services, mojo::ServiceProviderPtr exposed_services) - : services(services.Pass()), - exposed_services(exposed_services.Pass()) { + : routing_id_(routing_id), + services_(services.Pass()), + exposed_services_(exposed_services.Pass()) { + // The RenderFrame may be deleted before the ExchangeServiceProviders message + // is received. In that case, the RenderFrameHost should close the connection, + // which is detected by setting an error handler on |exposed_services_|. + exposed_services_.set_error_handler(this); } RenderThreadImpl::PendingRenderFrameConnect::~PendingRenderFrameConnect() { } +void RenderThreadImpl::PendingRenderFrameConnect::OnConnectionError() { + size_t erased = + RenderThreadImpl::current()->pending_render_frame_connects_.erase( + routing_id_); + DCHECK_EQ(1u, erased); +} + } // namespace content
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 26de62b..6ec87b5 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -606,19 +606,31 @@ bool is_elastic_overscroll_enabled_; unsigned use_image_texture_target_; - struct PendingRenderFrameConnect - : public base::RefCounted<PendingRenderFrameConnect> { + class PendingRenderFrameConnect + : public base::RefCounted<PendingRenderFrameConnect>, + public mojo::ErrorHandler { + public: PendingRenderFrameConnect( + int routing_id, mojo::InterfaceRequest<mojo::ServiceProvider> services, mojo::ServiceProviderPtr exposed_services); - mojo::InterfaceRequest<mojo::ServiceProvider> services; - mojo::ServiceProviderPtr exposed_services; + mojo::InterfaceRequest<mojo::ServiceProvider>& services() { + return services_; + } + + mojo::ServiceProviderPtr& exposed_services() { return exposed_services_; } private: friend class base::RefCounted<PendingRenderFrameConnect>; - ~PendingRenderFrameConnect(); + ~PendingRenderFrameConnect() override; + + void OnConnectionError() override; + + int routing_id_; + mojo::InterfaceRequest<mojo::ServiceProvider> services_; + mojo::ServiceProviderPtr exposed_services_; }; typedef std::map<int, scoped_refptr<PendingRenderFrameConnect>>
diff --git a/content/renderer/render_view_browsertest.cc b/content/renderer/render_view_browsertest.cc index 713c976..1f1b990 100644 --- a/content/renderer/render_view_browsertest.cc +++ b/content/renderer/render_view_browsertest.cc
@@ -286,6 +286,31 @@ scoped_ptr<MockKeyboard> mock_keyboard_; }; +// Test for https://crbug.com/461191. +TEST_F(RenderViewImplTest, RenderFrameMessageAfterDetach) { + // Create a new main frame RenderFrame so that we don't interfere with the + // shutdown of frame() in RenderViewTest.TearDown. + blink::WebURLRequest popup_request(GURL("http://foo.com")); + blink::WebView* new_web_view = view()->createView( + GetMainFrame(), popup_request, blink::WebWindowFeatures(), "foo", + blink::WebNavigationPolicyNewForegroundTab, false); + RenderViewImpl* new_view = RenderViewImpl::FromWebView(new_web_view); + RenderFrameImpl* new_frame = + static_cast<RenderFrameImpl*>(new_view->GetMainRenderFrame()); + + // Detach the main frame. + new_view->Close(); + + // Before the frame is asynchronously deleted, it may receive a message. + // We should not crash here, and the message should not be processed. + scoped_ptr<const IPC::Message> msg( + new FrameMsg_Stop(frame()->GetRoutingID())); + EXPECT_FALSE(new_frame->OnMessageReceived(*msg)); + + // Clean up after the new view so we don't leak it. + new_view->Release(); +} + TEST_F(RenderViewImplTest, SaveImageFromDataURL) { const IPC::Message* msg1 = render_thread_->sink().GetFirstMessageMatching( ViewHostMsg_SaveImageFromDataURL::ID); @@ -2209,7 +2234,7 @@ params.viewSize.width = 327; params.viewSize.height = 415; - view()->EnableScreenMetricsEmulation(params); + view()->OnEnableDeviceEmulation(params); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_width, &width)); EXPECT_EQ(params.viewSize.width, width); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_height, &height)); @@ -2217,15 +2242,15 @@ params.viewSize.width = 1005; params.viewSize.height = 1102; - view()->EnableScreenMetricsEmulation(params); + view()->OnEnableDeviceEmulation(params); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_width, &width)); EXPECT_EQ(params.viewSize.width, width); EXPECT_TRUE(ExecuteJavaScriptAndReturnIntValue(get_height, &height)); EXPECT_EQ(params.viewSize.height, height); - view()->DisableScreenMetricsEmulation(); + view()->OnDisableDeviceEmulation(); - view()->EnableScreenMetricsEmulation(params); + view()->OnEnableDeviceEmulation(params); // Don't disable here to test that emulation is being shutdown properly. }
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 0a8ce9b..3fcbc28 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -3448,8 +3448,8 @@ } #if defined(OS_WIN) - // When a plug-in has focus, we create platform-specific IME data used by - // our IME emulator and send it directly to the focused plug-in, i.e. we + // When a plugin has focus, we create platform-specific IME data used by + // our IME emulator and send it directly to the focused plugin, i.e. we // bypass WebKit. (WebPluginDelegate dispatches this IME data only when its // instance ID is the same one as the specified ID.) if (focused_plugin_id_ >= 0) { @@ -3491,7 +3491,7 @@ } #if defined(OS_WIN) // Same as OnImeSetComposition(), we send the text from IMEs directly to - // plug-ins. When we send IME text directly to plug-ins, we should not send + // plugins. When we send IME text directly to plugins, we should not send // it to WebKit to prevent WebKit from controlling IMEs. // TODO(thakis): Honor |replacement_range| for plugins? if (focused_plugin_id_ >= 0) { @@ -3633,14 +3633,13 @@ } void RenderViewImpl::SetScreenMetricsEmulationParameters( - float device_scale_factor, - const gfx::Point& root_layer_offset, - float root_layer_scale) { + bool enabled, + const blink::WebDeviceEmulationParams& params) { if (webview() && compositor()) { - webview()->setCompositorDeviceScaleFactorOverride(device_scale_factor); - webview()->setRootLayerTransform( - blink::WebSize(root_layer_offset.x(), root_layer_offset.y()), - root_layer_scale); + if (enabled) + webview()->enableDeviceEmulation(params); + else + webview()->disableDeviceEmulation(); } }
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 8496410..d844217 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -282,7 +282,7 @@ // Returns true if the focused element is editable text from the perspective // of IME support (also used for on-screen keyboard). Works correctly inside - // supported PPAPI plug-ins. + // supported PPAPI plugins. bool HasIMETextFocus(); // Callback for use with GetWindowSnapshot. @@ -509,9 +509,9 @@ void Initialize(const ViewMsg_New_Params& params, CompositorDependencies* compositor_deps, bool was_created_by_renderer); - void SetScreenMetricsEmulationParameters(float device_scale_factor, - const gfx::Point& root_layer_offset, - float root_layer_scale) override; + void SetScreenMetricsEmulationParameters( + bool enabled, + const blink::WebDeviceEmulationParams& params) override; // Do not delete directly. This class is reference counted. virtual ~RenderViewImpl(); @@ -528,6 +528,7 @@ // code away from this class. friend class RenderFrameImpl; + FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, RenderFrameMessageAfterDetach); FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, DecideNavigationPolicyForWebUI); FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, DidFailProvisionalLoadWithErrorForError); @@ -551,6 +552,7 @@ FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, GetCompositionCharacterBoundsTest); FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, OnNavigationHttpPost); + FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, ScreenMetricsEmulation); FRIEND_TEST_ALL_PREFIXES(RenderViewImplTest, DecideNavigationPolicyHandlesAllTopLevel); #if defined(OS_MACOSX) @@ -968,7 +970,7 @@ std::set<WebPluginDelegateProxy*> plugin_delegates_; #if defined(OS_WIN) - // The ID of the focused NPAPI plug-in. + // The ID of the focused NPAPI plugin. int focused_plugin_id_; #endif
diff --git a/content/renderer/render_widget.cc b/content/renderer/render_widget.cc index 8c5c6d6..e3c2602 100644 --- a/content/renderer/render_widget.cc +++ b/content/renderer/render_widget.cc
@@ -248,7 +248,7 @@ // Scale and offset used to convert between host coordinates // and webwidget coordinates. float scale() { return scale_; } - gfx::Point offset() { return offset_; } + gfx::PointF offset() { return offset_; } gfx::Rect applied_widget_rect() const { return applied_widget_rect_; } gfx::Rect original_screen_rect() const { return original_view_screen_rect_; } const WebScreenInfo& original_screen_info() { return original_screen_info_; } @@ -278,7 +278,7 @@ // The computed scale and offset used to fit widget into browser window. float scale_; - gfx::Point offset_; + gfx::PointF offset_; // Widget rect as passed to webwidget. gfx::Rect applied_widget_rect_; @@ -314,7 +314,7 @@ widget_->screen_info_ = original_screen_info_; widget_->SetDeviceScaleFactor(original_screen_info_.deviceScaleFactor); - widget_->SetScreenMetricsEmulationParameters(0.f, gfx::Point(), 1.f); + widget_->SetScreenMetricsEmulationParameters(false, params_); widget_->view_screen_rect_ = original_view_screen_rect_; widget_->window_screen_rect_ = original_window_screen_rect_; widget_->Resize(original_size_, @@ -392,8 +392,11 @@ // even when emulating different scale factor; // - in order to fit into view, WebView applies offset and scale to the // root layer. - widget_->SetScreenMetricsEmulationParameters( - original_screen_info_.deviceScaleFactor, offset_, scale_); + blink::WebDeviceEmulationParams modified_params = params_; + modified_params.deviceScaleFactor = original_screen_info_.deviceScaleFactor; + modified_params.offset = blink::WebFloatPoint(offset_.x(), offset_.y()); + modified_params.scale = scale_; + widget_->SetScreenMetricsEmulationParameters(true, modified_params); widget_->SetDeviceScaleFactor(applied_device_scale_factor); widget_->view_screen_rect_ = applied_widget_rect_; @@ -656,18 +659,6 @@ RenderProcess::current()->ReleaseProcess(); } -void RenderWidget::EnableScreenMetricsEmulation( - const WebDeviceEmulationParams& params) { - if (!screen_metrics_emulator_) - screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params)); - else - screen_metrics_emulator_->ChangeEmulationParams(params); -} - -void RenderWidget::DisableScreenMetricsEmulation() { - screen_metrics_emulator_.reset(); -} - void RenderWidget::SetPopupOriginAdjustmentsForEmulation( ScreenMetricsEmulator* emulator) { popup_origin_scale_for_emulation_ = emulator->scale(); @@ -686,9 +677,8 @@ } void RenderWidget::SetScreenMetricsEmulationParameters( - float device_scale_factor, - const gfx::Point& root_layer_offset, - float root_layer_scale) { + bool enabled, + const blink::WebDeviceEmulationParams& params) { // This is only supported in RenderView. NOTREACHED(); } @@ -732,6 +722,10 @@ IPC_MESSAGE_HANDLER(ViewMsg_Close, OnClose) IPC_MESSAGE_HANDLER(ViewMsg_CreatingNew_ACK, OnCreatingNewAck) IPC_MESSAGE_HANDLER(ViewMsg_Resize, OnResize) + IPC_MESSAGE_HANDLER(ViewMsg_EnableDeviceEmulation, + OnEnableDeviceEmulation) + IPC_MESSAGE_HANDLER(ViewMsg_DisableDeviceEmulation, + OnDisableDeviceEmulation) IPC_MESSAGE_HANDLER(ViewMsg_ColorProfile, OnColorProfile) IPC_MESSAGE_HANDLER(ViewMsg_ChangeResizeRect, OnChangeResizeRect) IPC_MESSAGE_HANDLER(ViewMsg_WasHidden, OnWasHidden) @@ -915,6 +909,18 @@ OnOrientationChange(); } +void RenderWidget::OnEnableDeviceEmulation( + const blink::WebDeviceEmulationParams& params) { + if (!screen_metrics_emulator_) + screen_metrics_emulator_.reset(new ScreenMetricsEmulator(this, params)); + else + screen_metrics_emulator_->ChangeEmulationParams(params); +} + +void RenderWidget::OnDisableDeviceEmulation() { + screen_metrics_emulator_.reset(); +} + void RenderWidget::OnColorProfile(const std::vector<char>& color_profile) { SetDeviceColorProfile(color_profile); }
diff --git a/content/renderer/render_widget.h b/content/renderer/render_widget.h index 50392c9..593675c 100644 --- a/content/renderer/render_widget.h +++ b/content/renderer/render_widget.h
@@ -274,11 +274,6 @@ // widget if required to fit into the browser window. class ScreenMetricsEmulator; - // Emulates screen and widget metrics. Supplied values override everything - // coming from host. - void EnableScreenMetricsEmulation( - const blink::WebDeviceEmulationParams& params); - void DisableScreenMetricsEmulation(); void SetPopupOriginAdjustmentsForEmulation(ScreenMetricsEmulator* emulator); gfx::Rect AdjustValidationMessageAnchor(const gfx::Rect& anchor); @@ -398,9 +393,8 @@ // Used to force the size of a window when running layout tests. void SetWindowRectSynchronously(const gfx::Rect& new_window_rect); virtual void SetScreenMetricsEmulationParameters( - float device_scale_factor, - const gfx::Point& root_layer_offset, - float root_layer_scale); + bool enabled, + const blink::WebDeviceEmulationParams& params); #if defined(OS_MACOSX) || defined(OS_ANDROID) void SetExternalPopupOriginAdjustmentsForEmulation( ExternalPopupMenu* popup, ScreenMetricsEmulator* emulator); @@ -416,6 +410,8 @@ virtual void OnClose(); void OnCreatingNewAck(); virtual void OnResize(const ViewMsg_Resize_Params& params); + void OnEnableDeviceEmulation(const blink::WebDeviceEmulationParams& params); + void OnDisableDeviceEmulation(); void OnColorProfile(const std::vector<char>& color_profile); void OnChangeResizeRect(const gfx::Rect& resizer_rect); virtual void OnWasHidden(); @@ -784,8 +780,8 @@ // Popups may be displaced when screen metrics emulation is enabled. // These values are used to properly adjust popup position. - gfx::Point popup_view_origin_for_emulation_; - gfx::Point popup_screen_origin_for_emulation_; + gfx::PointF popup_view_origin_for_emulation_; + gfx::PointF popup_screen_origin_for_emulation_; float popup_origin_scale_for_emulation_; scoped_refptr<FrameSwapMessageQueue> frame_swap_message_queue_;
diff --git a/content/shell/browser/shell_net_log.cc b/content/shell/browser/shell_net_log.cc index c006c2f..698b4b7 100644 --- a/content/shell/browser/shell_net_log.cc +++ b/content/shell/browser/shell_net_log.cc
@@ -8,16 +8,18 @@ #include "base/command_line.h" #include "base/files/file_path.h" +#include "base/files/scoped_file.h" #include "base/values.h" #include "content/public/common/content_switches.h" #include "net/base/net_log_logger.h" +#include "net/base/net_log_util.h" namespace content { namespace { base::DictionaryValue* GetShellConstants(const std::string& app_name) { - base::DictionaryValue* constants_dict = net::NetLogLogger::GetConstants(); + scoped_ptr<base::DictionaryValue> constants_dict = net::GetNetConstants(); // Add a dictionary with client information base::DictionaryValue* dict = new base::DictionaryValue(); @@ -29,12 +31,14 @@ constants_dict->Set("clientInfo", dict); - return constants_dict; + return constants_dict.release(); } } // namespace ShellNetLog::ShellNetLog(const std::string& app_name) { + // TODO(mmenke): Other than a different set of constants, this code is + // identical to code in ChromeNetLog. Consider merging the code. const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); @@ -47,20 +51,21 @@ // would result in an unbounded buffer size, so not much can be gained by // doing this on another thread. It's only used when debugging, so // performance is not a big concern. - FILE* file = NULL; + base::ScopedFILE file; #if defined(OS_WIN) - file = _wfopen(log_path.value().c_str(), L"w"); + file.reset(_wfopen(log_path.value().c_str(), L"w")); #elif defined(OS_POSIX) - file = fopen(log_path.value().c_str(), "w"); + file.reset(fopen(log_path.value().c_str(), "w")); #endif - if (file == NULL) { + if (!file) { LOG(ERROR) << "Could not open file " << log_path.value() << " for net logging"; } else { scoped_ptr<base::Value> constants(GetShellConstants(app_name)); - net_log_logger_.reset(new net::NetLogLogger(file, *constants)); - net_log_logger_->StartObserving(this); + net_log_logger_.reset(new net::NetLogLogger()); + net_log_logger_->StartObserving(this, file.Pass(), constants.get(), + nullptr); } } } @@ -68,7 +73,7 @@ ShellNetLog::~ShellNetLog() { // Remove the observer we own before we're destroyed. if (net_log_logger_) - RemoveThreadSafeObserver(net_log_logger_.get()); + net_log_logger_->StopObserving(nullptr); } } // namespace content
diff --git a/content/shell/renderer/test_runner/test_plugin.h b/content/shell/renderer/test_runner/test_plugin.h index b62ddc4c..f55b693 100644 --- a/content/shell/renderer/test_runner/test_plugin.h +++ b/content/shell/renderer/test_runner/test_plugin.h
@@ -69,7 +69,7 @@ const blink::WebRect& clip_rect, const blink::WebVector<blink::WebRect>& cut_outs_rects, bool is_visible); - virtual void updateFocus(bool focus) {} + virtual void updateFocus(bool focus, blink::WebFocusType focus_type) {} virtual void updateVisibility(bool visibility) {} virtual bool acceptsInputEvents(); virtual bool handleInputEvent(const blink::WebInputEvent& event,
diff --git a/content/shell/tools/plugin/PluginObject.cpp b/content/shell/tools/plugin/PluginObject.cpp index b071c09..a3c723f 100644 --- a/content/shell/tools/plugin/PluginObject.cpp +++ b/content/shell/tools/plugin/PluginObject.cpp
@@ -437,7 +437,7 @@ const NPVariant*, uint32_t, NPVariant* result) { - // Get plug-in's DOM element + // Get plugin's DOM element NPObject* elementObject; if (browser->getvalue(obj->npp, NPNVPluginElementNPObject, &elementObject) == NPERR_NO_ERROR) {
diff --git a/content/shell/tools/plugin/PluginObjectMac.mm b/content/shell/tools/plugin/PluginObjectMac.mm index e95e541a..d69908b 100644 --- a/content/shell/tools/plugin/PluginObjectMac.mm +++ b/content/shell/tools/plugin/PluginObjectMac.mm
@@ -40,7 +40,7 @@ - (void)drawInContext:(CGContextRef)context { CGRect bounds = [self bounds]; - const char* text = "Test Plug-in"; + const char* text = "Test Plugin"; CGContextSelectFont(context, "Helvetica", 24, kCGEncodingMacRoman); CGContextShowTextAtPoint(context, bounds.origin.x + 3.0f,
diff --git a/content/shell/tools/plugin/PluginTest.cpp b/content/shell/tools/plugin/PluginTest.cpp index ddaab7e..d0a56c71 100644 --- a/content/shell/tools/plugin/PluginTest.cpp +++ b/content/shell/tools/plugin/PluginTest.cpp
@@ -72,7 +72,7 @@ void PluginTest::indicateTestFailure() { // This should really be an assert, but there's no way for the test framework -// to know that the plug-in process crashed, so we'll just sleep for a while +// to know that the plugin process crashed, so we'll just sleep for a while // to ensure that the test times out. #if defined(XP_WIN) ::Sleep(100000); @@ -124,7 +124,7 @@ } NPError PluginTest::NPP_GetValue(NPPVariable variable, void* value) { - // We don't know anything about plug-in values so just return + // We don't know anything about plugin values so just return // NPERR_GENERIC_ERROR. return NPERR_GENERIC_ERROR; }
diff --git a/content/shell/tools/plugin/PluginTest.h b/content/shell/tools/plugin/PluginTest.h index 0929ba9..82093ae3 100644 --- a/content/shell/tools/plugin/PluginTest.h +++ b/content/shell/tools/plugin/PluginTest.h
@@ -158,7 +158,7 @@ protected: PluginTest(NPP npp, const std::string& identifier); - // FIXME: A plug-in test shouldn't need to know about it's NPP. Make this + // FIXME: A plugin test shouldn't need to know about it's NPP. Make this // private. NPP m_npp;
diff --git a/content/shell/tools/plugin/Tests/GetURLNotifyWithURLThatFailsToLoad.cpp b/content/shell/tools/plugin/Tests/GetURLNotifyWithURLThatFailsToLoad.cpp index e9131a7..cfbc2cd 100644 --- a/content/shell/tools/plugin/Tests/GetURLNotifyWithURLThatFailsToLoad.cpp +++ b/content/shell/tools/plugin/Tests/GetURLNotifyWithURLThatFailsToLoad.cpp
@@ -34,7 +34,7 @@ using namespace std; // From NPP_New, call NPN_GetURLNotify with a URL that fails to load (NPP_NewStream won't be called). -// The plug-in should still get a NPP_URLNotify indicating that the load failed. +// The plugin should still get a NPP_URLNotify indicating that the load failed. static const char *urlThatFailsToLoad = "foo://bar/"; class GetURLNotifyWithURLThatFailsToLoad : public PluginTest {
diff --git a/content/shell/tools/plugin/Tests/GetURLWithJavaScriptURLDestroyingPlugin.cpp b/content/shell/tools/plugin/Tests/GetURLWithJavaScriptURLDestroyingPlugin.cpp index 37ad4a5..4e7470f 100644 --- a/content/shell/tools/plugin/Tests/GetURLWithJavaScriptURLDestroyingPlugin.cpp +++ b/content/shell/tools/plugin/Tests/GetURLWithJavaScriptURLDestroyingPlugin.cpp
@@ -31,7 +31,7 @@ using namespace std; -// From NPP_New, call NPN_GetURL to evaluate JavaScript that destroys the plug-in. +// From NPP_New, call NPN_GetURL to evaluate JavaScript that destroys the plugin. class GetURLWithJavaScriptURLDestroyingPlugin : public PluginTest { public:
diff --git a/content/shell/tools/plugin/Tests/PluginScriptableNPObjectInvokeDefault.cpp b/content/shell/tools/plugin/Tests/PluginScriptableNPObjectInvokeDefault.cpp index 8f42d6c..488c859 100644 --- a/content/shell/tools/plugin/Tests/PluginScriptableNPObjectInvokeDefault.cpp +++ b/content/shell/tools/plugin/Tests/PluginScriptableNPObjectInvokeDefault.cpp
@@ -31,7 +31,7 @@ using namespace std; -// A test where the plug-ins scriptable object either has or doesn't have an invokeDefault function. +// A test where the plugins scriptable object either has or doesn't have an invokeDefault function. class PluginScriptableNPObjectInvokeDefault : public PluginTest { public: PluginScriptableNPObjectInvokeDefault(NPP npp, const string& identifier)
diff --git a/content/shell/tools/plugin/main.cpp b/content/shell/tools/plugin/main.cpp index 0b1e55f..fb682b3 100644 --- a/content/shell/tools/plugin/main.cpp +++ b/content/shell/tools/plugin/main.cpp
@@ -840,7 +840,7 @@ return NPERR_NO_ERROR; } if (variable == NPPVpluginDescriptionString) { - *((char **)value) = const_cast<char*>("Simple Netscape® plug-in that handles test content for WebKit"); + *((char **)value) = const_cast<char*>("Simple Netscape® plugin that handles test content for WebKit"); return NPERR_NO_ERROR; } if (variable == NPPVpluginNeedsXEmbed) {
diff --git a/content/test/blink_test_environment.cc b/content/test/blink_test_environment.cc index 816983c7..16b35a6 100644 --- a/content/test/blink_test_environment.cc +++ b/content/test/blink_test_environment.cc
@@ -10,6 +10,7 @@ #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/strings/string_tokenizer.h" +#include "base/test/test_discardable_memory_shmem_allocator.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "content/public/common/content_switches.h" #include "content/public/common/user_agent.h" @@ -67,6 +68,9 @@ // TestBlinkWebUnitTestSupport must be instantiated after MessageLoopType. blink_test_support_.reset(new TestBlinkWebUnitTestSupport); content_initializer_.reset(new content::TestContentClientInitializer()); + + base::DiscardableMemoryShmemAllocator::SetInstance( + &discardable_memory_allocator_); } ~TestEnvironment() { @@ -80,6 +84,7 @@ scoped_ptr<MessageLoopType> main_message_loop_; scoped_ptr<TestBlinkWebUnitTestSupport> blink_test_support_; scoped_ptr<TestContentClientInitializer> content_initializer_; + base::TestDiscardableMemoryShmemAllocator discardable_memory_allocator_; }; TestEnvironment* test_environment;
diff --git a/content/test/plugin/npapi_test.cc b/content/test/plugin/npapi_test.cc index 975de43..02e9093 100644 --- a/content/test/plugin/npapi_test.cc +++ b/content/test/plugin/npapi_test.cc
@@ -94,7 +94,7 @@ break; case NPPVpluginDescriptionString: *(static_cast<const char**>(value)) = - "Simple NPAPI plug-in for Chromium unit tests"; + "Simple NPAPI plugin for Chromium unit tests"; break; case NPPVpluginNeedsXEmbed: *(static_cast<NPBool*>(value)) = true;
diff --git a/content/test/plugin/plugin_client.h b/content/test/plugin/plugin_client.h index 07d9a70..3b5ef3e1 100644 --- a/content/test/plugin/plugin_client.h +++ b/content/test/plugin/plugin_client.h
@@ -20,17 +20,17 @@ // NPAPI Host to call. static NPError GetEntryPoints(NPPluginFuncs* pFuncs); - // The browser calls this function only once: when a plug-in is loaded, + // The browser calls this function only once: when a plugin is loaded, // before the first instance is created. This is the first function that - // the browser calls. NP_Initialize tells the plug-in that the browser has + // the browser calls. NP_Initialize tells the plugin that the browser has // loaded it and provides global initialization. Allocate any memory or - // resources shared by all instances of your plug-in at this time. + // resources shared by all instances of your plugin at this time. static NPError Initialize(NPNetscapeFuncs* pFuncs); // The browser calls this function once after the last instance of your - // plug-in is destroyed, before unloading the plug-in library itself. Use + // plugin is destroyed, before unloading the plugin library itself. Use // NP_Shutdown to delete any data allocated in NP_Initialize to be shared - // by all instances of a plug-in. + // by all instances of a plugin. static NPError Shutdown(); // The table of functions provided by the host.
diff --git a/content/test/plugin/plugin_setup_test.h b/content/test/plugin/plugin_setup_test.h index 98452a9..1708ce1 100644 --- a/content/test/plugin/plugin_setup_test.h +++ b/content/test/plugin/plugin_setup_test.h
@@ -9,7 +9,7 @@ namespace NPAPIClient { -// A very simple test that just sets up a new plug-in. +// A very simple test that just sets up a new plugin. class PluginSetupTest : public PluginTest { public: // Constructor.
diff --git a/content/test/plugin/plugin_thread_async_call_test.cc b/content/test/plugin/plugin_thread_async_call_test.cc index 096041c..4afd0042 100644 --- a/content/test/plugin/plugin_thread_async_call_test.cc +++ b/content/test/plugin/plugin_thread_async_call_test.cc
@@ -67,7 +67,7 @@ // a different thread to fully test it. if (this == g_short_lived_instance) { // This is slightly complicated thanks to the Linux shared library build, - // which shares more compilation units between the NPAPI plug-in and + // which shares more compilation units between the NPAPI plugin and // the base code. at_exit_manager_ = new base::ShadowingAtExitManager(); base::Thread random_thread("random_thread");
diff --git a/content/utility/utility_thread_impl.cc b/content/utility/utility_thread_impl.cc index 7551818..a22005e8 100644 --- a/content/utility/utility_thread_impl.cc +++ b/content/utility/utility_thread_impl.cc
@@ -119,8 +119,8 @@ PluginList* plugin_list = PluginList::Singleton(); std::vector<WebPluginInfo> plugins; - // TODO(bauerb): If we restart loading plug-ins, we might mess up the logic in - // PluginList::ShouldLoadPlugin due to missing the previously loaded plug-ins + // TODO(bauerb): If we restart loading plugins, we might mess up the logic in + // PluginList::ShouldLoadPlugin due to missing the previously loaded plugins // in |plugin_groups|. for (size_t i = 0; i < plugin_paths.size(); ++i) { WebPluginInfo plugin;
diff --git a/extensions/browser/api/management/management_api.cc b/extensions/browser/api/management/management_api.cc index c2fb30d8..2eb5b44 100644 --- a/extensions/browser/api/management/management_api.cc +++ b/extensions/browser/api/management/management_api.cc
@@ -61,11 +61,9 @@ std::vector<std::string> CreateWarningsList(const Extension* extension) { std::vector<std::string> warnings_list; - PermissionMessages warnings = - extension->permissions_data()->GetPermissionMessages(); - for (PermissionMessages::const_iterator iter = warnings.begin(); - iter != warnings.end(); ++iter) { - warnings_list.push_back(base::UTF16ToUTF8(iter->message())); + for (const base::string16& warning : + extension->permissions_data()->GetPermissionMessageStrings()) { + warnings_list.push_back(base::UTF16ToUTF8(warning)); } return warnings_list;
diff --git a/extensions/browser/app_window/app_window.cc b/extensions/browser/app_window/app_window.cc index 7d0e7c3..0689b136 100644 --- a/extensions/browser/app_window/app_window.cc +++ b/extensions/browser/app_window/app_window.cc
@@ -525,8 +525,9 @@ app_icon_url_ = url; web_contents()->DownloadImage( url, - true, // is a favicon - 0, // no maximum size + true, // is a favicon + 0, // no maximum size + false, // normal cache policy base::Bind(&AppWindow::DidDownloadFavicon, image_loader_ptr_factory_.GetWeakPtr())); } @@ -541,8 +542,9 @@ badge_icon_url_ = url; web_contents()->DownloadImage( url, - true, // is a favicon - 0, // no maximum size + true, // is a favicon + 0, // no maximum size + false, // normal cache policy base::Bind(&AppWindow::DidDownloadFavicon, image_loader_ptr_factory_.GetWeakPtr())); }
diff --git a/extensions/browser/process_manager.h b/extensions/browser/process_manager.h index 16691b4..d897d29 100644 --- a/extensions/browser/process_manager.h +++ b/extensions/browser/process_manager.h
@@ -120,7 +120,7 @@ // called regularly. void KeepaliveImpulse(const Extension* extension); - // Triggers a keepalive impulse for a plug-in (e.g NaCl). + // Triggers a keepalive impulse for a plugin (e.g NaCl). static void OnKeepaliveFromPlugin(int render_process_id, int render_frame_id, const std::string& extension_id);
diff --git a/extensions/common/api/_api_features.json b/extensions/common/api/_api_features.json index 300c9e8..9907815 100644 --- a/extensions/common/api/_api_features.json +++ b/extensions/common/api/_api_features.json
@@ -405,24 +405,6 @@ "contexts": ["webui"], "matches": ["chrome://chrome-signin/*", "chrome://oobe/*"] }], - "webViewExperimentalInternal": [{ - "internal": true, - "channel": "dev", - "contexts": ["blessed_extension"], - "dependencies": ["permission:webview"] - }, - { - "internal": true, - "channel": "stable", - "contexts": ["blessed_extension"], - "dependencies": ["permission:webview"], - "whitelist": [ - "8C3741E3AF0B93B6E8E0DDD499BB0B74839EA578", - "E703483CEF33DEC18B4B6DD84B5C776FB9182BDB", - "1A26E32DE447A17CBE5E9750CDBA78F58539B39C", - "59048028102D7B4C681DBC7BC6CD980C3DC66DA3" - ] - }], "webViewInternal": [{ "internal": true, "dependencies": ["permission:webview"],
diff --git a/extensions/common/permissions/permission_message.h b/extensions/common/permissions/permission_message.h index 94781bd..87ece37 100644 --- a/extensions/common/permissions/permission_message.h +++ b/extensions/common/permissions/permission_message.h
@@ -145,6 +145,7 @@ }; typedef std::vector<PermissionMessage> PermissionMessages; +typedef std::vector<PermissionMessage::ID> PermissionMessageIDs; } // namespace extensions
diff --git a/extensions/common/permissions/permission_message_provider.cc b/extensions/common/permissions/permission_message_provider.cc index 5650eab..80cc582 100644 --- a/extensions/common/permissions/permission_message_provider.cc +++ b/extensions/common/permissions/permission_message_provider.cc
@@ -4,10 +4,25 @@ #include "extensions/common/permissions/permission_message_provider.h" +#include "base/strings/string_split.h" #include "extensions/common/extensions_client.h" namespace extensions { +PermissionMessageString::PermissionMessageString( + const CoalescedPermissionMessage& message) + : message(message.message()), submessages(message.submessages()) { +} + +PermissionMessageString::PermissionMessageString(const base::string16& message, + const base::string16& details) + : message(message) { + base::SplitString(details, base::char16('\n'), &submessages); +} + +PermissionMessageString::~PermissionMessageString() { +} + // static const PermissionMessageProvider* PermissionMessageProvider::Get() { return &(ExtensionsClient::Get()->GetPermissionMessageProvider());
diff --git a/extensions/common/permissions/permission_message_provider.h b/extensions/common/permissions/permission_message_provider.h index a140e435..942cb09 100644 --- a/extensions/common/permissions/permission_message_provider.h +++ b/extensions/common/permissions/permission_message_provider.h
@@ -16,6 +16,20 @@ class PermissionIDSet; class PermissionSet; +// Temporary type to help the transition between old and new system. +// Essentially a CoalescedPermissionMessage minus the IDs. +// TODO(treib): Remove this once we've switched to the new system. +struct PermissionMessageString { + PermissionMessageString(const CoalescedPermissionMessage& message); + PermissionMessageString(const base::string16& message, + const base::string16& details); + ~PermissionMessageString(); + + base::string16 message; + std::vector<base::string16> submessages; +}; +typedef std::vector<PermissionMessageString> PermissionMessageStrings; + // The PermissionMessageProvider interprets permissions, translating them // into warning messages to show to the user. It also determines whether // a new set of permissions entails showing new warning messages. @@ -27,11 +41,20 @@ // Return the global permission message provider. static const PermissionMessageProvider* Get(); - // Gets the localized permission messages that represent this set. - // The set of permission messages shown varies by extension type. - // TODO(sashab): Deprecate this method in favor of - // GetCoalescedPermissionMessages() instead. - virtual PermissionMessages GetPermissionMessages( + // Calculates and returns the full list of permission messages for the given + // |permissions|. This forwards to the new GetCoalescedPermissionMessages or + // to the old GetWarningMessages/GetWarningMessagesDetails, depending on a + // cmdline flag. + // TODO(treib): Remove this once we've switched to the new system, and update + // all callers to use GetCoalescedPermissionMessages directly. + virtual PermissionMessageStrings GetPermissionMessageStrings( + const PermissionSet* permissions, + Manifest::Type extension_type) const = 0; + + // Gets the legacy permission message IDs that represent this set. + // Deprecated. You DO NOT want to call this! + // TODO(treib): Remove this once we've switched to the new system. + virtual PermissionMessageIDs GetLegacyPermissionMessageIDs( const PermissionSet* permissions, Manifest::Type extension_type) const = 0; @@ -48,18 +71,18 @@ // as strings). The set of permission messages shown varies by extension type. // Any permissions added by API, host or manifest permissions need to be added // to |permissions| before this function is called. - // TODO(sashab): Deprecate this method in favor of - // GetCoalescedPermissionMessages(). - virtual std::vector<base::string16> GetWarningMessages( + // Deprecated; use GetPermissionMessageStrings instead. + // TODO(treib): Remove this once we've switched to the new system. + virtual std::vector<base::string16> GetLegacyWarningMessages( const PermissionSet* permissions, Manifest::Type extension_type) const = 0; // Gets the localized permission details for messages that represent this set // (represented as strings). The set of permission messages shown varies by // extension type. - // TODO(sashab): Deprecate this method in favor of - // GetCoalescedPermissionMessages(). - virtual std::vector<base::string16> GetWarningMessagesDetails( + // Deprecated; use GetPermissionMessageStrings instead. + // TODO(treib): Remove this once we've switched to the new system. + virtual std::vector<base::string16> GetLegacyWarningMessagesDetails( const PermissionSet* permissions, Manifest::Type extension_type) const = 0;
diff --git a/extensions/common/permissions/permissions_data.cc b/extensions/common/permissions/permissions_data.cc index dcf2ec7..92eabb5 100644 --- a/extensions/common/permissions/permissions_data.cc +++ b/extensions/common/permissions/permissions_data.cc
@@ -196,11 +196,11 @@ return active_permissions()->HasEffectiveAccessToAllHosts(); } -PermissionMessages PermissionsData::GetPermissionMessages() const { +PermissionMessageIDs PermissionsData::GetLegacyPermissionMessageIDs() const { if (ShouldSkipPermissionWarnings(extension_id_)) { - return PermissionMessages(); + return PermissionMessageIDs(); } else { - return PermissionMessageProvider::Get()->GetPermissionMessages( + return PermissionMessageProvider::Get()->GetLegacyPermissionMessageIDs( active_permissions().get(), manifest_type_); } } @@ -209,7 +209,7 @@ const { if (ShouldSkipPermissionWarnings(extension_id_)) return std::vector<base::string16>(); - return PermissionMessageProvider::Get()->GetWarningMessages( + return PermissionMessageProvider::Get()->GetLegacyWarningMessages( active_permissions().get(), manifest_type_); } @@ -217,7 +217,7 @@ PermissionsData::GetPermissionMessageDetailsStrings() const { if (ShouldSkipPermissionWarnings(extension_id_)) return std::vector<base::string16>(); - return PermissionMessageProvider::Get()->GetWarningMessagesDetails( + return PermissionMessageProvider::Get()->GetLegacyWarningMessagesDetails( active_permissions().get(), manifest_type_); }
diff --git a/extensions/common/permissions/permissions_data.h b/extensions/common/permissions/permissions_data.h index 9a24fbf0..ab7ea52 100644 --- a/extensions/common/permissions/permissions_data.h +++ b/extensions/common/permissions/permissions_data.h
@@ -131,10 +131,10 @@ // network, etc.) bool HasEffectiveAccessToAllHosts() const; - // Returns the full list of permission messages that should display at - // install time. - // TODO(sashab): Deprecate this in favor of GetCoalescedPermissionMessages(). - PermissionMessages GetPermissionMessages() const; + // Returns the full list of legacy permission message IDs. + // Deprecated. You DO NOT want to call this! + // TODO(treib): Remove once we've switched to the new system. + PermissionMessageIDs GetLegacyPermissionMessageIDs() const; // Returns the full list of permission messages that should display at install // time as strings.
diff --git a/extensions/renderer/dispatcher.cc b/extensions/renderer/dispatcher.cc index 09156c3..8f37d82 100644 --- a/extensions/renderer/dispatcher.cc +++ b/extensions/renderer/dispatcher.cc
@@ -24,7 +24,6 @@ #include "content/public/renderer/render_view.h" #include "extensions/common/api/messaging/message.h" #include "extensions/common/constants.h" -#include "extensions/common/extension.h" #include "extensions/common/extension_api.h" #include "extensions/common/extension_messages.h" #include "extensions/common/extension_urls.h" @@ -37,7 +36,6 @@ #include "extensions/common/manifest_handlers/content_capabilities_handler.h" #include "extensions/common/manifest_handlers/externally_connectable.h" #include "extensions/common/manifest_handlers/options_page_info.h" -#include "extensions/common/manifest_handlers/sandboxed_page_info.h" #include "extensions/common/message_bundle.h" #include "extensions/common/permissions/permission_set.h" #include "extensions/common/permissions/permissions_data.h" @@ -56,7 +54,6 @@ #include "extensions/renderer/document_custom_bindings.h" #include "extensions/renderer/dom_activity_logger.h" #include "extensions/renderer/event_bindings.h" -#include "extensions/renderer/extension_groups.h" #include "extensions/renderer/extension_helper.h" #include "extensions/renderer/extensions_renderer_client.h" #include "extensions/renderer/file_system_natives.h" @@ -205,6 +202,8 @@ RenderThread::Get()->RegisterExtension(SafeBuiltins::CreateV8Extension()); + script_context_set_.reset( + new ScriptContextSet(&extensions_, &active_extension_ids_)); user_script_set_manager_.reset(new UserScriptSetManager(&extensions_)); script_injection_manager_.reset( new ScriptInjectionManager(&extensions_, user_script_set_manager_.get())); @@ -228,39 +227,6 @@ return is_active; } -const Extension* Dispatcher::GetExtensionFromFrameAndWorld( - const blink::WebFrame* frame, - int world_id, - bool use_effective_url) { - std::string extension_id; - if (world_id != 0) { - // Isolated worlds (content script). - extension_id = ScriptInjection::GetHostIdForIsolatedWorld(world_id); - } else if (!frame->document().securityOrigin().isUnique()) { - // TODO(kalman): Delete the above check. - - // Extension pages (chrome-extension:// URLs). - GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame); - frame_url = ScriptContext::GetEffectiveDocumentURL( - frame, frame_url, use_effective_url); - extension_id = extensions_.GetExtensionOrAppIDByURL(frame_url); - } - - const Extension* extension = extensions_.GetByID(extension_id); - if (!extension && !extension_id.empty()) { - // There are conditions where despite a context being associated with an - // extension, no extension actually gets found. Ignore "invalid" because - // CSP blocks extension page loading by switching the extension ID to - // "invalid". This isn't interesting. - if (extension_id != "invalid") { - LOG(ERROR) << "Extension \"" << extension_id << "\" not found"; - RenderThread::Get()->RecordAction( - UserMetricsAction("ExtensionNotFound_ED")); - } - } - return extension; -} - void Dispatcher::DidCreateScriptContext( blink::WebLocalFrame* frame, const v8::Handle<v8::Context>& v8_context, @@ -268,32 +234,13 @@ int world_id) { const base::TimeTicks start_time = base::TimeTicks::Now(); - const Extension* extension = - GetExtensionFromFrameAndWorld(frame, world_id, false); - const Extension* effective_extension = - GetExtensionFromFrameAndWorld(frame, world_id, true); - - GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame); - Feature::Context context_type = - ClassifyJavaScriptContext(extension, - extension_group, - frame_url, - frame->document().securityOrigin()); - Feature::Context effective_context_type = ClassifyJavaScriptContext( - effective_extension, - extension_group, - ScriptContext::GetEffectiveDocumentURL(frame, frame_url, true), - frame->document().securityOrigin()); - - ScriptContext* context = - new ScriptContext(v8_context, frame, extension, context_type, - effective_extension, effective_context_type); - script_context_set_.Add(context); + ScriptContext* context = script_context_set_->Register( + frame, v8_context, extension_group, world_id); // Initialize origin permissions for content scripts, which can't be // initialized in |OnActivateExtension|. - if (context_type == Feature::CONTENT_SCRIPT_CONTEXT) - InitOriginPermissions(extension); + if (context->context_type() == Feature::CONTENT_SCRIPT_CONTEXT) + InitOriginPermissions(context->extension()); { scoped_ptr<ModuleSystem> module_system( @@ -328,7 +275,7 @@ delegate_->RequireAdditionalModules(context, is_within_platform_app); const base::TimeDelta elapsed = base::TimeTicks::Now() - start_time; - switch (context_type) { + switch (context->context_type()) { case Feature::UNSPECIFIED_CONTEXT: UMA_HISTOGRAM_TIMES("Extensions.DidCreateScriptContext_Unspecified", elapsed); @@ -356,14 +303,14 @@ break; } - VLOG(1) << "Num tracked contexts: " << script_context_set_.size(); + VLOG(1) << "Num tracked contexts: " << script_context_set_->size(); } void Dispatcher::WillReleaseScriptContext( blink::WebLocalFrame* frame, const v8::Handle<v8::Context>& v8_context, int world_id) { - ScriptContext* context = script_context_set_.GetByV8Context(v8_context); + ScriptContext* context = script_context_set_->GetByV8Context(v8_context); if (!context) return; @@ -371,8 +318,8 @@ // TODO(kalman): add an invalidation observer interface to ScriptContext. request_sender_->InvalidateSource(context); - script_context_set_.Remove(context); - VLOG(1) << "Num tracked contexts: " << script_context_set_.size(); + script_context_set_->Remove(context); + VLOG(1) << "Num tracked contexts: " << script_context_set_->size(); } void Dispatcher::DidCreateDocumentElement(blink::WebFrame* frame) { @@ -443,7 +390,8 @@ // Theoretically we could end up with bindings being injected into sandboxed // frames, for example content scripts. Don't let them execute API functions. blink::WebFrame* frame = context->web_frame(); - if (IsSandboxedPage(ScriptContext::GetDataSourceURLForFrame(frame))) { + if (ScriptContext::IsSandboxedPage( + extensions_, ScriptContext::GetDataSourceURLForFrame(frame))) { static const char kMessage[] = "%s cannot be used within a sandboxed frame."; std::string error_msg = base::StringPrintf(kMessage, function_name.c_str()); @@ -470,11 +418,9 @@ // Needed for Windows compilation, since kEventBindings is declared extern. const char* local_event_bindings = kEventBindings; - script_context_set_.ForEach(extension_id, - base::Bind(&CallModuleMethod, - local_event_bindings, - kEventDispatchFunction, - &args)); + script_context_set_->ForEach( + extension_id, base::Bind(&CallModuleMethod, local_event_bindings, + kEventDispatchFunction, &args)); } void Dispatcher::InvokeModuleSystemMethod(content::RenderView* render_view, @@ -487,9 +433,8 @@ if (user_gesture) web_user_gesture.reset(new WebScopedUserGesture); - script_context_set_.ForEach( - extension_id, - render_view, + script_context_set_->ForEach( + extension_id, render_view, base::Bind(&CallModuleMethod, module_name, function_name, &args)); // Reset the idle handler each time there's any activity like event or message @@ -587,8 +532,6 @@ resources.push_back(std::make_pair("webViewConstants", IDR_WEB_VIEW_CONSTANTS_JS)); resources.push_back(std::make_pair("webViewEvents", IDR_WEB_VIEW_EVENTS_JS)); - resources.push_back(std::make_pair("webViewExperimental", - IDR_WEB_VIEW_EXPERIMENTAL_JS)); resources.push_back(std::make_pair("webViewInternal", IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS)); resources.push_back( @@ -896,8 +839,7 @@ new RequestSender::ScopedTabID(request_sender(), it->second)); } - MessagingBindings::DeliverMessage(script_context_set_, - target_port_id, + MessagingBindings::DeliverMessage(*script_context_set_, target_port_id, message, NULL); // All render frames. } @@ -914,19 +856,15 @@ source.tab.GetInteger("id", &sender_tab_id); port_to_tab_id_map_[target_port_id] = sender_tab_id; - MessagingBindings::DispatchOnConnect(script_context_set_, - target_port_id, - channel_name, - source, - info, + MessagingBindings::DispatchOnConnect(*script_context_set_, target_port_id, + channel_name, source, info, tls_channel_id, NULL); // All render frames. } void Dispatcher::OnDispatchOnDisconnect(int port_id, const std::string& error_message) { - MessagingBindings::DispatchOnDisconnect(script_context_set_, - port_id, + MessagingBindings::DispatchOnDisconnect(*script_context_set_, port_id, error_message, NULL); // All render frames. } @@ -1016,12 +954,10 @@ // Invalidate all of the contexts that were removed. // TODO(kalman): add an invalidation observer interface to ScriptContext. - ScriptContextSet::ContextSet removed_contexts = - script_context_set_.OnExtensionUnloaded(id); - for (ScriptContextSet::ContextSet::iterator it = removed_contexts.begin(); - it != removed_contexts.end(); - ++it) { - request_sender_->InvalidateSource(*it); + std::set<ScriptContext*> removed_contexts = + script_context_set_->OnExtensionUnloaded(id); + for (ScriptContext* context : removed_contexts) { + request_sender_->InvalidateSource(context); } // Update the available bindings for the remaining contexts. These may have @@ -1386,75 +1322,6 @@ return false; } -// TODO(kalman): This is checking for the wrong thing, it should be checking if -// the frame's security origin is unique. The extension sandbox directive is -// checked for in extensions/common/manifest_handlers/csp_info.cc. -bool Dispatcher::IsSandboxedPage(const GURL& url) const { - if (url.SchemeIs(kExtensionScheme)) { - const Extension* extension = extensions_.GetByID(url.host()); - if (extension) { - return SandboxedPageInfo::IsSandboxedPage(extension, url.path()); - } - } - return false; -} - -Feature::Context Dispatcher::ClassifyJavaScriptContext( - const Extension* extension, - int extension_group, - const GURL& url, - const blink::WebSecurityOrigin& origin) { - // WARNING: This logic must match ProcessMap::GetContextType, as much as - // possible. - - DCHECK_GE(extension_group, 0); - if (extension_group == EXTENSION_GROUP_CONTENT_SCRIPTS) { - return extension ? // TODO(kalman): when does this happen? - Feature::CONTENT_SCRIPT_CONTEXT - : Feature::UNSPECIFIED_CONTEXT; - } - - // We have an explicit check for sandboxed pages before checking whether the - // extension is active in this process because: - // 1. Sandboxed pages run in the same process as regular extension pages, so - // the extension is considered active. - // 2. ScriptContext creation (which triggers bindings injection) happens - // before the SecurityContext is updated with the sandbox flags (after - // reading the CSP header), so the caller can't check if the context's - // security origin is unique yet. - if (IsSandboxedPage(url)) - return Feature::WEB_PAGE_CONTEXT; - - if (extension && IsExtensionActive(extension->id())) { - // |extension| is active in this process, but it could be either a true - // extension process or within the extent of a hosted app. In the latter - // case this would usually be considered a (blessed) web page context, - // unless the extension in question is a component extension, in which case - // we cheat and call it blessed. - return (extension->is_hosted_app() && - extension->location() != Manifest::COMPONENT) - ? Feature::BLESSED_WEB_PAGE_CONTEXT - : Feature::BLESSED_EXTENSION_CONTEXT; - } - - // TODO(kalman): This isUnique() check is wrong, it should be performed as - // part of IsSandboxedPage(). - if (!origin.isUnique() && extensions_.ExtensionBindingsAllowed(url)) { - if (!extension) // TODO(kalman): when does this happen? - return Feature::UNSPECIFIED_CONTEXT; - return extension->is_hosted_app() ? Feature::BLESSED_WEB_PAGE_CONTEXT - : Feature::UNBLESSED_EXTENSION_CONTEXT; - } - - if (!url.is_valid()) - return Feature::UNSPECIFIED_CONTEXT; - - if (url.SchemeIs(content::kChromeUIScheme)) - return Feature::WEBUI_CONTEXT; - - return Feature::WEB_PAGE_CONTEXT; -} - v8::Handle<v8::Object> Dispatcher::GetOrCreateObject( const v8::Handle<v8::Object>& object, const std::string& field, @@ -1559,10 +1426,6 @@ module_system->Require("webView"); module_system->Require("webViewApiMethods"); module_system->Require("webViewAttributes"); - if (context->GetAvailability("webViewExperimentalInternal") - .is_available()) { - module_system->Require("webViewExperimental"); - } } // The "guestViewDeny" module must always be loaded last. It registers
diff --git a/extensions/renderer/dispatcher.h b/extensions/renderer/dispatcher.h index c5ac3651..c71cb64 100644 --- a/extensions/renderer/dispatcher.h +++ b/extensions/renderer/dispatcher.h
@@ -11,10 +11,12 @@ #include <utility> #include <vector> +#include "base/memory/scoped_ptr.h" #include "base/scoped_observer.h" #include "base/timer/timer.h" #include "content/public/renderer/render_process_observer.h" #include "extensions/common/event_filter.h" +#include "extensions/common/extension.h" #include "extensions/common/extension_set.h" #include "extensions/common/extensions_client.h" #include "extensions/common/features/feature.h" @@ -53,7 +55,6 @@ namespace extensions { class ContentWatcher; class DispatcherDelegate; -class Extension; class FilteredEventRouter; class ManifestPermissionSet; class RequestSender; @@ -76,7 +77,7 @@ const ExtensionSet* extensions() const { return &extensions_; } const ScriptContextSet& script_context_set() const { - return script_context_set_; + return *script_context_set_; } V8SchemaRegistry* v8_schema_registry() { return v8_schema_registry_.get(); } @@ -89,14 +90,6 @@ bool IsExtensionActive(const std::string& extension_id) const; - // Finds the extension for the JavaScript context associated with the - // specified |frame| and isolated world. If |world_id| is zero, finds the - // extension ID associated with the main world's JavaScript context. If the - // JavaScript context isn't from an extension, returns empty string. - const Extension* GetExtensionFromFrameAndWorld(const blink::WebFrame* frame, - int world_id, - bool use_effective_url); - void DidCreateScriptContext(blink::WebLocalFrame* frame, const v8::Handle<v8::Context>& context, int extension_group, @@ -242,15 +235,6 @@ // Returns whether the current renderer hosts a platform app. bool IsWithinPlatformApp(); - bool IsSandboxedPage(const GURL& url) const; - - // Returns the Feature::Context type of context for a JavaScript context. - Feature::Context ClassifyJavaScriptContext( - const Extension* extension, - int extension_group, - const GURL& url, - const blink::WebSecurityOrigin& origin); - // Gets |field| from |object| or creates it as an empty object if it doesn't // exist. v8::Handle<v8::Object> GetOrCreateObject(const v8::Handle<v8::Object>& object, @@ -284,7 +268,7 @@ // All the bindings contexts that are currently loaded for this renderer. // There is zero or one for each v8 context. - ScriptContextSet script_context_set_; + scoped_ptr<ScriptContextSet> script_context_set_; scoped_ptr<ContentWatcher> content_watcher_; @@ -300,7 +284,7 @@ std::set<std::string> function_names_; // The extensions and apps that are active in this process. - std::set<std::string> active_extension_ids_; + ExtensionIdSet active_extension_ids_; ResourceBundleSourceMap source_map_;
diff --git a/extensions/renderer/document_custom_bindings.cc b/extensions/renderer/document_custom_bindings.cc index bb9d7f7..f9f35d2 100644 --- a/extensions/renderer/document_custom_bindings.cc +++ b/extensions/renderer/document_custom_bindings.cc
@@ -9,7 +9,7 @@ #include "base/bind.h" #include "extensions/renderer/script_context.h" #include "third_party/WebKit/public/web/WebDocument.h" -#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" #include "v8/include/v8.h" namespace extensions {
diff --git a/extensions/renderer/request_sender.cc b/extensions/renderer/request_sender.cc index 60c77c6..5797953 100644 --- a/extensions/renderer/request_sender.cc +++ b/extensions/renderer/request_sender.cc
@@ -10,7 +10,7 @@ #include "extensions/renderer/dispatcher.h" #include "extensions/renderer/script_context.h" #include "third_party/WebKit/public/web/WebDocument.h" -#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScopedUserGesture.h" #include "third_party/WebKit/public/web/WebUserGestureIndicator.h" #include "third_party/WebKit/public/web/WebUserGestureToken.h" @@ -97,7 +97,7 @@ return; GURL source_url; - if (blink::WebFrame* webframe = context->web_frame()) + if (blink::WebLocalFrame* webframe = context->web_frame()) source_url = webframe->document().url(); InsertRequest(request_id, new PendingRequest(name, source,
diff --git a/extensions/renderer/resources/extensions_renderer_resources.grd b/extensions/renderer/resources/extensions_renderer_resources.grd index ca9d87e9..d224022 100644 --- a/extensions/renderer/resources/extensions_renderer_resources.grd +++ b/extensions/renderer/resources/extensions_renderer_resources.grd
@@ -58,7 +58,6 @@ <include name="IDR_WEB_VIEW_ATTRIBUTES_JS" file="guest_view/web_view/web_view_attributes.js" type="BINDATA" /> <include name="IDR_WEB_VIEW_CONSTANTS_JS" file="guest_view/web_view/web_view_constants.js" type="BINDATA" /> <include name="IDR_WEB_VIEW_EVENTS_JS" file="guest_view/web_view/web_view_events.js" type="BINDATA" /> - <include name="IDR_WEB_VIEW_EXPERIMENTAL_JS" file="guest_view/web_view/web_view_experimental.js" type="BINDATA" /> <include name="IDR_WEB_VIEW_INTERNAL_CUSTOM_BINDINGS_JS" file="guest_view/web_view/web_view_internal.js" type="BINDATA" /> <include name="IDR_WEB_VIEW_JS" file="guest_view/web_view/web_view.js" type="BINDATA" />
diff --git a/extensions/renderer/resources/guest_view/web_view/web_view.js b/extensions/renderer/resources/guest_view/web_view/web_view.js index aa1d67d7..a69736b 100644 --- a/extensions/renderer/resources/guest_view/web_view/web_view.js +++ b/extensions/renderer/resources/guest_view/web_view/web_view.js
@@ -32,11 +32,6 @@ // Public-facing API methods. var apiMethods = WebViewImpl.getApiMethods(); - // Add the experimental API methods, if available. - var experimentalApiMethods = - WebViewImpl.maybeGetExperimentalApiMethods(); - apiMethods = $Array.concat(apiMethods, experimentalApiMethods); - // Create default implementations for undefined API methods. var createDefaultApiMethod = function(m) { return function(var_args) { @@ -222,11 +217,7 @@ } // Implemented when the ChromeWebView API is available. -WebViewImpl.prototype.maybeGetChromeWebViewEvents = function() {}; - -// Implemented when the experimental WebView API is available. -WebViewImpl.maybeGetExperimentalApiMethods = function() { return []; }; -WebViewImpl.prototype.setupExperimentalContextMenus = function() {}; +WebViewImpl.prototype.maybeSetupContextMenus = function() {}; GuestViewContainer.registerElement(WebViewImpl);
diff --git a/extensions/renderer/resources/guest_view/web_view/web_view_events.js b/extensions/renderer/resources/guest_view/web_view/web_view_events.js index 470b49a..bae210e 100644 --- a/extensions/renderer/resources/guest_view/web_view/web_view_events.js +++ b/extensions/renderer/resources/guest_view/web_view/web_view_events.js
@@ -22,7 +22,7 @@ GuestViewEvents.call(this, webViewImpl); this.setupWebRequestEvents(); - this.view.setupExperimentalContextMenus(); + this.view.maybeSetupContextMenus(); } WebViewEvents.prototype.__proto__ = GuestViewEvents.prototype;
diff --git a/extensions/renderer/resources/guest_view/web_view/web_view_experimental.js b/extensions/renderer/resources/guest_view/web_view/web_view_experimental.js deleted file mode 100644 index 04299e9..0000000 --- a/extensions/renderer/resources/guest_view/web_view/web_view_experimental.js +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2014 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. - -// This module implements experimental API for <webview>. -// See web_view.js and web_view_api_methods.js for details. -// -// <webview> Experimental API is only available on canary and dev channels of -// Chrome. - -var WebViewImpl = require('webView').WebViewImpl; -var WebViewInternal = require('webViewInternal').WebViewInternal; - -// An array of <webview>'s experimental API methods. See |WEB_VIEW_API_METHODS| -// in web_view_api_methods.js for more details. -var WEB_VIEW_EXPERIMENTAL_API_METHODS = [ -]; - -// Registers the experimantal WebVIew API when available. -WebViewImpl.maybeGetExperimentalApiMethods = function() { - return WEB_VIEW_EXPERIMENTAL_API_METHODS; -};
diff --git a/extensions/renderer/script_context.cc b/extensions/renderer/script_context.cc index e5677aa..47a3c2a 100644 --- a/extensions/renderer/script_context.cc +++ b/extensions/renderer/script_context.cc
@@ -13,15 +13,19 @@ #include "content/public/common/url_constants.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_view.h" +#include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/extension_api.h" +#include "extensions/common/extension_set.h" #include "extensions/common/extension_urls.h" #include "extensions/common/features/base_feature_provider.h" +#include "extensions/common/manifest_handlers/sandboxed_page_info.h" #include "extensions/common/permissions/permissions_data.h" #include "gin/per_context_data.h" #include "third_party/WebKit/public/web/WebDataSource.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h" #include "third_party/WebKit/public/web/WebSecurityOrigin.h" #include "third_party/WebKit/public/web/WebView.h" @@ -75,7 +79,7 @@ }; ScriptContext::ScriptContext(const v8::Handle<v8::Context>& v8_context, - blink::WebFrame* web_frame, + blink::WebLocalFrame* web_frame, const Extension* extension, Feature::Context context_type, const Extension* effective_extension, @@ -110,6 +114,21 @@ Invalidate(); } +// static +bool ScriptContext::IsSandboxedPage(const ExtensionSet& extensions, + const GURL& url) { + // TODO(kalman): This is checking for the wrong thing, it should be checking + // if the frame's security origin is unique. The extension sandbox directive + // is checked for in extensions/common/manifest_handlers/csp_info.cc. + if (url.SchemeIs(kExtensionScheme)) { + const Extension* extension = extensions.GetByID(url.host()); + if (extension) { + return SandboxedPageInfo::IsSandboxedPage(extension, url.path()); + } + } + return false; +} + void ScriptContext::Invalidate() { if (!is_valid()) return;
diff --git a/extensions/renderer/script_context.h b/extensions/renderer/script_context.h index b6c90f2..745f522 100644 --- a/extensions/renderer/script_context.h +++ b/extensions/renderer/script_context.h
@@ -20,6 +20,7 @@ namespace blink { class WebFrame; +class WebLocalFrame; } namespace content { @@ -29,18 +30,27 @@ namespace extensions { class Extension; +class ExtensionSet; // Extensions wrapper for a v8 context. class ScriptContext : public RequestSender::Source { public: ScriptContext(const v8::Handle<v8::Context>& context, - blink::WebFrame* frame, + blink::WebLocalFrame* frame, const Extension* extension, Feature::Context context_type, const Extension* effective_extension, Feature::Context effective_context_type); ~ScriptContext() override; + // Returns whether |url| is sandboxed (as declared in any Extension in + // |extension_set| as sandboxed). + // + // Declared in ScriptContext for lack of a better place, but this should + // become unnecessary at some point as crbug.com/466373 is worked on. + static bool IsSandboxedPage(const ExtensionSet& extension_set, + const GURL& url); + // Clears the WebFrame for this contexts and invalidates the associated // ModuleSystem. void Invalidate(); @@ -59,7 +69,7 @@ return effective_extension_.get(); } - blink::WebFrame* web_frame() const { return web_frame_; } + blink::WebLocalFrame* web_frame() const { return web_frame_; } Feature::Context context_type() const { return context_type_; } @@ -114,6 +124,14 @@ v8::Isolate* isolate() const { return isolate_; } // Get the URL of this context's web frame. + // + // TODO(kalman): Remove this and replace with a GetOrigin() call which reads + // of WebDocument::securityOrigin(): + // - The URL can change (e.g. pushState) but the origin cannot. Luckily it + // appears as though callers don't make security decisions based on the + // result of GetURL() so it's not a problem... yet. + // - Origin is the correct check to be making. + // - It might let us remove the about:blank resolving? GURL GetURL() const; // Returns whether the API |api| or any part of the API could be @@ -157,9 +175,9 @@ private: class Runner; - // The WebFrame associated with this context. This can be NULL because this - // object can outlive is destroyed asynchronously. - blink::WebFrame* web_frame_; + // The WebLocalFrame associated with this context. This can be NULL because + // this object can outlive is destroyed asynchronously. + blink::WebLocalFrame* web_frame_; // The extension associated with this context, or NULL if there is none. This // might be a hosted app in the case that this context is hosting a web URL.
diff --git a/extensions/renderer/script_context_set.cc b/extensions/renderer/script_context_set.cc index 5f7be6c1..1e9e9e8 100644 --- a/extensions/renderer/script_context_set.cc +++ b/extensions/renderer/script_context_set.cc
@@ -5,34 +5,50 @@ #include "extensions/renderer/script_context_set.h" #include "base/message_loop/message_loop.h" +#include "content/public/common/url_constants.h" #include "content/public/renderer/render_view.h" #include "extensions/common/extension.h" +#include "extensions/renderer/extension_groups.h" #include "extensions/renderer/script_context.h" +#include "extensions/renderer/script_injection.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" #include "v8/include/v8.h" namespace extensions { -ScriptContextSet::ScriptContextSet() { +ScriptContextSet::ScriptContextSet(ExtensionSet* extensions, + ExtensionIdSet* active_extension_ids) + : extensions_(extensions), active_extension_ids_(active_extension_ids) { } + ScriptContextSet::~ScriptContextSet() { } -int ScriptContextSet::size() const { - return static_cast<int>(contexts_.size()); -} +ScriptContext* ScriptContextSet::Register( + blink::WebLocalFrame* frame, + const v8::Handle<v8::Context>& v8_context, + int extension_group, + int world_id) { + const Extension* extension = + GetExtensionFromFrameAndWorld(frame, world_id, false); + const Extension* effective_extension = + GetExtensionFromFrameAndWorld(frame, world_id, true); -void ScriptContextSet::Add(ScriptContext* context) { -#if DCHECK_IS_ON() - // It's OK to insert the same context twice, but we should only ever have - // one ScriptContext per v8::Context. - for (ContextSet::iterator iter = contexts_.begin(); iter != contexts_.end(); - ++iter) { - ScriptContext* candidate = *iter; - if (candidate != context) - DCHECK(candidate->v8_context() != context->v8_context()); - } -#endif - contexts_.insert(context); + GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame); + Feature::Context context_type = + ClassifyJavaScriptContext(extension, extension_group, frame_url, + frame->document().securityOrigin()); + Feature::Context effective_context_type = ClassifyJavaScriptContext( + effective_extension, extension_group, + ScriptContext::GetEffectiveDocumentURL(frame, frame_url, true), + frame->document().securityOrigin()); + + ScriptContext* context = + new ScriptContext(v8_context, frame, extension, context_type, + effective_extension, effective_context_type); + contexts_.insert(context); // takes ownership + return context; } void ScriptContextSet::Remove(ScriptContext* context) { @@ -42,32 +58,25 @@ } } -ScriptContextSet::ContextSet ScriptContextSet::GetAll() const { - return contexts_; -} - ScriptContext* ScriptContextSet::GetCurrent() const { v8::Isolate* isolate = v8::Isolate::GetCurrent(); return isolate->InContext() ? GetByV8Context(isolate->GetCurrentContext()) - : NULL; + : nullptr; } ScriptContext* ScriptContextSet::GetCalling() const { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> calling = isolate->GetCallingContext(); - return calling.IsEmpty() ? NULL : GetByV8Context(calling); + return calling.IsEmpty() ? nullptr : GetByV8Context(calling); } ScriptContext* ScriptContextSet::GetByV8Context( - v8::Handle<v8::Context> v8_context) const { - for (ContextSet::const_iterator iter = contexts_.begin(); - iter != contexts_.end(); - ++iter) { - if ((*iter)->v8_context() == v8_context) - return *iter; + const v8::Handle<v8::Context>& v8_context) const { + for (ScriptContext* script_context : contexts_) { + if (script_context->v8_context() == v8_context) + return script_context; } - - return NULL; + return nullptr; } void ScriptContextSet::ForEach( @@ -76,11 +85,9 @@ const base::Callback<void(ScriptContext*)>& callback) const { // We copy the context list, because calling into javascript may modify it // out from under us. - ContextSet contexts = GetAll(); + std::set<ScriptContext*> contexts_copy = contexts_; - for (ContextSet::iterator it = contexts.begin(); it != contexts.end(); ++it) { - ScriptContext* context = *it; - + for (ScriptContext* context : contexts_copy) { // For the same reason as above, contexts may become invalid while we run. if (!context->is_valid()) continue; @@ -102,23 +109,103 @@ } } -ScriptContextSet::ContextSet ScriptContextSet::OnExtensionUnloaded( +std::set<ScriptContext*> ScriptContextSet::OnExtensionUnloaded( const std::string& extension_id) { - ContextSet contexts = GetAll(); - ContextSet removed; + std::set<ScriptContext*> removed; + ForEach(extension_id, + base::Bind(&ScriptContextSet::DispatchOnUnloadEventAndRemove, + base::Unretained(this), &removed)); + return removed; +} - // Clean up contexts belonging to the unloaded extension. This is done so - // that content scripts (which remain injected into the page) don't continue - // receiving events and sending messages. - for (ContextSet::iterator it = contexts.begin(); it != contexts.end(); ++it) { - if ((*it)->extension() && (*it)->extension()->id() == extension_id) { - (*it)->DispatchOnUnloadEvent(); - removed.insert(*it); - Remove(*it); - } +const Extension* ScriptContextSet::GetExtensionFromFrameAndWorld( + const blink::WebLocalFrame* frame, + int world_id, + bool use_effective_url) { + std::string extension_id; + if (world_id != 0) { + // Isolated worlds (content script). + extension_id = ScriptInjection::GetHostIdForIsolatedWorld(world_id); + } else if (!frame->document().securityOrigin().isUnique()) { + // TODO(kalman): Delete the above check. + // Extension pages (chrome-extension:// URLs). + GURL frame_url = ScriptContext::GetDataSourceURLForFrame(frame); + frame_url = ScriptContext::GetEffectiveDocumentURL(frame, frame_url, + use_effective_url); + extension_id = extensions_->GetExtensionOrAppIDByURL(frame_url); } - return removed; + // There are conditions where despite a context being associated with an + // extension, no extension actually gets found. Ignore "invalid" because CSP + // blocks extension page loading by switching the extension ID to "invalid". + const Extension* extension = extensions_->GetByID(extension_id); + if (!extension && !extension_id.empty() && extension_id != "invalid") { + // TODO(kalman): Do something here? + } + return extension; +} + +Feature::Context ScriptContextSet::ClassifyJavaScriptContext( + const Extension* extension, + int extension_group, + const GURL& url, + const blink::WebSecurityOrigin& origin) { + // WARNING: This logic must match ProcessMap::GetContextType, as much as + // possible. + + DCHECK_GE(extension_group, 0); + if (extension_group == EXTENSION_GROUP_CONTENT_SCRIPTS) { + return extension ? // TODO(kalman): when does this happen? + Feature::CONTENT_SCRIPT_CONTEXT + : Feature::UNSPECIFIED_CONTEXT; + } + + // We have an explicit check for sandboxed pages before checking whether the + // extension is active in this process because: + // 1. Sandboxed pages run in the same process as regular extension pages, so + // the extension is considered active. + // 2. ScriptContext creation (which triggers bindings injection) happens + // before the SecurityContext is updated with the sandbox flags (after + // reading the CSP header), so the caller can't check if the context's + // security origin is unique yet. + if (ScriptContext::IsSandboxedPage(*extensions_, url)) + return Feature::WEB_PAGE_CONTEXT; + + if (extension && active_extension_ids_->count(extension->id()) > 0) { + // |extension| is active in this process, but it could be either a true + // extension process or within the extent of a hosted app. In the latter + // case this would usually be considered a (blessed) web page context, + // unless the extension in question is a component extension, in which case + // we cheat and call it blessed. + return (extension->is_hosted_app() && + extension->location() != Manifest::COMPONENT) + ? Feature::BLESSED_WEB_PAGE_CONTEXT + : Feature::BLESSED_EXTENSION_CONTEXT; + } + + // TODO(kalman): This isUnique() check is wrong, it should be performed as + // part of ScriptContext::IsSandboxedPage(). + if (!origin.isUnique() && extensions_->ExtensionBindingsAllowed(url)) { + if (!extension) // TODO(kalman): when does this happen? + return Feature::UNSPECIFIED_CONTEXT; + return extension->is_hosted_app() ? Feature::BLESSED_WEB_PAGE_CONTEXT + : Feature::UNBLESSED_EXTENSION_CONTEXT; + } + + if (!url.is_valid()) + return Feature::UNSPECIFIED_CONTEXT; + + if (url.SchemeIs(content::kChromeUIScheme)) + return Feature::WEBUI_CONTEXT; + + return Feature::WEB_PAGE_CONTEXT; +} + +void ScriptContextSet::DispatchOnUnloadEventAndRemove( + std::set<ScriptContext*>* out, + ScriptContext* context) { + Remove(context); // deleted asynchronously + out->insert(context); } } // namespace extensions
diff --git a/extensions/renderer/script_context_set.h b/extensions/renderer/script_context_set.h index aa7b253..ac3cb178 100644 --- a/extensions/renderer/script_context_set.h +++ b/extensions/renderer/script_context_set.h
@@ -8,8 +8,12 @@ #include <set> #include <string> -#include "base/basictypes.h" -#include "base/bind.h" +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "extensions/common/extension.h" +#include "extensions/common/extension_set.h" +#include "extensions/common/features/feature.h" +#include "url/gurl.h" #include "v8/include/v8.h" class GURL; @@ -18,39 +22,50 @@ class ListValue; } -namespace content { -class RenderView; +namespace blink { +class WebLocalFrame; +class WebSecurityOrigin; } -namespace v8 { -class Context; +namespace content { +class RenderView; } namespace extensions { class ScriptContext; -// A container of ExtensionBindingsContext. Since calling JavaScript within a -// context can cause any number of contexts to be created or destroyed, this -// has additional smarts to help with the set changing underneath callers. +// A container of ScriptContexts, responsible for both creating and managing +// them. +// +// Since calling JavaScript within a context can cause any number of contexts +// to be created or destroyed, this has additional smarts to help with the set +// changing underneath callers. class ScriptContextSet { public: - ScriptContextSet(); + ScriptContextSet( + ExtensionSet* extensions, + // Set of the IDs of extensions that are active in this process. + // Must outlive this. TODO(kalman): Combine this and |extensions|. + ExtensionIdSet* active_extension_ids); + ~ScriptContextSet(); - int size() const; + // Returns the number of contexts being tracked by this set. + // This may also include invalid contexts. TODO(kalman): Useful? + size_t size() const { return contexts_.size(); } - // Takes ownership of |context|. - void Add(ScriptContext* context); + // Creates and starts managing a new ScriptContext. Ownership is held. + // Returns a weak reference to the new ScriptContext. + ScriptContext* Register(blink::WebLocalFrame* frame, + const v8::Handle<v8::Context>& v8_context, + int extension_group, + int world_id); // If the specified context is contained in this set, remove it, then delete // it asynchronously. After this call returns the context object will still // be valid, but its frame() pointer will be cleared. void Remove(ScriptContext* context); - // Returns a copy to protect against changes. - typedef std::set<ScriptContext*> ContextSet; - ContextSet GetAll() const; - // Gets the ScriptContext corresponding to v8::Context::GetCurrent(), or // NULL if no such context exists. ScriptContext* GetCurrent() const; @@ -61,7 +76,7 @@ // Gets the ScriptContext corresponding to the specified // v8::Context or NULL if no such context exists. - ScriptContext* GetByV8Context(v8::Handle<v8::Context> context) const; + ScriptContext* GetByV8Context(const v8::Handle<v8::Context>& context) const; // Synchronously runs |callback| with each ScriptContext that belongs to // |extension_id| in |render_view|. @@ -88,10 +103,39 @@ // Returns the set of ScriptContexts that were removed as a result. These // are safe to interact with until the end of the current event loop, since // they're deleted asynchronously. - ContextSet OnExtensionUnloaded(const std::string& extension_id); + std::set<ScriptContext*> OnExtensionUnloaded(const std::string& extension_id); private: - ContextSet contexts_; + // Finds the extension for the JavaScript context associated with the + // specified |frame| and isolated world. If |world_id| is zero, finds the + // extension ID associated with the main world's JavaScript context. If the + // JavaScript context isn't from an extension, returns empty string. + const Extension* GetExtensionFromFrameAndWorld( + const blink::WebLocalFrame* frame, + int world_id, + bool use_effective_url); + + // Returns the Feature::Context type of context for a JavaScript context. + Feature::Context ClassifyJavaScriptContext( + const Extension* extension, + int extension_group, + const GURL& url, + const blink::WebSecurityOrigin& origin); + + // Calls Remove on |context| then appends |context| to |out|. + // This is a helper designed to be used by OnExtensionUnloaded with ForEach. + void DispatchOnUnloadEventAndRemove(std::set<ScriptContext*>* out, + ScriptContext* context); + + // Weak reference to all installed Extensions. + ExtensionSet* extensions_; + + // Weak reference to all installed Extensions that are also active in this + // process. + ExtensionIdSet* active_extension_ids_; + + // The set of all ScriptContexts we own. + std::set<ScriptContext*> contexts_; DISALLOW_COPY_AND_ASSIGN(ScriptContextSet); };
diff --git a/extensions/renderer/script_context_set_unittest.cc b/extensions/renderer/script_context_set_unittest.cc index e795dd9..089caca 100644 --- a/extensions/renderer/script_context_set_unittest.cc +++ b/extensions/renderer/script_context_set_unittest.cc
@@ -2,61 +2,59 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <vector> + #include "base/message_loop/message_loop.h" #include "extensions/common/extension.h" +#include "extensions/common/extension_set.h" #include "extensions/common/features/feature.h" #include "extensions/renderer/script_context.h" #include "extensions/renderer/script_context_set.h" #include "gin/public/context_holder.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/WebKit/public/web/WebFrame.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebView.h" #include "v8/include/v8.h" namespace extensions { -TEST(ScriptContextSet, Lifecycle) { +TEST(ScriptContextSetTest, Lifecycle) { base::MessageLoop loop; - ScriptContextSet context_set; - - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - v8::HandleScope handle_scope(isolate); - gin::ContextHolder context_holder(isolate); - context_holder.SetContext(v8::Context::New(isolate)); + ExtensionSet extensions; + ExtensionIdSet active_extensions; + ScriptContextSet context_set(&extensions, &active_extensions); blink::WebView* webview = blink::WebView::create(nullptr); - blink::WebFrame* frame = blink::WebLocalFrame::create(nullptr); + blink::WebLocalFrame* frame = blink::WebLocalFrame::create(nullptr); webview->setMainFrame(frame); - const Extension* extension = NULL; - ScriptContext* context = - new ScriptContext(context_holder.context(), - frame, - extension, - Feature::BLESSED_EXTENSION_CONTEXT, - extension, - Feature::BLESSED_EXTENSION_CONTEXT); + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::HandleScope handle_scope(isolate); + // Note: ScriptContext has gin stuff in it, and without a ContextHolder tests + // will leak memory. + gin::ContextHolder context_holder(isolate); + v8::Handle<v8::Context> v8_context = v8::Context::New(isolate); + v8::Context::Scope context_scope(v8_context); + ScriptContext* context = context_set.Register( + frame, v8_context, 0, 0); // no extension group or world ID - context_set.Add(context); - EXPECT_EQ(1u, context_set.GetAll().count(context)); - EXPECT_EQ(context, context_set.GetByV8Context(context->v8_context())); + // Context is valid and resembles correctness. + EXPECT_TRUE(context->is_valid()); + EXPECT_EQ(frame, context->web_frame()); + EXPECT_EQ(v8_context, context->v8_context()); - // Adding the same item multiple times should be OK and deduped. - context_set.Add(context); - EXPECT_EQ(1u, context_set.GetAll().count(context)); + // Context has been correctly added. + EXPECT_EQ(1u, context_set.size()); + EXPECT_EQ(context, context_set.GetByV8Context(v8_context)); - // GetAll() returns a copy so removing from one should not remove from others. - ScriptContextSet::ContextSet set_copy = context_set.GetAll(); - EXPECT_EQ(1u, set_copy.count(context)); - + // Test context is correctly removed. context_set.Remove(context); - EXPECT_EQ(0, context_set.size()); - EXPECT_FALSE(context_set.GetByV8Context(context->v8_context())); - EXPECT_EQ(1u, set_copy.size()); + EXPECT_EQ(0u, context_set.size()); + EXPECT_EQ(nullptr, context_set.GetByV8Context(v8_context)); - // After removal, the context should be marked for destruction. - EXPECT_FALSE(context->web_frame()); + // After removal, the context should be invalid. + EXPECT_FALSE(context->is_valid()); + EXPECT_EQ(nullptr, context->web_frame()); // Run loop to do the actual deletion. loop.RunUntilIdle();
diff --git a/extensions/shell/common/shell_extensions_client.cc b/extensions/shell/common/shell_extensions_client.cc index 53476c4..072ebb1 100644 --- a/extensions/shell/common/shell_extensions_client.cc +++ b/extensions/shell/common/shell_extensions_client.cc
@@ -42,10 +42,16 @@ ~ShellPermissionMessageProvider() override {} // PermissionMessageProvider implementation. - PermissionMessages GetPermissionMessages( + PermissionMessageStrings GetPermissionMessageStrings( const PermissionSet* permissions, Manifest::Type extension_type) const override { - return PermissionMessages(); + return PermissionMessageStrings(); + } + + PermissionMessageIDs GetLegacyPermissionMessageIDs( + const PermissionSet* permissions, + Manifest::Type extension_type) const override { + return PermissionMessageIDs(); } CoalescedPermissionMessages GetCoalescedPermissionMessages( @@ -53,13 +59,13 @@ return CoalescedPermissionMessages(); } - std::vector<base::string16> GetWarningMessages( + std::vector<base::string16> GetLegacyWarningMessages( const PermissionSet* permissions, Manifest::Type extension_type) const override { return std::vector<base::string16>(); } - std::vector<base::string16> GetWarningMessagesDetails( + std::vector<base::string16> GetLegacyWarningMessagesDetails( const PermissionSet* permissions, Manifest::Type extension_type) const override { return std::vector<base::string16>();
diff --git a/extensions/test/test_permission_message_provider.cc b/extensions/test/test_permission_message_provider.cc index d13c297..28a9112 100644 --- a/extensions/test/test_permission_message_provider.cc +++ b/extensions/test/test_permission_message_provider.cc
@@ -12,10 +12,18 @@ TestPermissionMessageProvider::~TestPermissionMessageProvider() { } -PermissionMessages TestPermissionMessageProvider::GetPermissionMessages( +PermissionMessageStrings +TestPermissionMessageProvider::GetPermissionMessageStrings( const PermissionSet* permissions, Manifest::Type extension_type) const { - return PermissionMessages(); + return PermissionMessageStrings(); +} + +PermissionMessageIDs +TestPermissionMessageProvider::GetLegacyPermissionMessageIDs( + const PermissionSet* permissions, + Manifest::Type extension_type) const { + return PermissionMessageIDs(); } CoalescedPermissionMessages @@ -24,14 +32,15 @@ return CoalescedPermissionMessages(); } -std::vector<base::string16> TestPermissionMessageProvider::GetWarningMessages( +std::vector<base::string16> +TestPermissionMessageProvider::GetLegacyWarningMessages( const PermissionSet* permissions, Manifest::Type extension_type) const { return std::vector<base::string16>(); } std::vector<base::string16> -TestPermissionMessageProvider::GetWarningMessagesDetails( +TestPermissionMessageProvider::GetLegacyWarningMessagesDetails( const PermissionSet* permissions, Manifest::Type extension_type) const { return std::vector<base::string16>();
diff --git a/extensions/test/test_permission_message_provider.h b/extensions/test/test_permission_message_provider.h index af1fa5e..6cefa22 100644 --- a/extensions/test/test_permission_message_provider.h +++ b/extensions/test/test_permission_message_provider.h
@@ -16,15 +16,18 @@ ~TestPermissionMessageProvider() override; private: - PermissionMessages GetPermissionMessages( + PermissionMessageStrings GetPermissionMessageStrings( + const PermissionSet* permissions, + Manifest::Type extension_type) const override; + PermissionMessageIDs GetLegacyPermissionMessageIDs( const PermissionSet* permissions, Manifest::Type extension_type) const override; CoalescedPermissionMessages GetCoalescedPermissionMessages( const PermissionIDSet& permissions) const override; - std::vector<base::string16> GetWarningMessages( + std::vector<base::string16> GetLegacyWarningMessages( const PermissionSet* permissions, Manifest::Type extension_type) const override; - std::vector<base::string16> GetWarningMessagesDetails( + std::vector<base::string16> GetLegacyWarningMessagesDetails( const PermissionSet* permissions, Manifest::Type extension_type) const override; bool IsPrivilegeIncrease(const PermissionSet* old_permissions,
diff --git a/google_apis/gcm/tools/mcs_probe.cc b/google_apis/gcm/tools/mcs_probe.cc index 7eea9a6..e4be29ad 100644 --- a/google_apis/gcm/tools/mcs_probe.cc +++ b/google_apis/gcm/tools/mcs_probe.cc
@@ -13,6 +13,7 @@ #include "base/at_exit.h" #include "base/command_line.h" #include "base/compiler_specific.h" +#include "base/files/scoped_file.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" @@ -278,6 +279,8 @@ } MCSProbe::~MCSProbe() { + if (logger_) + logger_->StopObserving(nullptr); file_thread_.Stop(); } @@ -345,20 +348,19 @@ } void MCSProbe::InitializeNetworkState() { - FILE* log_file = NULL; + base::ScopedFILE log_file; if (command_line_.HasSwitch(kLogFileSwitch)) { base::FilePath log_path = command_line_.GetSwitchValuePath(kLogFileSwitch); #if defined(OS_WIN) - log_file = _wfopen(log_path.value().c_str(), L"w"); + log_file.reset(_wfopen(log_path.value().c_str(), L"w")); #elif defined(OS_POSIX) - log_file = fopen(log_path.value().c_str(), "w"); + log_file.reset(fopen(log_path.value().c_str(), "w")); #endif } - if (log_file != NULL) { - scoped_ptr<base::Value> net_constants(net::NetLogLogger::GetConstants()); - logger_.reset(new net::NetLogLogger(log_file, *net_constants)); + if (log_file.get()) { + logger_.reset(new net::NetLogLogger()); logger_->set_log_level(net::NetLog::LOG_ALL_BUT_BYTES); - logger_->StartObserving(&net_log_); + logger_->StartObserving(&net_log_, log_file.Pass(), nullptr, nullptr); } host_resolver_ = net::HostResolver::CreateDefaultResolver(&net_log_);
diff --git a/ios/web/public/web_client.h b/ios/web/public/web_client.h index d4bd2b0..e8ac0c8 100644 --- a/ios/web/public/web_client.h +++ b/ios/web/public/web_client.h
@@ -72,7 +72,7 @@ // browser would return true for "chrome://about" URL. virtual bool IsAppSpecificURL(const GURL& url) const; - // Returns text to be displayed for an unsupported plug-in. + // Returns text to be displayed for an unsupported plugin. virtual base::string16 GetPluginNotSupportedText() const; // Returns a string describing the embedder product name and version, of the
diff --git a/media/video/capture/mac/video_capture_device_mac.mm b/media/video/capture/mac/video_capture_device_mac.mm index e0bb96e..b35729d2c 100644 --- a/media/video/capture/mac/video_capture_device_mac.mm +++ b/media/video/capture/mac/video_capture_device_mac.mm
@@ -118,7 +118,7 @@ const int product_id, const io_service_t usb_device, IOUSBDeviceInterface*** device_interface) { - // Create a plug-in, i.e. a user-side controller to manipulate USB device. + // Create a plugin, i.e. a user-side controller to manipulate USB device. IOCFPlugInInterface** plugin; SInt32 score; // Unused, but required for IOCreatePlugInInterfaceForService. kern_return_t kr = @@ -133,7 +133,7 @@ } base::mac::ScopedIOPluginInterface<IOCFPlugInInterface> plugin_ref(plugin); - // Fetch the Device Interface from the plug-in. + // Fetch the Device Interface from the plugin. HRESULT res = (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), @@ -179,7 +179,7 @@ } base::mac::ScopedIOObject<io_service_t> found_interface_ref(found_interface); - // Create a user side controller (i.e. a "plug-in") for the found interface. + // Create a user side controller (i.e. a "plugin") for the found interface. SInt32 score; kr = IOCreatePlugInInterfaceForService(found_interface, kIOUSBInterfaceUserClientTypeID, @@ -198,8 +198,8 @@ static void SetAntiFlickerInVideoControlInterface( IOCFPlugInInterface** plugin_interface, const int frequency) { - // Create, the control interface for the found plug-in, and release - // the intermediate plug-in. + // Create, the control interface for the found plugin, and release + // the intermediate plugin. IOUSBInterfaceInterface** control_interface = NULL; HRESULT res = (*plugin_interface)->QueryInterface( plugin_interface,
diff --git a/mojo/services/html_viewer/BUILD.gn b/mojo/services/html_viewer/BUILD.gn index 4a8d4091..b649ae39b 100644 --- a/mojo/services/html_viewer/BUILD.gn +++ b/mojo/services/html_viewer/BUILD.gn
@@ -110,13 +110,65 @@ ] } -mojo_native_application("html_viewer") { - sources = [ - "html_viewer.cc", - ] - deps = [ - ":lib", - ] +if (is_android) { + import("//build/config/android/rules.gni") + + java_library_path = "$target_out_dir/java_library.dex.jar" + + mojo_android_application("html_viewer") { + input_so = "$root_out_dir/lib.stripped/libhtml_viewer_lib.so" + input_dex_jar = java_library_path + } + + shared_library("html_viewer_lib") { + sources = [ + "android/android_hooks.cc", + "html_viewer.cc", + ] + + deps = [ + ":html_viewer_jni_headers", + ":lib", + "//base", + "//ui/gfx:gfx_jni_headers", + ] + } + + generate_jni("html_viewer_jni_headers") { + sources = [ + "android/java/org/chromium/html_viewer/Main.java", + ] + jni_package = "mojo/services/html_viewer" + } + + android_library("html_viewer_java_classes") { + java_files = [ "android/java/org/chromium/html_viewer/Main.java" ] + + deps = [ + "//base:base_java", + ] + } + + android_standalone_library("java_library") { + dex_path = java_library_path + + deps = [ + ":html_viewer_java_classes", + + # TODO(sky): this is WAY more than we need. We really only need + # DeviceDisplayInfo. Refactor to make this clearer. + "//ui/android:ui_java", + ] + } +} else { + mojo_native_application("html_viewer") { + sources = [ + "html_viewer.cc", + ] + deps = [ + ":lib", + ] + } } test("tests") {
diff --git a/mojo/services/html_viewer/android/android_hooks.cc b/mojo/services/html_viewer/android/android_hooks.cc new file mode 100644 index 0000000..a1a29d2 --- /dev/null +++ b/mojo/services/html_viewer/android/android_hooks.cc
@@ -0,0 +1,49 @@ +// 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 <vector> + +#include "base/android/base_jni_onload.h" +#include "base/android/jni_android.h" +#include "base/android/library_loader/library_loader_hooks.h" +#include "base/bind.h" +#include "mojo/services/html_viewer/jni/Main_jni.h" + +namespace { +bool RegisterJNI(JNIEnv* env) { + return true; +} + +bool Init() { + Java_Main_init(base::android::AttachCurrentThread()); + return true; +} +} // namespace + +// This is called by the VM when the shared library is first loaded. +JNI_EXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { + std::vector<base::android::RegisterCallback> register_callbacks; + register_callbacks.push_back(base::Bind(&RegisterJNI)); + register_callbacks.push_back(base::Bind(&RegisterNativesImpl)); + + std::vector<base::android::InitCallback> init_callbacks; + init_callbacks.push_back(base::Bind(&Init)); + + if (!base::android::OnJNIOnLoadRegisterJNI(vm, register_callbacks) || + !base::android::OnJNIOnLoadInit(init_callbacks)) { + return -1; + } + + // There cannot be two AtExitManagers at the same time. Remove the one from + // LibraryLoader as ApplicationRunnerChromium also uses one. + base::android::LibraryLoaderExitHook(); + + return JNI_VERSION_1_4; +} + +extern "C" JNI_EXPORT void InitApplicationContext( + const base::android::JavaRef<jobject>& context) { + JNIEnv* env = base::android::AttachCurrentThread(); + base::android::InitApplicationContext(env, context); +}
diff --git a/mojo/services/html_viewer/android/java/org/chromium/html_viewer/Main.java b/mojo/services/html_viewer/android/java/org/chromium/html_viewer/Main.java new file mode 100644 index 0000000..283029d1 --- /dev/null +++ b/mojo/services/html_viewer/android/java/org/chromium/html_viewer/Main.java
@@ -0,0 +1,23 @@ +// 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. + +package org.chromium.html_viewer; + +import org.chromium.base.CalledByNative; +import org.chromium.base.PathUtils; + +/** + * This class does setup for html_viewer. + */ +public final class Main { + private static final String PRIVATE_DATA_DIRECTORY_SUFFIX = "html_viewer"; + + private Main() {} + + @SuppressWarnings("unused") + @CalledByNative + private static void init() { + PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX); + } +}
diff --git a/mojo/services/html_viewer/blink_platform_impl.cc b/mojo/services/html_viewer/blink_platform_impl.cc index e94e70ac2..270fc75 100644 --- a/mojo/services/html_viewer/blink_platform_impl.cc +++ b/mojo/services/html_viewer/blink_platform_impl.cc
@@ -159,7 +159,7 @@ return blink::WebData(data, length); } } - NOTREACHED() << "Requested resource is unavailable!"; + NOTREACHED() << "Requested resource is unavailable: " << resource; return blink::WebData(); }
diff --git a/mojo/services/html_viewer/html_viewer.cc b/mojo/services/html_viewer/html_viewer.cc index b4354e4..8c71a9f3 100644 --- a/mojo/services/html_viewer/html_viewer.cc +++ b/mojo/services/html_viewer/html_viewer.cc
@@ -170,6 +170,7 @@ void Initialize(mojo::ApplicationImpl* app) override { blink_platform_.reset(new MojoBlinkPlatformImpl(app)); #if defined(V8_USE_EXTERNAL_STARTUP_DATA) + // Note: this requires file system access. gin::IsolateHolder::LoadV8Snapshot(); #endif blink::initialize(blink_platform_.get()); @@ -199,6 +200,8 @@ is_headless_ = command_line->HasSwitch(kIsHeadless); if (!is_headless_) { + // TODO(sky): consider putting this into the .so so that we don't need + // file system access. base::FilePath ui_test_pak_path; CHECK(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
diff --git a/net/base/net_log_logger.cc b/net/base/net_log_logger.cc index bb0331b..9b46ab1 100644 --- a/net/base/net_log_logger.cc +++ b/net/base/net_log_logger.cc
@@ -6,32 +6,22 @@ #include <stdio.h> +#include <set> + #include "base/json/json_writer.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/values.h" #include "net/base/net_log_util.h" +#include "net/url_request/url_request_context.h" namespace net { -NetLogLogger::NetLogLogger(FILE* file, const base::Value& constants) - : file_(file), - log_level_(NetLog::LOG_STRIP_PRIVATE_DATA), - added_events_(false) { - DCHECK(file); - - // Write constants to the output file. This allows loading files that have - // different source and event types, as they may be added and removed - // between Chrome versions. - std::string json; - base::JSONWriter::Write(&constants, &json); - fprintf(file_.get(), "{\"constants\": %s,\n", json.c_str()); - fprintf(file_.get(), "\"events\": [\n"); +NetLogLogger::NetLogLogger() + : log_level_(NetLog::LOG_STRIP_PRIVATE_DATA), added_events_(false) { } NetLogLogger::~NetLogLogger() { - if (file_.get()) - fprintf(file_.get(), "]}"); } void NetLogLogger::set_log_level(net::NetLog::LogLevel log_level) { @@ -39,12 +29,60 @@ log_level_ = log_level; } -void NetLogLogger::StartObserving(net::NetLog* net_log) { +void NetLogLogger::StartObserving(net::NetLog* net_log, + base::ScopedFILE file, + base::Value* constants, + net::URLRequestContext* url_request_context) { + DCHECK(file.get()); + file_ = file.Pass(); + added_events_ = false; + + // Write constants to the output file. This allows loading files that have + // different source and event types, as they may be added and removed + // between Chrome versions. + std::string json; + if (constants) { + base::JSONWriter::Write(constants, &json); + } else { + scoped_ptr<base::DictionaryValue> scoped_constants(GetNetConstants()); + base::JSONWriter::Write(scoped_constants.get(), &json); + } + fprintf(file_.get(), "{\"constants\": %s,\n", json.c_str()); + + // Start events array. It's closed in StopObserving(). + fprintf(file_.get(), "\"events\": [\n"); + + // Add events for in progress requests if a context is given. + if (url_request_context) { + DCHECK(url_request_context->CalledOnValidThread()); + + std::set<URLRequestContext*> contexts; + contexts.insert(url_request_context); + CreateNetLogEntriesForActiveObjects(contexts, this); + } + net_log->AddThreadSafeObserver(this, log_level_); } -void NetLogLogger::StopObserving() { +void NetLogLogger::StopObserving(net::URLRequestContext* url_request_context) { net_log()->RemoveThreadSafeObserver(this); + + // End events array. + fprintf(file_.get(), "]"); + + // Write state of the URLRequestContext when logging stopped. + if (url_request_context) { + DCHECK(url_request_context->CalledOnValidThread()); + + std::string json; + scoped_ptr<base::DictionaryValue> net_info = + GetNetInfo(url_request_context, NET_INFO_ALL_SOURCES); + base::JSONWriter::Write(net_info.get(), &json); + fprintf(file_.get(), ",\"tabInfo\": %s\n", json.c_str()); + } + fprintf(file_.get(), "}"); + + file_.reset(); } void NetLogLogger::OnAddEntry(const net::NetLog::Entry& entry) { @@ -60,9 +98,4 @@ added_events_ = true; } -// static -base::DictionaryValue* NetLogLogger::GetConstants() { - return GetNetConstants().release(); -} - } // namespace net
diff --git a/net/base/net_log_logger.h b/net/base/net_log_logger.h index ede3ca4..79a45d8 100644 --- a/net/base/net_log_logger.h +++ b/net/base/net_log_logger.h
@@ -9,6 +9,7 @@ #include "base/files/scoped_file.h" #include "base/macros.h" +#include "base/memory/ref_counted.h" #include "net/base/net_log.h" namespace base { @@ -19,38 +20,48 @@ namespace net { +class URLRequestContext; + // NetLogLogger watches the NetLog event stream, and sends all entries to // a file specified on creation. // // The text file will contain a single JSON object. class NET_EXPORT NetLogLogger : public NetLog::ThreadSafeObserver { public: - // Takes ownership of |file| and will write network events to it once logging - // starts. |file| must be non-NULL handle and be open for writing. - // |constants| is a legend for decoding constant values used in the log. - NetLogLogger(FILE* file, const base::Value& constants); + NetLogLogger(); ~NetLogLogger() override; // Sets the log level to log at. Must be called before StartObserving. void set_log_level(NetLog::LogLevel log_level); - // Starts observing specified NetLog. Must not already be watching a NetLog. - // Separate from constructor to enforce thread safety. - void StartObserving(NetLog* net_log); + // Starts observing |net_log| and writes output to |file|. Must not already + // be watching a NetLog. Separate from constructor to enforce thread safety. + // + // |file| must be a non-NULL empty file that's open for writing. + // + // |constants| is an optional legend for decoding constant values used in the + // log. It should generally be a modified version of GetNetConstants(). If + // not present, the output of GetNetConstants() will be used. + // + // |url_request_context| is an optional URLRequestContext that will be used to + // pre-populate the log with information about in-progress events. + // If the context is non-NULL, this must be called on the context's thread. + void StartObserving(NetLog* net_log, + base::ScopedFILE file, + base::Value* constants, + net::URLRequestContext* url_request_context); - // Stops observing net_log(). Must already be watching. - void StopObserving(); + // Stops observing net_log(). Must already be watching. Must be called + // before destruction of the NetLogLogger and the NetLog. + // + // |url_request_context| is an optional argument used to added additional + // network stack state to the log. If the context is non-NULL, this must be + // called on the context's thread. + void StopObserving(net::URLRequestContext* url_request_context); // net::NetLog::ThreadSafeObserver implementation: void OnAddEntry(const NetLog::Entry& entry) override; - // Create a dictionary containing legend for net/ constants. Caller takes - // ownership of returned value. - // TODO(mmenke): Get rid of this, and have embedders use GetNetConstants - // directly. Also maybe call that function by default, so only embedders - // that need more constants need to worry about it. - static base::DictionaryValue* GetConstants(); - private: base::ScopedFILE file_;
diff --git a/net/base/net_log_logger_unittest.cc b/net/base/net_log_logger_unittest.cc index 16fea58..f66a3da4 100644 --- a/net/base/net_log_logger_unittest.cc +++ b/net/base/net_log_logger_unittest.cc
@@ -6,11 +6,16 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/files/scoped_file.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_reader.h" +#include "base/memory/scoped_ptr.h" #include "base/values.h" #include "net/base/net_log.h" #include "net/base/net_log_util.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { @@ -27,14 +32,16 @@ protected: base::ScopedTempDir temp_dir_; base::FilePath log_path_; + NetLog net_log_; }; TEST_F(NetLogLoggerTest, GeneratesValidJSONForNoEvents) { // Create and destroy a logger. - FILE* file = base::OpenFile(log_path_, "w"); + base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<base::Value> constants(GetNetConstants()); - scoped_ptr<NetLogLogger> logger(new NetLogLogger(file, *constants)); + scoped_ptr<NetLogLogger> logger(new NetLogLogger()); + logger->StartObserving(&net_log_, file.Pass(), nullptr, nullptr); + logger->StopObserving(nullptr); logger.reset(); std::string input; @@ -49,33 +56,34 @@ base::ListValue* events; ASSERT_TRUE(dict->GetList("events", &events)); ASSERT_EQ(0u, events->GetSize()); + + base::DictionaryValue* constants; + ASSERT_TRUE(dict->GetDictionary("constants", &constants)); } -// Make sure the log level is LOG_STRIP_PRIVATE_DATA by default. TEST_F(NetLogLoggerTest, LogLevel) { - FILE* file = base::OpenFile(log_path_, "w"); + base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<base::Value> constants(GetNetConstants()); - NetLogLogger logger(file, *constants); - - NetLog net_log; - logger.StartObserving(&net_log); + NetLogLogger logger; + logger.StartObserving(&net_log_, file.Pass(), nullptr, nullptr); EXPECT_EQ(NetLog::LOG_STRIP_PRIVATE_DATA, logger.log_level()); - EXPECT_EQ(NetLog::LOG_STRIP_PRIVATE_DATA, net_log.GetLogLevel()); - logger.StopObserving(); + EXPECT_EQ(NetLog::LOG_STRIP_PRIVATE_DATA, net_log_.GetLogLevel()); + logger.StopObserving(nullptr); + file.reset(base::OpenFile(log_path_, "w")); + ASSERT_TRUE(file); logger.set_log_level(NetLog::LOG_ALL_BUT_BYTES); - logger.StartObserving(&net_log); + logger.StartObserving(&net_log_, file.Pass(), nullptr, nullptr); EXPECT_EQ(NetLog::LOG_ALL_BUT_BYTES, logger.log_level()); - EXPECT_EQ(NetLog::LOG_ALL_BUT_BYTES, net_log.GetLogLevel()); - logger.StopObserving(); + EXPECT_EQ(NetLog::LOG_ALL_BUT_BYTES, net_log_.GetLogLevel()); + logger.StopObserving(nullptr); } TEST_F(NetLogLoggerTest, GeneratesValidJSONWithOneEvent) { - FILE* file = base::OpenFile(log_path_, "w"); + base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<base::Value> constants(GetNetConstants()); - scoped_ptr<NetLogLogger> logger(new NetLogLogger(file, *constants)); + scoped_ptr<NetLogLogger> logger(new NetLogLogger()); + logger->StartObserving(&net_log_, file.Pass(), nullptr, nullptr); const int kDummyId = 1; NetLog::Source source(NetLog::SOURCE_HTTP2_SESSION, kDummyId); @@ -86,6 +94,7 @@ NULL); NetLog::Entry entry(&entry_data, NetLog::LOG_ALL); logger->OnAddEntry(entry); + logger->StopObserving(nullptr); logger.reset(); std::string input; @@ -103,10 +112,10 @@ } TEST_F(NetLogLoggerTest, GeneratesValidJSONWithMultipleEvents) { - FILE* file = base::OpenFile(log_path_, "w"); + base::ScopedFILE file(base::OpenFile(log_path_, "w")); ASSERT_TRUE(file); - scoped_ptr<base::Value> constants(GetNetConstants()); - scoped_ptr<NetLogLogger> logger(new NetLogLogger(file, *constants)); + scoped_ptr<NetLogLogger> logger(new NetLogLogger()); + logger->StartObserving(&net_log_, file.Pass(), nullptr, nullptr); const int kDummyId = 1; NetLog::Source source(NetLog::SOURCE_HTTP2_SESSION, kDummyId); @@ -120,6 +129,7 @@ // Add the entry multiple times. logger->OnAddEntry(entry); logger->OnAddEntry(entry); + logger->StopObserving(nullptr); logger.reset(); std::string input; @@ -136,6 +146,100 @@ ASSERT_EQ(2u, events->GetSize()); } +TEST_F(NetLogLoggerTest, CustomConstants) { + const char kConstantString[] = "awesome constant"; + scoped_ptr<base::Value> constants(new base::StringValue(kConstantString)); + base::ScopedFILE file(base::OpenFile(log_path_, "w")); + ASSERT_TRUE(file); + scoped_ptr<NetLogLogger> logger(new NetLogLogger()); + logger->StartObserving(&net_log_, file.Pass(), constants.get(), nullptr); + logger->StopObserving(nullptr); + logger.reset(); + + std::string input; + ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); + + base::JSONReader reader; + scoped_ptr<base::Value> root(reader.ReadToValue(input)); + ASSERT_TRUE(root) << reader.GetErrorMessage(); + + base::DictionaryValue* dict; + ASSERT_TRUE(root->GetAsDictionary(&dict)); + std::string constants_string; + ASSERT_TRUE(dict->GetString("constants", &constants_string)); + ASSERT_EQ(kConstantString, constants_string); +} + +TEST_F(NetLogLoggerTest, GeneratesValidJSONWithContext) { + // Create context, start a request. + TestURLRequestContext context(true); + context.set_net_log(&net_log_); + context.Init(); + + // Create and destroy a logger. + base::ScopedFILE file(base::OpenFile(log_path_, "w")); + ASSERT_TRUE(file); + scoped_ptr<NetLogLogger> logger(new NetLogLogger()); + logger->StartObserving(&net_log_, file.Pass(), nullptr, &context); + logger->StopObserving(&context); + logger.reset(); + + std::string input; + ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); + + base::JSONReader reader; + scoped_ptr<base::Value> root(reader.ReadToValue(input)); + ASSERT_TRUE(root) << reader.GetErrorMessage(); + + base::DictionaryValue* dict; + ASSERT_TRUE(root->GetAsDictionary(&dict)); + base::ListValue* events; + ASSERT_TRUE(dict->GetList("events", &events)); + ASSERT_EQ(0u, events->GetSize()); + + // Make sure additional information is present, but don't validate it. + base::DictionaryValue* tab_info; + ASSERT_TRUE(dict->GetDictionary("tabInfo", &tab_info)); +} + +TEST_F(NetLogLoggerTest, GeneratesValidJSONWithContextWithActiveRequest) { + // Create context, start a request. + TestURLRequestContext context(true); + context.set_net_log(&net_log_); + context.Init(); + TestDelegate delegate; + + // URL doesn't matter. Requests can't fail synchronously. + scoped_ptr<URLRequest> request( + context.CreateRequest(GURL("blah:blah"), IDLE, &delegate, nullptr)); + request->Start(); + + // Create and destroy a logger. + base::ScopedFILE file(base::OpenFile(log_path_, "w")); + ASSERT_TRUE(file); + scoped_ptr<NetLogLogger> logger(new NetLogLogger()); + logger->StartObserving(&net_log_, file.Pass(), nullptr, &context); + logger->StopObserving(&context); + logger.reset(); + + std::string input; + ASSERT_TRUE(base::ReadFileToString(log_path_, &input)); + + base::JSONReader reader; + scoped_ptr<base::Value> root(reader.ReadToValue(input)); + ASSERT_TRUE(root) << reader.GetErrorMessage(); + + base::DictionaryValue* dict; + ASSERT_TRUE(root->GetAsDictionary(&dict)); + base::ListValue* events; + ASSERT_TRUE(dict->GetList("events", &events)); + ASSERT_EQ(1u, events->GetSize()); + + // Make sure additional information is present, but don't validate it. + base::DictionaryValue* tab_info; + ASSERT_TRUE(dict->GetDictionary("tabInfo", &tab_info)); +} + } // namespace } // namespace net
diff --git a/net/data/websocket/trailing-whitespace_wsh.py b/net/data/websocket/trailing-whitespace_wsh.py new file mode 100644 index 0000000..1e65155 --- /dev/null +++ b/net/data/websocket/trailing-whitespace_wsh.py
@@ -0,0 +1,27 @@ +# 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. +# +# The purpose of this test is to verify that the WebSocket handshake correctly +# ignores trailing whitespace on response headers. +# It is used by test case WebSocketEndToEndTest.TrailingWhitespace. + +from mod_pywebsocket import handshake +from mod_pywebsocket.handshake.hybi import compute_accept + + +def web_socket_do_extra_handshake(request): + accept = compute_accept(request.headers_in['Sec-WebSocket-Key'])[0] + message = ('HTTP/1.1 101 Switching Protocols\r\n' + 'Upgrade: websocket\r\n' + 'Connection: Upgrade\r\n' + 'Sec-WebSocket-Accept: %s\r\n' + 'Sec-WebSocket-Protocol: sip \r\n' + '\r\n' % accept) + request.connection.write(message) + # Prevent pywebsocket from sending its own handshake message. + raise handshake.AbortedByUserException('Close the connection') + + +def web_socket_transfer_data(request): + pass
diff --git a/net/http/http_network_session.cc b/net/http/http_network_session.cc index d6aa6e2..8085641 100644 --- a/net/http/http_network_session.cc +++ b/net/http/http_network_session.cc
@@ -45,8 +45,7 @@ params.host_resolver, params.cert_verifier, params.channel_id_service, params.transport_security_state, params.cert_transparency_verifier, params.cert_policy_enforcer, params.ssl_session_cache_shard, - params.ssl_config_service, params.enable_ssl_connect_job_waiting, - pool_type); + params.ssl_config_service, pool_type); } } // unnamed namespace @@ -67,7 +66,6 @@ network_delegate(NULL), net_log(NULL), host_mapping_rules(NULL), - enable_ssl_connect_job_waiting(false), ignore_certificate_errors(false), use_stale_while_revalidate(false), testing_fixed_http_port(0),
diff --git a/net/http/http_network_session.h b/net/http/http_network_session.h index 07a3546..e46ffc9 100644 --- a/net/http/http_network_session.h +++ b/net/http/http_network_session.h
@@ -79,7 +79,6 @@ base::WeakPtr<HttpServerProperties> http_server_properties; NetLog* net_log; HostMappingRules* host_mapping_rules; - bool enable_ssl_connect_job_waiting; bool ignore_certificate_errors; bool use_stale_while_revalidate; uint16 testing_fixed_http_port;
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index aa169748..105b30db 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -601,7 +601,6 @@ NULL, NULL, NULL, - false, NULL) { }
diff --git a/net/http/http_proxy_client_socket_pool_unittest.cc b/net/http/http_proxy_client_socket_pool_unittest.cc index fd6de0c..acff27b 100644 --- a/net/http/http_proxy_client_socket_pool_unittest.cc +++ b/net/http/http_proxy_client_socket_pool_unittest.cc
@@ -177,7 +177,6 @@ NULL, NULL, session_deps_.ssl_config_service.get(), - false, BoundNetLog().net_log()), session_(CreateNetworkSession()), http_proxy_histograms_("HttpProxyUnitTest"),
diff --git a/net/http/http_stream_factory_impl_unittest.cc b/net/http/http_stream_factory_impl_unittest.cc index 8f71595..fd8d350 100644 --- a/net/http/http_stream_factory_impl_unittest.cc +++ b/net/http/http_stream_factory_impl_unittest.cc
@@ -413,7 +413,6 @@ nullptr, nullptr, nullptr, // ssl_config_service - false, // enable_ssl_connect_job_waiting nullptr), // net_log last_num_streams_(-1) { }
diff --git a/net/net.gypi b/net/net.gypi index d8f93d0..5a3cc76 100644 --- a/net/net.gypi +++ b/net/net.gypi
@@ -757,6 +757,8 @@ 'proxy/proxy_service.h', 'quic/congestion_control/cubic.cc', 'quic/congestion_control/cubic.h', + 'quic/congestion_control/cubic_bytes.cc', + 'quic/congestion_control/cubic_bytes.h', 'quic/congestion_control/hybrid_slow_start.cc', 'quic/congestion_control/hybrid_slow_start.h', 'quic/congestion_control/loss_detection_interface.cc', @@ -769,6 +771,8 @@ 'quic/congestion_control/rtt_stats.h', 'quic/congestion_control/send_algorithm_interface.cc', 'quic/congestion_control/send_algorithm_interface.h', + 'quic/congestion_control/tcp_cubic_bytes_sender.cc', + 'quic/congestion_control/tcp_cubic_bytes_sender.h', 'quic/congestion_control/tcp_cubic_sender.cc', 'quic/congestion_control/tcp_cubic_sender.h', 'quic/congestion_control/tcp_loss_algorithm.cc', @@ -1455,6 +1459,7 @@ 'proxy/proxy_server_unittest.cc', 'proxy/proxy_service_mojo_unittest.cc', 'proxy/proxy_service_unittest.cc', + 'quic/congestion_control/cubic_bytes_test.cc', 'quic/congestion_control/cubic_test.cc', 'quic/congestion_control/hybrid_slow_start_test.cc', 'quic/congestion_control/pacing_sender_test.cc', @@ -1462,6 +1467,7 @@ 'quic/congestion_control/rtt_stats_test.cc', 'quic/congestion_control/send_algorithm_simulator.cc', 'quic/congestion_control/send_algorithm_simulator.h', + 'quic/congestion_control/tcp_cubic_bytes_sender_test.cc', 'quic/congestion_control/tcp_cubic_sender_test.cc', 'quic/congestion_control/tcp_loss_algorithm_test.cc', 'quic/congestion_control/time_loss_algorithm_test.cc',
diff --git a/net/quic/congestion_control/cubic_bytes.cc b/net/quic/congestion_control/cubic_bytes.cc new file mode 100644 index 0000000..77e90f4 --- /dev/null +++ b/net/quic/congestion_control/cubic_bytes.cc
@@ -0,0 +1,163 @@ +// Copyright (c) 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 "net/quic/congestion_control/cubic_bytes.h" + +#include <algorithm> +#include <cmath> + +#include "base/basictypes.h" +#include "base/logging.h" +#include "net/quic/quic_protocol.h" + +using std::max; + +namespace net { + +namespace { + +// Constants based on TCP defaults. +// The following constants are in 2^10 fractions of a second instead of ms to +// allow a 10 shift right to divide. +const int kCubeScale = 40; // 1024*1024^3 (first 1024 is from 0.100^3) + // where 0.100 is 100 ms which is the scaling + // round trip time. +const int kCubeCongestionWindowScale = 410; +// The cube factor for packets in bytes. +const uint64 kCubeFactor = (GG_UINT64_C(1) << kCubeScale) / + kCubeCongestionWindowScale / kDefaultTCPMSS; + +const uint32 kDefaultNumConnections = 2; +const float kBeta = 0.7f; // Default Cubic backoff factor. +// Additional backoff factor when loss occurs in the concave part of the Cubic +// curve. This additional backoff factor is expected to give up bandwidth to +// new concurrent flows and speed up convergence. +const float kBetaLastMax = 0.85f; + +} // namespace + +CubicBytes::CubicBytes(const QuicClock* clock) + : clock_(clock), + num_connections_(kDefaultNumConnections), + epoch_(QuicTime::Zero()), + last_update_time_(QuicTime::Zero()) { + Reset(); +} + +void CubicBytes::SetNumConnections(int num_connections) { + num_connections_ = num_connections; +} + +float CubicBytes::Alpha() const { + // TCPFriendly alpha is described in Section 3.3 of the CUBIC paper. Note that + // beta here is a cwnd multiplier, and is equal to 1-beta from the paper. + // We derive the equivalent alpha for an N-connection emulation as: + const float beta = Beta(); + return 3 * num_connections_ * num_connections_ * (1 - beta) / (1 + beta); +} + +float CubicBytes::Beta() const { + // kNConnectionBeta is the backoff factor after loss for our N-connection + // emulation, which emulates the effective backoff of an ensemble of N + // TCP-Reno connections on a single loss event. The effective multiplier is + // computed as: + return (num_connections_ - 1 + kBeta) / num_connections_; +} + +void CubicBytes::Reset() { + epoch_ = QuicTime::Zero(); // Reset time. + last_update_time_ = QuicTime::Zero(); // Reset time. + last_congestion_window_ = 0; + last_max_congestion_window_ = 0; + acked_bytes_count_ = 0; + estimated_tcp_congestion_window_ = 0; + origin_point_congestion_window_ = 0; + time_to_origin_point_ = 0; + last_target_congestion_window_ = 0; +} + +QuicByteCount CubicBytes::CongestionWindowAfterPacketLoss( + QuicByteCount current_congestion_window) { + if (current_congestion_window < last_max_congestion_window_) { + // We never reached the old max, so assume we are competing with another + // flow. Use our extra back off factor to allow the other flow to go up. + last_max_congestion_window_ = + static_cast<int>(kBetaLastMax * current_congestion_window); + } else { + last_max_congestion_window_ = current_congestion_window; + } + epoch_ = QuicTime::Zero(); // Reset time. + return static_cast<int>(current_congestion_window * Beta()); +} + +QuicByteCount CubicBytes::CongestionWindowAfterAck( + QuicByteCount acked_bytes, + QuicByteCount current_congestion_window, + QuicTime::Delta delay_min) { + acked_bytes_count_ += acked_bytes; + QuicTime current_time = clock_->ApproximateNow(); + + // Cubic is "independent" of RTT, the update is limited by the time elapsed. + if (last_congestion_window_ == current_congestion_window && + (current_time.Subtract(last_update_time_) <= MaxCubicTimeInterval())) { + return max(last_target_congestion_window_, + estimated_tcp_congestion_window_); + } + last_congestion_window_ = current_congestion_window; + last_update_time_ = current_time; + + if (!epoch_.IsInitialized()) { + // First ACK after a loss event. + DVLOG(1) << "Start of epoch"; + epoch_ = current_time; // Start of epoch. + acked_bytes_count_ = acked_bytes; // Reset count. + // Reset estimated_tcp_congestion_window_ to be in sync with cubic. + estimated_tcp_congestion_window_ = current_congestion_window; + if (last_max_congestion_window_ <= current_congestion_window) { + time_to_origin_point_ = 0; + origin_point_congestion_window_ = current_congestion_window; + } else { + time_to_origin_point_ = + static_cast<uint32>(cbrt(kCubeFactor * (last_max_congestion_window_ - + current_congestion_window))); + origin_point_congestion_window_ = last_max_congestion_window_; + } + } + // Change the time unit from microseconds to 2^10 fractions per second. Take + // the round trip time in account. This is done to allow us to use shift as a + // divide operator. + int64 elapsed_time = + (current_time.Add(delay_min).Subtract(epoch_).ToMicroseconds() << 10) / + kNumMicrosPerSecond; + + int64 offset = time_to_origin_point_ - elapsed_time; + QuicByteCount delta_congestion_window = + ((kCubeCongestionWindowScale * offset * offset * offset) >> kCubeScale) * + kDefaultTCPMSS; + + QuicByteCount target_congestion_window = + origin_point_congestion_window_ - delta_congestion_window; + + DCHECK_LT(0u, estimated_tcp_congestion_window_); + // Increase the window by Alpha * 1 MSS of bytes every time we ack an + // estimated tcp window of bytes. + estimated_tcp_congestion_window_ += acked_bytes_count_ * + (Alpha() * kDefaultTCPMSS) / + estimated_tcp_congestion_window_; + acked_bytes_count_ = 0; + + // We have a new cubic congestion window. + last_target_congestion_window_ = target_congestion_window; + + // Compute target congestion_window based on cubic target and estimated TCP + // congestion_window, use highest (fastest). + if (target_congestion_window < estimated_tcp_congestion_window_) { + target_congestion_window = estimated_tcp_congestion_window_; + } + + DVLOG(1) << "Target congestion_window: " << target_congestion_window; + return target_congestion_window; +} + +} // namespace net
diff --git a/net/quic/congestion_control/cubic_bytes.h b/net/quic/congestion_control/cubic_bytes.h new file mode 100644 index 0000000..1df9f37 --- /dev/null +++ b/net/quic/congestion_control/cubic_bytes.h
@@ -0,0 +1,91 @@ +// Copyright (c) 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. + +// Cubic algorithm, helper class to TCP cubic. +// For details see http://netsrv.csc.ncsu.edu/export/cubic_a_new_tcp_2008.pdf. + +#ifndef NET_QUIC_CONGESTION_CONTROL_CUBIC_BYTES_H_ +#define NET_QUIC_CONGESTION_CONTROL_CUBIC_BYTES_H_ + +#include "base/basictypes.h" +#include "net/base/net_export.h" +#include "net/quic/quic_bandwidth.h" +#include "net/quic/quic_clock.h" +#include "net/quic/quic_connection_stats.h" +#include "net/quic/quic_time.h" + +namespace net { + +class NET_EXPORT_PRIVATE CubicBytes { + public: + explicit CubicBytes(const QuicClock* clock); + + void SetNumConnections(int num_connections); + + // Call after a timeout to reset the cubic state. + void Reset(); + + // Compute a new congestion window to use after a loss event. + // Returns the new congestion window in packets. The new congestion window is + // a multiplicative decrease of our current window. + QuicByteCount CongestionWindowAfterPacketLoss(QuicPacketCount current); + + // Compute a new congestion window to use after a received ACK. + // Returns the new congestion window in bytes. The new congestion window + // follows a cubic function that depends on the time passed since last packet + // loss. + QuicByteCount CongestionWindowAfterAck(QuicByteCount acked_bytes, + QuicByteCount current, + QuicTime::Delta delay_min); + + private: + static const QuicTime::Delta MaxCubicTimeInterval() { + return QuicTime::Delta::FromMilliseconds(30); + } + + // Compute the TCP Cubic alpha and beta based on the current number of + // connections. + float Alpha() const; + float Beta() const; + + const QuicClock* clock_; + + // Number of connections to simulate. + int num_connections_; + + // Time when this cycle started, after last loss event. + QuicTime epoch_; + + // Time when we updated last_congestion_window. + QuicTime last_update_time_; + + // Last congestion window used. + QuicByteCount last_congestion_window_; + + // Max congestion window used just before last loss event. + // Note: to improve fairness to other streams an additional back off is + // applied to this value if the new value is below our latest value. + QuicByteCount last_max_congestion_window_; + + // Number of acked bytes since the cycle started (epoch). + QuicByteCount acked_bytes_count_; + + // TCP Reno equivalent congestion window in packets. + QuicByteCount estimated_tcp_congestion_window_; + + // Origin point of cubic function. + QuicByteCount origin_point_congestion_window_; + + // Time to origin point of cubic function in 2^10 fractions of a second. + uint32 time_to_origin_point_; + + // Last congestion window in packets computed by cubic function. + QuicByteCount last_target_congestion_window_; + + DISALLOW_COPY_AND_ASSIGN(CubicBytes); +}; + +} // namespace net + +#endif // NET_QUIC_CONGESTION_CONTROL_CUBIC_BYTES_H_
diff --git a/net/quic/congestion_control/cubic_bytes_test.cc b/net/quic/congestion_control/cubic_bytes_test.cc new file mode 100644 index 0000000..3de16510 --- /dev/null +++ b/net/quic/congestion_control/cubic_bytes_test.cc
@@ -0,0 +1,157 @@ +// Copyright (c) 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 "net/quic/congestion_control/cubic_bytes.h" + +#include "base/basictypes.h" +#include "base/logging.h" +#include "net/quic/quic_connection_stats.h" +#include "net/quic/test_tools/mock_clock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +const float kBeta = 0.7f; // Default Cubic backoff factor. +const uint32 kNumConnections = 2; +const float kNConnectionBeta = (kNumConnections - 1 + kBeta) / kNumConnections; +const float kNConnectionAlpha = 3 * kNumConnections * kNumConnections * + (1 - kNConnectionBeta) / (1 + kNConnectionBeta); + +class CubicBytesTest : public ::testing::Test { + protected: + CubicBytesTest() + : one_ms_(QuicTime::Delta::FromMilliseconds(1)), + hundred_ms_(QuicTime::Delta::FromMilliseconds(100)), + cubic_(&clock_) {} + const QuicTime::Delta one_ms_; + const QuicTime::Delta hundred_ms_; + MockClock clock_; + CubicBytes cubic_; +}; + +TEST_F(CubicBytesTest, AboveOrigin) { + // Convex growth. + const QuicTime::Delta rtt_min = hundred_ms_; + QuicByteCount current_cwnd = 10 * kDefaultTCPMSS; + QuicByteCount expected_cwnd = current_cwnd + kDefaultTCPMSS; + // Initialize the state. + clock_.AdvanceTime(one_ms_); + EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck( + kDefaultTCPMSS, current_cwnd, rtt_min)); + current_cwnd = expected_cwnd; + // Normal TCP phase. + for (int i = 0; i < 48; ++i) { + for (QuicPacketCount n = 1; + n < current_cwnd / kDefaultTCPMSS / kNConnectionAlpha; ++n) { + // Call once per ACK. + EXPECT_NEAR(current_cwnd, cubic_.CongestionWindowAfterAck( + kDefaultTCPMSS, current_cwnd, rtt_min), + kDefaultTCPMSS); + } + clock_.AdvanceTime(hundred_ms_); + current_cwnd = + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + EXPECT_NEAR(expected_cwnd, current_cwnd, kDefaultTCPMSS); + expected_cwnd += kDefaultTCPMSS; + } + // Cubic phase. + for (int i = 0; i < 52; ++i) { + for (QuicPacketCount n = 1; n < current_cwnd / kDefaultTCPMSS; ++n) { + // Call once per ACK. + EXPECT_NEAR(current_cwnd, cubic_.CongestionWindowAfterAck( + kDefaultTCPMSS, current_cwnd, rtt_min), + kDefaultTCPMSS); + } + clock_.AdvanceTime(hundred_ms_); + current_cwnd = + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + } + // Total time elapsed so far; add min_rtt (0.1s) here as well. + float elapsed_time_s = 10.0f + 0.1f; + // |expected_cwnd| is initial value of cwnd + K * t^3, where K = 0.4. + expected_cwnd = + 11 + (elapsed_time_s * elapsed_time_s * elapsed_time_s * 410) / 1024; + EXPECT_EQ(expected_cwnd, current_cwnd / kDefaultTCPMSS); +} + +TEST_F(CubicBytesTest, CwndIncreaseStatsDuringConvexRegion) { + const QuicTime::Delta rtt_min = hundred_ms_; + QuicByteCount current_cwnd = 10 * kDefaultTCPMSS; + QuicByteCount expected_cwnd = current_cwnd + kDefaultTCPMSS; + // Initialize controller state. + clock_.AdvanceTime(one_ms_); + expected_cwnd = + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + current_cwnd = expected_cwnd; + // Testing Reno mode increase. + for (int i = 0; i < 48; ++i) { + for (QuicPacketCount n = 1; + n < current_cwnd / kDefaultTCPMSS / kNConnectionAlpha; ++n) { + // Call once per ACK, causing cwnd growth in Reno mode. + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + } + // Advance current time so that cwnd update is allowed to happen by Cubic. + clock_.AdvanceTime(hundred_ms_); + current_cwnd = + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + expected_cwnd += kDefaultTCPMSS; + } + + // Testing Cubic mode increase. + for (int i = 0; i < 52; ++i) { + for (QuicPacketCount n = 1; n < current_cwnd / kDefaultTCPMSS; ++n) { + // Call once per ACK. + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + } + clock_.AdvanceTime(hundred_ms_); + current_cwnd = + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + } +} + +TEST_F(CubicBytesTest, LossEvents) { + const QuicTime::Delta rtt_min = hundred_ms_; + QuicByteCount current_cwnd = 422 * kDefaultTCPMSS; + QuicPacketCount expected_cwnd = current_cwnd + kDefaultTCPMSS; + // Initialize the state. + clock_.AdvanceTime(one_ms_); + EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck( + kDefaultTCPMSS, current_cwnd, rtt_min)); + expected_cwnd = static_cast<QuicPacketCount>(current_cwnd * kNConnectionBeta); + EXPECT_EQ(expected_cwnd, + cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); + expected_cwnd = static_cast<QuicPacketCount>(current_cwnd * kNConnectionBeta); + EXPECT_EQ(expected_cwnd, + cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); +} + +TEST_F(CubicBytesTest, BelowOrigin) { + // Concave growth. + const QuicTime::Delta rtt_min = hundred_ms_; + QuicByteCount current_cwnd = 422 * kDefaultTCPMSS; + QuicPacketCount expected_cwnd = current_cwnd + kDefaultTCPMSS; + // Initialize the state. + clock_.AdvanceTime(one_ms_); + EXPECT_EQ(expected_cwnd, cubic_.CongestionWindowAfterAck( + kDefaultTCPMSS, current_cwnd, rtt_min)); + expected_cwnd = static_cast<QuicPacketCount>(current_cwnd * kNConnectionBeta); + EXPECT_EQ(expected_cwnd, + cubic_.CongestionWindowAfterPacketLoss(current_cwnd)); + current_cwnd = expected_cwnd; + // First update after loss to initialize the epoch. + current_cwnd = + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + // Cubic phase. + for (int i = 0; i < 40; ++i) { + clock_.AdvanceTime(hundred_ms_); + current_cwnd = + cubic_.CongestionWindowAfterAck(kDefaultTCPMSS, current_cwnd, rtt_min); + } + expected_cwnd = 422 * kDefaultTCPMSS; + EXPECT_EQ(expected_cwnd, current_cwnd); +} + +} // namespace test +} // namespace net
diff --git a/net/quic/congestion_control/pacing_sender.cc b/net/quic/congestion_control/pacing_sender.cc index 3df555f..addf426b 100644 --- a/net/quic/congestion_control/pacing_sender.cc +++ b/net/quic/congestion_control/pacing_sender.cc
@@ -21,10 +21,10 @@ PacingSender::~PacingSender() {} void PacingSender::SetFromConfig(const QuicConfig& config, - bool is_server, + Perspective perspective, bool using_pacing) { DCHECK(using_pacing); - sender_->SetFromConfig(config, is_server, using_pacing); + sender_->SetFromConfig(config, perspective, using_pacing); } bool PacingSender::ResumeConnectionState(
diff --git a/net/quic/congestion_control/pacing_sender.h b/net/quic/congestion_control/pacing_sender.h index 43afa53..9f64648 100644 --- a/net/quic/congestion_control/pacing_sender.h +++ b/net/quic/congestion_control/pacing_sender.h
@@ -37,7 +37,7 @@ // SendAlgorithmInterface methods. void SetFromConfig(const QuicConfig& config, - bool is_server, + Perspective perspective, bool using_pacing) override; bool ResumeConnectionState( const CachedNetworkParameters& cached_network_params) override;
diff --git a/net/quic/congestion_control/send_algorithm_interface.h b/net/quic/congestion_control/send_algorithm_interface.h index 0154c7e..0fbefec 100644 --- a/net/quic/congestion_control/send_algorithm_interface.h +++ b/net/quic/congestion_control/send_algorithm_interface.h
@@ -39,8 +39,9 @@ virtual ~SendAlgorithmInterface() {} - virtual void SetFromConfig( - const QuicConfig& config, bool is_server, bool using_pacing) = 0; + virtual void SetFromConfig(const QuicConfig& config, + Perspective perspective, + bool using_pacing) = 0; // Sets the number of connections to emulate when doing congestion control, // particularly for congestion avoidance. Can be set any time.
diff --git a/net/quic/congestion_control/tcp_cubic_bytes_sender.cc b/net/quic/congestion_control/tcp_cubic_bytes_sender.cc new file mode 100644 index 0000000..a5b2f68 --- /dev/null +++ b/net/quic/congestion_control/tcp_cubic_bytes_sender.cc
@@ -0,0 +1,346 @@ +// Copyright (c) 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 "net/quic/congestion_control/tcp_cubic_bytes_sender.h" + +#include <algorithm> + +#include "net/quic/congestion_control/prr_sender.h" +#include "net/quic/congestion_control/rtt_stats.h" +#include "net/quic/crypto/crypto_protocol.h" + +using std::max; +using std::min; + +namespace net { + +namespace { +// Constants based on TCP defaults. +// The minimum cwnd based on RFC 3782 (TCP NewReno) for cwnd reductions on a +// fast retransmission. +const QuicByteCount kMinimumCongestionWindow = 2 * kDefaultTCPMSS; +const QuicByteCount kMaxSegmentSize = kDefaultTCPMSS; +const int kMaxBurstLength = 3; +const float kRenoBeta = 0.7f; // Reno backoff factor. +const uint32 kDefaultNumConnections = 2; // N-connection emulation. +} // namespace + +TcpCubicBytesSender::TcpCubicBytesSender( + const QuicClock* clock, + const RttStats* rtt_stats, + bool reno, + QuicPacketCount initial_tcp_congestion_window, + QuicConnectionStats* stats) + : hybrid_slow_start_(clock), + cubic_(clock), + rtt_stats_(rtt_stats), + stats_(stats), + reno_(reno), + num_connections_(kDefaultNumConnections), + num_acked_packets_(0), + largest_sent_sequence_number_(0), + largest_acked_sequence_number_(0), + largest_sent_at_last_cutback_(0), + congestion_window_(initial_tcp_congestion_window * kMaxSegmentSize), + slowstart_threshold_(std::numeric_limits<uint64>::max()), + last_cutback_exited_slowstart_(false), + clock_(clock) { +} + +TcpCubicBytesSender::~TcpCubicBytesSender() { +} + +void TcpCubicBytesSender::SetFromConfig(const QuicConfig& config, + Perspective perspective, + bool using_pacing) { + if (perspective == Perspective::IS_SERVER) { + if (config.HasReceivedConnectionOptions() && + ContainsQuicTag(config.ReceivedConnectionOptions(), kIW10)) { + // Initial window experiment. + congestion_window_ = 10 * kMaxSegmentSize; + } + if (using_pacing) { + // Disable the ack train mode in hystart when pacing is enabled, since it + // may be falsely triggered. + hybrid_slow_start_.set_ack_train_detection(false); + } + } +} + +bool TcpCubicBytesSender::ResumeConnectionState( + const CachedNetworkParameters& cached_network_params) { + // If the previous bandwidth estimate is less than an hour old, store in + // preparation for doing bandwidth resumption. + int64 seconds_since_estimate = + clock_->WallNow().ToUNIXSeconds() - cached_network_params.timestamp(); + if (seconds_since_estimate > kNumSecondsPerHour) { + return false; + } + + QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond( + cached_network_params.bandwidth_estimate_bytes_per_second()); + QuicTime::Delta rtt_ms = + QuicTime::Delta::FromMilliseconds(cached_network_params.min_rtt_ms()); + + // Make sure CWND is in appropriate range (in case of bad data). + QuicByteCount new_congestion_window = bandwidth.ToBytesPerPeriod(rtt_ms); + congestion_window_ = + max(min(new_congestion_window, + kMaxCongestionWindowForBandwidthResumption * kMaxSegmentSize), + kMinCongestionWindowForBandwidthResumption * kMaxSegmentSize); + + // TODO(rjshade): Set appropriate CWND when previous connection was in slow + // start at time of estimate. + return true; +} + +void TcpCubicBytesSender::SetNumEmulatedConnections(int num_connections) { + num_connections_ = max(1, num_connections); + cubic_.SetNumConnections(num_connections_); +} + +float TcpCubicBytesSender::RenoBeta() const { + // kNConnectionBeta is the backoff factor after loss for our N-connection + // emulation, which emulates the effective backoff of an ensemble of N + // TCP-Reno connections on a single loss event. The effective multiplier is + // computed as: + return (num_connections_ - 1 + kRenoBeta) / num_connections_; +} + +void TcpCubicBytesSender::OnCongestionEvent( + bool rtt_updated, + QuicByteCount bytes_in_flight, + const CongestionVector& acked_packets, + const CongestionVector& lost_packets) { + if (rtt_updated && InSlowStart() && + hybrid_slow_start_.ShouldExitSlowStart( + rtt_stats_->latest_rtt(), rtt_stats_->min_rtt(), + congestion_window_ / kMaxSegmentSize)) { + slowstart_threshold_ = congestion_window_; + } + for (CongestionVector::const_iterator it = lost_packets.begin(); + it != lost_packets.end(); ++it) { + OnPacketLost(it->first, bytes_in_flight); + } + for (CongestionVector::const_iterator it = acked_packets.begin(); + it != acked_packets.end(); ++it) { + OnPacketAcked(it->first, it->second.bytes_sent, bytes_in_flight); + } +} + +void TcpCubicBytesSender::OnPacketAcked( + QuicPacketSequenceNumber acked_sequence_number, + QuicByteCount acked_bytes, + QuicByteCount bytes_in_flight) { + largest_acked_sequence_number_ = + max(acked_sequence_number, largest_acked_sequence_number_); + if (InRecovery()) { + // PRR is used when in recovery. + prr_.OnPacketAcked(acked_bytes); + return; + } + MaybeIncreaseCwnd(acked_sequence_number, acked_bytes, bytes_in_flight); + // TODO(ianswett): Should this even be called when not in slow start? + hybrid_slow_start_.OnPacketAcked(acked_sequence_number, InSlowStart()); +} + +void TcpCubicBytesSender::OnPacketLost(QuicPacketSequenceNumber sequence_number, + QuicByteCount bytes_in_flight) { + // TCP NewReno (RFC6582) says that once a loss occurs, any losses in packets + // already sent should be treated as a single loss event, since it's expected. + if (sequence_number <= largest_sent_at_last_cutback_) { + if (last_cutback_exited_slowstart_) { + ++stats_->slowstart_packets_lost; + } + DVLOG(1) << "Ignoring loss for largest_missing:" << sequence_number + << " because it was sent prior to the last CWND cutback."; + return; + } + ++stats_->tcp_loss_events; + last_cutback_exited_slowstart_ = InSlowStart(); + if (InSlowStart()) { + ++stats_->slowstart_packets_lost; + } + + prr_.OnPacketLost(bytes_in_flight); + + if (reno_) { + congestion_window_ = congestion_window_ * RenoBeta(); + } else { + congestion_window_ = + cubic_.CongestionWindowAfterPacketLoss(congestion_window_); + } + slowstart_threshold_ = congestion_window_; + // Enforce TCP's minimum congestion window of 2*MSS. + if (congestion_window_ < kMinimumCongestionWindow) { + congestion_window_ = kMinimumCongestionWindow; + } + largest_sent_at_last_cutback_ = largest_sent_sequence_number_; + // Reset packet count from congestion avoidance mode. We start counting again + // when we're out of recovery. + num_acked_packets_ = 0; + DVLOG(1) << "Incoming loss; congestion window: " << congestion_window_ + << " slowstart threshold: " << slowstart_threshold_; +} + +bool TcpCubicBytesSender::OnPacketSent( + QuicTime /*sent_time*/, + QuicByteCount /*bytes_in_flight*/, + QuicPacketSequenceNumber sequence_number, + QuicByteCount bytes, + HasRetransmittableData is_retransmittable) { + // Only update bytes_in_flight_ for data packets. + if (is_retransmittable != HAS_RETRANSMITTABLE_DATA) { + return false; + } + if (InRecovery()) { + // PRR is used when in recovery. + prr_.OnPacketSent(bytes); + } + DCHECK_LT(largest_sent_sequence_number_, sequence_number); + largest_sent_sequence_number_ = sequence_number; + hybrid_slow_start_.OnPacketSent(sequence_number); + return true; +} + +QuicTime::Delta TcpCubicBytesSender::TimeUntilSend( + QuicTime /* now */, + QuicByteCount bytes_in_flight, + HasRetransmittableData has_retransmittable_data) const { + if (has_retransmittable_data == NO_RETRANSMITTABLE_DATA) { + // For TCP we can always send an ACK immediately. + return QuicTime::Delta::Zero(); + } + if (InRecovery()) { + // PRR is used when in recovery. + return prr_.TimeUntilSend(GetCongestionWindow(), bytes_in_flight, + slowstart_threshold_); + } + if (GetCongestionWindow() > bytes_in_flight) { + return QuicTime::Delta::Zero(); + } + return QuicTime::Delta::Infinite(); +} + +QuicBandwidth TcpCubicBytesSender::PacingRate() const { + // We pace at twice the rate of the underlying sender's bandwidth estimate + // during slow start and 1.25x during congestion avoidance to ensure pacing + // doesn't prevent us from filling the window. + QuicTime::Delta srtt = rtt_stats_->smoothed_rtt(); + if (srtt.IsZero()) { + srtt = QuicTime::Delta::FromMicroseconds(rtt_stats_->initial_rtt_us()); + } + const QuicBandwidth bandwidth = + QuicBandwidth::FromBytesAndTimeDelta(GetCongestionWindow(), srtt); + return bandwidth.Scale(InSlowStart() ? 2 : 1.25); +} + +QuicBandwidth TcpCubicBytesSender::BandwidthEstimate() const { + QuicTime::Delta srtt = rtt_stats_->smoothed_rtt(); + if (srtt.IsZero()) { + // If we haven't measured an rtt, the bandwidth estimate is unknown. + return QuicBandwidth::Zero(); + } + return QuicBandwidth::FromBytesAndTimeDelta(GetCongestionWindow(), srtt); +} + +bool TcpCubicBytesSender::HasReliableBandwidthEstimate() const { + return !InSlowStart() && !InRecovery() && + !rtt_stats_->smoothed_rtt().IsZero(); +} + +QuicTime::Delta TcpCubicBytesSender::RetransmissionDelay() const { + if (rtt_stats_->smoothed_rtt().IsZero()) { + return QuicTime::Delta::Zero(); + } + return rtt_stats_->smoothed_rtt().Add( + rtt_stats_->mean_deviation().Multiply(4)); +} + +QuicByteCount TcpCubicBytesSender::GetCongestionWindow() const { + return congestion_window_; +} + +bool TcpCubicBytesSender::InSlowStart() const { + return congestion_window_ < slowstart_threshold_; +} + +QuicByteCount TcpCubicBytesSender::GetSlowStartThreshold() const { + return slowstart_threshold_; +} + +bool TcpCubicBytesSender::IsCwndLimited(QuicByteCount bytes_in_flight) const { + if (bytes_in_flight >= congestion_window_) { + return true; + } + const QuicByteCount max_burst = kMaxBurstLength * kMaxSegmentSize; + const QuicByteCount available_bytes = congestion_window_ - bytes_in_flight; + const bool slow_start_limited = + InSlowStart() && bytes_in_flight > congestion_window_ / 2; + return slow_start_limited || available_bytes <= max_burst; +} + +bool TcpCubicBytesSender::InRecovery() const { + return largest_acked_sequence_number_ <= largest_sent_at_last_cutback_ && + largest_acked_sequence_number_ != 0; +} + +// Called when we receive an ack. Normal TCP tracks how many packets one ack +// represents, but quic has a separate ack for each packet. +void TcpCubicBytesSender::MaybeIncreaseCwnd( + QuicPacketSequenceNumber acked_sequence_number, + QuicByteCount acked_bytes, + QuicByteCount bytes_in_flight) { + LOG_IF(DFATAL, InRecovery()) << "Never increase the CWND during recovery."; + if (!IsCwndLimited(bytes_in_flight)) { + // We don't update the congestion window unless we are close to using the + // window we have available. + return; + } + if (InSlowStart()) { + // TCP slow start, exponential growth, increase by one for each ACK. + congestion_window_ += kMaxSegmentSize; + DVLOG(1) << "Slow start; congestion window: " << congestion_window_ + << " slowstart threshold: " << slowstart_threshold_; + return; + } + // Congestion avoidance. + if (reno_) { + // Classic Reno congestion avoidance. + ++num_acked_packets_; + // Divide by num_connections to smoothly increase the CWND at a faster rate + // than conventional Reno. + if (num_acked_packets_ * num_connections_ >= + congestion_window_ / kMaxSegmentSize) { + congestion_window_ += kMaxSegmentSize; + num_acked_packets_ = 0; + } + + DVLOG(1) << "Reno; congestion window: " << congestion_window_ + << " slowstart threshold: " << slowstart_threshold_ + << " congestion window count: " << num_acked_packets_; + } else { + congestion_window_ = cubic_.CongestionWindowAfterAck( + acked_bytes, congestion_window_, rtt_stats_->min_rtt()); + DVLOG(1) << "Cubic; congestion window: " << congestion_window_ + << " slowstart threshold: " << slowstart_threshold_; + } +} + +void TcpCubicBytesSender::OnRetransmissionTimeout(bool packets_retransmitted) { + largest_sent_at_last_cutback_ = 0; + if (!packets_retransmitted) { + return; + } + cubic_.Reset(); + hybrid_slow_start_.Restart(); + slowstart_threshold_ = congestion_window_ / 2; + congestion_window_ = kMinimumCongestionWindow; +} + +CongestionControlType TcpCubicBytesSender::GetCongestionControlType() const { + return reno_ ? kReno : kCubic; +} + +} // namespace net
diff --git a/net/quic/congestion_control/tcp_cubic_bytes_sender.h b/net/quic/congestion_control/tcp_cubic_bytes_sender.h new file mode 100644 index 0000000..f4cdd97 --- /dev/null +++ b/net/quic/congestion_control/tcp_cubic_bytes_sender.h
@@ -0,0 +1,129 @@ +// Copyright (c) 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. + +// TCP cubic send side congestion algorithm, emulates the behavior of TCP cubic. + +#ifndef NET_QUIC_CONGESTION_CONTROL_TCP_CUBIC_BYTES_SENDER_H_ +#define NET_QUIC_CONGESTION_CONTROL_TCP_CUBIC_BYTES_SENDER_H_ + +#include "base/basictypes.h" +#include "net/base/net_export.h" +#include "net/quic/congestion_control/cubic_bytes.h" +#include "net/quic/congestion_control/hybrid_slow_start.h" +#include "net/quic/congestion_control/prr_sender.h" +#include "net/quic/congestion_control/send_algorithm_interface.h" +#include "net/quic/quic_bandwidth.h" +#include "net/quic/quic_connection_stats.h" +#include "net/quic/quic_protocol.h" +#include "net/quic/quic_time.h" + +namespace net { + +class RttStats; + +namespace test { +class TcpCubicBytesSenderPeer; +} // namespace test + +class NET_EXPORT_PRIVATE TcpCubicBytesSender : public SendAlgorithmInterface { + public: + TcpCubicBytesSender(const QuicClock* clock, + const RttStats* rtt_stats, + bool reno, + QuicPacketCount initial_tcp_congestion_window, + QuicConnectionStats* stats); + ~TcpCubicBytesSender() override; + + // Start implementation of SendAlgorithmInterface. + void SetFromConfig(const QuicConfig& config, + Perspective perspective, + bool using_pacing) override; + bool ResumeConnectionState( + const CachedNetworkParameters& cached_network_params) override; + void SetNumEmulatedConnections(int num_connections) override; + void OnCongestionEvent(bool rtt_updated, + QuicByteCount bytes_in_flight, + const CongestionVector& acked_packets, + const CongestionVector& lost_packets) override; + bool OnPacketSent(QuicTime sent_time, + QuicByteCount bytes_in_flight, + QuicPacketSequenceNumber sequence_number, + QuicByteCount bytes, + HasRetransmittableData is_retransmittable) override; + void OnRetransmissionTimeout(bool packets_retransmitted) override; + QuicTime::Delta TimeUntilSend( + QuicTime now, + QuicByteCount bytes_in_flight, + HasRetransmittableData has_retransmittable_data) const override; + QuicBandwidth PacingRate() const override; + QuicBandwidth BandwidthEstimate() const override; + bool HasReliableBandwidthEstimate() const override; + QuicTime::Delta RetransmissionDelay() const override; + QuicByteCount GetCongestionWindow() const override; + bool InSlowStart() const override; + bool InRecovery() const override; + QuicByteCount GetSlowStartThreshold() const override; + CongestionControlType GetCongestionControlType() const override; + // End implementation of SendAlgorithmInterface. + + private: + friend class test::TcpCubicBytesSenderPeer; + + // Compute the TCP Reno beta based on the current number of connections. + float RenoBeta() const; + + // TODO(ianswett): Remove these and migrate to OnCongestionEvent. + void OnPacketAcked(QuicPacketSequenceNumber acked_sequence_number, + QuicByteCount acked_bytes, + QuicByteCount bytes_in_flight); + void OnPacketLost(QuicPacketSequenceNumber largest_loss, + QuicByteCount bytes_in_flight); + + void MaybeIncreaseCwnd(QuicPacketSequenceNumber acked_sequence_number, + QuicByteCount acked_bytes, + QuicByteCount bytes_in_flight); + bool IsCwndLimited(QuicByteCount bytes_in_flight) const; + + HybridSlowStart hybrid_slow_start_; + CubicBytes cubic_; + PrrSender prr_; + const RttStats* rtt_stats_; + QuicConnectionStats* stats_; + + // If true, Reno congestion control is used instead of Cubic. + const bool reno_; + + // Number of connections to simulate. + uint32 num_connections_; + + // ACK counter for the Reno implementation. + uint64 num_acked_packets_; + + // Track the largest packet that has been sent. + QuicPacketSequenceNumber largest_sent_sequence_number_; + + // Track the largest packet that has been acked. + QuicPacketSequenceNumber largest_acked_sequence_number_; + + // Track the largest sequence number outstanding when a CWND cutback occurs. + QuicPacketSequenceNumber largest_sent_at_last_cutback_; + + // Congestion window in bytes. + QuicByteCount congestion_window_; + + // Slow start congestion window in bytes, aka ssthresh. + QuicByteCount slowstart_threshold_; + + // Whether the last loss event caused us to exit slowstart. Used for stats + // collection of slowstart_packets_lost. + bool last_cutback_exited_slowstart_; + + const QuicClock* clock_; + + DISALLOW_COPY_AND_ASSIGN(TcpCubicBytesSender); +}; + +} // namespace net + +#endif // NET_QUIC_CONGESTION_CONTROL_TCP_CUBIC_BYTES_SENDER_H_
diff --git a/net/quic/congestion_control/tcp_cubic_bytes_sender_test.cc b/net/quic/congestion_control/tcp_cubic_bytes_sender_test.cc new file mode 100644 index 0000000..3f442ce --- /dev/null +++ b/net/quic/congestion_control/tcp_cubic_bytes_sender_test.cc
@@ -0,0 +1,641 @@ +// Copyright (c) 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 "net/quic/congestion_control/tcp_cubic_bytes_sender.h" + +#include <algorithm> + +#include "base/logging.h" +#include "base/memory/scoped_ptr.h" +#include "net/quic/congestion_control/rtt_stats.h" +#include "net/quic/crypto/crypto_protocol.h" +#include "net/quic/quic_protocol.h" +#include "net/quic/quic_utils.h" +#include "net/quic/test_tools/mock_clock.h" +#include "net/quic/test_tools/quic_config_peer.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { +namespace test { + +// TODO(ianswett): A number of theses tests were written with the assumption of +// an initial CWND of 10. They have carefully calculated values which should be +// updated to be based on kInitialCongestionWindowInsecure. +const uint32 kInitialCongestionWindowPackets = 10; +const uint32 kDefaultWindowTCP = + kInitialCongestionWindowPackets * kDefaultTCPMSS; +const float kRenoBeta = 0.7f; // Reno backoff factor. + +class TcpCubicBytesSenderPeer : public TcpCubicBytesSender { + public: + TcpCubicBytesSenderPeer(const QuicClock* clock, bool reno) + : TcpCubicBytesSender(clock, + &rtt_stats_, + reno, + kInitialCongestionWindowPackets, + &stats_) {} + + const HybridSlowStart& hybrid_slow_start() const { + return hybrid_slow_start_; + } + + float GetRenoBeta() const { return RenoBeta(); } + + RttStats rtt_stats_; + QuicConnectionStats stats_; +}; + +class TcpCubicBytesSenderTest : public ::testing::Test { + protected: + TcpCubicBytesSenderTest() + : one_ms_(QuicTime::Delta::FromMilliseconds(1)), + sender_(new TcpCubicBytesSenderPeer(&clock_, true)), + sequence_number_(1), + acked_sequence_number_(0), + bytes_in_flight_(0) { + standard_packet_.bytes_sent = kDefaultTCPMSS; + } + + int SendAvailableSendWindow() { + // Send as long as TimeUntilSend returns Zero. + int packets_sent = 0; + bool can_send = sender_->TimeUntilSend(clock_.Now(), bytes_in_flight_, + HAS_RETRANSMITTABLE_DATA).IsZero(); + while (can_send) { + sender_->OnPacketSent(clock_.Now(), bytes_in_flight_, sequence_number_++, + kDefaultTCPMSS, HAS_RETRANSMITTABLE_DATA); + ++packets_sent; + bytes_in_flight_ += kDefaultTCPMSS; + can_send = sender_->TimeUntilSend(clock_.Now(), bytes_in_flight_, + HAS_RETRANSMITTABLE_DATA).IsZero(); + } + return packets_sent; + } + + // Normal is that TCP acks every other segment. + void AckNPackets(int n) { + sender_->rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(60), + QuicTime::Delta::Zero(), clock_.Now()); + SendAlgorithmInterface::CongestionVector acked_packets; + SendAlgorithmInterface::CongestionVector lost_packets; + for (int i = 0; i < n; ++i) { + ++acked_sequence_number_; + acked_packets.push_back( + std::make_pair(acked_sequence_number_, standard_packet_)); + } + sender_->OnCongestionEvent(true, bytes_in_flight_, acked_packets, + lost_packets); + bytes_in_flight_ -= n * kDefaultTCPMSS; + clock_.AdvanceTime(one_ms_); + } + + void LoseNPackets(int n) { + SendAlgorithmInterface::CongestionVector acked_packets; + SendAlgorithmInterface::CongestionVector lost_packets; + for (int i = 0; i < n; ++i) { + ++acked_sequence_number_; + lost_packets.push_back( + std::make_pair(acked_sequence_number_, standard_packet_)); + } + sender_->OnCongestionEvent(false, bytes_in_flight_, acked_packets, + lost_packets); + bytes_in_flight_ -= n * kDefaultTCPMSS; + } + + // Does not increment acked_sequence_number_. + void LosePacket(QuicPacketSequenceNumber sequence_number) { + SendAlgorithmInterface::CongestionVector acked_packets; + SendAlgorithmInterface::CongestionVector lost_packets; + lost_packets.push_back(std::make_pair(sequence_number, standard_packet_)); + sender_->OnCongestionEvent(false, bytes_in_flight_, acked_packets, + lost_packets); + bytes_in_flight_ -= kDefaultTCPMSS; + } + + const QuicTime::Delta one_ms_; + MockClock clock_; + scoped_ptr<TcpCubicBytesSenderPeer> sender_; + QuicPacketSequenceNumber sequence_number_; + QuicPacketSequenceNumber acked_sequence_number_; + QuicByteCount bytes_in_flight_; + TransmissionInfo standard_packet_; +}; + +TEST_F(TcpCubicBytesSenderTest, SimpleSender) { + // At startup make sure we are at the default. + EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); + // At startup make sure we can send. + EXPECT_TRUE(sender_->TimeUntilSend(clock_.Now(), 0, HAS_RETRANSMITTABLE_DATA) + .IsZero()); + // Make sure we can send. + EXPECT_TRUE(sender_->TimeUntilSend(clock_.Now(), 0, HAS_RETRANSMITTABLE_DATA) + .IsZero()); + // And that window is un-affected. + EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); + + // Fill the send window with data, then verify that we can't send. + SendAvailableSendWindow(); + EXPECT_FALSE(sender_->TimeUntilSend(clock_.Now(), + sender_->GetCongestionWindow(), + HAS_RETRANSMITTABLE_DATA).IsZero()); +} + +TEST_F(TcpCubicBytesSenderTest, ApplicationLimitedSlowStart) { + // Send exactly 10 packets and ensure the CWND ends at 14 packets. + const int kNumberOfAcks = 5; + // At startup make sure we can send. + EXPECT_TRUE(sender_->TimeUntilSend(clock_.Now(), 0, HAS_RETRANSMITTABLE_DATA) + .IsZero()); + // Make sure we can send. + EXPECT_TRUE(sender_->TimeUntilSend(clock_.Now(), 0, HAS_RETRANSMITTABLE_DATA) + .IsZero()); + + SendAvailableSendWindow(); + for (int i = 0; i < kNumberOfAcks; ++i) { + AckNPackets(2); + } + QuicByteCount bytes_to_send = sender_->GetCongestionWindow(); + // It's expected 2 acks will arrive when the bytes_in_flight are greater than + // half the CWND. + EXPECT_EQ(kDefaultWindowTCP + kDefaultTCPMSS * 2 * 2, bytes_to_send); +} + +TEST_F(TcpCubicBytesSenderTest, ExponentialSlowStart) { + const int kNumberOfAcks = 20; + // At startup make sure we can send. + EXPECT_TRUE(sender_->TimeUntilSend(clock_.Now(), 0, HAS_RETRANSMITTABLE_DATA) + .IsZero()); + EXPECT_FALSE(sender_->HasReliableBandwidthEstimate()); + EXPECT_EQ(QuicBandwidth::Zero(), sender_->BandwidthEstimate()); + // Make sure we can send. + EXPECT_TRUE(sender_->TimeUntilSend(clock_.Now(), 0, HAS_RETRANSMITTABLE_DATA) + .IsZero()); + + for (int i = 0; i < kNumberOfAcks; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + AckNPackets(2); + } + const QuicByteCount cwnd = sender_->GetCongestionWindow(); + EXPECT_EQ(kDefaultWindowTCP + kDefaultTCPMSS * 2 * kNumberOfAcks, cwnd); + EXPECT_FALSE(sender_->HasReliableBandwidthEstimate()); + EXPECT_EQ(QuicBandwidth::FromBytesAndTimeDelta( + cwnd, sender_->rtt_stats_.smoothed_rtt()), + sender_->BandwidthEstimate()); +} + +TEST_F(TcpCubicBytesSenderTest, SlowStartAckTrain) { + sender_->SetNumEmulatedConnections(1); + + // Make sure that we fall out of slow start when we send ACK train longer + // than half the RTT, in this test case 30ms, which is more than 30 calls to + // Ack2Packets in one round. + // Since we start at 10 packet first round will be 5 second round 10 etc + // Hence we should pass 30 at 65 = 5 + 10 + 20 + 30. + const int kNumberOfAcks = 65; + for (int i = 0; i < kNumberOfAcks; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + AckNPackets(2); + } + QuicByteCount expected_send_window = + kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // We should now have fallen out of slow start. + // Testing Reno phase. + // We should need 140(65*2+10) ACK:ed packets before increasing window by + // one. + for (int i = 0; i < 69; ++i) { + SendAvailableSendWindow(); + AckNPackets(2); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + } + SendAvailableSendWindow(); + AckNPackets(2); + QuicByteCount expected_ss_tresh = expected_send_window; + expected_send_window += kDefaultTCPMSS; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + EXPECT_EQ(expected_ss_tresh, sender_->GetSlowStartThreshold()); + + // Now RTO and ensure slow start gets reset. + EXPECT_TRUE(sender_->hybrid_slow_start().started()); + sender_->OnRetransmissionTimeout(true); + EXPECT_FALSE(sender_->hybrid_slow_start().started()); + EXPECT_EQ(2 * kDefaultTCPMSS, sender_->GetCongestionWindow()); + EXPECT_EQ(expected_send_window / 2, sender_->GetSlowStartThreshold()); +} + +TEST_F(TcpCubicBytesSenderTest, SlowStartPacketLoss) { + sender_->SetNumEmulatedConnections(1); + const int kNumberOfAcks = 10; + for (int i = 0; i < kNumberOfAcks; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + AckNPackets(2); + } + SendAvailableSendWindow(); + QuicByteCount expected_send_window = + kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Lose a packet to exit slow start. + LoseNPackets(1); + size_t packets_in_recovery_window = expected_send_window / kDefaultTCPMSS; + + // We should now have fallen out of slow start with a reduced window. + expected_send_window *= kRenoBeta; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Recovery phase. We need to ack every packet in the recovery window before + // we exit recovery. + size_t number_of_packets_in_window = expected_send_window / kDefaultTCPMSS; + DVLOG(1) << "number_packets: " << number_of_packets_in_window; + AckNPackets(packets_in_recovery_window); + SendAvailableSendWindow(); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // We need to ack an entire window before we increase CWND by 1. + AckNPackets(number_of_packets_in_window - 2); + SendAvailableSendWindow(); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Next ack should increase cwnd by 1. + AckNPackets(1); + expected_send_window += kDefaultTCPMSS; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Now RTO and ensure slow start gets reset. + EXPECT_TRUE(sender_->hybrid_slow_start().started()); + sender_->OnRetransmissionTimeout(true); + EXPECT_FALSE(sender_->hybrid_slow_start().started()); +} + +TEST_F(TcpCubicBytesSenderTest, NoPRRWhenLessThanOnePacketInFlight) { + SendAvailableSendWindow(); + LoseNPackets(kInitialCongestionWindowPackets - 1); + AckNPackets(1); + // PRR will allow 2 packets for every ack during recovery. + EXPECT_EQ(2, SendAvailableSendWindow()); + // Simulate abandoning all packets by supplying a bytes_in_flight of 0. + // PRR should now allow a packet to be sent, even though prr's state variables + // believe it has sent enough packets. + EXPECT_EQ(QuicTime::Delta::Zero(), + sender_->TimeUntilSend(clock_.Now(), 0, HAS_RETRANSMITTABLE_DATA)); +} + +TEST_F(TcpCubicBytesSenderTest, SlowStartPacketLossPRR) { + sender_->SetNumEmulatedConnections(1); + // Test based on the first example in RFC6937. + // Ack 10 packets in 5 acks to raise the CWND to 20, as in the example. + const int kNumberOfAcks = 5; + for (int i = 0; i < kNumberOfAcks; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + AckNPackets(2); + } + SendAvailableSendWindow(); + QuicByteCount expected_send_window = + kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + LoseNPackets(1); + + // We should now have fallen out of slow start with a reduced window. + size_t send_window_before_loss = expected_send_window; + expected_send_window *= kRenoBeta; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Testing TCP proportional rate reduction. + // We should send packets paced over the received acks for the remaining + // outstanding packets. The number of packets before we exit recovery is the + // original CWND minus the packet that has been lost and the one which + // triggered the loss. + size_t remaining_packets_in_recovery = + send_window_before_loss / kDefaultTCPMSS - 2; + + for (size_t i = 0; i < remaining_packets_in_recovery; ++i) { + AckNPackets(1); + SendAvailableSendWindow(); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + } + + // We need to ack another window before we increase CWND by 1. + size_t number_of_packets_in_window = expected_send_window / kDefaultTCPMSS; + for (size_t i = 0; i < number_of_packets_in_window; ++i) { + AckNPackets(1); + EXPECT_EQ(1, SendAvailableSendWindow()); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + } + + AckNPackets(1); + expected_send_window += kDefaultTCPMSS; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); +} + +TEST_F(TcpCubicBytesSenderTest, SlowStartBurstPacketLossPRR) { + sender_->SetNumEmulatedConnections(1); + // Test based on the second example in RFC6937, though we also implement + // forward acknowledgements, so the first two incoming acks will trigger + // PRR immediately. + // Ack 20 packets in 10 acks to raise the CWND to 30. + const int kNumberOfAcks = 10; + for (int i = 0; i < kNumberOfAcks; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + AckNPackets(2); + } + SendAvailableSendWindow(); + QuicByteCount expected_send_window = + kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Lose one more than the congestion window reduction, so that after loss, + // bytes_in_flight is lesser than the congestion window. + size_t send_window_after_loss = kRenoBeta * expected_send_window; + size_t num_packets_to_lose = + (expected_send_window - send_window_after_loss) / kDefaultTCPMSS + 1; + LoseNPackets(num_packets_to_lose); + // Immediately after the loss, ensure at least one packet can be sent. + // Losses without subsequent acks can occur with timer based loss detection. + EXPECT_TRUE(sender_->TimeUntilSend(clock_.Now(), bytes_in_flight_, + HAS_RETRANSMITTABLE_DATA).IsZero()); + AckNPackets(1); + + // We should now have fallen out of slow start with a reduced window. + expected_send_window *= kRenoBeta; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Only 2 packets should be allowed to be sent, per PRR-SSRB. + EXPECT_EQ(2, SendAvailableSendWindow()); + + // Ack the next packet, which triggers another loss. + LoseNPackets(1); + AckNPackets(1); + + // Send 2 packets to simulate PRR-SSRB. + EXPECT_EQ(2, SendAvailableSendWindow()); + + // Ack the next packet, which triggers another loss. + LoseNPackets(1); + AckNPackets(1); + + // Send 2 packets to simulate PRR-SSRB. + EXPECT_EQ(2, SendAvailableSendWindow()); + + // Exit recovery and return to sending at the new rate. + for (int i = 0; i < kNumberOfAcks; ++i) { + AckNPackets(1); + EXPECT_EQ(1, SendAvailableSendWindow()); + } +} + +TEST_F(TcpCubicBytesSenderTest, RTOCongestionWindow) { + EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); + // Expect the window to decrease to the minimum once the RTO fires and slow + // start threshold to be set to 1/2 of the CWND. + sender_->OnRetransmissionTimeout(true); + EXPECT_EQ(2 * kDefaultTCPMSS, sender_->GetCongestionWindow()); + EXPECT_EQ(5u * kDefaultTCPMSS, sender_->GetSlowStartThreshold()); +} + +TEST_F(TcpCubicBytesSenderTest, RTOCongestionWindowNoRetransmission) { + EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); + + // Expect the window to remain unchanged if the RTO fires but no packets are + // retransmitted. + sender_->OnRetransmissionTimeout(false); + EXPECT_EQ(kDefaultWindowTCP, sender_->GetCongestionWindow()); +} + +TEST_F(TcpCubicBytesSenderTest, RetransmissionDelay) { + const int64 kRttMs = 10; + const int64 kDeviationMs = 3; + EXPECT_EQ(QuicTime::Delta::Zero(), sender_->RetransmissionDelay()); + + sender_->rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(kRttMs), + QuicTime::Delta::Zero(), clock_.Now()); + + // Initial value is to set the median deviation to half of the initial rtt, + // the median in then multiplied by a factor of 4 and finally the smoothed rtt + // is added which is the initial rtt. + QuicTime::Delta expected_delay = + QuicTime::Delta::FromMilliseconds(kRttMs + kRttMs / 2 * 4); + EXPECT_EQ(expected_delay, sender_->RetransmissionDelay()); + + for (int i = 0; i < 100; ++i) { + // Run to make sure that we converge. + sender_->rtt_stats_.UpdateRtt( + QuicTime::Delta::FromMilliseconds(kRttMs + kDeviationMs), + QuicTime::Delta::Zero(), clock_.Now()); + sender_->rtt_stats_.UpdateRtt( + QuicTime::Delta::FromMilliseconds(kRttMs - kDeviationMs), + QuicTime::Delta::Zero(), clock_.Now()); + } + expected_delay = QuicTime::Delta::FromMilliseconds(kRttMs + kDeviationMs * 4); + + EXPECT_NEAR(kRttMs, sender_->rtt_stats_.smoothed_rtt().ToMilliseconds(), 1); + EXPECT_NEAR(expected_delay.ToMilliseconds(), + sender_->RetransmissionDelay().ToMilliseconds(), 1); + EXPECT_EQ( + static_cast<int64>(sender_->GetCongestionWindow() * kNumMicrosPerSecond / + sender_->rtt_stats_.smoothed_rtt().ToMicroseconds()), + sender_->BandwidthEstimate().ToBytesPerSecond()); +} + +TEST_F(TcpCubicBytesSenderTest, MultipleLossesInOneWindow) { + SendAvailableSendWindow(); + const QuicByteCount initial_window = sender_->GetCongestionWindow(); + LosePacket(acked_sequence_number_ + 1); + const QuicByteCount post_loss_window = sender_->GetCongestionWindow(); + EXPECT_GT(initial_window, post_loss_window); + LosePacket(acked_sequence_number_ + 3); + EXPECT_EQ(post_loss_window, sender_->GetCongestionWindow()); + LosePacket(sequence_number_ - 1); + EXPECT_EQ(post_loss_window, sender_->GetCongestionWindow()); + + // Lose a later packet and ensure the window decreases. + LosePacket(sequence_number_); + EXPECT_GT(post_loss_window, sender_->GetCongestionWindow()); +} + +TEST_F(TcpCubicBytesSenderTest, DontTrackAckPackets) { + // Send a packet with no retransmittable data, and ensure it's not tracked. + EXPECT_FALSE(sender_->OnPacketSent(clock_.Now(), bytes_in_flight_, + sequence_number_++, kDefaultTCPMSS, + NO_RETRANSMITTABLE_DATA)); + + // Send a data packet with retransmittable data, and ensure it is tracked. + EXPECT_TRUE(sender_->OnPacketSent(clock_.Now(), bytes_in_flight_, + sequence_number_++, kDefaultTCPMSS, + HAS_RETRANSMITTABLE_DATA)); +} + +TEST_F(TcpCubicBytesSenderTest, ConfigureMaxInitialWindow) { + QuicConfig config; + + // Verify that kCOPT: kIW10 forces the congestion window to the default of 10. + QuicTagVector options; + options.push_back(kIW10); + QuicConfigPeer::SetReceivedConnectionOptions(&config, options); + sender_->SetFromConfig(config, + /* is_server= */ Perspective::IS_SERVER, + /* using_pacing= */ false); + EXPECT_EQ(10u * kDefaultTCPMSS, sender_->GetCongestionWindow()); +} + +TEST_F(TcpCubicBytesSenderTest, DisableAckTrainDetectionWithPacing) { + EXPECT_TRUE(sender_->hybrid_slow_start().ack_train_detection()); + + QuicConfig config; + sender_->SetFromConfig(config, + /* is_server= */ Perspective::IS_SERVER, + /* using_pacing= */ true); + EXPECT_FALSE(sender_->hybrid_slow_start().ack_train_detection()); +} + +TEST_F(TcpCubicBytesSenderTest, 2ConnectionCongestionAvoidanceAtEndOfRecovery) { + sender_->SetNumEmulatedConnections(2); + // Ack 10 packets in 5 acks to raise the CWND to 20. + const int kNumberOfAcks = 5; + for (int i = 0; i < kNumberOfAcks; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + AckNPackets(2); + } + SendAvailableSendWindow(); + QuicByteCount expected_send_window = + kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + LoseNPackets(1); + + // We should now have fallen out of slow start with a reduced window. + expected_send_window = expected_send_window * sender_->GetRenoBeta(); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // No congestion window growth should occur in recovery phase, i.e., until the + // currently outstanding 20 packets are acked. + for (int i = 0; i < 10; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + EXPECT_TRUE(sender_->InRecovery()); + AckNPackets(2); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + } + EXPECT_FALSE(sender_->InRecovery()); + + // Out of recovery now. Congestion window should not grow for half an RTT. + size_t packets_in_send_window = expected_send_window / kDefaultTCPMSS; + SendAvailableSendWindow(); + AckNPackets(packets_in_send_window / 2 - 2); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Next ack should increase congestion window by 1MSS. + SendAvailableSendWindow(); + AckNPackets(2); + expected_send_window += kDefaultTCPMSS; + packets_in_send_window += 1; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Congestion window should remain steady again for half an RTT. + SendAvailableSendWindow(); + AckNPackets(packets_in_send_window / 2 - 1); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // Next ack should cause congestion window to grow by 1MSS. + SendAvailableSendWindow(); + AckNPackets(2); + expected_send_window += kDefaultTCPMSS; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); +} + +TEST_F(TcpCubicBytesSenderTest, 1ConnectionCongestionAvoidanceAtEndOfRecovery) { + sender_->SetNumEmulatedConnections(1); + // Ack 10 packets in 5 acks to raise the CWND to 20. + const int kNumberOfAcks = 5; + for (int i = 0; i < kNumberOfAcks; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + AckNPackets(2); + } + SendAvailableSendWindow(); + QuicByteCount expected_send_window = + kDefaultWindowTCP + (kDefaultTCPMSS * 2 * kNumberOfAcks); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + LoseNPackets(1); + + // We should now have fallen out of slow start with a reduced window. + expected_send_window *= kRenoBeta; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + + // No congestion window growth should occur in recovery phase, i.e., until the + // currently outstanding 20 packets are acked. + for (int i = 0; i < 10; ++i) { + // Send our full send window. + SendAvailableSendWindow(); + EXPECT_TRUE(sender_->InRecovery()); + AckNPackets(2); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + } + EXPECT_FALSE(sender_->InRecovery()); + + // Out of recovery now. Congestion window should not grow during RTT. + for (uint64 i = 0; i < expected_send_window / kDefaultTCPMSS - 2; i += 2) { + // Send our full send window. + SendAvailableSendWindow(); + AckNPackets(2); + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); + } + + // Next ack should cause congestion window to grow by 1MSS. + SendAvailableSendWindow(); + AckNPackets(2); + expected_send_window += kDefaultTCPMSS; + EXPECT_EQ(expected_send_window, sender_->GetCongestionWindow()); +} + +TEST_F(TcpCubicBytesSenderTest, BandwidthResumption) { + // Test that when provided with CachedNetworkParameters and opted in to the + // bandwidth resumption experiment, that the TcpCubicSender sets initial CWND + // appropriately. + + // Set some common values. + CachedNetworkParameters cached_network_params; + const QuicPacketCount kNumberOfPackets = 123; + const int kBandwidthEstimateBytesPerSecond = + kNumberOfPackets * kDefaultTCPMSS; + cached_network_params.set_bandwidth_estimate_bytes_per_second( + kBandwidthEstimateBytesPerSecond); + cached_network_params.set_min_rtt_ms(1000); + + // Ensure that an old estimate is not used for bandwidth resumption. + cached_network_params.set_timestamp(clock_.WallNow().ToUNIXSeconds() - + (kNumSecondsPerHour + 1)); + EXPECT_FALSE(sender_->ResumeConnectionState(cached_network_params)); + EXPECT_EQ(10u * kDefaultTCPMSS, sender_->GetCongestionWindow()); + + // If the estimate is new enough, make sure it is used. + cached_network_params.set_timestamp(clock_.WallNow().ToUNIXSeconds() - + (kNumSecondsPerHour - 1)); + EXPECT_TRUE(sender_->ResumeConnectionState(cached_network_params)); + EXPECT_EQ(kNumberOfPackets * kDefaultTCPMSS, sender_->GetCongestionWindow()); + + // Resumed CWND is limited to be in a sensible range. + cached_network_params.set_bandwidth_estimate_bytes_per_second( + (kMaxCongestionWindowForBandwidthResumption + 1) * kDefaultTCPMSS); + EXPECT_TRUE(sender_->ResumeConnectionState(cached_network_params)); + EXPECT_EQ(kMaxCongestionWindowForBandwidthResumption * kDefaultTCPMSS, + sender_->GetCongestionWindow()); + + cached_network_params.set_bandwidth_estimate_bytes_per_second( + (kMinCongestionWindowForBandwidthResumption - 1) * kDefaultTCPMSS); + EXPECT_TRUE(sender_->ResumeConnectionState(cached_network_params)); + EXPECT_EQ(kMinCongestionWindowForBandwidthResumption * kDefaultTCPMSS, + sender_->GetCongestionWindow()); +} + +} // namespace test +} // namespace net
diff --git a/net/quic/congestion_control/tcp_cubic_sender.cc b/net/quic/congestion_control/tcp_cubic_sender.cc index 6cfe0fb..e8541da 100644 --- a/net/quic/congestion_control/tcp_cubic_sender.cc +++ b/net/quic/congestion_control/tcp_cubic_sender.cc
@@ -20,7 +20,7 @@ // Constants based on TCP defaults. // The minimum cwnd based on RFC 3782 (TCP NewReno) for cwnd reductions on a // fast retransmission. The cwnd after a timeout is still 1. -const QuicPacketCount kMinimumCongestionWindow = 2; +const QuicPacketCount kDefaultMinimumCongestionWindow = 2; const QuicByteCount kMaxSegmentSize = kDefaultTCPMSS; const int kMaxBurstLength = 3; const float kRenoBeta = 0.7f; // Reno backoff factor. @@ -43,6 +43,7 @@ largest_acked_sequence_number_(0), largest_sent_at_last_cutback_(0), congestion_window_(initial_tcp_congestion_window), + min_congestion_window_(kDefaultMinimumCongestionWindow), slowstart_threshold_(std::numeric_limits<uint64>::max()), last_cutback_exited_slowstart_(false), clock_(clock) { @@ -53,14 +54,19 @@ } void TcpCubicSender::SetFromConfig(const QuicConfig& config, - bool is_server, + Perspective perspective, bool using_pacing) { - if (is_server) { + if (perspective == Perspective::IS_SERVER) { if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), kIW10)) { // Initial window experiment. congestion_window_ = 10; } + if (config.HasReceivedConnectionOptions() && + ContainsQuicTag(config.ReceivedConnectionOptions(), kMIN1)) { + // Min CWND experiment. + min_congestion_window_ = 1; + } if (using_pacing) { // Disable the ack train mode in hystart when pacing is enabled, since it // may be falsely triggered. @@ -173,9 +179,9 @@ cubic_.CongestionWindowAfterPacketLoss(congestion_window_); } slowstart_threshold_ = congestion_window_; - // Enforce TCP's minimum congestion window of 2*MSS. - if (congestion_window_ < kMinimumCongestionWindow) { - congestion_window_ = kMinimumCongestionWindow; + // Enforce a minimum congestion window. + if (congestion_window_ < min_congestion_window_) { + congestion_window_ = min_congestion_window_; } largest_sent_at_last_cutback_ = largest_sent_sequence_number_; // reset packet count from congestion avoidance mode. We start @@ -337,7 +343,7 @@ cubic_.Reset(); hybrid_slow_start_.Restart(); slowstart_threshold_ = congestion_window_ / 2; - congestion_window_ = kMinimumCongestionWindow; + congestion_window_ = min_congestion_window_; } CongestionControlType TcpCubicSender::GetCongestionControlType() const {
diff --git a/net/quic/congestion_control/tcp_cubic_sender.h b/net/quic/congestion_control/tcp_cubic_sender.h index 4659a4b..757934b 100644 --- a/net/quic/congestion_control/tcp_cubic_sender.h +++ b/net/quic/congestion_control/tcp_cubic_sender.h
@@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // -// TCP cubic send side congestion algorithm, emulates the behavior of -// TCP cubic. +// TCP cubic send side congestion algorithm, emulates the behavior of TCP cubic. #ifndef NET_QUIC_CONGESTION_CONTROL_TCP_CUBIC_SENDER_H_ #define NET_QUIC_CONGESTION_CONTROL_TCP_CUBIC_SENDER_H_ @@ -40,7 +39,7 @@ // Start implementation of SendAlgorithmInterface. void SetFromConfig(const QuicConfig& config, - bool is_server, + Perspective perspective, bool using_pacing) override; bool ResumeConnectionState( const CachedNetworkParameters& cached_network_params) override; @@ -114,6 +113,9 @@ // Congestion window in packets. QuicPacketCount congestion_window_; + // Minimum congestion window in packets. + QuicPacketCount min_congestion_window_; + // Slow start congestion window in packets, aka ssthresh. QuicPacketCount slowstart_threshold_;
diff --git a/net/quic/congestion_control/tcp_cubic_sender_test.cc b/net/quic/congestion_control/tcp_cubic_sender_test.cc index ab5fcdb..a5e70ef9 100644 --- a/net/quic/congestion_control/tcp_cubic_sender_test.cc +++ b/net/quic/congestion_control/tcp_cubic_sender_test.cc
@@ -494,25 +494,36 @@ HAS_RETRANSMITTABLE_DATA)); } -TEST_F(TcpCubicSenderTest, ConfigureMaxInitialWindow) { +TEST_F(TcpCubicSenderTest, ConfigureInitialWindow) { QuicConfig config; // Verify that kCOPT: kIW10 forces the congestion window to the default of 10. QuicTagVector options; options.push_back(kIW10); QuicConfigPeer::SetReceivedConnectionOptions(&config, options); - sender_->SetFromConfig(config, - /* is_server= */ true, + sender_->SetFromConfig(config, Perspective::IS_SERVER, /* using_pacing= */ false); EXPECT_EQ(10u, sender_->congestion_window()); } +TEST_F(TcpCubicSenderTest, ConfigureMinimumWindow) { + QuicConfig config; + + // Verify that kCOPT: kMIN1 forces the min CWND to 1 packet. + QuicTagVector options; + options.push_back(kMIN1); + QuicConfigPeer::SetReceivedConnectionOptions(&config, options); + sender_->SetFromConfig(config, Perspective::IS_SERVER, + /* using_pacing= */ false); + sender_->OnRetransmissionTimeout(true); + EXPECT_EQ(1u, sender_->congestion_window()); +} + TEST_F(TcpCubicSenderTest, DisableAckTrainDetectionWithPacing) { EXPECT_TRUE(sender_->hybrid_slow_start().ack_train_detection()); QuicConfig config; - sender_->SetFromConfig(config, - /* is_server= */ true, + sender_->SetFromConfig(config, Perspective::IS_SERVER, /* using_pacing= */ true); EXPECT_FALSE(sender_->hybrid_slow_start().ack_train_detection()); }
diff --git a/net/quic/crypto/crypto_protocol.h b/net/quic/crypto/crypto_protocol.h index 821874e0..fdfcf98 100644 --- a/net/quic/crypto/crypto_protocol.h +++ b/net/quic/crypto/crypto_protocol.h
@@ -60,6 +60,7 @@ const QuicTag kNCON = TAG('N', 'C', 'O', 'N'); // N Connection Congestion Ctrl const QuicTag kNRTO = TAG('N', 'R', 'T', 'O'); // CWND reduction on loss const QuicTag kTIME = TAG('T', 'I', 'M', 'E'); // Time based +const QuicTag kMIN1 = TAG('M', 'I', 'N', '1'); // Min CWND of 1 packet // Optional support of truncated Connection IDs. If sent by a peer, the value // is the minimum number of bytes allowed for the connection ID sent to the
diff --git a/net/quic/crypto/crypto_utils.cc b/net/quic/crypto/crypto_utils.cc index c595775..0916474 100644 --- a/net/quic/crypto/crypto_utils.cc +++ b/net/quic/crypto/crypto_utils.cc
@@ -104,7 +104,7 @@ crypto::HKDF hkdf(premaster_secret, nonce, hkdf_input, key_bytes, nonce_prefix_bytes, subkey_secret_bytes); - if (perspective == SERVER) { + if (perspective == Perspective::IS_SERVER) { if (!crypters->encrypter->SetKey(hkdf.server_write_key()) || !crypters->encrypter->SetNoncePrefix(hkdf.server_write_iv()) || !crypters->decrypter->SetKey(hkdf.client_write_key()) ||
diff --git a/net/quic/crypto/crypto_utils.h b/net/quic/crypto/crypto_utils.h index af3ecbb8..725a863 100644 --- a/net/quic/crypto/crypto_utils.h +++ b/net/quic/crypto/crypto_utils.h
@@ -24,11 +24,6 @@ class NET_EXPORT_PRIVATE CryptoUtils { public: - enum Perspective { - SERVER, - CLIENT, - }; - // Generates the connection nonce. The nonce is formed as: // <4 bytes> current time // <8 bytes> |orbit| (or random if |orbit| is empty)
diff --git a/net/quic/crypto/quic_crypto_client_config.cc b/net/quic/crypto/quic_crypto_client_config.cc index 9ec19fd8..1bc3146 100644 --- a/net/quic/crypto/quic_crypto_client_config.cc +++ b/net/quic/crypto/quic_crypto_client_config.cc
@@ -533,11 +533,10 @@ cetv.SetStringPiece(kCIDS, signature); CrypterPair crypters; - if (!CryptoUtils::DeriveKeys(out_params->initial_premaster_secret, - out_params->aead, out_params->client_nonce, - out_params->server_nonce, hkdf_input, - CryptoUtils::CLIENT, &crypters, - nullptr /* subkey secret */)) { + if (!CryptoUtils::DeriveKeys( + out_params->initial_premaster_secret, out_params->aead, + out_params->client_nonce, out_params->server_nonce, hkdf_input, + Perspective::IS_CLIENT, &crypters, nullptr /* subkey secret */)) { *error_details = "Symmetric key setup failed"; return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED; } @@ -580,10 +579,10 @@ hkdf_input.append(out_params->hkdf_input_suffix); if (!CryptoUtils::DeriveKeys( - out_params->initial_premaster_secret, out_params->aead, - out_params->client_nonce, out_params->server_nonce, hkdf_input, - CryptoUtils::CLIENT, &out_params->initial_crypters, - nullptr /* subkey secret */)) { + out_params->initial_premaster_secret, out_params->aead, + out_params->client_nonce, out_params->server_nonce, hkdf_input, + Perspective::IS_CLIENT, &out_params->initial_crypters, + nullptr /* subkey secret */)) { *error_details = "Symmetric key setup failed"; return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED; } @@ -772,10 +771,10 @@ hkdf_input.append(out_params->hkdf_input_suffix); if (!CryptoUtils::DeriveKeys( - out_params->forward_secure_premaster_secret, out_params->aead, - out_params->client_nonce, out_params->server_nonce, hkdf_input, - CryptoUtils::CLIENT, &out_params->forward_secure_crypters, - &out_params->subkey_secret)) { + out_params->forward_secure_premaster_secret, out_params->aead, + out_params->client_nonce, out_params->server_nonce, hkdf_input, + Perspective::IS_CLIENT, &out_params->forward_secure_crypters, + &out_params->subkey_secret)) { *error_details = "Symmetric key setup failed"; return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED; }
diff --git a/net/quic/crypto/quic_crypto_server_config.cc b/net/quic/crypto/quic_crypto_server_config.cc index c324db2a..557435d 100644 --- a/net/quic/crypto/quic_crypto_server_config.cc +++ b/net/quic/crypto/quic_crypto_server_config.cc
@@ -679,7 +679,7 @@ CrypterPair crypters; if (!CryptoUtils::DeriveKeys(params->initial_premaster_secret, params->aead, info.client_nonce, info.server_nonce, - hkdf_input, CryptoUtils::SERVER, &crypters, + hkdf_input, Perspective::IS_SERVER, &crypters, nullptr /* subkey secret */)) { *error_details = "Symmetric key setup failed"; return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED; @@ -719,11 +719,10 @@ hkdf_input.append(QuicCryptoConfig::kInitialLabel, label_len); hkdf_input.append(hkdf_suffix); - if (!CryptoUtils::DeriveKeys(params->initial_premaster_secret, params->aead, - info.client_nonce, info.server_nonce, hkdf_input, - CryptoUtils::SERVER, - ¶ms->initial_crypters, - nullptr /* subkey secret */)) { + if (!CryptoUtils::DeriveKeys( + params->initial_premaster_secret, params->aead, info.client_nonce, + info.server_nonce, hkdf_input, Perspective::IS_SERVER, + ¶ms->initial_crypters, nullptr /* subkey secret */)) { *error_details = "Symmetric key setup failed"; return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED; } @@ -754,10 +753,10 @@ forward_secure_hkdf_input.append(hkdf_suffix); if (!CryptoUtils::DeriveKeys( - params->forward_secure_premaster_secret, params->aead, - info.client_nonce, info.server_nonce, forward_secure_hkdf_input, - CryptoUtils::SERVER, ¶ms->forward_secure_crypters, - ¶ms->subkey_secret)) { + params->forward_secure_premaster_secret, params->aead, + info.client_nonce, info.server_nonce, forward_secure_hkdf_input, + Perspective::IS_SERVER, ¶ms->forward_secure_crypters, + ¶ms->subkey_secret)) { *error_details = "Symmetric key setup failed"; return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED; }
diff --git a/net/quic/quic_client_session_test.cc b/net/quic/quic_client_session_test.cc index 3cad46a..544131b 100644 --- a/net/quic/quic_client_session_test.cc +++ b/net/quic/quic_client_session_test.cc
@@ -41,8 +41,8 @@ class QuicClientSessionTest : public ::testing::TestWithParam<QuicVersion> { protected: QuicClientSessionTest() - : connection_( - new PacketSavingConnection(false, SupportedVersions(GetParam()))), + : connection_(new PacketSavingConnection(Perspective::IS_CLIENT, + SupportedVersions(GetParam()))), session_(connection_, GetSocket().Pass(), nullptr,
diff --git a/net/quic/quic_config.cc b/net/quic/quic_config.cc index 07445ee..3bdf26a3 100644 --- a/net/quic/quic_config.cc +++ b/net/quic/quic_config.cc
@@ -64,7 +64,8 @@ QuicConfigPresence presence) : QuicNegotiableValue(tag, presence), max_value_(0), - default_value_(0) { + default_value_(0), + negotiated_value_(0) { } QuicNegotiableUint32::~QuicNegotiableUint32() {}
diff --git a/net/quic/quic_connection.cc b/net/quic/quic_connection.cc index 4a510fb7..5241870 100644 --- a/net/quic/quic_connection.cc +++ b/net/quic/quic_connection.cc
@@ -197,19 +197,20 @@ original_sequence_number(original_sequence_number) { } -#define ENDPOINT (is_server_ ? "Server: " : " Client: ") +#define ENDPOINT \ + (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") QuicConnection::QuicConnection(QuicConnectionId connection_id, IPEndPoint address, QuicConnectionHelperInterface* helper, const PacketWriterFactory& writer_factory, bool owns_writer, - bool is_server, + Perspective perspective, bool is_secure, const QuicVersionVector& supported_versions) : framer_(supported_versions, helper->GetClock()->ApproximateNow(), - is_server), + perspective), helper_(helper), writer_(writer_factory.Create(this)), owns_writer_(owns_writer), @@ -250,14 +251,14 @@ time_of_last_sent_new_packet_(clock_->ApproximateNow()), sequence_number_of_last_sent_packet_(0), sent_packet_manager_( - is_server, + perspective, clock_, &stats_, FLAGS_quic_use_bbr_congestion_control ? kBBR : kCubic, FLAGS_quic_use_time_loss_detection ? kTime : kNack, is_secure), version_negotiation_state_(START_NEGOTIATION), - is_server_(is_server), + perspective_(perspective), connected_(true), peer_ip_changed_(false), peer_port_changed_(false), @@ -271,7 +272,8 @@ framer_.set_received_entropy_calculator(&received_packet_manager_); stats_.connection_creation_time = clock_->ApproximateNow(); sent_packet_manager_.set_network_change_visitor(this); - if (FLAGS_quic_small_default_packet_size && is_server_) { + if (FLAGS_quic_small_default_packet_size && + perspective_ == Perspective::IS_SERVER) { set_max_packet_length(kDefaultServerMaxPacketSize); } } @@ -310,8 +312,18 @@ max_undecryptable_packets_ = config.max_undecryptable_packets(); } +void QuicConnection::OnSendConnectionState( + const CachedNetworkParameters& cached_network_params) { + if (debug_visitor_ != nullptr) { + debug_visitor_->OnSendConnectionState(cached_network_params); + } +} + bool QuicConnection::ResumeConnectionState( const CachedNetworkParameters& cached_network_params) { + if (debug_visitor_ != nullptr) { + debug_visitor_->OnResumeConnectionState(cached_network_params); + } return sent_packet_manager_.ResumeConnectionState(cached_network_params); } @@ -386,7 +398,7 @@ DVLOG(1) << ENDPOINT << "Received packet with mismatched version " << received_version; // TODO(satyamshekhar): Implement no server state in this mode. - if (!is_server_) { + if (perspective_ == Perspective::IS_CLIENT) { LOG(DFATAL) << ENDPOINT << "Framer called OnProtocolVersionMismatch. " << "Closing connection."; CloseConnection(QUIC_INTERNAL_ERROR, false); @@ -442,7 +454,7 @@ // Handles version negotiation for client connection. void QuicConnection::OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) { - if (is_server_) { + if (perspective_ == Perspective::IS_SERVER) { LOG(DFATAL) << ENDPOINT << "Framer parsed VersionNegotiationPacket." << " Closing connection."; CloseConnection(QUIC_INTERNAL_ERROR, false); @@ -548,7 +560,7 @@ } if (version_negotiation_state_ != NEGOTIATED_VERSION) { - if (is_server_) { + if (perspective_ == Perspective::IS_SERVER) { if (!header.public_header.version_flag) { DLOG(WARNING) << ENDPOINT << "Packet " << header.packet_sequence_number << " without version flag before version negotiated."; @@ -1269,7 +1281,8 @@ DVLOG(1) << ENDPOINT << "time of last received packet: " << time_of_last_received_packet_.ToDebuggingValue(); - if (is_server_ && encryption_level_ == ENCRYPTION_NONE && + if (perspective_ == Perspective::IS_SERVER && + encryption_level_ == ENCRYPTION_NONE && last_size_ > packet_generator_.max_packet_length()) { set_max_packet_length(last_size_); } @@ -1596,7 +1609,7 @@ sent_packet_manager_.SetHandshakeConfirmed(); // The client should immediately ack the SHLO to confirm the handshake is // complete with the server. - if (!is_server_ && !ack_queued_) { + if (perspective_ == Perspective::IS_CLIENT && !ack_queued_) { ack_alarm_->Cancel(); ack_alarm_->Set(clock_->ApproximateNow()); } @@ -1942,7 +1955,7 @@ << " overall_timeout:" << overall_timeout.ToMilliseconds(); // Adjust the idle timeout on client and server to prevent clients from // sending requests to servers which have already closed the connection. - if (is_server_) { + if (perspective_ == Perspective::IS_SERVER) { idle_timeout = idle_timeout.Add(QuicTime::Delta::FromSeconds(3)); } else if (idle_timeout > QuicTime::Delta::FromSeconds(1)) { idle_timeout = idle_timeout.Subtract(QuicTime::Delta::FromSeconds(1)); @@ -2007,7 +2020,7 @@ } void QuicConnection::SetPingAlarm() { - if (is_server_) { + if (perspective_ == Perspective::IS_SERVER) { // Only clients send pings. return; }
diff --git a/net/quic/quic_connection.h b/net/quic/quic_connection.h index 789a7e5..2b2a363 100644 --- a/net/quic/quic_connection.h +++ b/net/quic/quic_connection.h
@@ -201,6 +201,14 @@ // Called when the version negotiation is successful. virtual void OnSuccessfulVersionNegotiation(const QuicVersion& version) {} + + // Called when a CachedNetworkParameters is sent to the client. + virtual void OnSendConnectionState( + const CachedNetworkParameters& cached_network_params) {} + + // Called when resuming previous connection state. + virtual void OnResumeConnectionState( + const CachedNetworkParameters& cached_network_params) {} }; class NET_EXPORT_PRIVATE QuicConnectionHelperInterface { @@ -247,7 +255,7 @@ QuicConnectionHelperInterface* helper, const PacketWriterFactory& writer_factory, bool owns_writer, - bool is_server, + Perspective perspective, bool is_secure, const QuicVersionVector& supported_versions); ~QuicConnection() override; @@ -255,6 +263,10 @@ // Sets connection parameters from the supplied |config|. void SetFromConfig(const QuicConfig& config); + // Called by the session when sending connection state to the client. + virtual void OnSendConnectionState( + const CachedNetworkParameters& cached_network_params); + // Called by the Session when the client has provided CachedNetworkParameters. // Returns true if this changes the initial connection state. virtual bool ResumeConnectionState( @@ -404,7 +416,7 @@ // Must only be called on client connections. const QuicVersionVector& server_supported_versions() const { - DCHECK(!is_server_); + DCHECK_EQ(Perspective::IS_CLIENT, perspective_); return server_supported_versions_; } @@ -487,7 +499,7 @@ const QuicDecrypter* decrypter() const; const QuicDecrypter* alternative_decrypter() const; - bool is_server() const { return is_server_; } + Perspective perspective() const { return perspective_; } // Allow easy overriding of truncated connection IDs. void set_can_truncate_connection_ids(bool can) { @@ -804,8 +816,8 @@ // The state of connection in version negotiation finite state machine. QuicVersionNegotiationState version_negotiation_state_; - // Tracks if the connection was created by the server. - bool is_server_; + // Tracks if the connection was created by the server or the client. + Perspective perspective_; // True by default. False if we've received or sent an explicit connection // close.
diff --git a/net/quic/quic_connection_logger_unittest.cc b/net/quic/quic_connection_logger_unittest.cc index e3a68f7..ab6d950 100644 --- a/net/quic/quic_connection_logger_unittest.cc +++ b/net/quic/quic_connection_logger_unittest.cc
@@ -21,7 +21,7 @@ class QuicConnectionLoggerTest : public ::testing::Test { protected: QuicConnectionLoggerTest() - : session_(new MockConnection(false)), + : session_(new MockConnection(Perspective::IS_CLIENT)), logger_(&session_, "CONNECTION_UNKNOWN", net_log_) {} BoundNetLog net_log_;
diff --git a/net/quic/quic_connection_test.cc b/net/quic/quic_connection_test.cc index 7f3f1d4..31ea1a6 100644 --- a/net/quic/quic_connection_test.cc +++ b/net/quic/quic_connection_test.cc
@@ -331,10 +331,13 @@ is_write_blocked_data_buffered_ = buffered; } - void set_is_server(bool is_server) { - // We invert is_server here, because the framer needs to parse packets + void set_perspective(Perspective perspective) { + // We invert perspective here, because the framer needs to parse packets // we send. - QuicFramerPeer::SetIsServer(framer_.framer(), !is_server); + perspective = perspective == Perspective::IS_CLIENT + ? Perspective::IS_SERVER + : Perspective::IS_CLIENT; + QuicFramerPeer::SetPerspective(framer_.framer(), perspective); } // final_bytes_of_last_packet_ returns the last four bytes of the previous @@ -385,20 +388,20 @@ IPEndPoint address, TestConnectionHelper* helper, const PacketWriterFactory& factory, - bool is_server, + Perspective perspective, QuicVersion version) : QuicConnection(connection_id, address, helper, factory, /* owns_writer= */ false, - is_server, + perspective, /* is_secure= */ false, SupportedVersions(version)) { // Disable tail loss probes for most tests. QuicSentPacketManagerPeer::SetMaxTailLossProbes( QuicConnectionPeer::GetSentPacketManager(this), 0); - writer()->set_is_server(is_server); + writer()->set_perspective(perspective); } void SendAck() { @@ -501,10 +504,6 @@ return SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, nullptr); } - bool is_server() { - return QuicConnectionPeer::IsServer(this); - } - void set_version(QuicVersion version) { QuicConnectionPeer::GetFramer(this)->set_version(version); } @@ -514,9 +513,9 @@ writer()->SetSupportedVersions(versions); } - void set_is_server(bool is_server) { - writer()->set_is_server(is_server); - QuicConnectionPeer::SetIsServer(this, is_server); + void set_perspective(Perspective perspective) { + writer()->set_perspective(perspective); + QuicConnectionPeer::SetPerspective(this, perspective); } TestConnectionHelper::TestAlarm* GetAckAlarm() { @@ -596,7 +595,9 @@ protected: QuicConnectionTest() : connection_id_(42), - framer_(SupportedVersions(version()), QuicTime::Zero(), false), + framer_(SupportedVersions(version()), + QuicTime::Zero(), + Perspective::IS_CLIENT), peer_creator_(connection_id_, &framer_, &random_generator_), send_algorithm_(new StrictMock<MockSendAlgorithm>), loss_algorithm_(new MockLossAlgorithm()), @@ -607,7 +608,7 @@ IPEndPoint(), helper_.get(), factory_, - false, + Perspective::IS_CLIENT, version()), creator_(QuicConnectionPeer::GetPacketCreator(&connection_)), generator_(QuicConnectionPeer::GetPacketGenerator(&connection_)), @@ -683,8 +684,9 @@ QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) { QuicFrames frames; frames.push_back(QuicFrame(frame)); - QuicPacketCreatorPeer::SetSendVersionInPacket(&peer_creator_, - connection_.is_server()); + QuicPacketCreatorPeer::SetSendVersionInPacket( + &peer_creator_, connection_.perspective() == Perspective::IS_SERVER); + SerializedPacket serialized_packet = peer_creator_.SerializeAllFrames(frames); scoped_ptr<QuicEncryptedPacket> encrypted(serialized_packet.packet); @@ -979,34 +981,32 @@ ::testing::ValuesIn(QuicSupportedVersions())); TEST_P(QuicConnectionTest, MaxPacketSize) { - EXPECT_FALSE(connection_.is_server()); + EXPECT_EQ(Perspective::IS_CLIENT, connection_.perspective()); EXPECT_EQ(1350u, connection_.max_packet_length()); } TEST_P(QuicConnectionTest, SmallerServerMaxPacketSize) { ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, true); QuicConnectionId connection_id = 42; - bool kIsServer = true; TestConnection connection(connection_id, IPEndPoint(), helper_.get(), - factory_, kIsServer, version()); - EXPECT_TRUE(connection.is_server()); + factory_, Perspective::IS_SERVER, version()); + EXPECT_EQ(Perspective::IS_SERVER, connection.perspective()); EXPECT_EQ(1000u, connection.max_packet_length()); } TEST_P(QuicConnectionTest, ServerMaxPacketSize) { ValueRestore<bool> old_flag(&FLAGS_quic_small_default_packet_size, false); QuicConnectionId connection_id = 42; - bool kIsServer = true; TestConnection connection(connection_id, IPEndPoint(), helper_.get(), - factory_, kIsServer, version()); - EXPECT_TRUE(connection.is_server()); + factory_, Perspective::IS_SERVER, version()); + EXPECT_EQ(Perspective::IS_SERVER, connection.perspective()); EXPECT_EQ(1350u, connection.max_packet_length()); } TEST_P(QuicConnectionTest, IncreaseServerMaxPacketSize) { EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_)); - connection_.set_is_server(true); + connection_.set_perspective(Perspective::IS_SERVER); connection_.set_max_packet_length(1000); QuicPacketHeader header; @@ -3299,13 +3299,13 @@ EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); // Completing the handshake as the server does nothing. - QuicConnectionPeer::SetIsServer(&connection_, true); + QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_SERVER); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.GetAckAlarm()->IsSet()); EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline()); // Complete the handshake as the client decreases the delayed ack time to 0ms. - QuicConnectionPeer::SetIsServer(&connection_, false); + QuicConnectionPeer::SetPerspective(&connection_, Perspective::IS_CLIENT); connection_.OnHandshakeComplete(); EXPECT_TRUE(connection_.GetAckAlarm()->IsSet()); EXPECT_EQ(clock_.ApproximateNow(), connection_.GetAckAlarm()->deadline()); @@ -3646,7 +3646,7 @@ framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet)); framer_.set_version(version()); - connection_.set_is_server(true); + connection_.set_perspective(Perspective::IS_SERVER); connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); EXPECT_TRUE(writer_->version_negotiation_packet() != nullptr); @@ -3684,7 +3684,7 @@ framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet)); framer_.set_version(version()); - connection_.set_is_server(true); + connection_.set_perspective(Perspective::IS_SERVER); BlockOnNextWrite(); connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); EXPECT_EQ(0u, writer_->last_packet_size()); @@ -3729,7 +3729,7 @@ framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet)); framer_.set_version(version()); - connection_.set_is_server(true); + connection_.set_perspective(Perspective::IS_SERVER); BlockOnNextWrite(); writer_->set_is_write_blocked_data_buffered(true); connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted); @@ -4315,10 +4315,10 @@ } TEST_P(QuicConnectionTest, Pacing) { - TestConnection server(connection_id_, IPEndPoint(), helper_.get(), - factory_, /* is_server= */ true, version()); - TestConnection client(connection_id_, IPEndPoint(), helper_.get(), - factory_, /* is_server= */ false, version()); + TestConnection server(connection_id_, IPEndPoint(), helper_.get(), factory_, + Perspective::IS_SERVER, version()); + TestConnection client(connection_id_, IPEndPoint(), helper_.get(), factory_, + Perspective::IS_CLIENT, version()); EXPECT_FALSE(client.sent_packet_manager().using_pacing()); EXPECT_FALSE(server.sent_packet_manager().using_pacing()); }
diff --git a/net/quic/quic_crypto_client_stream.cc b/net/quic/quic_crypto_client_stream.cc index eaff528..133f4fb9 100644 --- a/net/quic/quic_crypto_client_stream.cc +++ b/net/quic/quic_crypto_client_stream.cc
@@ -88,7 +88,7 @@ channel_id_source_callback_(nullptr), verify_context_(verify_context), proof_verify_callback_(nullptr) { - DCHECK(!session->connection()->is_server()); + DCHECK_EQ(Perspective::IS_CLIENT, session->connection()->perspective()); } QuicCryptoClientStream::~QuicCryptoClientStream() {
diff --git a/net/quic/quic_crypto_client_stream_test.cc b/net/quic/quic_crypto_client_stream_test.cc index 454d930..417652d0 100644 --- a/net/quic/quic_crypto_client_stream_test.cc +++ b/net/quic/quic_crypto_client_stream_test.cc
@@ -30,7 +30,7 @@ class QuicCryptoClientStreamTest : public ::testing::Test { public: QuicCryptoClientStreamTest() - : connection_(new PacketSavingConnection(/*is_server=*/false)), + : connection_(new PacketSavingConnection(Perspective::IS_CLIENT)), session_(new TestClientSession(connection_, DefaultQuicConfig())), server_id_(kServerHostname, kServerPort, false, PRIVACY_MODE_DISABLED), stream_(new QuicCryptoClientStream(server_id_, @@ -123,7 +123,7 @@ // Seed the config with a cached server config. CompleteCryptoHandshake(); - connection_ = new PacketSavingConnection(/*is_server=*/false); + connection_ = new PacketSavingConnection(Perspective::IS_CLIENT); session_.reset(new TestClientSession(connection_, DefaultQuicConfig())); stream_.reset(new QuicCryptoClientStream(server_id_, session_.get(), nullptr, &crypto_config_));
diff --git a/net/quic/quic_crypto_server_stream.cc b/net/quic/quic_crypto_server_stream.cc index 8e04298..b51f840 100644 --- a/net/quic/quic_crypto_server_stream.cc +++ b/net/quic/quic_crypto_server_stream.cc
@@ -33,7 +33,7 @@ validate_client_hello_cb_(nullptr), num_handshake_messages_(0), num_server_config_update_messages_sent_(0) { - DCHECK(session->connection()->is_server()); + DCHECK_EQ(Perspective::IS_SERVER, session->connection()->perspective()); } QuicCryptoServerStream::~QuicCryptoServerStream() {
diff --git a/net/quic/quic_crypto_server_stream_test.cc b/net/quic/quic_crypto_server_stream_test.cc index 2b885fa8..5667261 100644 --- a/net/quic/quic_crypto_server_stream_test.cc +++ b/net/quic/quic_crypto_server_stream_test.cc
@@ -56,7 +56,7 @@ class QuicCryptoServerStreamTest : public ::testing::TestWithParam<bool> { public: QuicCryptoServerStreamTest() - : connection_(new PacketSavingConnection(/*is_server=*/true)), + : connection_(new PacketSavingConnection(Perspective::IS_SERVER)), session_(connection_, DefaultQuicConfig()), crypto_config_(QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance()), @@ -134,9 +134,9 @@ TEST_P(QuicCryptoServerStreamTest, ZeroRTT) { PacketSavingConnection* client_conn = - new PacketSavingConnection(/*is_server=*/false); + new PacketSavingConnection(Perspective::IS_CLIENT); PacketSavingConnection* server_conn = - new PacketSavingConnection(/*is_server=*/true); + new PacketSavingConnection(Perspective::IS_SERVER); client_conn->AdvanceTime(QuicTime::Delta::FromSeconds(100000)); server_conn->AdvanceTime(QuicTime::Delta::FromSeconds(100000)); @@ -168,8 +168,8 @@ // Now do another handshake, hopefully in 0-RTT. LOG(INFO) << "Resetting for 0-RTT handshake attempt"; - client_conn = new PacketSavingConnection(/*is_server=*/false); - server_conn = new PacketSavingConnection(/*is_server=*/true); + client_conn = new PacketSavingConnection(Perspective::IS_CLIENT); + server_conn = new PacketSavingConnection(Perspective::IS_SERVER); // We need to advance time past the strike-server window so that it's // authoritative in this time span. client_conn->AdvanceTime(QuicTime::Delta::FromSeconds(102000));
diff --git a/net/quic/quic_crypto_stream.cc b/net/quic/quic_crypto_stream.cc index 6d9358d..43cf497 100644 --- a/net/quic/quic_crypto_stream.cc +++ b/net/quic/quic_crypto_stream.cc
@@ -18,7 +18,9 @@ namespace net { -#define ENDPOINT (session()->is_server() ? "Server: " : " Client: ") +#define ENDPOINT \ + (session()->perspective() == Perspective::IS_SERVER ? "Server: " : "Client:" \ + " ") QuicCryptoStream::QuicCryptoStream(QuicSession* session) : ReliableQuicStream(kCryptoStreamId, session),
diff --git a/net/quic/quic_crypto_stream_test.cc b/net/quic/quic_crypto_stream_test.cc index 0abd49d..8c83e92 100644 --- a/net/quic/quic_crypto_stream_test.cc +++ b/net/quic/quic_crypto_stream_test.cc
@@ -46,7 +46,7 @@ class QuicCryptoStreamTest : public ::testing::Test { public: QuicCryptoStreamTest() - : connection_(new MockConnection(false)), + : connection_(new MockConnection(Perspective::IS_CLIENT)), session_(connection_), stream_(&session_) { message_.set_tag(kSHLO);
diff --git a/net/quic/quic_data_stream.cc b/net/quic/quic_data_stream.cc index 10f8b4c..55f92056 100644 --- a/net/quic/quic_data_stream.cc +++ b/net/quic/quic_data_stream.cc
@@ -14,7 +14,9 @@ namespace net { -#define ENDPOINT (session()->is_server() ? "Server: " : " Client: ") +#define ENDPOINT \ + (session()->perspective() == Perspective::IS_SERVER ? "Server: " : "Client:" \ + " ") namespace { @@ -150,7 +152,7 @@ } void QuicDataStream::OnStreamHeadersPriority(QuicPriority priority) { - DCHECK(session()->connection()->is_server()); + DCHECK_EQ(Perspective::IS_SERVER, session()->connection()->perspective()); set_priority(priority); }
diff --git a/net/quic/quic_data_stream_test.cc b/net/quic/quic_data_stream_test.cc index cc865c09..246edc92 100644 --- a/net/quic/quic_data_stream_test.cc +++ b/net/quic/quic_data_stream_test.cc
@@ -30,7 +30,6 @@ namespace test { namespace { -const bool kIsServer = true; const bool kShouldProcessData = true; class TestStream : public QuicDataStream { @@ -93,7 +92,7 @@ void Initialize(bool stream_should_process_data) { connection_ = new testing::StrictMock<MockConnection>( - kIsServer, SupportedVersions(GetParam())); + Perspective::IS_SERVER, SupportedVersions(GetParam())); session_.reset(new testing::StrictMock<MockSession>(connection_)); stream_.reset(new TestStream(kClientDataStreamId1, session_.get(), stream_should_process_data));
diff --git a/net/quic/quic_dispatcher.cc b/net/quic/quic_dispatcher.cc index 09d34a0..f26f6ab3 100644 --- a/net/quic/quic_dispatcher.cc +++ b/net/quic/quic_dispatcher.cc
@@ -170,7 +170,9 @@ connection_writer_factory_(this), supported_versions_(supported_versions), current_packet_(nullptr), - framer_(supported_versions, /*unused*/ QuicTime::Zero(), true), + framer_(supported_versions, + /*unused*/ QuicTime::Zero(), + Perspective::IS_SERVER), framer_visitor_(new QuicFramerVisitor(this)) { framer_.set_visitor(framer_visitor_.get()); } @@ -392,7 +394,7 @@ // The QuicSession takes ownership of |connection| below. QuicConnection* connection = new QuicConnection( connection_id, client_address, helper_, connection_writer_factory_, - /* owns_writer= */ true, /* is_server= */ true, + /* owns_writer= */ true, Perspective::IS_SERVER, crypto_config_.HasProofSource(), supported_versions_); QuicServerSession* session = new QuicServerSession(config_, connection, this);
diff --git a/net/quic/quic_flags.cc b/net/quic/quic_flags.cc index ac5cc864a..325cf04 100644 --- a/net/quic/quic_flags.cc +++ b/net/quic/quic_flags.cc
@@ -29,11 +29,6 @@ // Chrome/Finch). bool FLAGS_quic_enable_bandwidth_resumption_experiment = true; -// If true, QUIC congestion control will be paced. If false, pacing may be -// controlled by QUIC connection options in the config or by enabling BBR -// congestion control. -bool FLAGS_quic_enable_pacing = true; - // If true, then the source address tokens generated for QUIC connects will // store multiple addresses. bool FLAGS_quic_use_multiple_address_in_source_tokens = false;
diff --git a/net/quic/quic_flags.h b/net/quic/quic_flags.h index bb18b49..d95c298 100644 --- a/net/quic/quic_flags.h +++ b/net/quic/quic_flags.h
@@ -17,7 +17,6 @@ NET_EXPORT_PRIVATE extern bool FLAGS_quic_too_many_outstanding_packets; NET_EXPORT_PRIVATE extern bool FLAGS_quic_enable_bandwidth_resumption_experiment; -NET_EXPORT_PRIVATE extern bool FLAGS_quic_enable_pacing; NET_EXPORT_PRIVATE extern bool FLAGS_quic_use_multiple_address_in_source_tokens; NET_EXPORT_PRIVATE extern int64 FLAGS_quic_time_wait_list_seconds; NET_EXPORT_PRIVATE extern int64 FLAGS_quic_time_wait_list_max_connections;
diff --git a/net/quic/quic_flow_controller.cc b/net/quic/quic_flow_controller.cc index 1fedd06..d95541e 100644 --- a/net/quic/quic_flow_controller.cc +++ b/net/quic/quic_flow_controller.cc
@@ -11,17 +11,18 @@ namespace net { -#define ENDPOINT (is_server_ ? "Server: " : " Client: ") +#define ENDPOINT \ + (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") QuicFlowController::QuicFlowController(QuicConnection* connection, QuicStreamId id, - bool is_server, + Perspective perspective, QuicStreamOffset send_window_offset, QuicStreamOffset receive_window_offset, QuicByteCount max_receive_window) : connection_(connection), id_(id), - is_server_(is_server), + perspective_(perspective), bytes_consumed_(0), highest_received_byte_offset_(0), bytes_sent_(0),
diff --git a/net/quic/quic_flow_controller.h b/net/quic/quic_flow_controller.h index 1b5ed61..afa022b1 100644 --- a/net/quic/quic_flow_controller.h +++ b/net/quic/quic_flow_controller.h
@@ -27,7 +27,7 @@ public: QuicFlowController(QuicConnection* connection, QuicStreamId id, - bool is_server, + Perspective perspective, QuicStreamOffset send_window_offset, QuicStreamOffset receive_window_offset, QuicByteCount max_receive_window); @@ -83,8 +83,8 @@ // connection level flow controller. QuicStreamId id_; - // True if this is owned by a server. - bool is_server_; + // Tracks if this is owned by a server or a client. + Perspective perspective_; // Track number of bytes received from the peer, which have been consumed // locally.
diff --git a/net/quic/quic_flow_controller_test.cc b/net/quic/quic_flow_controller_test.cc index b3c75c4..4562a14 100644 --- a/net/quic/quic_flow_controller_test.cc +++ b/net/quic/quic_flow_controller_test.cc
@@ -23,12 +23,11 @@ send_window_(kInitialSessionFlowControlWindowForTest), receive_window_(kInitialSessionFlowControlWindowForTest), max_receive_window_(kInitialSessionFlowControlWindowForTest), - connection_(false) { - } + connection_(Perspective::IS_CLIENT) {} void Initialize() { flow_controller_.reset(new QuicFlowController( - &connection_, stream_id_, false, send_window_, + &connection_, stream_id_, Perspective::IS_CLIENT, send_window_, receive_window_, max_receive_window_)); }
diff --git a/net/quic/quic_framer.cc b/net/quic/quic_framer.cc index 4d387cf..7d6ecc2 100644 --- a/net/quic/quic_framer.cc +++ b/net/quic/quic_framer.cc
@@ -142,7 +142,7 @@ QuicFramer::QuicFramer(const QuicVersionVector& supported_versions, QuicTime creation_time, - bool is_server) + Perspective perspective) : visitor_(nullptr), fec_builder_(nullptr), entropy_calculator_(nullptr), @@ -153,7 +153,7 @@ decrypter_level_(ENCRYPTION_NONE), alternative_decrypter_level_(ENCRYPTION_NONE), alternative_decrypter_latch_(false), - is_server_(is_server), + perspective_(perspective), validate_flags_(true), creation_time_(creation_time), last_timestamp_(QuicTime::Delta::Zero()) { @@ -531,7 +531,7 @@ return true; } - if (is_server_ && public_header.version_flag && + if (perspective_ == Perspective::IS_SERVER && public_header.version_flag && public_header.versions[0] != quic_version_) { if (!visitor_->OnProtocolVersionMismatch(public_header.versions[0])) { reader_.reset(nullptr); @@ -540,7 +540,7 @@ } bool rv; - if (!is_server_ && public_header.version_flag) { + if (perspective_ == Perspective::IS_CLIENT && public_header.version_flag) { rv = ProcessVersionNegotiationPacket(&public_header); } else if (public_header.reset_flag) { rv = ProcessPublicResetPacket(public_header); @@ -562,7 +562,7 @@ bool QuicFramer::ProcessVersionNegotiationPacket( QuicPacketPublicHeader* public_header) { - DCHECK(!is_server_); + DCHECK_EQ(Perspective::IS_CLIENT, perspective_); // Try reading at least once to raise error if the packet is invalid. do { QuicTag version; @@ -744,7 +744,7 @@ last_serialized_connection_id_ = header.public_header.connection_id; if (header.public_header.version_flag) { - DCHECK(!is_server_); + DCHECK_EQ(Perspective::IS_CLIENT, perspective_); writer->WriteUInt32(QuicVersionToQuicTag(quic_version_)); } @@ -910,7 +910,7 @@ // Read the version only if the packet is from the client. // version flag from the server means version negotiation packet. - if (public_header->version_flag && is_server_) { + if (public_header->version_flag && perspective_ == Perspective::IS_SERVER) { QuicTag version_tag; if (!reader_->ReadUInt32(&version_tag)) { set_detailed_error("Unable to read protocol version.");
diff --git a/net/quic/quic_framer.h b/net/quic/quic_framer.h index 3cfaa88d..34744d91 100644 --- a/net/quic/quic_framer.h +++ b/net/quic/quic_framer.h
@@ -67,8 +67,8 @@ // Called if an error is detected in the QUIC protocol. virtual void OnError(QuicFramer* framer) = 0; - // Called only when |is_server_| is true and the the framer gets a packet with - // version flag true and the version on the packet doesn't match + // Called only when |perspective_| is IS_SERVER and the the framer gets a + // packet with version flag true and the version on the packet doesn't match // |quic_version_|. The visitor should return true after it updates the // version of the |framer_| to |received_version| or false to stop processing // this packet. @@ -83,8 +83,8 @@ virtual void OnPublicResetPacket( const QuicPublicResetPacket& packet) = 0; - // Called only when |is_server_| is false and a version negotiation packet has - // been parsed. + // Called only when |perspective_| is IS_CLIENT and a version negotiation + // packet has been parsed. virtual void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& packet) = 0; @@ -187,7 +187,7 @@ // version in |supported_versions|. QuicFramer(const QuicVersionVector& supported_versions, QuicTime creation_time, - bool is_server); + Perspective perspective); virtual ~QuicFramer(); @@ -370,7 +370,7 @@ void set_validate_flags(bool value) { validate_flags_ = value; } - bool is_server() const { return is_server_; } + Perspective perspective() const { return perspective_; } static QuicPacketEntropyHash GetPacketEntropyHash( const QuicPacketHeader& header); @@ -529,7 +529,7 @@ scoped_ptr<QuicEncrypter> encrypter_[NUM_ENCRYPTION_LEVELS]; // Tracks if the framer is being used by the entity that received the // connection or the entity that initiated it. - bool is_server_; + Perspective perspective_; // If false, skip validation that the public flags are set to legal values. bool validate_flags_; // The time this framer was created. Time written to the wire will be
diff --git a/net/quic/quic_framer_test.cc b/net/quic/quic_framer_test.cc index 69373e0..fd3fb15 100644 --- a/net/quic/quic_framer_test.cc +++ b/net/quic/quic_framer_test.cc
@@ -342,7 +342,7 @@ : encrypter_(new test::TestEncrypter()), decrypter_(new test::TestDecrypter()), start_(QuicTime::Zero().Add(QuicTime::Delta::FromMicroseconds(0x10))), - framer_(QuicSupportedVersions(), start_, true) { + framer_(QuicSupportedVersions(), start_, Perspective::IS_SERVER) { version_ = GetParam(); framer_.set_version(version_); framer_.SetDecrypter(decrypter_, ENCRYPTION_NONE); @@ -2769,7 +2769,7 @@ 'Q', '2', '.', '0', }; - QuicFramerPeer::SetIsServer(&framer_, false); + QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); QuicEncryptedPacket encrypted(AsChars(packet), arraysize(packet), false); EXPECT_TRUE(framer_.ProcessPacket(encrypted)); @@ -3193,7 +3193,7 @@ '!', }; - QuicFramerPeer::SetIsServer(&framer_, false); + QuicFramerPeer::SetPerspective(&framer_, Perspective::IS_CLIENT); scoped_ptr<QuicPacket> data(BuildDataPacket(header, frames)); ASSERT_TRUE(data != nullptr);
diff --git a/net/quic/quic_headers_stream.cc b/net/quic/quic_headers_stream.cc index b40142db..435267b 100644 --- a/net/quic/quic_headers_stream.cc +++ b/net/quic/quic_headers_stream.cc
@@ -222,7 +222,7 @@ QuicAckNotifier::DelegateInterface* ack_notifier_delegate) { scoped_ptr<SpdySerializedFrame> frame; if (spdy_framer_->protocol_version() == SPDY3) { - if (session()->is_server()) { + if (session()->perspective() == Perspective::IS_SERVER) { SpdySynReplyIR syn_reply(stream_id); syn_reply.set_name_value_block(headers); syn_reply.set_fin(fin); @@ -238,7 +238,7 @@ SpdyHeadersIR headers_frame(stream_id); headers_frame.set_name_value_block(headers); headers_frame.set_fin(fin); - if (!session()->is_server()) { + if (session()->perspective() == Perspective::IS_CLIENT) { headers_frame.set_has_priority(true); headers_frame.set_priority(priority); } @@ -275,7 +275,7 @@ void QuicHeadersStream::OnSynStream(SpdyStreamId stream_id, SpdyPriority priority, bool fin) { - if (!session()->is_server()) { + if (session()->perspective() == Perspective::IS_CLIENT) { CloseConnectionWithDetails( QUIC_INVALID_HEADERS_STREAM_DATA, "SPDY SYN_STREAM frame received at the client"); @@ -288,7 +288,7 @@ } void QuicHeadersStream::OnSynReply(SpdyStreamId stream_id, bool fin) { - if (session()->is_server()) { + if (session()->perspective() == Perspective::IS_SERVER) { CloseConnectionWithDetails( QUIC_INVALID_HEADERS_STREAM_DATA, "SPDY SYN_REPLY frame received at the server");
diff --git a/net/quic/quic_headers_stream_test.cc b/net/quic/quic_headers_stream_test.cc index d4cf018..1016f16 100644 --- a/net/quic/quic_headers_stream_test.cc +++ b/net/quic/quic_headers_stream_test.cc
@@ -76,17 +76,17 @@ // Run all tests with each version, and client or server struct TestParams { - TestParams(QuicVersion version, bool is_server) - : version(version), is_server(is_server) {} + TestParams(QuicVersion version, Perspective perspective) + : version(version), perspective(perspective) {} friend ostream& operator<<(ostream& os, const TestParams& p) { os << "{ version: " << QuicVersionToString(p.version); - os << ", is_server: " << p.is_server << " }"; + os << ", perspective: " << p.perspective << " }"; return os; } QuicVersion version; - bool is_server; + Perspective perspective; }; // Constructs various test permutations. @@ -94,8 +94,8 @@ vector<TestParams> params; QuicVersionVector all_supported_versions = QuicSupportedVersions(); for (const QuicVersion version : all_supported_versions) { - params.push_back(TestParams(version, false)); - params.push_back(TestParams(version, true)); + params.push_back(TestParams(version, Perspective::IS_CLIENT)); + params.push_back(TestParams(version, Perspective::IS_SERVER)); } return params; } @@ -103,7 +103,8 @@ class QuicHeadersStreamTest : public ::testing::TestWithParam<TestParams> { public: QuicHeadersStreamTest() - : connection_(new StrictMock<MockConnection>(is_server(), GetVersion())), + : connection_( + new StrictMock<MockConnection>(perspective(), GetVersion())), session_(connection_), headers_stream_(QuicSessionPeer::GetHeadersStream(&session_)), body_("hello world"), @@ -197,7 +198,7 @@ saved_header_data_.clear(); } - bool is_server() { return GetParam().is_server; } + Perspective perspective() { return GetParam().perspective; } QuicVersion version() { return GetParam().version; } @@ -244,7 +245,7 @@ stream_id < kClientDataStreamId3; stream_id += 2) { for (int count = 0; count < 2; ++count) { bool fin = (count == 0); - if (is_server()) { + if (perspective() == Perspective::IS_SERVER) { WriteHeadersAndExpectSynReply(stream_id, fin); } else { for (QuicPriority priority = 0; priority < 7; ++priority) { @@ -264,7 +265,7 @@ for (QuicPriority priority = 0; priority < 7; ++priority) { // Replace with "WriteHeadersAndSaveData" scoped_ptr<SpdySerializedFrame> frame; - if (is_server()) { + if (perspective() == Perspective::IS_SERVER) { if (version() > QUIC_VERSION_23) { SpdyHeadersIR headers_frame(stream_id); headers_frame.set_name_value_block(headers_); @@ -318,7 +319,7 @@ for (QuicPriority priority = 0; priority < 7; ++priority) { // Replace with "WriteHeadersAndSaveData" scoped_ptr<SpdySerializedFrame> frame; - if (is_server()) { + if (perspective() == Perspective::IS_SERVER) { if (version() > QUIC_VERSION_23) { SpdyHeadersIR headers_frame(stream_id); headers_frame.set_name_value_block(headers_);
diff --git a/net/quic/quic_http_stream_test.cc b/net/quic/quic_http_stream_test.cc index 71417a1..497493c3 100644 --- a/net/quic/quic_http_stream_test.cc +++ b/net/quic/quic_http_stream_test.cc
@@ -64,11 +64,10 @@ address, helper, writer_factory, - true /* owns_writer */, - false /* is_server */, - false /* is_secure */, - versions) { - } + true /* owns_writer */, + Perspective::IS_CLIENT, + false /* is_secure */, + versions) {} void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) { QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
diff --git a/net/quic/quic_packet_creator.cc b/net/quic/quic_packet_creator.cc index 6fecaa8..ac2a94e 100644 --- a/net/quic/quic_packet_creator.cc +++ b/net/quic/quic_packet_creator.cc
@@ -75,7 +75,7 @@ sequence_number_(0), should_fec_protect_(false), fec_group_number_(0), - send_version_in_packet_(!framer->is_server()), + send_version_in_packet_(framer->perspective() == Perspective::IS_CLIENT), max_packet_length_(kDefaultMaxPacketSize), max_packets_per_fec_group_(kDefaultMaxPacketsPerFecGroup), connection_id_length_(PACKET_8BYTE_CONNECTION_ID), @@ -452,7 +452,7 @@ QuicEncryptedPacket* QuicPacketCreator::SerializeVersionNegotiationPacket( const QuicVersionVector& supported_versions) { - DCHECK(framer_->is_server()); + DCHECK_EQ(Perspective::IS_SERVER, framer_->perspective()); QuicPacketPublicHeader header; header.connection_id = connection_id_; header.reset_flag = false;
diff --git a/net/quic/quic_packet_creator_test.cc b/net/quic/quic_packet_creator_test.cc index 877ccc8..75a86763 100644 --- a/net/quic/quic_packet_creator_test.cc +++ b/net/quic/quic_packet_creator_test.cc
@@ -73,10 +73,12 @@ class QuicPacketCreatorTest : public ::testing::TestWithParam<TestParams> { protected: QuicPacketCreatorTest() - : server_framer_(SupportedVersions(GetParam().version), QuicTime::Zero(), - true), - client_framer_(SupportedVersions(GetParam().version), QuicTime::Zero(), - false), + : server_framer_(SupportedVersions(GetParam().version), + QuicTime::Zero(), + Perspective::IS_SERVER), + client_framer_(SupportedVersions(GetParam().version), + QuicTime::Zero(), + Perspective::IS_CLIENT), connection_id_(2), data_("foo"), creator_(connection_id_, &client_framer_, &mock_random_) { @@ -779,7 +781,7 @@ } TEST_P(QuicPacketCreatorTest, SerializeVersionNegotiationPacket) { - QuicFramerPeer::SetIsServer(&client_framer_, true); + QuicFramerPeer::SetPerspective(&client_framer_, Perspective::IS_SERVER); QuicVersionVector versions; versions.push_back(test::QuicVersionMax()); scoped_ptr<QuicEncryptedPacket> encrypted( @@ -791,7 +793,7 @@ EXPECT_CALL(framer_visitor_, OnUnauthenticatedPublicHeader(_)); EXPECT_CALL(framer_visitor_, OnVersionNegotiationPacket(_)); } - QuicFramerPeer::SetIsServer(&client_framer_, false); + QuicFramerPeer::SetPerspective(&client_framer_, Perspective::IS_CLIENT); client_framer_.ProcessPacket(*encrypted); }
diff --git a/net/quic/quic_packet_generator_test.cc b/net/quic/quic_packet_generator_test.cc index a8abf27..ea0bf3b1 100644 --- a/net/quic/quic_packet_generator_test.cc +++ b/net/quic/quic_packet_generator_test.cc
@@ -106,7 +106,9 @@ class QuicPacketGeneratorTest : public ::testing::Test { protected: QuicPacketGeneratorTest() - : framer_(QuicSupportedVersions(), QuicTime::Zero(), false), + : framer_(QuicSupportedVersions(), + QuicTime::Zero(), + Perspective::IS_CLIENT), generator_(42, &framer_, &random_, &delegate_), creator_(QuicPacketGeneratorPeer::GetPacketCreator(&generator_)), packet_(0, PACKET_1BYTE_SEQUENCE_NUMBER, nullptr, 0, nullptr),
diff --git a/net/quic/quic_protocol.cc b/net/quic/quic_protocol.cc index 6cd3ae9..284586ae 100644 --- a/net/quic/quic_protocol.cc +++ b/net/quic/quic_protocol.cc
@@ -199,6 +199,15 @@ return result; } +ostream& operator<<(ostream& os, const Perspective& s) { + if (s == Perspective::IS_SERVER) { + os << "IS_SERVER"; + } else { + os << "IS_CLIENT"; + } + return os; +} + ostream& operator<<(ostream& os, const QuicPacketHeader& header) { os << "{ connection_id: " << header.public_header.connection_id << ", connection_id_length:" << header.public_header.connection_id_length @@ -615,6 +624,18 @@ return frames_.back(); } +void RetransmittableFrames::RemoveFramesForStream(QuicStreamId stream_id) { + QuicFrames::iterator it = frames_.begin(); + while (it != frames_.end()) { + if (it->type != STREAM_FRAME || it->stream_frame->stream_id != stream_id) { + ++it; + continue; + } + delete it->stream_frame; + it = frames_.erase(it); + } +} + SerializedPacket::SerializedPacket( QuicPacketSequenceNumber sequence_number, QuicSequenceNumberLength sequence_number_length,
diff --git a/net/quic/quic_protocol.h b/net/quic/quic_protocol.h index 398a5fd..69b2ab4 100644 --- a/net/quic/quic_protocol.h +++ b/net/quic/quic_protocol.h
@@ -193,6 +193,11 @@ IS_HANDSHAKE }; +enum class Perspective { IS_SERVER, IS_CLIENT }; + +NET_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& os, + const Perspective& s); + // Indicates FEC protection level for data being written. enum FecProtection { MUST_FEC_PROTECT, // Callee must FEC protect this data. @@ -974,6 +979,9 @@ const QuicFrame& AddStreamFrame(QuicStreamFrame* stream_frame); // Takes ownership of the frame inside |frame|. const QuicFrame& AddNonStreamFrame(const QuicFrame& frame); + // Removes all stream frames associated with |stream_id|. + void RemoveFramesForStream(QuicStreamId stream_id); + const QuicFrames& frames() const { return frames_; } IsHandshake HasCryptoHandshake() const {
diff --git a/net/quic/quic_reliable_client_stream_test.cc b/net/quic/quic_reliable_client_stream_test.cc index 4da460c..977542a 100644 --- a/net/quic/quic_reliable_client_stream_test.cc +++ b/net/quic/quic_reliable_client_stream_test.cc
@@ -42,7 +42,8 @@ : public ::testing::TestWithParam<QuicVersion> { public: QuicReliableClientStreamTest() - : session_(new MockConnection(false, SupportedVersions(GetParam()))) { + : session_(new MockConnection(Perspective::IS_CLIENT, + SupportedVersions(GetParam()))) { stream_ = new QuicReliableClientStream(kStreamId, &session_, BoundNetLog()); session_.ActivateStream(stream_); stream_->SetDelegate(&delegate_);
diff --git a/net/quic/quic_sent_packet_manager.cc b/net/quic/quic_sent_packet_manager.cc index 242d8e7..8a198db 100644 --- a/net/quic/quic_sent_packet_manager.cc +++ b/net/quic/quic_sent_packet_manager.cc
@@ -65,17 +65,18 @@ } // namespace -#define ENDPOINT (is_server_ ? "Server: " : " Client: ") +#define ENDPOINT \ + (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") QuicSentPacketManager::QuicSentPacketManager( - bool is_server, + Perspective perspective, const QuicClock* clock, QuicConnectionStats* stats, CongestionControlType congestion_control_type, LossDetectionType loss_type, bool is_secure) : unacked_packets_(), - is_server_(is_server), + perspective_(perspective), clock_(clock), stats_(stats), debug_delegate_(nullptr), @@ -140,11 +141,8 @@ send_algorithm_.reset(SendAlgorithmInterface::Create( clock_, &rtt_stats_, kReno, stats_, initial_congestion_window_)); } - if (HasClientSentConnectionOption(config, kPACE) || - FLAGS_quic_enable_pacing || - (FLAGS_quic_allow_bbr && HasClientSentConnectionOption(config, kTBBR))) { - EnablePacing(); - } + EnablePacing(); + if (HasClientSentConnectionOption(config, k1CON)) { send_algorithm_->SetNumEmulatedConnections(1); } @@ -166,7 +164,7 @@ max(kMinSocketReceiveBuffer, static_cast<QuicByteCount>(config.ReceivedSocketReceiveBuffer())); } - send_algorithm_->SetFromConfig(config, is_server_, using_pacing_); + send_algorithm_->SetFromConfig(config, perspective_, using_pacing_); if (network_change_visitor_ != nullptr) { network_change_visitor_->OnCongestionWindowChange(); @@ -195,7 +193,7 @@ bool QuicSentPacketManager::HasClientSentConnectionOption( const QuicConfig& config, QuicTag tag) const { - if (is_server_) { + if (perspective_ == Perspective::IS_SERVER) { if (config.HasReceivedConnectionOptions() && ContainsQuicTag(config.ReceivedConnectionOptions(), tag)) { return true; @@ -935,6 +933,8 @@ } void QuicSentPacketManager::EnablePacing() { + // TODO(ianswett): Replace with a method which wraps the send algorithm in a + // pacer every time a new algorithm is set. if (using_pacing_) { return; }
diff --git a/net/quic/quic_sent_packet_manager.h b/net/quic/quic_sent_packet_manager.h index d917106..88d69ac 100644 --- a/net/quic/quic_sent_packet_manager.h +++ b/net/quic/quic_sent_packet_manager.h
@@ -93,7 +93,7 @@ QuicSequenceNumberLength sequence_number_length; }; - QuicSentPacketManager(bool is_server, + QuicSentPacketManager(Perspective perspective, const QuicClock* clock, QuicConnectionStats* stats, CongestionControlType congestion_control_type, @@ -352,8 +352,8 @@ // Pending retransmissions which have not been packetized and sent yet. PendingRetransmissionMap pending_retransmissions_; - // Tracks if the connection was created by the server. - bool is_server_; + // Tracks if the connection was created by the server or the client. + Perspective perspective_; // An AckNotifier can register to be informed when ACKs have been received for // all packets that a given block of data was sent in. The AckNotifierManager
diff --git a/net/quic/quic_sent_packet_manager_test.cc b/net/quic/quic_sent_packet_manager_test.cc index c74b744..76fb1b5 100644 --- a/net/quic/quic_sent_packet_manager_test.cc +++ b/net/quic/quic_sent_packet_manager_test.cc
@@ -46,7 +46,7 @@ class QuicSentPacketManagerTest : public ::testing::TestWithParam<bool> { protected: QuicSentPacketManagerTest() - : manager_(true, &clock_, &stats_, kCubic, kNack, false), + : manager_(Perspective::IS_SERVER, &clock_, &stats_, kCubic, kNack, true), send_algorithm_(new StrictMock<MockSendAlgorithm>), network_change_visitor_(new StrictMock<MockNetworkChangeVisitor>) { QuicSentPacketManagerPeer::SetSendAlgorithm(&manager_, send_algorithm_); @@ -1123,7 +1123,7 @@ QuicConfig client_config; QuicTagVector options; options.push_back(kNRTO); - QuicSentPacketManagerPeer::SetIsServer(&manager_, false); + QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT); client_config.SetConnectionOptionsToSend(options); EXPECT_CALL(*network_change_visitor_, OnCongestionWindowChange()); EXPECT_CALL(*network_change_visitor_, OnRttChange()); @@ -1486,7 +1486,7 @@ EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, _)); manager_.SetFromConfig(config); - QuicSentPacketManagerPeer::SetIsServer(&manager_, false); + QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT); QuicConfig client_config; client_config.SetConnectionOptionsToSend(options); EXPECT_CALL(*network_change_visitor_, OnCongestionWindowChange()); @@ -1532,7 +1532,7 @@ QuicTagVector options; options.push_back(kNTLP); - QuicSentPacketManagerPeer::SetIsServer(&manager_, false); + QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT); client_config.SetConnectionOptionsToSend(options); EXPECT_CALL(*network_change_visitor_, OnCongestionWindowChange()); EXPECT_CALL(*network_change_visitor_, OnRttChange()); @@ -1561,7 +1561,7 @@ QuicTagVector options; options.push_back(kNRTO); - QuicSentPacketManagerPeer::SetIsServer(&manager_, false); + QuicSentPacketManagerPeer::SetPerspective(&manager_, Perspective::IS_CLIENT); client_config.SetConnectionOptionsToSend(options); EXPECT_CALL(*network_change_visitor_, OnCongestionWindowChange()); EXPECT_CALL(*network_change_visitor_, OnRttChange()); @@ -1585,21 +1585,6 @@ EXPECT_TRUE(manager_.using_pacing()); } -TEST_F(QuicSentPacketManagerTest, EnablePacingViaFlag) { - EXPECT_FALSE(manager_.using_pacing()); - - // If pacing is enabled via command-line flag, it will be turned on, - // regardless of the contents of the config. - ValueRestore<bool> old_flag(&FLAGS_quic_enable_pacing, true); - QuicConfig config; - EXPECT_CALL(*network_change_visitor_, OnCongestionWindowChange()); - EXPECT_CALL(*network_change_visitor_, OnRttChange()); - EXPECT_CALL(*send_algorithm_, SetFromConfig(_, _, /*using_pacing=*/true)); - manager_.SetFromConfig(config); - - EXPECT_TRUE(manager_.using_pacing()); -} - TEST_F(QuicSentPacketManagerTest, NegotiateReceiveWindowFromOptions) { EXPECT_EQ(kDefaultSocketReceiveBuffer, QuicSentPacketManagerPeer::GetReceiveWindow(&manager_));
diff --git a/net/quic/quic_server_session.cc b/net/quic/quic_server_session.cc index 41b2a88b..f28bedf 100644 --- a/net/quic/quic_server_session.cc +++ b/net/quic/quic_server_session.cc
@@ -155,6 +155,9 @@ } crypto_stream_->SendServerConfigUpdate(&cached_network_params); + + connection()->OnSendConnectionState(cached_network_params); + last_scup_time_ = now; last_scup_sequence_number_ = connection()->sequence_number_of_last_sent_packet();
diff --git a/net/quic/quic_session.cc b/net/quic/quic_session.cc index c8231a0..ac28ba8 100644 --- a/net/quic/quic_session.cc +++ b/net/quic/quic_session.cc
@@ -22,7 +22,8 @@ namespace net { -#define ENDPOINT (is_server() ? "Server: " : " Client: ") +#define ENDPOINT \ + (perspective() == Perspective::IS_SERVER ? "Server: " : " Client: ") // We want to make sure we delete any closed streams in a safe manner. // To avoid deleting a stream in mid-operation, we have a simple shim between @@ -101,14 +102,14 @@ visitor_shim_(new VisitorShim(this)), config_(config), max_open_streams_(config_.MaxStreamsPerConnection()), - next_stream_id_(is_server() ? 2 : 5), + next_stream_id_(perspective() == Perspective::IS_SERVER ? 2 : 5), write_blocked_streams_(true), largest_peer_created_stream_id_(0), error_(QUIC_NO_ERROR), flow_controller_(new QuicFlowController( connection_.get(), 0, - is_server(), + perspective(), kMinimumFlowControlSendWindow, config_.GetInitialSessionFlowControlWindowToSend(), config_.GetInitialSessionFlowControlWindowToSend())), @@ -461,7 +462,7 @@ connection_->SetFromConfig(config_); uint32 max_streams = config_.MaxStreamsPerConnection(); - if (is_server()) { + if (perspective() == Perspective::IS_SERVER) { // A server should accept a small number of additional streams beyond the // limit sent to the client. This helps avoid early connection termination // when FIN/RSTs for old streams are lost or arrive out of order. @@ -633,7 +634,7 @@ return nullptr; } if (largest_peer_created_stream_id_ == 0) { - if (is_server()) { + if (perspective() == Perspective::IS_SERVER) { largest_peer_created_stream_id_ = 3; } else { largest_peer_created_stream_id_ = 1;
diff --git a/net/quic/quic_session.h b/net/quic/quic_session.h index 9502331..6e913ec 100644 --- a/net/quic/quic_session.h +++ b/net/quic/quic_session.h
@@ -202,7 +202,7 @@ QuicErrorCode error() const { return error_; } - bool is_server() const { return connection_->is_server(); } + Perspective perspective() const { return connection_->perspective(); } QuicFlowController* flow_controller() { return flow_controller_.get(); }
diff --git a/net/quic/quic_session_test.cc b/net/quic/quic_session_test.cc index 842c4eb..b4f831d 100644 --- a/net/quic/quic_session_test.cc +++ b/net/quic/quic_session_test.cc
@@ -184,7 +184,8 @@ class QuicSessionTest : public ::testing::TestWithParam<QuicVersion> { protected: QuicSessionTest() - : connection_(new MockConnection(true, SupportedVersions(GetParam()))), + : connection_(new MockConnection(Perspective::IS_SERVER, + SupportedVersions(GetParam()))), session_(connection_) { session_.config()->SetInitialStreamFlowControlWindowToSend( kInitialStreamFlowControlWindowForTest);
diff --git a/net/quic/quic_stream_factory.cc b/net/quic/quic_stream_factory.cc index a364490..b5db6e1e 100644 --- a/net/quic/quic_stream_factory.cc +++ b/net/quic/quic_stream_factory.cc
@@ -1079,14 +1079,10 @@ FROM_HERE_WITH_EXPLICIT_FUNCTION( "422516 QuicStreamFactory::CreateSession4")); - QuicConnection* connection = new QuicConnection(connection_id, - addr, - helper_.get(), - packet_writer_factory, - true /* owns_writer */, - false /* is_server */, - server_id.is_https(), - supported_versions_); + QuicConnection* connection = new QuicConnection( + connection_id, addr, helper_.get(), packet_writer_factory, + true /* owns_writer */, Perspective::IS_CLIENT, server_id.is_https(), + supported_versions_); connection->set_max_packet_length(max_packet_length_); // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
diff --git a/net/quic/quic_stream_sequencer_test.cc b/net/quic/quic_stream_sequencer_test.cc index c5ddb7bc..e15f3d3e 100644 --- a/net/quic/quic_stream_sequencer_test.cc +++ b/net/quic/quic_stream_sequencer_test.cc
@@ -61,13 +61,12 @@ class QuicStreamSequencerTest : public ::testing::Test { protected: QuicStreamSequencerTest() - : connection_(new MockConnection(false)), + : connection_(new MockConnection(Perspective::IS_CLIENT)), session_(connection_), stream_(&session_, 1), sequencer_(new QuicStreamSequencer(&stream_)), buffered_frames_( - QuicStreamSequencerPeer::GetBufferedFrames(sequencer_.get())) { - } + QuicStreamSequencerPeer::GetBufferedFrames(sequencer_.get())) {} bool VerifyIovec(const iovec& iovec, StringPiece expected) { if (iovec.iov_len != expected.length()) {
diff --git a/net/quic/quic_unacked_packet_map.cc b/net/quic/quic_unacked_packet_map.cc index 194443bf..0ada9f6 100644 --- a/net/quic/quic_unacked_packet_map.cc +++ b/net/quic/quic_unacked_packet_map.cc
@@ -300,6 +300,25 @@ } } +void QuicUnackedPacketMap::StopRetransmissionForStream(QuicStreamId stream_id) { + if (stream_id == kCryptoStreamId || stream_id == kHeadersStreamId) { + LOG(DFATAL) << "Special streams must always retransmit data: " << stream_id; + return; + } + QuicPacketSequenceNumber sequence_number = least_unacked_; + for (UnackedPacketMap::const_iterator it = unacked_packets_.begin(); + it != unacked_packets_.end(); ++it, ++sequence_number) { + RetransmittableFrames* retransmittable_frames = it->retransmittable_frames; + if (!retransmittable_frames) { + continue; + } + retransmittable_frames->RemoveFramesForStream(stream_id); + if (retransmittable_frames->frames().empty()) { + RemoveRetransmittability(sequence_number); + } + } +} + bool QuicUnackedPacketMap::HasUnackedPackets() const { return !unacked_packets_.empty(); }
diff --git a/net/quic/quic_unacked_packet_map.h b/net/quic/quic_unacked_packet_map.h index 0c14ca2..040118a 100644 --- a/net/quic/quic_unacked_packet_map.h +++ b/net/quic/quic_unacked_packet_map.h
@@ -43,6 +43,9 @@ // Marks |sequence_number| as no longer in flight. void RemoveFromInFlight(QuicPacketSequenceNumber sequence_number); + // No longer retransmit data for |stream_id|. + void StopRetransmissionForStream(QuicStreamId stream_id); + // Returns true if the unacked packet |sequence_number| has retransmittable // frames. This will return false if the packet has been acked, if a // previous transmission of this packet was ACK'd, or if this packet has been
diff --git a/net/quic/quic_unacked_packet_map_test.cc b/net/quic/quic_unacked_packet_map_test.cc index 0e1d68aa..cf622e1 100644 --- a/net/quic/quic_unacked_packet_map_test.cc +++ b/net/quic/quic_unacked_packet_map_test.cc
@@ -36,6 +36,18 @@ new RetransmittableFrames(ENCRYPTION_NONE)); } + SerializedPacket CreateRetransmittablePacketForStream( + QuicPacketSequenceNumber sequence_number, + QuicStreamId stream_id) { + packets_.push_back(new QuicEncryptedPacket(nullptr, kDefaultLength)); + RetransmittableFrames* frames = new RetransmittableFrames(ENCRYPTION_NONE); + QuicStreamFrame* frame = new QuicStreamFrame(); + frame->stream_id = stream_id; + frames->AddStreamFrame(frame); + return SerializedPacket(sequence_number, PACKET_1BYTE_SEQUENCE_NUMBER, + packets_.back(), 0, frames); + } + SerializedPacket CreateNonRetransmittablePacket( QuicPacketSequenceNumber sequence_number) { packets_.push_back(new QuicEncryptedPacket(nullptr, kDefaultLength)); @@ -165,6 +177,64 @@ VerifyRetransmittablePackets(nullptr, 0); } +TEST_F(QuicUnackedPacketMapTest, StopRetransmission) { + const QuicStreamId stream_id = 2; + unacked_packets_.AddSentPacket( + CreateRetransmittablePacketForStream(1, stream_id), 0, NOT_RETRANSMISSION, + now_, kDefaultLength, true); + + QuicPacketSequenceNumber unacked[] = {1}; + VerifyUnackedPackets(unacked, arraysize(unacked)); + VerifyInFlightPackets(unacked, arraysize(unacked)); + QuicPacketSequenceNumber retransmittable[] = {1}; + VerifyRetransmittablePackets(retransmittable, arraysize(retransmittable)); + + unacked_packets_.StopRetransmissionForStream(stream_id); + VerifyUnackedPackets(unacked, arraysize(unacked)); + VerifyInFlightPackets(unacked, arraysize(unacked)); + VerifyRetransmittablePackets(nullptr, 0); +} + +TEST_F(QuicUnackedPacketMapTest, StopRetransmissionOnOtherStream) { + const QuicStreamId stream_id = 2; + unacked_packets_.AddSentPacket( + CreateRetransmittablePacketForStream(1, stream_id), 0, NOT_RETRANSMISSION, + now_, kDefaultLength, true); + + QuicPacketSequenceNumber unacked[] = {1}; + VerifyUnackedPackets(unacked, arraysize(unacked)); + VerifyInFlightPackets(unacked, arraysize(unacked)); + QuicPacketSequenceNumber retransmittable[] = {1}; + VerifyRetransmittablePackets(retransmittable, arraysize(retransmittable)); + + // Stop retransmissions on another stream and verify the packet is unchanged. + unacked_packets_.StopRetransmissionForStream(stream_id + 2); + VerifyUnackedPackets(unacked, arraysize(unacked)); + VerifyInFlightPackets(unacked, arraysize(unacked)); + VerifyRetransmittablePackets(retransmittable, arraysize(retransmittable)); +} + +TEST_F(QuicUnackedPacketMapTest, StopRetransmissionAfterRetransmission) { + const QuicStreamId stream_id = 2; + unacked_packets_.AddSentPacket( + CreateRetransmittablePacketForStream(1, stream_id), 0, NOT_RETRANSMISSION, + now_, kDefaultLength, true); + unacked_packets_.AddSentPacket(CreateNonRetransmittablePacket(2), 1, + LOSS_RETRANSMISSION, now_, kDefaultLength, + true); + + QuicPacketSequenceNumber unacked[] = {1, 2}; + VerifyUnackedPackets(unacked, arraysize(unacked)); + VerifyInFlightPackets(unacked, arraysize(unacked)); + QuicPacketSequenceNumber retransmittable[] = {2}; + VerifyRetransmittablePackets(retransmittable, arraysize(retransmittable)); + + unacked_packets_.StopRetransmissionForStream(stream_id); + VerifyUnackedPackets(unacked, arraysize(unacked)); + VerifyInFlightPackets(unacked, arraysize(unacked)); + VerifyRetransmittablePackets(nullptr, 0); +} + TEST_F(QuicUnackedPacketMapTest, RetransmittedPacket) { // Simulate a retransmittable packet being sent, retransmitted, and the first // transmission being acked.
diff --git a/net/quic/reliable_quic_stream.cc b/net/quic/reliable_quic_stream.cc index adb8051..6eb0378 100644 --- a/net/quic/reliable_quic_stream.cc +++ b/net/quic/reliable_quic_stream.cc
@@ -17,7 +17,8 @@ namespace net { -#define ENDPOINT (is_server_ ? "Server: " : " Client: ") +#define ENDPOINT \ + (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") namespace { @@ -126,12 +127,13 @@ rst_sent_(false), rst_received_(false), fec_policy_(FEC_PROTECT_OPTIONAL), - is_server_(session_->is_server()), - flow_controller_( - session_->connection(), id_, is_server_, - GetReceivedFlowControlWindow(session), - GetInitialStreamFlowControlWindowToSend(session), - GetInitialStreamFlowControlWindowToSend(session)), + perspective_(session_->perspective()), + flow_controller_(session_->connection(), + id_, + perspective_, + GetReceivedFlowControlWindow(session), + GetInitialStreamFlowControlWindowToSend(session), + GetInitialStreamFlowControlWindowToSend(session)), connection_flow_controller_(session_->flow_controller()), stream_contributes_to_connection_flow_control_(true) { }
diff --git a/net/quic/reliable_quic_stream.h b/net/quic/reliable_quic_stream.h index 3139ae7..806c6a6 100644 --- a/net/quic/reliable_quic_stream.h +++ b/net/quic/reliable_quic_stream.h
@@ -227,8 +227,9 @@ // FEC policy to be used for this stream. FecPolicy fec_policy_; - // True if the session this stream is running under is a server session. - bool is_server_; + // Tracks if the session this stream is running under was created by a + // server or a client. + Perspective perspective_; QuicFlowController flow_controller_;
diff --git a/net/quic/reliable_quic_stream_test.cc b/net/quic/reliable_quic_stream_test.cc index 5073e1e..f88beb1 100644 --- a/net/quic/reliable_quic_stream_test.cc +++ b/net/quic/reliable_quic_stream_test.cc
@@ -38,7 +38,6 @@ const char kData1[] = "FooAndBar"; const char kData2[] = "EepAndBaz"; const size_t kDataLen = 9; -const bool kIsServer = true; const bool kShouldProcessData = true; class TestStream : public ReliableQuicStream { @@ -106,8 +105,8 @@ } void Initialize(bool stream_should_process_data) { - connection_ = - new StrictMock<MockConnection>(kIsServer, supported_versions_); + connection_ = new StrictMock<MockConnection>(Perspective::IS_SERVER, + supported_versions_); session_.reset(new StrictMock<MockSession>(connection_)); // New streams rely on having the peer's flow control receive window
diff --git a/net/quic/test_tools/crypto_test_utils.cc b/net/quic/test_tools/crypto_test_utils.cc index d6238bd..22854bd 100644 --- a/net/quic/test_tools/crypto_test_utils.cc +++ b/net/quic/test_tools/crypto_test_utils.cc
@@ -183,8 +183,8 @@ int CryptoTestUtils::HandshakeWithFakeServer( PacketSavingConnection* client_conn, QuicCryptoClientStream* client) { - PacketSavingConnection* server_conn = - new PacketSavingConnection(true, client_conn->supported_versions()); + PacketSavingConnection* server_conn = new PacketSavingConnection( + Perspective::IS_SERVER, client_conn->supported_versions()); TestSession server_session(server_conn, DefaultQuicConfig()); server_session.InitializeSession(); QuicCryptoServerConfig crypto_config(QuicCryptoServerConfig::TESTING, @@ -213,7 +213,8 @@ PacketSavingConnection* server_conn, QuicCryptoServerStream* server, const FakeClientOptions& options) { - PacketSavingConnection* client_conn = new PacketSavingConnection(false); + PacketSavingConnection* client_conn = + new PacketSavingConnection(Perspective::IS_CLIENT); // Advance the time, because timers do not like uninitialized times. client_conn->AdvanceTime(QuicTime::Delta::FromSeconds(1)); TestClientSession client_session(client_conn, DefaultQuicConfig());
diff --git a/net/quic/test_tools/quic_connection_peer.cc b/net/quic/test_tools/quic_connection_peer.cc index dd75ca8..3525a324 100644 --- a/net/quic/test_tools/quic_connection_peer.cc +++ b/net/quic/test_tools/quic_connection_peer.cc
@@ -100,15 +100,10 @@ } // static -bool QuicConnectionPeer::IsServer(QuicConnection* connection) { - return connection->is_server_; -} - -// static -void QuicConnectionPeer::SetIsServer(QuicConnection* connection, - bool is_server) { - connection->is_server_ = is_server; - QuicFramerPeer::SetIsServer(&connection->framer_, is_server); +void QuicConnectionPeer::SetPerspective(QuicConnection* connection, + Perspective perspective) { + connection->perspective_ = perspective; + QuicFramerPeer::SetPerspective(&connection->framer_, perspective); } // static
diff --git a/net/quic/test_tools/quic_connection_peer.h b/net/quic/test_tools/quic_connection_peer.h index 67463380..88b05f0 100644 --- a/net/quic/test_tools/quic_connection_peer.h +++ b/net/quic/test_tools/quic_connection_peer.h
@@ -67,9 +67,8 @@ QuicConnection* connection, QuicPacketSequenceNumber sequence_number); - static bool IsServer(QuicConnection* connection); - - static void SetIsServer(QuicConnection* connection, bool is_server); + static void SetPerspective(QuicConnection* connection, + Perspective perspective); static void SetSelfAddress(QuicConnection* connection, const IPEndPoint& self_address);
diff --git a/net/quic/test_tools/quic_framer_peer.cc b/net/quic/test_tools/quic_framer_peer.cc index c6464cc..44bbed1 100644 --- a/net/quic/test_tools/quic_framer_peer.cc +++ b/net/quic/test_tools/quic_framer_peer.cc
@@ -31,8 +31,9 @@ framer->last_sequence_number_ = packet_sequence_number; } -void QuicFramerPeer::SetIsServer(QuicFramer* framer, bool is_server) { - framer->is_server_ = is_server; +void QuicFramerPeer::SetPerspective(QuicFramer* framer, + Perspective perspective) { + framer->perspective_ = perspective; } void QuicFramerPeer::SwapCrypters(QuicFramer* framer1, QuicFramer* framer2) {
diff --git a/net/quic/test_tools/quic_framer_peer.h b/net/quic/test_tools/quic_framer_peer.h index 9b9c9fa..c6ddb28 100644 --- a/net/quic/test_tools/quic_framer_peer.h +++ b/net/quic/test_tools/quic_framer_peer.h
@@ -24,7 +24,7 @@ static void SetLastSequenceNumber( QuicFramer* framer, QuicPacketSequenceNumber packet_sequence_number); - static void SetIsServer(QuicFramer* framer, bool is_server); + static void SetPerspective(QuicFramer* framer, Perspective perspective); // SwapCrypters exchanges the state of the crypters of |framer1| with // |framer2|.
diff --git a/net/quic/test_tools/quic_sent_packet_manager_peer.cc b/net/quic/test_tools/quic_sent_packet_manager_peer.cc index c50a1715..add97bb 100644 --- a/net/quic/test_tools/quic_sent_packet_manager_peer.cc +++ b/net/quic/test_tools/quic_sent_packet_manager_peer.cc
@@ -38,10 +38,10 @@ } // static -void QuicSentPacketManagerPeer::SetIsServer( +void QuicSentPacketManagerPeer::SetPerspective( QuicSentPacketManager* sent_packet_manager, - bool is_server) { - sent_packet_manager->is_server_ = is_server; + Perspective perspective) { + sent_packet_manager->perspective_ = perspective; } // static
diff --git a/net/quic/test_tools/quic_sent_packet_manager_peer.h b/net/quic/test_tools/quic_sent_packet_manager_peer.h index 3543a1b..e0686e1c2 100644 --- a/net/quic/test_tools/quic_sent_packet_manager_peer.h +++ b/net/quic/test_tools/quic_sent_packet_manager_peer.h
@@ -27,8 +27,8 @@ static QuicByteCount GetReceiveWindow( QuicSentPacketManager* sent_packet_manager); - static void SetIsServer(QuicSentPacketManager* sent_packet_manager, - bool is_server); + static void SetPerspective(QuicSentPacketManager* sent_packet_manager, + Perspective perspective); static const SendAlgorithmInterface* GetSendAlgorithm( const QuicSentPacketManager& sent_packet_manager);
diff --git a/net/quic/test_tools/quic_test_packet_maker.cc b/net/quic/test_tools/quic_test_packet_maker.cc index ecdd6bf..486c2f51 100644 --- a/net/quic/test_tools/quic_test_packet_maker.cc +++ b/net/quic/test_tools/quic_test_packet_maker.cc
@@ -82,7 +82,8 @@ QuicRstStreamFrame rst(stream_id, error_code, 0); frames.push_back(QuicFrame(&rst)); - QuicFramer framer(SupportedVersions(version_), clock_->Now(), false); + QuicFramer framer(SupportedVersions(version_), clock_->Now(), + Perspective::IS_CLIENT); scoped_ptr<QuicPacket> packet( BuildUnsizedDataPacket(&framer, header, frames)); return scoped_ptr<QuicEncryptedPacket>(framer.EncryptPacket( @@ -128,7 +129,8 @@ ack.received_packet_times.push_back(make_pair(i, clock_->Now())); } - QuicFramer framer(SupportedVersions(version_), clock_->Now(), false); + QuicFramer framer(SupportedVersions(version_), clock_->Now(), + Perspective::IS_CLIENT); QuicFrames frames; frames.push_back(QuicFrame(&ack)); @@ -234,7 +236,8 @@ scoped_ptr<QuicEncryptedPacket> QuicTestPacketMaker::MakePacket( const QuicPacketHeader& header, const QuicFrame& frame) { - QuicFramer framer(SupportedVersions(version_), QuicTime::Zero(), false); + QuicFramer framer(SupportedVersions(version_), QuicTime::Zero(), + Perspective::IS_CLIENT); QuicFrames frames; frames.push_back(frame); scoped_ptr<QuicPacket> packet(
diff --git a/net/quic/test_tools/quic_test_utils.cc b/net/quic/test_tools/quic_test_utils.cc index 4ab3d0c..1c3e0fe 100644 --- a/net/quic/test_tools/quic_test_utils.cc +++ b/net/quic/test_tools/quic_test_utils.cc
@@ -234,63 +234,63 @@ return new testing::NiceMock<MockPacketWriter>(); } -MockConnection::MockConnection(bool is_server) +MockConnection::MockConnection(Perspective perspective) : QuicConnection(kTestConnectionId, IPEndPoint(TestPeerIPAddress(), kTestPort), new testing::NiceMock<MockHelper>(), NiceMockPacketWriterFactory(), /* owns_writer= */ true, - is_server, + perspective, /* is_secure= */ false, QuicSupportedVersions()), helper_(helper()) { } -MockConnection::MockConnection(bool is_server, bool is_secure) +MockConnection::MockConnection(Perspective perspective, bool is_secure) : QuicConnection(kTestConnectionId, IPEndPoint(TestPeerIPAddress(), kTestPort), new testing::NiceMock<MockHelper>(), NiceMockPacketWriterFactory(), /* owns_writer= */ true, - is_server, + perspective, is_secure, QuicSupportedVersions()), helper_(helper()) { } -MockConnection::MockConnection(IPEndPoint address, - bool is_server) - : QuicConnection(kTestConnectionId, address, +MockConnection::MockConnection(IPEndPoint address, Perspective perspective) + : QuicConnection(kTestConnectionId, + address, new testing::NiceMock<MockHelper>(), NiceMockPacketWriterFactory(), /* owns_writer= */ true, - is_server, + perspective, /* is_secure= */ false, QuicSupportedVersions()), helper_(helper()) { } MockConnection::MockConnection(QuicConnectionId connection_id, - bool is_server) + Perspective perspective) : QuicConnection(connection_id, IPEndPoint(TestPeerIPAddress(), kTestPort), new testing::NiceMock<MockHelper>(), NiceMockPacketWriterFactory(), /* owns_writer= */ true, - is_server, + perspective, /* is_secure= */ false, QuicSupportedVersions()), helper_(helper()) { } -MockConnection::MockConnection(bool is_server, +MockConnection::MockConnection(Perspective perspective, const QuicVersionVector& supported_versions) : QuicConnection(kTestConnectionId, IPEndPoint(TestPeerIPAddress(), kTestPort), new testing::NiceMock<MockHelper>(), NiceMockPacketWriterFactory(), /* owns_writer= */ true, - is_server, + perspective, /* is_secure= */ false, supported_versions), helper_(helper()) { @@ -303,14 +303,14 @@ static_cast<MockHelper*>(helper())->AdvanceTime(delta); } -PacketSavingConnection::PacketSavingConnection(bool is_server) - : MockConnection(is_server) { +PacketSavingConnection::PacketSavingConnection(Perspective perspective) + : MockConnection(perspective) { } PacketSavingConnection::PacketSavingConnection( - bool is_server, + Perspective perspective, const QuicVersionVector& supported_versions) - : MockConnection(is_server, supported_versions) { + : MockConnection(perspective, supported_versions) { } PacketSavingConnection::~PacketSavingConnection() { @@ -431,8 +431,9 @@ } hex = hex + " "; - for (const char *p = row; p < row + 4 && p < row + length; ++p) + for (const char* p = row; p < row + 4 && p < row + length; ++p) { hex += (*p >= 0x20 && *p <= 0x7f) ? (*p) : '.'; + } hex = hex + '\n'; } @@ -502,7 +503,8 @@ QuicFrame frame(&stream_frame); QuicFrames frames; frames.push_back(frame); - QuicFramer framer(QuicSupportedVersions(), QuicTime::Zero(), false); + QuicFramer framer(QuicSupportedVersions(), QuicTime::Zero(), + Perspective::IS_CLIENT); scoped_ptr<QuicPacket> packet( BuildUnsizedDataPacket(&framer, header, frames)); EXPECT_TRUE(packet != nullptr); @@ -563,7 +565,8 @@ bool should_include_version) { CryptoFramer crypto_framer; scoped_ptr<QuicData> data(crypto_framer.ConstructHandshakeMessage(message)); - QuicFramer quic_framer(QuicSupportedVersions(), QuicTime::Zero(), false); + QuicFramer quic_framer(QuicSupportedVersions(), QuicTime::Zero(), + Perspective::IS_CLIENT); QuicPacketHeader header; header.public_header.connection_id = connection_id;
diff --git a/net/quic/test_tools/quic_test_utils.h b/net/quic/test_tools/quic_test_utils.h index a2a8951..2be080b2 100644 --- a/net/quic/test_tools/quic_test_utils.h +++ b/net/quic/test_tools/quic_test_utils.h
@@ -20,6 +20,7 @@ #include "net/quic/quic_dispatcher.h" #include "net/quic/quic_framer.h" #include "net/quic/quic_per_connection_packet_writer.h" +#include "net/quic/quic_protocol.h" #include "net/quic/quic_sent_packet_manager.h" #include "net/quic/quic_session.h" #include "net/quic/test_tools/mock_clock.h" @@ -290,19 +291,20 @@ class MockConnection : public QuicConnection { public: // Uses a MockHelper, ConnectionId of 42, and 127.0.0.1:123. - explicit MockConnection(bool is_server); + explicit MockConnection(Perspective perspective); // Uses a MockHelper, ConnectionId of 42, and 127.0.0.1:123. - MockConnection(bool is_server, bool is_secure); + MockConnection(Perspective perspective, bool is_secure); // Uses a MockHelper, ConnectionId of 42. - MockConnection(IPEndPoint address, bool is_server); + MockConnection(IPEndPoint address, Perspective perspective); // Uses a MockHelper, and 127.0.0.1:123 - MockConnection(QuicConnectionId connection_id, bool is_server); + MockConnection(QuicConnectionId connection_id, Perspective perspective); // Uses a Mock helper, ConnectionId of 42, and 127.0.0.1:123. - MockConnection(bool is_server, const QuicVersionVector& supported_versions); + MockConnection(Perspective perspective, + const QuicVersionVector& supported_versions); ~MockConnection() override; @@ -330,6 +332,7 @@ QuicStreamOffset byte_offset)); MOCK_METHOD0(OnCanWrite, void()); + MOCK_METHOD1(OnSendConnectionState, void(const CachedNetworkParameters&)); MOCK_METHOD1(ResumeConnectionState, bool(const CachedNetworkParameters&)); void ReallyProcessUdpPacket(const IPEndPoint& self_address, @@ -350,9 +353,9 @@ class PacketSavingConnection : public MockConnection { public: - explicit PacketSavingConnection(bool is_server); + explicit PacketSavingConnection(Perspective perspective); - PacketSavingConnection(bool is_server, + PacketSavingConnection(Perspective perspective, const QuicVersionVector& supported_versions); ~PacketSavingConnection() override; @@ -464,9 +467,10 @@ MockSendAlgorithm(); ~MockSendAlgorithm() override; - MOCK_METHOD3(SetFromConfig, void(const QuicConfig& config, - bool is_server, - bool using_pacing)); + MOCK_METHOD3(SetFromConfig, + void(const QuicConfig& config, + Perspective perspective, + bool using_pacing)); MOCK_METHOD1(SetNumEmulatedConnections, void(int num_connections)); MOCK_METHOD1(SetMaxPacketSize, void(QuicByteCount max_packet_size)); MOCK_METHOD4(OnCongestionEvent, void(bool rtt_updated,
diff --git a/net/quic/test_tools/simple_quic_framer.cc b/net/quic/test_tools/simple_quic_framer.cc index c6c7b5f8..2e9e373 100644 --- a/net/quic/test_tools/simple_quic_framer.cc +++ b/net/quic/test_tools/simple_quic_framer.cc
@@ -165,11 +165,13 @@ }; SimpleQuicFramer::SimpleQuicFramer() - : framer_(QuicSupportedVersions(), QuicTime::Zero(), true) { + : framer_(QuicSupportedVersions(), + QuicTime::Zero(), + Perspective::IS_SERVER) { } SimpleQuicFramer::SimpleQuicFramer(const QuicVersionVector& supported_versions) - : framer_(supported_versions, QuicTime::Zero(), true) { + : framer_(supported_versions, QuicTime::Zero(), Perspective::IS_SERVER) { } SimpleQuicFramer::~SimpleQuicFramer() {
diff --git a/net/socket/client_socket_pool_manager_impl.cc b/net/socket/client_socket_pool_manager_impl.cc index 6d0751b3..34599aa4 100644 --- a/net/socket/client_socket_pool_manager_impl.cc +++ b/net/socket/client_socket_pool_manager_impl.cc
@@ -45,7 +45,6 @@ CertPolicyEnforcer* cert_policy_enforcer, const std::string& ssl_session_cache_shard, SSLConfigService* ssl_config_service, - bool enable_ssl_connect_job_waiting, HttpNetworkSession::SocketPoolType pool_type) : net_log_(net_log), socket_factory_(socket_factory), @@ -57,7 +56,6 @@ cert_policy_enforcer_(cert_policy_enforcer), ssl_session_cache_shard_(ssl_session_cache_shard), ssl_config_service_(ssl_config_service), - enable_ssl_connect_job_waiting_(enable_ssl_connect_job_waiting), pool_type_(pool_type), transport_pool_histograms_("TCP"), transport_socket_pool_( @@ -90,7 +88,6 @@ NULL /* no socks proxy */, NULL /* no http proxy */, ssl_config_service, - enable_ssl_connect_job_waiting, net_log)), transport_for_socks_pool_histograms_("TCPforSOCKS"), socks_pool_histograms_("SOCK"), @@ -303,8 +300,7 @@ ssl_session_cache_shard_, socket_factory_, tcp_https_ret.first->second /* https proxy */, NULL /* no socks proxy */, NULL /* no http proxy */, - ssl_config_service_.get(), - enable_ssl_connect_job_waiting_, net_log_))); + ssl_config_service_.get(), net_log_))); DCHECK(tcp_https_ret.second); std::pair<HTTPProxySocketPoolMap::iterator, bool> ret = @@ -338,7 +334,7 @@ NULL, /* no tcp pool, we always go through a proxy */ GetSocketPoolForSOCKSProxy(proxy_server), GetSocketPoolForHTTPProxy(proxy_server), ssl_config_service_.get(), - enable_ssl_connect_job_waiting_, net_log_); + net_log_); std::pair<SSLSocketPoolMap::iterator, bool> ret = ssl_socket_pools_for_proxies_.insert(std::make_pair(proxy_server,
diff --git a/net/socket/client_socket_pool_manager_impl.h b/net/socket/client_socket_pool_manager_impl.h index d669333..1c6295b2 100644 --- a/net/socket/client_socket_pool_manager_impl.h +++ b/net/socket/client_socket_pool_manager_impl.h
@@ -65,7 +65,6 @@ CertPolicyEnforcer* cert_policy_enforcer, const std::string& ssl_session_cache_shard, SSLConfigService* ssl_config_service, - bool enable_ssl_connect_job_waiting, HttpNetworkSession::SocketPoolType pool_type); ~ClientSocketPoolManagerImpl() override; @@ -113,7 +112,6 @@ CertPolicyEnforcer* const cert_policy_enforcer_; const std::string ssl_session_cache_shard_; const scoped_refptr<SSLConfigService> ssl_config_service_; - bool enable_ssl_connect_job_waiting_; const HttpNetworkSession::SocketPoolType pool_type_; // Note: this ordering is important.
diff --git a/net/socket/socket_test_util.cc b/net/socket/socket_test_util.cc index 791c9f6..fb22055 100644 --- a/net/socket/socket_test_util.cc +++ b/net/socket/socket_test_util.cc
@@ -10,7 +10,6 @@ #include "base/basictypes.h" #include "base/bind.h" #include "base/bind_helpers.h" -#include "base/callback_helpers.h" #include "base/compiler_specific.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" @@ -279,9 +278,7 @@ client_cert_sent(false), cert_request_info(NULL), channel_id_sent(false), - connection_status(0), - should_pause_on_connect(false), - is_in_session_cache(false) { + connection_status(0) { SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2, &connection_status); // Set to TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 @@ -712,10 +709,8 @@ next_ssl_data->next_protos_expected_in_ssl_config.end(), ssl_config.next_protos.begin())); } - scoped_ptr<MockSSLClientSocket> socket(new MockSSLClientSocket( + return scoped_ptr<SSLClientSocket>(new MockSSLClientSocket( transport_socket.Pass(), host_and_port, ssl_config, next_ssl_data)); - ssl_client_sockets_.push_back(socket.get()); - return socket.Pass(); } void MockClientSocketFactory::ClearSSLSessionCache() { @@ -771,20 +766,6 @@ return net_log_; } -std::string MockClientSocket::GetSessionCacheKey() const { - NOTIMPLEMENTED(); - return std::string(); -} - -bool MockClientSocket::InSessionCache() const { - NOTIMPLEMENTED(); - return false; -} - -void MockClientSocket::SetHandshakeCompletionCallback(const base::Closure& cb) { - NOTIMPLEMENTED(); -} - void MockClientSocket::GetSSLCertRequestInfo( SSLCertRequestInfo* cert_request_info) { } @@ -1324,6 +1305,16 @@ void DeterministicMockTCPClientSocket::OnConnectComplete( const MockConnect& data) {} +// static +void MockSSLClientSocket::ConnectCallback( + MockSSLClientSocket* ssl_client_socket, + const CompletionCallback& callback, + int rv) { + if (rv == OK) + ssl_client_socket->connected_ = true; + callback.Run(rv); +} + MockSSLClientSocket::MockSSLClientSocket( scoped_ptr<ClientSocketHandle> transport_socket, const HostPortPair& host_port_pair, @@ -1334,15 +1325,11 @@ // tests. transport_socket->socket()->NetLog()), transport_(transport_socket.Pass()), - host_port_pair_(host_port_pair), data_(data), is_npn_state_set_(false), new_npn_value_(false), is_protocol_negotiated_set_(false), - protocol_negotiated_(kProtoUnknown), - next_connect_state_(STATE_NONE), - reached_connect_(false), - weak_factory_(this) { + protocol_negotiated_(kProtoUnknown) { DCHECK(data_); peer_addr_ = data->connect.peer_addr; } @@ -1362,23 +1349,28 @@ } int MockSSLClientSocket::Connect(const CompletionCallback& callback) { - next_connect_state_ = STATE_SSL_CONNECT; - reached_connect_ = true; - int rv = DoConnectLoop(OK); - if (rv == ERR_IO_PENDING) - connect_callback_ = callback; + int rv = transport_->socket()->Connect( + base::Bind(&ConnectCallback, base::Unretained(this), callback)); + if (rv == OK) { + if (data_->connect.result == OK) + connected_ = true; + if (data_->connect.mode == ASYNC) { + RunCallbackAsync(callback, data_->connect.result); + return ERR_IO_PENDING; + } + return data_->connect.result; + } return rv; } void MockSSLClientSocket::Disconnect() { - weak_factory_.InvalidateWeakPtrs(); MockClientSocket::Disconnect(); if (transport_->socket() != NULL) transport_->socket()->Disconnect(); } bool MockSSLClientSocket::IsConnected() const { - return transport_->socket()->IsConnected() && connected_; + return transport_->socket()->IsConnected(); } bool MockSSLClientSocket::WasEverUsed() const { @@ -1402,21 +1394,6 @@ return true; } -std::string MockSSLClientSocket::GetSessionCacheKey() const { - // For the purposes of these tests, |host_and_port| will serve as the - // cache key. - return host_port_pair_.ToString(); -} - -bool MockSSLClientSocket::InSessionCache() const { - return data_->is_in_session_cache; -} - -void MockSSLClientSocket::SetHandshakeCompletionCallback( - const base::Closure& cb) { - handshake_completion_callback_ = cb; -} - void MockSSLClientSocket::GetSSLCertRequestInfo( SSLCertRequestInfo* cert_request_info) { DCHECK(cert_request_info); @@ -1478,69 +1455,6 @@ NOTIMPLEMENTED(); } -void MockSSLClientSocket::RestartPausedConnect() { - DCHECK(data_->should_pause_on_connect); - DCHECK_EQ(next_connect_state_, STATE_SSL_CONNECT_COMPLETE); - OnIOComplete(data_->connect.result); -} - -void MockSSLClientSocket::OnIOComplete(int result) { - int rv = DoConnectLoop(result); - if (rv != ERR_IO_PENDING) - base::ResetAndReturn(&connect_callback_).Run(rv); -} - -int MockSSLClientSocket::DoConnectLoop(int result) { - DCHECK_NE(next_connect_state_, STATE_NONE); - - int rv = result; - do { - ConnectState state = next_connect_state_; - next_connect_state_ = STATE_NONE; - switch (state) { - case STATE_SSL_CONNECT: - rv = DoSSLConnect(); - break; - case STATE_SSL_CONNECT_COMPLETE: - rv = DoSSLConnectComplete(rv); - break; - default: - NOTREACHED() << "bad state"; - rv = ERR_UNEXPECTED; - break; - } - } while (rv != ERR_IO_PENDING && next_connect_state_ != STATE_NONE); - - return rv; -} - -int MockSSLClientSocket::DoSSLConnect() { - next_connect_state_ = STATE_SSL_CONNECT_COMPLETE; - - if (data_->should_pause_on_connect) - return ERR_IO_PENDING; - - if (data_->connect.mode == ASYNC) { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&MockSSLClientSocket::OnIOComplete, - weak_factory_.GetWeakPtr(), - data_->connect.result)); - return ERR_IO_PENDING; - } - - return data_->connect.result; -} - -int MockSSLClientSocket::DoSSLConnectComplete(int result) { - if (result == OK) - connected_ = true; - - if (!handshake_completion_callback_.is_null()) - base::ResetAndReturn(&handshake_completion_callback_).Run(); - return result; -} - MockUDPClientSocket::MockUDPClientSocket(SocketDataProvider* data, net::NetLog* net_log) : connected_(false),
diff --git a/net/socket/socket_test_util.h b/net/socket/socket_test_util.h index d6c7aba..ef15a84 100644 --- a/net/socket/socket_test_util.h +++ b/net/socket/socket_test_util.h
@@ -336,12 +336,6 @@ bool channel_id_sent; ChannelIDService* channel_id_service; int connection_status; - // Indicates that the socket should pause in the Connect method. - bool should_pause_on_connect; - // Whether or not the Socket should behave like there is a pre-existing - // session to resume. Whether or not such a session is reported as - // resumed is controlled by |connection_status|. - bool is_in_session_cache; }; // A DataProvider where the client must write a request before the reads (e.g. @@ -645,12 +639,6 @@ return mock_data_; } - // Note: this method is unsafe; the elements of the returned vector - // are not necessarily valid. - const std::vector<MockSSLClientSocket*>& ssl_client_sockets() const { - return ssl_client_sockets_; - } - // ClientSocketFactory scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( DatagramSocket::BindType bind_type, @@ -671,7 +659,6 @@ private: SocketDataProviderArray<SocketDataProvider> mock_data_; SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_; - std::vector<MockSSLClientSocket*> ssl_client_sockets_; }; class MockClientSocket : public SSLClientSocket { @@ -705,9 +692,6 @@ void SetOmniboxSpeculation() override {} // SSLClientSocket implementation. - std::string GetSessionCacheKey() const override; - bool InSessionCache() const override; - void SetHandshakeCompletionCallback(const base::Closure& cb) override; void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override; int ExportKeyingMaterial(const base::StringPiece& label, bool has_context, @@ -966,9 +950,6 @@ bool GetSSLInfo(SSLInfo* ssl_info) override; // SSLClientSocket implementation. - std::string GetSessionCacheKey() const override; - bool InSessionCache() const override; - void SetHandshakeCompletionCallback(const base::Closure& cb) override; void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override; NextProtoStatus GetNextProto(std::string* proto) override; bool set_was_npn_negotiated(bool negotiated) override; @@ -983,45 +964,18 @@ void set_channel_id_sent(bool channel_id_sent) override; ChannelIDService* GetChannelIDService() const override; - bool reached_connect() const { return reached_connect_; } - - // Resumes the connection of a socket that was paused for testing. - // |connect_callback_| should be set before invoking this method. - void RestartPausedConnect(); - private: - enum ConnectState { - STATE_NONE, - STATE_SSL_CONNECT, - STATE_SSL_CONNECT_COMPLETE, - }; - - void OnIOComplete(int result); - - // Runs the state transistion loop. - int DoConnectLoop(int result); - - int DoSSLConnect(); - int DoSSLConnectComplete(int result); + static void ConnectCallback(MockSSLClientSocket* ssl_client_socket, + const CompletionCallback& callback, + int rv); scoped_ptr<ClientSocketHandle> transport_; - HostPortPair host_port_pair_; SSLSocketDataProvider* data_; bool is_npn_state_set_; bool new_npn_value_; bool is_protocol_negotiated_set_; NextProto protocol_negotiated_; - CompletionCallback connect_callback_; - // Indicates what state of Connect the socket should enter. - ConnectState next_connect_state_; - // True if the Connect method has been called on the socket. - bool reached_connect_; - - base::Closure handshake_completion_callback_; - - base::WeakPtrFactory<MockSSLClientSocket> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket); };
diff --git a/net/socket/ssl_client_socket.cc b/net/socket/ssl_client_socket.cc index 5f2b8ac..f333cb8e 100644 --- a/net/socket/ssl_client_socket.cc +++ b/net/socket/ssl_client_socket.cc
@@ -9,7 +9,6 @@ #include "base/strings/string_util.h" #include "crypto/ec_private_key.h" #include "net/base/connection_type_histograms.h" -#include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/ssl/channel_id_service.h" #include "net/ssl/ssl_cipher_suite_names.h"
diff --git a/net/socket/ssl_client_socket.h b/net/socket/ssl_client_socket.h index 90dbd01..357f0d3 100644 --- a/net/socket/ssl_client_socket.h +++ b/net/socket/ssl_client_socket.h
@@ -20,8 +20,6 @@ class CertVerifier; class ChannelIDService; class CTVerifier; -class HostPortPair; -class ServerBoundCertService; class SSLCertRequestInfo; struct SSLConfig; class SSLInfo; @@ -95,39 +93,6 @@ bool WasNpnNegotiated() const override; NextProto GetNegotiatedProtocol() const override; - // Computes a unique key string for the SSL session cache. - virtual std::string GetSessionCacheKey() const = 0; - - // Returns true if there is a cache entry in the SSL session cache - // for the cache key of the SSL socket. - // - // The cache key consists of a host and port concatenated with a session - // cache shard. These two strings are passed to the constructor of most - // subclasses of SSLClientSocket. - virtual bool InSessionCache() const = 0; - - // Sets |callback| to be run when the handshake has fully completed. - // For example, in the case of False Start, Connect() will return - // early, before the peer's TLS Finished message has been verified, - // in order to allow the caller to call Write() and send application - // data with the client's Finished message. - // In such situations, |callback| will be invoked sometime after - // Connect() - either during a Write() or Read() call, and before - // invoking the Read() or Write() callback. - // Otherwise, during a traditional TLS connection (i.e. no False - // Start), this will be called right before the Connect() callback - // is called. - // - // Note that it's not valid to mutate this socket during such - // callbacks, including deleting the socket. - // - // TODO(mshelley): Provide additional details about whether or not - // the handshake actually succeeded or not. This can be inferred - // from the result to Connect()/Read()/Write(), but may be useful - // to inform here as well. - virtual void SetHandshakeCompletionCallback( - const base::Closure& callback) = 0; - // Gets the SSL CertificateRequest info of the socket after Connect failed // with ERR_SSL_CLIENT_AUTH_CERT_NEEDED. virtual void GetSSLCertRequestInfo(
diff --git a/net/socket/ssl_client_socket_nss.cc b/net/socket/ssl_client_socket_nss.cc index 9a8f72e..78e936b2 100644 --- a/net/socket/ssl_client_socket_nss.cc +++ b/net/socket/ssl_client_socket_nss.cc
@@ -2925,21 +2925,6 @@ return true; } -std::string SSLClientSocketNSS::GetSessionCacheKey() const { - NOTIMPLEMENTED(); - return std::string(); -} - -bool SSLClientSocketNSS::InSessionCache() const { - // For now, always return true so that SSLConnectJobs are never held back. - return true; -} - -void SSLClientSocketNSS::SetHandshakeCompletionCallback( - const base::Closure& callback) { - NOTIMPLEMENTED(); -} - void SSLClientSocketNSS::GetSSLCertRequestInfo( SSLCertRequestInfo* cert_request_info) { EnterFunction("");
diff --git a/net/socket/ssl_client_socket_nss.h b/net/socket/ssl_client_socket_nss.h index 10bb57f5..93d266c3 100644 --- a/net/socket/ssl_client_socket_nss.h +++ b/net/socket/ssl_client_socket_nss.h
@@ -68,9 +68,6 @@ ~SSLClientSocketNSS() override; // SSLClientSocket implementation. - std::string GetSessionCacheKey() const override; - bool InSessionCache() const override; - void SetHandshakeCompletionCallback(const base::Closure& callback) override; void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override; NextProtoStatus GetNextProto(std::string* proto) override;
diff --git a/net/socket/ssl_client_socket_openssl.cc b/net/socket/ssl_client_socket_openssl.cc index d8713f2..63e7f83 100644 --- a/net/socket/ssl_client_socket_openssl.cc +++ b/net/socket/ssl_client_socket_openssl.cc
@@ -218,7 +218,7 @@ static std::string GetSessionCacheKey(const SSL* ssl) { SSLClientSocketOpenSSL* socket = GetInstance()->GetClientSocketFromSSL(ssl); - DCHECK(socket); + CHECK(socket); return socket->GetSessionCacheKey(); } @@ -386,8 +386,6 @@ next_handshake_state_(STATE_NONE), npn_status_(kNextProtoUnsupported), channel_id_xtn_negotiated_(false), - handshake_succeeded_(false), - marked_session_as_good_(false), transport_security_state_(context.transport_security_state), policy_enforcer_(context.cert_policy_enforcer), net_log_(transport_->socket()->NetLog()), @@ -398,45 +396,6 @@ Disconnect(); } -std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const { - std::string result = host_and_port_.ToString(); - result.append("/"); - result.append(ssl_session_cache_shard_); - - // Shard the session cache based on maximum protocol version. This causes - // fallback connections to use a separate session cache. - result.append("/"); - switch (ssl_config_.version_max) { - case SSL_PROTOCOL_VERSION_SSL3: - result.append("ssl3"); - break; - case SSL_PROTOCOL_VERSION_TLS1: - result.append("tls1"); - break; - case SSL_PROTOCOL_VERSION_TLS1_1: - result.append("tls1.1"); - break; - case SSL_PROTOCOL_VERSION_TLS1_2: - result.append("tls1.2"); - break; - default: - NOTREACHED(); - } - - return result; -} - -bool SSLClientSocketOpenSSL::InSessionCache() const { - SSLContext* context = SSLContext::GetInstance(); - std::string cache_key = GetSessionCacheKey(); - return context->session_cache()->SSLSessionIsInCache(cache_key); -} - -void SSLClientSocketOpenSSL::SetHandshakeCompletionCallback( - const base::Closure& callback) { - handshake_completion_callback_ = callback; -} - void SSLClientSocketOpenSSL::GetSSLCertRequestInfo( SSLCertRequestInfo* cert_request_info) { cert_request_info->host_and_port = host_and_port_; @@ -509,18 +468,12 @@ user_connect_callback_ = callback; } else { net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); - if (rv < OK) - OnHandshakeCompletion(); } return rv > OK ? OK : rv; } void SSLClientSocketOpenSSL::Disconnect() { - // If a handshake was pending (Connect() had been called), notify interested - // parties that it's been aborted now. If the handshake had already - // completed, this is a no-op. - OnHandshakeCompletion(); if (ssl_) { // Calling SSL_shutdown prevents the session from being marked as // unresumable. @@ -699,11 +652,6 @@ was_ever_used_ = true; user_read_buf_ = NULL; user_read_buf_len_ = 0; - if (rv <= 0) { - // Failure of a read attempt may indicate a failed false start - // connection. - OnHandshakeCompletion(); - } } return rv; @@ -724,11 +672,6 @@ was_ever_used_ = true; user_write_buf_ = NULL; user_write_buf_len_ = 0; - if (rv < 0) { - // Failure of a write attempt may indicate a failed false start - // connection. - OnHandshakeCompletion(); - } } return rv; @@ -756,9 +699,6 @@ if (!SSL_set_tlsext_host_name(ssl_, host_and_port_.host().c_str())) return ERR_UNEXPECTED; - // Set an OpenSSL callback to monitor this SSL*'s connection. - SSL_set_info_callback(ssl_, &InfoCallback); - trying_cached_session_ = context->session_cache()->SetSSLSessionWithKey( ssl_, GetSessionCacheKey()); @@ -780,7 +720,7 @@ DCHECK(transport_bio_); // Install a callback on OpenSSL's end to plumb transport errors through. - BIO_set_callback(ssl_bio, BIOCallback); + BIO_set_callback(ssl_bio, &SSLClientSocketOpenSSL::BIOCallback); BIO_set_callback_arg(ssl_bio, reinterpret_cast<char*>(this)); SSL_set_bio(ssl_, ssl_bio, ssl_bio); @@ -917,11 +857,6 @@ was_ever_used_ = true; user_read_buf_ = NULL; user_read_buf_len_ = 0; - if (rv <= 0) { - // Failure of a read attempt may indicate a failed false start - // connection. - OnHandshakeCompletion(); - } base::ResetAndReturn(&user_read_callback_).Run(rv); } @@ -932,19 +867,9 @@ was_ever_used_ = true; user_write_buf_ = NULL; user_write_buf_len_ = 0; - if (rv < 0) { - // Failure of a write attempt may indicate a failed false start - // connection. - OnHandshakeCompletion(); - } base::ResetAndReturn(&user_write_callback_).Run(rv); } -void SSLClientSocketOpenSSL::OnHandshakeCompletion() { - if (!handshake_completion_callback_.is_null()) - base::ResetAndReturn(&handshake_completion_callback_).Run(); -} - bool SSLClientSocketOpenSSL::DoTransportIO() { bool network_moved = false; int rv; @@ -1259,23 +1184,18 @@ // TODO(joth): Work out if we need to remember the intermediate CA certs // when the server sends them to us, and do so here. SSLContext::GetInstance()->session_cache()->MarkSSLSessionAsGood(ssl_); - marked_session_as_good_ = true; - CheckIfHandshakeFinished(); } else { DVLOG(1) << "DoVerifyCertComplete error " << ErrorToString(result) << " (" << result << ")"; } completed_connect_ = true; - // Exit DoHandshakeLoop and return the result to the caller to Connect. DCHECK_EQ(STATE_NONE, next_handshake_state_); return result; } void SSLClientSocketOpenSSL::DoConnectCallback(int rv) { - if (rv < OK) - OnHandshakeCompletion(); if (!user_connect_callback_.is_null()) { CompletionCallback c = user_connect_callback_; user_connect_callback_.Reset(); @@ -1486,7 +1406,6 @@ rv = OK; // This causes us to stay in the loop. } } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE); - return rv; } @@ -1607,6 +1526,7 @@ int SSLClientSocketOpenSSL::DoPayloadWrite() { crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_); + if (rv >= 0) { net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv, user_write_buf_->data()); @@ -1991,37 +1911,6 @@ bio, cmd, argp, argi, argl, retvalue); } -// static -void SSLClientSocketOpenSSL::InfoCallback(const SSL* ssl, - int type, - int /*val*/) { - // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed. - tracked_objects::ScopedTracker tracking_profile( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "424386 SSLClientSocketOpenSSL::InfoCallback")); - - if (type == SSL_CB_HANDSHAKE_DONE) { - SSLClientSocketOpenSSL* ssl_socket = - SSLContext::GetInstance()->GetClientSocketFromSSL(ssl); - ssl_socket->handshake_succeeded_ = true; - ssl_socket->CheckIfHandshakeFinished(); - } -} - -// Determines if both the handshake and certificate verification have completed -// successfully, and calls the handshake completion callback if that is the -// case. -// -// CheckIfHandshakeFinished is called twice per connection: once after -// MarkSSLSessionAsGood, when the certificate has been verified, and -// once via an OpenSSL callback when the handshake has completed. On the -// second call, when the certificate has been verified and the handshake -// has completed, the connection's handshake completion callback is run. -void SSLClientSocketOpenSSL::CheckIfHandshakeFinished() { - if (handshake_succeeded_ && marked_session_as_good_) - OnHandshakeCompletion(); -} - void SSLClientSocketOpenSSL::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const { for (ct::SCTList::const_iterator iter = ct_verify_result_.verified_scts.begin(); @@ -2044,6 +1933,34 @@ } } +std::string SSLClientSocketOpenSSL::GetSessionCacheKey() const { + std::string result = host_and_port_.ToString(); + result.append("/"); + result.append(ssl_session_cache_shard_); + + // Shard the session cache based on maximum protocol version. This causes + // fallback connections to use a separate session cache. + result.append("/"); + switch (ssl_config_.version_max) { + case SSL_PROTOCOL_VERSION_SSL3: + result.append("ssl3"); + break; + case SSL_PROTOCOL_VERSION_TLS1: + result.append("tls1"); + break; + case SSL_PROTOCOL_VERSION_TLS1_1: + result.append("tls1.1"); + break; + case SSL_PROTOCOL_VERSION_TLS1_2: + result.append("tls1.2"); + break; + default: + NOTREACHED(); + } + + return result; +} + scoped_refptr<X509Certificate> SSLClientSocketOpenSSL::GetUnverifiedServerCertificateChain() const { return server_cert_;
diff --git a/net/socket/ssl_client_socket_openssl.h b/net/socket/ssl_client_socket_openssl.h index 6aaf1e1..f19813e 100644 --- a/net/socket/ssl_client_socket_openssl.h +++ b/net/socket/ssl_client_socket_openssl.h
@@ -60,9 +60,6 @@ } // SSLClientSocket implementation. - std::string GetSessionCacheKey() const override; - bool InSessionCache() const override; - void SetHandshakeCompletionCallback(const base::Closure& callback) override; void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override; NextProtoStatus GetNextProto(std::string* proto) override; ChannelIDService* GetChannelIDService() const override; @@ -114,8 +111,6 @@ void DoReadCallback(int result); void DoWriteCallback(int result); - void OnHandshakeCompletion(); - bool DoTransportIO(); int DoHandshake(); int DoChannelIDLookup(); @@ -171,12 +166,6 @@ const char *argp, int argi, long argl, long retvalue); - // Callback that is used to obtain information about the state of the SSL - // handshake. - static void InfoCallback(const SSL* ssl, int type, int val); - - void CheckIfHandshakeFinished(); - // Adds the SignedCertificateTimestamps from ct_verify_result_ to |ssl_info|. // SCTs are held in three separate vectors in ct_verify_result, each // vetor representing a particular verification state, this method associates @@ -184,6 +173,10 @@ // the |ssl_info|.signed_certificate_timestamps list. void AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const; + // Returns a unique key string for the SSL session cache for + // this socket. + std::string GetSessionCacheKey() const; + bool transport_send_busy_; bool transport_recv_busy_; @@ -259,12 +252,6 @@ // The service for retrieving Channel ID keys. May be NULL. ChannelIDService* channel_id_service_; - // Callback that is invoked when the connection finishes. - // - // Note: this callback will be run in Disconnect(). It will not alter - // any member variables of the SSLClientSocketOpenSSL. - base::Closure handshake_completion_callback_; - // OpenSSL stuff SSL* ssl_; BIO* transport_bio_; @@ -296,11 +283,6 @@ std::string channel_id_cert_; // True if channel ID extension was negotiated. bool channel_id_xtn_negotiated_; - // True if InfoCallback has been run with result = SSL_CB_HANDSHAKE_DONE. - bool handshake_succeeded_; - // True if MarkSSLSessionAsGood has been called for this socket's - // SSL session. - bool marked_session_as_good_; // The request handle for |channel_id_service_|. ChannelIDService::RequestHandle channel_id_request_handle_;
diff --git a/net/socket/ssl_client_socket_pool.cc b/net/socket/ssl_client_socket_pool.cc index 6643ef4..342e5ea8 100644 --- a/net/socket/ssl_client_socket_pool.cc +++ b/net/socket/ssl_client_socket_pool.cc
@@ -9,7 +9,6 @@ #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" -#include "base/stl_util.h" #include "base/values.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" @@ -95,77 +94,6 @@ return http_proxy_params_; } -SSLConnectJobMessenger::SocketAndCallback::SocketAndCallback( - SSLClientSocket* ssl_socket, - const base::Closure& job_resumption_callback) - : socket(ssl_socket), callback(job_resumption_callback) { -} - -SSLConnectJobMessenger::SocketAndCallback::~SocketAndCallback() { -} - -SSLConnectJobMessenger::SSLConnectJobMessenger( - const base::Closure& messenger_finished_callback) - : messenger_finished_callback_(messenger_finished_callback), - weak_factory_(this) { -} - -SSLConnectJobMessenger::~SSLConnectJobMessenger() { -} - -void SSLConnectJobMessenger::RemovePendingSocket(SSLClientSocket* ssl_socket) { - // Sockets do not need to be removed from connecting_sockets_ because - // OnSSLHandshakeCompleted will do this. - for (SSLPendingSocketsAndCallbacks::iterator it = - pending_sockets_and_callbacks_.begin(); - it != pending_sockets_and_callbacks_.end(); - ++it) { - if (it->socket == ssl_socket) { - pending_sockets_and_callbacks_.erase(it); - return; - } - } -} - -bool SSLConnectJobMessenger::CanProceed(SSLClientSocket* ssl_socket) { - // If there are no connecting sockets, allow the connection to proceed. - return connecting_sockets_.empty(); -} - -void SSLConnectJobMessenger::MonitorConnectionResult( - SSLClientSocket* ssl_socket) { - connecting_sockets_.push_back(ssl_socket); - ssl_socket->SetHandshakeCompletionCallback( - base::Bind(&SSLConnectJobMessenger::OnSSLHandshakeCompleted, - weak_factory_.GetWeakPtr())); -} - -void SSLConnectJobMessenger::AddPendingSocket(SSLClientSocket* ssl_socket, - const base::Closure& callback) { - DCHECK(!connecting_sockets_.empty()); - pending_sockets_and_callbacks_.push_back( - SocketAndCallback(ssl_socket, callback)); -} - -void SSLConnectJobMessenger::OnSSLHandshakeCompleted() { - connecting_sockets_.clear(); - SSLPendingSocketsAndCallbacks temp_list; - temp_list.swap(pending_sockets_and_callbacks_); - base::Closure messenger_finished_callback = messenger_finished_callback_; - messenger_finished_callback.Run(); - RunAllCallbacks(temp_list); -} - -void SSLConnectJobMessenger::RunAllCallbacks( - const SSLPendingSocketsAndCallbacks& pending_sockets_and_callbacks) { - for (std::vector<SocketAndCallback>::const_iterator it = - pending_sockets_and_callbacks.begin(); - it != pending_sockets_and_callbacks.end(); - ++it) { - it->callback.Run(); - } -} - // Timeout for the SSL handshake portion of the connect. static const int kSSLHandshakeTimeoutInSeconds = 30; @@ -178,7 +106,6 @@ HttpProxyClientSocketPool* http_proxy_pool, ClientSocketFactory* client_socket_factory, const SSLClientSocketContext& context, - const GetMessengerCallback& get_messenger_callback, Delegate* delegate, NetLog* net_log) : ConnectJob(group_name, @@ -199,16 +126,11 @@ (params->privacy_mode() == PRIVACY_MODE_ENABLED ? "pm/" + context.ssl_session_cache_shard : context.ssl_session_cache_shard)), - io_callback_( - base::Bind(&SSLConnectJob::OnIOComplete, base::Unretained(this))), - messenger_(NULL), - get_messenger_callback_(get_messenger_callback), - weak_factory_(this) { + callback_( + base::Bind(&SSLConnectJob::OnIOComplete, base::Unretained(this))) { } SSLConnectJob::~SSLConnectJob() { - if (ssl_socket_.get() && messenger_) - messenger_->RemovePendingSocket(ssl_socket_.get()); } LoadState SSLConnectJob::GetLoadState() const { @@ -223,8 +145,6 @@ case STATE_SOCKS_CONNECT_COMPLETE: case STATE_TUNNEL_CONNECT: return transport_socket_handle_->GetLoadState(); - case STATE_CREATE_SSL_SOCKET: - case STATE_CHECK_FOR_RESUME: case STATE_SSL_CONNECT: case STATE_SSL_CONNECT_COMPLETE: return LOAD_STATE_SSL_HANDSHAKE; @@ -281,12 +201,6 @@ case STATE_TUNNEL_CONNECT_COMPLETE: rv = DoTunnelConnectComplete(rv); break; - case STATE_CREATE_SSL_SOCKET: - rv = DoCreateSSLSocket(); - break; - case STATE_CHECK_FOR_RESUME: - rv = DoCheckForResume(); - break; case STATE_SSL_CONNECT: DCHECK_EQ(OK, rv); rv = DoSSLConnect(); @@ -311,17 +225,13 @@ transport_socket_handle_.reset(new ClientSocketHandle()); scoped_refptr<TransportSocketParams> direct_params = params_->GetDirectConnectionParams(); - return transport_socket_handle_->Init(group_name(), - direct_params, - priority(), - io_callback_, - transport_pool_, - net_log()); + return transport_socket_handle_->Init(group_name(), direct_params, priority(), + callback_, transport_pool_, net_log()); } int SSLConnectJob::DoTransportConnectComplete(int result) { if (result == OK) - next_state_ = STATE_CREATE_SSL_SOCKET; + next_state_ = STATE_SSL_CONNECT; return result; } @@ -332,17 +242,14 @@ transport_socket_handle_.reset(new ClientSocketHandle()); scoped_refptr<SOCKSSocketParams> socks_proxy_params = params_->GetSocksProxyConnectionParams(); - return transport_socket_handle_->Init(group_name(), - socks_proxy_params, - priority(), - io_callback_, - socks_pool_, + return transport_socket_handle_->Init(group_name(), socks_proxy_params, + priority(), callback_, socks_pool_, net_log()); } int SSLConnectJob::DoSOCKSConnectComplete(int result) { if (result == OK) - next_state_ = STATE_CREATE_SSL_SOCKET; + next_state_ = STATE_SSL_CONNECT; return result; } @@ -354,11 +261,8 @@ transport_socket_handle_.reset(new ClientSocketHandle()); scoped_refptr<HttpProxySocketParams> http_proxy_params = params_->GetHttpProxyConnectionParams(); - return transport_socket_handle_->Init(group_name(), - http_proxy_params, - priority(), - io_callback_, - http_proxy_pool_, + return transport_socket_handle_->Init(group_name(), http_proxy_params, + priority(), callback_, http_proxy_pool_, net_log()); } @@ -376,16 +280,17 @@ } if (result < 0) return result; - next_state_ = STATE_CREATE_SSL_SOCKET; + + next_state_ = STATE_SSL_CONNECT; return result; } -int SSLConnectJob::DoCreateSSLSocket() { +int SSLConnectJob::DoSSLConnect() { // TODO(pkasting): Remove ScopedTracker below once crbug.com/462815 is fixed. tracked_objects::ScopedTracker tracking_profile( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "462815 SSLConnectJob::DoCreateSSLSocket")); - next_state_ = STATE_CHECK_FOR_RESUME; + FROM_HERE_WITH_EXPLICIT_FUNCTION("462815 SSLConnectJob::DoSSLConnect")); + + next_state_ = STATE_SSL_CONNECT_COMPLETE; // Reset the timeout to just the time allowed for the SSL handshake. ResetTimer(base::TimeDelta::FromSeconds(kSSLHandshakeTimeoutInSeconds)); @@ -404,48 +309,14 @@ connect_timing_.dns_end = socket_connect_timing.dns_end; } + connect_timing_.ssl_start = base::TimeTicks::Now(); + ssl_socket_ = client_socket_factory_->CreateSSLClientSocket( transport_socket_handle_.Pass(), params_->host_and_port(), params_->ssl_config(), context_); - - if (!ssl_socket_->InSessionCache()) - messenger_ = get_messenger_callback_.Run(ssl_socket_->GetSessionCacheKey()); - - return OK; -} - -int SSLConnectJob::DoCheckForResume() { - next_state_ = STATE_SSL_CONNECT; - - if (!messenger_) - return OK; - - if (messenger_->CanProceed(ssl_socket_.get())) { - messenger_->MonitorConnectionResult(ssl_socket_.get()); - // The SSLConnectJob no longer needs access to the messenger after this - // point. - messenger_ = NULL; - return OK; - } - - messenger_->AddPendingSocket(ssl_socket_.get(), - base::Bind(&SSLConnectJob::ResumeSSLConnection, - weak_factory_.GetWeakPtr())); - - return ERR_IO_PENDING; -} - -int SSLConnectJob::DoSSLConnect() { - // TODO(pkasting): Remove ScopedTracker below once crbug.com/462813 is fixed. - tracked_objects::ScopedTracker tracking_profile( - FROM_HERE_WITH_EXPLICIT_FUNCTION("462813 SSLConnectJob::DoSSLConnect")); - next_state_ = STATE_SSL_CONNECT_COMPLETE; - - connect_timing_.ssl_start = base::TimeTicks::Now(); - - return ssl_socket_->Connect(io_callback_); + return ssl_socket_->Connect(callback_); } int SSLConnectJob::DoSSLConnectComplete(int result) { @@ -578,12 +449,6 @@ return result; } -void SSLConnectJob::ResumeSSLConnection() { - DCHECK_EQ(next_state_, STATE_SSL_CONNECT); - messenger_ = NULL; - OnIOComplete(OK); -} - SSLConnectJob::State SSLConnectJob::GetInitialState( SSLSocketParams::ConnectionType connection_type) { switch (connection_type) { @@ -609,14 +474,12 @@ HttpProxyClientSocketPool* http_proxy_pool, ClientSocketFactory* client_socket_factory, const SSLClientSocketContext& context, - const SSLConnectJob::GetMessengerCallback& get_messenger_callback, NetLog* net_log) : transport_pool_(transport_pool), socks_pool_(socks_pool), http_proxy_pool_(http_proxy_pool), client_socket_factory_(client_socket_factory), context_(context), - get_messenger_callback_(get_messenger_callback), net_log_(net_log) { base::TimeDelta max_transport_timeout = base::TimeDelta(); base::TimeDelta pool_timeout; @@ -654,7 +517,6 @@ SOCKSClientSocketPool* socks_pool, HttpProxyClientSocketPool* http_proxy_pool, SSLConfigService* ssl_config_service, - bool enable_ssl_connect_job_waiting, NetLog* net_log) : transport_pool_(transport_pool), socks_pool_(socks_pool), @@ -676,12 +538,8 @@ cert_transparency_verifier, cert_policy_enforcer, ssl_session_cache_shard), - base::Bind( - &SSLClientSocketPool::GetOrCreateSSLConnectJobMessenger, - base::Unretained(this)), net_log)), - ssl_config_service_(ssl_config_service), - enable_ssl_connect_job_waiting_(enable_ssl_connect_job_waiting) { + ssl_config_service_(ssl_config_service) { if (ssl_config_service_.get()) ssl_config_service_->AddObserver(this); if (transport_pool_) @@ -693,8 +551,6 @@ } SSLClientSocketPool::~SSLClientSocketPool() { - STLDeleteContainerPairSecondPointers(messenger_map_.begin(), - messenger_map_.end()); if (ssl_config_service_.get()) ssl_config_service_->RemoveObserver(this); } @@ -712,7 +568,6 @@ http_proxy_pool_, client_socket_factory_, context_, - get_messenger_callback_, delegate, net_log_)); } @@ -833,32 +688,6 @@ return base_.CloseOneIdleConnectionInHigherLayeredPool(); } -SSLConnectJobMessenger* SSLClientSocketPool::GetOrCreateSSLConnectJobMessenger( - const std::string& cache_key) { - if (!enable_ssl_connect_job_waiting_) - return NULL; - MessengerMap::const_iterator it = messenger_map_.find(cache_key); - if (it == messenger_map_.end()) { - std::pair<MessengerMap::iterator, bool> iter = - messenger_map_.insert(MessengerMap::value_type( - cache_key, - new SSLConnectJobMessenger( - base::Bind(&SSLClientSocketPool::DeleteSSLConnectJobMessenger, - base::Unretained(this), - cache_key)))); - it = iter.first; - } - return it->second; -} - -void SSLClientSocketPool::DeleteSSLConnectJobMessenger( - const std::string& cache_key) { - MessengerMap::iterator it = messenger_map_.find(cache_key); - CHECK(it != messenger_map_.end()); - delete it->second; - messenger_map_.erase(it); -} - void SSLClientSocketPool::OnSSLConfigChanged() { FlushWithError(ERR_NETWORK_CHANGED); }
diff --git a/net/socket/ssl_client_socket_pool.h b/net/socket/ssl_client_socket_pool.h index f895d7c..ae7036b 100644 --- a/net/socket/ssl_client_socket_pool.h +++ b/net/socket/ssl_client_socket_pool.h
@@ -5,9 +5,7 @@ #ifndef NET_SOCKET_SSL_CLIENT_SOCKET_POOL_H_ #define NET_SOCKET_SSL_CLIENT_SOCKET_POOL_H_ -#include <map> #include <string> -#include <vector> #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" @@ -96,89 +94,10 @@ DISALLOW_COPY_AND_ASSIGN(SSLSocketParams); }; -// SSLConnectJobMessenger handles communication between concurrent -// SSLConnectJobs that share the same SSL session cache key. -// -// SSLConnectJobMessengers tell the session cache when a certain -// connection should be monitored for success or failure, and -// tell SSLConnectJobs when to pause or resume their connections. -class SSLConnectJobMessenger { - public: - struct SocketAndCallback { - SocketAndCallback(SSLClientSocket* ssl_socket, - const base::Closure& job_resumption_callback); - ~SocketAndCallback(); - - SSLClientSocket* socket; - base::Closure callback; - }; - - typedef std::vector<SocketAndCallback> SSLPendingSocketsAndCallbacks; - - // |messenger_finished_callback| is run when a connection monitored by the - // SSLConnectJobMessenger has completed and we are finished with the - // SSLConnectJobMessenger. - explicit SSLConnectJobMessenger( - const base::Closure& messenger_finished_callback); - ~SSLConnectJobMessenger(); - - // Removes |socket| from the set of sockets being monitored. This - // guarantees that |job_resumption_callback| will not be called for - // the socket. - void RemovePendingSocket(SSLClientSocket* ssl_socket); - - // Returns true if |ssl_socket|'s Connect() method should be called. - bool CanProceed(SSLClientSocket* ssl_socket); - - // Configures the SSLConnectJobMessenger to begin monitoring |ssl_socket|'s - // connection status. After a successful connection, or an error, - // the messenger will determine which sockets that have been added - // via AddPendingSocket() to allow to proceed. - void MonitorConnectionResult(SSLClientSocket* ssl_socket); - - // Adds |socket| to the list of sockets waiting to Connect(). When - // the messenger has determined that it's an appropriate time for |socket| - // to connect, it will invoke |callback|. - // - // Note: It is an error to call AddPendingSocket() without having first - // called MonitorConnectionResult() and configuring a socket that WILL - // have Connect() called on it. - void AddPendingSocket(SSLClientSocket* ssl_socket, - const base::Closure& callback); - - private: - // Processes pending callbacks when a socket completes its SSL handshake -- - // either successfully or unsuccessfully. - void OnSSLHandshakeCompleted(); - - // Runs all callbacks stored in |pending_sockets_and_callbacks_|. - void RunAllCallbacks( - const SSLPendingSocketsAndCallbacks& pending_socket_and_callbacks); - - SSLPendingSocketsAndCallbacks pending_sockets_and_callbacks_; - // Note: this field is a vector to allow for future design changes. Currently, - // this vector should only ever have one entry. - std::vector<SSLClientSocket*> connecting_sockets_; - - base::Closure messenger_finished_callback_; - - base::WeakPtrFactory<SSLConnectJobMessenger> weak_factory_; -}; - // SSLConnectJob handles the SSL handshake after setting up the underlying // connection as specified in the params. class SSLConnectJob : public ConnectJob { public: - // Callback to allow the SSLConnectJob to obtain an SSLConnectJobMessenger to - // coordinate connecting. The SSLConnectJob will supply a unique identifer - // (ex: the SSL session cache key), with the expectation that the same - // Messenger will be returned for all such ConnectJobs. - // - // Note: It will only be called for situations where the SSL session cache - // does not already have a candidate session to resume. - typedef base::Callback<SSLConnectJobMessenger*(const std::string&)> - GetMessengerCallback; - // Note: the SSLConnectJob does not own |messenger| so it must outlive the // job. SSLConnectJob(const std::string& group_name, @@ -190,7 +109,6 @@ HttpProxyClientSocketPool* http_proxy_pool, ClientSocketFactory* client_socket_factory, const SSLClientSocketContext& context, - const GetMessengerCallback& get_messenger_callback, Delegate* delegate, NetLog* net_log); ~SSLConnectJob() override; @@ -208,8 +126,6 @@ STATE_SOCKS_CONNECT_COMPLETE, STATE_TUNNEL_CONNECT, STATE_TUNNEL_CONNECT_COMPLETE, - STATE_CREATE_SSL_SOCKET, - STATE_CHECK_FOR_RESUME, STATE_SSL_CONNECT, STATE_SSL_CONNECT_COMPLETE, STATE_NONE, @@ -226,14 +142,9 @@ int DoSOCKSConnectComplete(int result); int DoTunnelConnect(); int DoTunnelConnectComplete(int result); - int DoCreateSSLSocket(); - int DoCheckForResume(); int DoSSLConnect(); int DoSSLConnectComplete(int result); - // Tells a waiting SSLConnectJob to resume its SSL connection. - void ResumeSSLConnection(); - // Returns the initial state for the state machine based on the // |connection_type|. static State GetInitialState(SSLSocketParams::ConnectionType connection_type); @@ -252,17 +163,12 @@ const SSLClientSocketContext context_; State next_state_; - CompletionCallback io_callback_; + CompletionCallback callback_; scoped_ptr<ClientSocketHandle> transport_socket_handle_; scoped_ptr<SSLClientSocket> ssl_socket_; - SSLConnectJobMessenger* messenger_; HttpResponseInfo error_response_info_; - GetMessengerCallback get_messenger_callback_; - - base::WeakPtrFactory<SSLConnectJob> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(SSLConnectJob); }; @@ -289,7 +195,6 @@ SOCKSClientSocketPool* socks_pool, HttpProxyClientSocketPool* http_proxy_pool, SSLConfigService* ssl_config_service, - bool enable_ssl_connect_job_waiting, NetLog* net_log); ~SSLClientSocketPool() override; @@ -344,16 +249,8 @@ // HigherLayeredPool implementation. bool CloseOneIdleConnection() override; - // Gets the SSLConnectJobMessenger for the given ssl session |cache_key|. If - // none exits, it creates one and stores it in |messenger_map_|. - SSLConnectJobMessenger* GetOrCreateSSLConnectJobMessenger( - const std::string& cache_key); - void DeleteSSLConnectJobMessenger(const std::string& cache_key); - private: typedef ClientSocketPoolBase<SSLSocketParams> PoolBase; - // Maps SSLConnectJob cache keys to SSLConnectJobMessenger objects. - typedef std::map<std::string, SSLConnectJobMessenger*> MessengerMap; // SSLConfigService::Observer implementation. @@ -369,7 +266,6 @@ HttpProxyClientSocketPool* http_proxy_pool, ClientSocketFactory* client_socket_factory, const SSLClientSocketContext& context, - const SSLConnectJob::GetMessengerCallback& get_messenger_callback, NetLog* net_log); ~SSLConnectJobFactory() override; @@ -389,7 +285,6 @@ ClientSocketFactory* const client_socket_factory_; const SSLClientSocketContext context_; base::TimeDelta timeout_; - SSLConnectJob::GetMessengerCallback get_messenger_callback_; NetLog* net_log_; DISALLOW_COPY_AND_ASSIGN(SSLConnectJobFactory); @@ -400,8 +295,6 @@ HttpProxyClientSocketPool* const http_proxy_pool_; PoolBase base_; const scoped_refptr<SSLConfigService> ssl_config_service_; - MessengerMap messenger_map_; - bool enable_ssl_connect_job_waiting_; DISALLOW_COPY_AND_ASSIGN(SSLClientSocketPool); };
diff --git a/net/socket/ssl_client_socket_pool_unittest.cc b/net/socket/ssl_client_socket_pool_unittest.cc index 3d5d9d3..333a524f 100644 --- a/net/socket/ssl_client_socket_pool_unittest.cc +++ b/net/socket/ssl_client_socket_pool_unittest.cc
@@ -6,7 +6,6 @@ #include "base/callback.h" #include "base/compiler_specific.h" -#include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" @@ -86,25 +85,23 @@ http_auth_handler_factory_( HttpAuthHandlerFactory::CreateDefault(&host_resolver_)), session_(CreateNetworkSession()), - direct_transport_socket_params_( - new TransportSocketParams( - HostPortPair("host", 443), - false, - false, - OnHostResolutionCallback(), - TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT)), + direct_transport_socket_params_(new TransportSocketParams( + HostPortPair("host", 443), + false, + false, + OnHostResolutionCallback(), + TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT)), transport_histograms_("MockTCP"), transport_socket_pool_(kMaxSockets, kMaxSocketsPerGroup, &transport_histograms_, &socket_factory_), - proxy_transport_socket_params_( - new TransportSocketParams( - HostPortPair("proxy", 443), - false, - false, - OnHostResolutionCallback(), - TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT)), + proxy_transport_socket_params_(new TransportSocketParams( + HostPortPair("proxy", 443), + false, + false, + OnHostResolutionCallback(), + TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT)), socks_socket_params_( new SOCKSSocketParams(proxy_transport_socket_params_, true, @@ -131,8 +128,7 @@ &http_proxy_histograms_, &transport_socket_pool_, NULL, - NULL), - enable_ssl_connect_job_waiting_(false) { + NULL) { scoped_refptr<SSLConfigService> ssl_config_service( new SSLConfigServiceDefaults); ssl_config_service->GetSSLConfig(&ssl_config_); @@ -148,8 +144,7 @@ std::string() /* ssl_session_cache_shard */, &socket_factory_, transport_pool ? &transport_socket_pool_ : NULL, socks_pool ? &socks_socket_pool_ : NULL, - http_proxy_pool ? &http_proxy_socket_pool_ : NULL, NULL, - enable_ssl_connect_job_waiting_, NULL)); + http_proxy_pool ? &http_proxy_socket_pool_ : NULL, NULL, NULL)); } scoped_refptr<SSLSocketParams> SSLParams(ProxyServer::Scheme proxy, @@ -223,8 +218,6 @@ SSLConfig ssl_config_; scoped_ptr<ClientSocketPoolHistograms> ssl_histograms_; scoped_ptr<SSLClientSocketPool> pool_; - - bool enable_ssl_connect_job_waiting_; }; INSTANTIATE_TEST_CASE_P(NextProto, @@ -233,462 +226,6 @@ kProtoSPDY4_14, kProtoSPDY4)); -// Tests that the final socket will connect even if all sockets -// prior to it fail. -// -// All sockets should wait for the first socket to attempt to -// connect. Once it fails to connect, all other sockets should -// attempt to connect. All should fail, except the final socket. -TEST_P(SSLClientSocketPoolTest, AllSocketsFailButLast) { - // Although we request four sockets, the first three socket connect - // failures cause the socket pool to create three more sockets because - // there are pending requests. - StaticSocketDataProvider data1; - StaticSocketDataProvider data2; - StaticSocketDataProvider data3; - StaticSocketDataProvider data4; - StaticSocketDataProvider data5; - StaticSocketDataProvider data6; - StaticSocketDataProvider data7; - socket_factory_.AddSocketDataProvider(&data1); - socket_factory_.AddSocketDataProvider(&data2); - socket_factory_.AddSocketDataProvider(&data3); - socket_factory_.AddSocketDataProvider(&data4); - socket_factory_.AddSocketDataProvider(&data5); - socket_factory_.AddSocketDataProvider(&data6); - socket_factory_.AddSocketDataProvider(&data7); - SSLSocketDataProvider ssl(ASYNC, ERR_SSL_PROTOCOL_ERROR); - ssl.is_in_session_cache = false; - SSLSocketDataProvider ssl2(ASYNC, ERR_SSL_PROTOCOL_ERROR); - ssl2.is_in_session_cache = false; - SSLSocketDataProvider ssl3(ASYNC, ERR_SSL_PROTOCOL_ERROR); - ssl3.is_in_session_cache = false; - SSLSocketDataProvider ssl4(ASYNC, OK); - ssl4.is_in_session_cache = false; - SSLSocketDataProvider ssl5(ASYNC, OK); - ssl5.is_in_session_cache = false; - SSLSocketDataProvider ssl6(ASYNC, OK); - ssl6.is_in_session_cache = false; - SSLSocketDataProvider ssl7(ASYNC, OK); - ssl7.is_in_session_cache = false; - - socket_factory_.AddSSLSocketDataProvider(&ssl); - socket_factory_.AddSSLSocketDataProvider(&ssl2); - socket_factory_.AddSSLSocketDataProvider(&ssl3); - socket_factory_.AddSSLSocketDataProvider(&ssl4); - socket_factory_.AddSSLSocketDataProvider(&ssl5); - socket_factory_.AddSSLSocketDataProvider(&ssl6); - socket_factory_.AddSSLSocketDataProvider(&ssl7); - - enable_ssl_connect_job_waiting_ = true; - CreatePool(true, false, false); - - scoped_refptr<SSLSocketParams> params1 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params2 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params3 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params4 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - ClientSocketHandle handle1; - ClientSocketHandle handle2; - ClientSocketHandle handle3; - ClientSocketHandle handle4; - TestCompletionCallback callback1; - TestCompletionCallback callback2; - TestCompletionCallback callback3; - TestCompletionCallback callback4; - - handle1.Init( - "b", params1, MEDIUM, callback1.callback(), pool_.get(), BoundNetLog()); - handle2.Init( - "b", params2, MEDIUM, callback2.callback(), pool_.get(), BoundNetLog()); - handle3.Init( - "b", params3, MEDIUM, callback3.callback(), pool_.get(), BoundNetLog()); - handle4.Init( - "b", params4, MEDIUM, callback4.callback(), pool_.get(), BoundNetLog()); - - base::RunLoop().RunUntilIdle(); - - // Only the last socket should have connected. - EXPECT_FALSE(handle1.socket()); - EXPECT_FALSE(handle2.socket()); - EXPECT_FALSE(handle3.socket()); - EXPECT_TRUE(handle4.socket()->IsConnected()); -} - -// Tests that sockets will still connect in parallel if the -// EnableSSLConnectJobWaiting flag is not enabled. -TEST_P(SSLClientSocketPoolTest, SocketsConnectWithoutFlag) { - StaticSocketDataProvider data1; - StaticSocketDataProvider data2; - StaticSocketDataProvider data3; - socket_factory_.AddSocketDataProvider(&data1); - socket_factory_.AddSocketDataProvider(&data2); - socket_factory_.AddSocketDataProvider(&data3); - - SSLSocketDataProvider ssl(ASYNC, OK); - ssl.is_in_session_cache = false; - ssl.should_pause_on_connect = true; - SSLSocketDataProvider ssl2(ASYNC, OK); - ssl2.is_in_session_cache = false; - ssl2.should_pause_on_connect = true; - SSLSocketDataProvider ssl3(ASYNC, OK); - ssl3.is_in_session_cache = false; - ssl3.should_pause_on_connect = true; - socket_factory_.AddSSLSocketDataProvider(&ssl); - socket_factory_.AddSSLSocketDataProvider(&ssl2); - socket_factory_.AddSSLSocketDataProvider(&ssl3); - - CreatePool(true, false, false); - - scoped_refptr<SSLSocketParams> params1 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params2 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params3 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - ClientSocketHandle handle1; - ClientSocketHandle handle2; - ClientSocketHandle handle3; - TestCompletionCallback callback1; - TestCompletionCallback callback2; - TestCompletionCallback callback3; - - handle1.Init( - "b", params1, MEDIUM, callback1.callback(), pool_.get(), BoundNetLog()); - handle2.Init( - "b", params2, MEDIUM, callback2.callback(), pool_.get(), BoundNetLog()); - handle3.Init( - "b", params3, MEDIUM, callback3.callback(), pool_.get(), BoundNetLog()); - - base::RunLoop().RunUntilIdle(); - - std::vector<MockSSLClientSocket*> sockets = - socket_factory_.ssl_client_sockets(); - - // All sockets should have started their connections. - for (std::vector<MockSSLClientSocket*>::iterator it = sockets.begin(); - it != sockets.end(); - ++it) { - EXPECT_TRUE((*it)->reached_connect()); - } - - // Resume connecting all of the sockets. - for (std::vector<MockSSLClientSocket*>::iterator it = sockets.begin(); - it != sockets.end(); - ++it) { - (*it)->RestartPausedConnect(); - } - - callback1.WaitForResult(); - callback2.WaitForResult(); - callback3.WaitForResult(); - - EXPECT_TRUE(handle1.socket()->IsConnected()); - EXPECT_TRUE(handle2.socket()->IsConnected()); - EXPECT_TRUE(handle3.socket()->IsConnected()); -} - -// Tests that the pool deleting an SSLConnectJob will not cause a crash, -// or prevent pending sockets from connecting. -TEST_P(SSLClientSocketPoolTest, DeletedSSLConnectJob) { - StaticSocketDataProvider data1; - StaticSocketDataProvider data2; - StaticSocketDataProvider data3; - socket_factory_.AddSocketDataProvider(&data1); - socket_factory_.AddSocketDataProvider(&data2); - socket_factory_.AddSocketDataProvider(&data3); - - SSLSocketDataProvider ssl(ASYNC, OK); - ssl.is_in_session_cache = false; - ssl.should_pause_on_connect = true; - SSLSocketDataProvider ssl2(ASYNC, OK); - ssl2.is_in_session_cache = false; - SSLSocketDataProvider ssl3(ASYNC, OK); - ssl3.is_in_session_cache = false; - socket_factory_.AddSSLSocketDataProvider(&ssl); - socket_factory_.AddSSLSocketDataProvider(&ssl2); - socket_factory_.AddSSLSocketDataProvider(&ssl3); - - enable_ssl_connect_job_waiting_ = true; - CreatePool(true, false, false); - - scoped_refptr<SSLSocketParams> params1 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params2 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params3 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - ClientSocketHandle handle1; - ClientSocketHandle handle2; - ClientSocketHandle handle3; - TestCompletionCallback callback1; - TestCompletionCallback callback2; - TestCompletionCallback callback3; - - handle1.Init( - "b", params1, MEDIUM, callback1.callback(), pool_.get(), BoundNetLog()); - handle2.Init( - "b", params2, MEDIUM, callback2.callback(), pool_.get(), BoundNetLog()); - handle3.Init( - "b", params3, MEDIUM, callback3.callback(), pool_.get(), BoundNetLog()); - - // Allow the connections to proceed until the first socket has started - // connecting. - base::RunLoop().RunUntilIdle(); - - std::vector<MockSSLClientSocket*> sockets = - socket_factory_.ssl_client_sockets(); - - pool_->CancelRequest("b", &handle2); - - sockets[0]->RestartPausedConnect(); - - callback1.WaitForResult(); - callback3.WaitForResult(); - - EXPECT_TRUE(handle1.socket()->IsConnected()); - EXPECT_FALSE(handle2.socket()); - EXPECT_TRUE(handle3.socket()->IsConnected()); -} - -// Tests that all pending sockets still connect when the pool deletes a pending -// SSLConnectJob which immediately followed a failed leading connection. -TEST_P(SSLClientSocketPoolTest, DeletedSocketAfterFail) { - StaticSocketDataProvider data1; - StaticSocketDataProvider data2; - StaticSocketDataProvider data3; - StaticSocketDataProvider data4; - socket_factory_.AddSocketDataProvider(&data1); - socket_factory_.AddSocketDataProvider(&data2); - socket_factory_.AddSocketDataProvider(&data3); - socket_factory_.AddSocketDataProvider(&data4); - - SSLSocketDataProvider ssl(ASYNC, ERR_SSL_PROTOCOL_ERROR); - ssl.is_in_session_cache = false; - ssl.should_pause_on_connect = true; - SSLSocketDataProvider ssl2(ASYNC, OK); - ssl2.is_in_session_cache = false; - SSLSocketDataProvider ssl3(ASYNC, OK); - ssl3.is_in_session_cache = false; - SSLSocketDataProvider ssl4(ASYNC, OK); - ssl4.is_in_session_cache = false; - socket_factory_.AddSSLSocketDataProvider(&ssl); - socket_factory_.AddSSLSocketDataProvider(&ssl2); - socket_factory_.AddSSLSocketDataProvider(&ssl3); - socket_factory_.AddSSLSocketDataProvider(&ssl4); - - enable_ssl_connect_job_waiting_ = true; - CreatePool(true, false, false); - - scoped_refptr<SSLSocketParams> params1 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params2 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params3 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - ClientSocketHandle handle1; - ClientSocketHandle handle2; - ClientSocketHandle handle3; - TestCompletionCallback callback1; - TestCompletionCallback callback2; - TestCompletionCallback callback3; - - handle1.Init( - "b", params1, MEDIUM, callback1.callback(), pool_.get(), BoundNetLog()); - handle2.Init( - "b", params2, MEDIUM, callback2.callback(), pool_.get(), BoundNetLog()); - handle3.Init( - "b", params3, MEDIUM, callback3.callback(), pool_.get(), BoundNetLog()); - - // Allow the connections to proceed until the first socket has started - // connecting. - base::RunLoop().RunUntilIdle(); - - std::vector<MockSSLClientSocket*> sockets = - socket_factory_.ssl_client_sockets(); - - EXPECT_EQ(3u, sockets.size()); - EXPECT_TRUE(sockets[0]->reached_connect()); - EXPECT_FALSE(handle1.socket()); - - pool_->CancelRequest("b", &handle2); - - sockets[0]->RestartPausedConnect(); - - callback1.WaitForResult(); - callback3.WaitForResult(); - - EXPECT_FALSE(handle1.socket()); - EXPECT_FALSE(handle2.socket()); - EXPECT_TRUE(handle3.socket()->IsConnected()); -} - -// Make sure that sockets still connect after the leader socket's -// connection fails. -TEST_P(SSLClientSocketPoolTest, SimultaneousConnectJobsFail) { - StaticSocketDataProvider data1; - StaticSocketDataProvider data2; - StaticSocketDataProvider data3; - StaticSocketDataProvider data4; - StaticSocketDataProvider data5; - socket_factory_.AddSocketDataProvider(&data1); - socket_factory_.AddSocketDataProvider(&data2); - socket_factory_.AddSocketDataProvider(&data3); - socket_factory_.AddSocketDataProvider(&data4); - socket_factory_.AddSocketDataProvider(&data5); - SSLSocketDataProvider ssl(ASYNC, ERR_SSL_PROTOCOL_ERROR); - ssl.is_in_session_cache = false; - ssl.should_pause_on_connect = true; - SSLSocketDataProvider ssl2(ASYNC, OK); - ssl2.is_in_session_cache = false; - ssl2.should_pause_on_connect = true; - SSLSocketDataProvider ssl3(ASYNC, OK); - ssl3.is_in_session_cache = false; - SSLSocketDataProvider ssl4(ASYNC, OK); - ssl4.is_in_session_cache = false; - SSLSocketDataProvider ssl5(ASYNC, OK); - ssl5.is_in_session_cache = false; - - socket_factory_.AddSSLSocketDataProvider(&ssl); - socket_factory_.AddSSLSocketDataProvider(&ssl2); - socket_factory_.AddSSLSocketDataProvider(&ssl3); - socket_factory_.AddSSLSocketDataProvider(&ssl4); - socket_factory_.AddSSLSocketDataProvider(&ssl5); - - enable_ssl_connect_job_waiting_ = true; - CreatePool(true, false, false); - scoped_refptr<SSLSocketParams> params1 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params2 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params3 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params4 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - ClientSocketHandle handle1; - ClientSocketHandle handle2; - ClientSocketHandle handle3; - ClientSocketHandle handle4; - TestCompletionCallback callback1; - TestCompletionCallback callback2; - TestCompletionCallback callback3; - TestCompletionCallback callback4; - handle1.Init( - "b", params1, MEDIUM, callback1.callback(), pool_.get(), BoundNetLog()); - handle2.Init( - "b", params2, MEDIUM, callback2.callback(), pool_.get(), BoundNetLog()); - handle3.Init( - "b", params3, MEDIUM, callback3.callback(), pool_.get(), BoundNetLog()); - handle4.Init( - "b", params4, MEDIUM, callback4.callback(), pool_.get(), BoundNetLog()); - - base::RunLoop().RunUntilIdle(); - - std::vector<MockSSLClientSocket*> sockets = - socket_factory_.ssl_client_sockets(); - - std::vector<MockSSLClientSocket*>::const_iterator it = sockets.begin(); - - // The first socket should have had Connect called on it. - EXPECT_TRUE((*it)->reached_connect()); - ++it; - - // No other socket should have reached connect yet. - for (; it != sockets.end(); ++it) - EXPECT_FALSE((*it)->reached_connect()); - - // Allow the first socket to resume it's connection process. - sockets[0]->RestartPausedConnect(); - - base::RunLoop().RunUntilIdle(); - - // The second socket should have reached connect. - EXPECT_TRUE(sockets[1]->reached_connect()); - - // Allow the second socket to continue its connection. - sockets[1]->RestartPausedConnect(); - - base::RunLoop().RunUntilIdle(); - - EXPECT_FALSE(handle1.socket()); - EXPECT_TRUE(handle2.socket()->IsConnected()); - EXPECT_TRUE(handle3.socket()->IsConnected()); - EXPECT_TRUE(handle4.socket()->IsConnected()); -} - -// Make sure that no sockets connect before the "leader" socket, -// given that the leader has a successful connection. -TEST_P(SSLClientSocketPoolTest, SimultaneousConnectJobsSuccess) { - StaticSocketDataProvider data1; - StaticSocketDataProvider data2; - StaticSocketDataProvider data3; - socket_factory_.AddSocketDataProvider(&data1); - socket_factory_.AddSocketDataProvider(&data2); - socket_factory_.AddSocketDataProvider(&data3); - - SSLSocketDataProvider ssl(ASYNC, OK); - ssl.is_in_session_cache = false; - ssl.should_pause_on_connect = true; - SSLSocketDataProvider ssl2(ASYNC, OK); - ssl2.is_in_session_cache = false; - SSLSocketDataProvider ssl3(ASYNC, OK); - ssl3.is_in_session_cache = false; - socket_factory_.AddSSLSocketDataProvider(&ssl); - socket_factory_.AddSSLSocketDataProvider(&ssl2); - socket_factory_.AddSSLSocketDataProvider(&ssl3); - - enable_ssl_connect_job_waiting_ = true; - CreatePool(true, false, false); - - scoped_refptr<SSLSocketParams> params1 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params2 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - scoped_refptr<SSLSocketParams> params3 = - SSLParams(ProxyServer::SCHEME_DIRECT, false); - ClientSocketHandle handle1; - ClientSocketHandle handle2; - ClientSocketHandle handle3; - TestCompletionCallback callback1; - TestCompletionCallback callback2; - TestCompletionCallback callback3; - - handle1.Init( - "b", params1, MEDIUM, callback1.callback(), pool_.get(), BoundNetLog()); - handle2.Init( - "b", params2, MEDIUM, callback2.callback(), pool_.get(), BoundNetLog()); - handle3.Init( - "b", params3, MEDIUM, callback3.callback(), pool_.get(), BoundNetLog()); - - // Allow the connections to proceed until the first socket has finished - // connecting. - base::RunLoop().RunUntilIdle(); - - std::vector<MockSSLClientSocket*> sockets = - socket_factory_.ssl_client_sockets(); - - std::vector<MockSSLClientSocket*>::const_iterator it = sockets.begin(); - // The first socket should have reached connect. - EXPECT_TRUE((*it)->reached_connect()); - ++it; - // No other socket should have reached connect yet. - for (; it != sockets.end(); ++it) - EXPECT_FALSE((*it)->reached_connect()); - - sockets[0]->RestartPausedConnect(); - - callback1.WaitForResult(); - callback2.WaitForResult(); - callback3.WaitForResult(); - - EXPECT_TRUE(handle1.socket()->IsConnected()); - EXPECT_TRUE(handle2.socket()->IsConnected()); - EXPECT_TRUE(handle3.socket()->IsConnected()); -} - TEST_P(SSLClientSocketPoolTest, TCPFail) { StaticSocketDataProvider data; data.set_connect_data(MockConnect(SYNCHRONOUS, ERR_CONNECTION_FAILED));
diff --git a/net/socket/ssl_client_socket_unittest.cc b/net/socket/ssl_client_socket_unittest.cc index 96435c9..7a9ce5e3 100644 --- a/net/socket/ssl_client_socket_unittest.cc +++ b/net/socket/ssl_client_socket_unittest.cc
@@ -370,9 +370,6 @@ // Waits for the blocked Write() call to be scheduled. void WaitForWrite(); - // Returns the wrapped stream socket. - StreamSocket* transport() { return transport_.get(); } - private: // Handles completion from the underlying transport read. void OnReadCompleted(int result); @@ -680,15 +677,12 @@ SSLClientSocketTest() : socket_factory_(ClientSocketFactory::GetDefaultFactory()), cert_verifier_(new MockCertVerifier), - transport_security_state_(new TransportSecurityState), - ran_handshake_completion_callback_(false) { + transport_security_state_(new TransportSecurityState) { cert_verifier_->set_default_result(OK); context_.cert_verifier = cert_verifier_.get(); context_.transport_security_state = transport_security_state_.get(); } - void RecordCompletedHandshake() { ran_handshake_completion_callback_ = true; } - protected: // The address of the spawned test server, after calling StartTestServer(). const AddressList& addr() const { return addr_; } @@ -769,7 +763,6 @@ SSLClientSocketContext context_; scoped_ptr<SSLClientSocket> sock_; CapturingNetLog log_; - bool ran_handshake_completion_callback_; private: scoped_ptr<StreamSocket> transport_; @@ -822,11 +815,6 @@ }; class SSLClientSocketFalseStartTest : public SSLClientSocketTest { - public: - SSLClientSocketFalseStartTest() - : monitor_handshake_callback_(false), - fail_handshake_after_false_start_(false) {} - protected: // Creates an SSLClientSocket with |client_config| attached to a // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and @@ -848,11 +836,8 @@ scoped_ptr<SSLClientSocket>* out_sock) { CHECK(test_server()); - scoped_ptr<StreamSocket> real_transport(scoped_ptr<StreamSocket>( - new TCPClientSocket(addr(), NULL, NetLog::Source()))); - real_transport.reset( - new SynchronousErrorStreamSocket(real_transport.Pass())); - + scoped_ptr<StreamSocket> real_transport( + new TCPClientSocket(addr(), NULL, NetLog::Source())); scoped_ptr<FakeBlockingStreamSocket> transport( new FakeBlockingStreamSocket(real_transport.Pass())); int rv = callback->GetResult(transport->Connect(callback->callback())); @@ -862,12 +847,6 @@ scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket( transport.Pass(), test_server()->host_port_pair(), client_config); - if (monitor_handshake_callback_) { - sock->SetHandshakeCompletionCallback( - base::Bind(&SSLClientSocketTest::RecordCompletedHandshake, - base::Unretained(this))); - } - // Connect. Stop before the client processes the first server leg // (ServerHello, etc.) raw_transport->BlockReadResult(); @@ -883,12 +862,6 @@ raw_transport->UnblockReadResult(); raw_transport->WaitForWrite(); - if (fail_handshake_after_false_start_) { - SynchronousErrorStreamSocket* error_socket = - static_cast<SynchronousErrorStreamSocket*>( - raw_transport->transport()); - error_socket->SetNextReadError(ERR_CONNECTION_RESET); - } // And, finally, release that and block the next server leg // (ChangeCipherSpec, Finished). raw_transport->BlockReadResult(); @@ -906,7 +879,6 @@ TestCompletionCallback callback; FakeBlockingStreamSocket* raw_transport = NULL; scoped_ptr<SSLClientSocket> sock; - ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived( client_config, &callback, &raw_transport, &sock)); @@ -941,10 +913,7 @@ // After releasing reads, the connection proceeds. raw_transport->UnblockReadResult(); rv = callback.GetResult(rv); - if (fail_handshake_after_false_start_) - EXPECT_EQ(ERR_CONNECTION_RESET, rv); - else - EXPECT_LT(0, rv); + EXPECT_LT(0, rv); } else { // False Start is not enabled, so the handshake will not complete because // the server second leg is blocked. @@ -952,13 +921,6 @@ EXPECT_FALSE(callback.have_result()); } } - - // Indicates that the socket's handshake completion callback should - // be monitored. - bool monitor_handshake_callback_; - // Indicates that this test's handshake should fail after the client - // "finished" message is sent. - bool fail_handshake_after_false_start_; }; class SSLClientSocketChannelIDTest : public SSLClientSocketTest { @@ -2886,162 +2848,6 @@ SSLConnectionStatusToVersion(ssl_info.connection_status)); } -#if defined(USE_OPENSSL) - -TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithFailure) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); - ASSERT_TRUE(test_server.Start()); - - AddressList addr; - ASSERT_TRUE(test_server.GetAddressList(&addr)); - - TestCompletionCallback callback; - scoped_ptr<StreamSocket> real_transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); - scoped_ptr<SynchronousErrorStreamSocket> transport( - new SynchronousErrorStreamSocket(real_transport.Pass())); - int rv = callback.GetResult(transport->Connect(callback.callback())); - EXPECT_EQ(OK, rv); - - // Disable TLS False Start to avoid handshake non-determinism. - SSLConfig ssl_config; - ssl_config.false_start_enabled = false; - - SynchronousErrorStreamSocket* raw_transport = transport.get(); - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), ssl_config)); - - sock->SetHandshakeCompletionCallback(base::Bind( - &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this))); - - raw_transport->SetNextWriteError(ERR_CONNECTION_RESET); - - rv = callback.GetResult(sock->Connect(callback.callback())); - EXPECT_EQ(ERR_CONNECTION_RESET, rv); - EXPECT_FALSE(sock->IsConnected()); - - EXPECT_TRUE(ran_handshake_completion_callback_); -} - -// Tests that the completion callback is run when an SSL connection -// completes successfully. -TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithSuccess) { - SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, - SpawnedTestServer::kLocalhost, - base::FilePath()); - ASSERT_TRUE(test_server.Start()); - - AddressList addr; - ASSERT_TRUE(test_server.GetAddressList(&addr)); - - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); - - TestCompletionCallback callback; - int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) - rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); - - SSLConfig ssl_config; - ssl_config.false_start_enabled = false; - - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), ssl_config)); - - sock->SetHandshakeCompletionCallback(base::Bind( - &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this))); - - rv = callback.GetResult(sock->Connect(callback.callback())); - - EXPECT_EQ(OK, rv); - EXPECT_TRUE(sock->IsConnected()); - EXPECT_TRUE(ran_handshake_completion_callback_); -} - -// Tests that the completion callback is run with a server that doesn't cache -// sessions. -TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithDisabledSessionCache) { - SpawnedTestServer::SSLOptions ssl_options; - ssl_options.disable_session_cache = true; - SpawnedTestServer test_server( - SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); - ASSERT_TRUE(test_server.Start()); - - AddressList addr; - ASSERT_TRUE(test_server.GetAddressList(&addr)); - - scoped_ptr<StreamSocket> transport( - new TCPClientSocket(addr, NULL, NetLog::Source())); - - TestCompletionCallback callback; - int rv = transport->Connect(callback.callback()); - if (rv == ERR_IO_PENDING) - rv = callback.WaitForResult(); - EXPECT_EQ(OK, rv); - - SSLConfig ssl_config; - ssl_config.false_start_enabled = false; - - scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( - transport.Pass(), test_server.host_port_pair(), ssl_config)); - - sock->SetHandshakeCompletionCallback(base::Bind( - &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this))); - - rv = callback.GetResult(sock->Connect(callback.callback())); - - EXPECT_EQ(OK, rv); - EXPECT_TRUE(sock->IsConnected()); - EXPECT_TRUE(ran_handshake_completion_callback_); -} - -TEST_F(SSLClientSocketFalseStartTest, - HandshakeCallbackIsRun_WithFalseStartFailure) { - if (!SupportsAESGCM()) { - LOG(WARNING) << "Skipping test because AES-GCM is not supported."; - return; - } - - // False Start requires NPN and a forward-secret cipher suite. - SpawnedTestServer::SSLOptions server_options; - server_options.key_exchanges = - SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA; - server_options.bulk_ciphers = - SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM; - server_options.enable_npn = true; - SSLConfig client_config; - client_config.next_protos.push_back(kProtoHTTP11); - monitor_handshake_callback_ = true; - fail_handshake_after_false_start_ = true; - ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, true)); - ASSERT_TRUE(ran_handshake_completion_callback_); -} - -TEST_F(SSLClientSocketFalseStartTest, - HandshakeCallbackIsRun_WithFalseStartSuccess) { - if (!SupportsAESGCM()) { - LOG(WARNING) << "Skipping test because AES-GCM is not supported."; - return; - } - - // False Start requires NPN and a forward-secret cipher suite. - SpawnedTestServer::SSLOptions server_options; - server_options.key_exchanges = - SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA; - server_options.bulk_ciphers = - SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM; - server_options.enable_npn = true; - SSLConfig client_config; - client_config.next_protos.push_back(kProtoHTTP11); - monitor_handshake_callback_ = true; - ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, true)); - ASSERT_TRUE(ran_handshake_completion_callback_); -} -#endif // defined(USE_OPENSSL) - TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) { if (!SupportsAESGCM()) { LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
diff --git a/net/socket/ssl_session_cache_openssl.cc b/net/socket/ssl_session_cache_openssl.cc index c77790f1a..9f7a37b 100644 --- a/net/socket/ssl_session_cache_openssl.cc +++ b/net/socket/ssl_session_cache_openssl.cc
@@ -253,27 +253,6 @@ return SSL_set_session(ssl, session) == 1; } - // Return true iff a cached session was associated with the given |cache_key|. - bool SSLSessionIsInCache(const std::string& cache_key) const { - // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed. - tracked_objects::ScopedTracker tracking_profile( - FROM_HERE_WITH_EXPLICIT_FUNCTION( - "424386 SSLSessionCacheOpenSSLImpl::SSLSessionIsInCache")); - - base::AutoLock locked(lock_); - KeyIndex::const_iterator it = key_index_.find(cache_key); - if (it == key_index_.end()) - return false; - - SSL_SESSION* session = *it->second; - DCHECK(session); - - void* session_is_good = - SSL_SESSION_get_ex_data(session, GetSSLSessionExIndex()); - - return session_is_good != NULL; - } - void MarkSSLSessionAsGood(SSL* ssl) { // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed. tracked_objects::ScopedTracker tracking_profile( @@ -281,7 +260,8 @@ "424386 SSLSessionCacheOpenSSLImpl::MarkSSLSessionAsGood")); SSL_SESSION* session = SSL_get_session(ssl); - CHECK(session); + if (!session) + return; // Mark the session as good, allowing it to be used for future connections. SSL_SESSION_set_ex_data( @@ -394,8 +374,7 @@ FROM_HERE_WITH_EXPLICIT_FUNCTION( "424386 SSLSessionCacheOpenSSLImpl::NewSessionCallbackStatic")); - SSLSessionCacheOpenSSLImpl* cache = GetCache(ssl->ctx); - cache->OnSessionAdded(ssl, session); + GetCache(ssl->ctx)->OnSessionAdded(ssl, session); return 1; } @@ -532,7 +511,7 @@ // method to get the index which can later be used with SSL_CTX_get_ex_data() // or SSL_CTX_set_ex_data(). - mutable base::Lock lock_; // Protects access to containers below. + base::Lock lock_; // Protects access to containers below. MRUSessionList ordering_; KeyIndex key_index_; @@ -562,11 +541,6 @@ return impl_->SetSSLSessionWithKey(ssl, cache_key); } -bool SSLSessionCacheOpenSSL::SSLSessionIsInCache( - const std::string& cache_key) const { - return impl_->SSLSessionIsInCache(cache_key); -} - void SSLSessionCacheOpenSSL::MarkSSLSessionAsGood(SSL* ssl) { return impl_->MarkSSLSessionAsGood(ssl); }
diff --git a/net/socket/ssl_session_cache_openssl.h b/net/socket/ssl_session_cache_openssl.h index abf5eab..bbd96596 100644 --- a/net/socket/ssl_session_cache_openssl.h +++ b/net/socket/ssl_session_cache_openssl.h
@@ -113,9 +113,6 @@ // Return true iff a cached session was associated with the |ssl| connection. bool SetSSLSessionWithKey(SSL* ssl, const std::string& cache_key); - // Return true iff a cached session was associated with the given |cache_key|. - bool SSLSessionIsInCache(const std::string& cache_key) const; - // Indicates that the SSL session associated with |ssl| is "good" - that is, // that all associated cryptographic parameters that were negotiated, // including the peer's certificate, were successfully validated. Because
diff --git a/net/test/spawned_test_server/base_test_server.cc b/net/test/spawned_test_server/base_test_server.cc index de76eed..d27eacb 100644 --- a/net/test/spawned_test_server/base_test_server.cc +++ b/net/test/spawned_test_server/base_test_server.cc
@@ -104,8 +104,7 @@ fallback_scsv_enabled(false), staple_ocsp_response(false), ocsp_server_unavailable(false), - enable_npn(false), - disable_session_cache(false) { + enable_npn(false) { } BaseTestServer::SSLOptions::SSLOptions( @@ -122,8 +121,7 @@ fallback_scsv_enabled(false), staple_ocsp_response(false), ocsp_server_unavailable(false), - enable_npn(false), - disable_session_cache(false) { + enable_npn(false) { } BaseTestServer::SSLOptions::~SSLOptions() {} @@ -486,8 +484,6 @@ } if (ssl_options_.enable_npn) arguments->Set("enable-npn", base::Value::CreateNullValue()); - if (ssl_options_.disable_session_cache) - arguments->Set("disable-session-cache", base::Value::CreateNullValue()); } return GenerateAdditionalArguments(arguments);
diff --git a/net/test/spawned_test_server/base_test_server.h b/net/test/spawned_test_server/base_test_server.h index a43df11..73bf7fa 100644 --- a/net/test/spawned_test_server/base_test_server.h +++ b/net/test/spawned_test_server/base_test_server.h
@@ -209,11 +209,6 @@ // Whether to enable NPN support. bool enable_npn; - - // Whether to disable TLS session caching. When session caching is - // disabled, the server will use an empty session ID in the - // ServerHello. - bool disable_session_cache; }; // Pass as the 'host' parameter during construction to server on 127.0.0.1
diff --git a/net/tools/quic/end_to_end_test.cc b/net/tools/quic/end_to_end_test.cc index 943bb6a..e6cac59 100644 --- a/net/tools/quic/end_to_end_test.cc +++ b/net/tools/quic/end_to_end_test.cc
@@ -77,13 +77,11 @@ TestParams(const QuicVersionVector& client_supported_versions, const QuicVersionVector& server_supported_versions, QuicVersion negotiated_version, - bool use_pacing, bool use_fec, QuicTag congestion_control_tag) : client_supported_versions(client_supported_versions), server_supported_versions(server_supported_versions), negotiated_version(negotiated_version), - use_pacing(use_pacing), use_fec(use_fec), congestion_control_tag(congestion_control_tag) { } @@ -94,7 +92,6 @@ os << " client_supported_versions: " << QuicVersionVectorToString(p.client_supported_versions); os << " negotiated_version: " << QuicVersionToString(p.negotiated_version); - os << " use_pacing: " << p.use_pacing; os << " use_fec: " << p.use_fec; os << " congestion_control_tag: " << QuicUtils::TagToString(p.congestion_control_tag) << " }"; @@ -104,7 +101,6 @@ QuicVersionVector client_supported_versions; QuicVersionVector server_supported_versions; QuicVersion negotiated_version; - bool use_pacing; bool use_fec; QuicTag congestion_control_tag; }; @@ -131,27 +127,25 @@ QuicTag congestion_control_tag = congestion_control_tags[congestion_control_index]; for (int use_fec = 0; use_fec < 2; ++use_fec) { - for (int use_pacing = 0; use_pacing < 2; ++use_pacing) { - for (int spdy_version = 3; spdy_version <= 4; ++spdy_version) { - const QuicVersionVector* client_versions = - spdy_version == 3 ? &spdy3_versions : &spdy4_versions; - // Add an entry for server and client supporting all versions. - params.push_back(TestParams(*client_versions, all_supported_versions, - (*client_versions)[0], use_pacing != 0, - use_fec != 0, congestion_control_tag)); + for (int spdy_version = 3; spdy_version <= 4; ++spdy_version) { + const QuicVersionVector* client_versions = + spdy_version == 3 ? &spdy3_versions : &spdy4_versions; + // Add an entry for server and client supporting all versions. + params.push_back(TestParams(*client_versions, all_supported_versions, + (*client_versions)[0], use_fec != 0, + congestion_control_tag)); - // Test client supporting all versions and server supporting 1 - // version. Simulate an old server and exercise version downgrade in - // the client. Protocol negotiation should occur. Skip the i = 0 case - // because it is essentially the same as the default case. - for (QuicVersion version : *client_versions) { - QuicVersionVector server_supported_versions; - server_supported_versions.push_back(version); - params.push_back( - TestParams(*client_versions, server_supported_versions, - server_supported_versions[0], use_pacing != 0, - use_fec != 0, congestion_control_tag)); - } + // Test client supporting all versions and server supporting 1 + // version. Simulate an old server and exercise version downgrade in + // the client. Protocol negotiation should occur. Skip the i = 0 case + // because it is essentially the same as the default case. + for (QuicVersion version : *client_versions) { + QuicVersionVector server_supported_versions; + server_supported_versions.push_back(version); + params.push_back(TestParams(*client_versions, + server_supported_versions, + server_supported_versions[0], + use_fec != 0, congestion_control_tag)); } } } @@ -279,10 +273,6 @@ bool Initialize() { QuicTagVector copt; - - if (GetParam().use_pacing) { - copt.push_back(kPACE); - } server_config_.SetConnectionOptionsToSend(copt); // TODO(nimia): Consider setting the congestion control algorithm for the @@ -318,8 +308,6 @@ // and TestWriterFactory when Initialize() is executed. client_writer_ = new PacketDroppingTestWriter(); server_writer_ = new PacketDroppingTestWriter(); - // TODO(ianswett): Remove this once it's fully rolled out. - FLAGS_quic_enable_pacing = false; } void TearDown() override { StopServer(); } @@ -929,16 +917,6 @@ const QuicSentPacketManager& server_sent_packet_manager = *GetSentPacketManagerFromFirstServerSession(); - // BBR automatically enables pacing. - EXPECT_EQ(GetParam().use_pacing || - (FLAGS_quic_allow_bbr && - GetParam().congestion_control_tag == kTBBR), - server_sent_packet_manager.using_pacing()); - EXPECT_EQ(GetParam().use_pacing || - (FLAGS_quic_allow_bbr && - GetParam().congestion_control_tag == kTBBR), - client_sent_packet_manager.using_pacing()); - EXPECT_EQ(kInitialRTT, client_sent_packet_manager.GetRttStats()->initial_rtt_us()); EXPECT_EQ(kInitialRTT, @@ -1356,28 +1334,6 @@ server_thread_->Resume(); } -TEST_P(EndToEndTest, EnablePacingViaFlag) { - // When pacing is enabled via command-line flag, it will always be enabled, - // regardless of the config. or the specific congestion-control algorithm. - ValueRestore<bool> old_flag(&FLAGS_quic_enable_pacing, true); - ASSERT_TRUE(Initialize()); - - client_->client()->WaitForCryptoHandshakeConfirmed(); - server_thread_->WaitForCryptoHandshakeConfirmed(); - - // Pause the server so we can access the server's internals without races. - server_thread_->Pause(); - QuicDispatcher* dispatcher = - QuicServerPeer::GetDispatcher(server_thread_->server()); - ASSERT_EQ(1u, dispatcher->session_map().size()); - const QuicSentPacketManager& client_sent_packet_manager = - client_->client()->session()->connection()->sent_packet_manager(); - const QuicSentPacketManager& server_sent_packet_manager = - *GetSentPacketManagerFromFirstServerSession(); - EXPECT_TRUE(server_sent_packet_manager.using_pacing()); - EXPECT_TRUE(client_sent_packet_manager.using_pacing()); -} - // A TestAckNotifierDelegate verifies that its OnAckNotification method has been // called exactly once on destruction. class TestAckNotifierDelegate : public QuicAckNotifier::DelegateInterface {
diff --git a/net/tools/quic/quic_client.cc b/net/tools/quic/quic_client.cc index 15efa56..d54464e 100644 --- a/net/tools/quic/quic_client.cc +++ b/net/tools/quic/quic_client.cc
@@ -201,14 +201,10 @@ session_.reset(new QuicClientSession( config_, - new QuicConnection(GenerateConnectionId(), - server_address_, - helper_.get(), + new QuicConnection(GenerateConnectionId(), server_address_, helper_.get(), factory, - /* owns_writer= */ false, - /* is_server= */ false, - server_id_.is_https(), - supported_versions_))); + /* owns_writer= */ false, Perspective::IS_CLIENT, + server_id_.is_https(), supported_versions_))); // Reset |writer_| after |session_| so that the old writer outlives the old // session.
diff --git a/net/tools/quic/quic_client_session_test.cc b/net/tools/quic/quic_client_session_test.cc index 47a708b0..c7d1f09c 100644 --- a/net/tools/quic/quic_client_session_test.cc +++ b/net/tools/quic/quic_client_session_test.cc
@@ -39,8 +39,8 @@ : public ::testing::TestWithParam<QuicVersion> { protected: ToolsQuicClientSessionTest() - : connection_( - new PacketSavingConnection(false, SupportedVersions(GetParam()))) { + : connection_(new PacketSavingConnection(Perspective::IS_CLIENT, + SupportedVersions(GetParam()))) { session_.reset(new QuicClientSession(DefaultQuicConfig(), connection_)); session_->InitializeSession( QuicServerId(kServerHostname, kPort, false, PRIVACY_MODE_DISABLED), @@ -69,7 +69,7 @@ TEST_P(ToolsQuicClientSessionTest, MaxNumStreams) { session_->config()->SetMaxStreamsPerConnection(1, 1); - // FLAGS_max_streams_per_connection = 1; + // Initialize crypto before the client session will create a stream. CompleteCryptoHandshake();
diff --git a/net/tools/quic/quic_dispatcher.cc b/net/tools/quic/quic_dispatcher.cc index 7be789a..8bb76ba 100644 --- a/net/tools/quic/quic_dispatcher.cc +++ b/net/tools/quic/quic_dispatcher.cc
@@ -174,7 +174,9 @@ connection_writer_factory_(this), supported_versions_(supported_versions), current_packet_(nullptr), - framer_(supported_versions, /*unused*/ QuicTime::Zero(), true), + framer_(supported_versions, + /*unused*/ QuicTime::Zero(), + Perspective::IS_SERVER), framer_visitor_(new QuicFramerVisitor(this)) { framer_.set_visitor(framer_visitor_.get()); } @@ -403,7 +405,7 @@ // The QuicSession takes ownership of |connection| below. QuicConnection* connection = new QuicConnection( connection_id, client_address, helper_.get(), connection_writer_factory_, - /* owns_writer= */ true, /* is_server= */ true, + /* owns_writer= */ true, Perspective::IS_SERVER, crypto_config_.HasProofSource(), supported_versions_); QuicServerSession* session = new QuicServerSession(config_, connection, this);
diff --git a/net/tools/quic/quic_dispatcher_test.cc b/net/tools/quic/quic_dispatcher_test.cc index ec20190..083d85a 100644 --- a/net/tools/quic/quic_dispatcher_test.cc +++ b/net/tools/quic/quic_dispatcher_test.cc
@@ -70,7 +70,7 @@ public: MockServerConnection(QuicConnectionId connection_id, QuicDispatcher* dispatcher) - : MockConnection(connection_id, true), + : MockConnection(connection_id, Perspective::IS_SERVER), dispatcher_(dispatcher) {} void UnregisterOnConnectionClosed() {
diff --git a/net/tools/quic/quic_server_session.cc b/net/tools/quic/quic_server_session.cc index f25ad92..f468c15e3 100644 --- a/net/tools/quic/quic_server_session.cc +++ b/net/tools/quic/quic_server_session.cc
@@ -156,6 +156,9 @@ } crypto_stream_->SendServerConfigUpdate(&cached_network_params); + + connection()->OnSendConnectionState(cached_network_params); + last_scup_time_ = now; last_scup_sequence_number_ = connection()->sequence_number_of_last_sent_packet();
diff --git a/net/tools/quic/quic_server_session_test.cc b/net/tools/quic/quic_server_session_test.cc index 8074d31..6e7f0f7 100644 --- a/net/tools/quic/quic_server_session_test.cc +++ b/net/tools/quic/quic_server_session_test.cc
@@ -72,8 +72,8 @@ config_.SetInitialSessionFlowControlWindowToSend( kInitialSessionFlowControlWindowForTest); - connection_ = - new StrictMock<MockConnection>(true, SupportedVersions(GetParam())); + connection_ = new StrictMock<MockConnection>(Perspective::IS_SERVER, + SupportedVersions(GetParam())); session_.reset(new QuicServerSession(config_, connection_, &owner_)); MockClock clock; handshake_message_.reset(crypto_config_.AddDefaultConfig( @@ -377,6 +377,7 @@ EXPECT_CALL(*crypto_stream, SendServerConfigUpdate(EqualsProto(expected_network_params))) .Times(1); + EXPECT_CALL(*connection_, OnSendConnectionState(_)).Times(1); session_->OnCongestionWindowChange(now); }
diff --git a/net/tools/quic/quic_spdy_client_stream_test.cc b/net/tools/quic/quic_spdy_client_stream_test.cc index 04e05b0..323018e 100644 --- a/net/tools/quic/quic_spdy_client_stream_test.cc +++ b/net/tools/quic/quic_spdy_client_stream_test.cc
@@ -29,8 +29,9 @@ class QuicSpdyClientStreamTest : public TestWithParam<QuicVersion> { public: QuicSpdyClientStreamTest() - : connection_(new StrictMock<MockConnection>( - false, SupportedVersions(GetParam()))), + : connection_( + new StrictMock<MockConnection>(Perspective::IS_CLIENT, + SupportedVersions(GetParam()))), session_(DefaultQuicConfig(), connection_), body_("hello world") { session_.InitializeSession(
diff --git a/net/tools/quic/quic_spdy_server_stream_test.cc b/net/tools/quic/quic_spdy_server_stream_test.cc index 1187d340..9277a82 100644 --- a/net/tools/quic/quic_spdy_server_stream_test.cc +++ b/net/tools/quic/quic_spdy_server_stream_test.cc
@@ -72,8 +72,9 @@ class QuicSpdyServerStreamTest : public ::testing::TestWithParam<QuicVersion> { public: QuicSpdyServerStreamTest() - : connection_(new StrictMock<MockConnection>( - true, SupportedVersions(GetParam()))), + : connection_( + new StrictMock<MockConnection>(Perspective::IS_SERVER, + SupportedVersions(GetParam()))), session_(connection_), body_("hello world") { BalsaHeaders request_headers;
diff --git a/net/tools/quic/quic_time_wait_list_manager_test.cc b/net/tools/quic/quic_time_wait_list_manager_test.cc index f67fe7e2..724f601 100644 --- a/net/tools/quic/quic_time_wait_list_manager_test.cc +++ b/net/tools/quic/quic_time_wait_list_manager_test.cc
@@ -90,9 +90,13 @@ class QuicTimeWaitListManagerTest : public ::testing::Test { protected: QuicTimeWaitListManagerTest() - : time_wait_list_manager_(&writer_, &visitor_, - &epoll_server_, QuicSupportedVersions()), - framer_(QuicSupportedVersions(), QuicTime::Zero(), true), + : time_wait_list_manager_(&writer_, + &visitor_, + &epoll_server_, + QuicSupportedVersions()), + framer_(QuicSupportedVersions(), + QuicTime::Zero(), + Perspective::IS_SERVER), connection_id_(45), client_address_(net::test::TestPeerIPAddress(), kTestPort), writer_is_blocked_(false) {} @@ -184,9 +188,8 @@ const std::tr1::tuple<const char*, int> packet_buffer, testing::MatchResultListener* /* listener */) const override { FramerVisitorCapturingPublicReset visitor; - QuicFramer framer(QuicSupportedVersions(), - QuicTime::Zero(), - false); + QuicFramer framer(QuicSupportedVersions(), QuicTime::Zero(), + Perspective::IS_CLIENT); framer.set_visitor(&visitor); QuicEncryptedPacket encrypted(std::tr1::get<0>(packet_buffer), std::tr1::get<1>(packet_buffer));
diff --git a/net/tools/quic/test_tools/quic_test_client.h b/net/tools/quic/test_tools/quic_test_client.h index 6dfea99..1181bec 100644 --- a/net/tools/quic/test_tools/quic_test_client.h +++ b/net/tools/quic/test_tools/quic_test_client.h
@@ -50,10 +50,15 @@ QuicConnectionId GenerateConnectionId() override; void UseWriter(QuicPacketWriterWrapper* writer); void UseConnectionId(QuicConnectionId connection_id); + void SendCachedNetworkParamaters( + const CachedNetworkParameters& cached_network_params) { + cached_network_paramaters_ = cached_network_params; + } private: QuicConnectionId override_connection_id_; // ConnectionId to use, if nonzero QuicPacketWriterWrapper* test_writer_; + CachedNetworkParameters cached_network_paramaters_; DISALLOW_COPY_AND_ASSIGN(MockableQuicClient); };
diff --git a/net/tools/testserver/testserver.py b/net/tools/testserver/testserver.py index 9e8b0bb..b2c7d55f 100755 --- a/net/tools/testserver/testserver.py +++ b/net/tools/testserver/testserver.py
@@ -157,7 +157,7 @@ ssl_bulk_ciphers, ssl_key_exchanges, enable_npn, record_resume_info, tls_intolerant, tls_intolerance_type, signed_cert_timestamps, - fallback_scsv_enabled, ocsp_response, disable_session_cache): + fallback_scsv_enabled, ocsp_response): self.cert_chain = tlslite.api.X509CertChain() self.cert_chain.parsePemList(pem_cert_and_key) # Force using only python implementation - otherwise behavior is different @@ -203,10 +203,7 @@ self.ssl_handshake_settings.tlsIntolerant = (3, tls_intolerant) self.ssl_handshake_settings.tlsIntoleranceType = tls_intolerance_type - - if disable_session_cache: - self.session_cache = None - elif record_resume_info: + if record_resume_info: # If record_resume_info is true then we'll replace the session cache with # an object that records the lookups and inserts that it sees. self.session_cache = RecordingSSLSessionCache() @@ -2048,8 +2045,7 @@ self.options.signed_cert_timestamps_tls_ext.decode( "base64"), self.options.fallback_scsv, - stapled_ocsp_response, - self.options.disable_session_cache) + stapled_ocsp_response) print 'HTTPS server started on https://%s:%d...' % \ (host, server.server_port) else: @@ -2149,11 +2145,6 @@ def add_options(self): testserver_base.TestServerRunner.add_options(self) - self.option_parser.add_option('--disable-session-cache', - action='store_true', - dest='disable_session_cache', - help='tells the server to disable the' - 'TLS session cache.') self.option_parser.add_option('-f', '--ftp', action='store_const', const=SERVER_FTP, default=SERVER_HTTP, dest='server_type',
diff --git a/net/websockets/websocket_end_to_end_test.cc b/net/websockets/websocket_end_to_end_test.cc index 0304eb1..2fbc20b 100644 --- a/net/websockets/websocket_end_to_end_test.cc +++ b/net/websockets/websocket_end_to_end_test.cc
@@ -242,12 +242,11 @@ if (!initialised_context_) { InitialiseContext(); } - std::vector<std::string> sub_protocols; url::Origin origin("http://localhost"); event_interface_ = new ConnectTestingEventInterface; channel_.reset( new WebSocketChannel(make_scoped_ptr(event_interface_), &context_)); - channel_->SendAddChannelRequest(GURL(socket_url), sub_protocols, origin); + channel_->SendAddChannelRequest(GURL(socket_url), sub_protocols_, origin); event_interface_->WaitForResponse(); return !event_interface_->failed(); } @@ -256,6 +255,7 @@ scoped_ptr<TestNetworkDelegateWithProxyInfo> network_delegate_; TestURLRequestContext context_; scoped_ptr<WebSocketChannel> channel_; + std::vector<std::string> sub_protocols_; bool initialised_context_; }; @@ -456,6 +456,20 @@ EXPECT_TRUE(ConnectAndWait(ws_url)); } +// Regression test for crbug.com/180504 "WebSocket handshake fails when HTTP +// headers have trailing LWS". +TEST_F(WebSocketEndToEndTest, DISABLED_ON_ANDROID(TrailingWhitespace)) { + SpawnedTestServer ws_server(SpawnedTestServer::TYPE_WS, + SpawnedTestServer::kLocalhost, + GetWebSocketTestDataDirectory()); + ASSERT_TRUE(ws_server.Start()); + + GURL ws_url = ws_server.GetURL("trailing-whitespace"); + sub_protocols_.push_back("sip"); + EXPECT_TRUE(ConnectAndWait(ws_url)); + EXPECT_EQ("sip", event_interface_->selected_subprotocol()); +} + } // namespace } // namespace net
diff --git a/ppapi/api/dev/ppp_zoom_dev.idl b/ppapi/api/dev/ppp_zoom_dev.idl index e8254da..2398f752 100644 --- a/ppapi/api/dev/ppp_zoom_dev.idl +++ b/ppapi/api/dev/ppp_zoom_dev.idl
@@ -16,7 +16,7 @@ */ interface PPP_Zoom_Dev { /** - * Instruct plug-in to zoom according to the given factor and whether the zoom + * Instruct plugin to zoom according to the given factor and whether the zoom * only applies to text only. The scale factor is the percentage divided by * 100, i.e. 150% zoom is 1.5. */
diff --git a/ppapi/c/dev/ppp_zoom_dev.h b/ppapi/c/dev/ppp_zoom_dev.h index d70fcdd..0cc39ea3 100644 --- a/ppapi/c/dev/ppp_zoom_dev.h +++ b/ppapi/c/dev/ppp_zoom_dev.h
@@ -31,7 +31,7 @@ */ struct PPP_Zoom_Dev_0_3 { /** - * Instruct plug-in to zoom according to the given factor and whether the zoom + * Instruct plugin to zoom according to the given factor and whether the zoom * only applies to text only. The scale factor is the percentage divided by * 100, i.e. 150% zoom is 1.5. */
diff --git a/ppapi/tests/test_case.html b/ppapi/tests/test_case.html index 5795572..529c9744 100644 --- a/ppapi/tests/test_case.html +++ b/ppapi/tests/test_case.html
@@ -300,7 +300,7 @@ } else { document.getElementById("console").innerHTML = '<span class="fail">FAIL</span>: ' + - '<span class="err_msg">Test plug-in is not registered.</span>'; + '<span class="err_msg">Test plugin is not registered.</span>'; } }
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index 6369e34..914693d 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -257,6 +257,10 @@ # define SK_IGNORE_ETC1_SUPPORT #endif +#ifndef SK_SUPPORT_LEGACY_FILTERLEVEL_ENUM +# define SK_SUPPORT_LEGACY_FILTERLEVEL_ENUM +#endif + #ifndef SK_IGNORE_GPU_DITHER # define SK_IGNORE_GPU_DITHER #endif
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 19609808..e872af6 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -338,7 +338,7 @@ { "test": "content_unittests", "args": ["--site-per-process"] }, { "test": "content_browsertests", "args": ["--site-per-process", "--gtest_filter=-*.AllowTargetedNavigationsAfterSwap:*.SupportCrossProcessPostMessage:*.DisownOpener:*.DontPreemptNavigationWithFrameTreeUpdate:*.ProcessExitWithSwappedOutViews:*.SupportCrossProcessPostMessageWithMessagePort"] }, { "test": "unit_tests", "args": ["--site-per-process"] }, - { "test": "browser_tests", "args": ["--site-per-process", "--gtest_filter=-AppApiTest.*:AutofillDialogControllerTest.*:BlockedAppApiTest.*:BookmarkOverrideTest.*:BrowserTest.ClearPendingOnFailUnlessNTP:BrowserTest.OtherRedirectsDontForkProcess:BrowserTest.WindowOpenClose:ChromeAppAPITest.*:ChromeRenderProcessHostTest.*:ChromeRenderProcessHostTestWithCommandLine.*:DevToolsExperimentalExtensionTest.*:DevToolsExtensionTest.*:DnsProbeBrowserTest.*:ErrorPageTest.*:ExecuteScriptApiTest.ExecuteScriptPermissions:ExtensionApiTest.ContentScriptExtensionIframe:ExtensionApiTest.ContentScriptOtherExtensions:ExtensionApiTest.ContentScriptExtensionProcess:ExtensionApiTest.TabsOnUpdated:ExtensionApiTest.WindowOpenPopupIframe:ExtensionBrowserTest.LoadChromeExtensionsWithOptionsParamWhenEmbedded:ExtensionCrxInstallerTest.InstallDelayedUntilNextUpdate:ExtensionOptionsApiTest.ExtensionCanEmbedOwnOptions:ExtensionSettingsApiTest.SimpleTest:ExtensionWebUITest.CanEmbedExtensionOptions:ExtensionWebUITest.ReceivesExtensionOptionsOnClose:ExternallyConnectableMessagingTest.*:GeolocationBrowserTest.*:HistoryBrowserTest.*:InlineLoginUISafeIframeBrowserTest.*:IsolatedAppTest.*:LaunchWebAuthFlowFunctionTest.*:MimeHandlerViewTest.*:NaClBrowserTestNonSfiMode.*:OptionsUIBrowserTest.*:PhishingClassifierTest.*:PhishingDOMFeatureExtractorTest.*:PlatformAppUrlRedirectorBrowserTest.*:PopupBlockerBrowserTest.*:PortForwardingTest.*:PrerenderBrowserTest.*:ProcessManagementTest.*:ProfileManagerBrowserTest.*:RedirectTest.*:ReferrerPolicyTest.*:SandboxStatusUITest.*:SSLUITest.*:SyncFileSystemApiTest.GetFileStatuses:SyncFileSystemTest.*:WebNavigationApiTest.CrossProcessFragment:WebNavigationApiTest.ServerRedirectSingleProcess:WebNavigationApiTest.CrossProcessHistory:WebViewDPITest.*:WebViewPluginTest.*:WebViewTest.*:ZoomControllerBrowserTest.*:*.NavigateFromNTPToOptionsInSameTab:*.ProfilesWithoutPagesNotLaunched:*.TabMove:*.WhitelistedExtension:*.NewTabPageURL:*.HomepageLocation:RestoreOnStartupPolicyTest*:ExtensionApiTest.ActiveTab:PhishingClassifierDelegateTest.*:WebUIWebViewBrowserTest.ExecuteScriptCode"] } + { "test": "browser_tests", "args": ["--site-per-process", "--gtest_filter=-AppApiTest.*:BlockedAppApiTest.*:BrowserTest.ClearPendingOnFailUnlessNTP:BrowserTest.OtherRedirectsDontForkProcess:BrowserTest.WindowOpenClose:ChromeAppAPITest.*:ChromeRenderProcessHostTest.*:ChromeRenderProcessHostTestWithCommandLine.*:DevToolsExperimentalExtensionTest.*:DevToolsExtensionTest.*:DnsProbeBrowserTest.*:ErrorPageTest.*:ExecuteScriptApiTest.ExecuteScriptPermissions:ExtensionApiTest.ContentScriptExtensionIframe:ExtensionApiTest.ContentScriptOtherExtensions:ExtensionApiTest.ContentScriptExtensionProcess:ExtensionApiTest.TabsOnUpdated:ExtensionApiTest.WindowOpenPopupIframe:ExtensionBrowserTest.LoadChromeExtensionsWithOptionsParamWhenEmbedded:ExtensionOptionsApiTest.ExtensionCanEmbedOwnOptions:ExtensionWebUITest.CanEmbedExtensionOptions:ExtensionWebUITest.ReceivesExtensionOptionsOnClose:ExternallyConnectableMessagingTest.*:HistoryBrowserTest.*:InlineLoginUISafeIframeBrowserTest.*:IsolatedAppTest.*:LaunchWebAuthFlowFunctionTest.*:MimeHandlerViewTest.*:OptionsUIBrowserTest.*:PhishingClassifierTest.*:PhishingDOMFeatureExtractorTest.*:PlatformAppUrlRedirectorBrowserTest.*:PopupBlockerBrowserTest.*:PrerenderBrowserTest.*:ProcessManagementTest.*:RedirectTest.*:ReferrerPolicyTest.*:SSLUITest.*:WebNavigationApiTest.CrossProcessFragment:WebNavigationApiTest.ServerRedirectSingleProcess:WebNavigationApiTest.CrossProcessHistory:WebViewDPITest.*:WebViewPluginTest.*:WebViewTest.*:ZoomControllerBrowserTest.*:*.NavigateFromNTPToOptionsInSameTab:*.ProfilesWithoutPagesNotLaunched:*.TabMove:*.WhitelistedExtension:*.NewTabPageURL:*.HomepageLocation:RestoreOnStartupPolicyTest*:PhishingClassifierDelegateTest.*:WebUIWebViewBrowserTest.ExecuteScriptCode"] } ] }, "Site Isolation Win": { @@ -346,7 +346,7 @@ { "test": "content_unittests", "args": ["--site-per-process"] }, { "test": "content_browsertests", "args": ["--site-per-process", "--gtest_filter=-*.AllowTargetedNavigationsAfterSwap:*.SupportCrossProcessPostMessage:*.DisownOpener:*.DontPreemptNavigationWithFrameTreeUpdate:*.ProcessExitWithSwappedOutViews:*.SupportCrossProcessPostMessageWithMessagePort"] }, { "test": "unit_tests", "args": ["--site-per-process"] }, - { "test": "browser_tests", "args": ["--site-per-process", "--gtest_filter=-AppApiTest.*:AutofillDialogControllerTest.*:BlockedAppApiTest.*:BookmarkOverrideTest.*:BrowserTest.ClearPendingOnFailUnlessNTP:BrowserTest.OtherRedirectsDontForkProcess:BrowserTest.WindowOpenClose:ChromeAppAPITest.*:ChromeRenderProcessHostTest.*:ChromeRenderProcessHostTestWithCommandLine.*:DevToolsExperimentalExtensionTest.*:DevToolsExtensionTest.*:DnsProbeBrowserTest.*:ErrorPageTest.*:ExecuteScriptApiTest.ExecuteScriptPermissions:ExtensionApiTest.ContentScriptExtensionIframe:ExtensionApiTest.ContentScriptOtherExtensions:ExtensionApiTest.ContentScriptExtensionProcess:ExtensionApiTest.TabsOnUpdated:ExtensionApiTest.WindowOpenPopupIframe:ExtensionBrowserTest.LoadChromeExtensionsWithOptionsParamWhenEmbedded:ExtensionCrxInstallerTest.InstallDelayedUntilNextUpdate:ExtensionOptionsApiTest.ExtensionCanEmbedOwnOptions:ExtensionSettingsApiTest.SimpleTest:ExtensionWebUITest.CanEmbedExtensionOptions:ExtensionWebUITest.ReceivesExtensionOptionsOnClose:ExternallyConnectableMessagingTest.*:GeolocationBrowserTest.*:HistoryBrowserTest.*:InlineLoginUISafeIframeBrowserTest.*:IsolatedAppTest.*:LaunchWebAuthFlowFunctionTest.*:MimeHandlerViewTest.*:NaClBrowserTestNonSfiMode.*:OptionsUIBrowserTest.*:PhishingClassifierTest.*:PhishingDOMFeatureExtractorTest.*:PlatformAppUrlRedirectorBrowserTest.*:PopupBlockerBrowserTest.*:PortForwardingTest.*:PrerenderBrowserTest.*:ProcessManagementTest.*:ProfileManagerBrowserTest.*:RedirectTest.*:ReferrerPolicyTest.*:SandboxStatusUITest.*:SSLUITest.*:SyncFileSystemApiTest.GetFileStatuses:SyncFileSystemTest.*:WebNavigationApiTest.CrossProcessFragment:WebNavigationApiTest.ServerRedirectSingleProcess:WebNavigationApiTest.CrossProcessHistory:WebViewDPITest.*:WebViewPluginTest.*:WebViewTest.*:ZoomControllerBrowserTest.*:*.NavigateFromNTPToOptionsInSameTab:*.ProfilesWithoutPagesNotLaunched:*.TabMove:*.WhitelistedExtension:*.NewTabPageURL:*.HomepageLocation:RestoreOnStartupPolicyTest*:ExtensionApiTest.ActiveTab:PhishingClassifierDelegateTest.*:WebUIWebViewBrowserTest.ExecuteScriptCode"] } + { "test": "browser_tests", "args": ["--site-per-process", "--gtest_filter=-AppApiTest.*:BlockedAppApiTest.*:BrowserTest.ClearPendingOnFailUnlessNTP:BrowserTest.OtherRedirectsDontForkProcess:BrowserTest.WindowOpenClose:ChromeAppAPITest.*:ChromeRenderProcessHostTest.*:ChromeRenderProcessHostTestWithCommandLine.*:DevToolsExperimentalExtensionTest.*:DevToolsExtensionTest.*:DnsProbeBrowserTest.*:ErrorPageTest.*:ExecuteScriptApiTest.ExecuteScriptPermissions:ExtensionApiTest.ContentScriptExtensionIframe:ExtensionApiTest.ContentScriptOtherExtensions:ExtensionApiTest.ContentScriptExtensionProcess:ExtensionApiTest.TabsOnUpdated:ExtensionApiTest.WindowOpenPopupIframe:ExtensionBrowserTest.LoadChromeExtensionsWithOptionsParamWhenEmbedded:ExtensionOptionsApiTest.ExtensionCanEmbedOwnOptions:ExtensionWebUITest.CanEmbedExtensionOptions:ExtensionWebUITest.ReceivesExtensionOptionsOnClose:ExternallyConnectableMessagingTest.*:HistoryBrowserTest.*:InlineLoginUISafeIframeBrowserTest.*:IsolatedAppTest.*:LaunchWebAuthFlowFunctionTest.*:MimeHandlerViewTest.*:OptionsUIBrowserTest.*:PhishingClassifierTest.*:PhishingDOMFeatureExtractorTest.*:PlatformAppUrlRedirectorBrowserTest.*:PopupBlockerBrowserTest.*:PrerenderBrowserTest.*:ProcessManagementTest.*:RedirectTest.*:ReferrerPolicyTest.*:SSLUITest.*:WebNavigationApiTest.CrossProcessFragment:WebNavigationApiTest.ServerRedirectSingleProcess:WebNavigationApiTest.CrossProcessHistory:WebViewDPITest.*:WebViewPluginTest.*:WebViewTest.*:ZoomControllerBrowserTest.*:*.NavigateFromNTPToOptionsInSameTab:*.ProfilesWithoutPagesNotLaunched:*.TabMove:*.WhitelistedExtension:*.NewTabPageURL:*.HomepageLocation:RestoreOnStartupPolicyTest*:PhishingClassifierDelegateTest.*:WebUIWebViewBrowserTest.ExecuteScriptCode"] } ] }, "Browser Side Navigation Linux": {
diff --git a/testing/buildbot/chromium.perf.json b/testing/buildbot/chromium.perf.json index 8bf43b23..2fd07bd 100644 --- a/testing/buildbot/chromium.perf.json +++ b/testing/buildbot/chromium.perf.json
@@ -1,4 +1,13 @@ { + "Linux Perf (3)": { + "scripts": [ + { + "name": "cc_perftests", + "script": "gtest_perf_test.py", + "args": ["cc_perftests", "--test-launcher-print-test-stdio=always"] + } + ] + }, "Android Nexus4 Perf": { "scripts": [ { @@ -71,11 +80,6 @@ }, "Android One Perf": { "scripts": [ - { - "name": "gpu_perftests", - "script": "gtest_perf_test.py", - "args": ["gpu_perftests"] - } ] }, "Android MotoE Perf": {
diff --git a/testing/buildbot/chromium.win.json b/testing/buildbot/chromium.win.json index f65c4b0..3f69a8e 100644 --- a/testing/buildbot/chromium.win.json +++ b/testing/buildbot/chromium.win.json
@@ -94,6 +94,7 @@ "shards": 2 } }, + "ipc_mojo_unittests", "ipc_tests", "jingle_unittests", {
diff --git a/testing/legion/tools/legion.py b/testing/legion/tools/legion.py new file mode 100755 index 0000000..7b67133 --- /dev/null +++ b/testing/legion/tools/legion.py
@@ -0,0 +1,159 @@ +#!/usr/bin/env python +# 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. + +"""A helper module to run Legion multi-machine tests. + +Example usage with 1 task machine: +$ testing/legion/tools/legion.py run \ + --controller-isolated out/Release/example_test_controller.isolated \ + --dimension os Ubuntu-14.04 \ + --task-name test-task-name \ + --task task_machine out/Release/example_task_machine.isolated + +Example usage with 2 task machines with the same isolated file: +$ testing/legion/tools/legion.py run \ + --controller-isolated out/Release/example_test_controller.isolated \ + --dimension os Ubuntu-14.04 \ + --task-name test-task-name \ + --task task_machine_1 out/Release/example_task_machine.isolated \ + --task task_machine_2 out/Release/example_task_machine.isolated + +Example usage with 2 task machines with different isolated file: +$ testing/legion/tools/legion.py run \ + --controller-isolated out/Release/example_test_controller.isolated \ + --dimension os Ubuntu-14.04 \ + --task-name test-task-name \ + --task task_machine_1 out/Release/example_task_machine_1.isolated \ + --task task_machine_2 out/Release/example_task_machine_2.isolated +""" + +import argparse +import logging +import os +import subprocess +import sys + + +THIS_DIR = os.path.split(__file__)[0] +SWARMING_DIR = os.path.join(THIS_DIR, '..', '..', '..', 'tools', + 'swarming_client') +ISOLATE_PY = os.path.join(SWARMING_DIR, 'isolate.py') +SWARMING_PY = os.path.join(SWARMING_DIR, 'swarming.py') +LOGGING_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR'] + + +class Error(Exception): + pass + + +def GetArgs(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=['run', 'trigger'], + help='The swarming action to perform.') + parser.add_argument('-f', '--format-only', action='store_true', + help='If true the .isolated files are archived but ' + 'swarming is not called, only the command line is built.') + parser.add_argument('--controller-isolated', required=True, + help='The isolated file for the test controller.') + parser.add_argument('--isolate-server', help='Optional. The isolated server ' + 'to use.') + parser.add_argument('--swarming-server', help='Optional. The swarming server ' + 'to use.') + parser.add_argument('--task-name', help='Optional. The swarming task name ' + 'to use.') + parser.add_argument('--dimension', action='append', dest='dimensions', + nargs=2, default=[], help='Dimensions to pass to ' + 'swarming.py. This is in the form of --dimension key ' + 'value. The minimum required is --dimension os <OS>') + parser.add_argument('--task', action='append', dest='tasks', + nargs=2, default=[], help='List of task names used in ' + 'the test controller. This is in the form of --task name ' + '.isolated and is passed to the controller as --name ' + '<ISOLATED HASH>.') + parser.add_argument('--controller-var', action='append', + dest='controller_vars', nargs=2, default=[], + help='Command line vars to pass to the controller. These ' + 'are in the form of --controller-var name value and are ' + 'passed to the controller as --name value.') + parser.add_argument('-v', '--verbosity', default=0, action='count') + return parser.parse_args() + + +def RunCommand(cmd, stream_stdout=False): + """Runs the command line and streams stdout if requested.""" + kwargs = { + 'args': cmd, + 'stderr': subprocess.PIPE, + } + if not stream_stdout: + kwargs['stdout'] = subprocess.PIPE + + p = subprocess.Popen(**kwargs) + stdout, stderr = p.communicate() + if p.returncode: + raise Error(stderr) + if not stream_stdout: + logging.debug(stdout) + return stdout + + +def Archive(isolated, isolate_server=None): + """Calls isolate.py archive with the given args.""" + cmd = [ + sys.executable, + ISOLATE_PY, + 'archive', + '--isolated', isolated, + ] + if isolate_server: + cmd.extend(['--isolate-server', isolate_server]) + print ' '.join(cmd) + return RunCommand(cmd).split()[0] # The isolated hash + + +def GetSwarmingCommandLine(args): + """Builds and returns the command line for swarming.py run|trigger.""" + cmd = [ + sys.executable, + SWARMING_PY, + args.action, + args.controller_isolated, + ] + if args.isolate_server: + cmd.extend(['--isolate-server', args.isolate_server]) + if args.swarming_server: + cmd.extend(['--swarming', args.swarming_server]) + if args.task_name: + cmd.extend(['--task-name', args.task_name]) + # swarming.py dimensions + for name, value in args.dimensions: + cmd.extend(['--dimension', name, value]) + + cmd.append('--') + + # Task name/hash values + for name, isolated in args.tasks: + cmd.extend(['--' + name, Archive(isolated, args.isolate_server)]) + # Test controller args + for name, value in args.controller_vars: + cmd.extend(['--' + name, value]) + print ' '.join(cmd) + return cmd + + +def main(): + args = GetArgs() + logging.basicConfig( + format='%(asctime)s %(filename)s:%(lineno)s %(levelname)s] %(message)s', + datefmt='%H:%M:%S', + level=LOGGING_LEVELS[len(LOGGING_LEVELS)-args.verbosity-1]) + cmd = GetSwarmingCommandLine(args) + if not args.format_only: + RunCommand(cmd, True) + return 0 + + +if __name__ == '__main__': + sys.exit(main())
diff --git a/third_party/instrumented_libraries/download_build_install.py b/third_party/instrumented_libraries/download_build_install.py index 50945d2e..48694fa 100755 --- a/third_party/instrumented_libraries/download_build_install.py +++ b/third_party/instrumented_libraries/download_build_install.py
@@ -58,6 +58,8 @@ product_dir = real_path(args.product_dir) self._destdir = os.path.join( product_dir, 'instrumented_libraries', self._sanitizer) + self._source_archives_dir = os.path.join( + product_dir, 'instrumented_libraries', 'sources', self._package) self._cflags = unescape_flags(args.cflags) if args.sanitizer_blacklist: @@ -70,6 +72,7 @@ # Initialized later. self._source_dir = None + self._source_archives = None def init_build_env(self): self._build_env = os.environ.copy() @@ -105,7 +108,11 @@ raise Exception('Failed to run: %s' % command) def maybe_download_source(self): - """Checks out the source code (if needed) and sets self._source_dir.""" + """Checks out the source code (if needed). + + Checks out the source code for the package, if required (i.e. unless running + in no-clobber mode). Initializes self._source_dir and self._source_archives. + """ get_fresh_source = self._clobber or not os.path.exists(self._working_dir) if get_fresh_source: self.shell_call('rm -rf %s' % self._working_dir) @@ -114,11 +121,19 @@ cwd=self._working_dir) (dirpath, dirnames, filenames) = os.walk(self._working_dir).next() + if len(dirnames) != 1: - raise Exception('apt-get source %s must create exactly one subdirectory.' - % self._package) + raise Exception( + '`apt-get source %s\' must create exactly one subdirectory.' + % self._package) self._source_dir = os.path.join(dirpath, dirnames[0], '') + if len(filenames) == 0: + raise Exception('Can\'t find source archives after `apt-get source %s\'.' + % self._package) + self._source_archives = \ + [os.path.join(dirpath, filename) for filename in filenames] + return get_fresh_source def patch_source(self): @@ -127,10 +142,24 @@ if self._run_before_build: self.shell_call(self._run_before_build, cwd=self._source_dir) + def copy_source_archives(self): + """Copies the downloaded source archives to the output dir. + + For license compliance purposes, every Chromium build that includes + instrumented libraries must include their full source code. + """ + self.shell_call('rm -rf %s' % self._source_archives_dir) + os.makedirs(self._source_archives_dir) + for filename in self._source_archives: + shutil.copy(filename, self._source_archives_dir) + if self._patch: + shutil.copy(self._patch, self._source_archives_dir) + def download_build_install(self): got_fresh_source = self.maybe_download_source() if got_fresh_source: self.patch_source() + self.copy_source_archives() self.shell_call('mkdir -p %s' % self.dest_libdir())
diff --git a/third_party/libjingle/README.chromium b/third_party/libjingle/README.chromium index 45a1d03..ea50d24 100644 --- a/third_party/libjingle/README.chromium +++ b/third_party/libjingle/README.chromium
@@ -1,7 +1,7 @@ Name: libjingle URL: http://code.google.com/p/webrtc/ Version: unknown -Revision: 8700 +Revision: 8725 License: BSD License File: source/talk/COPYING Security Critical: yes
diff --git a/third_party/libusb/src/libusb/os/darwin_usb.c b/third_party/libusb/src/libusb/os/darwin_usb.c index 07d6d61a..f95706a 100644 --- a/third_party/libusb/src/libusb/os/darwin_usb.c +++ b/third_party/libusb/src/libusb/os/darwin_usb.c
@@ -1195,7 +1195,7 @@ kresult = (*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID)&cInterface->interface); - /* We no longer need the intermediate plug-in */ + /* We no longer need the intermediate plugin */ /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */ (*plugInInterface)->Release (plugInInterface); if (kresult || !cInterface->interface) {
diff --git a/third_party/npapi/bindings/npapi.h b/third_party/npapi/bindings/npapi.h index aec11da2..8d42450 100644 --- a/third_party/npapi/bindings/npapi.h +++ b/third_party/npapi/bindings/npapi.h
@@ -197,11 +197,11 @@ #endif /* __LP64__ */ /* - * NPP is a plug-in's opaque instance handle + * NPP is a plugin's opaque instance handle */ typedef struct _NPP { - void* pdata; /* plug-in private data */ + void* pdata; /* plugin private data */ void* ndata; /* netscape private data */ } NPP_t; @@ -209,7 +209,7 @@ typedef struct _NPStream { - void* pdata; /* plug-in private data */ + void* pdata; /* plugin private data */ void* ndata; /* netscape private data */ const char* url; uint32_t end; @@ -387,7 +387,7 @@ /* Browsers can retrieve a native ATK accessibility plug ID via this variable. */ NPPVpluginNativeAccessibleAtkPlugId = 19, - /* Checks to see if the plug-in would like the browser to load the "src" attribute. */ + /* Checks to see if the plugin would like the browser to load the "src" attribute. */ NPPVpluginCancelSrcStream = 20, NPPVsupportsAdvancedKeyHandling = 21, @@ -399,7 +399,7 @@ , NPPVpluginDrawingModel = 1000 /* Used for negotiating event models */ , NPPVpluginEventModel = 1001 - /* In the NPDrawingModelCoreAnimation drawing model, the browser asks the plug-in for a Core Animation layer. */ + /* In the NPDrawingModelCoreAnimation drawing model, the browser asks the plugin for a Core Animation layer. */ , NPPVpluginCoreAnimationLayer = 1003 #endif
diff --git a/third_party/npapi/bindings/npfunctions.h b/third_party/npapi/bindings/npfunctions.h index 02a54be..f755b04 100644 --- a/third_party/npapi/bindings/npfunctions.h +++ b/third_party/npapi/bindings/npfunctions.h
@@ -227,8 +227,8 @@ typedef struct _BPSupportedMIMETypes { SInt32 structVersion; /* struct version */ - Handle typeStrings; /* STR# formated handle, allocated by plug-in */ - Handle infoStrings; /* STR# formated handle, allocated by plug-in */ + Handle typeStrings; /* STR# formated handle, allocated by plugin */ + Handle infoStrings; /* STR# formated handle, allocated by plugin */ } BPSupportedMIMETypes; OSErr BP_GetSupportedMIMETypes(BPSupportedMIMETypes *mimeInfo, UInt32 flags); #define NP_GETMIMEDESCRIPTION_NAME "NP_GetMIMEDescription"
diff --git a/tools/gn/BUILD.gn b/tools/gn/BUILD.gn index bc37bc7..97c0f94 100644 --- a/tools/gn/BUILD.gn +++ b/tools/gn/BUILD.gn
@@ -222,6 +222,7 @@ test("gn_unittests") { sources = [ "action_target_generator_unittest.cc", + "args_unittest.cc", "builder_unittest.cc", "c_include_iterator_unittest.cc", "command_format_unittest.cc",
diff --git a/tools/gn/args.cc b/tools/gn/args.cc index 2a1509a4..60ee7b2 100644 --- a/tools/gn/args.cc +++ b/tools/gn/args.cc
@@ -66,13 +66,30 @@ " to specify build args in an \"import\"-ed file if you want such\n" " arguments to apply to multiple buildfiles.\n"; +namespace { + +// Removes all entries in |overrides| that are in |declared_overrides|. +void RemoveDeclaredOverrides(const Scope::KeyValueMap& declared_arguments, + Scope::KeyValueMap* overrides) { + for (Scope::KeyValueMap::iterator override = overrides->begin(); + override != overrides->end();) { + if (declared_arguments.find(override->first) == declared_arguments.end()) + ++override; + else + overrides->erase(override++); + } +} + +} // namespace + Args::Args() { } Args::Args(const Args& other) : overrides_(other.overrides_), all_overrides_(other.all_overrides_), - declared_arguments_(other.declared_arguments_) { + declared_arguments_per_toolchain_( + other.declared_arguments_per_toolchain_) { } Args::~Args() { @@ -124,6 +141,8 @@ Err* err) const { base::AutoLock lock(lock_); + Scope::KeyValueMap& declared_arguments( + DeclaredArgumentsForToolchainLocked(scope_to_set)); for (const auto& arg : args) { // Verify that the value hasn't already been declared. We want each value // to be declared only once. @@ -132,8 +151,8 @@ // when used from different toolchains, so we can't just check that we've // seen it before. Instead, we check that the location matches. Scope::KeyValueMap::iterator previously_declared = - declared_arguments_.find(arg.first); - if (previously_declared != declared_arguments_.end()) { + declared_arguments.find(arg.first); + if (previously_declared != declared_arguments.end()) { if (previously_declared->second.origin() != arg.second.origin()) { // Declaration location mismatch. *err = Err(arg.second.origin(), @@ -151,7 +170,7 @@ return false; } } else { - declared_arguments_.insert(arg); + declared_arguments.insert(arg); } // Only set on the current scope to the new value if it hasn't been already @@ -168,43 +187,41 @@ bool Args::VerifyAllOverridesUsed(Err* err) const { base::AutoLock lock(lock_); - return VerifyAllOverridesUsed(all_overrides_, declared_arguments_, err); -} + Scope::KeyValueMap all_overrides(all_overrides_); + for (const auto& map_pair : declared_arguments_per_toolchain_) + RemoveDeclaredOverrides(map_pair.second, &all_overrides); -bool Args::VerifyAllOverridesUsed( - const Scope::KeyValueMap& overrides, - const Scope::KeyValueMap& declared_arguments, - Err* err) { - for (const auto& override : overrides) { - if (declared_arguments.find(override.first) == declared_arguments.end()) { - // Get a list of all possible overrides for help with error finding. - // - // It might be nice to do edit distance checks to see if we can find one - // close to what you typed. - std::string all_declared_str; - for (Scope::KeyValueMap::const_iterator cur_str = - declared_arguments.begin(); - cur_str != declared_arguments.end(); ++cur_str) { - if (cur_str != declared_arguments.begin()) - all_declared_str += ", "; - all_declared_str += cur_str->first.as_string(); - } + if (all_overrides.empty()) + return true; - *err = Err(override.second.origin(), "Build argument has no effect.", - "The variable \"" + override.first.as_string() + - "\" was set as a build " - "argument\nbut never appeared in a declare_args() block in any " - "buildfile.\n\nPossible arguments: " + all_declared_str); - return false; + // Get a list of all possible overrides for help with error finding. + // + // It might be nice to do edit distance checks to see if we can find one close + // to what you typed. + std::string all_declared_str; + for (const auto& map_pair : declared_arguments_per_toolchain_) { + for (const auto& cur_str : map_pair.second) { + if (!all_declared_str.empty()) + all_declared_str += ", "; + all_declared_str += cur_str.first.as_string(); } } - return true; + + *err = Err( + all_overrides.begin()->second.origin(), "Build argument has no effect.", + "The variable \"" + all_overrides.begin()->first.as_string() + + "\" was set as a build argument\nbut never appeared in a " + + "declare_args() block in any buildfile.\n\nPossible arguments: " + + all_declared_str); + return false; } void Args::MergeDeclaredArguments(Scope::KeyValueMap* dest) const { base::AutoLock lock(lock_); - for (const auto& arg : declared_arguments_) - (*dest)[arg.first] = arg.second; + for (const auto& map_pair : declared_arguments_per_toolchain_) { + for (const auto& arg : map_pair.second) + (*dest)[arg.first] = arg.second; + } } void Args::SetSystemVarsLocked(Scope* dest) const { @@ -257,12 +274,14 @@ dest->SetValue(variables::kTargetCpu, empty_string, nullptr); dest->SetValue(variables::kCurrentCpu, empty_string, nullptr); - declared_arguments_[variables::kHostOs] = os_val; - declared_arguments_[variables::kCurrentOs] = empty_string; - declared_arguments_[variables::kTargetOs] = empty_string; - declared_arguments_[variables::kHostCpu] = arch_val; - declared_arguments_[variables::kCurrentCpu] = empty_string; - declared_arguments_[variables::kTargetCpu] = empty_string; + Scope::KeyValueMap& declared_arguments( + DeclaredArgumentsForToolchainLocked(dest)); + declared_arguments[variables::kHostOs] = os_val; + declared_arguments[variables::kCurrentOs] = empty_string; + declared_arguments[variables::kTargetOs] = empty_string; + declared_arguments[variables::kHostCpu] = arch_val; + declared_arguments[variables::kCurrentCpu] = empty_string; + declared_arguments[variables::kTargetCpu] = empty_string; // Mark these variables used so the build config file can override them // without geting a warning about overwriting an unused variable. @@ -286,3 +305,9 @@ for (const auto& val : values) all_overrides_[val.first] = val.second; } + +Scope::KeyValueMap& Args::DeclaredArgumentsForToolchainLocked( + Scope* scope) const { + lock_.AssertAcquired(); + return declared_arguments_per_toolchain_[scope->settings()]; +}
diff --git a/tools/gn/args.h b/tools/gn/args.h index 6852c309..345516c 100644 --- a/tools/gn/args.h +++ b/tools/gn/args.h
@@ -61,19 +61,15 @@ // arguments. If there are, this returns false and sets the error. bool VerifyAllOverridesUsed(Err* err) const; - // Like VerifyAllOverridesUsed but takes the lists of overrides specified and - // parameters declared. - static bool VerifyAllOverridesUsed( - const Scope::KeyValueMap& overrides, - const Scope::KeyValueMap& declared_arguments, - Err* err); - // Adds all declared arguments to the given output list. If the values exist // in the list already, their values will be overwriten, but other values // already in the list will remain. void MergeDeclaredArguments(Scope::KeyValueMap* dest) const; private: + using DeclaredArgumentsPerToolchain = + base::hash_map<const Settings*, Scope::KeyValueMap>; + // Sets the default config based on the current system. void SetSystemVarsLocked(Scope* scope) const; @@ -83,6 +79,10 @@ void SaveOverrideRecordLocked(const Scope::KeyValueMap& values) const; + // Returns the KeyValueMap used for arguments declared for the specified + // toolchain. + Scope::KeyValueMap& DeclaredArgumentsForToolchainLocked(Scope* scope) const; + // Since this is called during setup which we assume is single-threaded, // this is not protected by the lock. It should be set only during init. Scope::KeyValueMap overrides_; @@ -94,9 +94,12 @@ // check for overrides that were specified but never used. mutable Scope::KeyValueMap all_overrides_; - // Tracks all variables declared in any buildfile. This is so we can see if - // the user set variables on the command line that are not used anywhere. - mutable Scope::KeyValueMap declared_arguments_; + // Maps from Settings (which corresponds to a toolchain) to the map of + // declared variables. This is used to tracks all variables declared in any + // buildfile. This is so we can see if the user set variables on the command + // line that are not used anywhere. Each map is toolchain specific as each + // toolchain may define variables in different locations. + mutable DeclaredArgumentsPerToolchain declared_arguments_per_toolchain_; Args& operator=(const Args& other); // Disallow assignment. };
diff --git a/tools/gn/args_unittest.cc b/tools/gn/args_unittest.cc new file mode 100644 index 0000000..098f3dec --- /dev/null +++ b/tools/gn/args_unittest.cc
@@ -0,0 +1,41 @@ +// 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 "tools/gn/args.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "tools/gn/scheduler.h" +#include "tools/gn/test_with_scope.h" + +// Assertions for VerifyAllOverridesUsed() and DeclareArgs() with multiple +// toolchains. +TEST(ArgsTest, VerifyAllOverridesUsed) { + TestWithScope setup1, setup2; + Args args; + Scope::KeyValueMap key_value_map1; + Err err; + LiteralNode assignment1; + + setup1.scope()->SetValue("a", Value(nullptr, true), &assignment1); + setup1.scope()->GetCurrentScopeValues(&key_value_map1); + EXPECT_TRUE(args.DeclareArgs(key_value_map1, setup1.scope(), &err)); + + LiteralNode assignment2; + setup2.scope()->SetValue("b", Value(nullptr, true), &assignment2); + Scope::KeyValueMap key_value_map2; + setup2.scope()->GetCurrentScopeValues(&key_value_map2); + EXPECT_TRUE(args.DeclareArgs(key_value_map2, setup2.scope(), &err)); + + // Override "a", shouldn't see any errors as "a" was defined. + args.AddArgOverride("a", Value(nullptr, true)); + EXPECT_TRUE(args.VerifyAllOverridesUsed(&err)); + + // Override "a", & "b", shouldn't see any errors as both were defined. + args.AddArgOverride("b", Value(nullptr, true)); + EXPECT_TRUE(args.VerifyAllOverridesUsed(&err)); + + // Override "a", "b" and "c", should fail as "c" was not defined. + args.AddArgOverride("c", Value(nullptr, true)); + EXPECT_FALSE(args.VerifyAllOverridesUsed(&err)); +}
diff --git a/tools/gn/config_values_extractors.h b/tools/gn/config_values_extractors.h index 8ccf7f5..49945421 100644 --- a/tools/gn/config_values_extractors.h +++ b/tools/gn/config_values_extractors.h
@@ -43,7 +43,7 @@ return target_->configs()[cur_index_].ptr->config_values(); } - // Returns the origin of who added this config, if any. This will alwsya be + // Returns the origin of who added this config, if any. This will always be // null for the config values of a target itself. const ParseNode* origin() const { if (cur_index_ == -1)
diff --git a/tools/gn/functions.cc b/tools/gn/functions.cc index 1cfa6fe..7798a96 100644 --- a/tools/gn/functions.cc +++ b/tools/gn/functions.cc
@@ -20,6 +20,27 @@ #include "tools/gn/token.h" #include "tools/gn/value.h" +namespace { + +// Some functions take a {} following them, and some don't. For the ones that +// don't, this is used to verify that the given block node is null and will +// set the error accordingly if it's not. Returns true if the block is null. +bool VerifyNoBlockForFunctionCall(const FunctionCallNode* function, + const BlockNode* block, + Err* err) { + if (!block) + return true; + + *err = Err(block, "Unexpected '{'.", + "This function call doesn't take a {} block following it, and you\n" + "can't have a {} block that's not connected to something like an if\n" + "statement or a target declaration."); + err->AppendRange(function->function().range()); + return false; +} + +} // namespace + bool EnsureNotProcessingImport(const ParseNode* node, const Scope* scope, Err* err) { @@ -744,6 +765,14 @@ } if (found_function->second.self_evaluating_args_runner) { + // Self evaluating args functions are special weird built-ins. Currently, + // only foreach() takes a block following it. Rather than force them all to + // check that they have a block or no block and risk bugs for new additions, + // check a whitelist here. + if (found_function->second.self_evaluating_args_runner != &RunForEach) { + if (!VerifyNoBlockForFunctionCall(function, block, err)) + return Value(); + } return found_function->second.self_evaluating_args_runner( scope, function, args_list, err); } @@ -784,6 +813,8 @@ } // Otherwise it's a no-block function. + if (!VerifyNoBlockForFunctionCall(function, block, err)) + return Value(); return found_function->second.no_block_runner(scope, function, args.list_value(), err); }
diff --git a/tools/gn/functions_unittest.cc b/tools/gn/functions_unittest.cc index 82173edac8..6a6c679 100644 --- a/tools/gn/functions_unittest.cc +++ b/tools/gn/functions_unittest.cc
@@ -53,3 +53,36 @@ ASSERT_EQ(Value::BOOLEAN, result.type()); EXPECT_FALSE(result.boolean_value()); } + +// Tests that an error is thrown when a {} is supplied to a function that +// doesn't take one. +TEST(Functions, FunctionsWithBlock) { + TestWithScope setup; + Err err; + + // No scope to print() is OK. + TestParseInput print_no_scope("print(6)"); + EXPECT_FALSE(print_no_scope.has_error()); + Value result = print_no_scope.parsed()->Execute(setup.scope(), &err); + EXPECT_FALSE(err.has_error()); + + // Passing a scope should pass parsing (it doesn't know about what kind of + // function it is) and then throw an error during execution. + TestParseInput print_with_scope("print(foo) {}"); + EXPECT_FALSE(print_with_scope.has_error()); + result = print_with_scope.parsed()->Execute(setup.scope(), &err); + EXPECT_TRUE(err.has_error()); + err = Err(); + + // defined() is a special function so test it separately. + TestParseInput defined_no_scope("defined(foo)"); + EXPECT_FALSE(defined_no_scope.has_error()); + result = defined_no_scope.parsed()->Execute(setup.scope(), &err); + EXPECT_FALSE(err.has_error()); + + // A block to defined should fail. + TestParseInput defined_with_scope("defined(foo) {}"); + EXPECT_FALSE(defined_with_scope.has_error()); + result = defined_with_scope.parsed()->Execute(setup.scope(), &err); + EXPECT_TRUE(err.has_error()); +}
diff --git a/tools/gn/parse_tree_unittest.cc b/tools/gn/parse_tree_unittest.cc index 6d21227..827f3d5 100644 --- a/tools/gn/parse_tree_unittest.cc +++ b/tools/gn/parse_tree_unittest.cc
@@ -56,8 +56,14 @@ TestWithScope setup; // Printing both values should be OK. + // + // The crazy template definition here is a way to execute a block without + // defining a target. Templates require that both the target_name and the + // invoker be used, which is what the assertion statement inside the template + // does. TestParseInput input_all_used( - "{\n" + "template(\"foo\") { assert(target_name != 0 && invoker != 0) }\n" + "foo(\"a\") {\n" " a = 12\n" " b = 13\n" " print(\"$a $b\")\n" @@ -70,7 +76,7 @@ // Skipping one should throw an unused var error. TestParseInput input_unused( - "{\n" + "foo(\"a\") {\n" " a = 12\n" " b = 13\n" " print(\"$a\")\n" @@ -85,7 +91,6 @@ // "13" assigned to "b". EXPECT_EQ(3, err.location().line_number()); EXPECT_EQ(7, err.location().char_offset()); - } TEST(ParseTree, OriginForDereference) {
diff --git a/tools/gn/parser.cc b/tools/gn/parser.cc index 4acd5103..13710cd 100644 --- a/tools/gn/parser.cc +++ b/tools/gn/parser.cc
@@ -446,9 +446,7 @@ } scoped_ptr<ParseNode> Parser::ParseStatement() { - if (LookAhead(Token::LEFT_BRACE)) { - return ParseBlock(); - } else if (LookAhead(Token::IF)) { + if (LookAhead(Token::IF)) { return ParseCondition(); } else if (LookAhead(Token::BLOCK_COMMENT)) { return BlockComment(Consume()); @@ -500,11 +498,14 @@ Consume(Token::RIGHT_PAREN, "Expected ')' after condition of 'if'."); condition->set_if_true(ParseBlock().Pass()); if (Match(Token::ELSE)) { - if (!LookAhead(Token::LEFT_BRACE) && !LookAhead(Token::IF)) { + if (LookAhead(Token::LEFT_BRACE)) { + condition->set_if_false(ParseBlock().Pass()); + } else if (LookAhead(Token::IF)) { + condition->set_if_false(ParseStatement().Pass()); + } else { *err_ = Err(cur_token(), "Expected '{' or 'if' after 'else'."); return scoped_ptr<ParseNode>(); } - condition->set_if_false(ParseStatement().Pass()); } if (has_error()) return scoped_ptr<ParseNode>();
diff --git a/tools/gn/parser_unittest.cc b/tools/gn/parser_unittest.cc index 823a98305..6216ee4 100644 --- a/tools/gn/parser_unittest.cc +++ b/tools/gn/parser_unittest.cc
@@ -363,25 +363,6 @@ DoParserPrintTest(input, expected); } -TEST(Parser, NestedBlocks) { - const char* input = "{cc_test(\"foo\") {{foo=1}\n{}}}"; - const char* expected = - "BLOCK\n" - " BLOCK\n" - " FUNCTION(cc_test)\n" - " LIST\n" - " LITERAL(\"foo\")\n" - " BLOCK\n" - " BLOCK\n" - " BINARY(=)\n" - " IDENTIFIER(foo)\n" - " LITERAL(1)\n" - " BLOCK\n"; - DoParserPrintTest(input, expected); - const char* input_with_newline = "{cc_test(\"foo\") {{foo=1}\n{}}}"; - DoParserPrintTest(input_with_newline, expected); -} - TEST(Parser, UnterminatedBlock) { DoParserErrorTest("stuff() {", 1, 9); } @@ -705,3 +686,18 @@ " foreach(bar, []) {}\n", 4, 3); } + +// Disallow standalone {} for introducing new scopes. These are ambiguous with +// target declarations (e.g. is: +// foo("bar") {} +// a function with an associated block, or a standalone function with a +// freestanding block. +TEST(Parser, StandaloneBlock) { + DoParserErrorTest( + "if (true) {\n" + "}\n" + "{\n" + " assert(false)\n" + "}\n", + 3, 1); +}
diff --git a/tools/json_schema_compiler/test/content_settings.json b/tools/json_schema_compiler/test/content_settings.json index 6fac436..f8778fa 100644 --- a/tools/json_schema_compiler/test/content_settings.json +++ b/tools/json_schema_compiler/test/content_settings.json
@@ -195,7 +195,7 @@ }, "plugins": { "$ref": "ContentSetting", - "description": "Whether to run plug-ins. One of<br><var>allow</var>: Run plug-ins automatically,<br><var>block</var>: Don't run plug-ins automatically. <br>Default is <var>allow</var>.<br>The primary URL is the main-frame URL. The secondary URL is not used.", + "description": "Whether to run plugins. One of<br><var>allow</var>: Run plugins automatically,<br><var>block</var>: Don't run plugins automatically. <br>Default is <var>allow</var>.<br>The primary URL is the main-frame URL. The secondary URL is not used.", "value": [ "plugins", {"type":"string", "enum": ["allow", "block"]}
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 443b3af..0cb8649f2 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -3035,6 +3035,14 @@ <summary>Event counts in ServiceProcessControl.</summary> </histogram> +<histogram name="CloudPrint.ServiceProcessSocketLength"> + <owner>vitalybuka@chromium.org</owner> + <summary> + Temporarily histogram with size of IPC sockets in default location. + TODO(vitalybuka) Remove after investigation http://crbug.com/466644 + </summary> +</histogram> + <histogram name="CloudPrint.ServiceUtilityCapsFailTime" units="ms"> <owner>vitalybuka@chromium.org</owner> <summary>
diff --git a/tools/perf/page_sets/top_25_smooth.py b/tools/perf/page_sets/top_25_smooth.py index 06bcb24..99edcbfa 100644 --- a/tools/perf/page_sets/top_25_smooth.py +++ b/tools/perf/page_sets/top_25_smooth.py
@@ -126,13 +126,13 @@ def RunPageInteractions(self, action_runner): interaction = action_runner.BeginGestureInteraction( - 'DragAction', is_smooth=True) + 'DragAction', is_smooth=True, repeatable=True) action_runner.DragPage(left_start_ratio=0.5, top_start_ratio=0.75, left_end_ratio=0.75, top_end_ratio=0.5) interaction.End() action_runner.Wait(2) interaction = action_runner.BeginGestureInteraction( - 'DragAction', is_smooth=True) + 'DragAction', is_smooth=True, repeatable=True) action_runner.DragPage(left_start_ratio=0.5, top_start_ratio=0.5, left_end_ratio=0.35, top_end_ratio=0.75) interaction.End()
diff --git a/tools/telemetry/telemetry/page/actions/action_runner.py b/tools/telemetry/telemetry/page/actions/action_runner.py index f4a9218..c29d1db 100644 --- a/tools/telemetry/telemetry/page/actions/action_runner.py +++ b/tools/telemetry/telemetry/page/actions/action_runner.py
@@ -34,8 +34,7 @@ action.WillRunAction(self._tab) action.RunAction(self._tab) - def BeginInteraction(self, label, is_smooth=False, is_responsive=False, - repeatable=False): + def BeginInteraction(self, label, is_smooth=False, repeatable=False): """Marks the beginning of an interaction record. An interaction record is a labeled time period containing @@ -48,8 +47,6 @@ label: A label for this particular interaction. This can be any user-defined string, but must not contain '/'. is_smooth: Whether to check for smoothness metrics for this interaction. - is_responsive: Whether to check for responsiveness metrics for - this interaction. repeatable: Whether other interactions may use the same logical name as this interaction. All interactions with the same logical name must have the same flags. @@ -57,8 +54,6 @@ flags = [] if is_smooth: flags.append(timeline_interaction_record.IS_SMOOTH) - if is_responsive: - flags.append(timeline_interaction_record.IS_RESPONSIVE) if repeatable: flags.append(timeline_interaction_record.REPEATABLE) @@ -66,8 +61,7 @@ interaction.Begin() return interaction - def BeginGestureInteraction(self, label, is_smooth=False, is_responsive=False, - repeatable=False): + def BeginGestureInteraction(self, label, is_smooth=False, repeatable=False): """Marks the beginning of a gesture-based interaction record. This is similar to normal interaction record, but it will @@ -82,14 +76,11 @@ label: A label for this particular interaction. This can be any user-defined string, but must not contain '/'. is_smooth: Whether to check for smoothness metrics for this interaction. - is_responsive: Whether to check for responsiveness metrics for - this interaction. repeatable: Whether other interactions may use the same logical name as this interaction. All interactions with the same logical name must have the same flags. """ - return self.BeginInteraction('Gesture_' + label, is_smooth, is_responsive, - repeatable) + return self.BeginInteraction('Gesture_' + label, is_smooth, repeatable) def NavigateToPage(self, page, timeout_in_seconds=60): """Navigates to the given page.
diff --git a/tools/telemetry/telemetry/page/actions/action_runner_unittest.py b/tools/telemetry/telemetry/page/actions/action_runner_unittest.py index d4e5355..d7f9e82c 100644 --- a/tools/telemetry/telemetry/page/actions/action_runner_unittest.py +++ b/tools/telemetry/telemetry/page/actions/action_runner_unittest.py
@@ -50,9 +50,8 @@ # Test disabled for android: crbug.com/437057 @decorators.Disabled('android', 'chromeos') def testIssuingMultipleMeasurementInteractionRecords(self): - self.VerifyIssuingInteractionRecords(is_responsive=True) self.VerifyIssuingInteractionRecords(is_smooth=True) - self.VerifyIssuingInteractionRecords(is_responsive=True, is_smooth=True) + self.VerifyIssuingInteractionRecords(is_smooth=True) class ActionRunnerTest(tab_test_case.TabTestCase):
diff --git a/tools/telemetry/telemetry/page/actions/drag_unittest.py b/tools/telemetry/telemetry/page/actions/drag_unittest.py index 0fabe60..b397c14 100644 --- a/tools/telemetry/telemetry/page/actions/drag_unittest.py +++ b/tools/telemetry/telemetry/page/actions/drag_unittest.py
@@ -1,10 +1,12 @@ # 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. +import logging import math import os from telemetry.page.actions import drag +from telemetry.page.actions import page_action from telemetry.unittest_util import tab_test_case @@ -28,7 +30,13 @@ i = drag.DragAction(left_start_ratio=0.5, top_start_ratio=0.5, left_end_ratio=0.25, top_end_ratio=0.25) - i.WillRunAction(self._tab) + try: + i.WillRunAction(self._tab) + except page_action.PageActionNotSupported: + logging.warning('This browser does not support drag gesture. Please try' + ' updating chrome.') + return + self._tab.ExecuteJavaScript(''' window.__dragAction.beginMeasuringHook = function() { window.__didBeginMeasuring = true;
diff --git a/tools/telemetry/telemetry/page/page_test.py b/tools/telemetry/telemetry/page/page_test.py index 59104860..8e297d14 100644 --- a/tools/telemetry/telemetry/page/page_test.py +++ b/tools/telemetry/telemetry/page/page_test.py
@@ -43,24 +43,17 @@ page, 'body_children', 'count', body_child_count)) Args: - action_name_to_run: This is the method name in telemetry.page.Page - subclasses to run. discard_first_run: Discard the first run of this page. This is usually used with page_repeat and pageset_repeat options. """ def __init__(self, - action_name_to_run='RunPageInteractions', needs_browser_restart_after_each_page=False, discard_first_result=False, clear_cache_before_each_run=False): super(PageTest, self).__init__() self.options = None - assert action_name_to_run == 'RunPageInteractions', ( - 'action_name_to_run can only be \'RunPageInteractions\', see ' - 'crbug.com/418375') - self._action_name_to_run = action_name_to_run self._needs_browser_restart_after_each_page = ( needs_browser_restart_after_each_page) self._discard_first_result = discard_first_result @@ -221,16 +214,10 @@ if interactive: action_runner.PauseInteractive() else: - self._RunMethod(page, self._action_name_to_run, action_runner) + page.RunPageInteractions(action_runner) self.DidRunActions(page, tab) - self.ValidateAndMeasurePage(page, tab, results) - def _RunMethod(self, page, method_name, action_runner): - if hasattr(page, method_name): - run_method = getattr(page, method_name) - run_method(action_runner) - def RunNavigateSteps(self, page, tab): """Navigates the tab to the page URL attribute. @@ -239,7 +226,3 @@ action_runner = action_runner_module.ActionRunner( tab, skip_waits=page.skip_waits) page.RunNavigateSteps(action_runner) - - @property - def action_name_to_run(self): - return self._action_name_to_run
diff --git a/tools/telemetry/telemetry/page/record_wpr.py b/tools/telemetry/telemetry/page/record_wpr.py index 12f4420..39b9074 100644 --- a/tools/telemetry/telemetry/page/record_wpr.py +++ b/tools/telemetry/telemetry/page/record_wpr.py
@@ -16,11 +16,6 @@ from telemetry.results import results_options from telemetry.user_story import user_story_runner -_ACTION_NAMES = [ - 'RunPageInteractions', - 'RunNavigateSteps', -] - class RecorderPageTest(page_test.PageTest): # pylint: disable=W0223 def __init__(self): super(RecorderPageTest, self).__init__() @@ -65,22 +60,10 @@ util.WaitFor(tab.HasReachedQuiescence, 30) if self.page_test: - self._action_name_to_run = self.page_test.action_name_to_run self.page_test.RunPage(page, tab, results) return - should_reload = False - # Run the actions on the page for all available measurements. - for action_name in _ACTION_NAMES: - # Skip this action if it is not defined - if not hasattr(page, action_name): - continue - # Reload the page between actions to start with a clean slate. - if should_reload: - self.RunNavigateSteps(page, tab) - self._action_name_to_run = action_name - super(RecorderPageTest, self).RunPage(page, tab, results) - should_reload = True + super(RecorderPageTest, self).RunPage(page, tab, results) def RunNavigateSteps(self, page, tab): if self.page_test:
diff --git a/tools/telemetry/telemetry/page/record_wpr_unittest.py b/tools/telemetry/telemetry/page/record_wpr_unittest.py index fcafadb2..cd38aeea 100644 --- a/tools/telemetry/telemetry/page/record_wpr_unittest.py +++ b/tools/telemetry/telemetry/page/record_wpr_unittest.py
@@ -99,9 +99,12 @@ def testRunPage_AllActions(self): record_page_test = record_wpr.RecorderPageTest() page = MockPage(page_set=MockPageSet(url=self._url), url=self._url) + + record_page_test.RunNavigateSteps(page, self._tab) + self.assertTrue('RunNavigateSteps' in page.func_calls) + record_page_test.RunPage(page, self._tab, results=None) self.assertTrue('RunPageInteractions' in page.func_calls) - self.assertTrue('RunNavigateSteps' in page.func_calls) # When the RecorderPageTest is created from a Benchmark, the benchmark will # have a PageTest, specified by its test attribute.
diff --git a/tools/telemetry/telemetry/web_perf/metrics/mainthread_jank_stats_unittest.py b/tools/telemetry/telemetry/web_perf/metrics/mainthread_jank_stats_unittest.py index 6ba6176..0c1bca3 100644 --- a/tools/telemetry/telemetry/web_perf/metrics/mainthread_jank_stats_unittest.py +++ b/tools/telemetry/telemetry/web_perf/metrics/mainthread_jank_stats_unittest.py
@@ -15,7 +15,7 @@ def CreateTestRecord(self, name, start, end, thread_start, thread_end, parent_thread): s = async_slice.AsyncSlice( - 'cat', 'Interaction.%s/is_responsive' % name, + 'cat', 'Interaction.%s' % name, timestamp=start, duration=end - start, start_thread=parent_thread, end_thread=parent_thread, thread_start=thread_start, thread_duration=thread_end - thread_start)
diff --git a/tools/telemetry/telemetry/web_perf/timeline_based_measurement_unittest.py b/tools/telemetry/telemetry/web_perf/timeline_based_measurement_unittest.py index fe7971b..043bdd1 100644 --- a/tools/telemetry/telemetry/web_perf/timeline_based_measurement_unittest.py +++ b/tools/telemetry/telemetry/web_perf/timeline_based_measurement_unittest.py
@@ -116,7 +116,7 @@ d.AddInteraction(d.renderer_thread, ts=0, duration=20, marker='Interaction.LogicalName1/is_smooth') d.AddInteraction(d.renderer_thread, ts=25, duration=5, - marker='Interaction.LogicalName2/is_responsive') + marker='Interaction.LogicalName2/') d.AddInteraction(d.foo_thread, ts=50, duration=15, marker='Interaction.LogicalName3/is_smooth') d.FinalizeImport() @@ -131,7 +131,6 @@ self.assertEquals(0, interactions[0].start) self.assertEquals(20, interactions[0].end) - self.assertTrue(interactions[1].is_responsive) self.assertEquals(25, interactions[1].start) self.assertEquals(30, interactions[1].end) @@ -148,7 +147,7 @@ d.AddInteraction(d.renderer_thread, ts=0, duration=20, marker='Interaction.LogicalName1/is_smooth') d.AddInteraction(d.foo_thread, ts=25, duration=5, - marker='Interaction.LogicalName2/is_responsive') + marker='Interaction.LogicalName2') d.FinalizeImport() d.AddResults() self.assertEquals(1, len(d.results.FindAllPageSpecificValuesNamed( @@ -195,7 +194,7 @@ def testDuplicateRepeatableInteractionsWithDifferentMetrics(self): d = TimelineBasedMetricTestData() - responsive_marker = 'Interaction.LogicalName/is_responsive,repeatable' + responsive_marker = 'Interaction.LogicalName/repeatable' d.AddInteraction( d.renderer_thread, ts=10, duration=5, marker=responsive_marker) smooth_marker = 'Interaction.LogicalName/is_smooth,repeatable'
diff --git a/tools/telemetry/telemetry/web_perf/timeline_interaction_record.py b/tools/telemetry/telemetry/web_perf/timeline_interaction_record.py index 8b43909..947e74f4 100644 --- a/tools/telemetry/telemetry/web_perf/timeline_interaction_record.py +++ b/tools/telemetry/telemetry/web_perf/timeline_interaction_record.py
@@ -7,15 +7,12 @@ import telemetry.timeline.bounds as timeline_bounds from telemetry import decorators -# Enables the responsiveness metric for this interaction -IS_RESPONSIVE = 'is_responsive' # Enables the smoothness metric for this interaction IS_SMOOTH = 'is_smooth' # Allows multiple duplicate interactions of the same type REPEATABLE = 'repeatable' METRICS = [ - IS_RESPONSIVE, IS_SMOOTH ] FLAGS = METRICS + [REPEATABLE] @@ -85,7 +82,7 @@ is currently done by pushing markers into the console.time/timeEnd API: this for instance can be issued in JS: - var str = 'Interaction.SendEmail/is_smooth,is_responsive'; + var str = 'Interaction.SendEmail/is_smooth'; console.time(str); setTimeout(function() { console.timeEnd(str); @@ -97,7 +94,6 @@ time-range. The valid interaction flags are: - * is_responsive: Enables the responsiveness metric * is_smooth: Enables the smoothness metric * repeatable: Allows other interactions to use the same label """ @@ -124,10 +120,6 @@ return self._end @property - def is_responsive(self): - return IS_RESPONSIVE in self._flags - - @property def is_smooth(self): return IS_SMOOTH in self._flags
diff --git a/tools/telemetry/telemetry/web_perf/timeline_interaction_record_unittest.py b/tools/telemetry/telemetry/web_perf/timeline_interaction_record_unittest.py index eb82c83..563af15 100644 --- a/tools/telemetry/telemetry/web_perf/timeline_interaction_record_unittest.py +++ b/tools/telemetry/telemetry/web_perf/timeline_interaction_record_unittest.py
@@ -40,32 +40,28 @@ r = self.CreateSimpleRecordWithName('Interaction.LogicalName') self.assertEquals('LogicalName', r.label) self.assertEquals(False, r.is_smooth) - self.assertEquals(False, r.is_responsive) r = self.CreateSimpleRecordWithName('Interaction.LogicalName/is_smooth') self.assertEquals('LogicalName', r.label) self.assertEquals(True, r.is_smooth) - self.assertEquals(False, r.is_responsive) r = self.CreateSimpleRecordWithName( 'Interaction.LogicalNameWith/Slash/is_smooth') self.assertEquals('LogicalNameWith/Slash', r.label) self.assertEquals(True, r.is_smooth) - self.assertEquals(False, r.is_responsive) r = self.CreateSimpleRecordWithName( - 'Interaction.LogicalNameWith/Slash/is_smooth,is_responsive') + 'Interaction.LogicalNameWith/Slash/is_smooth') self.assertEquals('LogicalNameWith/Slash', r.label) self.assertEquals(True, r.is_smooth) - self.assertEquals(True, r.is_responsive) def testGetJavaScriptMarker(self): smooth_marker = tir_module.GetJavaScriptMarker( 'MyLabel', [tir_module.IS_SMOOTH]) self.assertEquals('Interaction.MyLabel/is_smooth', smooth_marker) slr_marker = tir_module.GetJavaScriptMarker( - 'MyLabel', [tir_module.IS_SMOOTH, tir_module.IS_RESPONSIVE]) - self.assertEquals('Interaction.MyLabel/is_smooth,is_responsive', slr_marker) + 'MyLabel', [tir_module.IS_SMOOTH]) + self.assertEquals('Interaction.MyLabel/is_smooth', slr_marker) def testGetOverlappedThreadTimeForSliceInSameThread(self): # Create a renderer thread.
diff --git a/tools/telemetry/unittest_data/interaction_enabled_page.html b/tools/telemetry/unittest_data/interaction_enabled_page.html index bdce85a..59af4e5f 100644 --- a/tools/telemetry/unittest_data/interaction_enabled_page.html +++ b/tools/telemetry/unittest_data/interaction_enabled_page.html
@@ -61,15 +61,15 @@ } } function makeJank() { - console.time('Interaction.JankThreadJSRun/is_responsive'); + console.time('Interaction.JankThreadJSRun'); waitMs(jankMs); - console.timeEnd('Interaction.JankThreadJSRun/is_responsive'); + console.timeEnd('Interaction.JankThreadJSRun'); window.jankScriptDone = true; } function makeSlow() { - console.time('Interaction.SlowThreadJsRun/is_fast'); + console.time('Interaction.SlowThreadJsRun'); waitMs(slowMs); - console.timeEnd('Interaction.SlowThreadJsRun/is_fast'); + console.timeEnd('Interaction.SlowThreadJsRun'); window.slowScriptDone = true; } </script>
diff --git a/tools/valgrind/gtest_exclude/browser_tests.gtest-drmemory_win32.txt b/tools/valgrind/gtest_exclude/browser_tests.gtest-drmemory_win32.txt index 31474ef..f5dcbb0d 100644 --- a/tools/valgrind/gtest_exclude/browser_tests.gtest-drmemory_win32.txt +++ b/tools/valgrind/gtest_exclude/browser_tests.gtest-drmemory_win32.txt
@@ -9,6 +9,9 @@ # http://crbug.com/450221 ProfileChooserViewExtensionsTest.LockProfileNoBlockOtherProfileExtensions +# http://crbug.com/467514 +AsyncExtensionSettingsWebUITest.testErrorListButtonVisibility + # it takes too long to run all browser_tests with Dr.Memory, # and we only select subset to run # A*
diff --git a/tools/valgrind/gtest_exclude/cc_unittests.gtest-drmemory_win32.txt b/tools/valgrind/gtest_exclude/cc_unittests.gtest-drmemory_win32.txt index e7f3488..5a76d89e 100644 --- a/tools/valgrind/gtest_exclude/cc_unittests.gtest-drmemory_win32.txt +++ b/tools/valgrind/gtest_exclude/cc_unittests.gtest-drmemory_win32.txt
@@ -12,20 +12,7 @@ LayerTreeHostCopyRequestTestMultipleRequests.SoftwareRenderer_RunSingleThread # http://crbug.com/430400 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfLayer/5 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfLayer/6 -PixelResourceTest/LayerTreeHostMasksPixelTest.ImageMaskOfLayer/5 -PixelResourceTest/LayerTreeHostMasksPixelTest.ImageMaskOfLayer/6 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfClippedLayer/5 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfClippedLayer/6 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskWithReplica/5 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskWithReplica/6 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskWithReplicaOfClippedLayer/5 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskWithReplicaOfClippedLayer/6 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfReplica/5 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfReplica/6 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfReplicaOfClippedLayer/5 -PixelResourceTest/LayerTreeHostMasksPixelTest.MaskOfReplicaOfClippedLayer/6 +PixelResourceTest* # https://crbug.com/460581 LayerTreeHostPictureTestRSLLMembershipWithScale.RunMultiThread_DirectRenderer_ImplSidePaint
diff --git a/ui/app_list/test/run_all_unittests.cc b/ui/app_list/test/run_all_unittests.cc index b60b4385..5da865b 100644 --- a/ui/app_list/test/run_all_unittests.cc +++ b/ui/app_list/test/run_all_unittests.cc
@@ -7,6 +7,7 @@ #include "base/compiler_specific.h" #include "base/path_service.h" #include "base/test/launcher/unit_test_launcher.h" +#include "base/test/test_discardable_memory_shmem_allocator.h" #include "base/test/test_suite.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/resource/resource_bundle.h" @@ -40,6 +41,9 @@ base::FilePath ui_test_pak_path; ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); + + base::DiscardableMemoryShmemAllocator::SetInstance( + &discardable_memory_allocator_); } void Shutdown() override { @@ -48,6 +52,8 @@ } private: + base::TestDiscardableMemoryShmemAllocator discardable_memory_allocator_; + DISALLOW_COPY_AND_ASSIGN(AppListTestSuite); };
diff --git a/ui/message_center/test/run_all_unittests.cc b/ui/message_center/test/run_all_unittests.cc index fa53d674..b0cc026 100644 --- a/ui/message_center/test/run_all_unittests.cc +++ b/ui/message_center/test/run_all_unittests.cc
@@ -7,6 +7,7 @@ #include "base/compiler_specific.h" #include "base/path_service.h" #include "base/test/launcher/unit_test_launcher.h" +#include "base/test/test_discardable_memory_shmem_allocator.h" #include "base/test/test_suite.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/resource/resource_bundle.h" @@ -37,6 +38,9 @@ base::FilePath ui_test_pak_path; ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); + + base::DiscardableMemoryShmemAllocator::SetInstance( + &discardable_memory_allocator_); } void Shutdown() override { @@ -45,6 +49,8 @@ } private: + base::TestDiscardableMemoryShmemAllocator discardable_memory_allocator_; + DISALLOW_COPY_AND_ASSIGN(MessageCenterTestSuite); };
diff --git a/ui/ozone/platform/drm/gpu/drm_device.cc b/ui/ozone/platform/drm/gpu/drm_device.cc index 5f870956..03ca9aa 100644 --- a/ui/ozone/platform/drm/gpu/drm_device.cc +++ b/ui/ozone/platform/drm/gpu/drm_device.cc
@@ -114,6 +114,7 @@ base::WaitableEvent done(false, false); io_task_runner_->PostTask( FROM_HERE, base::Bind(&IOWatcher::SetPausedOnIO, this, &done)); + done.Wait(); } void Shutdown() { @@ -125,7 +126,7 @@ private: friend class base::RefCountedThreadSafe<IOWatcher>; - ~IOWatcher() override { SetPaused(true); } + ~IOWatcher() override {} void RegisterOnIO() { DCHECK(base::MessageLoopForIO::IsCurrent());
diff --git a/ui/webui/resources/js/cr/ui/focus_grid.js b/ui/webui/resources/js/cr/ui/focus_grid.js index 307f5a1..5269a5cf 100644 --- a/ui/webui/resources/js/cr/ui/focus_grid.js +++ b/ui/webui/resources/js/cr/ui/focus_grid.js
@@ -64,7 +64,7 @@ // Only the clicked row should be active. var target = assertInstanceof(e.target, Node); this.focusGrid_.rows.forEach(function(row) { - row.makeRowActive(row.contains(target)); + row.makeActive(row.contains(target)); }); return true; @@ -149,15 +149,12 @@ if (this.rows.length == 0) { // The first row should be active if no other row is focused. - row.makeRowActive(true); + row.makeActive(true); } else if (row.contains(document.activeElement)) { // The current row should be made active if it's the activeElement. - row.makeRowActive(true); + row.makeActive(true); // Deactivate the first row. - this.rows[0].makeRowActive(false); - } else { - // All other rows should be inactive. - row.makeRowActive(false); + this.rows[0].makeActive(false); } // Add the row after its initial focus is set.
diff --git a/ui/webui/resources/js/cr/ui/focus_row.js b/ui/webui/resources/js/cr/ui/focus_row.js index f5f0665..a50e62a5 100644 --- a/ui/webui/resources/js/cr/ui/focus_row.js +++ b/ui/webui/resources/js/cr/ui/focus_row.js
@@ -54,6 +54,9 @@ onMousedown: assertNotReached, }; + /** @const {string} */ + FocusRow.ACTIVE_CLASS = 'focus-row-active'; + FocusRow.prototype = { __proto__: HTMLDivElement.prototype, @@ -105,6 +108,8 @@ assert(this.focusableElements.indexOf(element) == -1); assert(this.contains(element)); + element.tabIndex = this.isActive() ? 0 : -1; + this.focusableElements.push(element); this.eventTracker_.add(element, 'mousedown', this.onMousedown_.bind(this)); @@ -118,12 +123,12 @@ * @private */ onFocusChange_: function(element) { - var isActive = this.contains(element); - var wasActive = this.classList.contains('focus-row-active'); + this.makeActive(this.contains(element)); + }, - // Only send events if the active state is different for the row. - if (isActive != wasActive) - this.makeRowActive(isActive); + /** @return {boolean} Whether this row is currently active. */ + isActive: function() { + return this.classList.contains(FocusRow.ACTIVE_CLASS); }, /** @@ -131,17 +136,21 @@ * tabIndex can be set properly. * @param {boolean} active True if tab is allowed for this row. */ - makeRowActive: function(active) { + makeActive: function(active) { + if (active == this.isActive()) + return; + this.focusableElements.forEach(function(element) { element.tabIndex = active ? 0 : -1; }); - this.classList.toggle('focus-row-active', active); + this.classList.toggle(FocusRow.ACTIVE_CLASS, active); this.onActiveStateChanged(active); }, - /** Call this to clean up event handling before dereferencing. */ + /** Dereferences nodes and removes event handlers. */ destroy: function() { + this.focusableElements.length = 0; this.eventTracker_.removeAll(); },