diff --git a/DEPS b/DEPS index 73bbc08..754942c 100644 --- a/DEPS +++ b/DEPS
@@ -222,11 +222,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '230a2514d6998866afacb5f3aa796e28447ed25c', + 'skia_revision': '8f553a769b2b618daeb8d74549ba3996160fd32d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'v8_revision': '10df900d12a671fb7a17514c0b62203df2ebaf2b', + 'v8_revision': 'a04426ffa7abb089a29295e6d863675892f65ca6', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling swarming_client # and whatever else without interference from each other. @@ -234,11 +234,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '5fb3a549f6a976c03cf7f94a7114d06d8e2c35d9', + 'angle_revision': '4ee176abe10ddbe936962b6ef5d12c043aaca39a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': 'ba18c78e46968726769813b68adb19466e092812', + 'swiftshader_revision': 'c6747d98397de4b906935a00ef3549ef58218380', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -301,7 +301,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '947b4d23d6bbfb5521c1cb49d1788059531aa2a8', + 'devtools_frontend_revision': '85d053b74c227a734d4f9a554eb2bcea2ea8753e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -651,7 +651,7 @@ 'packages': [ { 'package': 'chromium/rts/model/linux-amd64', - 'version': 'fvEId-G6mcDn7wqWAKltvTLPp9m345D92nqbGxE3iDwC', + 'version': 'uYn940FBk_ICotJoTOu1E1AteY-XUIF8XcFnT5dmWMkC', }, ], 'dep_type': 'cipd', @@ -662,7 +662,7 @@ 'packages': [ { 'package': 'chromium/rts/model/mac-amd64', - 'version': 'uXbvNaog6n1tFOFTYV-A2QtP-_Oy9k99tJ_8G7iVQp4C', + 'version': 'qWsm2aW_77qIRj_oOPKdUX0ule-VVZqY45g-K64y408C', }, ], 'dep_type': 'cipd', @@ -673,7 +673,7 @@ 'packages': [ { 'package': 'chromium/rts/model/windows-amd64', - 'version': 'pxX1ohs47yFigowe6qlllfxaohogMowiTw8xWLc86o0C', + 'version': 'uuHcKSIrpBg-xESipDyzMpTv8BF0j9HXwOJtIAPZOoYC', }, ], 'dep_type': 'cipd', @@ -738,7 +738,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'S6dCY92KZR4uySXoIPzDOReE8nJYQNPXboKDPsSdhpYC', + 'version': 'zlAhnfTSwBjk1AdlgJt15ddN7j2UFayDE0Jj_xHCigAC', }, ], 'condition': 'checkout_android', @@ -954,7 +954,7 @@ # Tools used when building Chrome for Chrome OS. This affects both the Simple # Chrome workflow, as well as the chromeos-chrome ebuild. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '6f3adc6df4848f7a1dae25117c647721d80a7356', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '3a7b7a26d93e82da511142a1284c6488ffa9babe', 'condition': 'checkout_chromeos', }, @@ -1360,7 +1360,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'b72f3ccca5e6ec7e47a05a947156e6378d08b2a7', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'cb9aee60bd100feb1079c736444a3b72c410730d', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1592,7 +1592,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + 'b5cc3b2500c0ba9e8a1381b357e1a6c341c9f297', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '261af57d751d38be5cf234e4c146f8849d37e621', + Var('webrtc_git') + '/src.git' + '@' + '4e0d46fde4adfcd4e922e2b38fb10bf5b3feaeaf', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1672,7 +1672,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/help_app/app', - 'version': '88X_UqDzg-7WMt33tTdiVcgQFI0vX4BQG6ykPp1XSfkC', + 'version': 'vNRb2vKdknUwfwzzhwzJo4sSETdJYnu_Wy_F91-fOSAC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal', @@ -1683,7 +1683,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/media_app/app', - 'version': 'jzPmlIFX_8ujI4LD-boxkoDuNOMBHQSXv0CK-7wQ9eEC', + 'version': 'WKUUwJJeT2Bz7DjwRD1mT4PNedG8Cr89EQRvQBrSlnMC', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/RendererProcessMetricsProviderTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/RendererProcessMetricsProviderTest.java index e3f7dd72..568922c 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/RendererProcessMetricsProviderTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/RendererProcessMetricsProviderTest.java
@@ -7,7 +7,7 @@ import static org.chromium.android_webview.test.OnlyRunIn.ProcessMode.MULTI_PROCESS; import static org.chromium.android_webview.test.OnlyRunIn.ProcessMode.SINGLE_PROCESS; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 755107525..1baf1648 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -457,8 +457,8 @@ "hud_display/ash_tracing_request.h", "hud_display/cpu_graph_page_view.cc", "hud_display/cpu_graph_page_view.h", - "hud_display/cpu_status.cc", - "hud_display/cpu_status.h", + "hud_display/cpu_stats.cc", + "hud_display/cpu_stats.h", "hud_display/data_source.cc", "hud_display/data_source.h", "hud_display/fps_graph_page_view.cc",
diff --git a/ash/accessibility/ui/accessibility_layer.cc b/ash/accessibility/ui/accessibility_layer.cc index 64a6406..dd4e10d3 100644 --- a/ash/accessibility/ui/accessibility_layer.cc +++ b/ash/accessibility/ui/accessibility_layer.cc
@@ -101,14 +101,16 @@ } void AccessibilityLayer::OnAnimationStep(base::TimeTicks timestamp) { - if (!delegate_->OnAnimationStep(timestamp) || - !animation_observation_.IsObserving()) { - return; + // Require the |delegate_| get forwarded the call after the first such + // callback from the compositor. This avoids a crash within tests under low + // resource situations. + if (got_first_animation_step_ && delegate_->OnAnimationStep(timestamp)) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&AccessibilityLayer::Reset, weak_factory_.GetWeakPtr())); } - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::BindOnce(&AccessibilityLayer::Reset, weak_factory_.GetWeakPtr())); + got_first_animation_step_ = true; } void AccessibilityLayer::OnCompositingShuttingDown(ui::Compositor* compositor) { @@ -118,6 +120,7 @@ void AccessibilityLayer::Reset() { animation_observation_.Reset(); + got_first_animation_step_ = false; } } // namespace ash
diff --git a/ash/accessibility/ui/accessibility_layer.h b/ash/accessibility/ui/accessibility_layer.h index 936457c..f717f97 100644 --- a/ash/accessibility/ui/accessibility_layer.h +++ b/ash/accessibility/ui/accessibility_layer.h
@@ -114,6 +114,8 @@ &ui::Compositor::RemoveAnimationObserver> animation_observation_{this}; + bool got_first_animation_step_ = false; + base::WeakPtrFactory<AccessibilityLayer> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(AccessibilityLayer);
diff --git a/ash/hud_display/cpu_status.cc b/ash/hud_display/cpu_stats.cc similarity index 97% rename from ash/hud_display/cpu_status.cc rename to ash/hud_display/cpu_stats.cc index f8c41c6..a69aebbd 100644 --- a/ash/hud_display/cpu_status.cc +++ b/ash/hud_display/cpu_stats.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 "ash/hud_display/cpu_status.h" +#include "ash/hud_display/cpu_stats.h" #include <cinttypes> #include <cstdio>
diff --git a/ash/hud_display/cpu_status.h b/ash/hud_display/cpu_stats.h similarity index 93% rename from ash/hud_display/cpu_status.h rename to ash/hud_display/cpu_stats.h index adc1f6f..471a1cf 100644 --- a/ash/hud_display/cpu_status.h +++ b/ash/hud_display/cpu_stats.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 ASH_HUD_DISPLAY_CPU_STATUS_H_ -#define ASH_HUD_DISPLAY_CPU_STATUS_H_ +#ifndef ASH_HUD_DISPLAY_CPU_STATS_H_ +#define ASH_HUD_DISPLAY_CPU_STATS_H_ #include <cstdint> @@ -41,4 +41,4 @@ } // namespace hud_display } // namespace ash -#endif // ASH_HUD_DISPLAY_CPU_STATUS_H_ +#endif // ASH_HUD_DISPLAY_CPU_STATS_H_
diff --git a/ash/hud_display/data_source.h b/ash/hud_display/data_source.h index 7eec37be..b1908059c 100644 --- a/ash/hud_display/data_source.h +++ b/ash/hud_display/data_source.h
@@ -7,7 +7,7 @@ #include <cstdint> #include <limits> -#include "ash/hud_display/cpu_status.h" +#include "ash/hud_display/cpu_stats.h" namespace ash { namespace hud_display {
diff --git a/ash/login/ui/access_code_input.cc b/ash/login/ui/access_code_input.cc index d4303d9..797ca03 100644 --- a/ash/login/ui/access_code_input.cc +++ b/ash/login/ui/access_code_input.cc
@@ -227,7 +227,7 @@ // Ignores the a11y focus of |field| because the a11y needs to focus to the // FixedLengthCodeInput object. - field->GetViewAccessibility().OverrideIsIgnored(true); + field->GetViewAccessibility().set_propagate_focus_to_ancestor(true); input_fields_.push_back(field); AddChildView(field); layout->SetFlexForView(field, 1);
diff --git a/ash/public/cpp/wallpaper/wallpaper_controller.h b/ash/public/cpp/wallpaper/wallpaper_controller.h index 1aaa941..49684c6 100644 --- a/ash/public/cpp/wallpaper/wallpaper_controller.h +++ b/ash/public/cpp/wallpaper/wallpaper_controller.h
@@ -13,6 +13,7 @@ #include "ash/public/cpp/wallpaper/online_wallpaper_params.h" #include "ash/public/cpp/wallpaper/wallpaper_info.h" #include "ash/public/cpp/wallpaper/wallpaper_types.h" +#include "base/callback_helpers.h" #include "base/files/file_path.h" #include "base/time/time.h" @@ -289,6 +290,15 @@ virtual void SetDailyRefreshCollectionId( const std::string& collection_id) = 0; + // Get the daily refresh collection id. Empty if daily refresh is not enabled; + virtual std::string GetDailyRefreshCollectionId() const = 0; + + // With daily refresh enabled, this updates the wallpaper by asking for a + // wallpaper from within the user specified collection. + using RefreshWallpaperCallback = base::OnceCallback<void(bool success)>; + virtual void UpdateDailyRefreshWallpaper( + RefreshWallpaperCallback callback = base::DoNothing()) = 0; + // DriveFS is available for the active user. virtual void OnGoogleDriveMounted() = 0;
diff --git a/ash/wallpaper/wallpaper_controller_impl.cc b/ash/wallpaper/wallpaper_controller_impl.cc index a884e04..15f8823 100644 --- a/ash/wallpaper/wallpaper_controller_impl.cc +++ b/ash/wallpaper/wallpaper_controller_impl.cc
@@ -2459,6 +2459,10 @@ pref_service->SetString(kWallpaperCollectionId, collection_id); } +std::string WallpaperControllerImpl::GetDailyRefreshCollectionId() const { + return GetCollectionId(); +} + void WallpaperControllerImpl::OnGoogleDriveMounted() { AccountId account_id = GetActiveAccountId(); WallpaperInfo local_info; @@ -2488,9 +2492,11 @@ return pref_service->GetString(kWallpaperCollectionId); } -void WallpaperControllerImpl::UpdateDailyRefreshWallpaper() { +void WallpaperControllerImpl::UpdateDailyRefreshWallpaper( + RefreshWallpaperCallback callback) { if (!IsDailyRefreshEnabled()) { daily_refresh_timer_.Stop(); + std::move(callback).Run(false); return; } @@ -2502,29 +2508,36 @@ base::BindOnce(&WallpaperControllerImpl::SetDailyWallpaper, weak_factory_.GetWeakPtr(), GetActiveAccountId(), ash::WallpaperLayout::WALLPAPER_LAYOUT_CENTER_CROPPED, - /*preview_mode=*/false)); + /*preview_mode=*/false, std::move(callback))); } else { StartDailyRefreshTimer(); + std::move(callback).Run(false); } } -void WallpaperControllerImpl::SetDailyWallpaper(const AccountId& account_id, - WallpaperLayout layout, - bool preview_mode, - const std::string& image_url) { +void WallpaperControllerImpl::SetDailyWallpaper( + const AccountId& account_id, + WallpaperLayout layout, + bool preview_mode, + RefreshWallpaperCallback callback, + const std::string& image_url) { if (!image_url.empty()) { SetOnlineWallpaper( OnlineWallpaperParams{ account_id, /*asset_id=*/absl::nullopt, GURL(image_url), /*collection_id=*/std::string(), layout, preview_mode}, base::BindOnce(&WallpaperControllerImpl::OnSetDailyWallpaper, - weak_factory_.GetWeakPtr())); + weak_factory_.GetWeakPtr(), std::move(callback))); } else { OnFetchDailyWallpaperFailed(); + std::move(callback).Run(false); } } -void WallpaperControllerImpl::OnSetDailyWallpaper(bool success) { +void WallpaperControllerImpl::OnSetDailyWallpaper( + RefreshWallpaperCallback callback, + bool success) { + std::move(callback).Run(success); if (success) { StartDailyRefreshTimer(); } else { @@ -2557,7 +2570,8 @@ daily_refresh_timer_.Start( FROM_HERE, desired_run_time, base::BindOnce(&WallpaperControllerImpl::UpdateDailyRefreshWallpaper, - weak_factory_.GetWeakPtr())); + weak_factory_.GetWeakPtr(), + base::DoNothing::Once<bool>())); } base::TimeDelta WallpaperControllerImpl::GetTimeToNextDailyRefreshUpdate()
diff --git a/ash/wallpaper/wallpaper_controller_impl.h b/ash/wallpaper/wallpaper_controller_impl.h index a70c020e..b5e7535 100644 --- a/ash/wallpaper/wallpaper_controller_impl.h +++ b/ash/wallpaper/wallpaper_controller_impl.h
@@ -24,6 +24,7 @@ #include "ash/wallpaper/wallpaper_utils/wallpaper_decoder.h" #include "ash/wallpaper/wallpaper_utils/wallpaper_resizer_observer.h" #include "ash/wm/overview/overview_observer.h" +#include "base/callback_helpers.h" #include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/observer_list.h" @@ -297,6 +298,9 @@ WallpaperInfo GetActiveUserWallpaperInfo() override; bool ShouldShowWallpaperSetting() override; void SetDailyRefreshCollectionId(const std::string& collection_id) override; + std::string GetDailyRefreshCollectionId() const override; + void UpdateDailyRefreshWallpaper( + RefreshWallpaperCallback callback = base::DoNothing()) override; void OnGoogleDriveMounted() override; // WindowTreeHostManager::Observer: @@ -584,21 +588,18 @@ // enabled. Is an empty string when it is not enabled. std::string GetCollectionId() const; - // With daily refresh enabled, this updates the wallpaper by asking for a - // wallpaper from within the user specified collection. - void UpdateDailyRefreshWallpaper(); - // Callback from the client providing a url to a wallpaper from the user // specified collection when daily refresh is enabled. If |image_url| is // empty, fetching the url failed, and should be tried again soon. void SetDailyWallpaper(const AccountId& account_id, WallpaperLayout layout, bool preview_mode, + RefreshWallpaperCallback callback, const std::string& image_url); // Called after attempting to download and set a daily refresh wallpaper. // On failure retry again in a while. - void OnSetDailyWallpaper(bool success); + void OnSetDailyWallpaper(RefreshWallpaperCallback callback, bool success); // Starts a wall clock timer, to update the wallpaper 24 hours since the last // wallpaper was set.
diff --git a/base/allocator/partition_allocator/partition_address_space.cc b/base/allocator/partition_allocator/partition_address_space.cc index e7de7d2..29a7c3f 100644 --- a/base/allocator/partition_allocator/partition_address_space.cc +++ b/base/allocator/partition_allocator/partition_address_space.cc
@@ -80,7 +80,6 @@ PA_CHECK(requested_address == actual_address) << "QuarantineCardTable is required to be allocated in the beginning of " "the BRPPool"; - SetSystemPagesAccess(actual_address, kSuperPageSize, PageInaccessible); #endif // defined(PA_ALLOW_PCSCAN) PA_DCHECK(reserved_base_address_ + properties.size == current);
diff --git a/base/allocator/partition_allocator/partition_alloc.cc b/base/allocator/partition_allocator/partition_alloc.cc index 637b60b..f079ae7 100644 --- a/base/allocator/partition_allocator/partition_alloc.cc +++ b/base/allocator/partition_allocator/partition_alloc.cc
@@ -21,6 +21,7 @@ #include "base/allocator/partition_allocator/partition_root.h" #include "base/allocator/partition_allocator/partition_stats.h" #include "base/allocator/partition_allocator/starscan/pcscan.h" +#include "base/dcheck_is_on.h" namespace base { @@ -104,13 +105,14 @@ template void PartitionAllocator<internal::NotThreadSafe>::init( PartitionOptions); -#if DCHECK_IS_ON() && BUILDFLAG(USE_BACKUP_REF_PTR) -void DCheckGetSlotOffsetIsZero(void* ptr) { +#if (DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS)) && \ + BUILDFLAG(USE_BACKUP_REF_PTR) +void CheckThatSlotOffsetIsZero(void* ptr) { // Add kPartitionPastAllocationAdjustment, because PartitionAllocGetSlotStart // will subtract it. - PA_DCHECK(PartitionAllocGetSlotStart(reinterpret_cast<char*>(ptr) + - kPartitionPastAllocationAdjustment) == - ptr); + PA_CHECK(PartitionAllocGetSlotStart(reinterpret_cast<char*>(ptr) + + kPartitionPastAllocationAdjustment) == + ptr); } #endif
diff --git a/base/allocator/partition_allocator/partition_alloc_forward.h b/base/allocator/partition_allocator/partition_alloc_forward.h index 30e3fa5d..9175e6e 100644 --- a/base/allocator/partition_allocator/partition_alloc_forward.h +++ b/base/allocator/partition_allocator/partition_alloc_forward.h
@@ -19,13 +19,11 @@ constexpr bool ThreadSafe = true; constexpr bool NotThreadSafe = false; -#if BUILDFLAG(USE_BACKUP_REF_PTR) -#if DCHECK_IS_ON() -BASE_EXPORT void DCheckGetSlotOffsetIsZero(void*); -#else -ALWAYS_INLINE void DCheckGetSlotOffsetIsZero(void*) {} +#if (DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS)) && \ + BUILDFLAG(USE_BACKUP_REF_PTR) +BASE_EXPORT void CheckThatSlotOffsetIsZero(void*); #endif -#endif // BUILDFLAG(USE_BACKUP_REF_PTR) + } // namespace internal template <bool thread_safe>
diff --git a/base/allocator/partition_allocator/partition_ref_count.h b/base/allocator/partition_allocator/partition_ref_count.h index a41efea..c05eccf 100644 --- a/base/allocator/partition_allocator/partition_ref_count.h +++ b/base/allocator/partition_allocator/partition_ref_count.h
@@ -23,6 +23,15 @@ #if BUILDFLAG(USE_BACKUP_REF_PTR) +namespace { + +[[noreturn]] NOINLINE NOT_TAIL_CALLED void DoubleFreeOrCorruptionDetected() { + NO_CODE_FOLDING(); + IMMEDIATE_CRASH(); +} + +} // namespace + // Special-purpose atomic reference count class used by BackupRefPtrImpl. // The least significant bit of the count is reserved for tracking the liveness // state of an allocation: it's set when the allocation is created and cleared @@ -84,7 +93,8 @@ #endif int32_t old_count = count_.fetch_sub(1, std::memory_order_release); - PA_CHECK(old_count & 1); // double-free detection + if (UNLIKELY(!(old_count & 1))) + DoubleFreeOrCorruptionDetected(); if (old_count == 1) { std::atomic_thread_fence(std::memory_order_acquire); #if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) @@ -169,12 +179,16 @@ "<= SystemPageSize()."); ALWAYS_INLINE PartitionRefCount* PartitionRefCountPointer(void* slot_start) { - DCheckGetSlotOffsetIsZero(slot_start); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CheckThatSlotOffsetIsZero(slot_start); +#endif uintptr_t slot_start_as_uintptr = reinterpret_cast<uintptr_t>(slot_start); if (LIKELY(slot_start_as_uintptr & SystemPageOffsetMask())) { uintptr_t refcount_ptr_as_uintptr = slot_start_as_uintptr - sizeof(PartitionRefCount); - PA_DCHECK(refcount_ptr_as_uintptr % alignof(PartitionRefCount) == 0); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + PA_CHECK(refcount_ptr_as_uintptr % alignof(PartitionRefCount) == 0); +#endif return reinterpret_cast<PartitionRefCount*>(refcount_ptr_as_uintptr); } else { PartitionRefCount* bitmap_base = reinterpret_cast<PartitionRefCount*>( @@ -187,7 +201,9 @@ #endif ) * kPartitionRefCountIndexMultiplier; - PA_DCHECK(sizeof(PartitionRefCount) * index <= SystemPageSize()); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + PA_CHECK(sizeof(PartitionRefCount) * index <= SystemPageSize()); +#endif return bitmap_base + index; } } @@ -205,7 +221,9 @@ constexpr size_t kPartitionPastAllocationAdjustment = 1; ALWAYS_INLINE PartitionRefCount* PartitionRefCountPointer(void* slot_start) { - DCheckGetSlotOffsetIsZero(slot_start); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CheckThatSlotOffsetIsZero(slot_start); +#endif return reinterpret_cast<PartitionRefCount*>(slot_start); }
diff --git a/base/memory/checked_ptr.cc b/base/memory/checked_ptr.cc index fb08d22..489bdaa 100644 --- a/base/memory/checked_ptr.cc +++ b/base/memory/checked_ptr.cc
@@ -13,27 +13,35 @@ #include "base/allocator/partition_allocator/partition_alloc.h" #include "base/allocator/partition_allocator/partition_ref_count.h" #include "base/allocator/partition_allocator/partition_root.h" +#include "base/allocator/partition_allocator/reservation_offset_table.h" #include "base/check.h" +#include "base/dcheck_is_on.h" namespace base { namespace internal { void BackupRefPtrImpl::AcquireInternal(void* ptr) { - DCHECK(IsManagedByPartitionAllocBRPPool(ptr)); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CHECK(IsManagedByPartitionAllocBRPPool(ptr)); +#endif void* slot_start = PartitionAllocGetSlotStart(ptr); PartitionRefCountPointer(slot_start)->Acquire(); } void BackupRefPtrImpl::ReleaseInternal(void* ptr) { - DCHECK(IsManagedByPartitionAllocBRPPool(ptr)); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CHECK(IsManagedByPartitionAllocBRPPool(ptr)); +#endif void* slot_start = PartitionAllocGetSlotStart(ptr); if (PartitionRefCountPointer(slot_start)->Release()) PartitionAllocFreeForRefCounting(slot_start); } bool BackupRefPtrImpl::IsPointeeAlive(void* ptr) { - DCHECK(IsManagedByPartitionAllocBRPPool(ptr)); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CHECK(IsManagedByPartitionAllocBRPPool(ptr)); +#endif void* slot_start = PartitionAllocGetSlotStart(ptr); return PartitionRefCountPointer(slot_start)->IsAlive(); } @@ -42,6 +50,20 @@ return PartitionAllocIsValidPtrDelta(ptr, delta); } +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +void CheckThatAddressIsntWithinFirstPartitionPage(void* ptr) { + if (IsManagedByDirectMap(ptr)) { + uintptr_t reservation_start = GetDirectMapReservationStart(ptr); + CHECK(reinterpret_cast<uintptr_t>(ptr) - reservation_start >= + PartitionPageSize()); + } else { + CHECK(IsManagedByNormalBuckets(ptr)); + CHECK(reinterpret_cast<uintptr_t>(ptr) % kSuperPageSize >= + PartitionPageSize()); + } +} +#endif // DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + } // namespace internal } // namespace base
diff --git a/base/memory/checked_ptr.h b/base/memory/checked_ptr.h index ea92b90..7a14bf1 100644 --- a/base/memory/checked_ptr.h +++ b/base/memory/checked_ptr.h
@@ -15,6 +15,7 @@ #include "base/allocator/buildflags.h" #include "base/check.h" #include "base/compiler_specific.h" +#include "base/dcheck_is_on.h" #include "build/build_config.h" #include "build/buildflag.h" @@ -26,7 +27,6 @@ #include "base/allocator/partition_allocator/partition_alloc_config.h" #include "base/allocator/partition_allocator/partition_alloc_constants.h" #include "base/base_export.h" -#include "base/dcheck_is_on.h" #endif // BUILDFLAG(USE_BACKUP_REF_PTR) namespace base { @@ -91,6 +91,10 @@ #if BUILDFLAG(USE_BACKUP_REF_PTR) +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +void CheckThatAddressIsntWithinFirstPartitionPage(void* ptr); +#endif + struct BackupRefPtrImpl { // Note that `BackupRefPtrImpl` itself is not thread-safe. If multiple threads // modify the same smart pointer object without synchronization, a data race @@ -114,7 +118,9 @@ // https://bugs.llvm.org/show_bug.cgi?id=49403 // https://reviews.llvm.org/D97848 // https://chromium-review.googlesource.com/c/chromium/src/+/2727400/2/base/memory/checked_ptr.h#120 - DCHECK(ptr != nullptr || !ret); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CHECK(ptr != nullptr || !ret); +#endif #if HAS_BUILTIN(__builtin_assume) __builtin_assume(ptr != nullptr || !ret); #endif @@ -135,15 +141,10 @@ // This allows us to make a stronger assertion that if // IsManagedByPartitionAllocBRPPool returns true for a valid pointer, // it must be at least partition page away from the beginning of a super - // page. This, however, can't be easily checked for direct maps, where a - // pointer on a consecutive super page may easily land in its first - // partition page. - // TODO(bartekn): Keep the assert for non-DirectMap as well as for the - // first page of DirectMap allocations. -#if 0 + // page. +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) if (ret) { - DCHECK(reinterpret_cast<uintptr_t>(ptr) % kSuperPageSize >= - PartitionPageSize()); + CheckThatAddressIsntWithinFirstPartitionPage(ptr); } #endif @@ -153,7 +154,9 @@ // Wraps a pointer. static ALWAYS_INLINE void* WrapRawPtr(void* ptr) { if (IsSupportedAndNotNull(ptr)) { - DCHECK(ptr != nullptr); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CHECK(ptr != nullptr); +#endif AcquireInternal(ptr); } #if !defined(PA_HAS_64_BITS_POINTERS) @@ -167,7 +170,9 @@ // Notifies the allocator when a wrapped pointer is being removed or replaced. static ALWAYS_INLINE void ReleaseWrappedPtr(void* wrapped_ptr) { if (IsSupportedAndNotNull(wrapped_ptr)) { - DCHECK(wrapped_ptr != nullptr); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CHECK(wrapped_ptr != nullptr); +#endif ReleaseInternal(wrapped_ptr); } #if !defined(PA_HAS_64_BITS_POINTERS) @@ -182,8 +187,8 @@ static ALWAYS_INLINE void* SafelyUnwrapPtrForDereference(void* wrapped_ptr) { #if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) if (IsSupportedAndNotNull(wrapped_ptr)) { - DCHECK(wrapped_ptr != nullptr); - DCHECK(IsPointeeAlive(wrapped_ptr)); + CHECK(wrapped_ptr != nullptr); + CHECK(IsPointeeAlive(wrapped_ptr)); } #endif return wrapped_ptr; @@ -384,8 +389,10 @@ ALWAYS_INLINE CheckedPtr& operator=(const CheckedPtr<U, Impl>& ptr) noexcept { // Make sure that pointer isn't assigned to itself (look at pointer address, // not its value). - DCHECK(reinterpret_cast<uintptr_t>(this) != - reinterpret_cast<uintptr_t>(&ptr)); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CHECK(reinterpret_cast<uintptr_t>(this) != + reinterpret_cast<uintptr_t>(&ptr)); +#endif Impl::ReleaseWrappedPtr(AsVoidPtr()); SetFromVoidPtr( Impl::Duplicate(Impl::template Upcast<T, U>(ptr.AsVoidPtr()))); @@ -398,8 +405,10 @@ ALWAYS_INLINE CheckedPtr& operator=(CheckedPtr<U, Impl>&& ptr) noexcept { // Make sure that pointer isn't assigned to itself (look at pointer address, // not its value). - DCHECK(reinterpret_cast<uintptr_t>(this) != - reinterpret_cast<uintptr_t>(&ptr)); +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) + CHECK(reinterpret_cast<uintptr_t>(this) != + reinterpret_cast<uintptr_t>(&ptr)); +#endif Impl::ReleaseWrappedPtr(AsVoidPtr()); SetFromVoidPtr(Impl::template Upcast<T, U>(ptr.AsVoidPtr())); #if BUILDFLAG(USE_BACKUP_REF_PTR)
diff --git a/base/memory/checked_ptr_unittest.cc b/base/memory/checked_ptr_unittest.cc index 2acf179..692eb89 100644 --- a/base/memory/checked_ptr_unittest.cc +++ b/base/memory/checked_ptr_unittest.cc
@@ -746,10 +746,10 @@ EXPECT_EQ(*raw_ptr1, *checked_ptr1); allocator.root()->Free(raw_ptr1); -#if DCHECK_IS_ON() +#if DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) // In debug builds, the use-after-free should be caught immediately. EXPECT_DEATH_IF_SUPPORTED(if (*checked_ptr1 == 42) return, ""); -#else // DCHECK_IS_ON() +#else // DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) // The allocation should be poisoned since there's a CheckedPtr alive. EXPECT_NE(*checked_ptr1, 42ul); @@ -763,7 +763,7 @@ void* raw_ptr3 = allocator.root()->Alloc(sizeof(uint64_t), ""); EXPECT_EQ(raw_ptr1, raw_ptr3); allocator.root()->Free(raw_ptr3); -#endif // DCHECK_IS_ON() +#endif // DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) } TEST(BackupRefPtrImpl, ZeroSized) {
diff --git a/base/trace_event/common/trace_event_common.h b/base/trace_event/common/trace_event_common.h index dff2f9b..41d1b86 100644 --- a/base/trace_event/common/trace_event_common.h +++ b/base/trace_event/common/trace_event_common.h
@@ -56,12 +56,12 @@ // static int send_count = 0; // ++send_count; // TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( -// "ipc", "message", TRACE_ID_LOCAL(send_count)); +// "ipc", "message", TRACE_ID_WITH_SCOPE("message", send_count)); // Send(new MyMessage(send_count)); // [receive code] // void OnMyMessage(send_count) { // TRACE_NESTABLE_EVENT_ASYNC_END0( -// "ipc", "message", TRACE_ID_LOCAL(send_count)); +// "ipc", "message", TRACE_ID_WITH_SCOPE("message", send_count)); // } // The third parameter is a unique ID to match NESTABLE_ASYNC_BEGIN/ASYNC_END // pairs. NESTABLE_ASYNC_BEGIN and ASYNC_END can occur on any thread of any @@ -71,10 +71,12 @@ // class MyTracedClass { // public: // MyTracedClass() { -// TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("category", "MyTracedClass", this); +// TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("category", "MyTracedClass", +// TRACE_ID_LOCAL(this)); // } // ~MyTracedClass() { -// TRACE_EVENT_NESTABLE_ASYNC_END0("category", "MyTracedClass", this); +// TRACE_EVENT_NESTABLE_ASYNC_END0("category", "MyTracedClass", +// TRACE_ID_LOCAL(this)); // } // } // @@ -925,6 +927,16 @@ INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN, \ category_group, name, id, \ TRACE_EVENT_FLAG_COPY) +#define TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN1(category_group, name, id, \ + arg1_name, arg1_val) \ + INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN, \ + category_group, name, id, \ + TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val) +#define TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN2( \ + category_group, name, id, arg1_name, arg1_val, arg2_name, arg2_val) \ + INTERNAL_TRACE_EVENT_ADD_WITH_ID( \ + TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN, category_group, name, id, \ + TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val, arg2_name, arg2_val) #define TRACE_EVENT_COPY_NESTABLE_ASYNC_END0(category_group, name, id) \ INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_NESTABLE_ASYNC_END, \ category_group, name, id, \
diff --git a/cc/metrics/compositor_timing_history.cc b/cc/metrics/compositor_timing_history.cc index 1aebad86..9bcd62a 100644 --- a/cc/metrics/compositor_timing_history.cc +++ b/cc/metrics/compositor_timing_history.cc
@@ -729,12 +729,14 @@ // Emit a trace event to highlight a long time lapse between the draw times // of back-to-back BeginImplFrames. if (draw_interval > kDrawIntervalTraceThreshold) { - TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP0( + TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0( "latency", "Long Draw Interval", - TRACE_ID_LOCAL(g_num_long_draw_intervals), draw_start_time_); - TRACE_EVENT_ASYNC_END_WITH_TIMESTAMP0( + TRACE_ID_WITH_SCOPE("Long Draw Interval", g_num_long_draw_intervals), + draw_start_time_); + TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP0( "latency", "Long Draw Interval", - TRACE_ID_LOCAL(g_num_long_draw_intervals), draw_end_time); + TRACE_ID_WITH_SCOPE("Long Draw Interval", g_num_long_draw_intervals), + draw_end_time); g_num_long_draw_intervals++; } if (has_custom_property_animations &&
diff --git a/cc/scheduler/begin_frame_tracker.cc b/cc/scheduler/begin_frame_tracker.cc index ac085cb..2f5d645 100644 --- a/cc/scheduler/begin_frame_tracker.cc +++ b/cc/scheduler/begin_frame_tracker.cc
@@ -26,11 +26,12 @@ "location", location_string_); // Trace this specific begin frame tracker Start/Finish times. - TRACE_EVENT_COPY_ASYNC_BEGIN2( + TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN2( TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"), location_string_.c_str(), - new_args.frame_time.since_origin().InMicroseconds(), "new args", - new_args.AsValue(), "current args", current_args_.AsValue()); + TRACE_ID_WITH_SCOPE(location_string_.c_str(), + new_args.frame_time.since_origin().InMicroseconds()), + "new args", new_args.AsValue(), "current args", current_args_.AsValue()); // Check the new viz::BeginFrameArgs are valid and monotonically increasing. DCHECK(new_args.IsValid()); @@ -58,10 +59,12 @@ void BeginFrameTracker::Finish() { DCHECK(!HasFinished()) << "Tried to finish an already finished frame"; current_finished_at_ = base::TimeTicks::Now(); - TRACE_EVENT_COPY_ASYNC_END0( + TRACE_EVENT_COPY_NESTABLE_ASYNC_END0( TRACE_DISABLED_BY_DEFAULT("cc.debug.scheduler.frames"), location_string_.c_str(), - current_args_.frame_time.since_origin().InMicroseconds()); + TRACE_ID_WITH_SCOPE( + location_string_.c_str(), + current_args_.frame_time.since_origin().InMicroseconds())); } const viz::BeginFrameArgs& BeginFrameTracker::Last() const {
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index de36df8..dee00d0 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -904,6 +904,7 @@ "//chrome/browser/android/browserservices/intents:junit", "//chrome/browser/android/browserservices/metrics:java", "//chrome/browser/android/browserservices/verification:java", + "//chrome/browser/android/browserservices/verification:junit_test_support", "//chrome/browser/android/lifecycle:java", "//chrome/browser/android/webapps/launchpad:junit_tests", "//chrome/browser/attribution_reporting/android/internal:junit_tests",
diff --git a/chrome/android/chrome_junit_test_java_sources.gni b/chrome/android/chrome_junit_test_java_sources.gni index 3d05070..1cdfe3d6 100644 --- a/chrome/android/chrome_junit_test_java_sources.gni +++ b/chrome/android/chrome_junit_test_java_sources.gni
@@ -69,12 +69,14 @@ "junit/src/org/chromium/chrome/browser/cookies/CanonicalCookieTest.java", "junit/src/org/chromium/chrome/browser/crash/LogcatExtractionRunnableUnitTest.java", "junit/src/org/chromium/chrome/browser/cryptids/ProbabilisticCryptidRendererUnitTest.java", + "junit/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java", "junit/src/org/chromium/chrome/browser/customtabs/CloseButtonNavigatorTest.java", "junit/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProviderTest.java", "junit/src/org/chromium/chrome/browser/customtabs/CustomTabNavigationBarControllerTest.java", "junit/src/org/chromium/chrome/browser/customtabs/CustomTabNightModeStateControllerTest.java", "junit/src/org/chromium/chrome/browser/customtabs/CustomTabStatusBarColorProviderTest.java", "junit/src/org/chromium/chrome/browser/customtabs/LaunchesWithColorSchemeTest.java", + "junit/src/org/chromium/chrome/browser/customtabs/MockPostMessageHandler.java", "junit/src/org/chromium/chrome/browser/customtabs/NavigationInfoCaptureTriggerTest.java", "junit/src/org/chromium/chrome/browser/customtabs/RequestThrottlerTest.java", "junit/src/org/chromium/chrome/browser/customtabs/content/CustomTabActivityContentTestEnvironment.java",
diff --git a/chrome/android/chrome_test_java_sources.gni b/chrome/android/chrome_test_java_sources.gni index 1c492aa4..80ebec0 100644 --- a/chrome/android/chrome_test_java_sources.gni +++ b/chrome/android/chrome_test_java_sources.gni
@@ -128,7 +128,6 @@ "javatests/src/org/chromium/chrome/browser/crash/MinidumpUploadServiceTest.java", "javatests/src/org/chromium/chrome/browser/crash/PureJavaExceptionReporterTest.java", "javatests/src/org/chromium/chrome/browser/crypto/CipherFactoryTest.java", - "javatests/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java", "javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityAppMenuTest.java", "javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityIncognitoMetricTest.java", "javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityIncognitoTest.java",
diff --git a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_component/AccessorySheetRenderTest.java b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_component/AccessorySheetRenderTest.java index 149463c..fd80850d 100644 --- a/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_component/AccessorySheetRenderTest.java +++ b/chrome/android/features/keyboard_accessory/javatests/src/org/chromium/chrome/browser/keyboard_accessory/sheet_component/AccessorySheetRenderTest.java
@@ -19,7 +19,6 @@ import android.content.Context; import android.graphics.drawable.Drawable; -import android.support.test.filters.MediumTest; import android.view.Gravity; import android.view.ViewStub; import android.widget.FrameLayout; @@ -29,6 +28,7 @@ import androidx.annotation.IdRes; import androidx.annotation.LayoutRes; import androidx.annotation.Nullable; +import androidx.test.filters.MediumTest; import org.junit.After; import org.junit.Before;
diff --git a/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/InstantStartTest.java b/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/InstantStartTest.java index c57fd6bd..605e486 100644 --- a/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/InstantStartTest.java +++ b/chrome/android/features/start_surface/internal/javatests/src/org/chromium/chrome/features/start_surface/InstantStartTest.java
@@ -38,7 +38,6 @@ import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Build; -import android.support.test.filters.MediumTest; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; @@ -49,6 +48,7 @@ import androidx.test.espresso.contrib.RecyclerViewActions; import androidx.test.espresso.matcher.BoundedMatcher; import androidx.test.espresso.matcher.ViewMatchers; +import androidx.test.filters.MediumTest; import androidx.test.filters.SmallTest; import org.hamcrest.Description;
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilitiesTest.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilitiesTest.java index ccb00f8..809128b9 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilitiesTest.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/PriceTrackingUtilitiesTest.java
@@ -7,7 +7,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.After; import org.junit.Assert;
diff --git a/chrome/android/java/res/layout/incognito_history_placeholder.xml b/chrome/android/java/res/layout/incognito_history_placeholder.xml index 8a9ba29..05446e4 100644 --- a/chrome/android/java/res/layout/incognito_history_placeholder.xml +++ b/chrome/android/java/res/layout/incognito_history_placeholder.xml
@@ -12,7 +12,6 @@ android:background="@color/default_bg_color"> <LinearLayout - android:id="@+id/incognito_history_placeholder_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"
diff --git a/chrome/android/java/res/layout/webapk_icon_name_update_dialog.xml b/chrome/android/java/res/layout/webapk_icon_name_update_dialog.xml index 3b2a8a2f..df3572f 100644 --- a/chrome/android/java/res/layout/webapk_icon_name_update_dialog.xml +++ b/chrome/android/java/res/layout/webapk_icon_name_update_dialog.xml
@@ -26,7 +26,7 @@ android:layout_width="64dp" android:layout_height="64dp" android:visibility="gone" - android:contentDescription="@string/update_webapk_current_icon" /> + android:contentDescription="@string/webapp_update_current_icon" /> <TextView android:id="@+id/short_app_name_old" @@ -67,7 +67,7 @@ android:layout_width="64dp" android:layout_height="64dp" android:visibility="gone" - android:contentDescription="@string/update_webapk_updated_icon"/> + android:contentDescription="@string/webapp_update_new_icon"/> <TextView android:id="@+id/short_app_name_new"
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java index 338617d..f1f14fc 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java
@@ -41,7 +41,7 @@ import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.content_public.browser.WebContents; import org.chromium.content_public.common.Referrer; -import org.chromium.url.URI; +import org.chromium.url.GURL; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -273,8 +273,24 @@ } } - // TODO(crbug.com/1164866): Inject the Factory/Supplier. - private final OriginVerifierFactory mOriginVerifierFactory = new OriginVerifierFactoryImpl(); + /** A wrapper around {@link InstalledAppProviderImpl} to aid testing. */ + interface InstalledAppProviderWrapper { + /** + * Calls through to {@link InstalledAppProviderImpl#isAppInstalledAndAssociatedWithOrigin}. + */ + boolean isAppInstalledAndAssociatedWithOrigin(String packageName, Origin origin); + } + + private static class ProdInstalledAppProviderWrapper implements InstalledAppProviderWrapper { + @Override + public boolean isAppInstalledAndAssociatedWithOrigin(String packageName, Origin origin) { + return InstalledAppProviderImpl.isAppInstalledAndAssociatedWithOrigin( + packageName, new GURL(origin.toString())); + } + } + + private final OriginVerifierFactory mOriginVerifierFactory; + private final InstalledAppProviderWrapper mInstalledAppProviderWrapper; private final Map<CustomTabsSessionToken, SessionParams> mSessionParams = new HashMap<>(); @@ -282,6 +298,13 @@ private boolean mWarmupHasBeenCalled; public ClientManager() { + this(new OriginVerifierFactoryImpl(), new ProdInstalledAppProviderWrapper()); + } + + public ClientManager(OriginVerifierFactory originVerifierFactory, + InstalledAppProviderWrapper installedAppProviderWrapper) { + mOriginVerifierFactory = originVerifierFactory; + mInstalledAppProviderWrapper = installedAppProviderWrapper; RequestThrottler.loadInBackground(); } @@ -485,8 +508,8 @@ PostTask.runOrPostTask(UiThreadTaskTraits.DEFAULT, () -> { params.originVerifier.start(listener, origin); }); if (relation == CustomTabsService.RELATION_HANDLE_ALL_URLS - && InstalledAppProviderImpl.isAppInstalledAndAssociatedWithOrigin( - params.getPackageName(), URI.create(origin.toString()))) { + && mInstalledAppProviderWrapper.isAppInstalledAndAssociatedWithOrigin( + params.getPackageName(), origin)) { params.mLinkedOrigins.add(origin); } return true;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManager.java b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManager.java index de722b38..08485a6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/history/HistoryManager.java
@@ -10,7 +10,6 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; -import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; @@ -230,14 +229,12 @@ private ViewGroup getIncognitoHistoryPlaceholderView() { ViewGroup placeholderView = (ViewGroup) LayoutInflater.from(mActivity).inflate( R.layout.incognito_history_placeholder, null); + ImageButton dismissButton = + placeholderView.findViewById(R.id.close_history_placeholder_button); if (mIsSeparateActivity) { - ImageButton dismissButton = - placeholderView.findViewById(R.id.close_history_placeholder_button); dismissButton.setOnClickListener(v -> mActivity.finish()); } else { - LinearLayout titleView = - placeholderView.findViewById(R.id.incognito_history_placeholder_title); - titleView.setVisibility(View.GONE); + dismissButton.setVisibility(View.GONE); } placeholderView.setFocusable(true); placeholderView.setFocusableInTouchMode(true);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkIconNameUpdateDialog.java b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkIconNameUpdateDialog.java index 671c513..af2ad8f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkIconNameUpdateDialog.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/webapps/WebApkIconNameUpdateDialog.java
@@ -73,10 +73,10 @@ int titleId = 0; if (iconChanging && (shortNameChanging || nameChanging)) { - titleId = R.string.webapk_update_dialog_title_name_and_icon; + titleId = R.string.webapp_update_dialog_title_name_and_icon; } else { - titleId = iconChanging ? R.string.webapk_update_dialog_title_icon - : R.string.webapk_update_dialog_title_name; + titleId = iconChanging ? R.string.webapp_update_dialog_title_icon + : R.string.webapp_update_dialog_title_name; } WebApkIconNameUpdateCustomView dialogCustomView = @@ -102,12 +102,12 @@ .with(ModalDialogProperties.CONTROLLER, this) .with(ModalDialogProperties.TITLE, resources, titleId) .with(ModalDialogProperties.MESSAGE, resources, - R.string.webapk_update_explanation) + R.string.webapp_update_explanation) .with(ModalDialogProperties.CUSTOM_VIEW, dialogCustomView) .with(ModalDialogProperties.PRIMARY_BUTTON_FILLED, true) .with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, resources, R.string.ok) .with(ModalDialogProperties.NEGATIVE_BUTTON_TEXT, resources, - R.string.webapk_update_negative_button) + R.string.webapp_update_negative_button) .with(ModalDialogProperties.TITLE_SCROLLABLE, true) .build();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ActivityTabProviderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ActivityTabProviderTest.java index 2fb8a2a..0ba407b3 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ActivityTabProviderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/ActivityTabProviderTest.java
@@ -8,7 +8,8 @@ import static org.junit.Assert.assertNotEquals; import android.support.test.InstrumentationRegistry; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Rule;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/permissiondelegation/TrustedWebActivityLocationDelegationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/permissiondelegation/TrustedWebActivityLocationDelegationTest.java index 901d72a..be0f67f 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/permissiondelegation/TrustedWebActivityLocationDelegationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/browserservices/permissiondelegation/TrustedWebActivityLocationDelegationTest.java
@@ -12,7 +12,8 @@ import android.net.Uri; import android.os.Build; import android.os.RemoteException; -import android.support.test.filters.MediumTest; + +import androidx.test.filters.MediumTest; import org.junit.Before; import org.junit.Rule;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java deleted file mode 100644 index 1465e68..0000000 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java +++ /dev/null
@@ -1,367 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.chrome.browser.customtabs; - -import android.content.Context; -import android.net.Uri; -import android.os.Process; -import android.support.test.InstrumentationRegistry; - -import androidx.browser.customtabs.CustomTabsService; -import androidx.browser.customtabs.CustomTabsSessionToken; -import androidx.browser.customtabs.PostMessageServiceConnection; -import androidx.test.filters.SmallTest; - -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.chromium.base.ContextUtils; -import org.chromium.base.IntentUtils; -import org.chromium.base.test.BaseJUnit4ClassRunner; -import org.chromium.base.test.util.Criteria; -import org.chromium.base.test.util.CriteriaHelper; -import org.chromium.base.test.util.MetricsUtils; -import org.chromium.chrome.browser.browserservices.PostMessageHandler; -import org.chromium.chrome.browser.browserservices.verification.OriginVerifier; -import org.chromium.components.embedder_support.util.Origin; -import org.chromium.content_public.browser.test.NativeLibraryTestUtils; -import org.chromium.content_public.browser.test.util.TestThreadUtils; - -/** Tests for ClientManager. */ -@RunWith(BaseJUnit4ClassRunner.class) -public class ClientManagerTest { - private static final String URL = "https://www.android.com"; - private static final String HTTP_URL = "http://www.android.com"; - - private ClientManager mClientManager; - private CustomTabsSessionToken mSession = - CustomTabsSessionToken.createMockSessionTokenForTesting(); - private int mUid = Process.myUid(); - - @Before - public void setUp() { - Context context = InstrumentationRegistry.getInstrumentation() - .getTargetContext() - .getApplicationContext(); - NativeLibraryTestUtils.loadNativeLibraryNoBrowserProcess(); - RequestThrottler.purgeAllEntriesForTesting(); - mClientManager = new ClientManager(); - TestThreadUtils.runOnUiThreadBlocking( - () -> OriginVerifier.clearCachedVerificationsForTesting()); - } - - @Test - @SmallTest - public void testNoSessionNoWarmup() { - Assert.assertEquals(ClientManager.CalledWarmup.NO_SESSION_NO_WARMUP, - mClientManager.getWarmupState(null)); - } - - @Test - @SmallTest - public void testNoSessionWarmup() { - mClientManager.recordUidHasCalledWarmup(mUid); - Assert.assertEquals( - ClientManager.CalledWarmup.NO_SESSION_WARMUP, mClientManager.getWarmupState(null)); - } - - @Test - @SmallTest - public void testInvalidSessionNoWarmup() { - Assert.assertEquals(ClientManager.CalledWarmup.NO_SESSION_NO_WARMUP, - mClientManager.getWarmupState(mSession)); - } - - @Test - @SmallTest - public void testInvalidSessionWarmup() { - mClientManager.recordUidHasCalledWarmup(mUid); - Assert.assertEquals(ClientManager.CalledWarmup.NO_SESSION_WARMUP, - mClientManager.getWarmupState(mSession)); - } - - @Test - @SmallTest - public void testValidSessionNoWarmup() { - mClientManager.newSession(mSession, mUid, null, null, null); - Assert.assertEquals(ClientManager.CalledWarmup.SESSION_NO_WARMUP_NOT_CALLED, - mClientManager.getWarmupState(mSession)); - } - - @Test - @SmallTest - public void testValidSessionOtherWarmup() { - mClientManager.recordUidHasCalledWarmup(mUid + 1); - mClientManager.newSession(mSession, mUid, null, null, null); - Assert.assertEquals(ClientManager.CalledWarmup.SESSION_NO_WARMUP_ALREADY_CALLED, - mClientManager.getWarmupState(mSession)); - } - - @Test - @SmallTest - public void testValidSessionWarmup() { - mClientManager.recordUidHasCalledWarmup(mUid); - mClientManager.newSession(mSession, mUid, null, null, null); - Assert.assertEquals( - ClientManager.CalledWarmup.SESSION_WARMUP, mClientManager.getWarmupState(mSession)); - } - - @Test - @SmallTest - public void testValidSessionWarmupSeveralCalls() { - mClientManager.recordUidHasCalledWarmup(mUid); - mClientManager.newSession(mSession, mUid, null, null, null); - Assert.assertEquals( - ClientManager.CalledWarmup.SESSION_WARMUP, mClientManager.getWarmupState(mSession)); - - CustomTabsSessionToken token = CustomTabsSessionToken.createMockSessionTokenForTesting(); - mClientManager.newSession(token, mUid, null, null, null); - Assert.assertEquals( - ClientManager.CalledWarmup.SESSION_WARMUP, mClientManager.getWarmupState(token)); - } - - @Test - @SmallTest - public void testPredictionOutcomeSuccess() { - Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); - Assert.assertEquals(ClientManager.PredictionStatus.GOOD, - mClientManager.getPredictionOutcome(mSession, URL)); - } - - @Test - @SmallTest - public void testPredictionOutcomeNoPrediction() { - Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); - mClientManager.recordUidHasCalledWarmup(mUid); - Assert.assertEquals(ClientManager.PredictionStatus.NONE, - mClientManager.getPredictionOutcome(mSession, URL)); - } - - @Test - @SmallTest - public void testPredictionOutcomeBadPrediction() { - Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); - Assert.assertEquals(ClientManager.PredictionStatus.BAD, - mClientManager.getPredictionOutcome(mSession, URL + "#fragment")); - } - - @Test - @SmallTest - public void testPredictionOutcomeIgnoreFragment() { - Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); - mClientManager.setIgnoreFragmentsForSession(mSession, true); - Assert.assertEquals(ClientManager.PredictionStatus.GOOD, - mClientManager.getPredictionOutcome(mSession, URL + "#fragment")); - } - - @Test - @SmallTest - public void testPostMessageOriginVerification() { - final ClientManager cm = mClientManager; - // TODO(peconn): Get rid of this anonymous class once PostMessageServiceConnection is made - // non-abstract. Same with the other occurrences below. - PostMessageServiceConnection serviceConnection = - new PostMessageServiceConnection(mSession) {}; - Assert.assertTrue(cm.newSession(mSession, mUid, null, - new PostMessageHandler(serviceConnection), serviceConnection)); - // Should always start with no origin. - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - - TestThreadUtils.runOnUiThreadBlocking(() -> { - // With no prepopulated origins, this verification should fail. - cm.verifyAndInitializeWithPostMessageOriginForSession( - mSession, Origin.create(URL), CustomTabsService.RELATION_USE_AS_ORIGIN); - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - - // If there is a prepopulated origin, we should get a synchronous verification. - OriginVerifier.addVerificationOverride( - ContextUtils.getApplicationContext().getPackageName(), Origin.create(URL), - CustomTabsService.RELATION_USE_AS_ORIGIN); - cm.verifyAndInitializeWithPostMessageOriginForSession( - mSession, Origin.create(URL), CustomTabsService.RELATION_USE_AS_ORIGIN); - }); - - CriteriaHelper.pollUiThread(() -> { - Criteria.checkThat( - cm.getPostMessageOriginForSessionForTesting(mSession), Matchers.notNullValue()); - }); - - TestThreadUtils.runOnUiThreadBlocking(() -> { - Uri verifiedOrigin = cm.getPostMessageOriginForSessionForTesting(mSession); - Assert.assertEquals( - IntentUtils.ANDROID_APP_REFERRER_SCHEME, verifiedOrigin.getScheme()); - - // initializeWithPostMessageOriginForSession should override without checking - // origin. - cm.initializeWithPostMessageOriginForSession(mSession, null); - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - }); - } - - @Test - @SmallTest - public void testPostMessageOriginDifferentRelations() { - final ClientManager cm = mClientManager; - PostMessageServiceConnection serviceConnection = - new PostMessageServiceConnection(mSession) {}; - Assert.assertTrue(cm.newSession(mSession, mUid, null, - new PostMessageHandler(serviceConnection), serviceConnection)); - // Should always start with no origin. - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - - Origin origin = Origin.create(URL); - - // With no prepopulated origins, this verification should fail. - cm.verifyAndInitializeWithPostMessageOriginForSession( - mSession, origin, CustomTabsService.RELATION_USE_AS_ORIGIN); - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - TestThreadUtils.runOnUiThreadBlocking(() -> { - // Prepopulated origins should depend on the relation used. - OriginVerifier.addVerificationOverride( - ContextUtils.getApplicationContext().getPackageName(), origin, - CustomTabsService.RELATION_HANDLE_ALL_URLS); - // This uses CustomTabsService.RELATION_USE_AS_ORIGIN by default. - Assert.assertFalse(cm.isFirstPartyOriginForSession(mSession, origin)); - }); - - cm.verifyAndInitializeWithPostMessageOriginForSession( - mSession, origin, CustomTabsService.RELATION_HANDLE_ALL_URLS); - - TestThreadUtils.runOnUiThreadBlocking(() -> { - Uri verifiedOrigin = cm.getPostMessageOriginForSessionForTesting(mSession); - Assert.assertEquals( - IntentUtils.ANDROID_APP_REFERRER_SCHEME, verifiedOrigin.getScheme()); - // initializeWithPostMessageOriginForSession should override without checking - // origin. - cm.initializeWithPostMessageOriginForSession(mSession, null); - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - }); - } - - @Test - @SmallTest - public void testPostMessageOriginHttpNotAllowed() { - final ClientManager cm = mClientManager; - PostMessageServiceConnection serviceConnection = - new PostMessageServiceConnection(mSession) {}; - Assert.assertTrue(cm.newSession(mSession, mUid, null, - new PostMessageHandler(serviceConnection), serviceConnection)); - // Should always start with no origin. - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - - TestThreadUtils.runOnUiThreadBlocking(() -> { - Origin origin = Origin.create(HTTP_URL); - // With no prepopulated origins, this verification should fail. - cm.verifyAndInitializeWithPostMessageOriginForSession( - mSession, origin, CustomTabsService.RELATION_USE_AS_ORIGIN); - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - - // Even if there is a prepopulated origin, non-https origins should get an early - // return with false. - OriginVerifier.addVerificationOverride( - ContextUtils.getApplicationContext().getPackageName(), origin, - CustomTabsService.RELATION_USE_AS_ORIGIN); - cm.verifyAndInitializeWithPostMessageOriginForSession( - mSession, origin, CustomTabsService.RELATION_USE_AS_ORIGIN); - Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); - }); - } - - @Test - @SmallTest - public void testFirstLowConfidencePredictionIsNotThrottled() { - Context context = InstrumentationRegistry.getInstrumentation() - .getTargetContext() - .getApplicationContext(); - Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); - - // Two low confidence in a row is OK. - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); - mClientManager.registerLaunch(mSession, URL); - - // Low -> High as well. - RequestThrottler.purgeAllEntriesForTesting(); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); - mClientManager.registerLaunch(mSession, URL); - - // High -> Low as well. - RequestThrottler.purgeAllEntriesForTesting(); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); - mClientManager.registerLaunch(mSession, URL); - } - - @Test - @SmallTest - public void testMayLaunchUrlAccounting() { - Context context = InstrumentationRegistry.getInstrumentation() - .getTargetContext() - .getApplicationContext(); - - String name = "CustomTabs.MayLaunchUrlType"; - MetricsUtils.HistogramDelta noMayLaunchUrlDelta = new MetricsUtils.HistogramDelta( - name, ClientManager.MayLaunchUrlType.NO_MAY_LAUNCH_URL); - MetricsUtils.HistogramDelta lowConfidenceDelta = new MetricsUtils.HistogramDelta( - name, ClientManager.MayLaunchUrlType.LOW_CONFIDENCE); - MetricsUtils.HistogramDelta highConfidenceDelta = new MetricsUtils.HistogramDelta( - name, ClientManager.MayLaunchUrlType.HIGH_CONFIDENCE); - MetricsUtils.HistogramDelta bothDelta = - new MetricsUtils.HistogramDelta(name, ClientManager.MayLaunchUrlType.BOTH); - - Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); - - // No prediction; - mClientManager.registerLaunch(mSession, URL); - Assert.assertEquals(1, noMayLaunchUrlDelta.getDelta()); - - // Low confidence. - RequestThrottler.purgeAllEntriesForTesting(); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); - mClientManager.registerLaunch(mSession, URL); - Assert.assertEquals(1, lowConfidenceDelta.getDelta()); - - // High confidence. - RequestThrottler.purgeAllEntriesForTesting(); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); - mClientManager.registerLaunch(mSession, URL); - Assert.assertEquals(1, highConfidenceDelta.getDelta()); - - // Low and High confidence. - RequestThrottler.purgeAllEntriesForTesting(); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); - mClientManager.registerLaunch(mSession, URL); - Assert.assertEquals(1, bothDelta.getDelta()); - - // Low and High confidence, same call. - RequestThrottler.purgeAllEntriesForTesting(); - bothDelta = new MetricsUtils.HistogramDelta(name, ClientManager.MayLaunchUrlType.BOTH); - Assert.assertTrue( - mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, true)); - mClientManager.registerLaunch(mSession, URL); - Assert.assertEquals(1, bothDelta.getDelta()); - } -}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/history/HistoryTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/history/HistoryTest.java index 769e33c..a8a751f 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/history/HistoryTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/history/HistoryTest.java
@@ -7,7 +7,8 @@ import static org.junit.Assert.assertNull; import android.graphics.Bitmap; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.Rule; import org.junit.Test;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/voice/AssistantVoiceSearchServiceRenderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/voice/AssistantVoiceSearchServiceRenderTest.java index a327d0d..ffc5d4f 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/voice/AssistantVoiceSearchServiceRenderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/voice/AssistantVoiceSearchServiceRenderTest.java
@@ -15,7 +15,7 @@ import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE; import static org.chromium.chrome.browser.preferences.ChromePreferenceKeys.ASSISTANT_VOICE_SEARCH_ENABLED; -import android.support.test.filters.MediumTest; +import androidx.test.filters.MediumTest; import org.junit.Before; import org.junit.Rule;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/voice/AssistantVoiceSearchServiceTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/voice/AssistantVoiceSearchServiceTest.java index acce865..f4b11c63 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/voice/AssistantVoiceSearchServiceTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/omnibox/voice/AssistantVoiceSearchServiceTest.java
@@ -11,7 +11,7 @@ import static org.chromium.base.test.util.Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE; import static org.chromium.chrome.browser.preferences.ChromePreferenceKeys.ASSISTANT_VOICE_SEARCH_ENABLED; -import android.support.test.filters.MediumTest; +import androidx.test.filters.MediumTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninFirstRunFragmentTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninFirstRunFragmentTest.java index 9661f1d..8088d84 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninFirstRunFragmentTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/SigninFirstRunFragmentTest.java
@@ -67,8 +67,7 @@ final String continueAsText = mChromeActivityTestRule.getActivity().getString( R.string.signin_promo_continue_as, GIVEN_NAME1); onView(withText(continueAsText)).check(matches(isDisplayed())); - onView(withText(R.string.signin_account_picker_dismiss_button)) - .check(matches(isDisplayed())); + onView(withText(R.string.signin_fre_dismiss_button)).check(matches(isDisplayed())); } @Test @@ -85,8 +84,7 @@ final String continueAsText = mChromeActivityTestRule.getActivity().getString( R.string.signin_promo_continue_as, TEST_EMAIL2); onView(withText(continueAsText)).check(matches(isDisplayed())); - onView(withText(R.string.signin_account_picker_dismiss_button)) - .check(matches(isDisplayed())); + onView(withText(R.string.signin_fre_dismiss_button)).check(matches(isDisplayed())); } private void launchActivityWithFragment() {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/survey/ChromeSurveyControllerIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/survey/ChromeSurveyControllerIntegrationTest.java index 3664e86..d1508be 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/survey/ChromeSurveyControllerIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/survey/ChromeSurveyControllerIntegrationTest.java
@@ -6,10 +6,11 @@ import android.app.Activity; import android.content.Context; -import android.support.test.filters.MediumTest; import android.text.style.ClickableSpan; import android.view.View; +import androidx.test.filters.MediumTest; + import org.junit.After; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/PersistedTabDataTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/PersistedTabDataTest.java index 91ded94..94fc53be2 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/PersistedTabDataTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/PersistedTabDataTest.java
@@ -8,7 +8,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataLegacyTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataLegacyTest.java index 6b21617..d78c5e6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataLegacyTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataLegacyTest.java
@@ -6,7 +6,7 @@ import static org.mockito.Mockito.doReturn; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; @@ -520,4 +520,4 @@ System.currentTimeMillis() - TimeUnit.DAYS.toMillis(8)); Assert.assertNull(shoppingPersistedTabData.getPriceDropLegacy()); } -} \ No newline at end of file +}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataLegacyWithPASTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataLegacyWithPASTest.java index 3f95717..2d09a4f6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataLegacyWithPASTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataLegacyWithPASTest.java
@@ -6,7 +6,7 @@ import static org.mockito.Mockito.doReturn; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; @@ -228,4 +228,4 @@ ShoppingPersistedTabDataWithPASTestUtils.verifyGetPageAnnotationsCalled( mPageAnnotationsServiceMock, 1); } -} \ No newline at end of file +}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataTest.java index cebe00d4..55111b8 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataTest.java
@@ -7,7 +7,7 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; @@ -734,4 +734,4 @@ }); callbackHelper.waitForCallback(0); } -} \ No newline at end of file +}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataWithPASTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataWithPASTest.java index 5c12596..ea3ab2e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataWithPASTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataWithPASTest.java
@@ -6,7 +6,7 @@ import static org.mockito.Mockito.doReturn; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before; @@ -184,4 +184,4 @@ }); ShoppingPersistedTabDataTestUtils.acquireSemaphore(semaphore); } -} \ No newline at end of file +}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/StorePersistedTabDataTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/StorePersistedTabDataTest.java index 90a9b87a..3595aec 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/StorePersistedTabDataTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/StorePersistedTabDataTest.java
@@ -9,7 +9,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.After; import org.junit.Assert; @@ -323,4 +323,4 @@ anyString(), any(String[].class), anyString(), anyLong(), any(Callback.class)); } -} \ No newline at end of file +}
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/AutofillUiUtilsTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/AutofillUiUtilsTest.java index 9611a50..5b4752c 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/AutofillUiUtilsTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/AutofillUiUtilsTest.java
@@ -6,9 +6,10 @@ import android.annotation.SuppressLint; import android.content.Context; -import android.support.test.filters.SmallTest; import android.widget.EditText; +import androidx.test.filters.SmallTest; + import org.junit.Assert; import org.junit.Before; import org.junit.Test;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/cryptids/ProbabilisticCryptidRendererUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/cryptids/ProbabilisticCryptidRendererUnitTest.java index a1ac3a5..6f9e927c 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/cryptids/ProbabilisticCryptidRendererUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/cryptids/ProbabilisticCryptidRendererUnitTest.java
@@ -4,8 +4,8 @@ package org.chromium.chrome.browser.cryptids; -import android.support.test.filters.MediumTest; -import android.support.test.filters.SmallTest; +import androidx.test.filters.MediumTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Rule;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java new file mode 100644 index 0000000..f5779e1 --- /dev/null +++ b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/ClientManagerTest.java
@@ -0,0 +1,358 @@ +// 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.browser.customtabs; + +import static android.os.Looper.getMainLooper; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import static org.robolectric.Shadows.shadowOf; + +import static org.chromium.chrome.browser.browserservices.verification.OriginVerifierUnitTestSupport.addVerification; + +import android.net.Uri; +import android.os.Process; + +import androidx.browser.customtabs.CustomTabsService; +import androidx.browser.customtabs.CustomTabsSessionToken; +import androidx.browser.customtabs.PostMessageServiceConnection; +import androidx.test.core.app.ApplicationProvider; +import androidx.test.filters.SmallTest; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.robolectric.annotation.Config; +import org.robolectric.shadows.ShadowPackageManager; + +import org.chromium.base.IntentUtils; +import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.metrics.test.ShadowRecordHistogram; +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.chrome.browser.browserservices.verification.OriginVerifier; +import org.chromium.chrome.browser.browserservices.verification.OriginVerifierFactoryImpl; +import org.chromium.chrome.browser.browserservices.verification.OriginVerifierUnitTestSupport; +import org.chromium.components.embedder_support.util.Origin; +import org.chromium.components.embedder_support.util.ShadowUrlUtilities; + +/** Tests for ClientManager. */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE, + shadows = {ShadowRecordHistogram.class, ShadowUrlUtilities.class, + ShadowPackageManager.class}) +public class ClientManagerTest { + private static final String URL = "https://www.android.com"; + private static final String PACKAGE_NAME = "org.chromium.chrome"; + + private ClientManager mClientManager; + private CustomTabsSessionToken mSession = + CustomTabsSessionToken.createMockSessionTokenForTesting(); + private int mUid = Process.myUid(); + + @Mock + private ClientManager.InstalledAppProviderWrapper mInstalledAppProviderWrapper; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + RequestThrottler.purgeAllEntriesForTesting(); + + OriginVerifierUnitTestSupport.registerPackageWithSignature( + shadowOf(ApplicationProvider.getApplicationContext().getPackageManager()), + PACKAGE_NAME, mUid); + + mClientManager = + new ClientManager(new OriginVerifierFactoryImpl(), mInstalledAppProviderWrapper); + + OriginVerifier.clearCachedVerificationsForTesting(); + ShadowRecordHistogram.reset(); + + ShadowUrlUtilities.setTestImpl(new ShadowUrlUtilities.TestImpl() { + @Override + public boolean urlsMatchIgnoringFragments(String url1, String url2) { + // Limited implementation that is good enough for these tests. + int index1 = url1.indexOf('#'); + int index2 = url2.indexOf('#'); + + if (index1 != -1) url1 = url1.substring(0, index1); + if (index2 != -1) url2 = url2.substring(0, index2); + + return url1.equals(url2); + } + }); + } + + @Test + @SmallTest + public void testNoSessionNoWarmup() { + Assert.assertEquals(ClientManager.CalledWarmup.NO_SESSION_NO_WARMUP, + mClientManager.getWarmupState(null)); + } + + @Test + @SmallTest + public void testNoSessionWarmup() { + mClientManager.recordUidHasCalledWarmup(mUid); + Assert.assertEquals( + ClientManager.CalledWarmup.NO_SESSION_WARMUP, mClientManager.getWarmupState(null)); + } + + @Test + @SmallTest + public void testInvalidSessionNoWarmup() { + Assert.assertEquals(ClientManager.CalledWarmup.NO_SESSION_NO_WARMUP, + mClientManager.getWarmupState(mSession)); + } + + @Test + @SmallTest + public void testInvalidSessionWarmup() { + mClientManager.recordUidHasCalledWarmup(mUid); + Assert.assertEquals(ClientManager.CalledWarmup.NO_SESSION_WARMUP, + mClientManager.getWarmupState(mSession)); + } + + @Test + @SmallTest + public void testValidSessionNoWarmup() { + mClientManager.newSession(mSession, mUid, null, null, null); + Assert.assertEquals(ClientManager.CalledWarmup.SESSION_NO_WARMUP_NOT_CALLED, + mClientManager.getWarmupState(mSession)); + } + + @Test + @SmallTest + public void testValidSessionOtherWarmup() { + mClientManager.recordUidHasCalledWarmup(mUid + 1); + mClientManager.newSession(mSession, mUid, null, null, null); + Assert.assertEquals(ClientManager.CalledWarmup.SESSION_NO_WARMUP_ALREADY_CALLED, + mClientManager.getWarmupState(mSession)); + } + + @Test + @SmallTest + public void testValidSessionWarmup() { + mClientManager.recordUidHasCalledWarmup(mUid); + mClientManager.newSession(mSession, mUid, null, null, null); + Assert.assertEquals( + ClientManager.CalledWarmup.SESSION_WARMUP, mClientManager.getWarmupState(mSession)); + } + + @Test + @SmallTest + public void testValidSessionWarmupSeveralCalls() { + mClientManager.recordUidHasCalledWarmup(mUid); + mClientManager.newSession(mSession, mUid, null, null, null); + Assert.assertEquals( + ClientManager.CalledWarmup.SESSION_WARMUP, mClientManager.getWarmupState(mSession)); + + CustomTabsSessionToken token = CustomTabsSessionToken.createMockSessionTokenForTesting(); + mClientManager.newSession(token, mUid, null, null, null); + Assert.assertEquals( + ClientManager.CalledWarmup.SESSION_WARMUP, mClientManager.getWarmupState(token)); + } + + @Test + @SmallTest + public void testPredictionOutcomeSuccess() { + Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); + Assert.assertEquals(ClientManager.PredictionStatus.GOOD, + mClientManager.getPredictionOutcome(mSession, URL)); + } + + @Test + @SmallTest + public void testPredictionOutcomeNoPrediction() { + Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); + mClientManager.recordUidHasCalledWarmup(mUid); + Assert.assertEquals(ClientManager.PredictionStatus.NONE, + mClientManager.getPredictionOutcome(mSession, URL)); + } + + @Test + @SmallTest + public void testPredictionOutcomeBadPrediction() { + Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); + Assert.assertEquals(ClientManager.PredictionStatus.BAD, + mClientManager.getPredictionOutcome(mSession, URL + "#fragment")); + } + + @Test + @SmallTest + public void testPredictionOutcomeIgnoreFragment() { + Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); + mClientManager.setIgnoreFragmentsForSession(mSession, true); + Assert.assertEquals(ClientManager.PredictionStatus.GOOD, + mClientManager.getPredictionOutcome(mSession, URL + "#fragment")); + } + + @Test + @SmallTest + public void testPostMessageOriginVerification() { + final ClientManager cm = mClientManager; + + // TODO(peconn): Get rid of this anonymous class once PostMessageServiceConnection is made + // non-abstract. Same with the other occurrences below. + PostMessageServiceConnection serviceConnection = + new PostMessageServiceConnection(mSession) {}; + Assert.assertTrue(cm.newSession( + mSession, mUid, null, MockPostMessageHandler.create(), serviceConnection)); + // Should always start with no origin. + Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); + + // With no prepopulated origins, this verification should fail. + cm.verifyAndInitializeWithPostMessageOriginForSession( + mSession, Origin.create(URL), CustomTabsService.RELATION_USE_AS_ORIGIN); + shadowOf(getMainLooper()).idle(); + Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); + + // If there is a prepopulated origin, we should get a synchronous verification. + addVerification(PACKAGE_NAME, Origin.create(URL), CustomTabsService.RELATION_USE_AS_ORIGIN); + cm.verifyAndInitializeWithPostMessageOriginForSession( + mSession, Origin.create(URL), CustomTabsService.RELATION_USE_AS_ORIGIN); + shadowOf(getMainLooper()).idle(); + + Assert.assertNotNull(cm.getPostMessageOriginForSessionForTesting(mSession)); + + Uri verifiedOrigin = cm.getPostMessageOriginForSessionForTesting(mSession); + Assert.assertEquals(IntentUtils.ANDROID_APP_REFERRER_SCHEME, verifiedOrigin.getScheme()); + + // initializeWithPostMessageOriginForSession should override without checking + // origin. + cm.initializeWithPostMessageOriginForSession(mSession, null); + Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); + } + + @Test + @SmallTest + public void testPostMessageOriginDifferentRelations() { + final ClientManager cm = mClientManager; + PostMessageServiceConnection serviceConnection = + new PostMessageServiceConnection(mSession) {}; + Assert.assertTrue(cm.newSession( + mSession, mUid, null, MockPostMessageHandler.create(), serviceConnection)); + + Origin origin = Origin.create(URL); + when(mInstalledAppProviderWrapper.isAppInstalledAndAssociatedWithOrigin(any(), eq(origin))) + .thenReturn(true); + + // Should always start with no origin. + Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); + + // With no prepopulated origins, this verification should fail. + cm.verifyAndInitializeWithPostMessageOriginForSession( + mSession, origin, CustomTabsService.RELATION_USE_AS_ORIGIN); + Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); + + // Prepopulated origins should depend on the relation used. + addVerification(PACKAGE_NAME, origin, CustomTabsService.RELATION_HANDLE_ALL_URLS); + // This uses CustomTabsService.RELATION_USE_AS_ORIGIN by default. + Assert.assertFalse(cm.isFirstPartyOriginForSession(mSession, origin)); + + cm.verifyAndInitializeWithPostMessageOriginForSession( + mSession, origin, CustomTabsService.RELATION_HANDLE_ALL_URLS); + + // TestThreadUtils.runOnUiThreadBlocking(() -> { + Uri verifiedOrigin = cm.getPostMessageOriginForSessionForTesting(mSession); + Assert.assertEquals(IntentUtils.ANDROID_APP_REFERRER_SCHEME, verifiedOrigin.getScheme()); + // initializeWithPostMessageOriginForSession should override without checking + // origin. + cm.initializeWithPostMessageOriginForSession(mSession, null); + Assert.assertNull(cm.getPostMessageOriginForSessionForTesting(mSession)); + // }); + } + + @Test + @SmallTest + public void testFirstLowConfidencePredictionIsNotThrottled() { + Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); + + // Two low confidence in a row is OK. + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); + mClientManager.registerLaunch(mSession, URL); + + // Low -> High as well. + RequestThrottler.purgeAllEntriesForTesting(); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); + mClientManager.registerLaunch(mSession, URL); + + // High -> Low as well. + RequestThrottler.purgeAllEntriesForTesting(); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); + mClientManager.registerLaunch(mSession, URL); + } + + @Test + @SmallTest + public void testMayLaunchUrlAccounting() { + String name = "CustomTabs.MayLaunchUrlType"; + Assert.assertTrue(mClientManager.newSession(mSession, mUid, null, null, null)); + + // No prediction; + mClientManager.registerLaunch(mSession, URL); + Assert.assertEquals(1, + RecordHistogram.getHistogramValueCountForTesting( + name, ClientManager.MayLaunchUrlType.NO_MAY_LAUNCH_URL)); + + // Low confidence. + RequestThrottler.purgeAllEntriesForTesting(); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); + mClientManager.registerLaunch(mSession, URL); + Assert.assertEquals(1, + RecordHistogram.getHistogramValueCountForTesting( + name, ClientManager.MayLaunchUrlType.LOW_CONFIDENCE)); + + // High confidence. + RequestThrottler.purgeAllEntriesForTesting(); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); + mClientManager.registerLaunch(mSession, URL); + Assert.assertEquals(1, + RecordHistogram.getHistogramValueCountForTesting( + name, ClientManager.MayLaunchUrlType.HIGH_CONFIDENCE)); + + // Low and High confidence. + RequestThrottler.purgeAllEntriesForTesting(); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, false)); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, null, true)); + mClientManager.registerLaunch(mSession, URL); + Assert.assertEquals(1, + RecordHistogram.getHistogramValueCountForTesting( + name, ClientManager.MayLaunchUrlType.BOTH)); + + // Low and High confidence, same call. + RequestThrottler.purgeAllEntriesForTesting(); + ShadowRecordHistogram.reset(); + Assert.assertTrue( + mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL, true)); + mClientManager.registerLaunch(mSession, URL); + Assert.assertEquals(1, + RecordHistogram.getHistogramValueCountForTesting( + name, ClientManager.MayLaunchUrlType.BOTH)); + } +}
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/MockPostMessageHandler.java b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/MockPostMessageHandler.java new file mode 100644 index 0000000..740e3a8 --- /dev/null +++ b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/MockPostMessageHandler.java
@@ -0,0 +1,82 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.customtabs; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.doAnswer; + +import android.net.Uri; + +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +import org.chromium.chrome.browser.browserservices.PostMessageHandler; +import org.chromium.chrome.browser.browserservices.verification.OriginVerifier; +import org.chromium.components.embedder_support.util.Origin; + +/** + * A mock {@link PostMessageHandler}. + */ +class MockPostMessageHandler { + private final PostMessageHandler mPostMessageHandler; + private Uri mPostMessageUri; + + public MockPostMessageHandler() { + mPostMessageHandler = Mockito.mock(PostMessageHandler.class); + + doAnswer((Answer<Void>) invocation -> { + reset(); + return null; + }) + .when(mPostMessageHandler) + .reset(any()); + + doAnswer((Answer<Void>) invocation -> { + initializeWithPostMessageUri(invocation.getArgument(0)); + return null; + }) + .when(mPostMessageHandler) + .initializeWithPostMessageUri(any()); + + doAnswer((Answer<Void>) invocation -> { + onOriginVerified(invocation.getArgument(0), invocation.getArgument(1), + invocation.getArgument(2)); + return null; + }) + .when(mPostMessageHandler) + .onOriginVerified(any(), any(), anyBoolean(), any()); + + doAnswer((Answer<Uri>) invocation -> { return getPostMessageUriForTesting(); }) + .when(mPostMessageHandler) + .getPostMessageUriForTesting(); + } + + public PostMessageHandler getPostMessageHandler() { + return mPostMessageHandler; + } + + public static PostMessageHandler create() { + return new MockPostMessageHandler().getPostMessageHandler(); + } + + private void reset() { + mPostMessageUri = null; + } + + private void initializeWithPostMessageUri(Uri uri) { + mPostMessageUri = uri; + } + + private void onOriginVerified(String packageName, Origin origin, boolean result) { + if (!result) return; + initializeWithPostMessageUri( + OriginVerifier.getPostMessageUriFromVerifiedOrigin(packageName, origin)); + } + + private Uri getPostMessageUriForTesting() { + return mPostMessageUri; + } +}
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/directactions/FindInPageDirectActionHandlerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/directactions/FindInPageDirectActionHandlerTest.java index d48b62f..7280d4478 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/directactions/FindInPageDirectActionHandlerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/directactions/FindInPageDirectActionHandlerTest.java
@@ -14,9 +14,9 @@ import static org.mockito.Mockito.when; import android.os.Bundle; -import android.support.test.filters.SmallTest; import androidx.appcompat.widget.AppCompatEditText; +import androidx.test.filters.SmallTest; import org.hamcrest.Matchers; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/directactions/GoBackDirectActionHandlerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/directactions/GoBackDirectActionHandlerTest.java index 32b4b1f..a9f56f3c 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/directactions/GoBackDirectActionHandlerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/directactions/GoBackDirectActionHandlerTest.java
@@ -8,7 +8,8 @@ import static org.junit.Assert.assertTrue; import android.os.Bundle; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.hamcrest.Matchers; import org.junit.Rule;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java index 94469fd..231a5704 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/display_cutout/DisplayCutoutControllerTest.java
@@ -11,10 +11,11 @@ import static org.mockito.Mockito.when; import android.app.Activity; -import android.support.test.filters.SmallTest; import android.view.Window; import android.view.WindowManager.LayoutParams; +import androidx.test.filters.SmallTest; + import org.junit.Assert; import org.junit.Before; import org.junit.Ignore;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPageStateUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPageStateUnitTest.java index 2cc29b9..007e3b0 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPageStateUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesPageStateUnitTest.java
@@ -6,7 +6,8 @@ import android.os.Parcel; import android.os.Parcelable; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Test;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/feed/NtpFeedSurfaceLifecycleManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/feed/NtpFeedSurfaceLifecycleManagerTest.java index c70aa77b..0b9ebc5 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/feed/NtpFeedSurfaceLifecycleManagerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/feed/NtpFeedSurfaceLifecycleManagerTest.java
@@ -19,7 +19,8 @@ import static org.chromium.chrome.browser.tab.TabSelectionType.FROM_USER; import android.app.Activity; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.After; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/FeedSliceViewTrackerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/FeedSliceViewTrackerTest.java index 860cdc04..fccf773 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/FeedSliceViewTrackerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/FeedSliceViewTrackerTest.java
@@ -13,12 +13,12 @@ import static org.mockito.Mockito.when; import android.graphics.Rect; -import android.support.test.filters.SmallTest; import android.view.View; import android.view.ViewTreeObserver; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/FeedStreamTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/FeedStreamTest.java index 027a310c..f37baed 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/FeedStreamTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/FeedStreamTest.java
@@ -18,11 +18,11 @@ import static org.mockito.Mockito.when; import android.app.Activity; -import android.support.test.filters.SmallTest; import android.util.TypedValue; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; +import androidx.test.filters.SmallTest; import com.google.protobuf.ByteString;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/NativeViewListRendererTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/NativeViewListRendererTest.java index e910343..6786bfb7 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/NativeViewListRendererTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/NativeViewListRendererTest.java
@@ -14,12 +14,12 @@ import android.app.Activity; import android.content.Context; -import android.support.test.filters.SmallTest; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; +import androidx.test.filters.SmallTest; import com.google.common.collect.ImmutableList;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/NtpListContentManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/NtpListContentManagerTest.java index 0b20544..1886ef0 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/NtpListContentManagerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/feed/v2/NtpListContentManagerTest.java
@@ -13,12 +13,13 @@ import android.app.Activity; import android.content.Context; -import android.support.test.filters.SmallTest; import android.view.View; import android.view.ViewParent; import android.widget.FrameLayout; import android.widget.LinearLayout; +import androidx.test.filters.SmallTest; + import com.google.common.collect.ImmutableList; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/homepage/HomepageManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/homepage/HomepageManagerTest.java index 58c4647..6a058d2a 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/homepage/HomepageManagerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/homepage/HomepageManagerTest.java
@@ -4,7 +4,7 @@ package org.chromium.chrome.browser.homepage; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Test;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/homepage/HomepagePolicyManagerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/homepage/HomepagePolicyManagerTest.java index 7cde7ee..c5d14b9 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/homepage/HomepagePolicyManagerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/homepage/HomepagePolicyManagerTest.java
@@ -4,9 +4,8 @@ package org.chromium.chrome.browser.homepage; -import android.support.test.filters.SmallTest; - import androidx.annotation.Nullable; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/incognito/IncognitoTabSnapshotControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/incognito/IncognitoTabSnapshotControllerTest.java index fc8522e..830965c 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/incognito/IncognitoTabSnapshotControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/incognito/IncognitoTabSnapshotControllerTest.java
@@ -25,14 +25,17 @@ import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.compositor.layouts.LayoutManagerChrome; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.browser.tabmodel.TabModelSelector; +import org.chromium.chrome.test.util.browser.Features.DisableFeatures; /** * Unit tests for IncognitoTabSnapshotController.java. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) +@DisableFeatures({ChromeFeatureList.INCOGNITO_SCREENSHOT}) public class IncognitoTabSnapshotControllerTest { private IncognitoTabSnapshotController mController; private WindowManager.LayoutParams mParams;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/quickactionsearchwidget/QuickActionSearchWidgetProviderTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/quickactionsearchwidget/QuickActionSearchWidgetProviderTest.java index 4f25fa1c..c902976 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/quickactionsearchwidget/QuickActionSearchWidgetProviderTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/quickactionsearchwidget/QuickActionSearchWidgetProviderTest.java
@@ -12,7 +12,8 @@ import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Rule;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/quickactionsearchwidget/QuickActionSearchWidgetReceiverTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/quickactionsearchwidget/QuickActionSearchWidgetReceiverTest.java index 1e3bcac..201b49d06 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/quickactionsearchwidget/QuickActionSearchWidgetReceiverTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/quickactionsearchwidget/QuickActionSearchWidgetReceiverTest.java
@@ -11,7 +11,8 @@ import android.content.Context; import android.content.Intent; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.After; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/read_later/ReadingListUtilsUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/read_later/ReadingListUtilsUnitTest.java index b380f57a..902632bf 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/read_later/ReadingListUtilsUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/read_later/ReadingListUtilsUnitTest.java
@@ -4,7 +4,7 @@ package org.chromium.chrome.browser.read_later; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Test;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceMetricsTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceMetricsTest.java index 7456fa3..71ecfad 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceMetricsTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceMetricsTest.java
@@ -9,7 +9,7 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Test;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceNotificationTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceNotificationTest.java index 8cbe951..12592a1 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceNotificationTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/search_engines/SearchEngineChoiceNotificationTest.java
@@ -15,7 +15,8 @@ import android.content.Context; import android.content.Intent; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Rule;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivityTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivityTest.java index 0535f86..af3f754 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivityTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivityTest.java
@@ -7,7 +7,7 @@ import static org.mockito.Mockito.eq; import static org.mockito.Mockito.when; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareRegistrationCoordinatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareRegistrationCoordinatorTest.java index 2d34971..c339134f 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareRegistrationCoordinatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareRegistrationCoordinatorTest.java
@@ -14,7 +14,8 @@ import android.app.Activity; import android.content.Context; import android.content.Intent; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabAttributesTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabAttributesTest.java index 06b2e48..7466ee2b 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabAttributesTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabAttributesTest.java
@@ -6,7 +6,7 @@ import static org.mockito.Mockito.when; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabStateExtractorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabStateExtractorTest.java index c305229..a0e53a13 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabStateExtractorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabStateExtractorTest.java
@@ -9,7 +9,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Rule;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabUnitTest.java index 03413e3..2b4d7dd 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/tab/TabUnitTest.java
@@ -14,7 +14,8 @@ import android.app.Activity; import android.content.Context; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Rule;
diff --git a/chrome/android/webapk/shell_apk/BUILD.gn b/chrome/android/webapk/shell_apk/BUILD.gn index 8eca4de2..a868020 100644 --- a/chrome/android/webapk/shell_apk/BUILD.gn +++ b/chrome/android/webapk/shell_apk/BUILD.gn
@@ -189,6 +189,7 @@ "res/drawable-xxxhdpi/shortcut_3_icon.png", "res/drawable-xxxhdpi/shortcut_4_icon.png", "res/drawable-xxxhdpi/splash_icon.xml", + "res/layout-v31/splash_screen_view.xml", "res/layout/choose_host_browser_dialog.xml", "res/layout/host_browser_list_item.xml", "res/mipmap-anydpi-v26/ic_launcher.xml", @@ -222,6 +223,7 @@ "res/values-mdpi/is_splash_icon_maskable_bool.xml", "res/values-v17/styles.xml", "res/values-v24/default_enabled_activity.xml", + "res/values-v31/dimens.xml", "res/values-xhdpi/is_splash_icon_maskable_bool.xml", "res/values-xxhdpi/is_splash_icon_maskable_bool.xml", "res/values-xxxhdpi/is_splash_icon_maskable_bool.xml",
diff --git a/chrome/android/webapk/shell_apk/current_version/current_version.gni b/chrome/android/webapk/shell_apk/current_version/current_version.gni index e5bc260..e795bb7 100644 --- a/chrome/android/webapk/shell_apk/current_version/current_version.gni +++ b/chrome/android/webapk/shell_apk/current_version/current_version.gni
@@ -12,4 +12,4 @@ # //chrome/android/webapk/shell_apk:webapk is changed. This includes # Java files, Android resource files and AndroidManifest.xml. Does not affect # Chrome.apk -current_shell_apk_version = 139 +current_shell_apk_version = 140
diff --git a/chrome/android/webapk/shell_apk/res/layout-v31/splash_screen_view.xml b/chrome/android/webapk/shell_apk/res/layout-v31/splash_screen_view.xml new file mode 100644 index 0000000..fc6712ee --- /dev/null +++ b/chrome/android/webapk/shell_apk/res/layout-v31/splash_screen_view.xml
@@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2021 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. --> + +<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:background="@color/background_color_non_empty"> + + <ImageView + android:id="@+id/splashscreen_icon_view" + android:layout_width="@dimen/oom_splash_icon_size" + android:layout_height="@dimen/oom_splash_icon_size" + android:layout_gravity="center" + android:src="@drawable/splash_icon"/> + +</FrameLayout>
diff --git a/chrome/android/webapk/shell_apk/res/values-v31/dimens.xml b/chrome/android/webapk/shell_apk/res/values-v31/dimens.xml new file mode 100644 index 0000000..75ff3057 --- /dev/null +++ b/chrome/android/webapk/shell_apk/res/values-v31/dimens.xml
@@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2021 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. --> + +<resources xmlns:tools="http://schemas.android.com/tools"> + <!-- The size of the icon that is displayed on the splash screen shown when the browser has + been killed because Android is Out Of Memory. This is the only time we create the splash + screen ourselves on Android S+, all other times we use the splash screen provided by the + OS. --> + <dimen name="oom_splash_icon_size">240dp</dimen> +</resources>
diff --git a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashActivity.java b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashActivity.java index 5c1cff8..2a49d91 100644 --- a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashActivity.java +++ b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashActivity.java
@@ -282,7 +282,7 @@ * * @return {@code true} if S APIs are available for use, {@code false} otherwise */ - private static boolean isAtLeastS() { + static boolean isAtLeastS() { return Build.VERSION.SDK_INT >= 31; } }
diff --git a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashUtils.java b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashUtils.java index d9d69c5..0d12c6a7 100644 --- a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashUtils.java +++ b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashUtils.java
@@ -4,6 +4,8 @@ package org.chromium.webapk.shell_apk.h2o; +import static org.chromium.webapk.shell_apk.h2o.SplashActivity.isAtLeastS; + import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; @@ -102,7 +104,9 @@ Context context, int splashWidth, int splashHeight, int maxSizeBytes) { if (splashWidth <= 0 || splashHeight <= 0) return null; - View splashView = createSplashView(context); + View splashView = isAtLeastS() ? SplashUtilsForS.createSplashView(context) + : createSplashView(context); + splashView.measure(View.MeasureSpec.makeMeasureSpec(splashWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(splashHeight, View.MeasureSpec.EXACTLY)); splashView.layout(0, 0, splashWidth, splashHeight);
diff --git a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashUtilsForS.java b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashUtilsForS.java index 834b408..7b4c64f 100644 --- a/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashUtilsForS.java +++ b/chrome/android/webapk/shell_apk/src/org/chromium/webapk/shell_apk/h2o/SplashUtilsForS.java
@@ -7,9 +7,11 @@ import static org.chromium.webapk.shell_apk.h2o.SplashUtils.createScaledBitmapAndCanvas; import android.app.Activity; +import android.content.Context; import android.graphics.Bitmap; import android.graphics.Insets; import android.graphics.Paint; +import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowInsets; @@ -131,4 +133,22 @@ iconView.draw(pair.canvas); return pair.bitmap; } + + /** + * Creates a View with a splash screen. + * + * Unlike {@link SplashUtils#createSplashView}, this splash screen will be an approximation of + * the splash screen generated by Android S+ (the main difference being that there is no app + * title). + * + * This is only used when the browser has been killed by Android for memory reasons, but the + * shell APK is still alive. When this happens we want to show a splash screen, but no longer + * have access to the one that was used to launch the shell APK (since we don't want to keep the + * ~12MB (see MAX_TRANSFER_SIZE_BYTES) image around for longer than needed). We create an + * approximation of the Android S splash screen instead (which is good enough since the user + * will never see them side by side). + */ + static View createSplashView(Context context) { + return LayoutInflater.from(context).inflate(R.layout.splash_screen_view, null); + } }
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index c7102b2..65c4869e 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -2521,25 +2521,25 @@ </message> <!-- WebApp name/icon update dialog --> - <message name="IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME" desc="The title at the top of the dialog when only the name changed."> - Review name updates + <message name="IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME" desc="The title at the top of the dialog when only the name changed." formatter_data="android_java"> + Review name update </message> - <message name="IDS_WEBAPP_UPDATE_DIALOG_TITLE_ICON" desc="The title at the top of the dialog when only the icon changed."> - Review icon updates + <message name="IDS_WEBAPP_UPDATE_DIALOG_TITLE_ICON" desc="The title at the top of the dialog when only the icon changed." formatter_data="android_java"> + Review icon update </message> - <message name="IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME_AND_ICON" desc="The title at the top of the dialog when the name and icon changed."> + <message name="IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME_AND_ICON" desc="The title at the top of the dialog when the name and icon changed." formatter_data="android_java"> Review name & icon updates </message> - <message name="IDS_WEBAPP_UPDATE_EXPLANATION" desc="The text at the top of the dialog, explaining what to do when an app changes its identity."> - If this web app is trying to trick you into thinking it is a different app, uninstall it. + <message name="IDS_WEBAPP_UPDATE_EXPLANATION" desc="The text at the top of the dialog, explaining what to do when an app changes its identity." formatter_data="android_java"> + If this web app is trying to trick you into thinking it's a different app, uninstall it. </message> - <message name="IDS_WEBAPP_UPDATE_NEGATIVE_BUTTON" desc="The text for the negative button (aka. cancel button), allowing the user to uninstall the app and report it to the abuse team."> + <message name="IDS_WEBAPP_UPDATE_NEGATIVE_BUTTON" desc="The text for the negative button (aka. cancel button), allowing the user to uninstall the app and report it to the abuse team." formatter_data="android_java"> Uninstall app </message> - <message name="IDS_UPDATE_WEBAPP_CURRENT_ICON" desc="The accessibility string explaining which icon is the current icon."> + <message name="IDS_WEBAPP_UPDATE_CURRENT_ICON" desc="The accessibility string explaining which icon is the current icon." formatter_data="android_java"> Current icon </message> - <message name="IDS_UPDATE_WEBAPP_UPDATED_ICON" desc="The accessibility string explaining which icon is the new icon."> + <message name="IDS_WEBAPP_UPDATE_NEW_ICON" desc="The accessibility string explaining which icon is the new icon." formatter_data="android_java"> New icon </message> @@ -9240,9 +9240,6 @@ <message name="IDS_NEW_INCOGNITO_WINDOW_MAC" desc="The Mac menu item for opening a new Incognito window in the file menu."> New Incognito Window </message> - <message name="IDS_BACKGROUND_APPS_MAC" desc="The Mac submenu for opening Background Apps."> - Background Apps - </message> <message name="IDS_REOPEN_CLOSED_TABS_MAC" desc="The Mac menu item reopen recently closed tabs in the file menu."> Reopen Closed Tab </message>
diff --git a/chrome/app/generated_resources_grd/IDS_UPDATE_WEBAPP_CURRENT_ICON.png.sha1 b/chrome/app/generated_resources_grd/IDS_UPDATE_WEBAPP_CURRENT_ICON.png.sha1 deleted file mode 100644 index 0860acb..0000000 --- a/chrome/app/generated_resources_grd/IDS_UPDATE_WEBAPP_CURRENT_ICON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -70a25cf918959e716c27dbc0652d1ad6b400f6d6 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_UPDATE_WEBAPP_UPDATED_ICON.png.sha1 b/chrome/app/generated_resources_grd/IDS_UPDATE_WEBAPP_UPDATED_ICON.png.sha1 deleted file mode 100644 index 0860acb..0000000 --- a/chrome/app/generated_resources_grd/IDS_UPDATE_WEBAPP_UPDATED_ICON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -70a25cf918959e716c27dbc0652d1ad6b400f6d6 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_CURRENT_ICON.png.sha1 b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_CURRENT_ICON.png.sha1 new file mode 100644 index 0000000..c8de7f9 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_CURRENT_ICON.png.sha1
@@ -0,0 +1 @@ +ddb5063b5042297019e0baef6da95639e7a2c98e \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_ICON.png.sha1 b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_ICON.png.sha1 index 046d794..5542a8e 100644 --- a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_ICON.png.sha1 +++ b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_ICON.png.sha1
@@ -1 +1 @@ -89752956d6c66d449c7d8eac2d5ac76f63acf9a3 \ No newline at end of file +89ad454bdb5eb0406b7925ee180750babae4b92a \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME.png.sha1 b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME.png.sha1 index ad7cad5..c959b1c4 100644 --- a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME.png.sha1 +++ b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME.png.sha1
@@ -1 +1 @@ -bc9dfc7931813a2e3cc421a343331e197dfb85f9 \ No newline at end of file +a31056091465cf397528d0bfad11e5f9289e1cd6 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME_AND_ICON.png.sha1 b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME_AND_ICON.png.sha1 index 0860acb..25e2be6 100644 --- a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME_AND_ICON.png.sha1 +++ b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_DIALOG_TITLE_NAME_AND_ICON.png.sha1
@@ -1 +1 @@ -70a25cf918959e716c27dbc0652d1ad6b400f6d6 \ No newline at end of file +be4ba61309944fd6b1b47aeb87edfc36a4c73d4f \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_EXPLANATION.png.sha1 b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_EXPLANATION.png.sha1 index 0860acb..25e2be6 100644 --- a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_EXPLANATION.png.sha1 +++ b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_EXPLANATION.png.sha1
@@ -1 +1 @@ -70a25cf918959e716c27dbc0652d1ad6b400f6d6 \ No newline at end of file +be4ba61309944fd6b1b47aeb87edfc36a4c73d4f \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_NEGATIVE_BUTTON.png.sha1 b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_NEGATIVE_BUTTON.png.sha1 index 0860acb..25e2be6 100644 --- a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_NEGATIVE_BUTTON.png.sha1 +++ b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_NEGATIVE_BUTTON.png.sha1
@@ -1 +1 @@ -70a25cf918959e716c27dbc0652d1ad6b400f6d6 \ No newline at end of file +be4ba61309944fd6b1b47aeb87edfc36a4c73d4f \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_NEW_ICON.png.sha1 b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_NEW_ICON.png.sha1 new file mode 100644 index 0000000..5386f2a --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_WEBAPP_UPDATE_NEW_ICON.png.sha1
@@ -0,0 +1 @@ +1aaf73b1b5324018e80a2fa4e47c4fab2f452570 \ No newline at end of file
diff --git a/chrome/browser/android/browserservices/verification/BUILD.gn b/chrome/browser/android/browserservices/verification/BUILD.gn index 1b60ee2..e6abf08 100644 --- a/chrome/browser/android/browserservices/verification/BUILD.gn +++ b/chrome/browser/android/browserservices/verification/BUILD.gn
@@ -58,3 +58,17 @@ "//third_party/junit", ] } + +java_library("junit_test_support") { + # Skip platform checks since Robolectric depends on requires_android targets. + bypass_platform_checks = true + testonly = true + sources = [ "./java/src/org/chromium/chrome/browser/browserservices/verification/OriginVerifierUnitTestSupport.java" ] + deps = [ + ":java", + "//components/embedder_support/android:util_java", + "//third_party/android_deps:robolectric_all_java", + "//third_party/androidx:androidx_browser_browser_java", + "//third_party/mockito:mockito_java", + ] +}
diff --git a/chrome/browser/android/browserservices/verification/java/src/org/chromium/chrome/browser/browserservices/verification/OriginVerifier.java b/chrome/browser/android/browserservices/verification/java/src/org/chromium/chrome/browser/browserservices/verification/OriginVerifier.java index 73c3df5..85489ff 100644 --- a/chrome/browser/android/browserservices/verification/java/src/org/chromium/chrome/browser/browserservices/verification/OriginVerifier.java +++ b/chrome/browser/android/browserservices/verification/java/src/org/chromium/chrome/browser/browserservices/verification/OriginVerifier.java
@@ -405,8 +405,9 @@ VerificationResultStore.getInstance().clearStoredRelationships(); } + // TODO: Make this not public. @NativeMethods - interface Natives { + public interface Natives { long init(OriginVerifier caller, @Nullable WebContents webContents, Profile profile); boolean verifyOrigin(long nativeOriginVerifier, OriginVerifier caller, String packageName, String signatureFingerprint, String origin, String relationship);
diff --git a/chrome/browser/android/browserservices/verification/java/src/org/chromium/chrome/browser/browserservices/verification/OriginVerifierUnitTestSupport.java b/chrome/browser/android/browserservices/verification/java/src/org/chromium/chrome/browser/browserservices/verification/OriginVerifierUnitTestSupport.java new file mode 100644 index 0000000..b93870a8 --- /dev/null +++ b/chrome/browser/android/browserservices/verification/java/src/org/chromium/chrome/browser/browserservices/verification/OriginVerifierUnitTestSupport.java
@@ -0,0 +1,57 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.browserservices.verification; + +import android.content.pm.PackageInfo; +import android.content.pm.Signature; + +import androidx.browser.customtabs.CustomTabsService; + +import org.robolectric.shadows.ShadowPackageManager; + +import org.chromium.components.embedder_support.util.Origin; + +/** + * Methods that make it easier to unit test functionality relying on {@link OriginVerifier}. + */ +public class OriginVerifierUnitTestSupport { + // A valid Android package signature - there are no requirements other than it being valid. + private static final byte[] PACKAGE_SIGNATURE = new byte[] {48, -126, 3, -121, 48, -126, 2, 111, + -96, 3, 2, 1, 2, 2, 4, 20, -104, -66, -126, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, + 1, 11, 5, 0, 48, 116, 49, 11, 48, 9, 6, 3, 85, 4, 6, 19, 2, 67, 65, 49, 16, 48, 14, 6, + 3, 85, 4, 8, 19, 7, 79, 110, 116, 97, 114, 105, 111, 49, 17, 48, 15, 6, 3, 85, 4, 7, 19, + 8, 87, 97, 116, 101, 114, 108, 111, 111, 49, 17, 48, 15, 6, 3, 85, 4, 10, 19, 8, 67, + 104, 114, 111, 109, 105, 117, 109, 49, 17, 48}; + + /** + * Registers the given package with Robolectric's ShadowPackageManager and provides it with a + * valid signature, so calls to + * {@link PackageFingerprintCalculator#getCertificateSHA256FingerprintForPackage} will not + * crash. + */ + public static void registerPackageWithSignature( + ShadowPackageManager shadowPackageManager, String packageName, int uid) { + PackageInfo info = new PackageInfo(); + info.signatures = new Signature[] {new Signature(PACKAGE_SIGNATURE)}; + info.packageName = packageName; + shadowPackageManager.addPackage(info); + shadowPackageManager.setPackagesForUid(uid, packageName); + } + + /** + * Registers the given relationship as valid, so future attempts by the OriginVerifier to + * validate that relationship will pass. + */ + public static void addVerification( + String packageName, Origin origin, @CustomTabsService.Relation int relationship) { + // A more thorough way to override test verification would be to mock out + // OriginVerifier.Natives. This would mean that most of the logic inside OriginVerifier + // would also be tested. Unfortunately OriginVerifier relies on native being loaded (it + // uses Profile.getLastUsedRegularProfile()), so even with the natives mocked out, it would + // fail to run. + + VerificationResultStore.getInstance().addOverride(packageName, origin, relationship); + } +}
diff --git a/chrome/browser/android/explore_sites/block_site_task_unittest.cc b/chrome/browser/android/explore_sites/block_site_task_unittest.cc index 82cbba5..bbd056b 100644 --- a/chrome/browser/android/explore_sites/block_site_task_unittest.cc +++ b/chrome/browser/android/explore_sites/block_site_task_unittest.cc
@@ -65,13 +65,14 @@ void ExploreSitesBlockSiteTest::PopulateActivity() { ExecuteSync(base::BindLambdaForTesting([&](sql::Database* db) { - sql::Statement insert_activity(db->GetUniqueStatement(R"( -INSERT INTO activity -(time, category_type, url) -VALUES -(12345, 1, "https://www.google.com"), -(23456, 1, "https://www.example.com/1"); - )")); + static constexpr char kActivitySql[] = + // clang-format off + "INSERT INTO activity(time, category_type, url)" + "VALUES" + "(12345, 1, 'https://www.google.com')," + "(23456, 1, 'https://www.example.com/1')"; + // clang-format on + sql::Statement insert_activity(db->GetUniqueStatement(kActivitySql)); return insert_activity.Run(); })); }
diff --git a/chrome/browser/android/explore_sites/clear_catalog_task_unittest.cc b/chrome/browser/android/explore_sites/clear_catalog_task_unittest.cc index 7be68bc..77813a9 100644 --- a/chrome/browser/android/explore_sites/clear_catalog_task_unittest.cc +++ b/chrome/browser/android/explore_sites/clear_catalog_task_unittest.cc
@@ -55,21 +55,28 @@ ExploreSitesSchema::InitMetaTable(db, &meta_table); meta_table.SetValue("current_catalog", "5678"); meta_table.SetValue("downloading_catalog", "9101112"); - sql::Statement insert(db->GetUniqueStatement(R"( -INSERT INTO categories -(category_id, version_token, type, label) -VALUES -(3, "5678", 1, "label_1"), -- current catalog -(4, "5678", 2, "label_2"); -- current catalog)")); - if (!insert.Run()) + + static constexpr char kCategoriesSql[] = + // clang-format off + "INSERT INTO categories" + "(category_id, version_token, type, label)" + "VALUES" + "(3, '5678', 1, 'label_1')," // current catalog + "(4, '5678', 2, 'label_2')"; // current catalog + // clang-format on + sql::Statement insert_categories(db->GetUniqueStatement(kCategoriesSql)); + if (!insert_categories.Run()) return false; - sql::Statement insert_sites(db->GetUniqueStatement(R"( -INSERT INTO sites -(site_id, url, category_id, title) -VALUES -(3, "https://www.example.com/1", 3, "example_1"), -(4, "https://www.example.com/2", 4, "example_2");)")); + static constexpr char kSitesSql[] = + // clang-format off + "INSERT INTO sites" + "(site_id, url, category_id, title)" + "VALUES" + "(3, 'https://www.example.com/1', 3, 'example_1')," + "(4, 'https://www.example.com/2', 4, 'example_2')"; + // clang-format on + sql::Statement insert_sites(db->GetUniqueStatement(kSitesSql)); return insert_sites.Run(); })); ASSERT_NE(std::make_pair(std::string(), std::string()),
diff --git a/chrome/browser/android/explore_sites/get_catalog_task_unittest.cc b/chrome/browser/android/explore_sites/get_catalog_task_unittest.cc index 3f26ca78..0e3f405b 100644 --- a/chrome/browser/android/explore_sites/get_catalog_task_unittest.cc +++ b/chrome/browser/android/explore_sites/get_catalog_task_unittest.cc
@@ -168,38 +168,44 @@ ExploreSitesSchema::InitMetaTable(db, &meta_table); meta_table.SetValue("current_catalog", "5678"); meta_table.DeleteKey("downloading_catalog"); - sql::Statement insert(db->GetUniqueStatement(R"( -INSERT INTO categories -(category_id, version_token, type, label, ntp_shown_count) -VALUES -(1, "1234", 1, "label_1", 5), -- older catalog -(2, "1234", 2, "label_2", 2), -- older catalog -(3, "1234", 3, "label_3", 9), -- older catalog -(4, "5678", 1, "label_1", 4), -- current catalog -(5, "5678", 2, "label_2", 6), -- current catalog -(6, "5678", 3, "label_3", 7); -- current catalog)")); - if (!insert.Run()) + static constexpr char kCategoriesSql[] = + // clang-format off + "INSERT INTO categories" + "(category_id, version_token, type, label, ntp_shown_count)" + "VALUES" + "(1, '1234', 1, 'label_1', 5)," // older catalog + "(2, '1234', 2, 'label_2', 2)," // older catalog + "(3, '1234', 3, 'label_3', 9)," // older catalog + "(4, '5678', 1, 'label_1', 4)," // current catalog + "(5, '5678', 2, 'label_2', 6)," // current catalog + "(6, '5678', 3, 'label_3', 7)"; // current catalog + // clang-format on + sql::Statement insert_categories(db->GetUniqueStatement(kCategoriesSql)); + if (!insert_categories.Run()) return false; - sql::Statement insert_sites(db->GetUniqueStatement(R"( -INSERT INTO sites -(site_id, url, category_id, title) -VALUES -(1, "https://www.example.com/1", 1, "example_old_1"), -(2, "https://www.example.com/2", 2, "example_old_2"), -(3, "https://www.example.com/1", 4, "example_1"), -(4, "https://www.example.com/2", 5, "example_2"); - )")); + static constexpr char kSitesSql[] = + // clang-format off + "INSERT INTO sites" + "(site_id, url, category_id, title)" + "VALUES" + "(1, 'https://www.example.com/1', 1, 'example_old_1')," + "(2, 'https://www.example.com/2', 2, 'example_old_2')," + "(3, 'https://www.example.com/1', 4, 'example_1')," + "(4, 'https://www.example.com/2', 5, 'example_2')"; + // clang-format on + sql::Statement insert_sites(db->GetUniqueStatement(kSitesSql)); if (!insert_sites.Run()) return false; - sql::Statement insert_activity(db->GetUniqueStatement(R"( -INSERT INTO activity -(time, category_type, url) -VALUES -(12345, 1, "https://www.example.com/1"), -(23456, 1, "https://www.example.com/1"); - )")); + static constexpr char kActivitySql[] = + // clang-format off + "INSERT INTO activity(time, category_type, url)" + "VALUES" + "(12345, 1, 'https://www.google.com')," + "(23456, 1, 'https://www.example.com/1')"; + // clang-format on + sql::Statement insert_activity(db->GetUniqueStatement(kActivitySql)); return insert_activity.Run(); })); }
diff --git a/chrome/browser/android/explore_sites/get_images_task_unittest.cc b/chrome/browser/android/explore_sites/get_images_task_unittest.cc index 90b67493..d807fcba 100644 --- a/chrome/browser/android/explore_sites/get_images_task_unittest.cc +++ b/chrome/browser/android/explore_sites/get_images_task_unittest.cc
@@ -78,24 +78,30 @@ ExploreSitesSchema::InitMetaTable(db, &meta_table); meta_table.SetValue("current_catalog", 5678); meta_table.DeleteKey("downloading_catalog"); - sql::Statement insert(db->GetUniqueStatement(R"( -INSERT INTO categories -(category_id, version_token, type, label) -VALUES -(3, "5678", 1, "label_1"), -(4, "5678", 2, "label_2");)")); - if (!insert.Run()) + + static constexpr char kCategoriesSql[] = + // clang-format off + "INSERT INTO categories" + "(category_id, version_token, type, label)" + "VALUES" + "(3, '5678', 1, 'label_1')," + "(4, '5678', 2, 'label_2')"; + // clang-format on + sql::Statement insert_categories(db->GetUniqueStatement(kCategoriesSql)); + if (!insert_categories.Run()) return false; - sql::Statement insert_sites(db->GetUniqueStatement(R"( -INSERT INTO sites -(site_id, url, category_id, title, favicon) -VALUES -(1, "https://www.example.com/1", 3, "example_1", "bytes1"), -(2, "https://www.example.com/2", 4, "example_2", "bytes2"), -(3, "https://www.example.com/3", 3, "example_3", "bytes3"), -(4, "https://www.example.com/4", 4, "example_4", "bytes4"); - )")); + static constexpr char kSitesSql[] = + // clang-format off + "INSERT INTO sites" + "(site_id, url, category_id, title, favicon)" + "VALUES" + "(1, 'https://www.example.com/1', 3, 'example_1', 'bytes1')," + "(2, 'https://www.example.com/2', 4, 'example_2', 'bytes2')," + "(3, 'https://www.example.com/3', 3, 'example_3', 'bytes3')," + "(4, 'https://www.example.com/4', 4, 'example_4', 'bytes4')"; + // clang-format on + sql::Statement insert_sites(db->GetUniqueStatement(kSitesSql)); return insert_sites.Run(); })); } @@ -120,22 +126,30 @@ ExploreSitesSchema::InitMetaTable(db, &meta_table); meta_table.SetValue(ExploreSitesSchema::kDownloadingCatalogKey, "5678"); meta_table.DeleteKey(ExploreSitesSchema::kCurrentCatalogKey); - sql::Statement insert(db->GetUniqueStatement(R"( -INSERT INTO categories -(category_id, version_token, type, label) -VALUES -(1, "XXXX", 1, "bad_1"), -(2, "XXXX", 2, "bad_2");)")); - if (!insert.Run()) + + static constexpr char kCategoriesSql[] = + // clang-format off + "INSERT INTO categories" + "(category_id, version_token, type, label)" + "VALUES" + "(1, 'XXXX', 1, 'bad_1')," + "(2, 'XXXX', 2, 'bad_2')"; + // clang-format on + sql::Statement insert_categories(db->GetUniqueStatement(kCategoriesSql)); + if (!insert_categories.Run()) return false; - sql::Statement insert_sites(db->GetUniqueStatement(R"( -INSERT INTO sites -(site_id, url, category_id, title, favicon) -VALUES -(5, "https://www.bad.com/1", 1, "bad", "bad - used unknown version"), -(6, "https://www.bad.com/2", 2, "bad", "bad - used unknown version"); - )")); + static constexpr char kSitesSql[] = + // clang-format off + "INSERT INTO sites" + "(site_id, url, category_id, title, favicon)" + "VALUES" + "(5, 'https://www.bad.com/1', 1, 'bad'," + "'bad - used unknown version')," + "(6, 'https://www.bad.com/2', 2, 'bad'," + "'bad - used unknown version')"; + // clang-format on + sql::Statement insert_sites(db->GetUniqueStatement(kSitesSql)); return insert_sites.Run(); })); } @@ -194,12 +208,14 @@ TEST_F(ExploreSitesGetImagesTaskTest, SitesExistAndBlocked) { PopulateTestingCatalog(); ExecuteSync(base::BindLambdaForTesting([&](sql::Database* db) { - sql::Statement insert(db->GetUniqueStatement(R"( -INSERT INTO site_blocklist -(url, date_removed) -VALUES -("https://www.example.com/1", 123);)")); - return insert.Run(); + static constexpr char kBlocklistSql[] = + // clang-format off + "INSERT INTO site_blocklist(url, date_removed)" + "VALUES" + "('https://www.example.com/1', 123)"; + // clang-format on + sql::Statement insert_blocklist(db->GetUniqueStatement(kBlocklistSql)); + return insert_blocklist.Run(); })); GetImagesTask task(store(), 3, 4, StoreResult()); RunTask(&task); @@ -214,14 +230,17 @@ PopulateTestingCatalog(); // Add 3 more sites to the interesting category, but limit the site max to 4. ExecuteSync(base::BindLambdaForTesting([&](sql::Database* db) { - sql::Statement insert(db->GetUniqueStatement(R"( -INSERT INTO sites -(site_id, url, category_id, title, favicon) -VALUES -(5, "https://www.example.com/5", 3, "example_5", "bytes5"), -(6, "https://www.example.com/6", 3, "example_6", "bytes6"), -(7, "https://www.example.com/7", 3, "example_7", "bytes7");)")); - return insert.Run(); + static constexpr char kSitesSql[] = + // clang-format off + "INSERT INTO sites" + "(site_id, url, category_id, title, favicon)" + "VALUES" + "(5, 'https://www.example.com/5', 3, 'example_5', 'bytes5')," + "(6, 'https://www.example.com/6', 3, 'example_6', 'bytes6')," + "(7, 'https://www.example.com/7', 3, 'example_7', 'bytes7')"; + // clang-format on + sql::Statement insert_sites(db->GetUniqueStatement(kSitesSql)); + return insert_sites.Run(); })); GetImagesTask task(store(), 3, 4, StoreResult()); RunTask(&task); @@ -232,15 +251,17 @@ TEST_F(ExploreSitesGetImagesTaskTest, SkipMissingFavicons) { PopulateTestingCatalog(); ExecuteSync(base::BindLambdaForTesting([&](sql::Database* db) { - sql::Statement insert(db->GetUniqueStatement(R"( -INSERT INTO sites -(site_id, url, category_id, title, favicon) -VALUES -(5, "https://www.example.com/5", 3, "example_5", NULL), -(6, "https://www.example.com/6", 3, "example_6", ""), -(7, "https://www.example.com/7", 3, "example_7", "bytes7"); -)")); - return insert.Run(); + static constexpr char kSitesSql[] = + // clang-format off + "INSERT INTO sites" + "(site_id, url, category_id, title, favicon)" + "VALUES" + "(5, 'https://www.example.com/5', 3, 'example_5', NULL)," + "(6, 'https://www.example.com/6', 3, 'example_6', '')," + "(7, 'https://www.example.com/7', 3, 'example_7', 'bytes7')"; + // clang-format on + sql::Statement insert_sites(db->GetUniqueStatement(kSitesSql)); + return insert_sites.Run(); })); GetImagesTask task(store(), 3, 3, StoreResult()); RunTask(&task);
diff --git a/chrome/browser/android/explore_sites/record_site_click_task_unittest.cc b/chrome/browser/android/explore_sites/record_site_click_task_unittest.cc index eb79228..92c9fe0b 100644 --- a/chrome/browser/android/explore_sites/record_site_click_task_unittest.cc +++ b/chrome/browser/android/explore_sites/record_site_click_task_unittest.cc
@@ -55,15 +55,17 @@ void ExploreSitesRecordSiteClickTest::PopulateActivity() { ExecuteSync(base::BindLambdaForTesting([&](sql::Database* db) { + static constexpr char kActivitySql[] = + // clang-format off + "INSERT INTO activity(time, category_type, url)" + "VALUES(?, 1, 'https://www.google.com')"; + // clang-format on + sql::Statement insert_activity(db->GetUniqueStatement(kActivitySql)); for (int i = 0; i < 200; i++) { - sql::Statement insert_activity(db->GetUniqueStatement(R"( -INSERT INTO activity -(time, category_type, url) -VALUES -(?, 1, "https://www.google.com"); - )")); + insert_activity.Reset(/*clear_bound_vars=*/true); insert_activity.BindInt64(0, i + 1); - insert_activity.Run(); + if (!insert_activity.Run()) + return false; } return true; }));
diff --git a/chrome/browser/android/metrics/BUILD.gn b/chrome/browser/android/metrics/BUILD.gn index 2b10ef6..a20b034 100644 --- a/chrome/browser/android/metrics/BUILD.gn +++ b/chrome/browser/android/metrics/BUILD.gn
@@ -52,6 +52,7 @@ "//content/public/test/android:content_java_test_support", "//third_party/android_support_test_runner:rules_java", "//third_party/android_support_test_runner:runner_java", + "//third_party/androidx:androidx_test_runner_java", "//third_party/junit", ] }
diff --git a/chrome/browser/android/metrics/javatests/src/org/chromium/chrome/browser/metrics/UkmTest.java b/chrome/browser/android/metrics/javatests/src/org/chromium/chrome/browser/metrics/UkmTest.java index 68579c8..a01a1185 100644 --- a/chrome/browser/android/metrics/javatests/src/org/chromium/chrome/browser/metrics/UkmTest.java +++ b/chrome/browser/android/metrics/javatests/src/org/chromium/chrome/browser/metrics/UkmTest.java
@@ -5,7 +5,8 @@ package org.chromium.chrome.browser.metrics; import android.support.test.InstrumentationRegistry; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/browser/app_controller_mac.mm b/chrome/browser/app_controller_mac.mm index db869764..5c87846 100644 --- a/chrome/browser/app_controller_mac.mm +++ b/chrome/browser/app_controller_mac.mm
@@ -35,8 +35,6 @@ #include "chrome/browser/apps/app_shim/app_shim_manager_mac.h" #include "chrome/browser/apps/app_shim/app_shim_termination_manager.h" #include "chrome/browser/apps/platform_apps/app_window_registry_util.h" -#include "chrome/browser/background/background_application_list_model.h" -#include "chrome/browser/background/background_mode_manager.h" #include "chrome/browser/browser_features.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" @@ -365,7 +363,6 @@ - (void)checkForAnyKeyWindows; - (BOOL)userWillWaitForInProgressDownloads:(int)downloadCount; - (BOOL)shouldQuitWithInProgressDownloads; -- (void)executeApplication:(id)sender; - (void)profileWasRemoved:(const base::FilePath&)profilePath forIncognito:(bool)isIncognito; - (void)setLastProfile:(Profile*)profile; @@ -1201,8 +1198,6 @@ } else if (action == @selector(toggleConfirmToQuit:)) { [self updateConfirmToQuitPrefMenuItem:static_cast<NSMenuItem*>(item)]; enable = YES; - } else if (action == @selector(executeApplication:)) { - enable = YES; } return enable; } @@ -1337,18 +1332,6 @@ } } -// Run a (background) application in a new tab. -- (void)executeApplication:(id)sender { - NSInteger tag = [sender tag]; - Profile* profile = [self lastProfile]; - DCHECK(profile); - BackgroundApplicationListModel applications(profile); - DCHECK(tag >= 0 && - tag < static_cast<int>(applications.size())); - const extensions::Extension* extension = applications.GetExtension(tag); - BackgroundModeManager::LaunchBackgroundApplication(profile, extension); -} - // Same as |-commandDispatch:|, but executes commands using a disposition // determined by the key flags. This will get called in the case where the // frontmost window is not a browser window, and the user has command-clicked @@ -1702,31 +1685,6 @@ [dockMenu addItem:item]; } - // TODO(rickcam): Mock out BackgroundApplicationListModel, then add unit tests - // which use the mock in place of the profile-initialized model. - BackgroundApplicationListModel applications(profile); - if (applications.size()) { - int position = 0; - NSString* menuStr = - l10n_util::GetNSStringWithFixup(IDS_BACKGROUND_APPS_MAC); - base::scoped_nsobject<NSMenu> appMenu( - [[NSMenu alloc] initWithTitle:menuStr]); - for (extensions::ExtensionList::const_iterator cursor = - applications.begin(); - cursor != applications.end(); ++cursor, ++position) { - DCHECK_EQ(applications.GetPosition(cursor->get()), position); - NSString* itemStr = - base::SysUTF16ToNSString(base::UTF8ToUTF16((*cursor)->name())); - base::scoped_nsobject<NSMenuItem> appItem([[NSMenuItem alloc] - initWithTitle:itemStr - action:@selector(executeApplication:) - keyEquivalent:@""]); - [appItem setTarget:self]; - [appItem setTag:position]; - [appMenu addItem:appItem]; - } - } - return dockMenu; }
diff --git a/chrome/browser/ash/crosapi/keystore_service_ash.cc b/chrome/browser/ash/crosapi/keystore_service_ash.cc index eaf29ea..2267e4f5 100644 --- a/chrome/browser/ash/crosapi/keystore_service_ash.cc +++ b/chrome/browser/ash/crosapi/keystore_service_ash.cc
@@ -466,18 +466,19 @@ //------------------------------------------------------------------------------ -void KeystoreServiceAsh::GetPublicKey( +void KeystoreServiceAsh::DEPRECATED_GetPublicKey( const std::vector<uint8_t>& certificate, mojom::KeystoreSigningAlgorithmName algorithm_name, - GetPublicKeyCallback callback) { + DEPRECATED_GetPublicKeyCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); absl::optional<std::string> name = StringFromSigningAlgorithmName(algorithm_name); if (!name) { - std::move(callback).Run(mojom::GetPublicKeyResult::NewErrorMessage( - chromeos::platform_keys::StatusToString( - chromeos::platform_keys::Status:: - kErrorAlgorithmNotPermittedByCertificate))); + std::move(callback).Run( + mojom::DEPRECATED_GetPublicKeyResult::NewErrorMessage( + chromeos::platform_keys::StatusToString( + chromeos::platform_keys::Status:: + kErrorAlgorithmNotPermittedByCertificate))); return; } @@ -485,7 +486,8 @@ chromeos::platform_keys::GetPublicKeyAndAlgorithm(certificate, name.value()); - mojom::GetPublicKeyResultPtr result_ptr = mojom::GetPublicKeyResult::New(); + mojom::DEPRECATED_GetPublicKeyResultPtr result_ptr = + mojom::DEPRECATED_GetPublicKeyResult::New(); if (output.status == chromeos::platform_keys::Status::kSuccess) { absl::optional<crosapi::mojom::KeystoreSigningAlgorithmPtr> signing_algorithm =
diff --git a/chrome/browser/ash/crosapi/keystore_service_ash.h b/chrome/browser/ash/crosapi/keystore_service_ash.h index 30fd678..e1beeb5 100644 --- a/chrome/browser/ash/crosapi/keystore_service_ash.h +++ b/chrome/browser/ash/crosapi/keystore_service_ash.h
@@ -75,9 +75,10 @@ void RemoveCertificate(mojom::KeystoreType keystore, const std::vector<uint8_t>& certificate, RemoveCertificateCallback callback) override; - void GetPublicKey(const std::vector<uint8_t>& certificate, - mojom::KeystoreSigningAlgorithmName algorithm_name, - GetPublicKeyCallback callback) override; + void DEPRECATED_GetPublicKey( + const std::vector<uint8_t>& certificate, + mojom::KeystoreSigningAlgorithmName algorithm_name, + DEPRECATED_GetPublicKeyCallback callback) override; void ExtensionGenerateKey(mojom::KeystoreType keystore, mojom::KeystoreSigningAlgorithmPtr algorithm, const absl::optional<std::string>& extension_id,
diff --git a/chrome/browser/ash/policy/dlp/data_transfer_dlp_controller_browsertest.cc b/chrome/browser/ash/policy/dlp/data_transfer_dlp_controller_browsertest.cc index 15e18e5..a66f3e69 100644 --- a/chrome/browser/ash/policy/dlp/data_transfer_dlp_controller_browsertest.cc +++ b/chrome/browser/ash/policy/dlp/data_transfer_dlp_controller_browsertest.cc
@@ -552,9 +552,13 @@ } }; -// Disabled due to flakiness: crbug.com/1220328 -IN_PROC_BROWSER_TEST_F(DataTransferDlpBlinkBrowserTest, - DISABLED_ProceedOnWarn) { +// Flaky on MSan bots: crbug.com/1230617 +#if defined(MEMORY_SANITIZER) +#define MAYBE_ProceedOnWarn DISABLED_ProceedOnWarn +#else +#define MAYBE_ProceedOnWarn ProceedOnWarn +#endif +IN_PROC_BROWSER_TEST_F(DataTransferDlpBlinkBrowserTest, MAYBE_ProceedOnWarn) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/title1.html"))); @@ -635,8 +639,13 @@ testing::Mock::VerifyAndClearExpectations(&dlp_controller); } -// Disabled due to flakiness: crbug.com/1220328 -IN_PROC_BROWSER_TEST_F(DataTransferDlpBlinkBrowserTest, DISABLED_CancelWarn) { +// Flaky on MSan bots: crbug.com/1230617 +#if defined(MEMORY_SANITIZER) +#define MAYBE_CancelWarn DISABLED_CancelWarn +#else +#define MAYBE_CancelWarn CancelWarn +#endif +IN_PROC_BROWSER_TEST_F(DataTransferDlpBlinkBrowserTest, MAYBE_CancelWarn) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/title1.html"))); @@ -719,8 +728,13 @@ } // Test case for crbug.com/1213143 -// Disabled due to flakiness: crbug.com/1219981 -IN_PROC_BROWSER_TEST_F(DataTransferDlpBlinkBrowserTest, DISABLED_Reporting) { +// Flaky on MSan bots: crbug.com/1230617 +#if defined(MEMORY_SANITIZER) +#define MAYBE_Reporting DISABLED_Reporting +#else +#define MAYBE_Reporting Reporting +#endif +IN_PROC_BROWSER_TEST_F(DataTransferDlpBlinkBrowserTest, MAYBE_Reporting) { ASSERT_TRUE(embedded_test_server()->Start()); ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("/title1.html")));
diff --git a/chrome/browser/ash/scanning/chrome_scanning_app_delegate.cc b/chrome/browser/ash/scanning/chrome_scanning_app_delegate.cc index d4d08e4..e2deef8 100644 --- a/chrome/browser/ash/scanning/chrome_scanning_app_delegate.cc +++ b/chrome/browser/ash/scanning/chrome_scanning_app_delegate.cc
@@ -15,18 +15,17 @@ #include "chrome/browser/apps/app_service/launch_utils.h" #include "chrome/browser/ash/drive/drive_integration_service.h" #include "chrome/browser/ash/file_manager/path_util.h" +#include "chrome/browser/ash/scanning/scanning_file_path_helper.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/chrome_select_file_policy.h" #include "chrome/browser/ui/web_applications/system_web_app_ui_utils.h" #include "chrome/browser/web_applications/components/web_app_id_constants.h" -#include "chromeos/strings/grit/chromeos_strings.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" -#include "ui/base/l10n/l10n_util.h" #include "ui/base/window_open_disposition.h" #include "ui/shell_dialogs/select_file_policy.h" @@ -34,10 +33,6 @@ namespace { -// "root" is appended to the user's Google Drive directory to form the -// complete path. -constexpr char kRoot[] = "root"; - // The name of the sticky settings pref. constexpr char kScanningStickySettingsPref[] = "scanning.scanning_sticky_settings"; @@ -46,8 +41,9 @@ ChromeScanningAppDelegate::ChromeScanningAppDelegate(content::WebUI* web_ui) : web_ui_(web_ui) { - my_files_path_ = file_manager::util::GetMyFilesFolderForProfile( - Profile::FromWebUI(web_ui)); + const base::FilePath my_files_path = + file_manager::util::GetMyFilesFolderForProfile( + Profile::FromWebUI(web_ui)); drive::DriveIntegrationService* integration_service = drive::DriveIntegrationServiceFactory::GetForProfile( @@ -55,9 +51,10 @@ const bool drive_available = integration_service && integration_service->is_enabled() && integration_service->IsMounted(); - google_drive_path_ = drive_available - ? integration_service->GetMountPointPath() - : base::FilePath(); + const base::FilePath google_drive_path = + drive_available ? integration_service->GetMountPointPath() + : base::FilePath(); + SetValidPaths(google_drive_path, my_files_path); } ChromeScanningAppDelegate::~ChromeScanningAppDelegate() = default; @@ -69,20 +66,11 @@ std::string ChromeScanningAppDelegate::GetBaseNameFromPath( const base::FilePath& path) { - // Returns string "Google Drive" from path "/media/fuse/drivefs-xxx/root". - if (google_drive_path_.Append(kRoot) == path) - return l10n_util::GetStringUTF8(IDS_SCANNING_APP_MY_DRIVE); - - // Returns string "My Files" from path "/home/chronos/u-xxx/MyFiles". - if (my_files_path_ == path) - return l10n_util::GetStringUTF8(IDS_SCANNING_APP_MY_FILES_SELECT_OPTION); - - // Returns base name as is from |path|. - return path.BaseName().value(); + return file_path_helper_.GetBaseNameFromPath(path); } base::FilePath ChromeScanningAppDelegate::GetMyFilesPath() { - return my_files_path_; + return file_path_helper_.GetMyFilesPath(); } std::string ChromeScanningAppDelegate::GetScanSettingsFromPrefs() { @@ -95,9 +83,7 @@ // supported. bool ChromeScanningAppDelegate::IsFilePathSupported( const base::FilePath& path_to_file) { - return !path_to_file.ReferencesParent() && - (google_drive_path_.IsParent(path_to_file) || - my_files_path_.IsParent(path_to_file)); + return file_path_helper_.IsFilePathSupported(path_to_file); } void ChromeScanningAppDelegate::OpenFilesInMediaApp( @@ -136,14 +122,10 @@ registry->RegisterStringPref(kScanningStickySettingsPref, std::string()); } -void ChromeScanningAppDelegate::SetGoogleDrivePathForTesting( - const base::FilePath& google_drive_path) { - google_drive_path_ = google_drive_path; -} - -void ChromeScanningAppDelegate::SetMyFilesPathForTesting( +void ChromeScanningAppDelegate::SetValidPaths( + const base::FilePath& google_drive_path, const base::FilePath& my_files_path) { - my_files_path_ = my_files_path; + file_path_helper_ = ScanningFilePathHelper(google_drive_path, my_files_path); } PrefService* ChromeScanningAppDelegate::GetPrefs() const {
diff --git a/chrome/browser/ash/scanning/chrome_scanning_app_delegate.h b/chrome/browser/ash/scanning/chrome_scanning_app_delegate.h index 96b6653..e68ddc3 100644 --- a/chrome/browser/ash/scanning/chrome_scanning_app_delegate.h +++ b/chrome/browser/ash/scanning/chrome_scanning_app_delegate.h
@@ -11,6 +11,7 @@ #include "ash/webui/scanning/scanning_app_delegate.h" #include "base/files/file_path.h" +#include "chrome/browser/ash/scanning/scanning_file_path_helper.h" class PrefService; @@ -51,11 +52,10 @@ // Register scan settings prefs. static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); - // Sets |google_drive_path_| for tests. - void SetGoogleDrivePathForTesting(const base::FilePath& google_drive_path); - - // Sets |my_files_path_| for tests. - void SetMyFilesPathForTesting(const base::FilePath& my_files_path); + // Initializes ScanningFilePathHelper with |google_drive_path_| and + // |my_files_path_|. + void SetValidPaths(const base::FilePath& google_drive_path, + const base::FilePath& my_files_path); private: // Returns the PrefService for the active Profile. @@ -63,9 +63,8 @@ content::WebUI* web_ui_; // Owns |this|. - // The paths to the user's My files and Google Drive directories. - base::FilePath google_drive_path_; - base::FilePath my_files_path_; + // Helper class for for file path manipulation and verification. + ScanningFilePathHelper file_path_helper_; }; } // namespace ash
diff --git a/chrome/browser/ash/scanning/chrome_scanning_app_delegate_unittest.cc b/chrome/browser/ash/scanning/chrome_scanning_app_delegate_unittest.cc index 10c3433..0160abcc 100644 --- a/chrome/browser/ash/scanning/chrome_scanning_app_delegate_unittest.cc +++ b/chrome/browser/ash/scanning/chrome_scanning_app_delegate_unittest.cc
@@ -72,8 +72,7 @@ chrome_scanning_app_delegate_ = std::make_unique<ChromeScanningAppDelegate>(web_ui_.get()); - chrome_scanning_app_delegate_->SetGoogleDrivePathForTesting(drive_path_); - chrome_scanning_app_delegate_->SetMyFilesPathForTesting(my_files_path_); + chrome_scanning_app_delegate_->SetValidPaths(drive_path_, my_files_path_); } protected: @@ -90,6 +89,11 @@ std::unique_ptr<content::WebContents> web_contents_; }; +// Validates that the correct My Files path is returned. +TEST_F(ChromeScanningAppDelegateTest, GetMyFilesPath) { + EXPECT_EQ(my_files_path_, chrome_scanning_app_delegate_->GetMyFilesPath()); +} + // Validates that the correct base name is returned from a generic filepath. TEST_F(ChromeScanningAppDelegateTest, BaseNameFromGenericPath) { EXPECT_EQ("directory", chrome_scanning_app_delegate_->GetBaseNameFromPath(
diff --git a/chrome/browser/ash/scanning/scan_service.cc b/chrome/browser/ash/scanning/scan_service.cc index 951e02b3..6da0a386 100644 --- a/chrome/browser/ash/scanning/scan_service.cc +++ b/chrome/browser/ash/scanning/scan_service.cc
@@ -26,6 +26,7 @@ #include "base/task_runner_util.h" #include "base/time/time.h" #include "chrome/browser/ash/scanning/lorgnette_scanner_manager.h" +#include "chrome/browser/ash/scanning/scanning_file_path_helper.h" #include "chrome/browser/ash/scanning/scanning_type_converters.h" #include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service.h" #include "chrome/browser/ui/ash/holding_space/holding_space_keyed_service_factory.h" @@ -160,12 +161,12 @@ base::FilePath google_drive_path, content::BrowserContext* context) : lorgnette_scanner_manager_(lorgnette_scanner_manager), - my_files_path_(std::move(my_files_path)), - google_drive_path_(std::move(google_drive_path)), context_(context), task_runner_(base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) { + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), + file_path_helper_(std::move(google_drive_path), + std::move(my_files_path)) { DCHECK(lorgnette_scanner_manager_); DCHECK(context_); } @@ -211,7 +212,7 @@ rotate_alternate_pages_ = lorgnette_scanner_manager_->IsRotateAlternate( scanner_name, settings->source_name); - if (!FilePathSupported(settings->scan_to_path)) { + if (!file_path_helper_.IsFilePathSupported(settings->scan_to_path)) { std::move(callback).Run(false); RecordScanJobResult(false, scanning::ScanJobFailureReason::kUnsupportedScanToPath, @@ -250,16 +251,6 @@ receiver_.Bind(std::move(pending_receiver)); } -void ScanService::SetGoogleDrivePathForTesting( - const base::FilePath& google_drive_path) { - google_drive_path_ = google_drive_path; -} - -void ScanService::SetMyFilesPathForTesting( - const base::FilePath& my_files_path) { - my_files_path_ = my_files_path; -} - void ScanService::Shutdown() { lorgnette_scanner_manager_ = nullptr; receiver_.reset(); @@ -429,17 +420,6 @@ num_pages_scanned_ = 0; } -bool ScanService::FilePathSupported(const base::FilePath& file_path) { - if (file_path == my_files_path_ || - (!file_path.ReferencesParent() && - (my_files_path_.IsParent(file_path) || - google_drive_path_.IsParent(file_path)))) { - return true; - } - - return false; -} - std::string ScanService::GetScannerName( const base::UnguessableToken& scanner_id) { const auto it = scanner_names_.find(scanner_id);
diff --git a/chrome/browser/ash/scanning/scan_service.h b/chrome/browser/ash/scanning/scan_service.h index fe8b244f..5011ac6 100644 --- a/chrome/browser/ash/scanning/scan_service.h +++ b/chrome/browser/ash/scanning/scan_service.h
@@ -16,6 +16,7 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/unguessable_token.h" +#include "chrome/browser/ash/scanning/scanning_file_path_helper.h" #include "chromeos/dbus/lorgnette/lorgnette_service.pb.h" #include "components/keyed_service/core/keyed_service.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -64,12 +65,6 @@ void BindInterface( mojo::PendingReceiver<scanning::mojom::ScanService> pending_receiver); - // Sets |google_drive_path_| for tests. - void SetGoogleDrivePathForTesting(const base::FilePath& google_drive_path); - - // Sets |my_files_path_| for tests. - void SetMyFilesPathForTesting(const base::FilePath& my_files_path); - private: // KeyedService: void Shutdown() override; @@ -142,11 +137,6 @@ // Unowned. Used to get scanner information and perform scans. LorgnetteScannerManager* lorgnette_scanner_manager_; - // The paths to the user's My files and Google Drive directories. Used to - // determine if a selected file path is supported. - base::FilePath my_files_path_; - base::FilePath google_drive_path_; - // The browser context from which scans are initiated. content::BrowserContext* const context_; @@ -176,6 +166,9 @@ // a user launching the Scan app and being able to interact with it. base::TimeTicks get_scanners_time_; + // Helper class for for file path manipulation and verification. + ScanningFilePathHelper file_path_helper_; + base::WeakPtrFactory<ScanService> weak_ptr_factory_{this}; };
diff --git a/chrome/browser/ash/scanning/scan_service_unittest.cc b/chrome/browser/ash/scanning/scan_service_unittest.cc index fb750a6..4b27f38 100644 --- a/chrome/browser/ash/scanning/scan_service_unittest.cc +++ b/chrome/browser/ash/scanning/scan_service_unittest.cc
@@ -267,12 +267,18 @@ const AccountId account_id(AccountId::FromUserEmail(kUserEmail)); user_manager_->AddUser(account_id); user_manager_->LoginUser(account_id); - scan_service_ = std::make_unique<ScanService>( - &fake_lorgnette_scanner_manager_, base::FilePath(), base::FilePath(), - profile_); + SetupScanService(scanned_files_mount_->GetRootPath(), + base::FilePath("/google/drive")); } - void SetUp() override { + void SetupScanService(base::FilePath my_files_path, + base::FilePath google_drive_path) { + scan_service_ = std::make_unique<ScanService>( + &fake_lorgnette_scanner_manager_, my_files_path, google_drive_path, + profile_); + if (scan_service_remote_.is_bound()) { + scan_service_remote_.reset(); + } scan_service_->BindInterface( scan_service_remote_.BindNewPipeAndPassReceiver()); } @@ -432,9 +438,9 @@ ASSERT_EQ(scanners.size(), 1u); const base::FilePath my_files_path(kMyFilesPath); - scan_service_->SetMyFilesPathForTesting(my_files_path); const mojo_ipc::ScanSettings settings = CreateScanSettings( my_files_path.Append("../../../var/log"), mojo_ipc::FileType::kPng); + SetupScanService(my_files_path, base::FilePath("/google/drive")); EXPECT_FALSE(StartScan(scanners[0]->id, settings.Clone())); } @@ -455,7 +461,6 @@ base::HistogramTester histogram_tester; int num_single_file_scans = 0u; int num_multi_file_scans = 0u; - scan_service_->SetMyFilesPathForTesting(scanned_files_mount_->GetRootPath()); for (int type_num = static_cast<int>(mojo_ipc::FileType::kMinValue); type_num <= static_cast<int>(mojo_ipc::FileType::kMaxValue); ++type_num) { @@ -509,7 +514,6 @@ // Since we're using mock time, this is deterministic. base::Time::Now().LocalExplode(&scan_time); - scan_service_->SetMyFilesPathForTesting(scanned_files_mount_->GetRootPath()); mojo_ipc::ScanSettings settings = CreateScanSettings(scanned_files_mount_->GetRootPath(), mojo_ipc::FileType::kPdf, "ADF Duplex"); @@ -534,7 +538,6 @@ auto scanners = GetScanners(); ASSERT_EQ(scanners.size(), 1u); - scan_service_->SetMyFilesPathForTesting(scanned_files_mount_->GetRootPath()); const mojo_ipc::ScanSettings settings = CreateScanSettings( scanned_files_mount_->GetRootPath(), mojo_ipc::FileType::kPng); @@ -554,7 +557,6 @@ auto scanners = GetScanners(); ASSERT_EQ(scanners.size(), 1u); - scan_service_->SetMyFilesPathForTesting(scanned_files_mount_->GetRootPath()); const mojo_ipc::ScanSettings settings = CreateScanSettings( scanned_files_mount_->GetRootPath(), mojo_ipc::FileType::kPng); @@ -603,7 +605,6 @@ // Since we're using mock time, this is deterministic. base::Time::Now().LocalExplode(&scan_time); - scan_service_->SetMyFilesPathForTesting(scanned_files_mount_->GetRootPath()); const mojo_ipc::ScanSettings settings = CreateScanSettings( scanned_files_mount_->GetRootPath(), mojo_ipc::FileType::kPng); const std::vector<base::FilePath> saved_scan_paths = @@ -641,7 +642,6 @@ auto scanners = GetScanners(); ASSERT_EQ(scanners.size(), 1u); - scan_service_->SetMyFilesPathForTesting(scanned_files_mount_->GetRootPath()); const mojo_ipc::ScanSettings settings = CreateScanSettings( scanned_files_mount_->GetRootPath(), mojo_ipc::FileType::kPng); @@ -673,7 +673,6 @@ size_t num_items_in_holding_space = 0u; ASSERT_EQ(num_items_in_holding_space, holding_space_model->items().size()); - scan_service_->SetMyFilesPathForTesting(scanned_files_mount_->GetRootPath()); for (int type_num = static_cast<int>(mojo_ipc::FileType::kMinValue); type_num <= static_cast<int>(mojo_ipc::FileType::kMaxValue); ++type_num) {
diff --git a/chrome/browser/ash/scanning/scanning_file_path_helper.cc b/chrome/browser/ash/scanning/scanning_file_path_helper.cc new file mode 100644 index 0000000..3bcb5013 --- /dev/null +++ b/chrome/browser/ash/scanning/scanning_file_path_helper.cc
@@ -0,0 +1,69 @@ +// Copyright 2021 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/ash/scanning/scanning_file_path_helper.h" + +#include <string> + +#include "base/check.h" +#include "base/files/file_path.h" +#include "chromeos/strings/grit/chromeos_strings.h" +#include "ui/base/l10n/l10n_util.h" + +namespace ash { + +namespace { + +// "root" is appended to the user's Google Drive directory to form the +// complete path. +constexpr char kRoot[] = "root"; + +} // namespace + +ScanningFilePathHelper::ScanningFilePathHelper() = default; +ScanningFilePathHelper::ScanningFilePathHelper( + const base::FilePath& google_drive_path, + const base::FilePath& my_files_path) + : google_drive_path_(google_drive_path), my_files_path_(my_files_path) {} + +ScanningFilePathHelper::ScanningFilePathHelper(ScanningFilePathHelper&& other) = + default; +ScanningFilePathHelper& ScanningFilePathHelper::operator=( + ScanningFilePathHelper&& other) = default; + +ScanningFilePathHelper::~ScanningFilePathHelper() = default; + +std::string ScanningFilePathHelper::GetBaseNameFromPath( + const base::FilePath& path) const { + DCHECK(!google_drive_path_.empty()); + DCHECK(!my_files_path_.empty()); + + // Returns string "Google Drive" from path "/media/fuse/drivefs-xxx/root". + if (google_drive_path_.Append(kRoot) == path) + return l10n_util::GetStringUTF8(IDS_SCANNING_APP_MY_DRIVE); + + // Returns string "My Files" from path "/home/chronos/u-xxx/MyFiles". + if (my_files_path_ == path) + return l10n_util::GetStringUTF8(IDS_SCANNING_APP_MY_FILES_SELECT_OPTION); + + // Returns base name as is from |path|. + return path.BaseName().value(); +} + +base::FilePath ScanningFilePathHelper::GetMyFilesPath() const { + return my_files_path_; +} + +bool ScanningFilePathHelper::IsFilePathSupported( + const base::FilePath& path_to_file) const { + DCHECK(!google_drive_path_.empty()); + DCHECK(!my_files_path_.empty()); + + return path_to_file == my_files_path_ || + (!path_to_file.ReferencesParent() && + (google_drive_path_.IsParent(path_to_file) || + my_files_path_.IsParent(path_to_file))); +} + +} // namespace ash
diff --git a/chrome/browser/ash/scanning/scanning_file_path_helper.h b/chrome/browser/ash/scanning/scanning_file_path_helper.h new file mode 100644 index 0000000..987fc828 --- /dev/null +++ b/chrome/browser/ash/scanning/scanning_file_path_helper.h
@@ -0,0 +1,47 @@ +// Copyright 2021 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_ASH_SCANNING_SCANNING_FILE_PATH_HELPER_H_ +#define CHROME_BROWSER_ASH_SCANNING_SCANNING_FILE_PATH_HELPER_H_ + +#include <string> + +#include "base/files/file_path.h" + +namespace ash { + +class ScanningFilePathHelper { + public: + ScanningFilePathHelper(); + ScanningFilePathHelper(const base::FilePath& google_drive_path, + const base::FilePath& my_files_path); + + ScanningFilePathHelper(ScanningFilePathHelper&& other); + ScanningFilePathHelper& operator=(ScanningFilePathHelper&& other); + + ~ScanningFilePathHelper(); + + // Gets the display name from |path| to show in the Scan To dropdown. Handles + // the special case of converting the Google Drive root and MyFiles directory + // to the desired display names "Google Drive" and "My Files" respectively. + std::string GetBaseNameFromPath(const base::FilePath& path) const; + + // Returns |my_file_path_|. + base::FilePath GetMyFilesPath() const; + + // Determines if |path_to_file| is a supported file path for the Files app. + // Only files under the |drive_path_| and |my_files_path_| paths are allowed + // to be opened to from the Scan app. Paths with references (i.e. "../path") + // are not supported. + bool IsFilePathSupported(const base::FilePath& path_to_file) const; + + private: + // The paths to the user's My files and Google Drive directories. + base::FilePath google_drive_path_; + base::FilePath my_files_path_; +}; + +} // namespace ash + +#endif // CHROME_BROWSER_ASH_SCANNING_SCANNING_FILE_PATH_HELPER_H_
diff --git a/chrome/browser/ash/scanning/scanning_file_path_helper_unittest.cc b/chrome/browser/ash/scanning/scanning_file_path_helper_unittest.cc new file mode 100644 index 0000000..b29b9cd7 --- /dev/null +++ b/chrome/browser/ash/scanning/scanning_file_path_helper_unittest.cc
@@ -0,0 +1,92 @@ +// Copyright 2021 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/ash/scanning/scanning_file_path_helper.h" + +#include "base/files/file_path.h" +#include "chrome/test/base/testing_browser_process.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace ash { + +namespace { + +// "root" is appended to the user's Google Drive directory to form the +// complete path. +constexpr char kRoot[] = "root"; + +} // namespace + +class ScanningFilePathHelperTest : public testing::Test { + public: + ScanningFilePathHelperTest() + : drive_path_(base::FilePath("drive/root")), + my_files_path_(base::FilePath("MyFiles")), + file_path_helper_(ScanningFilePathHelper(drive_path_, my_files_path_)) { + } + ~ScanningFilePathHelperTest() override = default; + + protected: + base::FilePath drive_path_; + base::FilePath my_files_path_; + ScanningFilePathHelper file_path_helper_; +}; + +// Validates that the correct My Files path is returned. +TEST_F(ScanningFilePathHelperTest, GetMyFilesPath) { + EXPECT_EQ(my_files_path_, file_path_helper_.GetMyFilesPath()); +} + +// Validates that the correct base name is returned from a generic filepath. +TEST_F(ScanningFilePathHelperTest, BaseNameFromGenericPath) { + EXPECT_EQ("directory", file_path_helper_.GetBaseNameFromPath( + base::FilePath("/test/directory"))); +} + +// Validates that the correct base name is returned from the file paths under +// the Google Drive root. +TEST_F(ScanningFilePathHelperTest, BaseNameFromGoogleDrivePath) { + EXPECT_EQ("Sub Folder", file_path_helper_.GetBaseNameFromPath( + drive_path_.Append(kRoot).Append("Sub Folder"))); + EXPECT_EQ("My Drive", + file_path_helper_.GetBaseNameFromPath(drive_path_.Append(kRoot))); +} + +// Validates that the correct base name is returned from file paths under the +// 'My Files' path. +TEST_F(ScanningFilePathHelperTest, BaseNameFromMyFilesPath) { + EXPECT_EQ("Sub Folder", file_path_helper_.GetBaseNameFromPath( + my_files_path_.Append("Sub Folder"))); + EXPECT_EQ("My files", file_path_helper_.GetBaseNameFromPath(my_files_path_)); +} + +// Validates that passing a file path that is a child of the MyFiles path +// returns true for IsFilePathSupported(). +TEST_F(ScanningFilePathHelperTest, FilePathSupportedMyFilesChild) { + EXPECT_TRUE(file_path_helper_.IsFilePathSupported( + my_files_path_.Append("test_file.png"))); +} + +// Validates that passing a file path that is a child of the Drive path returns +// true for IsFilePathSupported(). +TEST_F(ScanningFilePathHelperTest, FilePathSupportedGoogleDrivePathChild) { + EXPECT_TRUE(file_path_helper_.IsFilePathSupported( + drive_path_.Append("test_file.png"))); +} + +// Validates that passing an unsupported path returns false for +// IsFilePathSupported(). +TEST_F(ScanningFilePathHelperTest, FilePathNotSupported) { + ASSERT_FALSE(file_path_helper_.IsFilePathSupported( + base::FilePath("/wrong/file/path/file.png"))); +} + +// Validates that passing a file path with a reference returns false for +// IsFilePathSupported(). +TEST_F(ScanningFilePathHelperTest, FilePathReferencesNotSupported) { + ASSERT_FALSE(file_path_helper_.IsFilePathSupported( + my_files_path_.Append("../MyFiles/test_file.png"))); +} + +} // namespace ash
diff --git a/chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.cc b/chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.cc index 9aa5f8e..05b5d5ce 100644 --- a/chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.cc +++ b/chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.cc
@@ -214,6 +214,7 @@ GURL(webui::GetBitmapDataUrl(*current_wallpaper_resized.bitmap())); switch (info.type) { + case ash::WallpaperType::DAILY: case ash::WallpaperType::ONLINE: { if (info.collection_id.empty() || !info.asset_id.has_value()) { // Cannot fetch attribution info from server without collection_id and @@ -256,7 +257,6 @@ return; } - case ash::WallpaperType::DAILY: case ash::WallpaperType::DEFAULT: case ash::WallpaperType::DEVICE: case ash::WallpaperType::ONE_SHOT: @@ -335,6 +335,24 @@ controller->UpdateCustomWallpaperLayout(account_id, layout); } +void ChromePersonalizationAppUiDelegate::SetDailyRefreshCollectionId( + const std::string& collection_id) { + auto* controller = ash::WallpaperController::Get(); + controller->SetDailyRefreshCollectionId(collection_id); +} + +void ChromePersonalizationAppUiDelegate::GetDailyRefreshCollectionId( + GetDailyRefreshCollectionIdCallback callback) { + auto* controller = ash::WallpaperController::Get(); + std::move(callback).Run(controller->GetDailyRefreshCollectionId()); +} + +void ChromePersonalizationAppUiDelegate::UpdateDailyRefreshWallpaper( + UpdateDailyRefreshWallpaperCallback callback) { + auto* controller = ash::WallpaperController::Get(); + controller->UpdateDailyRefreshWallpaper(std::move(callback)); +} + void ChromePersonalizationAppUiDelegate::OnFetchCollections( FetchCollectionsCallback callback, bool success,
diff --git a/chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.h b/chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.h index cdeb84ba..375b515 100644 --- a/chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.h +++ b/chrome/browser/ash/web_applications/personalization_app/chrome_personalization_app_ui_delegate.h
@@ -85,6 +85,14 @@ void SetCustomWallpaperLayout(ash::WallpaperLayout layout) override; + void SetDailyRefreshCollectionId(const std::string& collection_id) override; + + void GetDailyRefreshCollectionId( + GetDailyRefreshCollectionIdCallback callback) override; + + void UpdateDailyRefreshWallpaper( + UpdateDailyRefreshWallpaperCallback callback) override; + private: mojo::Receiver<chromeos::personalization_app::mojom::WallpaperProvider> wallpaper_receiver_{this};
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 7cfda31c..bfb70e8e 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -2218,13 +2218,6 @@ kIntensiveWakeUpThrottlingPolicy_ForceDisable); } - // Same as above, but for the blink side of UserAgentClientHints - if (!local_state->GetBoolean( - policy::policy_prefs::kUserAgentClientHintsEnabled)) { - command_line->AppendSwitch( - blink::switches::kUserAgentClientHintDisable); - } - if (!local_state->GetBoolean( policy::policy_prefs::kTargetBlankImpliesNoOpener)) { command_line->AppendSwitch(
diff --git a/chrome/browser/chrome_notification_types.h b/chrome/browser/chrome_notification_types.h index 79276db..dbcaa4ce 100644 --- a/chrome/browser/chrome_notification_types.h +++ b/chrome/browser/chrome_notification_types.h
@@ -119,12 +119,6 @@ NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE, #endif - // Sent when the applications in the NTP app launcher have been reordered. - // The details, if not NoDetails, is the std::string ID of the extension that - // was moved. - // TODO(https://crbug.com/1174798): Remove. - NOTIFICATION_APP_LAUNCHER_REORDERED, - // Note:- // Currently only Content and Chrome define and use notifications. // Custom notifications not belonging to Content and Chrome should start
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index a55dd3f..4a6f7527 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -2284,6 +2284,8 @@ "../ash/scanning/scan_service_factory.cc", "../ash/scanning/scan_service_factory.h", "../ash/scanning/scanner_detector.h", + "../ash/scanning/scanning_file_path_helper.cc", + "../ash/scanning/scanning_file_path_helper.h", "../ash/scanning/scanning_type_converters.cc", "../ash/scanning/scanning_type_converters.h", "../ash/scanning/zeroconf_scanner_detector.cc", @@ -4039,6 +4041,7 @@ "../ash/scanning/lorgnette_scanner_manager_util_unittest.cc", "../ash/scanning/scan_service_factory_unittest.cc", "../ash/scanning/scan_service_unittest.cc", + "../ash/scanning/scanning_file_path_helper_unittest.cc", "../ash/scanning/scanning_type_converters_unittest.cc", "../ash/scanning/zeroconf_scanner_detector_unittest.cc", "../ash/settings/cros_settings_unittest.cc",
diff --git a/chrome/browser/client_hints/client_hints_browsertest.cc b/chrome/browser/client_hints/client_hints_browsertest.cc index c6f2965..9a424847 100644 --- a/chrome/browser/client_hints/client_hints_browsertest.cc +++ b/chrome/browser/client_hints/client_hints_browsertest.cc
@@ -18,7 +18,6 @@ #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/devtools/protocol/devtools_protocol_test_support.h" -#include "chrome/browser/policy/policy_test_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -32,9 +31,6 @@ #include "components/embedder_support/user_agent_utils.h" #include "components/metrics/content/subprocess_metrics_provider.h" #include "components/page_load_metrics/browser/page_load_metrics_test_waiter.h" -#include "components/policy/core/common/policy_map.h" -#include "components/policy/core/common/policy_pref_names.h" -#include "components/policy/policy_constants.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_entry.h" @@ -151,7 +147,7 @@ } // namespace -class ClientHintsBrowserTest : public policy::PolicyTest, +class ClientHintsBrowserTest : public InProcessBrowserTest, public testing::WithParamInterface<bool> { public: ClientHintsBrowserTest() @@ -2082,29 +2078,6 @@ count_client_hints_headers_seen()); } -class ClientHintsEnterprisePolicyTest : public ClientHintsBrowserTest { - void SetUpInProcessBrowserTestFixture() override { - policy::PolicyTest::SetUpInProcessBrowserTestFixture(); - policy::PolicyMap policies; - SetPolicy(&policies, policy::key::kUserAgentClientHintsEnabled, - base::Value(false)); - provider_.UpdateChromePolicy(policies); - } -}; - -// Makes sure that no client hints are sent by default when the -// "UserAgentClientHintsEnabled" enterprise polickly is set to -// false -IN_PROC_BROWSER_TEST_F(ClientHintsEnterprisePolicyTest, - ClientHintsEnterprisePolicy) { - const GURL gurl = accept_ch_without_lifetime_url(); - ui_test_utils::NavigateToURL(browser(), gurl); - // These would normally be one each - EXPECT_EQ(0u, count_user_agent_hint_headers_seen()); - EXPECT_EQ(0u, count_ua_mobile_client_hints_headers_seen()); - EXPECT_EQ(0u, count_ua_platform_client_hints_headers_seen()); -} - class ClientHintsWebHoldbackBrowserTest : public ClientHintsBrowserTest { public: ClientHintsWebHoldbackBrowserTest() : ClientHintsBrowserTest() {
diff --git a/chrome/browser/client_hints/client_hints_factory.cc b/chrome/browser/client_hints/client_hints_factory.cc index 29a8614..226b17c 100644 --- a/chrome/browser/client_hints/client_hints_factory.cc +++ b/chrome/browser/client_hints/client_hints_factory.cc
@@ -10,8 +10,6 @@ #include "components/client_hints/browser/client_hints.h" #include "components/embedder_support/user_agent_utils.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/policy/core/common/policy_pref_names.h" -#include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" namespace { @@ -42,11 +40,10 @@ KeyedService* ClientHintsFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { - PrefService* local_state = g_browser_process->local_state(); return new client_hints::ClientHints( context, g_browser_process->network_quality_tracker(), HostContentSettingsMapFactory::GetForProfile(context), - embedder_support::GetUserAgentMetadata(), local_state); + embedder_support::GetUserAgentMetadata()); } content::BrowserContext* ClientHintsFactory::GetBrowserContextToUse(
diff --git a/chrome/browser/devtools/devtools_browsertest.cc b/chrome/browser/devtools/devtools_browsertest.cc index b6688dd..16d686f 100644 --- a/chrome/browser/devtools/devtools_browsertest.cc +++ b/chrome/browser/devtools/devtools_browsertest.cc
@@ -1942,7 +1942,13 @@ RunTestWithPanel("network"); } -IN_PROC_BROWSER_TEST_F(DevToolsTest, AutoAttachToWindowOpen) { +// Very flaky on Linux only. http://crbug.com/1216219 +#if defined(OS_LINUX) +#define MAYBE_AutoAttachToWindowOpen DISABLED_AutoAttachToWindowOpen +#else +#define MAYBE_AutoAttachToWindowOpen AutoAttachToWindowOpen +#endif +IN_PROC_BROWSER_TEST_F(DevToolsTest, MAYBE_AutoAttachToWindowOpen) { OpenDevToolsWindow(kWindowOpenTestPage, false); DevToolsWindowTesting::Get(window_)->SetOpenNewWindowForPopups(true); DevToolsWindowCreationObserver observer;
diff --git a/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc b/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc index d8375e9..c17a626 100644 --- a/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc +++ b/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc
@@ -277,8 +277,8 @@ api_pki::GetPublicKey::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - std::string error = ValidateCrosapi(KeystoreService::kGetPublicKeyMinVersion, - browser_context()); + std::string error = ValidateCrosapi( + KeystoreService::kDEPRECATED_GetPublicKeyMinVersion, browser_context()); if (!error.empty()) { return RespondNow(Error(error)); } @@ -293,13 +293,13 @@ auto cb = base::BindOnce( &PlatformKeysInternalGetPublicKeyFunction::OnGetPublicKey, this); GetKeystoreService(browser_context()) - ->GetPublicKey(params->certificate, algorithm_name.value(), - std::move(cb)); + ->DEPRECATED_GetPublicKey(params->certificate, algorithm_name.value(), + std::move(cb)); return RespondLater(); } void PlatformKeysInternalGetPublicKeyFunction::OnGetPublicKey( - crosapi::mojom::GetPublicKeyResultPtr result) { + crosapi::mojom::DEPRECATED_GetPublicKeyResultPtr result) { if (result->is_error_message()) { Respond(Error(result->get_error_message())); return;
diff --git a/chrome/browser/extensions/api/platform_keys/platform_keys_api.h b/chrome/browser/extensions/api/platform_keys/platform_keys_api.h index ec59a71..5a386b4b 100644 --- a/chrome/browser/extensions/api/platform_keys/platform_keys_api.h +++ b/chrome/browser/extensions/api/platform_keys/platform_keys_api.h
@@ -52,7 +52,8 @@ ~PlatformKeysInternalGetPublicKeyFunction() override; ResponseAction Run() override; - void OnGetPublicKey(crosapi::mojom::GetPublicKeyResultPtr result_ptr); + void OnGetPublicKey( + crosapi::mojom::DEPRECATED_GetPublicKeyResultPtr result_ptr); DECLARE_EXTENSION_FUNCTION("platformKeysInternal.getPublicKey", PLATFORMKEYSINTERNAL_GETPUBLICKEY)
diff --git a/chrome/browser/extensions/api/storage/settings_sync_unittest.cc b/chrome/browser/extensions/api/storage/settings_sync_unittest.cc index ddca992..6b19761 100644 --- a/chrome/browser/extensions/api/storage/settings_sync_unittest.cc +++ b/chrome/browser/extensions/api/storage/settings_sync_unittest.cc
@@ -117,10 +117,6 @@ return absl::nullopt; } - syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override { - return syncer::SyncDataList(); - } - // Mock methods. const SettingSyncDataList& changes() { return changes_; }
diff --git a/chrome/browser/extensions/chrome_app_sorting.cc b/chrome/browser/extensions/chrome_app_sorting.cc index b14cfb3..b76576c 100644 --- a/chrome/browser/extensions/chrome_app_sorting.cc +++ b/chrome/browser/extensions/chrome_app_sorting.cc
@@ -14,8 +14,8 @@ #include "base/threading/sequenced_task_runner_handle.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/extension_sync_service.h" +#include "chrome/browser/extensions/install_tracker.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/web_applications/components/web_app_id.h" #include "chrome/browser/web_applications/web_app.h" @@ -23,9 +23,7 @@ #include "chrome/browser/web_applications/web_app_sync_bridge.h" #include "chrome/common/chrome_features.h" #include "chrome/common/extensions/extension_constants.h" -#include "content/public/browser/notification_service.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" @@ -267,11 +265,7 @@ } } } - - content::NotificationService::current()->Notify( - chrome::NOTIFICATION_APP_LAUNCHER_REORDERED, - content::Source<ChromeAppSorting>(this), - content::NotificationService::NoDetails()); + InstallTracker::Get(browser_context_)->OnAppsReordered(absl::nullopt); } void ChromeAppSorting::EnsureValidOrdinals( @@ -350,10 +344,7 @@ SyncIfNeeded(moved_extension_id); - content::NotificationService::current()->Notify( - chrome::NOTIFICATION_APP_LAUNCHER_REORDERED, - content::Source<ChromeAppSorting>(this), - content::Details<const std::string>(&moved_extension_id)); + InstallTracker::Get(browser_context_)->OnAppsReordered(moved_extension_id); } syncer::StringOrdinal ChromeAppSorting::GetAppLaunchOrdinal(
diff --git a/chrome/browser/extensions/extension_prefs_unittest.cc b/chrome/browser/extensions/extension_prefs_unittest.cc index c99a6f6..4375e9a 100644 --- a/chrome/browser/extensions/extension_prefs_unittest.cc +++ b/chrome/browser/extensions/extension_prefs_unittest.cc
@@ -14,6 +14,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/values.h" +#include "chrome/browser/extensions/install_tracker.h" #include "chrome/common/chrome_paths.h" #include "components/content_settings/core/browser/content_settings_registry.h" #include "components/content_settings/core/common/content_settings.h" @@ -68,6 +69,11 @@ void ExtensionPrefsTest::TearDown() { Verify(); + // Shutdown the InstallTracker early, which is a dependency on some + // ExtensionPrefTests (and depends on PrefService being available in + // shutdown). + InstallTracker::Get(prefs_.profile())->Shutdown(); + // Reset ExtensionPrefs, and re-verify. prefs_.ResetPrefRegistry(); RegisterPreferences(prefs_.pref_registry().get());
diff --git a/chrome/browser/extensions/extension_service_sync_unittest.cc b/chrome/browser/extensions/extension_service_sync_unittest.cc index b59853c..e0c974fb 100644 --- a/chrome/browser/extensions/extension_service_sync_unittest.cc +++ b/chrome/browser/extensions/extension_service_sync_unittest.cc
@@ -136,12 +136,11 @@ ExtensionSyncData::CreateFromSyncData(sync_data); // Start by removing any existing entry for this extension id. - syncer::SyncDataList& data_list = data(); - for (auto iter = data_list.begin(); iter != data_list.end(); ++iter) { + for (auto iter = data_.begin(); iter != data_.end(); ++iter) { std::unique_ptr<ExtensionSyncData> existing = ExtensionSyncData::CreateFromSyncData(*iter); if (existing->id() == modified->id()) { - data_list.erase(iter); + data_.erase(iter); break; } } @@ -149,7 +148,7 @@ // Now add in the new data for this id, if appropriate. if (change.change_type() == SyncChange::ACTION_ADD || change.change_type() == SyncChange::ACTION_UPDATE) { - data_list.push_back(sync_data); + data_.push_back(sync_data); } else if (change.change_type() != SyncChange::ACTION_DELETE) { ADD_FAILURE() << "Unexpected change type " << change.change_type(); } @@ -157,14 +156,6 @@ return absl::nullopt; } - // We override this to help catch the error of trying to use a single - // StatefulChangeProcessor to process changes for both extensions and apps - // sync data. - syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override { - EXPECT_EQ(expected_type_, type); - return FakeSyncChangeProcessor::GetAllSyncData(type); - } - // This is a helper to vend a wrapped version of this object suitable for // passing in to MergeDataAndStartSyncing, which takes a // std::unique_ptr<SyncChangeProcessor>, since in tests we typically don't @@ -174,9 +165,12 @@ return std::make_unique<syncer::SyncChangeProcessorWrapperForTest>(this); } - protected: + const syncer::SyncDataList& data() const { return data_; } + + private: // The expected ModelType of changes that this processor will see. - syncer::ModelType expected_type_; + const syncer::ModelType expected_type_; + syncer::SyncDataList data_; DISALLOW_COPY_AND_ASSIGN(StatefulChangeProcessor); }; @@ -1795,9 +1789,8 @@ // Get the current data from the change processors to use as the input to // the following call to MergeDataAndStartSyncing. This simulates what should // happen with sync. - syncer::SyncDataList extensions_data = - extensions_processor.GetAllSyncData(syncer::EXTENSIONS); - syncer::SyncDataList apps_data = apps_processor.GetAllSyncData(syncer::APPS); + syncer::SyncDataList extensions_data = extensions_processor.data(); + syncer::SyncDataList apps_data = apps_processor.data(); // Stop syncing, then start again. extension_sync_service()->StopSyncing(syncer::EXTENSIONS);
diff --git a/chrome/browser/extensions/install_observer.h b/chrome/browser/extensions/install_observer.h index 0185dd3..50a28aea 100644 --- a/chrome/browser/extensions/install_observer.h +++ b/chrome/browser/extensions/install_observer.h
@@ -7,6 +7,8 @@ #include <string> +#include "extensions/common/extension_id.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/image/image_skia.h" namespace extensions { @@ -62,8 +64,10 @@ // simply forwarded from the chrome::NOTIFICATIONs. virtual void OnDisabledExtensionUpdated(const Extension* extension) {} - // Called when the app list is reordered. - virtual void OnAppsReordered() {} + // Called when the app list is reordered. If |extension_id| is set, it + // indicates the extension ID that was re-ordered. + virtual void OnAppsReordered( + const absl::optional<ExtensionId>& extension_id) {} // Notifies observers that the observed object is going away. virtual void OnShutdown() {}
diff --git a/chrome/browser/extensions/install_tracker.cc b/chrome/browser/extensions/install_tracker.cc index 2f864957..d60bc72f 100644 --- a/chrome/browser/extensions/install_tracker.cc +++ b/chrome/browser/extensions/install_tracker.cc
@@ -24,14 +24,10 @@ // Prefs may be null in tests. if (prefs) { - AppSorting* sorting = ExtensionSystem::Get(browser_context)->app_sorting(); - registrar_.Add(this, - chrome::NOTIFICATION_APP_LAUNCHER_REORDERED, - content::Source<AppSorting>(sorting)); pref_change_registrar_.Init(prefs->pref_service()); pref_change_registrar_.Add( pref_names::kExtensions, - base::BindRepeating(&InstallTracker::OnAppsReordered, + base::BindRepeating(&InstallTracker::OnExtensionPrefChanged, base::Unretained(this))); } } @@ -122,8 +118,13 @@ } void InstallTracker::Shutdown() { + // Note: tests may call this method prematurely to avoid shutdown ordering + // issues. Make sure observers don't need to handle this awkward complexity by + // clearing them here and making this method idempotent. for (auto& observer : observers_) observer.OnShutdown(); + observers_.Clear(); + pref_change_registrar_.RemoveAll(); } void InstallTracker::Observe(int type, @@ -137,11 +138,6 @@ observer.OnDisabledExtensionUpdated(extension); break; } - case chrome::NOTIFICATION_APP_LAUNCHER_REORDERED: { - for (auto& observer : observers_) - observer.OnAppsReordered(); - break; - } default: NOTREACHED(); } @@ -154,9 +150,14 @@ RemoveActiveInstall(extension->id()); } -void InstallTracker::OnAppsReordered() { +void InstallTracker::OnAppsReordered( + const absl::optional<std::string>& extension_id) { for (auto& observer : observers_) - observer.OnAppsReordered(); + observer.OnAppsReordered(extension_id); +} + +void InstallTracker::OnExtensionPrefChanged() { + OnAppsReordered(absl::nullopt); } } // namespace extensions
diff --git a/chrome/browser/extensions/install_tracker.h b/chrome/browser/extensions/install_tracker.h index 02a9dd4..f3645d4 100644 --- a/chrome/browser/extensions/install_tracker.h +++ b/chrome/browser/extensions/install_tracker.h
@@ -18,6 +18,8 @@ #include "content/public/browser/notification_registrar.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" +#include "extensions/common/extension_id.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace content { class BrowserContext; @@ -71,8 +73,12 @@ // Overriddes for KeyedService. void Shutdown() override; + // Called directly by AppSorting logic when apps are re-ordered on the new tab + // page. + void OnAppsReordered(const absl::optional<ExtensionId>& extension_id); + private: - void OnAppsReordered(); + void OnExtensionPrefChanged(); // content::NotificationObserver implementation. void Observe(int type,
diff --git a/chrome/browser/image_editor/public/android/java/src/org/chromium/chrome/browser/image_editor/ImageEditorDialogCoordinator.java b/chrome/browser/image_editor/public/android/java/src/org/chromium/chrome/browser/image_editor/ImageEditorDialogCoordinator.java index 75d030c..3d907dae 100644 --- a/chrome/browser/image_editor/public/android/java/src/org/chromium/chrome/browser/image_editor/ImageEditorDialogCoordinator.java +++ b/chrome/browser/image_editor/public/android/java/src/org/chromium/chrome/browser/image_editor/ImageEditorDialogCoordinator.java
@@ -14,6 +14,6 @@ * Interface to interact with the image editor dialog. */ public interface ImageEditorDialogCoordinator { - public void launchEditor(Activity activity, Bitmap image, Tab mTab, + public void launchEditor(Activity activity, Bitmap image, Tab mTab, String shareUrl, ChromeOptionShareCallback chromeOptionShareCallback); }
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc index d4c92e2..57f161d 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc
@@ -1180,13 +1180,13 @@ feature_usage_metrics_.GetNearbyShareEnabledState()); base::UmaHistogramBoolean("Nearby.Share.EnabledStateChanged", enabled); if (enabled) { - NS_LOG(INFO) << __func__ << ": Nearby sharing enabled!"; + NS_LOG(VERBOSE) << __func__ << ": Nearby sharing enabled!"; local_device_data_manager_->Start(); contact_manager_->Start(); certificate_manager_->Start(); BindToNearbyProcess(); } else { - NS_LOG(INFO) << __func__ << ": Nearby sharing disabled!"; + NS_LOG(VERBOSE) << __func__ << ": Nearby sharing disabled!"; StopAdvertising(); StopScanning(); nearby_connections_manager_->Shutdown();
diff --git a/chrome/browser/net/errorpage_browsertest.cc b/chrome/browser/net/errorpage_browsertest.cc index e19709e..f1da904 100644 --- a/chrome/browser/net/errorpage_browsertest.cc +++ b/chrome/browser/net/errorpage_browsertest.cc
@@ -811,10 +811,9 @@ protected: void SetUpInProcessBrowserTestFixture() override { // Sets up a mock policy provider for user and device policies. - EXPECT_CALL(policy_provider_, IsInitializationComplete(testing::_)) - .WillRepeatedly(testing::Return(true)); - EXPECT_CALL(policy_provider_, IsFirstPolicyLoadComplete(testing::_)) - .WillRepeatedly(testing::Return(true)); + policy_provider_.SetDefaultReturns( + /*is_initialization_complete_return=*/true, + /*is_first_policy_load_complete_return=*/true); policy::PolicyMap policy_map; if (set_allow_dinosaur_easter_egg_) {
diff --git a/chrome/browser/net/network_context_configuration_browsertest.cc b/chrome/browser/net/network_context_configuration_browsertest.cc index 46951d7..027b2f8 100644 --- a/chrome/browser/net/network_context_configuration_browsertest.cc +++ b/chrome/browser/net/network_context_configuration_browsertest.cc
@@ -241,10 +241,9 @@ ~NetworkContextConfigurationBrowserTest() override {} void SetUpInProcessBrowserTestFixture() override { - ON_CALL(provider_, IsInitializationComplete(testing::_)) - .WillByDefault(testing::Return(true)); - ON_CALL(provider_, IsFirstPolicyLoadComplete(testing::_)) - .WillByDefault(testing::Return(true)); + provider_.SetDefaultReturns( + /*is_initialization_complete_return=*/true, + /*is_first_policy_load_complete_return=*/true); policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); }
diff --git a/chrome/browser/net/private_network_access_browsertest.cc b/chrome/browser/net/private_network_access_browsertest.cc index 4c278ff..d129c2e 100644 --- a/chrome/browser/net/private_network_access_browsertest.cc +++ b/chrome/browser/net/private_network_access_browsertest.cc
@@ -9,6 +9,8 @@ #include "base/strings/string_piece.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" +#include "base/threading/platform_thread.h" +#include "base/time/time.h" #include "chrome/browser/dom_distiller/tab_utils.h" #include "chrome/browser/dom_distiller/test_distillation_observers.h" #include "chrome/browser/extensions/extension_service.h" @@ -23,6 +25,7 @@ #include "components/dom_distiller/core/dom_distiller_switches.h" #include "components/dom_distiller/core/url_constants.h" #include "components/embedder_support/switches.h" +#include "components/metrics/content/subprocess_metrics_provider.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_features.h" #include "content/public/common/url_constants.h" @@ -125,6 +128,9 @@ // Returns a map of WebFeature to bucket count. Skips buckets with zero counts. std::map<WebFeature, int> GetAddressSpaceFeatureBucketCounts( const base::HistogramTester& tester) { + content::FetchHistogramsFromChildProcesses(); + metrics::SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); + std::map<WebFeature, int> counts; for (WebFeature feature : kAllAddressSpaceFeatures) { int count = tester.GetBucketCount(kFeatureHistogramName, feature); @@ -137,6 +143,56 @@ return counts; } +// Helper for `IsLessBucketCounts()`. +// `ASSERT_*` macros can only be used in functions that return `void`. +void AssertLe(size_t lhs, size_t rhs) { + ASSERT_LE(lhs, rhs); +} + +// Returns true if all the keys in `lhs` have lesser-than-or-equal values than +// the corresponding keys in `rhs` and `lhs != rhs`. +bool IsLessBucketCounts(const std::map<WebFeature, int>& lhs, + const std::map<WebFeature, int>& rhs) { + bool lhs_has_lesser_entry = false; + + for (const auto& entry : lhs) { + WebFeature feature = entry.first; + int count = entry.second; + + const auto it = rhs.find(feature); + if (it == rhs.end() || count > it->second) { + return false; + } + + if (count < it->second) { + lhs_has_lesser_entry = true; + } + } + + // All entries in `lhs` have a corresponding entry in `rhs`. + AssertLe(lhs.size(), rhs.size()); + + // `lhs` is less if one of its entries is strictly less than the corresponding + // `rhs` entry, or if `rhs` has some keys which `lhs` does not have. + return lhs_has_lesser_entry || lhs.size() < rhs.size(); +} + +void WaitForBucketCounts(const base::HistogramTester& histogram_tester, + const std::map<WebFeature, int>& expected) { + std::map<WebFeature, int> counts; + + while (true) { + counts = GetAddressSpaceFeatureBucketCounts(histogram_tester); + if (!IsLessBucketCounts(counts, expected)) { + break; + } + + base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(5)); + } + + EXPECT_EQ(counts, expected); +} + // Private Network Access is a web platform specification aimed at securing // requests made from public websites to the private network and localhost. // @@ -162,13 +218,6 @@ return browser()->tab_strip_model()->GetActiveWebContents(); } - bool NavigateAndFlushHistograms() { - // Commit a new navigation in order to flush UseCounters incremented during - // the last navigation to the browser process, so they are reflected in - // histograms. - return content::NavigateToURL(web_contents(), GURL("about:blank")); - } - // Never returns nullptr. The returned server is already Start()ed. // // NOTE: This is defined as a method on the test fixture instead of a free @@ -262,7 +311,6 @@ std::unique_ptr<net::EmbeddedTestServer> server = NewServer(); EXPECT_TRUE(content::NavigateToURL(web_contents(), PublicSecureURL(*server))); - EXPECT_TRUE(NavigateAndFlushHistograms()); EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); } @@ -280,7 +328,6 @@ EXPECT_TRUE(content::NavigateToURL(web_contents(), PublicSecureURL(*server))); EXPECT_TRUE(content::NavigateToURL(web_contents(), LocalSecureURL(*server))); - EXPECT_TRUE(NavigateAndFlushHistograms()); EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); } @@ -288,44 +335,46 @@ // This test verifies that when a secure context served from the public address // space loads a resource from the local network, the correct WebFeature is // use-counted. -// Disabled, as explained in https://crbug.com/1143206 IN_PROC_BROWSER_TEST_F(PrivateNetworkAccessWithFeatureDisabledBrowserTest, - DISABLED_RecordsAddressSpaceFeatureForFetch) { + RecordsAddressSpaceFeatureForFetch) { base::HistogramTester histogram_tester; std::unique_ptr<net::EmbeddedTestServer> server = NewServer(); EXPECT_TRUE(content::NavigateToURL(web_contents(), PublicSecureURL(*server))); - EXPECT_EQ(true, content::EvalJs(web_contents(), R"( - fetch("defaultresponse").then(response => response.ok) - )")); - EXPECT_TRUE(NavigateAndFlushHistograms()); + EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); - EXPECT_THAT( - GetAddressSpaceFeatureBucketCounts(histogram_tester), - ElementsAre( - Pair(WebFeature::kAddressSpacePublicSecureContextEmbeddedLocal, 1))); + EXPECT_EQ(true, content::EvalJs(web_contents(), R"( + fetch("/defaultresponse").then(response => response.ok) + )")); + + WaitForBucketCounts( + histogram_tester, + { + {WebFeature::kAddressSpacePublicSecureContextEmbeddedLocal, 1}, + }); } // This test verifies that when a non-secure context served from the public // address space loads a resource from the local network, the correct WebFeature // is use-counted. -IN_PROC_BROWSER_TEST_F( - PrivateNetworkAccessWithFeatureDisabledBrowserTest, - DISABLED_RecordsAddressSpaceFeatureForFetchInNonSecureContext) { +IN_PROC_BROWSER_TEST_F(PrivateNetworkAccessWithFeatureDisabledBrowserTest, + RecordsAddressSpaceFeatureForFetchInNonSecureContext) { base::HistogramTester histogram_tester; std::unique_ptr<net::EmbeddedTestServer> server = NewServer(); EXPECT_TRUE( content::NavigateToURL(web_contents(), PublicNonSecureURL(*server))); - EXPECT_EQ(true, content::EvalJs(web_contents(), R"( - fetch("defaultresponse").then(response => response.ok) - )")); - EXPECT_TRUE(NavigateAndFlushHistograms()); + EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); - EXPECT_THAT( - GetAddressSpaceFeatureBucketCounts(histogram_tester), - ElementsAre(Pair( - WebFeature::kAddressSpacePublicNonSecureContextEmbeddedLocal, 1))); + EXPECT_EQ(true, content::EvalJs(web_contents(), R"( + fetch("/defaultresponse").then(response => response.ok) + )")); + + WaitForBucketCounts( + histogram_tester, + { + {WebFeature::kAddressSpacePublicNonSecureContextEmbeddedLocal, 1}, + }); } // This test verifies that when the user navigates a `public` document to a @@ -355,14 +404,16 @@ EXPECT_TRUE( content::NavigateToURL(web_contents(), PublicNonSecureURL(*server))); + EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); EXPECT_TRUE(content::NavigateToURLFromRenderer(web_contents(), LocalNonSecureURL(*server))); - EXPECT_THAT( - GetAddressSpaceFeatureBucketCounts(histogram_tester), - ElementsAre(Pair( - WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1))); + WaitForBucketCounts( + histogram_tester, + { + {WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1}, + }); } // This test verifies that when a `public` document navigates itself to a @@ -377,7 +428,6 @@ EXPECT_TRUE( content::NavigateToURL(web_contents(), PublicNonSecureURL(*server))); - EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); // Navigate to a different URL with the same CSP directive. If we just tried @@ -388,10 +438,11 @@ *server, "/set-header?Content-Security-Policy: treat-as-public-address"))); - EXPECT_THAT( - GetAddressSpaceFeatureBucketCounts(histogram_tester), - ElementsAre(Pair( - WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1))); + WaitForBucketCounts( + histogram_tester, + { + {WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1}, + }); } // This test verifies that when a page embeds an empty iframe pointing to @@ -413,7 +464,6 @@ document.body.appendChild(child); }) )")); - EXPECT_TRUE(NavigateAndFlushHistograms()); EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); } @@ -428,6 +478,7 @@ EXPECT_TRUE( content::NavigateToURL(web_contents(), PublicNonSecureURL(*server))); + EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); base::StringPiece script_template = R"( new Promise(resolve => { @@ -441,12 +492,12 @@ content::EvalJs(web_contents(), content::JsReplace(script_template, LocalNonSecureURL(*server)))); - EXPECT_TRUE(NavigateAndFlushHistograms()); - EXPECT_THAT( - GetAddressSpaceFeatureBucketCounts(histogram_tester), - ElementsAre(Pair( - WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1))); + WaitForBucketCounts( + histogram_tester, + { + {WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1}, + }); } // This test verifies that when a non-secure context served from the public @@ -460,6 +511,7 @@ EXPECT_TRUE( content::NavigateToURL(web_contents(), PublicNonSecureURL(*server))); + EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); base::StringPiece script_template = R"( function addChildFrame(doc, src) { @@ -479,12 +531,12 @@ content::EvalJs(web_contents(), content::JsReplace(script_template, LocalNonSecureURL(*server)))); - EXPECT_TRUE(NavigateAndFlushHistograms()); - EXPECT_THAT( - GetAddressSpaceFeatureBucketCounts(histogram_tester), - ElementsAre(Pair( - WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1))); + WaitForBucketCounts( + histogram_tester, + { + {WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1}, + }); } // This test verifies that the right address space feature is recorded when a @@ -501,6 +553,7 @@ NonSecureURL( *server, "/private_network_access/remote-initiator-navigation.html"))); + EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); EXPECT_EQ(true, content::EvalJs(web_contents(), content::JsReplace(R"( runTest({ @@ -508,12 +561,11 @@ }); )"))); - EXPECT_TRUE(NavigateAndFlushHistograms()); - - EXPECT_THAT( - GetAddressSpaceFeatureBucketCounts(histogram_tester), - ElementsAre(Pair( - WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1))); + WaitForBucketCounts( + histogram_tester, + { + {WebFeature::kAddressSpacePublicNonSecureContextNavigatedToLocal, 1}, + }); } // This test verifies that when the initiator of a navigation is no longer @@ -538,8 +590,6 @@ }); )")); - EXPECT_TRUE(NavigateAndFlushHistograms()); - EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); } @@ -565,8 +615,6 @@ }); )")); - EXPECT_TRUE(NavigateAndFlushHistograms()); - EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); } @@ -579,15 +627,17 @@ EXPECT_TRUE( content::NavigateToURL(web_contents(), PublicNonSecureURL(*server))); - EXPECT_EQ(true, content::EvalJs(web_contents(), R"( - fetch("defaultresponse").catch(() => true) - )")); - EXPECT_TRUE(NavigateAndFlushHistograms()); + EXPECT_THAT(GetAddressSpaceFeatureBucketCounts(histogram_tester), IsEmpty()); - EXPECT_THAT( - GetAddressSpaceFeatureBucketCounts(histogram_tester), - ElementsAre(Pair( - WebFeature::kAddressSpacePublicNonSecureContextEmbeddedLocal, 1))); + EXPECT_EQ(true, content::EvalJs(web_contents(), R"( + fetch("/defaultresponse").catch(() => true) + )")); + + WaitForBucketCounts( + histogram_tester, + { + {WebFeature::kAddressSpacePublicNonSecureContextEmbeddedLocal, 1}, + }); } IN_PROC_BROWSER_TEST_F(PrivateNetworkAccessWithFeatureEnabledBrowserTest, @@ -596,7 +646,6 @@ content::DeprecationTrialURLLoaderInterceptor interceptor; EXPECT_TRUE(content::NavigateToURL(web_contents(), interceptor.EnabledUrl())); - EXPECT_TRUE(NavigateAndFlushHistograms()); EXPECT_EQ( histogram_tester.GetBucketCount(
diff --git a/chrome/browser/net/stub_resolver_config_reader_browsertest.cc b/chrome/browser/net/stub_resolver_config_reader_browsertest.cc index 0562bca..b4beb6b 100644 --- a/chrome/browser/net/stub_resolver_config_reader_browsertest.cc +++ b/chrome/browser/net/stub_resolver_config_reader_browsertest.cc
@@ -59,10 +59,9 @@ void SetUpInProcessBrowserTestFixture() override { // Normal boilerplate to setup a MockConfigurationPolicyProvider. - ON_CALL(policy_provider_, IsInitializationComplete(testing::_)) - .WillByDefault(testing::Return(true)); - ON_CALL(policy_provider_, IsFirstPolicyLoadComplete(testing::_)) - .WillByDefault(testing::Return(true)); + policy_provider_.SetDefaultReturns( + /*is_initialization_complete_return=*/true, + /*is_first_policy_load_complete_return=*/true); policy::BrowserPolicyConnector::SetPolicyProviderForTesting( &policy_provider_); }
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc index 461b6ac2..654df754 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc
@@ -1267,10 +1267,10 @@ IN_PROC_BROWSER_TEST_F( AdsPageLoadMetricsObserverBrowserTest, FrameCreatedByAdScriptNavigatedToAllowListRule_NotRecorddedAsAd) { - // Allowlist rules are only checked if there is a matching blocklist rule. + // Subdocument resources should always check allowlist rules, even if + // there is not matching blocklist rule. SetRulesetWithRules( {subresource_filter::testing::CreateSuffixRule("ad_iframe_writer.js"), - subresource_filter::testing::CreateSuffixRule("ixel.png"), subresource_filter::testing::CreateAllowlistSuffixRule("xel.png")}); base::HistogramTester histogram_tester; content::WebContents* web_contents =
diff --git a/chrome/browser/pdf/pdf_extension_test.cc b/chrome/browser/pdf/pdf_extension_test.cc index 646b7f6..bf3e0ca 100644 --- a/chrome/browser/pdf/pdf_extension_test.cc +++ b/chrome/browser/pdf/pdf_extension_test.cc
@@ -146,6 +146,18 @@ namespace { const int kNumberLoadTestParts = 10; +// `base::test::WithFeatureOverride` for `chrome_pdf::features::kPdfUnseasoned`. +// This should be the first class a test fixture inherits from. +// +// This class should be used only for tests that are identical or substantially +// identical in Pepper and Pepper-free modes. Otherwise, it makes more sense to +// define separate test fixtures for each mode. +class WithUnseasonedOverride : public base::test::WithFeatureOverride { + public: + WithUnseasonedOverride() + : base::test::WithFeatureOverride(chrome_pdf::features::kPdfUnseasoned) {} +}; + #if defined(OS_MAC) const int kDefaultKeyModifier = blink::WebInputEvent::kMetaKey; #else @@ -394,20 +406,8 @@ base::test::ScopedFeatureList feature_list_; }; -// Parameterized version of `PDFExtensionTest` for testing identical behavior -// with the unseasoned PDF feature disabled and enabled. -// -// If a behavior is specific to one of these states, consider testing with -// `PDFExtensionUnseasonedDisabledTest` or `PDFExtensionUnseasonedEnabledTest` -// instead. Tests can also be conditional on `IsParamFeatureEnabled()`, but only -// use this if the tests are almost identical. -class PDFExtensionTestWithUnseasonedOverride - : public base::test::WithFeatureOverride, - public PDFExtensionTest { - public: - PDFExtensionTestWithUnseasonedOverride() - : base::test::WithFeatureOverride(chrome_pdf::features::kPdfUnseasoned) {} -}; +class PDFExtensionTestWithUnseasonedOverride : public WithUnseasonedOverride, + public PDFExtensionTest {}; class PDFExtensionTestWithTestGuestViewManager : public PDFExtensionTestWithUnseasonedOverride { @@ -906,6 +906,9 @@ ~PDFExtensionJSTest() override = default; }; +class PDFExtensionJSTestWithUnseasonedOverride : public WithUnseasonedOverride, + public PDFExtensionJSTest {}; + IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Basic) { RunTestsInJsModule("basic_test.js", "test.pdf"); @@ -917,75 +920,81 @@ RunTestsInJsModule("basic_plugin_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Viewport) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Viewport) { RunTestsInJsModule("viewport_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Layout3) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Layout3) { RunTestsInJsModule("layout_test.js", "test-layout3.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Layout4) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Layout4) { RunTestsInJsModule("layout_test.js", "test-layout4.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Bookmark) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Bookmark) { RunTestsInJsModule("bookmarks_test.js", "test-bookmarks-with-zoom.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Navigator) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Navigator) { RunTestsInJsModule("navigator_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ParamsParser) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, ParamsParser) { RunTestsInJsModule("params_parser_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ZoomManager) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, ZoomManager) { RunTestsInJsModule("zoom_manager_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, GestureDetector) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + GestureDetector) { RunTestsInJsModule("gesture_detector_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, TouchHandling) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + TouchHandling) { RunTestsInJsModule("touch_handling_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Elements) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Elements) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("material_elements_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, DownloadControls) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + DownloadControls) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("download_controls_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Title) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Title) { RunTestsInJsModule("title_test.js", "test-title.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, WhitespaceTitle) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + WhitespaceTitle) { RunTestsInJsModule("whitespace_title_test.js", "test-whitespace-title.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, PageChange) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, PageChange) { RunTestsInJsModule("page_change_test.js", "test-bookmarks.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Metrics) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Metrics) { RunTestsInJsModule("metrics_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerPasswordDialog) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + ViewerPasswordDialog) { RunTestsInJsModule("viewer_password_dialog_test.js", "encrypted.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ArrayBufferAllocator) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + ArrayBufferAllocator) { // Run several times to see if there are issues with unloading. RunTestsInJsModule("beep_test.js", "array_buffer.pdf"); RunTestsInJsModule("beep_test.js", "array_buffer.pdf"); @@ -999,37 +1008,42 @@ RunTestsInJsModule("redirects_fail_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerToolbar) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + ViewerToolbar) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("viewer_toolbar_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerPdfSidenav) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + ViewerPdfSidenav) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("viewer_pdf_sidenav_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerThumbnailBar) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + ViewerThumbnailBar) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("viewer_thumbnail_bar_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerThumbnail) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + ViewerThumbnail) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("viewer_thumbnail_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Fullscreen) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Fullscreen) { // Use a PDF document with multiple pages, to exercise navigating between // pages. RunTestsInJsModule("fullscreen_test.js", "test-bookmarks.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerPropertiesDialog) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + ViewerPropertiesDialog) { // The properties dialog formats some values based on locale. base::test::ScopedRestoreICUDefaultLocale scoped_locale{"en_US"}; // This will apply to the new processes spawned within RunTestsInJsModule(), @@ -1038,14 +1052,15 @@ RunTestsInJsModule("viewer_properties_dialog_test.js", "document_info.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, PostMessageProxy) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + PostMessageProxy) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("post_message_proxy_test.js", "test.pdf"); } #if BUILDFLAG(IS_CHROMEOS_ASH) -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, Printing) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, Printing) { RunTestsInJsModule("printing_icon_test.js", "test.pdf"); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) @@ -1062,13 +1077,15 @@ RunTestsInJsModule("annotations_feature_enabled_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, AnnotationsToolbar) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + AnnotationsToolbar) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("annotations_toolbar_test.js", "test.pdf"); } -IN_PROC_BROWSER_TEST_F(PDFExtensionJSTest, ViewerToolbarDropdown) { +IN_PROC_BROWSER_TEST_P(PDFExtensionJSTestWithUnseasonedOverride, + ViewerToolbarDropdown) { // Although this test file does not require a PDF to be loaded, loading the // elements without loading a PDF is difficult. RunTestsInJsModule("viewer_toolbar_dropdown_test.js", "test.pdf"); @@ -3487,3 +3504,5 @@ INSTANTIATE_FEATURE_OVERRIDE_TEST_SUITE( PDFExtensionTestWithTestGuestViewManager); INSTANTIATE_FEATURE_OVERRIDE_TEST_SUITE(PDFPluginDisabledTest); +INSTANTIATE_FEATURE_OVERRIDE_TEST_SUITE( + PDFExtensionJSTestWithUnseasonedOverride);
diff --git a/chrome/browser/policy/browser_dm_token_storage_linux.h b/chrome/browser/policy/browser_dm_token_storage_linux.h index 5663767..f4983686 100644 --- a/chrome/browser/policy/browser_dm_token_storage_linux.h +++ b/chrome/browser/policy/browser_dm_token_storage_linux.h
@@ -10,7 +10,6 @@ #include <string> #include "base/gtest_prod_util.h" -#include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" @@ -22,6 +21,9 @@ class BrowserDMTokenStorageLinux : public BrowserDMTokenStorage::Delegate { public: BrowserDMTokenStorageLinux(); + BrowserDMTokenStorageLinux(const BrowserDMTokenStorageLinux&) = delete; + BrowserDMTokenStorageLinux& operator=(const BrowserDMTokenStorageLinux&) = + delete; ~BrowserDMTokenStorageLinux() override; private: @@ -48,8 +50,6 @@ FRIEND_TEST_ALL_PREFIXES(BrowserDMTokenStorageLinuxTest, InitDMTokenWithoutDirectory); FRIEND_TEST_ALL_PREFIXES(BrowserDMTokenStorageLinuxTest, SaveDMToken); - - DISALLOW_COPY_AND_ASSIGN(BrowserDMTokenStorageLinux); }; } // namespace policy
diff --git a/chrome/browser/policy/browser_dm_token_storage_mac.h b/chrome/browser/policy/browser_dm_token_storage_mac.h index 0aea069e..6fcf26ff 100644 --- a/chrome/browser/policy/browser_dm_token_storage_mac.h +++ b/chrome/browser/policy/browser_dm_token_storage_mac.h
@@ -10,7 +10,6 @@ #include <string> #include "base/gtest_prod_util.h" -#include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" @@ -22,6 +21,8 @@ class BrowserDMTokenStorageMac : public BrowserDMTokenStorage::Delegate { public: BrowserDMTokenStorageMac(); + BrowserDMTokenStorageMac(const BrowserDMTokenStorageMac&) = delete; + BrowserDMTokenStorageMac& operator=(const BrowserDMTokenStorageMac&) = delete; ~BrowserDMTokenStorageMac() override; private: @@ -45,7 +46,6 @@ FRIEND_TEST_ALL_PREFIXES(BrowserDMTokenStorageMacTest, InitDMTokenWithoutDirectory); FRIEND_TEST_ALL_PREFIXES(BrowserDMTokenStorageMacTest, SaveDMToken); - DISALLOW_COPY_AND_ASSIGN(BrowserDMTokenStorageMac); }; } // namespace policy
diff --git a/chrome/browser/policy/browser_dm_token_storage_win.h b/chrome/browser/policy/browser_dm_token_storage_win.h index 91943494..ed5f1af 100644 --- a/chrome/browser/policy/browser_dm_token_storage_win.h +++ b/chrome/browser/policy/browser_dm_token_storage_win.h
@@ -10,7 +10,6 @@ #include <string> #include "base/gtest_prod_util.h" -#include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/sequence_checker.h" @@ -22,6 +21,8 @@ class BrowserDMTokenStorageWin : public BrowserDMTokenStorage::Delegate { public: BrowserDMTokenStorageWin(); + BrowserDMTokenStorageWin(const BrowserDMTokenStorageWin&) = delete; + BrowserDMTokenStorageWin& operator=(const BrowserDMTokenStorageWin&) = delete; ~BrowserDMTokenStorageWin() override; private: @@ -45,8 +46,6 @@ FRIEND_TEST_ALL_PREFIXES(BrowserDMTokenStorageWinTest, InitDMToken); FRIEND_TEST_ALL_PREFIXES(BrowserDMTokenStorageWinTest, InitDMTokenFromBrowserLocation); - - DISALLOW_COPY_AND_ASSIGN(BrowserDMTokenStorageWin); }; } // namespace policy
diff --git a/chrome/browser/policy/browser_signin_policy_handler.h b/chrome/browser/policy/browser_signin_policy_handler.h index c223502..46c2de5 100644 --- a/chrome/browser/policy/browser_signin_policy_handler.h +++ b/chrome/browser/policy/browser_signin_policy_handler.h
@@ -6,7 +6,6 @@ #define CHROME_BROWSER_POLICY_BROWSER_SIGNIN_POLICY_HANDLER_H_ #include "base/compiler_specific.h" -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" namespace policy { @@ -24,14 +23,14 @@ class BrowserSigninPolicyHandler : public IntRangePolicyHandler { public: explicit BrowserSigninPolicyHandler(Schema chrome_schema); + BrowserSigninPolicyHandler(const BrowserSigninPolicyHandler&) = delete; + BrowserSigninPolicyHandler& operator=(const BrowserSigninPolicyHandler&) = + delete; ~BrowserSigninPolicyHandler() override; // ConfigurationPolicyHandler methods: void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override; - - private: - DISALLOW_COPY_AND_ASSIGN(BrowserSigninPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/browsing_history_policy_handler.h b/chrome/browser/policy/browsing_history_policy_handler.h index cb08f53..5d55373 100644 --- a/chrome/browser/policy/browsing_history_policy_handler.h +++ b/chrome/browser/policy/browsing_history_policy_handler.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_POLICY_BROWSING_HISTORY_POLICY_HANDLER_H_ #define CHROME_BROWSER_POLICY_BROWSING_HISTORY_POLICY_HANDLER_H_ -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; @@ -20,15 +19,15 @@ class BrowsingHistoryPolicyHandler : public TypeCheckingPolicyHandler { public: BrowsingHistoryPolicyHandler(); + BrowsingHistoryPolicyHandler(const BrowsingHistoryPolicyHandler&) = delete; + BrowsingHistoryPolicyHandler& operator=(const BrowsingHistoryPolicyHandler&) = + delete; ~BrowsingHistoryPolicyHandler() override; protected: // ConfigurationPolicyHandler: void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override; - - private: - DISALLOW_COPY_AND_ASSIGN(BrowsingHistoryPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/chrome_browser_cloud_management_register_watcher.h b/chrome/browser/policy/chrome_browser_cloud_management_register_watcher.h index 773d87a3..fb3ef29 100644 --- a/chrome/browser/policy/chrome_browser_cloud_management_register_watcher.h +++ b/chrome/browser/policy/chrome_browser_cloud_management_register_watcher.h
@@ -9,7 +9,6 @@ #include "base/callback_forward.h" #include "base/gtest_prod_util.h" -#include "base/macros.h" #include "base/run_loop.h" #include "base/time/time.h" #include "chrome/browser/ui/enterprise_startup_dialog.h" @@ -31,6 +30,10 @@ explicit ChromeBrowserCloudManagementRegisterWatcher( ChromeBrowserCloudManagementController* controller); + ChromeBrowserCloudManagementRegisterWatcher( + const ChromeBrowserCloudManagementRegisterWatcher&) = delete; + ChromeBrowserCloudManagementRegisterWatcher& operator=( + const ChromeBrowserCloudManagementRegisterWatcher&) = delete; ~ChromeBrowserCloudManagementRegisterWatcher() override; // Blocks until the chrome browser cloud management enrollment process @@ -117,8 +120,6 @@ DialogCreationCallback dialog_creation_callback_; base::Time visible_start_time_; - - DISALLOW_COPY_AND_ASSIGN(ChromeBrowserCloudManagementRegisterWatcher); }; } // namespace policy
diff --git a/chrome/browser/policy/chrome_browser_cloud_management_register_watcher_unittest.cc b/chrome/browser/policy/chrome_browser_cloud_management_register_watcher_unittest.cc index 32de97e..a20826ad 100644 --- a/chrome/browser/policy/chrome_browser_cloud_management_register_watcher_unittest.cc +++ b/chrome/browser/policy/chrome_browser_cloud_management_register_watcher_unittest.cc
@@ -8,7 +8,6 @@ #include <utility> #include "base/bind.h" -#include "base/macros.h" #include "base/test/metrics/histogram_tester.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/policy/chrome_browser_cloud_management_controller_desktop.h" @@ -42,18 +41,23 @@ std::unique_ptr<ChromeBrowserCloudManagementController::Delegate> delegate) : ChromeBrowserCloudManagementController(std::move(delegate)) {} + FakeChromeBrowserCloudManagementController( + const FakeChromeBrowserCloudManagementController&) = delete; + FakeChromeBrowserCloudManagementController& operator=( + const FakeChromeBrowserCloudManagementController&) = delete; + void FireNotification(bool succeeded) { NotifyPolicyRegisterFinished(succeeded); } - - private: - DISALLOW_COPY_AND_ASSIGN(FakeChromeBrowserCloudManagementController); }; // A mock EnterpriseStartDialog to mimic the behavior of real dialog. class MockEnterpriseStartupDialog : public EnterpriseStartupDialog { public: MockEnterpriseStartupDialog() = default; + MockEnterpriseStartupDialog(const MockEnterpriseStartupDialog&) = delete; + MockEnterpriseStartupDialog& operator=(const MockEnterpriseStartupDialog&) = + delete; ~MockEnterpriseStartupDialog() override { // |callback_| exists if we're mocking the process that dialog is dismissed // automatically. @@ -82,8 +86,6 @@ private: DialogResultCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(MockEnterpriseStartupDialog); }; } // namespace @@ -104,6 +106,10 @@ CreateEnterpriseStartupDialog, base::Unretained(this))); } + ChromeBrowserCloudManagementRegisterWatcherTest( + const ChromeBrowserCloudManagementRegisterWatcherTest&) = delete; + ChromeBrowserCloudManagementRegisterWatcherTest& operator=( + const ChromeBrowserCloudManagementRegisterWatcherTest&) = delete; protected: FakeBrowserDMTokenStorage* storage() { return &storage_; } @@ -127,8 +133,6 @@ FakeBrowserDMTokenStorage storage_; std::unique_ptr<MockEnterpriseStartupDialog> dialog_; MockEnterpriseStartupDialog* dialog_ptr_; - - DISALLOW_COPY_AND_ASSIGN(ChromeBrowserCloudManagementRegisterWatcherTest); }; TEST_F(ChromeBrowserCloudManagementRegisterWatcherTest,
diff --git a/chrome/browser/policy/cloud/chrome_browser_cloud_management_browsertest.cc b/chrome/browser/policy/cloud/chrome_browser_cloud_management_browsertest.cc index 5050e2e..6e844d0 100644 --- a/chrome/browser/policy/cloud/chrome_browser_cloud_management_browsertest.cc +++ b/chrome/browser/policy/cloud/chrome_browser_cloud_management_browsertest.cc
@@ -90,7 +90,7 @@ const char kUnenrollmentSuccessMetrics[] = "Enterprise.MachineLevelUserCloudPolicyEnrollment.UnenrollSuccess"; -std::unique_ptr<PolicyStorage> CreatePolicyStorage() { +void UpdatePolicyStorage(PolicyStorage* policy_storage) { em::CloudPolicySettings settings; em::BooleanPolicyProto* saving_browser_history_disabled = settings.mutable_savingbrowserhistorydisabled(); @@ -98,7 +98,6 @@ em::PolicyOptions::MANDATORY); saving_browser_history_disabled->set_value(true); - auto policy_storage = std::make_unique<PolicyStorage>(); policy_storage->SetPolicyPayload( dm_protocol::kChromeMachineLevelUserCloudPolicyType, settings.SerializeAsString()); @@ -107,7 +106,6 @@ settings.SerializeAsString()); policy_storage->set_robot_api_auth_code("fake_auth_code"); policy_storage->set_service_account_identity("foo@bar.com"); - return policy_storage; } ClientStorage::ClientInfo CreateTestClientInfo() { @@ -672,8 +670,8 @@ #endif void SetUpTestServer() { - test_server_ = std::make_unique<EmbeddedPolicyTestServer>( - std::make_unique<ClientStorage>(), CreatePolicyStorage()); + test_server_ = std::make_unique<EmbeddedPolicyTestServer>(); + UpdatePolicyStorage(test_server_->policy_storage()); test_server_->client_storage()->RegisterClient(CreateTestClientInfo()); } @@ -833,8 +831,8 @@ #endif void SetUpTestServer() { - test_server_ = std::make_unique<EmbeddedPolicyTestServer>( - std::make_unique<ClientStorage>(), CreatePolicyStorage()); + test_server_ = std::make_unique<EmbeddedPolicyTestServer>(); + UpdatePolicyStorage(test_server_->policy_storage()); test_server_->client_storage()->RegisterClient(CreateTestClientInfo()); }
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index 60d200d..d686bacf 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -1380,9 +1380,6 @@ { key::kIntensiveWakeUpThrottlingEnabled, policy::policy_prefs::kIntensiveWakeUpThrottlingEnabled, base::Value::Type::BOOLEAN }, - { key::kUserAgentClientHintsEnabled, - policy::policy_prefs::kUserAgentClientHintsEnabled, - base::Value::Type::BOOLEAN }, { key::kShowFullUrlsInAddressBar, omnibox::kPreventUrlElisionsInOmnibox, base::Value::Type::BOOLEAN },
diff --git a/chrome/browser/policy/default_geolocation_policy_handler.h b/chrome/browser/policy/default_geolocation_policy_handler.h index ee6df1d..b945c674b 100644 --- a/chrome/browser/policy/default_geolocation_policy_handler.h +++ b/chrome/browser/policy/default_geolocation_policy_handler.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_POLICY_DEFAULT_GEOLOCATION_POLICY_HANDLER_H_ #define CHROME_BROWSER_POLICY_DEFAULT_GEOLOCATION_POLICY_HANDLER_H_ -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; @@ -17,14 +16,15 @@ class DefaultGeolocationPolicyHandler : public IntRangePolicyHandlerBase { public: DefaultGeolocationPolicyHandler(); + DefaultGeolocationPolicyHandler(const DefaultGeolocationPolicyHandler&) = + delete; + DefaultGeolocationPolicyHandler& operator=( + const DefaultGeolocationPolicyHandler&) = delete; ~DefaultGeolocationPolicyHandler() override; // IntRangePolicyHandlerBase: void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override; - - private: - DISALLOW_COPY_AND_ASSIGN(DefaultGeolocationPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/developer_tools_policy_handler.h b/chrome/browser/policy/developer_tools_policy_handler.h index 6ea42a4a..481ec29 100644 --- a/chrome/browser/policy/developer_tools_policy_handler.h +++ b/chrome/browser/policy/developer_tools_policy_handler.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_POLICY_DEVELOPER_TOOLS_POLICY_HANDLER_H_ #define CHROME_BROWSER_POLICY_DEVELOPER_TOOLS_POLICY_HANDLER_H_ -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" class PrefService; @@ -22,6 +21,9 @@ class DeveloperToolsPolicyHandler : public ConfigurationPolicyHandler { public: DeveloperToolsPolicyHandler(); + DeveloperToolsPolicyHandler(const DeveloperToolsPolicyHandler&) = delete; + DeveloperToolsPolicyHandler& operator=(const DeveloperToolsPolicyHandler&) = + delete; ~DeveloperToolsPolicyHandler() override; // Developer tools availability as set by policy. The values must match the @@ -64,9 +66,6 @@ static Availability GetMostRestrictiveAvailability( Availability availability_1, Availability availability_2); - - private: - DISALLOW_COPY_AND_ASSIGN(DeveloperToolsPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/device_account_initializer.h b/chrome/browser/policy/device_account_initializer.h index 9ae910e..8e2a6053 100644 --- a/chrome/browser/policy/device_account_initializer.h +++ b/chrome/browser/policy/device_account_initializer.h
@@ -11,7 +11,6 @@ #include "chrome/browser/policy/enrollment_status.h" #include "base/compiler_specific.h" -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" @@ -66,6 +65,8 @@ }; DeviceAccountInitializer(CloudPolicyClient* client, Delegate* delegate); + DeviceAccountInitializer(const DeviceAccountInitializer&) = delete; + DeviceAccountInitializer& operator=(const DeviceAccountInitializer&) = delete; ~DeviceAccountInitializer() override; // Starts process that downloads OAuth2 auth code and exchanges it to OAuth2 @@ -117,7 +118,6 @@ std::string robot_refresh_token_; base::WeakPtrFactory<DeviceAccountInitializer> weak_ptr_factory_{this}; - DISALLOW_COPY_AND_ASSIGN(DeviceAccountInitializer); }; } // namespace policy
diff --git a/chrome/browser/policy/device_management_service_configuration.h b/chrome/browser/policy/device_management_service_configuration.h index 176de27..3207d78 100644 --- a/chrome/browser/policy/device_management_service_configuration.h +++ b/chrome/browser/policy/device_management_service_configuration.h
@@ -8,7 +8,6 @@ #include <string> #include "base/compiler_specific.h" -#include "base/macros.h" #include "components/policy/core/common/cloud/device_management_service.h" namespace content { @@ -26,6 +25,10 @@ const std::string& dm_server_url, const std::string& realtime_reporting_server_url, const std::string& encrypted_reporting_server_url); + DeviceManagementServiceConfiguration( + const DeviceManagementServiceConfiguration&) = delete; + DeviceManagementServiceConfiguration& operator=( + const DeviceManagementServiceConfiguration&) = delete; ~DeviceManagementServiceConfiguration() override; std::string GetDMServerUrl() const override; @@ -40,8 +43,6 @@ const std::string dm_server_url_; const std::string realtime_reporting_server_url_; const std::string encrypted_reporting_server_url_; - - DISALLOW_COPY_AND_ASSIGN(DeviceManagementServiceConfiguration); }; } // namespace policy
diff --git a/chrome/browser/policy/file_selection_dialogs_policy_handler.h b/chrome/browser/policy/file_selection_dialogs_policy_handler.h index dbe333b..8c709cc9 100644 --- a/chrome/browser/policy/file_selection_dialogs_policy_handler.h +++ b/chrome/browser/policy/file_selection_dialogs_policy_handler.h
@@ -6,7 +6,6 @@ #define CHROME_BROWSER_POLICY_FILE_SELECTION_DIALOGS_POLICY_HANDLER_H_ #include "base/compiler_specific.h" -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" namespace policy { @@ -15,14 +14,15 @@ class FileSelectionDialogsPolicyHandler : public TypeCheckingPolicyHandler { public: FileSelectionDialogsPolicyHandler(); + FileSelectionDialogsPolicyHandler(const FileSelectionDialogsPolicyHandler&) = + delete; + FileSelectionDialogsPolicyHandler& operator=( + const FileSelectionDialogsPolicyHandler&) = delete; ~FileSelectionDialogsPolicyHandler() override; // ConfigurationPolicyHandler methods: void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override; - - private: - DISALLOW_COPY_AND_ASSIGN(FileSelectionDialogsPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/homepage_location_policy_handler.h b/chrome/browser/policy/homepage_location_policy_handler.h index 3acf4f8..70e8b9d 100644 --- a/chrome/browser/policy/homepage_location_policy_handler.h +++ b/chrome/browser/policy/homepage_location_policy_handler.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_POLICY_HOMEPAGE_LOCATION_POLICY_HANDLER_H_ #define CHROME_BROWSER_POLICY_HOMEPAGE_LOCATION_POLICY_HANDLER_H_ -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; @@ -21,6 +20,9 @@ class HomepageLocationPolicyHandler : public TypeCheckingPolicyHandler { public: HomepageLocationPolicyHandler(); + HomepageLocationPolicyHandler(const HomepageLocationPolicyHandler&) = delete; + HomepageLocationPolicyHandler& operator=( + const HomepageLocationPolicyHandler&) = delete; ~HomepageLocationPolicyHandler() override; // ConfigurationPolicyHandler: @@ -29,9 +31,6 @@ void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override; - - private: - DISALLOW_COPY_AND_ASSIGN(HomepageLocationPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/javascript_policy_handler.h b/chrome/browser/policy/javascript_policy_handler.h index 8b1c6c0..d66d544 100644 --- a/chrome/browser/policy/javascript_policy_handler.h +++ b/chrome/browser/policy/javascript_policy_handler.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_POLICY_JAVASCRIPT_POLICY_HANDLER_H_ #define CHROME_BROWSER_POLICY_JAVASCRIPT_POLICY_HANDLER_H_ -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; @@ -19,6 +18,8 @@ class JavascriptPolicyHandler : public ConfigurationPolicyHandler { public: JavascriptPolicyHandler(); + JavascriptPolicyHandler(const JavascriptPolicyHandler&) = delete; + JavascriptPolicyHandler& operator=(const JavascriptPolicyHandler&) = delete; ~JavascriptPolicyHandler() override; // ConfigurationPolicyHandler methods: @@ -26,9 +27,6 @@ PolicyErrorMap* errors) override; void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override; - - private: - DISALLOW_COPY_AND_ASSIGN(JavascriptPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/local_sync_policy_handler.h b/chrome/browser/policy/local_sync_policy_handler.h index 99e9802..dd8adef 100644 --- a/chrome/browser/policy/local_sync_policy_handler.h +++ b/chrome/browser/policy/local_sync_policy_handler.h
@@ -6,7 +6,6 @@ #define CHROME_BROWSER_POLICY_LOCAL_SYNC_POLICY_HANDLER_H_ #include "base/compiler_specific.h" -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" namespace policy { @@ -15,14 +14,13 @@ class LocalSyncPolicyHandler : public TypeCheckingPolicyHandler { public: LocalSyncPolicyHandler(); + LocalSyncPolicyHandler(const LocalSyncPolicyHandler&) = delete; + LocalSyncPolicyHandler& operator=(const LocalSyncPolicyHandler&) = delete; ~LocalSyncPolicyHandler() override; // ConfigurationPolicyHandler methods: void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override; - - private: - DISALLOW_COPY_AND_ASSIGN(LocalSyncPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/login_policy_test_base_browsertest.cc b/chrome/browser/policy/login_policy_test_base_browsertest.cc index f288798..a25a97b 100644 --- a/chrome/browser/policy/login_policy_test_base_browsertest.cc +++ b/chrome/browser/policy/login_policy_test_base_browsertest.cc
@@ -161,6 +161,10 @@ class StartupBrowserWindowLaunchSuppressedTest : public LoginPolicyTestBase { public: StartupBrowserWindowLaunchSuppressedTest() = default; + StartupBrowserWindowLaunchSuppressedTest( + const StartupBrowserWindowLaunchSuppressedTest&) = delete; + StartupBrowserWindowLaunchSuppressedTest& operator=( + const StartupBrowserWindowLaunchSuppressedTest&) = delete; void SetUpPolicy(bool enabled) { std::unique_ptr<base::DictionaryValue> policy = @@ -180,9 +184,6 @@ ASSERT_EQ(count, chrome::GetBrowserCount(profile)); } - - private: - DISALLOW_COPY_AND_ASSIGN(StartupBrowserWindowLaunchSuppressedTest); }; // Test that the browser window is not launched when @@ -204,9 +205,10 @@ class PrimaryUserPoliciesProxiedTest : public LoginPolicyTestBase { public: PrimaryUserPoliciesProxiedTest() = default; - - private: - DISALLOW_COPY_AND_ASSIGN(PrimaryUserPoliciesProxiedTest); + PrimaryUserPoliciesProxiedTest(const PrimaryUserPoliciesProxiedTest&) = + delete; + PrimaryUserPoliciesProxiedTest& operator=( + const PrimaryUserPoliciesProxiedTest&) = delete; }; IN_PROC_BROWSER_TEST_F(PrimaryUserPoliciesProxiedTest,
diff --git a/chrome/browser/policy/network_prediction_policy_handler.h b/chrome/browser/policy/network_prediction_policy_handler.h index af6671f..53671e2 100644 --- a/chrome/browser/policy/network_prediction_policy_handler.h +++ b/chrome/browser/policy/network_prediction_policy_handler.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_POLICY_NETWORK_PREDICTION_POLICY_HANDLER_H_ #define CHROME_BROWSER_POLICY_NETWORK_PREDICTION_POLICY_HANDLER_H_ -#include "base/macros.h" #include "components/policy/core/browser/configuration_policy_handler.h" class PrefValueMap; @@ -19,6 +18,10 @@ class NetworkPredictionPolicyHandler : public ConfigurationPolicyHandler { public: NetworkPredictionPolicyHandler(); + NetworkPredictionPolicyHandler(const NetworkPredictionPolicyHandler&) = + delete; + NetworkPredictionPolicyHandler& operator=( + const NetworkPredictionPolicyHandler&) = delete; ~NetworkPredictionPolicyHandler() override; // ConfigurationPolicyHandler methods: @@ -26,9 +29,6 @@ PolicyErrorMap* errors) override; void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override; - - private: - DISALLOW_COPY_AND_ASSIGN(NetworkPredictionPolicyHandler); }; } // namespace policy
diff --git a/chrome/browser/policy/policy_initialization_browsertest.cc b/chrome/browser/policy/policy_initialization_browsertest.cc index 4da058f..7cf64fe 100644 --- a/chrome/browser/policy/policy_initialization_browsertest.cc +++ b/chrome/browser/policy/policy_initialization_browsertest.cc
@@ -5,7 +5,6 @@ #include <memory> #include <string> -#include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" @@ -41,23 +40,30 @@ class ChromeBrowserMainExtraPartsPolicyValueChecker : public ChromeBrowserMainExtraParts { public: - ChromeBrowserMainExtraPartsPolicyValueChecker() {} + ChromeBrowserMainExtraPartsPolicyValueChecker() = default; + ChromeBrowserMainExtraPartsPolicyValueChecker( + const ChromeBrowserMainExtraPartsPolicyValueChecker&) = delete; + ChromeBrowserMainExtraPartsPolicyValueChecker& operator=( + const ChromeBrowserMainExtraPartsPolicyValueChecker&) = delete; // ChromeBrowserMainExtraParts void PreCreateThreads() override { VerifyLocalState(); } void PreBrowserStart() override { VerifyLocalState(); } void PreMainMessageLoopRun() override { VerifyLocalState(); } - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeBrowserMainExtraPartsPolicyValueChecker); }; } // namespace // Test if the policy value can be read from the pref properly on Windows. class PolicyInitializationBrowserTest : public InProcessBrowserTest { + public: + PolicyInitializationBrowserTest(const PolicyInitializationBrowserTest&) = + delete; + PolicyInitializationBrowserTest& operator=( + const PolicyInitializationBrowserTest&) = delete; + protected: - PolicyInitializationBrowserTest() {} + PolicyInitializationBrowserTest() = default; // content::BrowserTestBase: void SetUpInProcessBrowserTestFixture() override { @@ -88,8 +94,6 @@ // This test hasn't supported other platform yet. void SetUpPlatformPolicyValue() {} #endif - - DISALLOW_COPY_AND_ASSIGN(PolicyInitializationBrowserTest); }; #if defined(OS_WIN)
diff --git a/chrome/browser/policy/policy_network_browsertest.cc b/chrome/browser/policy/policy_network_browsertest.cc index efec0c6..8f37fca9 100644 --- a/chrome/browser/policy/policy_network_browsertest.cc +++ b/chrome/browser/policy/policy_network_browsertest.cc
@@ -5,7 +5,6 @@ #include "base/bind.h" #include "base/command_line.h" #include "base/feature_list.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" @@ -143,6 +142,9 @@ class QuicAllowedPolicyTestBase : public QuicTestBase { public: QuicAllowedPolicyTestBase() : QuicTestBase() {} + QuicAllowedPolicyTestBase(const QuicAllowedPolicyTestBase&) = delete; + QuicAllowedPolicyTestBase& operator=(const QuicAllowedPolicyTestBase&) = + delete; protected: void SetUpInProcessBrowserTestFixture() override { @@ -168,22 +170,20 @@ private: testing::NiceMock<MockConfigurationPolicyProvider> provider_; - DISALLOW_COPY_AND_ASSIGN(QuicAllowedPolicyTestBase); }; // Policy QuicAllowed set to false. class QuicAllowedPolicyIsFalse: public QuicAllowedPolicyTestBase { public: QuicAllowedPolicyIsFalse() : QuicAllowedPolicyTestBase() {} + QuicAllowedPolicyIsFalse(const QuicAllowedPolicyIsFalse&) = delete; + QuicAllowedPolicyIsFalse& operator=(const QuicAllowedPolicyIsFalse&) = delete; protected: void GetQuicAllowedPolicy(PolicyMap* values) override { values->Set(key::kQuicAllowed, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, base::Value(false), nullptr); } - - private: - DISALLOW_COPY_AND_ASSIGN(QuicAllowedPolicyIsFalse); }; // It's important that all these tests be separate, as the first NetworkContext @@ -240,15 +240,14 @@ class QuicAllowedPolicyIsTrue: public QuicAllowedPolicyTestBase { public: QuicAllowedPolicyIsTrue() : QuicAllowedPolicyTestBase() {} + QuicAllowedPolicyIsTrue(const QuicAllowedPolicyIsTrue&) = delete; + QuicAllowedPolicyIsTrue& operator=(const QuicAllowedPolicyIsTrue&) = delete; protected: void GetQuicAllowedPolicy(PolicyMap* values) override { values->Set(key::kQuicAllowed, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, base::Value(true), nullptr); } - - private: - DISALLOW_COPY_AND_ASSIGN(QuicAllowedPolicyIsTrue); }; // It's important that all these tests be separate, as the first NetworkContext @@ -312,12 +311,12 @@ class QuicAllowedPolicyIsNotSet : public QuicAllowedPolicyTestBase { public: QuicAllowedPolicyIsNotSet() : QuicAllowedPolicyTestBase() {} + QuicAllowedPolicyIsNotSet(const QuicAllowedPolicyIsNotSet&) = delete; + QuicAllowedPolicyIsNotSet& operator=(const QuicAllowedPolicyIsNotSet&) = + delete; protected: void GetQuicAllowedPolicy(PolicyMap* values) override {} - - private: - DISALLOW_COPY_AND_ASSIGN(QuicAllowedPolicyIsNotSet); }; // Flaky test on Win7. https://crbug.com/961049 @@ -332,6 +331,9 @@ class QuicAllowedPolicyDynamicTest : public QuicTestBase { public: QuicAllowedPolicyDynamicTest() : profile_1_(nullptr), profile_2_(nullptr) {} + QuicAllowedPolicyDynamicTest(const QuicAllowedPolicyDynamicTest&) = delete; + QuicAllowedPolicyDynamicTest& operator=(const QuicAllowedPolicyDynamicTest&) = + delete; protected: void SetUpCommandLine(base::CommandLine* command_line) override { @@ -454,8 +456,6 @@ MockConfigurationPolicyProvider policy_for_profile_1_; // Mock Policy for profile_2_. MockConfigurationPolicyProvider policy_for_profile_2_; - - DISALLOW_COPY_AND_ASSIGN(QuicAllowedPolicyDynamicTest); }; // QUIC is disallowed by policy after the profile has been initialized.
diff --git a/chrome/browser/policy/policy_startup_browsertest.cc b/chrome/browser/policy/policy_startup_browsertest.cc index 61f5e37..e95cdb50 100644 --- a/chrome/browser/policy/policy_startup_browsertest.cc +++ b/chrome/browser/policy/policy_startup_browsertest.cc
@@ -6,7 +6,6 @@ // PolicyMakeDefaultBrowserTest is not valid for this platform. #include "base/command_line.h" -#include "base/macros.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" @@ -18,6 +17,11 @@ #include "content/public/test/browser_test.h" class PolicyMakeDefaultBrowserTest : public InProcessBrowserTest { + public: + PolicyMakeDefaultBrowserTest(const PolicyMakeDefaultBrowserTest&) = delete; + PolicyMakeDefaultBrowserTest& operator=(const PolicyMakeDefaultBrowserTest&) = + delete; + protected: PolicyMakeDefaultBrowserTest() : InProcessBrowserTest() { set_expected_exit_code(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY); @@ -41,7 +45,6 @@ private: testing::NiceMock<policy::MockConfigurationPolicyProvider> provider_; - DISALLOW_COPY_AND_ASSIGN(PolicyMakeDefaultBrowserTest); }; IN_PROC_BROWSER_TEST_F(PolicyMakeDefaultBrowserTest, MakeDefaultDisabled) {
diff --git a/chrome/browser/policy/profile_policy_connector_unittest.cc b/chrome/browser/policy/profile_policy_connector_unittest.cc index 49769bd..d3d6e751 100644 --- a/chrome/browser/policy/profile_policy_connector_unittest.cc +++ b/chrome/browser/policy/profile_policy_connector_unittest.cc
@@ -60,6 +60,10 @@ : policy_service_(policy_service), policy_domain_(policy_domain) { policy_service_->AddObserver(policy_domain_, this); } + PolicyServiceInitializedWaiter(const PolicyServiceInitializedWaiter&) = + delete; + PolicyServiceInitializedWaiter& operator=( + const PolicyServiceInitializedWaiter&) = delete; ~PolicyServiceInitializedWaiter() override { policy_service_->RemoveObserver(policy_domain_, this); @@ -88,8 +92,6 @@ PolicyService* policy_service_; PolicyDomain policy_domain_; base::RunLoop run_loop_; - - DISALLOW_COPY_AND_ASSIGN(PolicyServiceInitializedWaiter); }; void UpdateChromePolicyToMockProviderAndVerify(
diff --git a/chrome/browser/policy/schema_registry_service.h b/chrome/browser/policy/schema_registry_service.h index 3919fa7a..c1bcf6f 100644 --- a/chrome/browser/policy/schema_registry_service.h +++ b/chrome/browser/policy/schema_registry_service.h
@@ -7,8 +7,6 @@ #include <memory> -#include "base/macros.h" - namespace policy { class CombinedSchemaRegistry; @@ -24,14 +22,14 @@ SchemaRegistryService(std::unique_ptr<SchemaRegistry> registry, const Schema& chrome_schema, CombinedSchemaRegistry* global_registry); + SchemaRegistryService(const SchemaRegistryService&) = delete; + SchemaRegistryService& operator=(const SchemaRegistryService&) = delete; ~SchemaRegistryService(); SchemaRegistry* registry() const { return registry_.get(); } private: std::unique_ptr<SchemaRegistry> registry_; - - DISALLOW_COPY_AND_ASSIGN(SchemaRegistryService); }; } // namespace policy
diff --git a/chrome/browser/policy/site_isolation_policy_browsertest.cc b/chrome/browser/policy/site_isolation_policy_browsertest.cc index 5ef0689f..50ad7f3 100644 --- a/chrome/browser/policy/site_isolation_policy_browsertest.cc +++ b/chrome/browser/policy/site_isolation_policy_browsertest.cc
@@ -27,8 +27,14 @@ #include "url/gurl.h" class SiteIsolationPolicyBrowserTest : public InProcessBrowserTest { + public: + SiteIsolationPolicyBrowserTest(const SiteIsolationPolicyBrowserTest&) = + delete; + SiteIsolationPolicyBrowserTest& operator=( + const SiteIsolationPolicyBrowserTest&) = delete; + protected: - SiteIsolationPolicyBrowserTest() {} + SiteIsolationPolicyBrowserTest() = default; struct Expectations { const char* url; @@ -61,15 +67,18 @@ } testing::NiceMock<policy::MockConfigurationPolicyProvider> provider_; - - private: - DISALLOW_COPY_AND_ASSIGN(SiteIsolationPolicyBrowserTest); }; template <bool policy_value> class SitePerProcessPolicyBrowserTest : public SiteIsolationPolicyBrowserTest { + public: + SitePerProcessPolicyBrowserTest(const SitePerProcessPolicyBrowserTest&) = + delete; + SitePerProcessPolicyBrowserTest& operator=( + const SitePerProcessPolicyBrowserTest&) = delete; + protected: - SitePerProcessPolicyBrowserTest() {} + SitePerProcessPolicyBrowserTest() = default; void SetUpInProcessBrowserTestFixture() override { // We setup the policy here, because the policy must be 'live' before @@ -94,9 +103,6 @@ base::Value(policy_value), nullptr); provider_.UpdateChromePolicy(values); } - - private: - DISALLOW_COPY_AND_ASSIGN(SitePerProcessPolicyBrowserTest); }; typedef SitePerProcessPolicyBrowserTest<true> @@ -105,8 +111,14 @@ SitePerProcessPolicyBrowserTestDisabled; class IsolateOriginsPolicyBrowserTest : public SiteIsolationPolicyBrowserTest { + public: + IsolateOriginsPolicyBrowserTest(const IsolateOriginsPolicyBrowserTest&) = + delete; + IsolateOriginsPolicyBrowserTest& operator=( + const IsolateOriginsPolicyBrowserTest&) = delete; + protected: - IsolateOriginsPolicyBrowserTest() {} + IsolateOriginsPolicyBrowserTest() = default; void SetUpInProcessBrowserTestFixture() override { // We setup the policy here, because the policy must be 'live' before @@ -127,26 +139,26 @@ nullptr); provider_.UpdateChromePolicy(values); } - - private: - DISALLOW_COPY_AND_ASSIGN(IsolateOriginsPolicyBrowserTest); }; // Ensure that --disable-site-isolation-trials and/or // --disable-site-isolation-for-enterprise-policy do not override policies. class NoOverrideSitePerProcessPolicyBrowserTest : public SitePerProcessPolicyBrowserTestEnabled { + public: + NoOverrideSitePerProcessPolicyBrowserTest( + const NoOverrideSitePerProcessPolicyBrowserTest&) = delete; + NoOverrideSitePerProcessPolicyBrowserTest& operator=( + const NoOverrideSitePerProcessPolicyBrowserTest&) = delete; + protected: - NoOverrideSitePerProcessPolicyBrowserTest() {} + NoOverrideSitePerProcessPolicyBrowserTest() = default; void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kDisableSiteIsolation); #if defined(OS_ANDROID) command_line->AppendSwitch(switches::kDisableSiteIsolationForPolicy); #endif } - - private: - DISALLOW_COPY_AND_ASSIGN(NoOverrideSitePerProcessPolicyBrowserTest); }; IN_PROC_BROWSER_TEST_F(SitePerProcessPolicyBrowserTestEnabled, Simple) { @@ -213,12 +225,14 @@ SitePerProcessPolicyBrowserTestFieldTrialTest() { scoped_feature_list_.InitAndEnableFeature(features::kSitePerProcess); } - ~SitePerProcessPolicyBrowserTestFieldTrialTest() override {} + SitePerProcessPolicyBrowserTestFieldTrialTest( + const SitePerProcessPolicyBrowserTestFieldTrialTest&) = delete; + SitePerProcessPolicyBrowserTestFieldTrialTest& operator=( + const SitePerProcessPolicyBrowserTestFieldTrialTest&) = delete; + ~SitePerProcessPolicyBrowserTestFieldTrialTest() override = default; private: base::test::ScopedFeatureList scoped_feature_list_; - - DISALLOW_COPY_AND_ASSIGN(SitePerProcessPolicyBrowserTestFieldTrialTest); }; IN_PROC_BROWSER_TEST_F(SitePerProcessPolicyBrowserTestFieldTrialTest, Simple) {
diff --git a/chrome/browser/policy/test/arc_policy_browsertest.cc b/chrome/browser/policy/test/arc_policy_browsertest.cc index 763be2d..36bcb390 100644 --- a/chrome/browser/policy/test/arc_policy_browsertest.cc +++ b/chrome/browser/policy/test/arc_policy_browsertest.cc
@@ -20,8 +20,10 @@ class ArcPolicyTest : public PolicyTest { public: - ArcPolicyTest() {} - ~ArcPolicyTest() override {} + ArcPolicyTest() = default; + ArcPolicyTest(const ArcPolicyTest&) = delete; + ArcPolicyTest& operator=(const ArcPolicyTest&) = delete; + ~ArcPolicyTest() override = default; protected: void SetUpOnMainThread() override { @@ -57,9 +59,6 @@ EXPECT_EQ(prefs->GetBoolean(arc::prefs::kArcEnabled), enabled); } } - - private: - DISALLOW_COPY_AND_ASSIGN(ArcPolicyTest); }; // Test ArcEnabled policy.
diff --git a/chrome/browser/policy/test/component_updater_policy_browsertest.cc b/chrome/browser/policy/test/component_updater_policy_browsertest.cc index abb9077..4ded68a 100644 --- a/chrome/browser/policy/test/component_updater_policy_browsertest.cc +++ b/chrome/browser/policy/test/component_updater_policy_browsertest.cc
@@ -30,6 +30,9 @@ class ComponentUpdaterPolicyTest : public PolicyTest { public: ComponentUpdaterPolicyTest(); + ComponentUpdaterPolicyTest(const ComponentUpdaterPolicyTest&) = delete; + ComponentUpdaterPolicyTest& operator=(const ComponentUpdaterPolicyTest&) = + delete; ~ComponentUpdaterPolicyTest() override; void SetUpCommandLine(base::CommandLine* command_line) override; @@ -88,8 +91,6 @@ component_updater::ComponentUpdateService* cus_ = nullptr; net::EmbeddedTestServer https_server_; - - DISALLOW_COPY_AND_ASSIGN(ComponentUpdaterPolicyTest); }; const char ComponentUpdaterPolicyTest::component_id_[] =
diff --git a/chrome/browser/policy/test/policy_browsertest.cc b/chrome/browser/policy/test/policy_browsertest.cc index 5d1df99..e5b066c 100644 --- a/chrome/browser/policy/test/policy_browsertest.cc +++ b/chrome/browser/policy/test/policy_browsertest.cc
@@ -427,8 +427,10 @@ class NetworkTimePolicyTest : public PolicyTest { public: - NetworkTimePolicyTest() {} - ~NetworkTimePolicyTest() override {} + NetworkTimePolicyTest() = default; + NetworkTimePolicyTest(const NetworkTimePolicyTest&) = delete; + NetworkTimePolicyTest& operator=(const NetworkTimePolicyTest&) = delete; + ~NetworkTimePolicyTest() override = default; void SetUpOnMainThread() override { std::map<std::string, std::string> parameters; @@ -459,8 +461,6 @@ private: base::test::ScopedFeatureList scoped_feature_list_; uint32_t num_requests_ = 0; - - DISALLOW_COPY_AND_ASSIGN(NetworkTimePolicyTest); }; // TODO(https://crbug.com/1012853): This test is using ScopedFeatureList
diff --git a/chrome/browser/policy/webusb_allow_devices_for_urls_policy_handler_unittest.cc b/chrome/browser/policy/webusb_allow_devices_for_urls_policy_handler_unittest.cc index 525a0d7..b9dc90c 100644 --- a/chrome/browser/policy/webusb_allow_devices_for_urls_policy_handler_unittest.cc +++ b/chrome/browser/policy/webusb_allow_devices_for_urls_policy_handler_unittest.cc
@@ -215,6 +215,10 @@ : public ConfigurationPolicyPrefStoreTest { public: WebUsbAllowDevicesForUrlsPolicyHandlerTest() = default; + WebUsbAllowDevicesForUrlsPolicyHandlerTest( + const WebUsbAllowDevicesForUrlsPolicyHandlerTest&) = delete; + WebUsbAllowDevicesForUrlsPolicyHandlerTest& operator=( + const WebUsbAllowDevicesForUrlsPolicyHandlerTest&) = delete; ~WebUsbAllowDevicesForUrlsPolicyHandlerTest() override = default; WebUsbAllowDevicesForUrlsPolicyHandler* handler() { return handler_; } @@ -229,8 +233,6 @@ } WebUsbAllowDevicesForUrlsPolicyHandler* handler_; - - DISALLOW_COPY_AND_ASSIGN(WebUsbAllowDevicesForUrlsPolicyHandlerTest); }; TEST_F(WebUsbAllowDevicesForUrlsPolicyHandlerTest, CheckPolicySettings) {
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 69791f0..4f0ff9f 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -636,6 +636,8 @@ const char kSuggestionsBlocklist[] = "suggestions.blacklist"; const char kSuggestionsData[] = "suggestions.data"; +const char kUserAgentClientHintsEnabled[] = + "policy.user_agent_client_hints_enabled"; #if BUILDFLAG(ENABLE_EXTENSIONS) // Deprecated 07/2021. @@ -674,6 +676,8 @@ registry->RegisterIntegerPref(kStabilityDebuggerPresent, 0); registry->RegisterIntegerPref(kStabilityDebuggerNotPresent, 0); + registry->RegisterBooleanPref(kUserAgentClientHintsEnabled, true); + #if BUILDFLAG(ENABLE_EXTENSIONS) registry->RegisterBooleanPref(kPinnedExtensionsMigrationComplete, false); #endif @@ -882,8 +886,6 @@ registry->RegisterBooleanPref( policy::policy_prefs::kIntensiveWakeUpThrottlingEnabled, false); registry->RegisterBooleanPref( - policy::policy_prefs::kUserAgentClientHintsEnabled, true); - registry->RegisterBooleanPref( policy::policy_prefs::kTargetBlankImpliesNoOpener, true); #if defined(OS_ANDROID) registry->RegisterBooleanPref(policy::policy_prefs::kBackForwardCacheEnabled, @@ -1417,6 +1419,9 @@ local_state->ClearPref(kPinnedExtensionsMigrationComplete); #endif + // Added 07/2021 + local_state->ClearPref(kUserAgentClientHintsEnabled); + // Please don't delete the following line. It is used by PRESUBMIT.py. // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS }
diff --git a/chrome/browser/prefs/proxy_policy_unittest.cc b/chrome/browser/prefs/proxy_policy_unittest.cc index 7e521dd..7a59eea 100644 --- a/chrome/browser/prefs/proxy_policy_unittest.cc +++ b/chrome/browser/prefs/proxy_policy_unittest.cc
@@ -96,9 +96,9 @@ ProxyPolicyTest() : command_line_(base::CommandLine::NO_PROGRAM) {} void SetUp() override { - ON_CALL(provider_, IsInitializationComplete(_)).WillByDefault(Return(true)); - ON_CALL(provider_, IsFirstPolicyLoadComplete(_)) - .WillByDefault(Return(true)); + provider_.SetDefaultReturns( + /*is_initialization_complete_return=*/true, + /*is_first_policy_load_complete_return=*/true); PolicyServiceImpl::Providers providers; providers.push_back(&provider_);
diff --git a/chrome/browser/privacy_sandbox/privacy_sandbox_settings_browsertest.cc b/chrome/browser/privacy_sandbox/privacy_sandbox_settings_browsertest.cc index 760ac73..72bc833 100644 --- a/chrome/browser/privacy_sandbox/privacy_sandbox_settings_browsertest.cc +++ b/chrome/browser/privacy_sandbox/privacy_sandbox_settings_browsertest.cc
@@ -170,10 +170,9 @@ : public PrivacySandboxSettingsBrowserTest { public: PrivacySandboxSettingsBrowserPolicyTest() { - ON_CALL(*policy_provider(), IsInitializationComplete(testing::_)) - .WillByDefault(testing::Return(true)); - ON_CALL(*policy_provider(), IsFirstPolicyLoadComplete(testing::_)) - .WillByDefault(testing::Return(true)); + policy_provider()->SetDefaultReturns( + /*is_initialization_complete_return=*/true, + /*is_first_policy_load_complete_return=*/true); policy::BrowserPolicyConnector::SetPolicyProviderForTesting( policy_provider());
diff --git a/chrome/browser/resources/chromeos/assistant_optin/assistant_related_info.html b/chrome/browser/resources/chromeos/assistant_optin/assistant_related_info.html index 00d3dba0..13ec187 100644 --- a/chrome/browser/resources/chromeos/assistant_optin/assistant_related_info.html +++ b/chrome/browser/resources/chromeos/assistant_optin/assistant_related_info.html
@@ -97,15 +97,13 @@ </div> <div class="line"></div> <setting-zippy id="zippy"> - <div slot="title" aria-hidden="true"> + <div slot="title"> [[i18nDynamic(locale, 'assistantScreenContextTitle')]] </div> - <div slot="content" aria-hidden="true" - hidden="[[childName_]]"> + <div slot="content" hidden="[[childName_]]"> [[i18nDynamic(locale, 'assistantScreenContextDesc')]] </div> - <div slot="content" aria-hidden="true" - hidden="[[!childName_]]"> + <div slot="content" hidden="[[!childName_]]"> [[i18nDynamic(locale, 'assistantScreenContextDescForChild', childName_)]] </div>
diff --git a/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_browsertest_win.cc b/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_browsertest_win.cc index 1da9fbb..85c16960 100644 --- a/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_browsertest_win.cc +++ b/chrome/browser/safe_browsing/chrome_cleaner/reporter_runner_browsertest_win.cc
@@ -126,10 +126,9 @@ } void SetUpInProcessBrowserTestFixture() override { - ON_CALL(policy_provider_, IsInitializationComplete(_)) - .WillByDefault(Return(true)); - ON_CALL(policy_provider_, IsFirstPolicyLoadComplete(_)) - .WillByDefault(Return(true)); + policy_provider_.SetDefaultReturns( + /*is_initialization_complete_return=*/true, + /*is_first_policy_load_complete_return=*/true); policy::BrowserPolicyConnector::SetPolicyProviderForTesting( &policy_provider_);
diff --git a/chrome/browser/search/chrome_colors/chrome_colors_service.cc b/chrome/browser/search/chrome_colors/chrome_colors_service.cc index 324110f2..32f6dd5 100644 --- a/chrome/browser/search/chrome_colors/chrome_colors_service.cc +++ b/chrome/browser/search/chrome_colors/chrome_colors_service.cc
@@ -37,10 +37,6 @@ kNumColorsInfo); } -void ChromeColorsService::RecordColorAppliedHistogram(int color_id) { - base::UmaHistogramSparse("ChromeColors.ColorApplied", color_id); -} - void ChromeColorsService::ApplyDefaultTheme(content::WebContents* tab) { SaveThemeRevertState(tab); theme_service_->UseDefaultTheme();
diff --git a/chrome/browser/search/chrome_colors/chrome_colors_service.h b/chrome/browser/search/chrome_colors/chrome_colors_service.h index 545a403..59ef0dc1 100644 --- a/chrome/browser/search/chrome_colors/chrome_colors_service.h +++ b/chrome/browser/search/chrome_colors/chrome_colors_service.h
@@ -37,9 +37,6 @@ // predefined set, |kOtherColorId| is recorded. static void RecordColorOnLoadHistogram(SkColor color); - // Records |color_id| to UMA histogram whenever a new theme is applied. - static void RecordColorAppliedHistogram(int color_id); - // Applies a theme that can be reverted by saving the previous theme state and // the |tab| that changes are made from. void ApplyDefaultTheme(content::WebContents* tab);
diff --git a/chrome/browser/search_engines/template_url_service_sync_unittest.cc b/chrome/browser/search_engines/template_url_service_sync_unittest.cc index b2b9bf1a..4e35383 100644 --- a/chrome/browser/search_engines/template_url_service_sync_unittest.cc +++ b/chrome/browser/search_engines/template_url_service_sync_unittest.cc
@@ -104,10 +104,6 @@ const base::Location& from_here, const syncer::SyncChangeList& change_list) override; - syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override { - return syncer::SyncDataList(); - } - bool contains_guid(const std::string& guid) const { return change_map_.count(guid) != 0; }
diff --git a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinator.java b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinator.java index c934b02..5c16d0c 100644 --- a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinator.java +++ b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinator.java
@@ -124,7 +124,7 @@ assert mImageEditorModuleProvider != null; ImageEditorDialogCoordinator editor = mImageEditorModuleProvider.getImageEditorDialogCoordinator(); - editor.launchEditor(mActivity, mScreenshot, mTab, mChromeOptionShareCallback); + editor.launchEditor(mActivity, mScreenshot, mTab, mShareUrl, mChromeOptionShareCallback); mScreenshot = null; }
diff --git a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/long_screenshots/bitmap_generation/BitmapGeneratorTest.java b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/long_screenshots/bitmap_generation/BitmapGeneratorTest.java index 40066ad..4b0cc83 100644 --- a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/long_screenshots/bitmap_generation/BitmapGeneratorTest.java +++ b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/long_screenshots/bitmap_generation/BitmapGeneratorTest.java
@@ -6,7 +6,8 @@ import android.graphics.Bitmap; import android.graphics.Rect; -import android.support.test.filters.LargeTest; + +import androidx.test.filters.LargeTest; import org.junit.After; import org.junit.Assert;
diff --git a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinatorTest.java b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinatorTest.java index 2dcd1a1..25f9bdb4 100644 --- a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinatorTest.java +++ b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/screenshot/ScreenshotCoordinatorTest.java
@@ -107,7 +107,8 @@ .thenReturn(mImageEditorDialogCoordinatorMock); doNothing() .when(mImageEditorDialogCoordinatorMock) - .launchEditor(mActivity, mBitmap, mTab, mChromeOptionShareCallback); + .launchEditor(mActivity, mBitmap, mTab, JUnitTestGURLs.EXAMPLE_URL, + mChromeOptionShareCallback); mBitmap = Bitmap.createBitmap(800, 600, Bitmap.Config.ARGB_8888); @@ -132,7 +133,8 @@ // Ensure the editor launches. verify(mImageEditorDialogCoordinatorMock) - .launchEditor(mActivity, mBitmap, mTab, mChromeOptionShareCallback); + .launchEditor(mActivity, mBitmap, mTab, JUnitTestGURLs.EXAMPLE_URL, + mChromeOptionShareCallback); } @Test @@ -150,7 +152,8 @@ // Failed install loads the share sheet. verify(mScreenshotShareSheetDialogMock).show(any(FragmentManager.class), any()); // The editor is not launched. - verify(mImageEditorDialogCoordinatorMock, never()).launchEditor(any(), any(), any(), any()); + verify(mImageEditorDialogCoordinatorMock, never()) + .launchEditor(any(), any(), any(), any(), any()); // A second install is attempted and succeeds. when(mImageEditorModuleProviderMock.isModuleInstalled()).thenReturn(true); @@ -161,7 +164,8 @@ mScreenshotCoordinator.captureScreenshot(); // The editor should launch without requiring a discrete user action. verify(mImageEditorDialogCoordinatorMock) - .launchEditor(mActivity, mBitmap, mTab, mChromeOptionShareCallback); + .launchEditor(mActivity, mBitmap, mTab, JUnitTestGURLs.EXAMPLE_URL, + mChromeOptionShareCallback); } @Test @@ -182,7 +186,8 @@ verify(mScreenshotShareSheetDialogMock, times(ScreenshotCoordinator.MAX_INSTALL_ATTEMPTS)) .show(any(FragmentManager.class), any()); // Ensure the editor was never loaded. - verify(mImageEditorDialogCoordinatorMock, never()).launchEditor(any(), any(), any(), any()); + verify(mImageEditorDialogCoordinatorMock, never()) + .launchEditor(any(), any(), any(), any(), any()); // Subsequent attempts will not invoke installation. mScreenshotCoordinator.captureScreenshot(); @@ -194,6 +199,7 @@ times(ScreenshotCoordinator.MAX_INSTALL_ATTEMPTS + 1)) .show(any(FragmentManager.class), any()); // The editor should not attempt to be loaded. - verify(mImageEditorDialogCoordinatorMock, never()).launchEditor(any(), any(), any(), any()); + verify(mImageEditorDialogCoordinatorMock, never()) + .launchEditor(any(), any(), any(), any(), any()); } }
diff --git a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/NotificationSharedPrefManagerTest.java b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/NotificationSharedPrefManagerTest.java index 9f6381b..0a8dc09 100644 --- a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/NotificationSharedPrefManagerTest.java +++ b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/NotificationSharedPrefManagerTest.java
@@ -4,9 +4,8 @@ package org.chromium.chrome.browser.share.send_tab_to_self; -import android.support.test.filters.SmallTest; - import androidx.annotation.Nullable; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Test;
diff --git a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java index b39c1e7..f5556453a 100644 --- a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java +++ b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java
@@ -12,7 +12,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfCoordinatorTest.java b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfCoordinatorTest.java index efa8586..380ce2d 100644 --- a/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfCoordinatorTest.java +++ b/chrome/browser/share/android/javatests/src/org/chromium/chrome/browser/share/send_tab_to_self/SendTabToSelfCoordinatorTest.java
@@ -8,7 +8,7 @@ import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Test;
diff --git a/chrome/browser/signin/ui/android/java/res/layout/signin_first_run_view.xml b/chrome/browser/signin/ui/android/java/res/layout/signin_first_run_view.xml index e49484a..b1b392a6 100644 --- a/chrome/browser/signin/ui/android/java/res/layout/signin_first_run_view.xml +++ b/chrome/browser/signin/ui/android/java/res/layout/signin_first_run_view.xml
@@ -72,7 +72,7 @@ android:layout_height="wrap_content" android:layout_marginStart="24dp" android:layout_marginEnd="24dp" - android:text="@string/signin_account_picker_dismiss_button" /> + android:text="@string/signin_fre_dismiss_button" /> <!-- TODO(crbug/1228155): Use the correct string for the footer --> <org.chromium.ui.widget.TextViewWithLeading
diff --git a/chrome/browser/ssl/sct_reporting_service_browsertest.cc b/chrome/browser/ssl/sct_reporting_service_browsertest.cc index 0f898dea..267da63 100644 --- a/chrome/browser/ssl/sct_reporting_service_browsertest.cc +++ b/chrome/browser/ssl/sct_reporting_service_browsertest.cc
@@ -6,6 +6,7 @@ #include "base/callback.h" #include "base/synchronization/lock.h" #include "base/test/scoped_feature_list.h" +#include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/profiles/profile.h" @@ -338,8 +339,15 @@ } // Tests that disabling Extended Reporting causes the cache to be cleared. +// TODO(crbug.com/1179504): Reenable. Flakes heavily on Linux, Win, and CrOS. +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_CHROMEOS) +#define MAYBE_OptingOutClearsSCTAuditingCache \ + DISABLED_OptingOutClearsSCTAuditingCache +#else +#define MAYBE_OptingOutClearsSCTAuditingCache OptingOutClearsSCTAuditingCache +#endif IN_PROC_BROWSER_TEST_F(SCTReportingServiceBrowserTest, - OptingOutClearsSCTAuditingCache) { + MAYBE_OptingOutClearsSCTAuditingCache) { // Enable SCT auditing and enqueue a report. SetExtendedReportingEnabled(true);
diff --git a/chrome/browser/sync/test/integration/apps_helper.cc b/chrome/browser/sync/test/integration/apps_helper.cc index 74ac7c2..714118d 100644 --- a/chrome/browser/sync/test/integration/apps_helper.cc +++ b/chrome/browser/sync/test/integration/apps_helper.cc
@@ -10,7 +10,6 @@ #include "base/test/bind.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync/test/integration/sync_app_helper.h" #include "chrome/browser/sync/test/integration/sync_datatype_helper.h" @@ -22,7 +21,6 @@ #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_sync_bridge.h" #include "components/webapps/browser/installable/installable_metrics.h" -#include "content/public/browser/notification_service.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/manifest.h" @@ -275,10 +273,10 @@ extensions::ExtensionPrefs* prefs = extensions::ExtensionPrefs::Get(profile); prefs->AddObserver(this); - } - registrar_.Add(this, chrome::NOTIFICATION_APP_LAUNCHER_REORDERED, - content::NotificationService::AllSources()); + install_tracker_observation_.AddObservation( + extensions::InstallTracker::Get(profile)); + } } AppsMatchChecker::~AppsMatchChecker() { @@ -290,9 +288,6 @@ extensions::ExtensionPrefs::Get(profile); prefs->RemoveObserver(this); } - - registrar_.Remove(this, chrome::NOTIFICATION_APP_LAUNCHER_REORDERED, - content::NotificationService::AllSources()); } bool AppsMatchChecker::IsExitConditionSatisfied(std::ostream* os) { @@ -364,9 +359,7 @@ CheckExitCondition(); } -void AppsMatchChecker::Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - DCHECK_EQ(chrome::NOTIFICATION_APP_LAUNCHER_REORDERED, type); +void AppsMatchChecker::OnAppsReordered( + const absl::optional<std::string>& extension_id) { CheckExitCondition(); }
diff --git a/chrome/browser/sync/test/integration/apps_helper.h b/chrome/browser/sync/test/integration/apps_helper.h index 9e4a31d..bbcd569 100644 --- a/chrome/browser/sync/test/integration/apps_helper.h +++ b/chrome/browser/sync/test/integration/apps_helper.h
@@ -10,13 +10,14 @@ #include <vector> #include "base/compiler_specific.h" +#include "base/scoped_multi_source_observation.h" +#include "chrome/browser/extensions/install_observer.h" +#include "chrome/browser/extensions/install_tracker.h" #include "chrome/browser/sync/test/integration/status_change_checker.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/browser/web_applications/components/web_app_id.h" #include "chrome/browser/web_applications/components/web_application_info.h" #include "components/sync/model/string_ordinal.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" #include "extensions/browser/extension_prefs_observer.h" #include "extensions/browser/extension_registry_observer.h" @@ -120,7 +121,7 @@ class AppsMatchChecker : public StatusChangeChecker, public extensions::ExtensionRegistryObserver, public extensions::ExtensionPrefsObserver, - public content::NotificationObserver { + public extensions::InstallObserver { public: AppsMatchChecker(); ~AppsMatchChecker() override; @@ -153,10 +154,9 @@ void OnExtensionStateChanged(const std::string& extension_id, bool state) override; - // Implementation of content::NotificationObserver. - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; + // Implementation of extensions::InstallObserver. + void OnAppsReordered( + const absl::optional<std::string>& extension_id) override; private: std::vector<Profile*> profiles_; @@ -167,6 +167,10 @@ std::vector<std::unique_ptr<SyncedExtensionInstaller>> synced_extension_installers_; + base::ScopedMultiSourceObservation<extensions::InstallTracker, + extensions::InstallObserver> + install_tracker_observation_{this}; + DISALLOW_COPY_AND_ASSIGN(AppsMatchChecker); };
diff --git a/chrome/browser/tab/BUILD.gn b/chrome/browser/tab/BUILD.gn index 3a662c5..da7a8bc 100644 --- a/chrome/browser/tab/BUILD.gn +++ b/chrome/browser/tab/BUILD.gn
@@ -153,6 +153,7 @@ "//content/public/android:content_full_java", "//third_party/android_deps:robolectric_all_java", "//third_party/android_support_test_runner:runner_java", + "//third_party/androidx:androidx_test_runner_java", "//third_party/junit", "//third_party/mockito:mockito_java", "//ui/android:ui_no_recycler_view_java",
diff --git a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/TabAssociatedAppTest.java b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/TabAssociatedAppTest.java index 4cbcd15b..e29fb41 100644 --- a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/TabAssociatedAppTest.java +++ b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/TabAssociatedAppTest.java
@@ -7,7 +7,7 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Before;
diff --git a/chrome/browser/ui/android/layouts/BUILD.gn b/chrome/browser/ui/android/layouts/BUILD.gn index 47ffb17..e40bec0b 100644 --- a/chrome/browser/ui/android/layouts/BUILD.gn +++ b/chrome/browser/ui/android/layouts/BUILD.gn
@@ -69,6 +69,7 @@ "//base:base_junit_test_support", "//third_party/android_deps:robolectric_all_java", "//third_party/android_support_test_runner:runner_java", + "//third_party/androidx:androidx_test_runner_java", "//third_party/junit", "//third_party/mockito:mockito_java", "//ui/android:ui_java",
diff --git a/chrome/browser/ui/android/layouts/java/src/org/chromium/chrome/browser/layouts/animation/CompositorAnimationHandlerTest.java b/chrome/browser/ui/android/layouts/java/src/org/chromium/chrome/browser/layouts/animation/CompositorAnimationHandlerTest.java index e96358b7..1085fa6 100644 --- a/chrome/browser/ui/android/layouts/java/src/org/chromium/chrome/browser/layouts/animation/CompositorAnimationHandlerTest.java +++ b/chrome/browser/ui/android/layouts/java/src/org/chromium/chrome/browser/layouts/animation/CompositorAnimationHandlerTest.java
@@ -4,7 +4,7 @@ package org.chromium.chrome.browser.layouts.animation; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Assert; import org.junit.Test; @@ -49,4 +49,4 @@ Assert.assertFalse(mFastAnimation.isRunning()); Assert.assertFalse(mSlowAnimation.isRunning()); } -} \ No newline at end of file +}
diff --git a/chrome/browser/ui/android/omnibox/BUILD.gn b/chrome/browser/ui/android/omnibox/BUILD.gn index 9409d01..ae6201a 100644 --- a/chrome/browser/ui/android/omnibox/BUILD.gn +++ b/chrome/browser/ui/android/omnibox/BUILD.gn
@@ -355,6 +355,7 @@ "//third_party/android_deps:robolectric_all_java", "//third_party/android_support_test_runner:runner_java", "//third_party/androidx:androidx_annotation_annotation_java", + "//third_party/androidx:androidx_test_runner_java", "//third_party/hamcrest:hamcrest_library_java", "//third_party/junit", "//third_party/mockito:mockito_java",
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/UrlBarUnitTest.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/UrlBarUnitTest.java index 0da49211..e09b36c4 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/UrlBarUnitTest.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/UrlBarUnitTest.java
@@ -7,10 +7,11 @@ import static org.mockito.Mockito.verify; import android.app.Activity; -import android.support.test.filters.SmallTest; import android.text.SpannableStringBuilder; import android.view.ViewStructure; +import androidx.test.filters.SmallTest; + import org.junit.Assert; import org.junit.Before; import org.junit.Test;
diff --git a/chrome/browser/ui/android/quickactionsearchwidget/BUILD.gn b/chrome/browser/ui/android/quickactionsearchwidget/BUILD.gn index 1c3ccc7..f33cfc84 100644 --- a/chrome/browser/ui/android/quickactionsearchwidget/BUILD.gn +++ b/chrome/browser/ui/android/quickactionsearchwidget/BUILD.gn
@@ -44,6 +44,7 @@ "//components/embedder_support/android:util_java", "//content/public/test/android:content_java_test_support", "//third_party/android_support_test_runner:runner_java", + "//third_party/androidx:androidx_test_runner_java", "//third_party/junit:junit", "//url:gurl_java", ]
diff --git a/chrome/browser/ui/android/quickactionsearchwidget/java/src/org/chromium/chrome/browser/ui/quickactionsearchwidget/QuickActionSearchWidgetProviderDelegateTest.java b/chrome/browser/ui/android/quickactionsearchwidget/java/src/org/chromium/chrome/browser/ui/quickactionsearchwidget/QuickActionSearchWidgetProviderDelegateTest.java index 374f485..14a2b74 100644 --- a/chrome/browser/ui/android/quickactionsearchwidget/java/src/org/chromium/chrome/browser/ui/quickactionsearchwidget/QuickActionSearchWidgetProviderDelegateTest.java +++ b/chrome/browser/ui/android/quickactionsearchwidget/java/src/org/chromium/chrome/browser/ui/quickactionsearchwidget/QuickActionSearchWidgetProviderDelegateTest.java
@@ -7,11 +7,12 @@ import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.support.test.InstrumentationRegistry; -import android.support.test.filters.SmallTest; import android.view.View; import android.widget.FrameLayout; import android.widget.RemoteViews; +import androidx.test.filters.SmallTest; + import org.junit.After; import org.junit.Before; import org.junit.Test;
diff --git a/chrome/browser/ui/android/quickactionsearchwidget/java/src/org/chromium/chrome/browser/ui/quickactionsearchwidget/QuickActionSearchWidgetReceiverDelegateTest.java b/chrome/browser/ui/android/quickactionsearchwidget/java/src/org/chromium/chrome/browser/ui/quickactionsearchwidget/QuickActionSearchWidgetReceiverDelegateTest.java index ab448bd3..8294ab4 100644 --- a/chrome/browser/ui/android/quickactionsearchwidget/java/src/org/chromium/chrome/browser/ui/quickactionsearchwidget/QuickActionSearchWidgetReceiverDelegateTest.java +++ b/chrome/browser/ui/android/quickactionsearchwidget/java/src/org/chromium/chrome/browser/ui/quickactionsearchwidget/QuickActionSearchWidgetReceiverDelegateTest.java
@@ -7,7 +7,8 @@ import android.content.ComponentName; import android.content.Intent; import android.support.test.InstrumentationRegistry; -import android.support.test.filters.SmallTest; + +import androidx.test.filters.SmallTest; import org.junit.After; import org.junit.Before;
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index 5f5baecca..b562db9 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -2588,6 +2588,11 @@ Your browser is managed by your organization </message> + <!-- Signin First Run strings --> + <message name="IDS_SIGNIN_FRE_DISMISS_BUTTON" desc="Text for the dismiss button on the welcome sign-in screen. By clicking this button users will continue without signing in,"> + Use without an account + </message> + <!-- Account Signin Strings --> <message name="IDS_SIGNIN_ADD_ACCOUNT" desc="Text for adding another Google Account"> Add account
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SIGNIN_FRE_DISMISS_BUTTON.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SIGNIN_FRE_DISMISS_BUTTON.png.sha1 new file mode 100644 index 0000000..5b9c61a --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SIGNIN_FRE_DISMISS_BUTTON.png.sha1
@@ -0,0 +1 @@ +8f877d831476f1a72bca69a3140206f4dc345b4f \ No newline at end of file
diff --git a/chrome/browser/ui/ash/test_wallpaper_controller.cc b/chrome/browser/ui/ash/test_wallpaper_controller.cc index 3d00b99..3645f9595 100644 --- a/chrome/browser/ui/ash/test_wallpaper_controller.cc +++ b/chrome/browser/ui/ash/test_wallpaper_controller.cc
@@ -231,6 +231,15 @@ collection_id_ = collection_id; } +std::string TestWallpaperController::GetDailyRefreshCollectionId() const { + return collection_id_; +} + +void TestWallpaperController::UpdateDailyRefreshWallpaper( + RefreshWallpaperCallback callback) { + NOTIMPLEMENTED(); +} + void TestWallpaperController::OnGoogleDriveMounted() { NOTIMPLEMENTED(); }
diff --git a/chrome/browser/ui/ash/test_wallpaper_controller.h b/chrome/browser/ui/ash/test_wallpaper_controller.h index 242043b..6428e1f8 100644 --- a/chrome/browser/ui/ash/test_wallpaper_controller.h +++ b/chrome/browser/ui/ash/test_wallpaper_controller.h
@@ -109,6 +109,8 @@ ash::WallpaperInfo GetActiveUserWallpaperInfo() override; bool ShouldShowWallpaperSetting() override; void SetDailyRefreshCollectionId(const std::string& collection_id) override; + std::string GetDailyRefreshCollectionId() const override; + void UpdateDailyRefreshWallpaper(RefreshWallpaperCallback callback) override; void OnGoogleDriveMounted() override; private:
diff --git a/chrome/browser/ui/browser_command_controller.cc b/chrome/browser/ui/browser_command_controller.cc index 57ef822..02d1736 100644 --- a/chrome/browser/ui/browser_command_controller.cc +++ b/chrome/browser/ui/browser_command_controller.cc
@@ -1070,11 +1070,11 @@ command_updater_.UpdateCommandEnabled(IDC_TAKE_SCREENSHOT, true); // Chrome OS uses the system tray menu to handle multi-profiles. Avatar menu // is only required in incognito mode. - if (profile()->IsIncognitoProfile()) - command_updater_.UpdateCommandEnabled(IDC_SHOW_AVATAR_MENU, true); + command_updater_.UpdateCommandEnabled( + IDC_SHOW_AVATAR_MENU, /*state=*/profile()->IsIncognitoProfile()); #else - if (normal_window) - command_updater_.UpdateCommandEnabled(IDC_SHOW_AVATAR_MENU, true); + command_updater_.UpdateCommandEnabled(IDC_SHOW_AVATAR_MENU, + /*state=*/normal_window); #endif command_updater_.UpdateCommandEnabled( IDC_SHOW_SAVE_LOCAL_CARD_SIGN_IN_PROMO_IF_APPLICABLE, true);
diff --git a/chrome/browser/ui/exclusive_access/fullscreen_controller_interactive_browsertest.cc b/chrome/browser/ui/exclusive_access/fullscreen_controller_interactive_browsertest.cc index 8356b23..d98a42b 100644 --- a/chrome/browser/ui/exclusive_access/fullscreen_controller_interactive_browsertest.cc +++ b/chrome/browser/ui/exclusive_access/fullscreen_controller_interactive_browsertest.cc
@@ -294,21 +294,15 @@ ASSERT_FALSE(IsWindowFullscreenForTabOrPending()); } -#if defined(OS_MAC) -// http://crbug.com/100467 -IN_PROC_BROWSER_TEST_F(ExclusiveAccessTest, - DISABLED_TabEntersPresentationModeFromWindowed) { +IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, + TabEntersPresentationModeFromWindowed) { ASSERT_TRUE(embedded_test_server()->Start()); AddTabAtIndex(0, GURL(url::kAboutBlankURL), PAGE_TRANSITION_TYPED); - WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); - { - FullscreenNotificationObserver fullscreen_observer(browser()); EXPECT_FALSE(browser()->window()->IsFullscreen()); - browser()->EnterFullscreenModeForTab(tab->GetMainFrame(), {}); - fullscreen_observer.Wait(); + ASSERT_NO_FATAL_FAILURE(ToggleTabFullscreenNoRetries(true)); EXPECT_TRUE(browser()->window()->IsFullscreen()); } @@ -328,7 +322,6 @@ EXPECT_TRUE(browser()->window()->IsFullscreen()); } } -#endif // Tests mouse lock can be escaped with ESC key. IN_PROC_BROWSER_TEST_F(FullscreenControllerInteractiveTest, EscapingMouseLock) {
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 110627b5..f03d782 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -3506,6 +3506,10 @@ base::RecordAction(base::UserMetricsAction("Accel_NewTabInGroup")); } + if (command_id == IDC_NEW_INCOGNITO_WINDOW) { + base::RecordAction(base::UserMetricsAction("Accel_NewIncognitoWindow")); + } + #if BUILDFLAG(IS_CHROMEOS_ASH) // Collect information about the relative popularity of various accelerators // on Chrome OS.
diff --git a/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.cc b/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.cc index 8083161..b0e0756 100644 --- a/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.cc +++ b/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.cc
@@ -134,6 +134,8 @@ gfx::Size image_size(web_app::kWebAppIconSmall, web_app::kWebAppIconSmall); old_icon_image_view->SetImageSize(image_size); old_icon_image_view->SetImage(gfx::ImageSkia::CreateFrom1xBitmap(old_icon)); + old_icon_image_view->SetAccessibleName( + l10n_util::GetStringUTF16(IDS_WEBAPP_UPDATE_CURRENT_ICON)); layout->AddView(std::move(old_icon_image_view)); auto arrow = @@ -145,6 +147,8 @@ auto new_icon_image_view = std::make_unique<views::ImageView>(); new_icon_image_view->SetImageSize(image_size); new_icon_image_view->SetImage(gfx::ImageSkia::CreateFrom1xBitmap(new_icon)); + new_icon_image_view->SetAccessibleName( + l10n_util::GetStringUTF16(IDS_WEBAPP_UPDATE_NEW_ICON)); layout->AddView(std::move(new_icon_image_view)); layout->AddPaddingRow(
diff --git a/chrome/browser/ui/webui/customize_themes/chrome_customize_themes_handler.cc b/chrome/browser/ui/webui/customize_themes/chrome_customize_themes_handler.cc index f248dc8..b8cb2be 100644 --- a/chrome/browser/ui/webui/customize_themes/chrome_customize_themes_handler.cc +++ b/chrome/browser/ui/webui/customize_themes/chrome_customize_themes_handler.cc
@@ -47,14 +47,10 @@ void ChromeCustomizeThemesHandler::ApplyAutogeneratedTheme( SkColor frame_color) { - chrome_colors::ChromeColorsService::RecordColorAppliedHistogram( - chrome_colors::kOtherColorId); chrome_colors_service_->ApplyAutogeneratedTheme(frame_color, web_contents_); } void ChromeCustomizeThemesHandler::ApplyDefaultTheme() { - chrome_colors::ChromeColorsService::RecordColorAppliedHistogram( - chrome_colors::kDefaultColorId); chrome_colors_service_->ApplyDefaultTheme(web_contents_); } @@ -67,7 +63,6 @@ }); if (result == end) return; - chrome_colors::ChromeColorsService::RecordColorAppliedHistogram(id); chrome_colors_service_->ApplyAutogeneratedTheme(result->color, web_contents_); }
diff --git a/chrome/browser/ui/webui/customize_themes/chrome_customize_themes_handler_unittest.cc b/chrome/browser/ui/webui/customize_themes/chrome_customize_themes_handler_unittest.cc index f64300ed..309774a 100644 --- a/chrome/browser/ui/webui/customize_themes/chrome_customize_themes_handler_unittest.cc +++ b/chrome/browser/ui/webui/customize_themes/chrome_customize_themes_handler_unittest.cc
@@ -294,19 +294,3 @@ EXPECT_EQ(kAutogeneratedThemeColor, theme_service()->GetAutogeneratedThemeColor()); } - -TEST_F(ChromeCustomizeThemesHandlerTest, RecordColorAppliedHistogram) { - base::HistogramTester histogram_tester; - const char kHistogramName[] = "ChromeColors.ColorApplied"; - - constexpr SkColor kAutogeneratedThemeColor = SK_ColorBLUE; - handler()->ApplyAutogeneratedTheme(kAutogeneratedThemeColor); - histogram_tester.ExpectBucketCount(kHistogramName, 0, 1); - - constexpr int kChromeThemeId = 4; - handler()->ApplyChromeTheme(kChromeThemeId); - histogram_tester.ExpectBucketCount(kHistogramName, kChromeThemeId, 1); - - handler()->ApplyDefaultTheme(); - histogram_tester.ExpectBucketCount(kHistogramName, -1, 1); -}
diff --git a/chrome/browser/ui/webui/ntp/app_launcher_handler.cc b/chrome/browser/ui/webui/ntp/app_launcher_handler.cc index 991f4146..e8702d9 100644 --- a/chrome/browser/ui/webui/ntp/app_launcher_handler.cc +++ b/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
@@ -182,7 +182,8 @@ has_loaded_apps_(false) {} AppLauncherHandler::~AppLauncherHandler() { - ExtensionRegistry::Get(Profile::FromWebUI(web_ui()))->RemoveObserver(this); + Profile* webui_profile = Profile::FromWebUI(web_ui()); + ExtensionRegistry::Get(webui_profile)->RemoveObserver(this); } void AppLauncherHandler::CreateWebAppInfo(const web_app::AppId& app_id, @@ -473,39 +474,29 @@ base::Unretained(this))); } -void AppLauncherHandler::Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { +void AppLauncherHandler::OnAppsReordered( + const absl::optional<std::string>& extension_id) { if (ignore_changes_ || !has_loaded_apps_) return; - switch (type) { - case chrome::NOTIFICATION_APP_LAUNCHER_REORDERED: { - const std::string* id = - content::Details<const std::string>(details).ptr(); - if (id) { - base::DictionaryValue app_info; - if (web_app_provider_->registrar().IsInstalled(*id)) { - CreateWebAppInfo(*id, &app_info); - } else { - const Extension* extension = - ExtensionRegistry::Get(extension_service_->profile()) - ->GetInstalledExtension(*id); - if (!extension) { - // Extension could still be downloading or installing. - return; - } - - CreateExtensionInfo(extension, &app_info); - } - web_ui()->CallJavascriptFunctionUnsafe("ntp.appMoved", app_info); - } else { - HandleGetApps(nullptr); + if (extension_id) { + base::DictionaryValue app_info; + if (web_app_provider_->registrar().IsInstalled(*extension_id)) { + CreateWebAppInfo(*extension_id, &app_info); + } else { + const Extension* extension = + ExtensionRegistry::Get(extension_service_->profile()) + ->GetInstalledExtension(*extension_id); + if (!extension) { + // Extension could still be downloading or installing. + return; } - break; + + CreateExtensionInfo(extension, &app_info); } - default: - NOTREACHED(); + web_ui()->CallJavascriptFunctionUnsafe("ntp.appMoved", app_info); + } else { + HandleGetApps(nullptr); } } @@ -727,9 +718,8 @@ extension_pref_change_registrar_.Add(prefs::kNtpAppPageNames, callback); ExtensionRegistry::Get(profile)->AddObserver(this); - registrar_.Add(this, chrome::NOTIFICATION_APP_LAUNCHER_REORDERED, - content::Source<AppSorting>( - ExtensionSystem::Get(profile)->app_sorting())); + install_tracker_observation_.Observe( + extensions::InstallTracker::Get(profile)); web_apps_observation_.Observe(&web_app_provider_->registrar()); web_apps_policy_manager_observation_.Observe( &web_app_provider_->policy_manager());
diff --git a/chrome/browser/ui/webui/ntp/app_launcher_handler.h b/chrome/browser/ui/webui/ntp/app_launcher_handler.h index 1f371ea..e1b21b0 100644 --- a/chrome/browser/ui/webui/ntp/app_launcher_handler.h +++ b/chrome/browser/ui/webui/ntp/app_launcher_handler.h
@@ -13,6 +13,8 @@ #include "base/scoped_observation.h" #include "base/task/cancelable_task_tracker.h" #include "chrome/browser/extensions/extension_uninstall_dialog.h" +#include "chrome/browser/extensions/install_observer.h" +#include "chrome/browser/extensions/install_tracker.h" #include "chrome/browser/ui/extensions/extension_enable_flow_delegate.h" #include "chrome/browser/web_applications/components/app_registrar_observer.h" #include "chrome/browser/web_applications/components/os_integration_manager.h" @@ -24,8 +26,6 @@ #include "components/favicon/core/favicon_service.h" #include "components/prefs/pref_change_registrar.h" #include "components/sync/model/string_ordinal.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_ui_data_source.h" #include "content/public/browser/web_ui_message_handler.h" #include "extensions/browser/extension_registry_observer.h" @@ -57,7 +57,7 @@ : public content::WebUIMessageHandler, public extensions::ExtensionUninstallDialog::Delegate, public ExtensionEnableFlowDelegate, - public content::NotificationObserver, + public extensions::InstallObserver, public web_app::AppRegistrarObserver, public web_app::WebAppPolicyManagerObserver, public extensions::ExtensionRegistryObserver { @@ -82,10 +82,9 @@ // WebUIMessageHandler: void RegisterMessages() override; - // content::NotificationObserver: - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; + // extensions::InstallObserver + void OnAppsReordered( + const absl::optional<std::string>& extension_id) override; // extensions::ExtensionRegistryObserver: void OnExtensionLoaded(content::BrowserContext* browser_context, @@ -236,9 +235,9 @@ web_app::WebAppPolicyManagerObserver> web_apps_policy_manager_observation_{this}; - // We monitor changes to the extension system so that we can reload the apps - // when necessary. - content::NotificationRegistrar registrar_; + base::ScopedObservation<extensions::InstallTracker, + extensions::InstallObserver> + install_tracker_observation_{this}; // Monitor extension preference changes so that the Web UI can be notified. PrefChangeRegistrar extension_pref_change_registrar_;
diff --git a/chrome/browser/ui/webui/signin/profile_creation_customize_themes_handler.cc b/chrome/browser/ui/webui/signin/profile_creation_customize_themes_handler.cc index 6cea5b55..ab25c10 100644 --- a/chrome/browser/ui/webui/signin/profile_creation_customize_themes_handler.cc +++ b/chrome/browser/ui/webui/signin/profile_creation_customize_themes_handler.cc
@@ -22,8 +22,6 @@ void ProfileCreationCustomizeThemesHandler::ApplyAutogeneratedTheme( SkColor frame_color) { - chrome_colors::ChromeColorsService::RecordColorAppliedHistogram( - chrome_colors::kOtherColorId); auto theme = customize_themes::mojom::Theme::New(); theme->type = customize_themes::mojom::ThemeType::kAutogenerated; auto theme_colors = customize_themes::mojom::ThemeColors::New(); @@ -37,8 +35,6 @@ } void ProfileCreationCustomizeThemesHandler::ApplyDefaultTheme() { - chrome_colors::ChromeColorsService::RecordColorAppliedHistogram( - chrome_colors::kDefaultColorId); auto theme = customize_themes::mojom::Theme::New(); theme->type = customize_themes::mojom::ThemeType::kDefault; theme->info = customize_themes::mojom::ThemeInfo::NewChromeThemeId( @@ -47,7 +43,6 @@ } void ProfileCreationCustomizeThemesHandler::ApplyChromeTheme(int32_t id) { - chrome_colors::ChromeColorsService::RecordColorAppliedHistogram(id); auto theme = customize_themes::mojom::Theme::New(); theme->type = customize_themes::mojom::ThemeType::kChrome; theme->info = customize_themes::mojom::ThemeInfo::NewChromeThemeId(id);
diff --git a/chrome/chrome_cleaner/ipc/chrome_prompt_test_util.cc b/chrome/chrome_cleaner/ipc/chrome_prompt_test_util.cc index 9a876d4..664fa93f 100644 --- a/chrome/chrome_cleaner/ipc/chrome_prompt_test_util.cc +++ b/chrome/chrome_cleaner/ipc/chrome_prompt_test_util.cc
@@ -176,8 +176,9 @@ // Read the protocol version handshake. uint8_t version; + DWORD bytes_read; ASSERT_TRUE( - ::ReadFile(read_handle, &version, sizeof(version), nullptr, nullptr)) + ::ReadFile(read_handle, &version, sizeof(version), &bytes_read, nullptr)) << "errno " << ::GetLastError(); ASSERT_EQ(version, 1); // kVersion from proto_chrome_prompt_ipc.cc @@ -185,14 +186,14 @@ // Read the length of the next message. uint32_t message_length; ASSERT_TRUE(::ReadFile(read_handle, &message_length, sizeof(message_length), - nullptr, nullptr)) + &bytes_read, nullptr)) << "errno " << ::GetLastError(); // Read the next message. std::string message; ASSERT_TRUE(::ReadFile(read_handle, base::WriteInto(&message, message_length + 1), - message_length, nullptr, nullptr)) + message_length, &bytes_read, nullptr)) << "errno " << ::GetLastError(); // Parse the message into a proto and invoke a mocked function for each @@ -244,10 +245,11 @@ HANDLE write_handle = handles_.response_write_handle.Get(); uint32_t message_size = response_string.size(); + DWORD bytes_written; ASSERT_TRUE(::WriteFile(write_handle, &message_size, sizeof(uint32_t), - nullptr, nullptr)); + &bytes_written, nullptr)); ASSERT_TRUE(::WriteFile(write_handle, response_string.data(), message_size, - nullptr, nullptr)); + &bytes_written, nullptr)); } ChromePromptPipeHandles CreateTestChromePromptMessagePipes(
diff --git a/chrome/chrome_cleaner/test/cleaner_test.cc b/chrome/chrome_cleaner/test/cleaner_test.cc index 8d0121c..b431303 100644 --- a/chrome/chrome_cleaner/test/cleaner_test.cc +++ b/chrome/chrome_cleaner/test/cleaner_test.cc
@@ -21,7 +21,6 @@ #include "base/task/thread_pool.h" #include "base/test/task_environment.h" #include "base/test/test_timeouts.h" -#include "base/win/windows_version.h" #include "chrome/chrome_cleaner/buildflags.h" #include "chrome/chrome_cleaner/constants/chrome_cleaner_switches.h" #include "chrome/chrome_cleaner/ipc/chrome_prompt_test_util.h" @@ -603,12 +602,6 @@ void SetUp() override { CleanerTestBase::SetUp(); - // TODO(crbug.com/1210601): All uses of MockChromePromptResponder are - // failing on Windows 7. Disable this test suite until the problem can be - // investigated. - if (base::win::GetVersion() < base::win::Version::WIN8) - GTEST_SKIP() << "Skipping on Win7: crbug.com/1210601"; - command_line_ = BuildCommandLine(kCleanerExecutable, ExecutionMode::kScanning); chrome_cleaner::ChromePromptPipeHandles pipe_handles =
diff --git a/chrome/renderer/v8_unwinder.cc b/chrome/renderer/v8_unwinder.cc index 71509f24..54d6153 100644 --- a/chrome/renderer/v8_unwinder.cc +++ b/chrome/renderer/v8_unwinder.cc
@@ -8,6 +8,14 @@ #include <memory> #include <utility> +#include "build/build_config.h" + +#if defined(ARCH_CPU_ARM_FAMILY) && defined(ARCH_CPU_32_BITS) +// V8 requires the embedder to establish the architecture define. +#define V8_TARGET_ARCH_ARM 1 +#include "v8/include/v8-unwinder-state.h" +#endif + namespace { class V8Module : public base::ModuleCache::Module { @@ -76,6 +84,52 @@ return range; } +void CopyCalleeSavedRegisterFromRegisterContext( + const base::RegisterContext& register_context, + v8::CalleeSavedRegisters* callee_saved_registers) { +#if defined(ARCH_CPU_ARM_FAMILY) && defined(ARCH_CPU_32_BITS) + // ARM requires callee-saved registers to be restored: + // https://crbug.com/v8/10799. + DCHECK(callee_saved_registers); + callee_saved_registers->arm_r4 = + reinterpret_cast<void*>(register_context.arm_r4); + callee_saved_registers->arm_r5 = + reinterpret_cast<void*>(register_context.arm_r5); + callee_saved_registers->arm_r6 = + reinterpret_cast<void*>(register_context.arm_r6); + callee_saved_registers->arm_r7 = + reinterpret_cast<void*>(register_context.arm_r7); + callee_saved_registers->arm_r8 = + reinterpret_cast<void*>(register_context.arm_r8); + callee_saved_registers->arm_r9 = + reinterpret_cast<void*>(register_context.arm_r9); + callee_saved_registers->arm_r10 = + reinterpret_cast<void*>(register_context.arm_r10); +#endif +} + +void CopyCalleeSavedRegisterToRegisterContext( + const v8::CalleeSavedRegisters* callee_saved_registers, + base::RegisterContext& register_context) { +#if defined(ARCH_CPU_ARM_FAMILY) && defined(ARCH_CPU_32_BITS) + DCHECK(callee_saved_registers); + register_context.arm_r4 = + reinterpret_cast<uintptr_t>(callee_saved_registers->arm_r4); + register_context.arm_r5 = + reinterpret_cast<uintptr_t>(callee_saved_registers->arm_r5); + register_context.arm_r6 = + reinterpret_cast<uintptr_t>(callee_saved_registers->arm_r6); + register_context.arm_r7 = + reinterpret_cast<uintptr_t>(callee_saved_registers->arm_r7); + register_context.arm_r8 = + reinterpret_cast<uintptr_t>(callee_saved_registers->arm_r8); + register_context.arm_r9 = + reinterpret_cast<uintptr_t>(callee_saved_registers->arm_r9); + register_context.arm_r10 = + reinterpret_cast<uintptr_t>(callee_saved_registers->arm_r10); +#endif +} + } // namespace V8Unwinder::V8Unwinder(v8::Isolate* isolate) @@ -199,6 +253,13 @@ register_state.fp = reinterpret_cast<void*>( base::RegisterContextFramePointer(thread_context)); +#if defined(ARCH_CPU_ARM_FAMILY) && defined(ARCH_CPU_32_BITS) + if (!register_state.callee_saved) + register_state.callee_saved = std::make_unique<v8::CalleeSavedRegisters>(); +#endif + CopyCalleeSavedRegisterFromRegisterContext(*thread_context, + register_state.callee_saved.get()); + if (!v8::Unwinder::TryUnwindV8Frames( js_entry_stubs_, code_ranges_.size(), code_ranges_.buffer(), ®ister_state, reinterpret_cast<const void*>(stack_top))) { @@ -217,6 +278,9 @@ base::RegisterContextFramePointer(thread_context) = reinterpret_cast<uintptr_t>(register_state.fp); + CopyCalleeSavedRegisterToRegisterContext(register_state.callee_saved.get(), + *thread_context); + stack->emplace_back( base::RegisterContextInstructionPointer(thread_context), module_cache()->GetModuleForAddress(
diff --git a/chrome/test/base/run_all_unittests.cc b/chrome/test/base/run_all_unittests.cc index 3717bc1..63170f2 100644 --- a/chrome/test/base/run_all_unittests.cc +++ b/chrome/test/base/run_all_unittests.cc
@@ -7,13 +7,19 @@ #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_io_thread.h" #include "base/threading/platform_thread.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/test/base/chrome_unit_test_suite.h" #include "content/public/test/unittest_test_suite.h" #include "mojo/core/embedder/scoped_ipc_support.h" -#if defined(OS_WIN) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && \ + (defined(OS_WIN) || defined(OS_MAC) || \ + (defined(OS_POSIX) && !defined(OS_ANDROID) && \ + !BUILDFLAG(IS_CHROMEOS_ASH))) +#include "chrome/test/base/scoped_channel_override.h" +#elif defined(OS_WIN) #include "chrome/install_static/test/scoped_install_details.h" #endif @@ -37,7 +43,17 @@ test_io_thread.task_runner(), mojo::core::ScopedIPCSupport::ShutdownPolicy::FAST); -#if defined(OS_WIN) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) && \ + (defined(OS_WIN) || defined(OS_MAC) || \ + (defined(OS_POSIX) && !defined(OS_ANDROID) && \ + !BUILDFLAG(IS_CHROMEOS_ASH))) + // Tests running in Google Chrome builds on Win/Mac/Lin/Lacros should present + // as stable channel by default. + chrome::ScopedChannelOverride scoped_channel_override( + chrome::ScopedChannelOverride::Channel::kStable); +#elif defined(OS_WIN) + // Tests running in Chromium builds on Windows need basic InstallDetails even + // though there are no channels. install_static::ScopedInstallDetails scoped_install_details; #endif
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index 42285b2..05ae7b48 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -382,7 +382,27 @@ "SavingBrowserHistoryDisabled": true }, "prefs": { - "history.saving_disabled": {} + "history.saving_disabled": { + "value": true + } + } + }, + { + "policies": { + "SavingBrowserHistoryDisabled": false + }, + "prefs": { + "history.saving_disabled": { + "value": false + } + } + }, + { + "policies": {}, + "prefs": { + "history.saving_disabled": { + "default_value": false + } } } ] @@ -1152,10 +1172,30 @@ "policy_pref_mapping_tests": [ { "policies": { + "SafeBrowsingEnabled": true + }, + "prefs": { + "safebrowsing.enabled": { + "value": true + } + } + }, + { + "policies": { "SafeBrowsingEnabled": false }, "prefs": { - "safebrowsing.enabled": {} + "safebrowsing.enabled": { + "value": false + } + } + }, + { + "policies": {}, + "prefs": { + "safebrowsing.enabled": { + "default_value": true + } } } ] @@ -1927,12 +1967,34 @@ ], "policy_pref_mapping_tests": [ { + "note": "Checking default value (no policies set)", + "policies": {}, + "prefs": { + "auth.disable_negotiate_cname_lookup": { + "location": "local_state", + "default_value": false + } + } + }, + { "policies": { "DisableAuthNegotiateCnameLookup": true }, "prefs": { "auth.disable_negotiate_cname_lookup": { - "location": "local_state" + "location": "local_state", + "value": true + } + } + }, + { + "policies": { + "DisableAuthNegotiateCnameLookup": false + }, + "prefs": { + "auth.disable_negotiate_cname_lookup": { + "location": "local_state", + "value": false } } } @@ -1947,12 +2009,34 @@ ], "policy_pref_mapping_tests": [ { + "note": "Checking default value (no policies set)", + "policies": {}, + "prefs": { + "auth.enable_negotiate_port": { + "location": "local_state", + "default_value": false + } + } + }, + { "policies": { "EnableAuthNegotiatePort": true }, "prefs": { "auth.enable_negotiate_port": { - "location": "local_state" + "location": "local_state", + "value": true + } + } + }, + { + "policies": { + "EnableAuthNegotiatePort": false + }, + "prefs": { + "auth.enable_negotiate_port": { + "location": "local_state", + "value": false } } } @@ -6223,10 +6307,31 @@ "policy_pref_mapping_tests": [ { "policies": { - "ScreenDimDelayAC": 420000 + "ScreenDimDelayAC": 12345 }, "prefs": { - "power.ac_screen_dim_delay_ms": {} + "power.ac_screen_dim_delay_ms": { + "value": 12345 + } + } + }, + { + "note": "Should clamp to range 0..INT_MAX", + "policies": { + "ScreenDimDelayAC": -1 + }, + "prefs": { + "power.ac_screen_dim_delay_ms": { + "value": 0 + } + } + }, + { + "policies": {}, + "prefs": { + "power.ac_screen_dim_delay_ms": { + "default_value": 420000 + } } } ] @@ -6298,10 +6403,31 @@ "policy_pref_mapping_tests": [ { "policies": { - "ScreenDimDelayBattery": 300000 + "ScreenDimDelayBattery": 1111 }, "prefs": { - "power.battery_screen_dim_delay_ms": {} + "power.battery_screen_dim_delay_ms": { + "value": 1111 + } + } + }, + { + "note": "Should clamp to range 0..INT_MAX", + "policies": { + "ScreenDimDelayBattery": -1 + }, + "prefs": { + "power.battery_screen_dim_delay_ms": { + "value": 0 + } + } + }, + { + "policies": {}, + "prefs": { + "power.battery_screen_dim_delay_ms": { + "default_value": 300000 + } } } ] @@ -7947,6 +8073,17 @@ "value": 90 } } + }, + { + "policies": {}, + "prefs": { + "power.ac_screen_brightness_percent": { + "default_value": -1 + }, + "power.battery_screen_brightness_percent": { + "default_value": -1 + } + } } ] }, @@ -11105,26 +11242,7 @@ ] }, "UserAgentClientHintsEnabled": { - "os": [ - "win", - "linux", - "mac", - "chromeos", - "android" - ], - "policy_pref_mapping_tests": [ - { - "policies": { - "UserAgentClientHintsEnabled": true - }, - "prefs": { - "policy.user_agent_client_hints_enabled": { - "location": "local_state", - "value": true - } - } - } - ] + "reason_for_missing_test": "Policy was removed" }, "ShowFullUrlsInAddressBar": { "os": [ @@ -11475,12 +11593,20 @@ ] }, "DataLeakPreventionClipboardCheckSizeLimit": { - "os": ["chromeos"], + "os": [ + "chromeos" + ], "can_be_recommended": false, "policy_pref_mapping_tests": [ { - "policies": { "DataLeakPreventionClipboardCheckSizeLimit": 50 }, - "prefs": { "policy.dlp_clipboard_check_size_limit": { "location": "local_state" } } + "policies": { + "DataLeakPreventionClipboardCheckSizeLimit": 50 + }, + "prefs": { + "policy.dlp_clipboard_check_size_limit": { + "location": "local_state" + } + } } ] },
diff --git a/chrome/test/data/webui/chromeos/personalization_app/test_mojo_interface_provider.js b/chrome/test/data/webui/chromeos/personalization_app/test_mojo_interface_provider.js index 8070b3d..f5d06e7 100644 --- a/chrome/test/data/webui/chromeos/personalization_app/test_mojo_interface_provider.js +++ b/chrome/test/data/webui/chromeos/personalization_app/test_mojo_interface_provider.js
@@ -19,6 +19,9 @@ 'getLocalImageThumbnail', 'getCurrentWallpaper', 'selectWallpaper', + 'setDailyRefreshCollectionId', + 'getDailyRefreshCollectionId', + 'updateDailyRefreshWallpaper', ]); /** @@ -91,6 +94,8 @@ this.selectWallpaperResponse = true; this.selectLocalImageResponse = true; + + this.updateDailyRefreshWallpaperResponse = true; } /** @@ -159,6 +164,23 @@ this.methodCalled('selectCustomWallpaperLayout', layout); } + /** @override */ + setDailyRefreshCollectionId(collectionId) { + this.methodCalled('setDailyRefreshCollectionId', collectionId); + } + + /** @override */ + getDailyRefreshCollectionId() { + this.methodCalled('getDailyRefreshCollectionId'); + return Promise.resolve({collectionId: this.collections_[0].id}); + } + + /** @override */ + updateDailyRefreshWallpaper() { + this.methodCalled('updateDailyRefreshWallpaper'); + return Promise.resolve({success: this.updateDailyRefreshWallpaperResponse}); + } + /** * @param {!Array<!chromeos.personalizationApp.mojom.WallpaperCollection>} * collections
diff --git a/chrome/test/data/webui/chromeos/personalization_app/wallpaper_selected_element_test.js b/chrome/test/data/webui/chromeos/personalization_app/wallpaper_selected_element_test.js index 15a8184..3fcbd965 100644 --- a/chrome/test/data/webui/chromeos/personalization_app/wallpaper_selected_element_test.js +++ b/chrome/test/data/webui/chromeos/personalization_app/wallpaper_selected_element_test.js
@@ -6,6 +6,7 @@ import {ActionName} from 'chrome://personalization/trusted/personalization_actions.js'; import {emptyState} from 'chrome://personalization/trusted/personalization_reducers.js'; +import {Paths} from 'chrome://personalization/trusted/personalization_router_element.js'; import {WallpaperSelected} from 'chrome://personalization/trusted/wallpaper_selected_element.js'; import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from '../../chai_assert.js'; import {flushTasks, waitAfterNextRender} from '../../test_util.m.js'; @@ -200,4 +201,52 @@ const img = wallpaperSelectedElement.shadowRoot.querySelector('img'); assertEquals('data:image/png;base64,abc=', img.src); }); + + test('shows daily refresh option on the collection view', async () => { + personalizationStore.data.selected = { + url: {url: 'data:image/png;base64,abc='}, + attribution: [], + assetId: BigInt(100), + }; + personalizationStore.data.loading.selected = false; + + wallpaperSelectedElement = + initElement(WallpaperSelected.is, {'path': Paths.CollectionImages}); + await waitAfterNextRender(wallpaperSelectedElement); + + const dailyRefresh = + wallpaperSelectedElement.shadowRoot.getElementById('dailyRefresh'); + assertTrue(!!dailyRefresh); + + const refreshWallpaper = + wallpaperSelectedElement.shadowRoot.getElementById('refreshWallpaper'); + assertFalse(!!refreshWallpaper); + }); + + test( + 'shows refresh button only on collection with daily refresh enabled', + async () => { + personalizationStore.data.selected = { + url: {url: 'data:image/png;base64,abc='}, + attribution: [], + assetId: BigInt(100), + }; + personalizationStore.data.loading.selected = false; + const collection_id = wallpaperProvider.collections[0].id; + personalizationStore.data.dailyRefresh = { + collectionId: collection_id, + }; + + wallpaperSelectedElement = initElement( + WallpaperSelected.is, + {'path': Paths.CollectionImages, 'collectionId': collection_id}); + personalizationStore.notifyObservers(); + + await waitAfterNextRender(wallpaperSelectedElement); + + const newRefreshWallpaper = + wallpaperSelectedElement.shadowRoot.getElementById( + 'refreshWallpaper'); + assertTrue(!!newRefreshWallpaper); + }); }
diff --git a/chromecast/browser/cast_web_contents_impl.cc b/chromecast/browser/cast_web_contents_impl.cc index efa9fcf..529cbd3 100644 --- a/chromecast/browser/cast_web_contents_impl.cc +++ b/chromecast/browser/cast_web_contents_impl.cc
@@ -1039,14 +1039,16 @@ void CastWebContentsImpl::TracePageLoadBegin(const GURL& url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - TRACE_EVENT_ASYNC_BEGIN1("browser,navigation", "CastWebContentsImpl Launch", - this, "URL", url.possibly_invalid_spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "browser,navigation", "CastWebContentsImpl Launch", TRACE_ID_LOCAL(this), + "URL", url.possibly_invalid_spec()); } void CastWebContentsImpl::TracePageLoadEnd(const GURL& url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - TRACE_EVENT_ASYNC_END1("browser,navigation", "CastWebContentsImpl Launch", - this, "URL", url.possibly_invalid_spec()); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "browser,navigation", "CastWebContentsImpl Launch", TRACE_ID_LOCAL(this), + "URL", url.possibly_invalid_spec()); } void CastWebContentsImpl::DisableDebugging() {
diff --git a/chromeos/chromeos_strings.grd b/chromeos/chromeos_strings.grd index a5444a06..372287430 100644 --- a/chromeos/chromeos_strings.grd +++ b/chromeos/chromeos_strings.grd
@@ -1556,6 +1556,12 @@ <message name="IDS_PERSONALIZATION_APP_FILL" desc="Label for fill cropping option for local images"> Fill </message> + <message name="IDS_PERSONALIZATION_APP_CHANGE_DAILY" desc="Label for daily refresh option"> + Change Daily + </message> + <message name="IDS_PERSONALIZATION_APP_REFRESH" desc="Label for wallpaper refresh button"> + Refresh + </message> <!-- Traffic Counters UI --> <message name="IDS_TRAFFIC_COUNTERS_UNKNOWN" desc="Traffic counters related to an unknown source">
diff --git a/chromeos/chromeos_strings_grd/IDS_PERSONALIZATION_APP_CHANGE_DAILY.png.sha1 b/chromeos/chromeos_strings_grd/IDS_PERSONALIZATION_APP_CHANGE_DAILY.png.sha1 new file mode 100644 index 0000000..1e4b07d --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_PERSONALIZATION_APP_CHANGE_DAILY.png.sha1
@@ -0,0 +1 @@ +655f1c74c64dacee7fdd183219abb143032bb272 \ No newline at end of file
diff --git a/chromeos/chromeos_strings_grd/IDS_PERSONALIZATION_APP_REFRESH.png.sha1 b/chromeos/chromeos_strings_grd/IDS_PERSONALIZATION_APP_REFRESH.png.sha1 new file mode 100644 index 0000000..1e4b07d --- /dev/null +++ b/chromeos/chromeos_strings_grd/IDS_PERSONALIZATION_APP_REFRESH.png.sha1
@@ -0,0 +1 @@ +655f1c74c64dacee7fdd183219abb143032bb272 \ No newline at end of file
diff --git a/chromeos/components/personalization_app/mojom/personalization_app.mojom b/chromeos/components/personalization_app/mojom/personalization_app.mojom index b698946..9f1bb37 100644 --- a/chromeos/components/personalization_app/mojom/personalization_app.mojom +++ b/chromeos/components/personalization_app/mojom/personalization_app.mojom
@@ -131,4 +131,14 @@ // Sets the custom layout for current wallpaper SetCustomWallpaperLayout(WallpaperLayout layout); + + // Set and enable daily refresh for the given |collection_id|. + SetDailyRefreshCollectionId(string collection_id); + + // Get the daily refresh collection id. It can be empty if daily refresh is + // not enabled. + GetDailyRefreshCollectionId() => (string collection_id); + + // Refresh the wallpaper. Noop if daily refresh is not enabled. + UpdateDailyRefreshWallpaper() => (bool success); };
diff --git a/chromeos/components/personalization_app/personalization_app_ui.cc b/chromeos/components/personalization_app/personalization_app_ui.cc index aaa72824..055c21d 100644 --- a/chromeos/components/personalization_app/personalization_app_ui.cc +++ b/chromeos/components/personalization_app/personalization_app_ui.cc
@@ -63,7 +63,9 @@ {"myImagesLabel", IDS_PERSONALIZATION_APP_MY_IMAGES}, {"wallpaperCollections", IDS_PERSONALIZATION_APP_WALLPAPER_COLLECTIONS}, {"center", IDS_PERSONALIZATION_APP_CENTER}, - {"fill", IDS_PERSONALIZATION_APP_FILL}}; + {"fill", IDS_PERSONALIZATION_APP_FILL}, + {"changeDaily", IDS_PERSONALIZATION_APP_CHANGE_DAILY}, + {"refresh", IDS_PERSONALIZATION_APP_REFRESH}}; source->AddLocalizedStrings(kLocalizedStrings); source->UseStringsJs(); }
diff --git a/chromeos/components/personalization_app/resources/common/icons.js b/chromeos/components/personalization_app/resources/common/icons.js index 3ead381d..cc49928 100644 --- a/chromeos/components/personalization_app/resources/common/icons.js +++ b/chromeos/components/personalization_app/resources/common/icons.js
@@ -30,6 +30,40 @@ </g> </defs> </svg> + <svg> + <defs> + <g id="change-daily"> + <svg width="20" height="20" viewBox="0 0 20 20" fill="none" + xmlns="http://www.w3.org/2000/svg">> + <rect width="20" height="20" fill="white"/> + <path d="M17.4989 4.16672H19.1656V15.8334H17.4989V4.16672ZM14.1656 + 4.16672H15.8322V15.8334H14.1656V4.16672ZM11.6656 + 4.16672H1.66558C1.20724 4.16672 0.832245 4.54172 0.832245 + 5.00005V15.0001C0.832245 15.4584 1.20724 15.8334 1.66558 + 15.8334H11.6656C12.1239 15.8334 12.4989 15.4584 12.4989 + 15.0001V5.00005C12.4989 4.54172 12.1239 4.16672 11.6656 + 4.16672ZM10.8322 14.1667H2.49891V5.83338H10.8322V14.1667ZM8.00724 + 9.37505L6.04058 11.7084L4.79058 10.0001L2.91558 + 12.5001H10.4156L8.00724 9.37505Z" fill="#1A73E8"/> + </svg> + </g> + </defs> + </svg> + <svg> + <defs> + <g id="refresh"> + <svg width="20" height="20" viewBox="0 0 20 20" fill="none" + xmlns="http://www.w3.org/2000/svg"> + <rect width="20" height="20" fill="white"/> + <path d="M10 3C6.136 3 3 6.136 3 10C3 13.864 6.136 17 10 17C12.1865 17 + 14.1399 15.9959 15.4239 14.4239L13.9984 12.9984C13.0852 14.2129 + 11.6325 15 10 15C7.24375 15 5 12.7563 5 10C5 7.24375 7.24375 5 10 + 5C11.6318 5 13.0839 5.78641 13.9972 7H11V9H17V3H15V5.10253C13.7292 + 3.80529 11.9581 3 10 3Z" fill="#1A73E8"/> + </svg> + </g> + </defs> + </svg> </iron-iconset-svg>`; document.head.appendChild(template.content);
diff --git a/chromeos/components/personalization_app/resources/trusted/BUILD.gn b/chromeos/components/personalization_app/resources/trusted/BUILD.gn index 254ecd46..7839a49 100644 --- a/chromeos/components/personalization_app/resources/trusted/BUILD.gn +++ b/chromeos/components/personalization_app/resources/trusted/BUILD.gn
@@ -152,10 +152,14 @@ deps = [ ":personalization_controller", ":personalization_reducers", + ":personalization_router_element", ":personalization_store", ":styles", + "../common:icons", "../common:styles", "../common:utils", + "//third_party/polymer/v3_0/components-chromium/iron-icon:iron-icon", + "//third_party/polymer/v3_0/components-chromium/iron-iconset-svg:iron-iconset-svg", "//third_party/polymer/v3_0/components-chromium/paper-spinner:paper-spinner-lite", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", ]
diff --git a/chromeos/components/personalization_app/resources/trusted/personalization_actions.js b/chromeos/components/personalization_app/resources/trusted/personalization_actions.js index 1c1abc57..8a53f2e 100644 --- a/chromeos/components/personalization_app/resources/trusted/personalization_actions.js +++ b/chromeos/components/personalization_app/resources/trusted/personalization_actions.js
@@ -15,11 +15,14 @@ BEGIN_LOAD_IMAGES_FOR_COLLECTIONS: 'begin_load_images_for_collections', BEGIN_LOAD_LOCAL_IMAGE_DATA: 'begin_load_local_image_data', BEGIN_SELECT_IMAGE: 'begin_select_image', + BEGIN_UPDATE_DAILY_REFRESH_IMAGE: 'begin_update_daily_refresh_image', SET_COLLECTIONS: 'set_collections', + SET_DAILY_REFRESH_COLLECTION_ID: 'set_daily_refresh_collection_id', SET_IMAGES_FOR_COLLECTION: 'set_images_for_collection', SET_LOCAL_IMAGES: 'set_local_images', SET_LOCAL_IMAGE_DATA: 'set_local_image_data', SET_SELECTED_IMAGE: 'set_selected_image', + SET_UPDATED_DAILY_REFRESH_IMAGE: 'set_updated_daily_refreshed_image', }; @@ -49,6 +52,16 @@ } /** + * Notify that a user has clicked on the refresh button. + * @return {!Action} + */ +export function beginUpdateDailyRefreshImageAction() { + return { + name: ActionName.BEGIN_UPDATE_DAILY_REFRESH_IMAGE, + }; +} + +/** * Notify that a user has clicked on an image to set as wallpaper. * @param {!DisplayableImage} image * @return {!Action} @@ -71,6 +84,17 @@ } /** + * Set and enable daily refresh for given collectionId. + * @param {?string} collectionId + * @return {!Action} + */ +export function setDailyRefreshCollectionIdAction(collectionId) { + return { + collectionId, name: ActionName.SET_DAILY_REFRESH_COLLECTION_ID, + } +} + +/** * Set the images for a given collection. May be called with null if an error * occurred. * @param {string} collectionId @@ -112,6 +136,16 @@ } /** + * Notify that a image has been refreshed. + * @return {!Action} + */ +export function setUpdatedDailyRefreshImageAction() { + return { + name: ActionName.SET_UPDATED_DAILY_REFRESH_IMAGE, + }; +} + +/** * Returns an action to set the current image as currently selected across the * app. Can be called with null to represent no image currently selected or that * an error occurred.
diff --git a/chromeos/components/personalization_app/resources/trusted/personalization_controller.js b/chromeos/components/personalization_app/resources/trusted/personalization_controller.js index ea588858..0662e82 100644 --- a/chromeos/components/personalization_app/resources/trusted/personalization_controller.js +++ b/chromeos/components/personalization_app/resources/trusted/personalization_controller.js
@@ -3,7 +3,7 @@ // found in the LICENSE file. import {isNonEmptyArray} from '../common/utils.js'; -import {beginLoadImagesForCollectionsAction, beginLoadLocalImageDataAction, beginSelectImageAction, setCollectionsAction, setImagesForCollectionAction, setLocalImageDataAction, setLocalImagesAction, setSelectedImageAction} from './personalization_actions.js'; +import {beginLoadImagesForCollectionsAction, beginLoadLocalImageDataAction, beginSelectImageAction, beginUpdateDailyRefreshImageAction, setCollectionsAction, setDailyRefreshCollectionIdAction, setImagesForCollectionAction, setLocalImageDataAction, setLocalImagesAction, setSelectedImageAction, setUpdatedDailyRefreshImageAction} from './personalization_actions.js'; import {PersonalizationStore} from './personalization_store.js'; /** @@ -124,6 +124,9 @@ if (!success) { console.warn('Error setting wallpaper'); } + // Explicitly disable daily refresh if wallpaper is manually selected. + setDailyRefreshCollectionId('', provider, store); + // Retrieve the current wallpaper from client to get the correct attribution. getCurrentWallpaper(provider, store); } @@ -139,6 +142,46 @@ } /** + * @param {string} collectionId + * @param {!chromeos.personalizationApp.mojom.WallpaperProviderInterface} + * provider + * @param {!PersonalizationStore} store + */ +export async function setDailyRefreshCollectionId( + collectionId, provider, store) { + await provider.setDailyRefreshCollectionId(collectionId); + // Dispatch action to highlight enabled daily refresh. + getDailyRefreshCollectionId(provider, store); +} + +/** + * Get the daily refresh collection id. It can be empty if daily refresh is not + * enabled. + * @param {!chromeos.personalizationApp.mojom.WallpaperProviderInterface} + * provider + * @param {!PersonalizationStore} store + */ +export async function getDailyRefreshCollectionId(provider, store) { + const {collectionId} = await provider.getDailyRefreshCollectionId(); + store.dispatch(setDailyRefreshCollectionIdAction(collectionId)); +} + +/** + * Refresh the wallpaper. Noop if daily refresh is not enabled. + * @param {!chromeos.personalizationApp.mojom.WallpaperProviderInterface} + * provider + * @param {!PersonalizationStore} store + */ +export async function updateDailyRefreshWallpaper(provider, store) { + store.dispatch(beginUpdateDailyRefreshImageAction()); + const {success} = await provider.updateDailyRefreshWallpaper(); + if (success) { + store.dispatch(setUpdatedDailyRefreshImageAction()); + getCurrentWallpaper(provider, store); + } +} + +/** * Fetches list of collections, then fetches list of images for each collection. * @param {!chromeos.personalizationApp.mojom.WallpaperProviderInterface} * provider
diff --git a/chromeos/components/personalization_app/resources/trusted/personalization_reducers.js b/chromeos/components/personalization_app/resources/trusted/personalization_reducers.js index 6f2e1bd4..89afa9db 100644 --- a/chromeos/components/personalization_app/resources/trusted/personalization_reducers.js +++ b/chromeos/components/personalization_app/resources/trusted/personalization_reducers.js
@@ -56,6 +56,7 @@ * }, * selected: boolean, * setWallpaper: boolean, + * refreshWallpaper: boolean, * }} */ export let LoadingState; @@ -72,12 +73,21 @@ export let LocalState; /** + * Stores daily refresh state. + * @typedef {{ + * collectionId: ?string + * }} + */ +export let DailyRefreshState; + +/** * Top level personalization app state. * @typedef {{ * backdrop: !BackdropState, * loading: !LoadingState, * local: !LocalState, * selected: ?DisplayableImage, + * dailyRefresh: !DailyRefreshState, * }} */ export let PersonalizationState; @@ -95,9 +105,11 @@ local: {images: true, data: {}}, selected: true, setWallpaper: false, + refreshWallpaper: false, }, local: {images: null, data: {}}, selected: null, + dailyRefresh: {collectionId: null}, }; } @@ -202,6 +214,10 @@ }); case ActionName.SET_SELECTED_IMAGE: return /** @type {!LoadingState} */ ({...state, selected: false}); + case ActionName.BEGIN_UPDATE_DAILY_REFRESH_IMAGE: + return /** @type {!LoadingState} */ ({...state, refreshWallpaper: true}); + case ActionName.SET_UPDATED_DAILY_REFRESH_IMAGE: + return /** @type {!LoadingState} */ ({...state, refreshWallpaper: false}); default: return state; } @@ -246,11 +262,29 @@ } } +/** + * @param {!DailyRefreshState} state + * @param {!Action} action + * @returns {!DailyRefreshState} + */ +function dailyRefreshReducer(state, action) { + switch (action.name) { + case ActionName.SET_DAILY_REFRESH_COLLECTION_ID: + return /** @type {!DailyRefreshState} */ ({ + ...state, + collectionId: action.collectionId, + }); + default: + return state; + } +} + const root = combineReducers({ backdrop: backdropReducer, loading: loadingReducer, local: localReducer, selected: selectedReducer, + dailyRefresh: dailyRefreshReducer, }); /**
diff --git a/chromeos/components/personalization_app/resources/trusted/personalization_router_element.html b/chromeos/components/personalization_app/resources/trusted/personalization_router_element.html index 681de5f..a36f639 100644 --- a/chromeos/components/personalization_app/resources/trusted/personalization_router_element.html +++ b/chromeos/components/personalization_app/resources/trusted/personalization_router_element.html
@@ -38,7 +38,8 @@ <div id="leftspacer"></div> <wallpaper-breadcrumb path=[[path_]] collection-id="[[queryParams_.id]]"> </wallpaper-breadcrumb> - <wallpaper-selected></wallpaper-selected> + <wallpaper-selected path=[[path_]] collection-id="[[queryParams_.id]]"> + </wallpaper-selected> <wallpaper-collections hidden$="[[!shouldShowCollections_(path_)]]"> </wallpaper-collections> <wallpaper-images collection-id="[[queryParams_.id]]"
diff --git a/chromeos/components/personalization_app/resources/trusted/wallpaper_selected_element.html b/chromeos/components/personalization_app/resources/trusted/wallpaper_selected_element.html index 3780fb38..f3e87ae 100644 --- a/chromeos/components/personalization_app/resources/trusted/wallpaper_selected_element.html +++ b/chromeos/components/personalization_app/resources/trusted/wallpaper_selected_element.html
@@ -58,23 +58,36 @@ line-height: 20px; } - #currentWallpaperMoreOptions { + #wallpaperOptions, + #collectionOptions { display: flex; } - #currentWallpaperMoreOptions > div { + #wallpaperOptions > div { display: flex; padding: 8px; margin-right: 8px; border: 1px solid var(--google-grey-refresh-300); border-radius: 16px; + cursor: pointer; } - #currentWallpaperMoreOptions #center.selected, - #currentWallpaperMoreOptions #fill.selected { + #wallpaperOptions .text, + #collectionOptions .text { + margin-left: 8px; + } + + #wallpaperOptions #fill.selected, + #wallpaperOptions #center.selected { color: var(--cros-toggle-color); pointer-events: none; } + + #collectionOptions > cr-button { + padding: 16px; + margin-right: 8px; + border-radius: 16px; + } </style> <header id="container" tabindex="0" aria-label="[[getAriaLabel_(image_)]]" role="heading" aria-level="1"> @@ -89,22 +102,39 @@ <p title="[[item]]">[[item]]</p> </template> </dom-repeat> - <template is="dom-if" if="[[showMoreOptions_]]"> - <div id="currentWallpaperMoreOptions"> - <div id="fill" data-layout="FILL" on-click="onClickLayoutIcon_" - class$="[[computeFillOptionClass_(image_)]]"> - <!-- TODO(b/178105894) add icon --> - <div class="text">[[i18n('fill')]]</div> - </div> - <div id="center" data-layout="CENTER" on-click="onClickLayoutIcon_" - class$="[[computeCenterOptionClass_(image_)]]"> - <!-- TODO(b/178105894) add icon --> - <div class="text">[[i18n('center')]]</div> - </div> - </div> - </template> + <div id="wallpaperOptions"> + <template is="dom-if" if="[[showWallpaperOptions_]]"> + <div id="fill" data-layout="FILL" on-click="onClickLayoutIcon_" + class$="[[computeFillOptionClass_(image_)]]"> + <!-- TODO(b/178105894) add icon --> + <div class="text">[[i18n('fill')]]</div> + </div> + <div id="center" data-layout="CENTER" on-click="onClickLayoutIcon_" + class$="[[computeCenterOptionClass_(image_)]]"> + <!-- TODO(b/178105894) add icon --> + <div class="text">[[i18n('center')]]</div> + </div> + </template> + </div> + <div id="collectionOptions"> + <template is="dom-if" if="[[showRefreshButton_]]"> + <cr-button id="refreshWallpaper" + on-click="onClickUpdateDailyRefreshWallpaper_"> + <iron-icon icon="personalization:refresh"></iron-icon> + <div class="text">[[i18n('refresh')]]</div> + </cr-button> + </template> + <template is="dom-if" if="[[showCollectionOptions_]]"> + <cr-button id="dailyRefresh" data-collection-id$="[[collectionId]]" + data-daily-refresh-collection-id$="[[dailyRefreshCollectionId_]]" + aria-pressed="[[ariaPressed_]]" + on-click="onClickDailyRefreshToggle_"> + <iron-icon icon="[[dailyRefreshIcon_]]"></iron-icon> + <div class="text">[[i18n('changeDaily')]]</div> + </cr-button> + </template> + </div> </div> - </template> <template is="dom-if" if="[[hasError_]]"> <!-- TODO(b/186668250) real error state -->
diff --git a/chromeos/components/personalization_app/resources/trusted/wallpaper_selected_element.js b/chromeos/components/personalization_app/resources/trusted/wallpaper_selected_element.js index a6abacf..0327b02 100644 --- a/chromeos/components/personalization_app/resources/trusted/wallpaper_selected_element.js +++ b/chromeos/components/personalization_app/resources/trusted/wallpaper_selected_element.js
@@ -7,11 +7,16 @@ * wallpaper. */ +import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; +import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; +import 'chrome://resources/polymer/v3_0/iron-iconset-svg/iron-iconset-svg.js'; +import '../common/icons.js'; import {assert} from 'chrome://resources/js/assert.m.js' import {html} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {getWallpaperProvider} from './mojo_interface_provider.js'; -import {getCurrentWallpaper, setCustomWallpaperLayout} from './personalization_controller.js'; +import {getCurrentWallpaper, getDailyRefreshCollectionId, setCustomWallpaperLayout, setDailyRefreshCollectionId, updateDailyRefreshWallpaper} from './personalization_controller.js'; import {WallpaperLayout, WallpaperType} from './personalization_reducers.js'; +import {Paths} from './personalization_router_element.js'; import {WithPersonalizationStore} from './personalization_store.js'; /** @@ -48,6 +53,20 @@ static get properties() { return { /** + * The current collection id to display. + */ + collectionId: { + type: String, + }, + + /** + * The current path of the page. + */ + path: { + type: String, + }, + + /** * @type {?chromeos.personalizationApp.mojom.WallpaperImage} * @private */ @@ -55,6 +74,14 @@ type: Object, }, + /** + * @type {?string} + * @private + */ + dailyRefreshCollectionId_: { + type: String, + }, + /** @private */ isLoading_: { type: Boolean, @@ -74,9 +101,35 @@ }, /** @private */ - showMoreOptions_: { + showWallpaperOptions_: { type: Boolean, - computed: 'computeShowMoreOptions_(image_)', + computed: 'computeShowWallpaperOptions_(image_)', + }, + + /** @private */ + showCollectionOptions_: { + type: Boolean, + computed: 'computeShowCollectionOptions_(path)', + }, + + /** @private */ + showRefreshButton_: { + type: Boolean, + computed: + 'isDailyRefreshCollectionId_(collectionId,dailyRefreshCollectionId_)', + }, + + /** @private */ + dailyRefreshIcon_: { + type: String, + computed: + 'computeDailyRefreshIcon_(collectionId,dailyRefreshCollectionId_)', + }, + + /** @private */ + ariaPressed_: { + type: String, + computed: 'computeAriaPressed_(collectionId,dailyRefreshCollectionId_)', }, }; } @@ -91,9 +144,14 @@ connectedCallback() { super.connectedCallback(); this.watch('image_', state => state.selected); - this.watch('isLoading_', state => state.loading.selected); + this.watch( + 'isLoading_', + state => state.loading.selected || state.loading.refreshWallpaper); + this.watch( + 'dailyRefreshCollectionId_', state => state.dailyRefresh.collectionId); this.updateFromStore(); getCurrentWallpaper(this.wallpaperProvider_, this.getStore()); + getDailyRefreshCollectionId(this.wallpaperProvider_, this.getStore()); } /** @@ -127,8 +185,17 @@ * @param {?chromeos.personalizationApp.mojom.CurrentWallpaper} image * @return {boolean} */ - computeShowMoreOptions_(image) { - return !!image && !!image.type && image.type === WallpaperType.kCustomized; + computeShowWallpaperOptions_(image) { + return !!image && image.type === WallpaperType.kCustomized; + } + + /** + * @private + * @param {string} path + * @return {boolean} + */ + computeShowCollectionOptions_(path) { + return path === Paths.CollectionImages; } /** @@ -168,6 +235,71 @@ /** * @private + * @param {!string} collectionId + * @param {!string} dailyRefreshCollectionId + * @return {string} + */ + computeDailyRefreshIcon_(collectionId, dailyRefreshCollectionId) { + if (this.isDailyRefreshCollectionId_( + collectionId, dailyRefreshCollectionId)) + return 'personalization:checkmark'; + return 'personalization:change-daily'; + } + + /** + * @private + * @param {!string} collectionId + * @param {!string} dailyRefreshCollectionId + * @return {string} + */ + computeAriaPressed_(collectionId, dailyRefreshCollectionId) { + if (this.isDailyRefreshCollectionId_( + collectionId, dailyRefreshCollectionId)) + return 'true'; + return 'false'; + } + + /** + * @private + * @param {!Event} event + */ + onClickDailyRefreshToggle_(event) { + const collectionId = event.currentTarget.dataset['collectionId']; + const dailyRefreshCollectionId = + event.currentTarget.dataset['dailyRefreshCollectionId']; + const isDailyRefreshCollectionId = this.isDailyRefreshCollectionId_( + collectionId, dailyRefreshCollectionId); + setDailyRefreshCollectionId( + isDailyRefreshCollectionId ? '' : collectionId, this.wallpaperProvider_, + this.getStore()); + // Only refresh the wallpaper if daily refresh is toggled on. + if (!isDailyRefreshCollectionId) { + updateDailyRefreshWallpaper(this.wallpaperProvider_, this.getStore()); + } + } + + /** + * Determine the current collection view belongs to the collection that is + * enabled with daily refresh. If true, highlight the toggle and display the + * refresh button + * @private + * @param {!string} collectionId + * @param {!string} dailyRefreshCollectionId + * @return {boolean} + */ + isDailyRefreshCollectionId_(collectionId, dailyRefreshCollectionId) { + return collectionId === dailyRefreshCollectionId; + } + + /** + * @private + */ + onClickUpdateDailyRefreshWallpaper_() { + updateDailyRefreshWallpaper(this.wallpaperProvider_, this.getStore()); + } + + /** + * @private * @param {?chromeos.personalizationApp.mojom.WallpaperImage} image * @param {boolean} loading * @return {boolean}
diff --git a/chromeos/components/personalization_app/test/fake_personalization_app_ui_delegate.cc b/chromeos/components/personalization_app/test/fake_personalization_app_ui_delegate.cc index f206d71..b989b70 100644 --- a/chromeos/components/personalization_app/test/fake_personalization_app_ui_delegate.cc +++ b/chromeos/components/personalization_app/test/fake_personalization_app_ui_delegate.cc
@@ -88,3 +88,18 @@ ash::WallpaperLayout layout) { return; } + +void FakePersonalizationAppUiDelegate::SetDailyRefreshCollectionId( + const std::string& collection_id) { + return; +} + +void FakePersonalizationAppUiDelegate::GetDailyRefreshCollectionId( + GetDailyRefreshCollectionIdCallback callback) { + std::move(callback).Run(kFakeCollectionId); +} + +void FakePersonalizationAppUiDelegate::UpdateDailyRefreshWallpaper( + UpdateDailyRefreshWallpaperCallback callback) { + std::move(callback).Run(/*success=*/true); +}
diff --git a/chromeos/components/personalization_app/test/fake_personalization_app_ui_delegate.h b/chromeos/components/personalization_app/test/fake_personalization_app_ui_delegate.h index a2ef92ff..c0ba99b 100644 --- a/chromeos/components/personalization_app/test/fake_personalization_app_ui_delegate.h +++ b/chromeos/components/personalization_app/test/fake_personalization_app_ui_delegate.h
@@ -55,6 +55,14 @@ void SetCustomWallpaperLayout(ash::WallpaperLayout layout) override; + void SetDailyRefreshCollectionId(const std::string& collection_id) override; + + void GetDailyRefreshCollectionId( + GetDailyRefreshCollectionIdCallback callback) override; + + void UpdateDailyRefreshWallpaper( + UpdateDailyRefreshWallpaperCallback callback) override; + private: mojo::Receiver<chromeos::personalization_app::mojom::WallpaperProvider> wallpaper_receiver_{this};
diff --git a/chromeos/crosapi/mojom/keystore_service.mojom b/chromeos/crosapi/mojom/keystore_service.mojom index 5479ebad..1b29c99 100644 --- a/chromeos/crosapi/mojom/keystore_service.mojom +++ b/chromeos/crosapi/mojom/keystore_service.mojom
@@ -147,8 +147,8 @@ }; // Returned by GetPublicKey(). -[Stable] -union GetPublicKeyResult { +[Stable, RenamedFrom="crosapi.mojom.GetPublicKeyResult"] +union DEPRECATED_GetPublicKeyResult { // Implies failure. string error_message; @@ -227,10 +227,10 @@ // WebCrypto algorithm |algorithm_name|. If so, returns the key info and // details about the signing algorithm. |certificate| must be a DER encoded // X.509 certificate. - [MinVersion=3] - GetPublicKey@6(array<uint8> certificate, + [MinVersion=3, RenamedFrom="crosapi.mojom.GetPublicKey"] + DEPRECATED_GetPublicKey@6(array<uint8> certificate, KeystoreSigningAlgorithmName algorithm_name) => - (GetPublicKeyResult result); + (DEPRECATED_GetPublicKeyResult result); // Generates a private/public key-pair with |algorithm| and stores the results // in |keystore|. Returns the public key as a binary blob. Also generates
diff --git a/chromeos/network/onc/onc_translation_tables.cc b/chromeos/network/onc/onc_translation_tables.cc index f416b0c..2b15aa1 100644 --- a/chromeos/network/onc/onc_translation_tables.cc +++ b/chromeos/network/onc/onc_translation_tables.cc
@@ -6,8 +6,6 @@ #include <cstddef> -#include "ash/constants/ash_features.h" -#include "base/feature_list.h" #include "base/logging.h" #include "chromeos/network/network_type_pattern.h" #include "chromeos/network/tether_constants.h" @@ -215,6 +213,7 @@ {::onc::cellular::kActivationType, shill::kActivationTypeProperty}, // This field is converted during translation, see onc_translator_*. // { ::onc::cellular::kActivationState, shill::kActivationStateProperty}, + {::onc::cellular::kAllowRoaming, shill::kCellularAllowRoamingProperty}, {::onc::cellular::kAutoConnect, shill::kAutoConnectProperty}, {::onc::cellular::kEID, shill::kEidProperty}, {::onc::cellular::kICCID, shill::kIccidProperty}, @@ -422,11 +421,7 @@ const FieldTranslationEntry kCellularDeviceTable[] = { // This field is converted during translation, see onc_translator_*. // { ::onc::cellular::kAPNList, shill::kCellularApnListProperty}, - {::onc::cellular::kAllowRoaming, - base::FeatureList::IsEnabled( - ash::features::kCellularAllowPerNetworkRoaming) - ? shill::kCellularPolicyAllowRoamingProperty - : shill::kCellularAllowRoamingProperty}, + {::onc::cellular::kAllowRoaming, shill::kCellularAllowRoamingProperty}, {::onc::cellular::kESN, shill::kEsnProperty}, {::onc::cellular::kFamily, shill::kTechnologyFamilyProperty}, {::onc::cellular::kFirmwareRevision, shill::kFirmwareRevisionProperty},
diff --git a/chromeos/network/onc/onc_translator_unittest.cc b/chromeos/network/onc/onc_translator_unittest.cc index f66c135..a7940fab 100644 --- a/chromeos/network/onc/onc_translator_unittest.cc +++ b/chromeos/network/onc/onc_translator_unittest.cc
@@ -75,6 +75,8 @@ std::make_pair("vpn_ipsec_clientcert_pkcs11.onc", "shill_vpn_ipsec_clientcert_pkcs11.json"), std::make_pair("cellular.onc", "shill_cellular.json"), + std::make_pair("cellular.per_network_roaming.onc", + "shill_cellular.per_network_roaming.json"), // WiMAX is deprecated, but we need to ensure older ONC configurations // are handled gracefully. std::make_pair("wimax.onc", "shill_wimax.json"), @@ -155,6 +157,9 @@ "translation_of_shill_wifi_proxy_pac.onc"), std::make_pair("shill_cellular_with_state.json", "translation_of_shill_cellular_with_state.onc"), + std::make_pair( + "shill_cellular_with_state.per_network_roaming.json", + "translation_of_shill_cellular_with_state.per_network_roaming.onc"), std::make_pair("shill_output_third_party_vpn.json", "translation_of_shill_output_third_party_vpn.onc"), std::make_pair(
diff --git a/chromeos/test/data/network/cellular.per_network_roaming.onc b/chromeos/test/data/network/cellular.per_network_roaming.onc new file mode 100644 index 0000000..7540410 --- /dev/null +++ b/chromeos/test/data/network/cellular.per_network_roaming.onc
@@ -0,0 +1,14 @@ +{ + "Type": "Cellular", + "Name": "Test Network", + "Cellular": { + "AllowRoaming": true, + "APN": { + "AccessPointName": "test-apn", + "Authentication": "chap", + "Username": "test-username", + "Password": "test-password" + }, + "AutoConnect": true + } +}
diff --git a/chromeos/test/data/network/shill_cellular.per_network_roaming.json b/chromeos/test/data/network/shill_cellular.per_network_roaming.json new file mode 100644 index 0000000..765d950 --- /dev/null +++ b/chromeos/test/data/network/shill_cellular.per_network_roaming.json
@@ -0,0 +1,11 @@ +{ + "AutoConnect": true, + "Type": "cellular", + "Cellular.AllowRoaming": true, + "Cellular.APN": { + "apn": "test-apn", + "authentication": "chap", + "username": "test-username", + "password": "test-password" + } +}
diff --git a/chromeos/test/data/network/shill_cellular_with_state.per_network_roaming.json b/chromeos/test/data/network/shill_cellular_with_state.per_network_roaming.json new file mode 100644 index 0000000..5942c479 --- /dev/null +++ b/chromeos/test/data/network/shill_cellular_with_state.per_network_roaming.json
@@ -0,0 +1,67 @@ +{ + "AutoConnect": true, + "Type": "cellular", + "Name": "Test Network", + "Cellular.ActivationState": "activated", + "Cellular.ActivationType": "OTASP", + "Cellular.AllowRoaming": true, + "Cellular.EID": "test_eid", + "Cellular.ICCID": "test_iccid", + "Cellular.NetworkTechnology": "LTE Advanced", + "Cellular.Olp": { + "method": "GET", + "url": "http://test.com/payment" + }, + "Cellular.RoamingState": "home", + "Cellular.ServingOperator": { + "code": "test-code", + "country": "test-country", + "name" : "test-name" + }, + "Cellular.APN": { + "apn": "test-apn", + "authentication": "chap", + "name": "test-apn-name", + "username": "test-username", + "password": "test-password" + }, + "Device": { + // This dictionary contains Device properties and not Service properties as + // above. + "Cellular.APNList": [ + { + "apn": "test-apn0", + "username": "test-username0", + "password": "test-password0" + }, + { + "apn": "test-apn1", + "username": "test-username1", + "password": "test-password1" + }, + { + "apn": "test-apn2", + "username": "test-username2", + "password": "test-password2" + }, + { + "apn": "test-apn3", + "username": "test-username3", + "password": "test-password3", + "attach": "attach" + } + ], + "Cellular.ICCID": "test_iccid", + "Cellular.HomeProvider": { + "country": "us", + "name": "cellular_provider" + }, + "Cellular.PolicyAllowRoaming": true, + "Cellular.SIMLockStatus": { + "LockType": "sim-pin", + "LockEnabled": true + }, + "Scanning": true + }, + "Profile": "/profile/default" +}
diff --git a/chromeos/test/data/network/translation_of_shill_cellular_with_state.per_network_roaming.onc b/chromeos/test/data/network/translation_of_shill_cellular_with_state.per_network_roaming.onc new file mode 100644 index 0000000..a248985 --- /dev/null +++ b/chromeos/test/data/network/translation_of_shill_cellular_with_state.per_network_roaming.onc
@@ -0,0 +1,61 @@ +{ + "Type": "Cellular", + "Name": "Test Network", + "Cellular": { + "ActivationState": "Activated", + "ActivationType": "OTASP", + "AllowRoaming": true, + "AutoConnect": true, + "EID": "test_eid", + "ICCID": "test_iccid", + "HomeProvider": { + "Country": "us", + "Name": "cellular_provider" + }, + "NetworkTechnology": "LTEAdvanced", + "PaymentPortal": { + "Method": "GET", + "Url": "http://test.com/payment" + }, + "RoamingState": "Home", + "ServingOperator": { + "Code": "test-code", + "Country": "test-country", + "Name": "test-name" + }, + "APN": { + "AccessPointName": "test-apn", + "Authentication": "chap", + "Name": "test-apn-name", + "Username": "test-username", + "Password": "test-password" + }, + "APNList": [ { + "AccessPointName": "test-apn0", + "Password": "test-password0", + "Username": "test-username0" + }, { + "AccessPointName": "test-apn1", + "Password": "test-password1", + "Username": "test-username1" + }, { + "AccessPointName": "test-apn2", + "Password": "test-password2", + "Username": "test-username2" + }, { + "AccessPointName": "test-apn3", + "Password": "test-password3", + "Username": "test-username3", + "Attach": "attach" + } + ], + "SIMLockStatus": { + "LockType": "sim-pin", + "LockEnabled": true + }, + "Scanning": true + }, + "IPAddressConfigType":"DHCP", + "NameServersConfigType":"DHCP", + "Source":"Device" +}
diff --git a/components/arc/enterprise/arc_data_snapshotd_manager.cc b/components/arc/enterprise/arc_data_snapshotd_manager.cc index beec538e6..d5f1d68 100644 --- a/components/arc/enterprise/arc_data_snapshotd_manager.cc +++ b/components/arc/enterprise/arc_data_snapshotd_manager.cc
@@ -292,6 +292,11 @@ local_state_->Set(arc::prefs::kArcSnapshotInfo, std::move(dict)); } +void ArcDataSnapshotdManager::Snapshot::Sync(base::OnceClosure callback) { + Sync(); + local_state_->CommitPendingWrite(std::move(callback), base::DoNothing()); +} + void ArcDataSnapshotdManager::Snapshot::ClearSnapshot(bool last) { std::unique_ptr<SnapshotInfo>* snapshot = (last ? &last_snapshot_ : &previous_snapshot_); @@ -814,10 +819,10 @@ LOG(ERROR) << "Key pair generation failed. Abort snapshot creation."; snapshot_.set_blocked_ui_mode(false); - snapshot_.Sync(); - DCHECK(!attempt_user_exit_callback_.is_null()); - EnsureDaemonStopped(std::move(attempt_user_exit_callback_)); + snapshot_.Sync(base::BindOnce(&ArcDataSnapshotdManager::EnsureDaemonStopped, + weak_ptr_factory_.GetWeakPtr(), + std::move(attempt_user_exit_callback_))); } } @@ -898,10 +903,11 @@ LOG(ERROR) << "Failed to take ARC data directory snapshot."; snapshot_.set_blocked_ui_mode(false); - snapshot_.Sync(); - DCHECK(!attempt_user_exit_callback_.is_null()); - EnsureDaemonStopped(std::move(attempt_user_exit_callback_)); + + snapshot_.Sync(base::BindOnce(&ArcDataSnapshotdManager::EnsureDaemonStopped, + weak_ptr_factory_.GetWeakPtr(), + std::move(attempt_user_exit_callback_))); } void ArcDataSnapshotdManager::OnSnapshotLoaded(base::OnceClosure callback, @@ -969,7 +975,9 @@ LOG(ERROR) << "Received a signal from UI when not in blocked UI mode."; break; } - StopDaemon(std::move(attempt_user_exit_callback_)); + snapshot_.Sync(base::BindOnce(&ArcDataSnapshotdManager::StopDaemon, + weak_ptr_factory_.GetWeakPtr(), + std::move(attempt_user_exit_callback_))); } std::vector<std::string> ArcDataSnapshotdManager::GetStartEnvVars() {
diff --git a/components/arc/enterprise/arc_data_snapshotd_manager.h b/components/arc/enterprise/arc_data_snapshotd_manager.h index c41a3bce..b656ca17 100644 --- a/components/arc/enterprise/arc_data_snapshotd_manager.h +++ b/components/arc/enterprise/arc_data_snapshotd_manager.h
@@ -193,6 +193,12 @@ void Parse(); // Syncs stored snapshot info to local state. void Sync(); + + // Syncs stored snapshot info to local state. + // |callback| is executed once all changes to the local state have been + // committed. + void Sync(base::OnceClosure callback); + // Clears snapshot related info in arc.snapshot preference either last // if |last| is true or previous otherwise. void ClearSnapshot(bool last);
diff --git a/components/arc/enterprise/arc_data_snapshotd_manager_unittest.cc b/components/arc/enterprise/arc_data_snapshotd_manager_unittest.cc index 9498d73..c366ad98 100644 --- a/components/arc/enterprise/arc_data_snapshotd_manager_unittest.cc +++ b/components/arc/enterprise/arc_data_snapshotd_manager_unittest.cc
@@ -1114,6 +1114,7 @@ // Send a cancellation signal. client()->signal_callback().Run(); + RunUntilIdle(); EXPECT_TRUE(is_attempt_user_exit_called); } else { EXPECT_TRUE(is_attempt_user_exit_called);
diff --git a/components/arc/session/arc_vm_client_adapter.cc b/components/arc/session/arc_vm_client_adapter.cc index 03319cf..5053c69 100644 --- a/components/arc/session/arc_vm_client_adapter.cc +++ b/components/arc/session/arc_vm_client_adapter.cc
@@ -323,7 +323,9 @@ uint32_t cpus, const base::FilePath& demo_session_apps_path, const FileSystemStatus& file_system_status, - std::vector<std::string> kernel_cmdline) { + std::vector<std::string> kernel_cmdline, + base::OnceCallback<bool(base::SystemMemoryInfoKB*)> + get_system_memory_info_cb) { vm_tools::concierge::StartArcVmRequest request; request.set_name(kArcVmName); @@ -384,7 +386,7 @@ // Specify VM Memory. if (base::FeatureList::IsEnabled(kVmMemorySize)) { base::SystemMemoryInfoKB info; - if (base::GetSystemMemoryInfo(&info)) { + if (std::move(get_system_memory_info_cb).Run(&info)) { const int ram_mib = info.total / 1024; const int shift_mib = kVmMemorySizeShiftMiB.Get(); const int max_mib = kVmMemorySizeMaxMiB.Get(); @@ -492,6 +494,12 @@ } // namespace +bool ArcVmClientAdapterDelegate::GetSystemMemoryInfo( + base::SystemMemoryInfoKB* info) { + // Call the base function by default. + return base::GetSystemMemoryInfo(info); +} + class ArcVmClientAdapter : public ArcClientAdapter, public chromeos::ConciergeClient::VmObserver, public chromeos::ConciergeClient::Observer { @@ -503,7 +511,8 @@ // For testing purposes and the internal use (by the other ctor) only. explicit ArcVmClientAdapter(const FileSystemStatusRewriter& rewriter) - : is_host_on_vm_(chromeos::system::StatisticsProvider::GetInstance() + : delegate_(std::make_unique<ArcVmClientAdapterDelegate>()), + is_host_on_vm_(chromeos::system::StatisticsProvider::GetInstance() ->IsRunningOnVm()), file_system_status_rewriter_for_testing_(rewriter) { auto* client = GetConciergeClient(); @@ -652,6 +661,11 @@ void ConciergeServiceStarted() override {} + void set_delegate_for_testing( // IN-TEST + std::unique_ptr<ArcVmClientAdapterDelegate> delegate) { + delegate_ = std::move(delegate); + } + private: void OnArcBugReportBackedUp(base::TimeTicks arc_bug_report_backup_time, bool result) { @@ -818,9 +832,13 @@ std::vector<std::string> kernel_cmdline = GenerateKernelCmdline( start_params_, file_system_status, *is_dev_mode_, is_host_on_vm_, GetChromeOsChannelFromLsbRelease()); - auto start_request = - CreateStartArcVmRequest(cpus, demo_session_apps_path, - file_system_status, std::move(kernel_cmdline)); + auto start_request = CreateStartArcVmRequest( + cpus, demo_session_apps_path, file_system_status, + std::move(kernel_cmdline), + base::BindOnce(&ArcVmClientAdapterDelegate::GetSystemMemoryInfo, + // Unretained is safe because CreateStartArcVmRequest is + // a synchronous function. + base::Unretained(delegate_.get()))); GetConciergeClient()->StartArcVm( start_request, @@ -1047,6 +1065,8 @@ std::move(callback).Run(success, failure_reason); } + std::unique_ptr<ArcVmClientAdapterDelegate> delegate_; + absl::optional<bool> is_dev_mode_; // True when the *host* is running on a VM. const bool is_host_on_vm_; @@ -1110,4 +1130,12 @@ return GenerateUpgradeProps(upgrade_params, serial_number, prefix); } +void SetArcVmClientAdapterDelegateForTesting( // IN-TEST + ArcClientAdapter* adapter, + std::unique_ptr<ArcVmClientAdapterDelegate> delegate) { + static_cast<ArcVmClientAdapter*>(adapter) + ->set_delegate_for_testing( // IN-TEST + std::move(delegate)); +} + } // namespace arc
diff --git a/components/arc/session/arc_vm_client_adapter.h b/components/arc/session/arc_vm_client_adapter.h index 028ce5c..f5215aa 100644 --- a/components/arc/session/arc_vm_client_adapter.h +++ b/components/arc/session/arc_vm_client_adapter.h
@@ -14,6 +14,7 @@ #include "third_party/abseil-cpp/absl/types/optional.h" namespace base { +struct SystemMemoryInfoKB; class TimeDelta; } @@ -29,6 +30,17 @@ NDK_TRANSLATION, }; +// For better unit-testing. +class ArcVmClientAdapterDelegate { + public: + ArcVmClientAdapterDelegate() = default; + ArcVmClientAdapterDelegate(const ArcVmClientAdapterDelegate&) = delete; + ArcVmClientAdapterDelegate& operator=(const ArcVmClientAdapterDelegate&) = + delete; + virtual ~ArcVmClientAdapterDelegate() = default; + virtual bool GetSystemMemoryInfo(base::SystemMemoryInfoKB* info); +}; + // Returns an adapter for arcvm. std::unique_ptr<ArcClientAdapter> CreateArcVmClientAdapter(); @@ -53,6 +65,10 @@ const std::string& serial_number, const std::string& prefix); +void SetArcVmClientAdapterDelegateForTesting( + ArcClientAdapter* adapter, + std::unique_ptr<ArcVmClientAdapterDelegate> delegate); + } // namespace arc #endif // COMPONENTS_ARC_SESSION_ARC_VM_CLIENT_ADAPTER_H_
diff --git a/components/arc/session/arc_vm_client_adapter_unittest.cc b/components/arc/session/arc_vm_client_adapter_unittest.cc index 9b43b76..60258615 100644 --- a/components/arc/session/arc_vm_client_adapter_unittest.cc +++ b/components/arc/session/arc_vm_client_adapter_unittest.cc
@@ -1922,6 +1922,29 @@ EXPECT_EQ(request.memory_mib(), 2049u); } +// Test that StartArcVmRequest has no memory_mib field when getting system +// memory info fails. +TEST_F(ArcVmClientAdapterTest, ArcVmMemorySizeEnabledNoSystemMemoryInfo) { + // Inject the failure. + class TestDelegate : public ArcVmClientAdapterDelegate { + bool GetSystemMemoryInfo(base::SystemMemoryInfoKB* info) override { + return false; + } + }; + SetArcVmClientAdapterDelegateForTesting(adapter(), + std::make_unique<TestDelegate>()); + + base::test::ScopedFeatureList feature_list; + base::FieldTrialParams params; + params["shift_mib"] = "0"; + feature_list.InitAndEnableFeatureWithParameters(kVmMemorySize, params); + StartParams start_params(GetPopulatedStartParams()); + SetValidUserInfo(); + StartMiniArcWithParams(true, std::move(start_params)); + auto request = GetTestConciergeClient()->start_arc_vm_request(); + EXPECT_EQ(request.memory_mib(), 0u); +} + struct DalvikMemoryProfileTestParam { // Requested profile. StartParams::DalvikMemoryProfile profile;
diff --git a/components/autofill/core/browser/autofill_download_manager.cc b/components/autofill/core/browser/autofill_download_manager.cc index 20f84b29..b3fef0e9 100644 --- a/components/autofill/core/browser/autofill_download_manager.cc +++ b/components/autofill/core/browser/autofill_download_manager.cc
@@ -381,6 +381,10 @@ out << "\n type: " << field.type(); if (field.generation_type()) out << "\n generation_type: " << field.generation_type(); + if (field.single_username_vote_type()) { + out << "\n single_username_vote_type: " + << field.single_username_vote_type(); + } } return out; }
diff --git a/components/autofill/core/browser/autofill_field.h b/components/autofill/core/browser/autofill_field.h index 815de3b..a45996a 100644 --- a/components/autofill/core/browser/autofill_field.h +++ b/components/autofill/core/browser/autofill_field.h
@@ -196,6 +196,15 @@ return state_is_a_matching_type_; } + void set_single_username_vote_type( + AutofillUploadContents::Field::SingleUsernameVoteType vote_type) { + single_username_vote_type_ = vote_type; + } + absl::optional<AutofillUploadContents::Field::SingleUsernameVoteType> + single_username_vote_type() const { + return single_username_vote_type_; + } + // For each type in |possible_types_| that's missing from // |possible_types_validities_|, will add it to the // |possible_types_validities_| and will set its validity to UNVALIDATED. This @@ -292,6 +301,10 @@ // Denotes if |ADDRESS_HOME_STATE| should be added to |possible_types_|. bool state_is_a_matching_type_ = false; + // Strength of the single username vote signal, if applicable. + absl::optional<AutofillUploadContents::Field::SingleUsernameVoteType> + single_username_vote_type_; + DISALLOW_COPY_AND_ASSIGN(AutofillField); };
diff --git a/components/autofill/core/browser/form_structure.cc b/components/autofill/core/browser/form_structure.cc index e2fc31f9..614b542 100644 --- a/components/autofill/core/browser/form_structure.cc +++ b/components/autofill/core/browser/form_structure.cc
@@ -2140,6 +2140,11 @@ added_field->mutable_randomized_field_metadata()); } + if (field->single_username_vote_type()) { + added_field->set_single_username_vote_type( + field->single_username_vote_type().value()); + } + if (is_raw_metadata_uploading_enabled) { added_field->set_type(field->form_control_type);
diff --git a/components/autofill/core/browser/form_structure_unittest.cc b/components/autofill/core/browser/form_structure_unittest.cc index d864a080..105708c3 100644 --- a/components/autofill/core/browser/form_structure_unittest.cc +++ b/components/autofill/core/browser/form_structure_unittest.cc
@@ -5145,6 +5145,29 @@ EXPECT_EQ(expected_query_string, encoded_query_string); } +TEST_F(FormStructureTestImpl, EncodeUploadRequest_WithSingleUsernameVoteType) { + FormData form; + form.url = GURL("http://www.foo.com/"); + FormFieldData field; + field.name = u"text field"; + field.unique_renderer_id = MakeFieldRendererId(); + form.fields.push_back(field); + + FormStructure form_structure(form); + form_structure.set_passwords_were_revealed(true); + form_structure.field(0)->set_single_username_vote_type( + AutofillUploadContents::Field::EDITED_IN_PROMPT); + + AutofillUploadContents upload; + std::vector<FormSignature> signatures; + EXPECT_TRUE(form_structure.EncodeUploadRequest( + {{}} /* available_field_types */, false /* form_was_autofilled */, + std::string() /* login_form_signature */, true /* observed_submission */, + false /* is_raw_metadata_uploading_enabled */, &upload, &signatures)); + EXPECT_EQ(form_structure.field(0)->single_username_vote_type(), + upload.field(0).single_username_vote_type()); +} + // Test that server predictions get precedence over htmll types if they are // overrides. TEST_F(FormStructureTestImpl, ParseQueryResponse_ServerPredictionIsOverride) {
diff --git a/components/autofill/core/browser/proto/server.proto b/components/autofill/core/browser/proto/server.proto index b845183..7712525 100644 --- a/components/autofill/core/browser/proto/server.proto +++ b/components/autofill/core/browser/proto/server.proto
@@ -222,7 +222,7 @@ // This message contains information about the field types in a single form. // It is sent by the toolbar to contribute to the field type statistics. -// Next available id: 41 +// Next available id: 42 message AutofillUploadContents { required string client_version = 1; required fixed64 form_signature = 2; @@ -347,6 +347,21 @@ // or automatic fillings. This field is used to detect static // placeholders. optional uint32 initial_value_hash = 40; + + // The type of the username first flow signal. + enum SingleUsernameVoteType { + DEFAULT = 0; + // Recorded if Save/Update prompt was accepted without username edits. + NOT_EDITED_IN_PROMPT = 1; + // Recorded if Save/Update prompt was accepted after username edits. + EDITED_IN_PROMPT = 2; + // Recorded when a single username candidate value had whitespaces. + HAD_WHITESPACES = 3; + } + + // The type of the username first flow vote signal, set iff |autofill_type| + // is SINGLE_USERNAME or NOT_USERNAME. + optional SingleUsernameVoteType single_username_vote_type = 41; } // Signature of the form action host (e.g. Hash64Bit("example.com")). optional fixed64 action_signature = 13;
diff --git a/components/autofill_payments_strings.grdp b/components/autofill_payments_strings.grdp index d70291c4..27c52e1c 100644 --- a/components/autofill_payments_strings.grdp +++ b/components/autofill_payments_strings.grdp
@@ -525,10 +525,10 @@ </message> <if expr="is_android"> <message name="IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_MESSAGE_TEXT" desc="Text to be displayed in the snackbar shown after a virtual card number id autofilled."> - Your virtual card number is applied. + Virtual card number not filled in? </message> <message name="IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_ACTION_TEXT" desc="Text to be displayed as the snackbar action shown after a virtual card number id autofilled."> - View virtual card + View card </message> </if>
diff --git a/components/autofill_payments_strings_grdp/IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_ACTION_TEXT.png.sha1 b/components/autofill_payments_strings_grdp/IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_ACTION_TEXT.png.sha1 index 99202b1..0e2212465 100644 --- a/components/autofill_payments_strings_grdp/IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_ACTION_TEXT.png.sha1 +++ b/components/autofill_payments_strings_grdp/IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_ACTION_TEXT.png.sha1
@@ -1 +1 @@ -d2f6c9ac4746fcf9e4c6d723c809c421fa048536 \ No newline at end of file +f50ae6a34d01cf3a6e5560f8b702aaf0149f55ba \ No newline at end of file
diff --git a/components/autofill_payments_strings_grdp/IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_MESSAGE_TEXT.png.sha1 b/components/autofill_payments_strings_grdp/IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_MESSAGE_TEXT.png.sha1 index 99202b1..0e2212465 100644 --- a/components/autofill_payments_strings_grdp/IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_MESSAGE_TEXT.png.sha1 +++ b/components/autofill_payments_strings_grdp/IDS_AUTOFILL_VIRTUAL_CARD_NUMBER_SNACKBAR_MESSAGE_TEXT.png.sha1
@@ -1 +1 @@ -d2f6c9ac4746fcf9e4c6d723c809c421fa048536 \ No newline at end of file +f50ae6a34d01cf3a6e5560f8b702aaf0149f55ba \ No newline at end of file
diff --git a/components/browser_ui/site_settings/android/BUILD.gn b/components/browser_ui/site_settings/android/BUILD.gn index 69571247..26464cf 100644 --- a/components/browser_ui/site_settings/android/BUILD.gn +++ b/components/browser_ui/site_settings/android/BUILD.gn
@@ -79,7 +79,6 @@ deps = [ ":java_resources", "//base:base_java", - "//build/android:build_config_java", "//components/browser_ui/settings/android:java", "//components/browser_ui/widget/android:java", "//components/content_settings/android:content_settings_enums_java",
diff --git a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/ChosenObjectSettings.java b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/ChosenObjectSettings.java index 8e1aa82c2..f4c6d5a 100644 --- a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/ChosenObjectSettings.java +++ b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/ChosenObjectSettings.java
@@ -20,7 +20,7 @@ import androidx.preference.PreferenceScreen; import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; -import org.chromium.build.BuildConfig; +import org.chromium.base.annotations.RemovableInRelease; import org.chromium.components.browser_ui.settings.ChromeImageViewPreference; import org.chromium.components.browser_ui.settings.ManagedPreferencesUtils; @@ -82,12 +82,11 @@ * returns the same value. This must be true because this activity is displaying permissions * for a single object. Each instance varies only in which site it represents. */ + @RemovableInRelease private void checkObjectConsistency() { - if (BuildConfig.ENABLE_ASSERTS) { - String exampleObject = mObjectInfos.get(0).getObject(); - for (ChosenObjectInfo info : mObjectInfos) { - assert info.getObject().equals(exampleObject); - } + String exampleObject = mObjectInfos.get(0).getObject(); + for (ChosenObjectInfo info : mObjectInfos) { + assert info.getObject().equals(exampleObject); } }
diff --git a/components/browser_ui/strings/android/browser_ui_strings.grd b/components/browser_ui/strings/android/browser_ui_strings.grd index 67cb598..bd38a7c 100644 --- a/components/browser_ui/strings/android/browser_ui_strings.grd +++ b/components/browser_ui/strings/android/browser_ui_strings.grd
@@ -771,29 +771,6 @@ Drag from top and touch the back button to exit full screen. </message> - <!-- WebApk name/icon update dialog --> - <message name="IDS_WEBAPK_UPDATE_DIALOG_TITLE_NAME" desc="The title at the top of the dialog when only the name changed."> - Review name updates - </message> - <message name="IDS_WEBAPK_UPDATE_DIALOG_TITLE_ICON" desc="The title at the top of the dialog when only the icon changed."> - Review icon updates - </message> - <message name="IDS_WEBAPK_UPDATE_DIALOG_TITLE_NAME_AND_ICON" desc="The title at the top of the dialog when the name and icon changed."> - Review name & icon updates - </message> - <message name="IDS_WEBAPK_UPDATE_EXPLANATION" desc="The text at the top of the dialog, explaining what to do when an app changes its identity."> - If this web app is trying to trick you into thinking it is a different app, uninstall it. - </message> - <message name="IDS_WEBAPK_UPDATE_NEGATIVE_BUTTON" desc="The text for the negative button (aka. cancel button), allowing the user to uninstall the app and report it to the abuse team."> - Uninstall app - </message> - <message name="IDS_UPDATE_WEBAPK_CURRENT_ICON" desc="The accessibility string explaining which icon is the current icon."> - Current icon - </message> - <message name="IDS_UPDATE_WEBAPK_UPDATED_ICON" desc="The accessibility string explaining which icon is the new icon."> - New icon - </message> - <!-- WebApk name/icon report abuse dialog --> <message name="IDS_WEBAPK_REPORT_ABUSE_DIALOG_TITLE" desc="The title at the top of the report abuse dialog."> Uninstall '<ph name="APP_NAME">%1$s<ex>Google App</ex></ph>'?
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_UPDATE_WEBAPK_CURRENT_ICON.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_UPDATE_WEBAPK_CURRENT_ICON.png.sha1 deleted file mode 100644 index d4b47ab..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_UPDATE_WEBAPK_CURRENT_ICON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -12f34b17c0d5c220817069937b6a9f30d69fb53d \ No newline at end of file
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_UPDATE_WEBAPK_UPDATED_ICON.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_UPDATE_WEBAPK_UPDATED_ICON.png.sha1 deleted file mode 100644 index d4b47ab..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_UPDATE_WEBAPK_UPDATED_ICON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -12f34b17c0d5c220817069937b6a9f30d69fb53d \ No newline at end of file
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_ICON.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_ICON.png.sha1 deleted file mode 100644 index 2dc1c99e..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_ICON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -2e06252bc0469b0c71aaa080a655a6d7978aa074 \ No newline at end of file
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_NAME.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_NAME.png.sha1 deleted file mode 100644 index fe05204d..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_NAME.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -0adc4d18dd265079b5e82ad217e2e9776d9aad85 \ No newline at end of file
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_NAME_AND_ICON.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_NAME_AND_ICON.png.sha1 deleted file mode 100644 index d4b47ab..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_DIALOG_TITLE_NAME_AND_ICON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -12f34b17c0d5c220817069937b6a9f30d69fb53d \ No newline at end of file
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_EXPLANATION.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_EXPLANATION.png.sha1 deleted file mode 100644 index d4b47ab..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_EXPLANATION.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -12f34b17c0d5c220817069937b6a9f30d69fb53d \ No newline at end of file
diff --git a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_NEGATIVE_BUTTON.png.sha1 b/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_NEGATIVE_BUTTON.png.sha1 deleted file mode 100644 index d4b47ab..0000000 --- a/components/browser_ui/strings/android/browser_ui_strings_grd/IDS_WEBAPK_UPDATE_NEGATIVE_BUTTON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -12f34b17c0d5c220817069937b6a9f30d69fb53d \ No newline at end of file
diff --git a/components/browsing_data/core/counters/browsing_data_counter.cc b/components/browsing_data/core/counters/browsing_data_counter.cc index 01adad2..98b1f87d 100644 --- a/components/browsing_data/core/counters/browsing_data_counter.cc +++ b/components/browsing_data/core/counters/browsing_data_counter.cc
@@ -70,8 +70,9 @@ void BrowsingDataCounter::Restart() { DCHECK(initialized_); - TRACE_EVENT_ASYNC_BEGIN1("browsing_data", "BrowsingDataCounter::Restart", - this, "data_type", GetPrefName()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "browsing_data", "BrowsingDataCounter::Restart", TRACE_ID_LOCAL(this), + "data_type", GetPrefName()); if (state_ == State::IDLE) { DCHECK(!timer_.IsRunning()); DCHECK(!staged_result_); @@ -103,8 +104,9 @@ void BrowsingDataCounter::ReportResult(std::unique_ptr<Result> result) { DCHECK(initialized_); DCHECK(result->Finished()); - TRACE_EVENT_ASYNC_END1("browsing_data", "BrowsingDataCounter::Restart", this, - "data_type", GetPrefName()); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "browsing_data", "BrowsingDataCounter::Restart", TRACE_ID_LOCAL(this), + "data_type", GetPrefName()); switch (state_) { case State::RESTARTED: case State::READY_TO_REPORT_RESULT:
diff --git a/components/client_hints/browser/BUILD.gn b/components/client_hints/browser/BUILD.gn index 7b03e6a4..857d45e 100644 --- a/components/client_hints/browser/BUILD.gn +++ b/components/client_hints/browser/BUILD.gn
@@ -12,9 +12,6 @@ "//components/client_hints/common", "//components/content_settings/core/browser", "//components/content_settings/core/common", - "//components/keyed_service/core", - "//components/policy/core/common", - "//components/prefs", "//content/public/browser", "//services/network/public/cpp", "//third_party/blink/public/common:headers",
diff --git a/components/client_hints/browser/DEPS b/components/client_hints/browser/DEPS index 4d88d49c..df9f6ca 100644 --- a/components/client_hints/browser/DEPS +++ b/components/client_hints/browser/DEPS
@@ -1,8 +1,6 @@ include_rules = [ "+components/content_settings/core/browser", "+components/keyed_service", - "+components/prefs", - "+components/policy/core/common", "+content/public/browser", "+third_party/blink/public/common/user_agent", "+services/network/public/cpp/is_potentially_trustworthy.h",
diff --git a/components/client_hints/browser/client_hints.cc b/components/client_hints/browser/client_hints.cc index 6542685..a7335d6 100644 --- a/components/client_hints/browser/client_hints.cc +++ b/components/client_hints/browser/client_hints.cc
@@ -13,11 +13,8 @@ #include "components/client_hints/common/client_hints.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings_utils.h" -#include "components/policy/core/common/policy_pref_names.h" -#include "components/prefs/pref_service.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" -#include "content/public/common/content_features.h" #include "services/network/public/cpp/is_potentially_trustworthy.h" namespace client_hints { @@ -26,13 +23,11 @@ content::BrowserContext* context, network::NetworkQualityTracker* network_quality_tracker, HostContentSettingsMap* settings_map, - const blink::UserAgentMetadata& user_agent_metadata, - PrefService* pref_service) + const blink::UserAgentMetadata& user_agent_metadata) : context_(context), network_quality_tracker_(network_quality_tracker), settings_map_(settings_map), - user_agent_metadata_(user_agent_metadata), - pref_service_(pref_service) { + user_agent_metadata_(user_agent_metadata) { DCHECK(context_); DCHECK(network_quality_tracker_); DCHECK(settings_map_); @@ -62,19 +57,6 @@ CONTENT_SETTING_BLOCK; } -bool ClientHints::UserAgentClientHintEnabled() { - // TODO(crbug.com/1097591): This extra path check is only here because the - // pref is not being registered in //weblayer. - bool pref_enabled = true; - if (pref_service_->HasPrefPath( - policy::policy_prefs::kUserAgentClientHintsEnabled)) { - pref_enabled = pref_service_->GetBoolean( - policy::policy_prefs::kUserAgentClientHintsEnabled); - } - return pref_enabled && - base::FeatureList::IsEnabled(features::kUserAgentClientHint); -} - blink::UserAgentMetadata ClientHints::GetUserAgentMetadata() { return user_agent_metadata_; }
diff --git a/components/client_hints/browser/client_hints.h b/components/client_hints/browser/client_hints.h index 57d192d..34d2fd0c 100644 --- a/components/client_hints/browser/client_hints.h +++ b/components/client_hints/browser/client_hints.h
@@ -9,7 +9,6 @@ #include "base/memory/ref_counted.h" #include "components/keyed_service/core/keyed_service.h" -#include "components/prefs/pref_service.h" #include "content/public/browser/client_hints_controller_delegate.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" @@ -25,8 +24,7 @@ ClientHints(content::BrowserContext* context, network::NetworkQualityTracker* network_quality_tracker, HostContentSettingsMap* settings_map, - const blink::UserAgentMetadata& user_agent_metadata, - PrefService* pref_service); + const blink::UserAgentMetadata& user_agent_metadata); ~ClientHints() override; // content::ClientHintsControllerDelegate: @@ -38,8 +36,6 @@ bool IsJavaScriptAllowed(const GURL& url) override; - bool UserAgentClientHintEnabled() override; - blink::UserAgentMetadata GetUserAgentMetadata() override; void PersistClientHints( @@ -57,7 +53,6 @@ network::NetworkQualityTracker* network_quality_tracker_ = nullptr; HostContentSettingsMap* settings_map_ = nullptr; blink::UserAgentMetadata user_agent_metadata_; - PrefService* pref_service_; std::vector<network::mojom::WebClientHintsType> additional_hints_; DISALLOW_COPY_AND_ASSIGN(ClientHints);
diff --git a/components/download/internal/background_service/controller_impl.cc b/components/download/internal/background_service/controller_impl.cc index 9216d754..eaee2cb 100644 --- a/components/download/internal/background_service/controller_impl.cc +++ b/components/download/internal/background_service/controller_impl.cc
@@ -147,8 +147,8 @@ base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( this, "DownloadService", base::ThreadTaskRunnerHandle::Get()); - TRACE_EVENT_ASYNC_BEGIN0("download_service", "DownloadServiceInitialize", - this); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( + "download_service", "DownloadServiceInitialize", TRACE_ID_LOCAL(this)); driver_->Initialize(this); model_->Initialize(this); @@ -1092,7 +1092,8 @@ } void ControllerImpl::NotifyServiceOfStartup() { - TRACE_EVENT_ASYNC_END0("download_service", "DownloadServiceInitialize", this); + TRACE_EVENT_NESTABLE_ASYNC_END0( + "download_service", "DownloadServiceInitialize", TRACE_ID_LOCAL(this)); if (init_callback_.is_null()) return;
diff --git a/components/download/internal/common/download_item_impl.cc b/components/download/internal/common/download_item_impl.cc index dd1dfe27..ec04dc1 100644 --- a/components/download/internal/common/download_item_impl.cc +++ b/components/download/internal/common/download_item_impl.cc
@@ -1517,8 +1517,10 @@ file_name, GetDangerType(), GetReceivedBytes(), HasUserGesture()); if (active) { - TRACE_EVENT_ASYNC_BEGIN1("download", "DownloadItemActive", download_id_, - "download_item", std::move(active_data)); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "download", "DownloadItemActive", + TRACE_ID_WITH_SCOPE("DownloadItemActive", download_id_), + "download_item", std::move(active_data)); ukm_download_id_ = GetUniqueDownloadId(); } else { TRACE_EVENT_INSTANT1("download", "DownloadItemActive", @@ -2477,13 +2479,17 @@ // Termination if (is_done && !was_done) - TRACE_EVENT_ASYNC_END0("download", "DownloadItemActive", download_id_); + TRACE_EVENT_NESTABLE_ASYNC_END0( + "download", "DownloadItemActive", + TRACE_ID_WITH_SCOPE("DownloadItemActive", download_id_)); // Resumption if (was_done && !is_done) { std::string file_name(GetTargetFilePath().BaseName().AsUTF8Unsafe()); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( - "download", "DownloadItemActive", download_id_, "download_item", + "download", "DownloadItemActive", + TRACE_ID_WITH_SCOPE("DownloadItemActive", download_id_), + "download_item", std::make_unique<DownloadItemActivatedData>( TYPE_ACTIVE_DOWNLOAD, GetId(), GetOriginalUrl().spec(), GetURL().spec(), file_name, GetDangerType(), GetReceivedBytes(),
diff --git a/components/full_restore/full_restore_read_and_save_unittest.cc b/components/full_restore/full_restore_read_and_save_unittest.cc index be23021..f2ed701 100644 --- a/components/full_restore/full_restore_read_and_save_unittest.cc +++ b/components/full_restore/full_restore_read_and_save_unittest.cc
@@ -370,9 +370,10 @@ AddAppLaunchInfo(tmp_dir2.GetPath(), kId2); EXPECT_TRUE(timer->IsRunning()); + CreateWindowInfo(kId2, kActivationIndex2); + // Simulate timeout, and verify the timer stops. timer->FireNow(); - CreateWindowInfo(kId2, kActivationIndex2); task_environment().RunUntilIdle(); EXPECT_FALSE(timer->IsRunning());
diff --git a/components/image_fetcher/BUILD.gn b/components/image_fetcher/BUILD.gn index 8114f5b..db74499 100644 --- a/components/image_fetcher/BUILD.gn +++ b/components/image_fetcher/BUILD.gn
@@ -65,6 +65,7 @@ "//components/embedder_support/android:simple_factory_key_java", "//third_party/android_deps:robolectric_all_java", "//third_party/android_support_test_runner:runner_java", + "//third_party/androidx:androidx_test_runner_java", "//third_party/gif_player:gif_player_java", "//third_party/junit", "//third_party/mockito:mockito_java",
diff --git a/components/image_fetcher/android/junit/src/org/chromium/components/image_fetcher/ImageFetcherFactoryTest.java b/components/image_fetcher/android/junit/src/org/chromium/components/image_fetcher/ImageFetcherFactoryTest.java index 779bb10..5c2ea53 100644 --- a/components/image_fetcher/android/junit/src/org/chromium/components/image_fetcher/ImageFetcherFactoryTest.java +++ b/components/image_fetcher/android/junit/src/org/chromium/components/image_fetcher/ImageFetcherFactoryTest.java
@@ -8,7 +8,7 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; -import android.support.test.filters.SmallTest; +import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Test;
diff --git a/components/metrics/net/DEPS b/components/metrics/net/DEPS index 3637549..eacfe8fa 100644 --- a/components/metrics/net/DEPS +++ b/components/metrics/net/DEPS
@@ -7,6 +7,7 @@ "+ios/web/public/test/web_task_environment.h", "+net", "+services/network/public/cpp", + "+services/network/public/mojom", "+services/network/test", "+third_party/cros_system_api", ]
diff --git a/components/metrics/net/net_metrics_log_uploader.cc b/components/metrics/net/net_metrics_log_uploader.cc index a946d20..1d92b58 100644 --- a/components/metrics/net/net_metrics_log_uploader.cc +++ b/components/metrics/net/net_metrics_log_uploader.cc
@@ -23,6 +23,7 @@ #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/simple_url_loader.h" +#include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/metrics_proto/chrome_user_metrics_extension.pb.h" #include "third_party/metrics_proto/reporting_info.pb.h" #include "third_party/zlib/google/compression_utils.h"
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index a825254c..2b985e0 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -114,19 +114,6 @@ return base::FeatureList::IsEnabled(features::kUsernameFirstFlow); } -// Find a field in |predictions| with given renderer id. -const PasswordFieldPrediction* FindFieldPrediction( - const absl::optional<FormPredictions>& predictions, - autofill::FieldRendererId field_renderer_id) { - if (!predictions) - return nullptr; - for (const auto& field : predictions->fields) { - if (field.renderer_id == field_renderer_id) - return &field; - } - return nullptr; -} - void LogUsingPossibleUsername(PasswordManagerClient* client, bool is_used, const char* message) { @@ -581,6 +568,11 @@ } #endif // defined(OS_IOS) +void PasswordFormManager::SaveSuggestedUsernameValueToVotesUploader() { + votes_uploader_.set_suggested_username( + GetPendingCredentials().username_value); +} + std::unique_ptr<PasswordFormManager> PasswordFormManager::Clone() { // Fetcher is cloned to avoid re-fetching data from PasswordStore. std::unique_ptr<FormFetcher> fetcher = form_fetcher_->Clone(); @@ -718,18 +710,24 @@ votes_uploader_.clear_single_username_vote_data(); if (IsUsernameFirstFlowFeatureEnabled() && - parsed_submitted_form_->username_value.empty() && - UsePossibleUsernameToBuildCredential(possible_username)) { - parsed_submitted_form_->username_value = possible_username->value; - metrics_recorder_->set_possible_username_used(true); - // PasswordManager does not upload votes for fields that have no names or - // ids to avoid aggregation of multiple unrelated fields during single - // username detection. (crbug.com/1209143) - if (!possible_username->field_name.empty() && - possible_username->form_predictions) { - votes_uploader_.set_single_username_vote_data( - possible_username->renderer_id, *possible_username->form_predictions); + parsed_submitted_form_->username_value.empty() && possible_username && + IsPossibleSingleUsernameAvailable(possible_username)) { + // Suggest the possible username value in a prompt if the server confirmed + // it is a single username field. Otherwise, |possible_username| is used + // only for voting. + if (possible_username->HasSingleUsernameServerPrediction()) { + parsed_submitted_form_->username_value = possible_username->value; + LogUsingPossibleUsername(client_, /*is_used*/ true, + "Valid possible username, populated in prompt"); + } else { + LogUsingPossibleUsername( + client_, /*is_used*/ true, + "Valid possible username, not populated in prompt"); } + metrics_recorder_->set_possible_username_used(true); + votes_uploader_.set_single_username_vote_data( + possible_username->renderer_id, possible_username->value, + possible_username->form_predictions.value_or(FormPredictions())); } CreatePendingCredentials(); return true; @@ -992,8 +990,8 @@ ->ComputePasswordAccountStorageUsageLevel()); } -bool PasswordFormManager::UsePossibleUsernameToBuildCredential( - const PossibleUsernameData* possible_username) { +bool PasswordFormManager::IsPossibleSingleUsernameAvailable( + const PossibleUsernameData* possible_username) const { if (!possible_username) { LogUsingPossibleUsername(client_, /*is_used*/ false, "Null"); return false; @@ -1011,7 +1009,15 @@ return false; } - if (IsPossibleUsernameStale(*possible_username)) { + // PasswordManager does not upload votes for fields that have no names or + // ids to avoid aggregation of multiple unrelated fields during single + // username detection. (crbug.com/1209143) + if (possible_username->field_name.empty()) { + LogUsingPossibleUsername(client_, /*is_used*/ false, "Empty field name"); + return false; + } + + if (possible_username->IsStale()) { LogUsingPossibleUsername(client_, /*is_used*/ false, "Possible username data expired"); return false; @@ -1028,18 +1034,7 @@ } } - // Check if there is a server prediction. - const PasswordFieldPrediction* field_prediction = FindFieldPrediction( - possible_username->form_predictions, possible_username->renderer_id); - if (field_prediction && field_prediction->type == SINGLE_USERNAME) { - LogUsingPossibleUsername(client_, /*is_used*/ true, - "Server predictions available"); - return true; - } else { - LogUsingPossibleUsername(client_, /*is_used*/ false, - "No server predictions"); - return false; - } + return true; } void PasswordFormManager::UpdatePredictionsForObservedForm(
diff --git a/components/password_manager/core/browser/password_form_manager.h b/components/password_manager/core/browser/password_form_manager.h index ced18968..78bc183 100644 --- a/components/password_manager/core/browser/password_form_manager.h +++ b/components/password_manager/core/browser/password_form_manager.h
@@ -229,6 +229,9 @@ return absl::get_if<autofill::FormData>(&observed_form_or_digest_); } + // Saves username value from |pending_credentials_| to votes uploader. + void SaveSuggestedUsernameValueToVotesUploader(); + #if defined(UNIT_TEST) static void set_wait_for_server_predictions_for_filling(bool value) { wait_for_server_predictions_for_filling_ = value; @@ -238,6 +241,7 @@ return password_save_manager_->GetFormSaver(); } + const VotesUploader& votes_uploader() const { return votes_uploader_; } #endif protected: @@ -311,12 +315,10 @@ PasswordFormDigest ConstructObservedFormDigest() const; - // Returns whether |possible_username| should be populated in a Save/Update - // prompt on username first flow. The decision is based on server predictions, - // and whether |possible_username| has a non empty value and is not expired - // yet. - bool UsePossibleUsernameToBuildCredential( - const PossibleUsernameData* possible_username); + // Returns whether |possible_username| data can be used in username first + // flow. + bool IsPossibleSingleUsernameAvailable( + const PossibleUsernameData* possible_username) const; // Updates the predictions stored in |parser_| with predictions relevant for // |observed_form_or_digest_|.
diff --git a/components/password_manager/core/browser/password_form_manager_unittest.cc b/components/password_manager/core/browser/password_form_manager_unittest.cc index 7e0a5fa..bd6435e 100644 --- a/components/password_manager/core/browser/password_form_manager_unittest.cc +++ b/components/password_manager/core/browser/password_form_manager_unittest.cc
@@ -2210,7 +2210,8 @@ } // Create possible username data. - const std::u16string possible_username = u"possible_username"; + const std::u16string possible_username = + is_password_update ? saved_match_.username_value : u"possible_username"; constexpr autofill::FieldRendererId kUsernameFieldRendererId(101); const std::u16string field_name = u"username_field"; PossibleUsernameData possible_username_data( @@ -2233,6 +2234,7 @@ ASSERT_TRUE(form_manager_->ProvisionallySave(submitted_form, &driver_, &possible_username_data)); + EXPECT_EQ(form_manager_->IsPasswordUpdate(), is_password_update); // Check that uploads for both username and password form happen. testing::InSequence in_sequence; @@ -2246,10 +2248,12 @@ } // Upload for the username form. +#if !defined(OS_ANDROID) EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest(SignatureIs(kUsernameFormSignature), false, ServerFieldTypeSet{SINGLE_USERNAME}, _, true, nullptr)); +#endif // !defined(OS_ANDROID) if (is_password_update) { // Upload for the password form. @@ -2259,11 +2263,11 @@ false, _, _, true, nullptr)); } - if (!is_password_update) { + if (!is_password_update) form_manager_->Save(); - } else { + else form_manager_->Update(saved_match_); - } + Mock::VerifyAndClearExpectations(&mock_autofill_download_manager_); } } @@ -2319,11 +2323,14 @@ // Upload for the username form. Ensure that we send `NOT_USERNAME` for the // username field. +#if !defined(OS_ANDROID) EXPECT_CALL( mock_autofill_download_manager_, StartUploadRequest(SignatureIs(kUsernameFormSignature), false, ServerFieldTypeSet{NOT_USERNAME}, _, true, nullptr)); - +#else + EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0); +#endif // !defined(OS_ANDROID) form_manager_->Save(); } @@ -3016,8 +3023,7 @@ FormData submitted_form = observed_form_only_password_fields_; submitted_form.fields[0].value = u"strongpassword"; PasswordForm parsed_submitted_form; - EXPECT_CALL(*mock_password_save_manager(), - CreatePendingCredentials(_, _, _, _, _)) + EXPECT_CALL(*mock_password_save_manager(), CreatePendingCredentials) .WillOnce(SaveArg<0>(&parsed_submitted_form)); ASSERT_TRUE(form_manager_->ProvisionallySave(submitted_form, &driver_, &possible_username_data));
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index cdf07abf8..f06016a6 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -1011,6 +1011,7 @@ if (ShouldPromptUserToSavePassword(*submitted_manager)) { if (logger) logger->LogMessage(Logger::STRING_DECISION_ASK); + submitted_manager->SaveSuggestedUsernameValueToVotesUploader(); bool update_password = submitted_manager->IsPasswordUpdate(); if (client_->PromptUserToSaveOrUpdatePassword(MoveOwnedSubmittedManager(), update_password)) {
diff --git a/components/password_manager/core/browser/password_manager_unittest.cc b/components/password_manager/core/browser/password_manager_unittest.cc index 3c52620..a146c06 100644 --- a/components/password_manager/core/browser/password_manager_unittest.cc +++ b/components/password_manager/core/browser/password_manager_unittest.cc
@@ -885,6 +885,10 @@ .WillOnce(WithArg<1>(InvokeConsumer(store_.get(), existing_different))); manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); + ASSERT_TRUE(manager()->form_managers().front()); + const VotesUploader& votes_uploader = + manager()->form_managers().front()->votes_uploader(); + EXPECT_CALL(client_, IsSavingAndFillingEnabled(form.url)) .WillRepeatedly(Return(true)); OnPasswordFormSubmitted(form.form_data); @@ -900,6 +904,9 @@ manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); + // Check that suggested value was properly recorded in VotesUploader. + EXPECT_EQ(form.username_value, votes_uploader.suggested_username()); + // Simulate saving the form. EXPECT_CALL(*store_, AddLogin(FormMatches(form))); ASSERT_TRUE(form_manager_to_save); @@ -1084,6 +1091,9 @@ manager()->OnPasswordFormsParsed(&driver_, observed); EXPECT_TRUE(manager()->IsPasswordFieldDetectedOnPage()); manager()->OnPasswordFormsRendered(&driver_, observed, true); + ASSERT_TRUE(manager()->form_managers().front()); + const VotesUploader& votes_uploader = + manager()->form_managers().front()->votes_uploader(); EXPECT_CALL(client_, IsSavingAndFillingEnabled(form.url)) .WillRepeatedly(Return(true)); @@ -1097,6 +1107,9 @@ manager()->OnPasswordFormsParsed(&driver_, observed); manager()->OnPasswordFormsRendered(&driver_, observed, true); + // Check that suggested value was properly recorded in VotesUploader. + EXPECT_EQ(form.username_value, votes_uploader.suggested_username()); + // Simulate saving the form, as if the info bar was accepted. EXPECT_CALL(*store_, AddLogin(FormMatches(form))); ASSERT_TRUE(form_manager_to_save); @@ -3907,6 +3920,9 @@ form_data.fields.push_back(confirm_password_field); manager()->OnPasswordFormsParsed(&driver_, {form_data}); + ASSERT_TRUE(manager()->form_managers().front()); + const VotesUploader& votes_uploader = + manager()->form_managers().front()->votes_uploader(); form_data.fields[0].value = u"oldpass"; form_data.fields[1].value = u"newpass"; @@ -3918,6 +3934,9 @@ EXPECT_CALL(client_, PromptUserToSaveOrUpdatePasswordPtr) .WillOnce(WithArg<0>(SaveToScopedPtr(&form_manager_to_save))); manager()->OnPasswordFormCleared(&driver_, form_data); + + // Check that suggested username was properly recorded in VotesUploader. + EXPECT_EQ(saved_match.username_value, votes_uploader.suggested_username()); } // Similar test as above with fields that have empty names.
diff --git a/components/password_manager/core/browser/password_save_manager_impl.cc b/components/password_manager/core/browser/password_save_manager_impl.cc index 498e9fb..cc226e2 100644 --- a/components/password_manager/core/browser/password_save_manager_impl.cc +++ b/components/password_manager/core/browser/password_save_manager_impl.cc
@@ -497,6 +497,9 @@ parsed_submitted_form.submission_event); metrics_recorder_->SetSubmissionIndicatorEvent( parsed_submitted_form.submission_event); + // Remember the final username value which the user accepted the prompt + // with in order to produce votes based on username edits. + votes_uploader_->set_saved_username(pending_credentials_.username_value); if (IsNewLogin()) { metrics_util::LogNewlySavedPasswordIsGenerated(
diff --git a/components/password_manager/core/browser/password_save_manager_impl_unittest.cc b/components/password_manager/core/browser/password_save_manager_impl_unittest.cc index e5aeac0..e17d13b4 100644 --- a/components/password_manager/core/browser/password_save_manager_impl_unittest.cc +++ b/components/password_manager/core/browser/password_save_manager_impl_unittest.cc
@@ -353,6 +353,8 @@ fetcher()->NotifyFetchCompleted(); } + VotesUploader* votes_uploader() { return &votes_uploader_; } + FormData observed_form_; FormData submitted_form_; FormData observed_form_only_password_fields_; @@ -604,6 +606,7 @@ EXPECT_EQ(submitted_form.url, saved_form.url); EXPECT_EQ(expected_signon_realm, saved_form.signon_realm); EXPECT_EQ(new_username, saved_form.username_value); + EXPECT_EQ(new_username, votes_uploader()->saved_username()); EXPECT_EQ(new_password, saved_form.password_value); EXPECT_EQ(submitted_form.fields[kUsernameFieldIndex].name, @@ -694,6 +697,7 @@ EXPECT_TRUE(ArePasswordFormUniqueKeysEqual(saved_match_, updated_form)); EXPECT_EQ(new_password, updated_form.password_value); + EXPECT_EQ(username, votes_uploader()->saved_username()); } // Tests that when the user changes password on a change password form then the @@ -734,6 +738,7 @@ EXPECT_TRUE(ArePasswordFormUniqueKeysEqual(saved_match_, updated_form)); EXPECT_EQ(new_password, updated_form.password_value); + EXPECT_EQ(saved_match_.username_value, votes_uploader()->saved_username()); } TEST_P(PasswordSaveManagerImplTest, UpdateUsernameToAnotherFieldValue) { @@ -767,6 +772,10 @@ EXPECT_EQ( user_chosen_username, password_save_manager_impl()->GetPendingCredentials().username_value); + + password_save_manager_impl()->Save(&observed_form_only_password_fields_, + parsed_submitted_form); + EXPECT_EQ(user_chosen_username, votes_uploader()->saved_username()); } TEST_P(PasswordSaveManagerImplTest, UpdateUsernameToAlreadyExisting) {
diff --git a/components/password_manager/core/browser/possible_username_data.cc b/components/password_manager/core/browser/possible_username_data.cc index 25dff93..6721d32 100644 --- a/components/password_manager/core/browser/possible_username_data.cc +++ b/components/password_manager/core/browser/possible_username_data.cc
@@ -15,6 +15,21 @@ namespace password_manager { +namespace { + +// Find a field in |predictions| with given renderer id. +const PasswordFieldPrediction* FindFieldPrediction( + const FormPredictions& predictions, + autofill::FieldRendererId field_renderer_id) { + for (const auto& field : predictions.fields) { + if (field.renderer_id == field_renderer_id) + return &field; + } + return nullptr; +} + +} // namespace + PossibleUsernameData::PossibleUsernameData( std::string signon_realm, autofill::FieldRendererId renderer_id, @@ -32,9 +47,18 @@ default; PossibleUsernameData::~PossibleUsernameData() = default; -bool IsPossibleUsernameStale(const PossibleUsernameData& possible_username) { - return base::Time::Now() - possible_username.last_change > - kPossibleUsernameExpirationTimeout; +bool PossibleUsernameData::IsStale() const { + return base::Time::Now() - last_change > kPossibleUsernameExpirationTimeout; +} + +bool PossibleUsernameData::HasSingleUsernameServerPrediction() const { + // Check if there is a server prediction. + if (!form_predictions) + return false; + const PasswordFieldPrediction* field_prediction = + FindFieldPrediction(*form_predictions, renderer_id); + return field_prediction && + field_prediction->type == autofill::SINGLE_USERNAME; } } // namespace password_manager
diff --git a/components/password_manager/core/browser/possible_username_data.h b/components/password_manager/core/browser/possible_username_data.h index 61a6ecb..169453c 100644 --- a/components/password_manager/core/browser/possible_username_data.h +++ b/components/password_manager/core/browser/possible_username_data.h
@@ -45,11 +45,15 @@ // Predictions for the form which contains a field with |renderer_id|. absl::optional<FormPredictions> form_predictions; -}; -// Returns whether |possible_username| was last edited too far in the past and -// should not be considered as a possible single username. -bool IsPossibleUsernameStale(const PossibleUsernameData& possible_username); + // Returns whether |possible_username| was last edited too far in the past and + // should not be considered as a possible single username. + bool IsStale() const; + + // Returns whether the field identified by |renderer_id| has a + // SINGLE_USERNAME prediction stored in |form_predictions|. + bool HasSingleUsernameServerPrediction() const; +}; } // namespace password_manager
diff --git a/components/password_manager/core/browser/possible_username_data_unittest.cc b/components/password_manager/core/browser/possible_username_data_unittest.cc index db005fe..4f6fee1 100644 --- a/components/password_manager/core/browser/possible_username_data_unittest.cc +++ b/components/password_manager/core/browser/possible_username_data_unittest.cc
@@ -34,17 +34,17 @@ // Check that if more than |kPossibleUsernameExpirationTimeout| time has // passed since the last change of |possible_username_data_|, then it is stale. TEST_F(IsPossibleUsernameValidTest, IsPossibleUsernameStale) { - EXPECT_FALSE(IsPossibleUsernameStale(possible_username_data_)); + EXPECT_FALSE(possible_username_data_.IsStale()); // Fast forward for a little less than expiration time, but not // exactly to not flake the test. task_environment_.FastForwardBy(kPossibleUsernameExpirationTimeout - TimeDelta::FromSeconds(3)); - EXPECT_FALSE(IsPossibleUsernameStale(possible_username_data_)); + EXPECT_FALSE(possible_username_data_.IsStale()); // Fast forward more until the data becomes stale. task_environment_.FastForwardBy(TimeDelta::FromSeconds(5)); - EXPECT_TRUE(IsPossibleUsernameStale(possible_username_data_)); + EXPECT_TRUE(possible_username_data_.IsStale()); } } // namespace
diff --git a/components/password_manager/core/browser/vote_uploads_test_matchers.h b/components/password_manager/core/browser/vote_uploads_test_matchers.h index afe797e8..739c97e 100644 --- a/components/password_manager/core/browser/vote_uploads_test_matchers.h +++ b/components/password_manager/core/browser/vote_uploads_test_matchers.h
@@ -170,6 +170,23 @@ return true; } +MATCHER_P(UploadedSingleUsernameVoteTypeIs, expected_type, "") { + for (const auto& field : arg) { + autofill::ServerFieldType vote = field->possible_types().empty() + ? autofill::UNKNOWN_TYPE + : *field->possible_types().begin(); + if ((vote == autofill::SINGLE_USERNAME || vote == autofill::NOT_USERNAME) && + expected_type != field->single_username_vote_type()) { + // Wrong vote type. + *result_listener << "Expected vote type for the field " << field->name + << " is " << expected_type << ", but found " + << field->single_username_vote_type().value(); + return false; + } + } + return true; +} + MATCHER_P(PasswordsWereRevealed, passwords_were_revealed, "") { return passwords_were_revealed == arg.passwords_were_revealed(); }
diff --git a/components/password_manager/core/browser/votes_uploader.cc b/components/password_manager/core/browser/votes_uploader.cc index d614cbe8..5ff1eb03 100644 --- a/components/password_manager/core/browser/votes_uploader.cc +++ b/components/password_manager/core/browser/votes_uploader.cc
@@ -15,6 +15,7 @@ #include "base/rand_util.h" #include "base/ranges/algorithm.h" #include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" #include "components/autofill/core/browser/autofill_download_manager.h" #include "components/autofill/core/browser/autofill_field.h" #include "components/autofill/core/browser/form_structure.h" @@ -177,8 +178,11 @@ SingleUsernameVoteData::SingleUsernameVoteData( autofill::FieldRendererId renderer_id, + const std::u16string& username_candidate_value, const FormPredictions& form_predictions) - : renderer_id(renderer_id), form_predictions(form_predictions) {} + : renderer_id(renderer_id), + username_candidate_value(username_candidate_value), + form_predictions(form_predictions) {} SingleUsernameVoteData::SingleUsernameVoteData( const SingleUsernameVoteData& other) = default; @@ -487,26 +491,24 @@ for (size_t i = 0; i < form_to_upload->field_count(); ++i) { AutofillField* field = form_to_upload->field(i); - ServerFieldType type = autofill::UNKNOWN_TYPE; autofill::FieldRendererId field_renderer_id = predictions.fields[i].renderer_id; - if (field_renderer_id == single_username_vote_data_->renderer_id) { - if (field_info_manager->GetFieldType(predictions.form_signature, - predictions.fields[i].signature) != - autofill::UNKNOWN_TYPE) { - // The vote for this field has been already sent. Don't send again. - return; - } - type = username_change_state_ == UsernameChangeState::kUnchanged - ? autofill::SINGLE_USERNAME - : autofill::NOT_USERNAME; - if (username_change_state_ == UsernameChangeState::kChangedToKnownValue) - field->set_vote_type(AutofillUploadContents::Field::USERNAME_EDITED); - available_field_types.insert(type); - SaveFieldVote(form_to_upload->form_signature(), - field->GetFieldSignature(), type); + + if (field_renderer_id != single_username_vote_data_->renderer_id) { + field->set_possible_types({autofill::UNKNOWN_TYPE}); + continue; } - field->set_possible_types({type}); + if (field_info_manager->GetFieldType(predictions.form_signature, + predictions.fields[i].signature) != + autofill::UNKNOWN_TYPE) { + // The vote for this field has been already sent. Don't send again. + return; + } + if (!SetSingleUsernameVote(field, &available_field_types, + form_to_upload->form_signature())) { + // The single username field has no field type. Don't send vote. + return; + } } if (password_manager_util::IsLoggingActive(client_)) { @@ -713,4 +715,54 @@ field_info_manager->AddFieldType(form_signature, field_signature, field_type); } +bool VotesUploader::SetSingleUsernameVote( + AutofillField* field, + ServerFieldTypeSet* available_field_types, + autofill::FormSignature form_signature) { + ServerFieldType type = autofill::UNKNOWN_TYPE; + autofill::AutofillUploadContents_Field_SingleUsernameVoteType vote_type = + AutofillUploadContents::Field::DEFAULT; + + // Send a negative vote if the possible username value contains whitespaces. + const std::u16string single_username_value = + single_username_vote_data_->username_candidate_value; + if (single_username_value.find(' ') != std::u16string::npos) { + type = autofill::NOT_USERNAME; + vote_type = AutofillUploadContents::Field::HAD_WHITESPACES; + } else { +// It's not possible to edit username in the save prompt on Android, thus it's +// not possible to rely on this heuristic. +#if !defined(OS_ANDROID) + if (saved_username_ != suggested_username_) { + // The user edited the username in a prompt before accepting it. + // The user removed some suggested username and that username wasn't the + // possible single username (|single_username_value|) => this is neither + // negative or positive vote. If the user removes |single_username_value|, + // then it is a negative signal and will be reported below. + if (saved_username_.empty() && + suggested_username_ != single_username_value) { + return false; + } + type = saved_username_ == single_username_value + ? autofill::SINGLE_USERNAME + : autofill::NOT_USERNAME; + vote_type = AutofillUploadContents::Field::EDITED_IN_PROMPT; + } else { // saved_username_ == suggested_username + // The user did NOT edit the username in prompt and accepted it as it is. + type = saved_username_ == single_username_value + ? autofill::SINGLE_USERNAME + : autofill::NOT_USERNAME; + vote_type = AutofillUploadContents::Field::NOT_EDITED_IN_PROMPT; + } +#else + return false; +#endif // !defined(OS_ANDROID) + } + available_field_types->insert(type); + SaveFieldVote(form_signature, field->GetFieldSignature(), type); + field->set_possible_types({type}); + field->set_single_username_vote_type(vote_type); + return true; +} + } // namespace password_manager
diff --git a/components/password_manager/core/browser/votes_uploader.h b/components/password_manager/core/browser/votes_uploader.h index 88a2c27..fa6bba7 100644 --- a/components/password_manager/core/browser/votes_uploader.h +++ b/components/password_manager/core/browser/votes_uploader.h
@@ -18,6 +18,7 @@ #include "third_party/abseil-cpp/absl/types/optional.h" namespace autofill { +class AutofillField; struct FormData; class FormStructure; } // namespace autofill @@ -35,6 +36,7 @@ // Contains information for sending a SINGLE_USERNAME vote. struct SingleUsernameVoteData { SingleUsernameVoteData(autofill::FieldRendererId renderer_id, + const std::u16string& username_candidate_value, const FormPredictions& form_predictions); SingleUsernameVoteData(const SingleUsernameVoteData&); SingleUsernameVoteData& operator=(const SingleUsernameVoteData&); @@ -45,6 +47,9 @@ // sent. autofill::FieldRendererId renderer_id; + // Value of the single username candidate field. + std::u16string username_candidate_value; + // Predictions for the form which contains a field with |renderer_id|. FormPredictions form_predictions; }; @@ -129,6 +134,8 @@ // SINGLE_USERNAME (if the user saved the credential with the username // captured from |single_username_vote_data|) or NOT_USERNAME (if the user // modified the username). + // TODO (crbug.com/959776): Have a single point in code that calls this + // method. void MaybeSendSingleUsernameVote(); void set_generation_popup_was_shown(bool generation_popup_was_shown) { @@ -173,11 +180,29 @@ void clear_single_username_vote_data() { single_username_vote_data_.reset(); } - void set_single_username_vote_data(autofill::FieldRendererId renderer_id, - const FormPredictions& form_predictions) { - single_username_vote_data_.emplace(renderer_id, form_predictions); + void set_single_username_vote_data( + autofill::FieldRendererId renderer_id, + const std::u16string& username_candidate_value, + const FormPredictions& form_predictions) { + single_username_vote_data_.emplace(renderer_id, username_candidate_value, + form_predictions); } + void set_suggested_username(const std::u16string& suggested_username) { + suggested_username_ = suggested_username; + } + + void set_saved_username(const std::u16string& saved_username) { + saved_username_ = saved_username; + } + +#if defined(UNIT_TEST) + const std::u16string& suggested_username() const { + return suggested_username_; + } + const std::u16string& saved_username() const { return saved_username_; } +#endif + private: // The outcome of the form classifier. enum FormClassifierOutcome { @@ -211,6 +236,14 @@ autofill::FieldSignature field_signature, autofill::ServerFieldType field_type); + // Sets a server field type for the |field| and updates + // |available_field_types| and |field_info_manager| accordingly. Returns true + // iff a non-default type is assigned to the |field|. + bool SetSingleUsernameVote( + autofill::AutofillField* field, + autofill::ServerFieldTypeSet* available_field_types, + autofill::FormSignature form_signature); + // The client which implements embedder-specific PasswordManager operations. PasswordManagerClient* client_; @@ -256,6 +289,12 @@ std::map<autofill::FieldRendererId, std::u16string> initial_values_; absl::optional<SingleUsernameVoteData> single_username_vote_data_; + + // The username that is suggested in a save/update prompt. + std::u16string suggested_username_; + + // The username that was saved. + std::u16string saved_username_; }; } // namespace password_manager
diff --git a/components/password_manager/core/browser/votes_uploader_unittest.cc b/components/password_manager/core/browser/votes_uploader_unittest.cc index c06133e..c367de9c 100644 --- a/components/password_manager/core/browser/votes_uploader_unittest.cc +++ b/components/password_manager/core/browser/votes_uploader_unittest.cc
@@ -64,6 +64,19 @@ constexpr int kNumberOfPasswordAttributes = static_cast<int>(PasswordAttribute::kPasswordAttributesCount); +constexpr autofill::FieldRendererId kSingleUsernameRendererId(101); +constexpr FieldSignature kSingleUsernameFieldSignature(1234); +constexpr FormSignature kSingleUsernameFormSignature(1000); + +FormPredictions MakeSimpleSingleUsernamePredictions() { + FormPredictions form_predictions; + form_predictions.form_signature = kSingleUsernameFormSignature; + form_predictions.fields.emplace_back(); + form_predictions.fields.back().renderer_id = kSingleUsernameRendererId; + form_predictions.fields.back().signature = kSingleUsernameFieldSignature; + return form_predictions; +} + class MockAutofillDownloadManager : public AutofillDownloadManager { public: MockAutofillDownloadManager() @@ -402,114 +415,258 @@ TEST_F(VotesUploaderTest, NoSingleUsernameDataNoUpload) { VotesUploader votes_uploader(&client_, false); - EXPECT_CALL(mock_autofill_download_manager_, - StartUploadRequest(_, _, _, _, _, _)) - .Times(0); + EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0); votes_uploader.MaybeSendSingleUsernameVote(); } -TEST_F(VotesUploaderTest, UploadSingleUsername) { - for (bool credentials_saved : {false, true}) { - SCOPED_TRACE(testing::Message("credentials_saved = ") << credentials_saved); - VotesUploader votes_uploader(&client_, false); +TEST_F(VotesUploaderTest, UploadSingleUsernameMultipleFieldsInUsernameForm) { + VotesUploader votes_uploader(&client_, false); - MockFieldInfoManager mock_field_manager; - ON_CALL(mock_field_manager, GetFieldType(_, _)) - .WillByDefault(Return(UNKNOWN_TYPE)); - ON_CALL(client_, GetFieldInfoManager()) - .WillByDefault(Return(&mock_field_manager)); + MockFieldInfoManager mock_field_manager; + ON_CALL(mock_field_manager, GetFieldType(_, _)) + .WillByDefault(Return(UNKNOWN_TYPE)); + ON_CALL(client_, GetFieldInfoManager()) + .WillByDefault(Return(&mock_field_manager)); - constexpr autofill::FieldRendererId kUsernameRendererId(101); - constexpr FieldSignature kUsernameFieldSignature(1234); - constexpr FormSignature kFormSignature(1000); + // Make form predictions for a form with multiple fields. + FormPredictions form_predictions; + form_predictions.form_signature = kSingleUsernameFormSignature; + // Add a non-username field. + form_predictions.fields.emplace_back(); + form_predictions.fields.back().renderer_id.value() = + kSingleUsernameRendererId.value() - 1; + form_predictions.fields.back().signature.value() = + kSingleUsernameFieldSignature.value() - 1; + // Add the username field. + form_predictions.fields.emplace_back(); + form_predictions.fields.back().renderer_id = kSingleUsernameRendererId; + form_predictions.fields.back().signature = kSingleUsernameFieldSignature; - FormPredictions form_predictions; - form_predictions.form_signature = kFormSignature; - // Add a non-username field. - form_predictions.fields.emplace_back(); - form_predictions.fields.back().renderer_id.value() = - kUsernameRendererId.value() - 1; - form_predictions.fields.back().signature.value() = - kUsernameFieldSignature.value() - 1; + std::u16string single_username_candidate_value = u"username_candidate_value"; + votes_uploader.set_single_username_vote_data(kSingleUsernameRendererId, + single_username_candidate_value, + form_predictions); + votes_uploader.set_suggested_username(single_username_candidate_value); + votes_uploader.set_saved_username(single_username_candidate_value); - // Add the username field. - form_predictions.fields.emplace_back(); - form_predictions.fields.back().renderer_id = kUsernameRendererId; - form_predictions.fields.back().signature = kUsernameFieldSignature; +#if !defined(OS_ANDROID) + ServerFieldTypeSet expected_types = {SINGLE_USERNAME}; + EXPECT_CALL( + mock_autofill_download_manager_, + StartUploadRequest(AllOf(SignatureIs(kSingleUsernameFormSignature), + UploadedSingleUsernameVoteTypeIs( + autofill::AutofillUploadContents::Field:: + NOT_EDITED_IN_PROMPT)), + false, expected_types, std::string(), true, + /* pref_service= */ nullptr)); +#else + EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0); +#endif // !defined(OS_ANDROID) - votes_uploader.set_single_username_vote_data(kUsernameRendererId, - form_predictions); - - ServerFieldTypeSet expected_types = {SINGLE_USERNAME}; - EXPECT_CALL(mock_autofill_download_manager_, - StartUploadRequest(SignatureIs(kFormSignature), false, - expected_types, std::string(), true, - /* pref_service= */ nullptr)); - - votes_uploader.MaybeSendSingleUsernameVote(); - } + votes_uploader.MaybeSendSingleUsernameVote(); } -// Verifies that the sent username vote depends on whether the username was -// changed or not. -TEST_F(VotesUploaderTest, UploadedVotesDependOnUsernameChangeState) { - using State = VotesUploader::UsernameChangeState; - constexpr autofill::FieldRendererId kUsernameRendererId(101); - constexpr FieldSignature kUsernameFieldSignature(1234); - constexpr FormSignature kFormSignature(1000); +// Tests that a negeative vote is sent if the username candidate field +// value contained whitespaces. +TEST_F(VotesUploaderTest, UploadNotSingleUsernameForWhitespaces) { + VotesUploader votes_uploader(&client_, false); MockFieldInfoManager mock_field_manager; + ON_CALL(mock_field_manager, GetFieldType(_, _)) + .WillByDefault(Return(UNKNOWN_TYPE)); + ON_CALL(client_, GetFieldInfoManager()) + .WillByDefault(Return(&mock_field_manager)); + + votes_uploader.set_single_username_vote_data( + kSingleUsernameRendererId, + /*username_candidate_value=*/u"some search query", + MakeSimpleSingleUsernamePredictions()); + + ServerFieldTypeSet expected_types = {NOT_USERNAME}; + EXPECT_CALL( + mock_autofill_download_manager_, + StartUploadRequest( + AllOf(SignatureIs(kSingleUsernameFormSignature), + UploadedSingleUsernameVoteTypeIs( + autofill::AutofillUploadContents::Field::HAD_WHITESPACES)), + false, expected_types, std::string(), true, + /* pref_service= */ nullptr)); + + votes_uploader.MaybeSendSingleUsernameVote(); +} + +// Verifies that SINGLE_USERNAME vote and NOT_EDITED_IN_PROMPT vote type +// are sent if single username candidate value was suggested and accepted. +TEST_F(VotesUploaderTest, SingleUsernameValueSuggestedAndAccepted) { + MockFieldInfoManager mock_field_manager; ON_CALL(mock_field_manager, GetFieldType).WillByDefault(Return(UNKNOWN_TYPE)); ON_CALL(client_, GetFieldInfoManager) .WillByDefault(Return(&mock_field_manager)); - for (State username_change_state : - {State::kUnchanged, State::kChangedToKnownValue, - State::kChangedToUnknownValue}) { - SCOPED_TRACE(testing::Message("username_change_state = ") - << base::to_underlying(username_change_state)); - ServerFieldTypeSet kExpectedVotes = { - username_change_state == State::kUnchanged ? SINGLE_USERNAME - : NOT_USERNAME}; + VotesUploader votes_uploader(&client_, false); + std::u16string single_username_candidate_value = u"username_candidate_value"; + votes_uploader.set_single_username_vote_data( + kSingleUsernameRendererId, single_username_candidate_value, + MakeSimpleSingleUsernamePredictions()); + votes_uploader.set_suggested_username(single_username_candidate_value); + votes_uploader.set_saved_username(single_username_candidate_value); - VotesUploader votes_uploader(&client_, false); - votes_uploader.set_username_change_state(username_change_state); +#if !defined(OS_ANDROID) + ServerFieldTypeSet expected_types = {SINGLE_USERNAME}; + EXPECT_CALL( + mock_autofill_download_manager_, + StartUploadRequest(AllOf(SignatureIs(kSingleUsernameFormSignature), + UploadedSingleUsernameVoteTypeIs( + autofill::AutofillUploadContents::Field:: + NOT_EDITED_IN_PROMPT)), + /*form_was_autofilled=*/false, expected_types, + /*login_form_signature=*/"", + /*observed_submission=*/true, + /*pref_service=*/nullptr)); +#else + EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0); +#endif // !defined(OS_ANDROID) + votes_uploader.MaybeSendSingleUsernameVote(); +} - FormPredictions form_predictions; - form_predictions.form_signature = kFormSignature; - form_predictions.fields.push_back({ - .renderer_id = kUsernameRendererId, - .signature = kUsernameFieldSignature, - }); - votes_uploader.set_single_username_vote_data(kUsernameRendererId, - form_predictions); - EXPECT_CALL( - mock_autofill_download_manager_, - StartUploadRequest(SignatureIs(kFormSignature), - /*form_was_autofilled=*/false, kExpectedVotes, - /*login_form_signature=*/"", - /*observed_submission=*/true, - /*pref_service=*/nullptr)); - votes_uploader.MaybeSendSingleUsernameVote(); - } +// Verifies that NOT_USERNAME vote and NOT_EDITED_IN_PROMPT vote type +// are sent if value other than single username candidate was suggested and +// accepted. +TEST_F(VotesUploaderTest, SingleUsernameOtherValueSuggestedAndAccepted) { + MockFieldInfoManager mock_field_manager; + ON_CALL(mock_field_manager, GetFieldType).WillByDefault(Return(UNKNOWN_TYPE)); + ON_CALL(client_, GetFieldInfoManager) + .WillByDefault(Return(&mock_field_manager)); + + VotesUploader votes_uploader(&client_, false); + std::u16string single_username_candidate_value = u"username_candidate_value"; + votes_uploader.set_single_username_vote_data( + kSingleUsernameRendererId, single_username_candidate_value, + MakeSimpleSingleUsernamePredictions()); + std::u16string suggested_value = u"other_value"; + votes_uploader.set_suggested_username(suggested_value); + votes_uploader.set_saved_username(suggested_value); + +#if !defined(OS_ANDROID) + ServerFieldTypeSet expected_types = {NOT_USERNAME}; + EXPECT_CALL( + mock_autofill_download_manager_, + StartUploadRequest(AllOf(SignatureIs(kSingleUsernameFormSignature), + UploadedSingleUsernameVoteTypeIs( + autofill::AutofillUploadContents::Field:: + NOT_EDITED_IN_PROMPT)), + /*form_was_autofilled=*/false, expected_types, + /*login_form_signature=*/"", + /*observed_submission=*/true, + /*pref_service=*/nullptr)); +#else + EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0); +#endif // !defined(OS_ANDROID) + votes_uploader.MaybeSendSingleUsernameVote(); +} + +// Verifies that SINGLE_USERNAME vote and EDITED_IN_PROMPT vote type are sent +// if value other than single username candidate was suggested, but the user +// has inputted single username candidate value in prompt. +TEST_F(VotesUploaderTest, SingleUsernameValueSetInPrompt) { + MockFieldInfoManager mock_field_manager; + ON_CALL(mock_field_manager, GetFieldType).WillByDefault(Return(UNKNOWN_TYPE)); + ON_CALL(client_, GetFieldInfoManager) + .WillByDefault(Return(&mock_field_manager)); + + VotesUploader votes_uploader(&client_, false); + std::u16string single_username_candidate_value = u"username_candidate_value"; + votes_uploader.set_single_username_vote_data( + kSingleUsernameRendererId, single_username_candidate_value, + MakeSimpleSingleUsernamePredictions()); + std::u16string suggested_value = u"other_value"; + votes_uploader.set_suggested_username(suggested_value); + votes_uploader.set_saved_username(single_username_candidate_value); + +#if !defined(OS_ANDROID) + ServerFieldTypeSet expected_types = {SINGLE_USERNAME}; + EXPECT_CALL( + mock_autofill_download_manager_, + StartUploadRequest( + AllOf(SignatureIs(kSingleUsernameFormSignature), + UploadedSingleUsernameVoteTypeIs( + autofill::AutofillUploadContents::Field::EDITED_IN_PROMPT)), + /*form_was_autofilled=*/false, expected_types, + /*login_form_signature=*/"", + /*observed_submission=*/true, + /*pref_service=*/nullptr)); +#else + EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0); +#endif // !defined(OS_ANDROID) + votes_uploader.MaybeSendSingleUsernameVote(); +} + +// Verifies that NOT_USERNAME vote and EDITED_IN_PROMPT vote type are sent +// if single username candidate value was suggested, but the user has deleted +// it in prompt. +TEST_F(VotesUploaderTest, SingleUsernameValueDeletedInPrompt) { + MockFieldInfoManager mock_field_manager; + ON_CALL(mock_field_manager, GetFieldType).WillByDefault(Return(UNKNOWN_TYPE)); + ON_CALL(client_, GetFieldInfoManager) + .WillByDefault(Return(&mock_field_manager)); + + VotesUploader votes_uploader(&client_, false); + std::u16string single_username_candidate_value = u"username_candidate_value"; + votes_uploader.set_single_username_vote_data( + kSingleUsernameRendererId, single_username_candidate_value, + MakeSimpleSingleUsernamePredictions()); + votes_uploader.set_suggested_username(single_username_candidate_value); + votes_uploader.set_saved_username(u""); + +#if !defined(OS_ANDROID) + ServerFieldTypeSet expected_types = {NOT_USERNAME}; + EXPECT_CALL( + mock_autofill_download_manager_, + StartUploadRequest( + AllOf(SignatureIs(kSingleUsernameFormSignature), + UploadedSingleUsernameVoteTypeIs( + autofill::AutofillUploadContents::Field::EDITED_IN_PROMPT)), + /*form_was_autofilled=*/false, expected_types, + /*login_form_signature=*/"", + /*observed_submission=*/true, + /*pref_service=*/nullptr)); +#else + EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0); +#endif // !defined(OS_ANDROID) + votes_uploader.MaybeSendSingleUsernameVote(); +} + +// Verifies that no vote is sent if the user has deleted the username value +// suggested in prompt, and suggested value wasn't equal to single username +// candidate value. +TEST_F(VotesUploaderTest, NotSingleUsernameValueDeletedInPrompt) { + MockFieldInfoManager mock_field_manager; + ON_CALL(mock_field_manager, GetFieldType).WillByDefault(Return(UNKNOWN_TYPE)); + ON_CALL(client_, GetFieldInfoManager) + .WillByDefault(Return(&mock_field_manager)); + + VotesUploader votes_uploader(&client_, false); + std::u16string single_username_candidate_value = u"username_candidate_value"; + votes_uploader.set_single_username_vote_data( + kSingleUsernameRendererId, single_username_candidate_value, + MakeSimpleSingleUsernamePredictions()); + std::u16string other_value = u"other_value"; + votes_uploader.set_suggested_username(other_value); + votes_uploader.set_saved_username(u""); + + // Expect no upload, as th signal is not informative to us. + EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0); + votes_uploader.MaybeSendSingleUsernameVote(); } TEST_F(VotesUploaderTest, SaveSingleUsernameVote) { VotesUploader votes_uploader(&client_, false); - constexpr autofill::FieldRendererId kUsernameRendererId(101); - constexpr autofill::FieldSignature kUsernameFieldSignature(1234); - constexpr autofill::FormSignature kFormSignature(1000); - FormPredictions form_predictions; - form_predictions.form_signature = kFormSignature; - - // Add the username field. - form_predictions.fields.emplace_back(); - form_predictions.fields.back().renderer_id = kUsernameRendererId; - form_predictions.fields.back().signature = kUsernameFieldSignature; - - votes_uploader.set_single_username_vote_data(kUsernameRendererId, - form_predictions); + std::u16string single_username_candidate_value = u"username_candidate_value"; + votes_uploader.set_single_username_vote_data( + kSingleUsernameRendererId, single_username_candidate_value, + MakeSimpleSingleUsernamePredictions()); + votes_uploader.set_saved_username(single_username_candidate_value); // Init store and expect that adding field info is called. scoped_refptr<MockPasswordStore> store = new MockPasswordStore; @@ -518,9 +675,9 @@ #if defined(OS_ANDROID) EXPECT_CALL(*store, AddFieldInfoImpl).Times(0); #else - EXPECT_CALL(*store, - AddFieldInfoImpl(FieldInfoHasData( - kFormSignature, kUsernameFieldSignature, SINGLE_USERNAME))); + EXPECT_CALL(*store, AddFieldInfoImpl(FieldInfoHasData( + kSingleUsernameFormSignature, + kSingleUsernameFieldSignature, SINGLE_USERNAME))); #endif // defined(OS_ANDROID) // Init FieldInfoManager. @@ -535,28 +692,19 @@ TEST_F(VotesUploaderTest, DontUploadSingleUsernameWhenAlreadyUploaded) { VotesUploader votes_uploader(&client_, false); - constexpr autofill::FieldRendererId kUsernameRendererId(101); - constexpr autofill::FieldSignature kUsernameFieldSignature(1234); - constexpr autofill::FormSignature kFormSignature(1000); MockFieldInfoManager mock_field_manager; ON_CALL(client_, GetFieldInfoManager()) .WillByDefault(Return(&mock_field_manager)); + // Simulate that the vote has been already uploaded. - ON_CALL(mock_field_manager, - GetFieldType(kFormSignature, kUsernameFieldSignature)) + ON_CALL(mock_field_manager, GetFieldType(kSingleUsernameFormSignature, + kSingleUsernameFieldSignature)) .WillByDefault(Return(SINGLE_USERNAME)); - FormPredictions form_predictions; - form_predictions.form_signature = kFormSignature; - - // Add the username field. - form_predictions.fields.emplace_back(); - form_predictions.fields.back().renderer_id = kUsernameRendererId; - form_predictions.fields.back().signature = kUsernameFieldSignature; - - votes_uploader.set_single_username_vote_data(kUsernameRendererId, - form_predictions); + votes_uploader.set_single_username_vote_data( + kSingleUsernameRendererId, u"username_candidate_value", + MakeSimpleSingleUsernamePredictions()); // Expect no upload, since the vote has been already uploaded. EXPECT_CALL(mock_autofill_download_manager_, StartUploadRequest).Times(0);
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java index eccb842b..11af6d6 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java +++ b/components/payments/content/android/java/src/org/chromium/components/payments/PaymentRequestService.java
@@ -692,7 +692,7 @@ } if (response.methodName.equals(MethodStrings.SECURE_PAYMENT_CONFIRMATION)) { assert mInvokedPaymentApp.getInstrumentMethodNames().contains(response.methodName); - mInvokedPaymentApp.setAppSpecificResponseFields(response); + response = mInvokedPaymentApp.setAppSpecificResponseFields(response); } if (mClient != null) { mClient.onPaymentResponse(response);
diff --git a/components/pdf/renderer/pdf_accessibility_tree.cc b/components/pdf/renderer/pdf_accessibility_tree.cc index 3a196ca..e8fa4d7 100644 --- a/components/pdf/renderer/pdf_accessibility_tree.cc +++ b/components/pdf/renderer/pdf_accessibility_tree.cc
@@ -1358,7 +1358,7 @@ doc_node_->child_ids.push_back(page_node->id); AddPageContent(page_node, page_bounds, page_index, text_runs, chars, - page_objects, render_accessibility); + page_objects); if (page_index == page_count_ - 1) Finish(); @@ -1370,9 +1370,11 @@ uint32_t page_index, const std::vector<chrome_pdf::AccessibilityTextRunInfo>& text_runs, const std::vector<chrome_pdf::AccessibilityCharInfo>& chars, - const ppapi::PdfAccessibilityPageObjects& page_objects, - content::RenderAccessibility* render_accessibility) { + const ppapi::PdfAccessibilityPageObjects& page_objects) { DCHECK(page_node); + content::RenderAccessibility* render_accessibility = + GetRenderAccessibilityIfEnabled(); + DCHECK(render_accessibility); PdfAccessibilityTreeBuilder tree_builder( text_runs, chars, page_objects, page_bounds, page_index, page_node, render_accessibility, &nodes_, &node_id_to_page_char_index_,
diff --git a/components/pdf/renderer/pdf_accessibility_tree.h b/components/pdf/renderer/pdf_accessibility_tree.h index 2100b6f..d7b6a08 100644 --- a/components/pdf/renderer/pdf_accessibility_tree.h +++ b/components/pdf/renderer/pdf_accessibility_tree.h
@@ -125,8 +125,7 @@ uint32_t page_index, const std::vector<chrome_pdf::AccessibilityTextRunInfo>& text_runs, const std::vector<chrome_pdf::AccessibilityCharInfo>& chars, - const ppapi::PdfAccessibilityPageObjects& page_objects, - content::RenderAccessibility* render_accessibility); + const ppapi::PdfAccessibilityPageObjects& page_objects); // Clears the local cache of node data used to create the tree so that // replacement node data can be introduced.
diff --git a/components/policy/core/common/android/android_combined_policy_provider.h b/components/policy/core/common/android/android_combined_policy_provider.h index cc4d6c1..03d1e32b 100644 --- a/components/policy/core/common/android/android_combined_policy_provider.h +++ b/components/policy/core/common/android/android_combined_policy_provider.h
@@ -10,7 +10,6 @@ #include <memory> #include "base/android/scoped_java_ref.h" -#include "base/macros.h" #include "components/policy/core/common/configuration_policy_provider.h" #include "components/policy/core/common/policy_bundle.h" #include "components/policy/policy_export.h" @@ -27,6 +26,9 @@ : public ConfigurationPolicyProvider { public: explicit AndroidCombinedPolicyProvider(SchemaRegistry* registry); + AndroidCombinedPolicyProvider(const AndroidCombinedPolicyProvider&) = delete; + AndroidCombinedPolicyProvider& operator=( + const AndroidCombinedPolicyProvider&) = delete; ~AndroidCombinedPolicyProvider() override; @@ -55,8 +57,6 @@ bool initialized_; std::unique_ptr<policy::android::PolicyConverter> policy_converter_; base::android::ScopedJavaGlobalRef<jobject> java_combined_policy_provider_; - - DISALLOW_COPY_AND_ASSIGN(AndroidCombinedPolicyProvider); }; } // namespace android
diff --git a/components/policy/core/common/cloud/cloud_external_data_store_unittest.cc b/components/policy/core/common/cloud/cloud_external_data_store_unittest.cc index ee45e84..2fe7a5c 100644 --- a/components/policy/core/common/cloud/cloud_external_data_store_unittest.cc +++ b/components/policy/core/common/cloud/cloud_external_data_store_unittest.cc
@@ -10,7 +10,6 @@ #include "base/compiler_specific.h" #include "base/files/scoped_temp_dir.h" -#include "base/macros.h" #include "base/test/test_simple_task_runner.h" #include "components/policy/core/common/cloud/resource_cache.h" #include "crypto/sha2.h" @@ -35,6 +34,9 @@ class CloudExternalDataStoreTest : public testing::Test { public: CloudExternalDataStoreTest(); + CloudExternalDataStoreTest(const CloudExternalDataStoreTest&) = delete; + CloudExternalDataStoreTest& operator=(const CloudExternalDataStoreTest&) = + delete; void SetUp() override; @@ -45,9 +47,6 @@ scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ScopedTempDir temp_dir_; std::unique_ptr<ResourceCache> resource_cache_; - - private: - DISALLOW_COPY_AND_ASSIGN(CloudExternalDataStoreTest); }; CloudExternalDataStoreTest::CloudExternalDataStoreTest()
diff --git a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h index 9137e5e..0c7b2507 100644 --- a/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h +++ b/components/policy/core/common/cloud/cloud_policy_client_registration_helper.h
@@ -11,7 +11,6 @@ #include "base/callback.h" #include "base/compiler_specific.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "build/build_config.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" @@ -41,6 +40,10 @@ CloudPolicyClientRegistrationHelper( CloudPolicyClient* client, enterprise_management::DeviceRegisterRequest::Type registration_type); + CloudPolicyClientRegistrationHelper( + const CloudPolicyClientRegistrationHelper&) = delete; + CloudPolicyClientRegistrationHelper& operator=( + const CloudPolicyClientRegistrationHelper&) = delete; ~CloudPolicyClientRegistrationHelper() override; // Starts the client registration process. This version uses the @@ -90,8 +93,6 @@ CloudPolicyClient* client_; enterprise_management::DeviceRegisterRequest::Type registration_type_; base::OnceClosure callback_; - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyClientRegistrationHelper); }; } // namespace policy
diff --git a/components/policy/core/common/cloud/cloud_policy_validator_unittest.cc b/components/policy/core/common/cloud/cloud_policy_validator_unittest.cc index dc0c2926..e556eae 100644 --- a/components/policy/core/common/cloud/cloud_policy_validator_unittest.cc +++ b/components/policy/core/common/cloud/cloud_policy_validator_unittest.cc
@@ -11,7 +11,6 @@ #include <utility> #include "base/bind.h" -#include "base/macros.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_util.h" @@ -81,6 +80,8 @@ validate_values_(false) { policy_.SetDefaultNewSigningKey(); } + CloudPolicyValidatorTest(const CloudPolicyValidatorTest&) = delete; + CloudPolicyValidatorTest& operator=(const CloudPolicyValidatorTest&) = delete; void Validate(testing::Action<void(UserCloudPolicyValidator*)> check_action) { policy_.Build(); @@ -181,8 +182,6 @@ private: MOCK_METHOD1(ValidationCompletion, void(UserCloudPolicyValidator* validator)); - - DISALLOW_COPY_AND_ASSIGN(CloudPolicyValidatorTest); }; #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/components/policy/core/common/cloud/component_cloud_policy_service.cc b/components/policy/core/common/cloud/component_cloud_policy_service.cc index 7dba285..9f97f805 100644 --- a/components/policy/core/common/cloud/component_cloud_policy_service.cc +++ b/components/policy/core/common/cloud/component_cloud_policy_service.cc
@@ -16,7 +16,6 @@ #include "base/callback_helpers.h" #include "base/location.h" #include "base/logging.h" -#include "base/macros.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -77,6 +76,8 @@ std::unique_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher, const std::string& policy_type, PolicySource policy_source); + Backend(const Backend&) = delete; + Backend& operator=(const Backend&) = delete; ~Backend() override; @@ -130,8 +131,6 @@ std::unique_ptr<ScopedResponseMap> last_fetched_policy_; SEQUENCE_CHECKER(sequence_checker_); - - DISALLOW_COPY_AND_ASSIGN(Backend); }; ComponentCloudPolicyService::Backend::Backend(
diff --git a/components/policy/core/common/cloud/device_management_service_unittest.cc b/components/policy/core/common/cloud/device_management_service_unittest.cc index 70adb8e..0b30e9f8 100644 --- a/components/policy/core/common/cloud/device_management_service_unittest.cc +++ b/components/policy/core/common/cloud/device_management_service_unittest.cc
@@ -1065,6 +1065,12 @@ // Tests that authorization data is correctly added to the request. class DeviceManagementRequestAuthTest : public DeviceManagementServiceTestBase { + public: + DeviceManagementRequestAuthTest(const DeviceManagementRequestAuthTest&) = + delete; + DeviceManagementRequestAuthTest& operator=( + const DeviceManagementRequestAuthTest&) = delete; + protected: DeviceManagementRequestAuthTest() = default; ~DeviceManagementRequestAuthTest() override = default; @@ -1098,9 +1104,6 @@ request.request.headers.GetHeader(dm_protocol::kAuthHeader, &header); return result ? absl::optional<std::string>(header) : absl::nullopt; } - - private: - DISALLOW_COPY_AND_ASSIGN(DeviceManagementRequestAuthTest); }; TEST_F(DeviceManagementRequestAuthTest, OnlyOAuthToken) {
diff --git a/components/policy/core/common/cloud/external_policy_data_fetcher_unittest.cc b/components/policy/core/common/cloud/external_policy_data_fetcher_unittest.cc index ffb41a8..6f2fd79e 100644 --- a/components/policy/core/common/cloud/external_policy_data_fetcher_unittest.cc +++ b/components/policy/core/common/cloud/external_policy_data_fetcher_unittest.cc
@@ -10,7 +10,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/compiler_specific.h" -#include "base/macros.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/test/task_environment.h" @@ -38,6 +37,11 @@ } // namespace class ExternalPolicyDataFetcherTest : public testing::Test { + public: + ExternalPolicyDataFetcherTest(const ExternalPolicyDataFetcherTest&) = delete; + ExternalPolicyDataFetcherTest& operator=( + const ExternalPolicyDataFetcherTest&) = delete; + protected: ExternalPolicyDataFetcherTest(); ~ExternalPolicyDataFetcherTest() override; @@ -64,9 +68,6 @@ int callback_job_index_; ExternalPolicyDataFetcher::Result callback_result_; std::unique_ptr<std::string> callback_data_; - - private: - DISALLOW_COPY_AND_ASSIGN(ExternalPolicyDataFetcherTest); }; ExternalPolicyDataFetcherTest::ExternalPolicyDataFetcherTest()
diff --git a/components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h b/components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h index a00acfd5..63e59a3 100644 --- a/components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h +++ b/components/policy/core/common/cloud/machine_level_user_cloud_policy_manager.h
@@ -7,7 +7,6 @@ #include <memory> -#include "base/macros.h" #include "components/policy/core/common/cloud/cloud_policy_manager.h" #include "services/network/public/cpp/network_connection_tracker.h" @@ -29,6 +28,10 @@ const scoped_refptr<base::SequencedTaskRunner>& task_runner, network::NetworkConnectionTrackerGetter network_connection_tracker_getter); + MachineLevelUserCloudPolicyManager( + const MachineLevelUserCloudPolicyManager&) = delete; + MachineLevelUserCloudPolicyManager& operator=( + const MachineLevelUserCloudPolicyManager&) = delete; ~MachineLevelUserCloudPolicyManager() override; // Initializes the cloud connection. |local_state| must stay valid until this @@ -58,8 +61,6 @@ std::unique_ptr<CloudExternalDataManager> external_data_manager_; const base::FilePath policy_dir_; - - DISALLOW_COPY_AND_ASSIGN(MachineLevelUserCloudPolicyManager); }; } // namespace policy
diff --git a/components/policy/core/common/cloud/machine_level_user_cloud_policy_manager_unittest.cc b/components/policy/core/common/cloud/machine_level_user_cloud_policy_manager_unittest.cc index f596209..4671209 100644 --- a/components/policy/core/common/cloud/machine_level_user_cloud_policy_manager_unittest.cc +++ b/components/policy/core/common/cloud/machine_level_user_cloud_policy_manager_unittest.cc
@@ -7,7 +7,6 @@ #include <string> #include <utility> -#include "base/macros.h" #include "base/sequenced_task_runner.h" #include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/cloud/dm_token.h" @@ -37,7 +36,11 @@ class MachineLevelUserCloudPolicyManagerTest : public ::testing::Test { public: - MachineLevelUserCloudPolicyManagerTest() {} + MachineLevelUserCloudPolicyManagerTest() = default; + MachineLevelUserCloudPolicyManagerTest( + const MachineLevelUserCloudPolicyManagerTest&) = delete; + MachineLevelUserCloudPolicyManagerTest& operator=( + const MachineLevelUserCloudPolicyManagerTest&) = delete; ~MachineLevelUserCloudPolicyManagerTest() override { manager_->Shutdown(); } void SetUp() override { @@ -52,9 +55,6 @@ SchemaRegistry schema_registry_; MockMachineLevelUserCloudPolicyStore* store_ = nullptr; std::unique_ptr<MachineLevelUserCloudPolicyManager> manager_; - - private: - DISALLOW_COPY_AND_ASSIGN(MachineLevelUserCloudPolicyManagerTest); }; TEST_F(MachineLevelUserCloudPolicyManagerTest, InitManager) {
diff --git a/components/policy/core/common/cloud/machine_level_user_cloud_policy_store.h b/components/policy/core/common/cloud/machine_level_user_cloud_policy_store.h index a371c4b..aa241d2 100644 --- a/components/policy/core/common/cloud/machine_level_user_cloud_policy_store.h +++ b/components/policy/core/common/cloud/machine_level_user_cloud_policy_store.h
@@ -8,7 +8,6 @@ #include <memory> #include <string> -#include "base/macros.h" #include "base/sequenced_task_runner.h" #include "components/policy/core/common/cloud/dm_token.h" #include "components/policy/core/common/cloud/user_cloud_policy_store.h" @@ -30,6 +29,10 @@ const base::FilePath& key_path, bool cloud_policy_has_priority, scoped_refptr<base::SequencedTaskRunner> background_task_runner); + MachineLevelUserCloudPolicyStore(const MachineLevelUserCloudPolicyStore&) = + delete; + MachineLevelUserCloudPolicyStore& operator=( + const MachineLevelUserCloudPolicyStore&) = delete; ~MachineLevelUserCloudPolicyStore() override; // Creates a MachineLevelUserCloudPolicyStore instance. |external_policy_path| @@ -81,8 +84,6 @@ DMToken machine_dm_token_; std::string machine_client_id_; - - DISALLOW_COPY_AND_ASSIGN(MachineLevelUserCloudPolicyStore); }; } // namespace policy
diff --git a/components/policy/core/common/cloud/machine_level_user_cloud_policy_store_unittest.cc b/components/policy/core/common/cloud/machine_level_user_cloud_policy_store_unittest.cc index bd5f1ae..7a8163b 100644 --- a/components/policy/core/common/cloud/machine_level_user_cloud_policy_store_unittest.cc +++ b/components/policy/core/common/cloud/machine_level_user_cloud_policy_store_unittest.cc
@@ -7,7 +7,6 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/macros.h" #include "base/run_loop.h" #include "base/test/task_environment.h" #include "base/threading/thread_task_runner_handle.h" @@ -41,6 +40,10 @@ policy_.payload().mutable_searchsuggestenabled()->set_value(false); policy_.Build(); } + MachineLevelUserCloudPolicyStoreTest( + const MachineLevelUserCloudPolicyStoreTest&) = delete; + MachineLevelUserCloudPolicyStoreTest& operator=( + const MachineLevelUserCloudPolicyStoreTest&) = delete; ~MachineLevelUserCloudPolicyStoreTest() override {} @@ -111,8 +114,6 @@ private: base::test::TaskEnvironment task_environment_; - - DISALLOW_COPY_AND_ASSIGN(MachineLevelUserCloudPolicyStoreTest); }; TEST_F(MachineLevelUserCloudPolicyStoreTest, LoadWithoutDMToken) {
diff --git a/components/policy/core/common/cloud/mock_cloud_external_data_manager.h b/components/policy/core/common/cloud/mock_cloud_external_data_manager.h index 294004f..d72cae0d05 100644 --- a/components/policy/core/common/cloud/mock_cloud_external_data_manager.h +++ b/components/policy/core/common/cloud/mock_cloud_external_data_manager.h
@@ -8,7 +8,6 @@ #include <memory> #include <string> -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/external_data_fetcher.h" @@ -22,6 +21,9 @@ class MockCloudExternalDataManager : public CloudExternalDataManager { public: MockCloudExternalDataManager(); + MockCloudExternalDataManager(const MockCloudExternalDataManager&) = delete; + MockCloudExternalDataManager& operator=(const MockCloudExternalDataManager&) = + delete; ~MockCloudExternalDataManager() override; MOCK_METHOD0(OnPolicyStoreLoaded, void(void)); @@ -32,9 +34,6 @@ std::unique_ptr<ExternalDataFetcher> CreateExternalDataFetcher( const std::string& policy); - - private: - DISALLOW_COPY_AND_ASSIGN(MockCloudExternalDataManager); }; } // namespace policy
diff --git a/components/policy/core/common/cloud/realtime_reporting_job_configuration.h b/components/policy/core/common/cloud/realtime_reporting_job_configuration.h index 89fa973..770fadb 100644 --- a/components/policy/core/common/cloud/realtime_reporting_job_configuration.h +++ b/components/policy/core/common/cloud/realtime_reporting_job_configuration.h
@@ -9,7 +9,6 @@ #include <string> #include "base/callback.h" -#include "base/macros.h" #include "base/values.h" #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/cloud/reporting_job_configuration_base.h" @@ -49,6 +48,10 @@ bool include_device_info, bool add_connector_url_params, UploadCompleteCallback callback); + RealtimeReportingJobConfiguration(const RealtimeReportingJobConfiguration&) = + delete; + RealtimeReportingJobConfiguration& operator=( + const RealtimeReportingJobConfiguration&) = delete; ~RealtimeReportingJobConfiguration() override; @@ -82,8 +85,6 @@ // Gathers the ids of the uploads that failed std::set<std::string> GetFailedUploadIds( const std::string& response_body) const; - - DISALLOW_COPY_AND_ASSIGN(RealtimeReportingJobConfiguration); }; } // namespace policy
diff --git a/components/policy/core/common/cloud/reporting_job_configuration_base.h b/components/policy/core/common/cloud/reporting_job_configuration_base.h index 85b939efe..2425352d 100644 --- a/components/policy/core/common/cloud/reporting_job_configuration_base.h +++ b/components/policy/core/common/cloud/reporting_job_configuration_base.h
@@ -9,7 +9,6 @@ #include <string> #include "base/callback.h" -#include "base/macros.h" #include "base/values.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/core/common/cloud/device_management_service.h" @@ -98,6 +97,10 @@ static const char kChromeVersion[]; }; + ReportingJobConfigurationBase(const ReportingJobConfigurationBase&) = delete; + ReportingJobConfigurationBase& operator=( + const ReportingJobConfigurationBase&) = delete; + // DeviceManagementService::JobConfiguration std::string GetPayload() override; std::string GetUmaName() override; @@ -157,8 +160,6 @@ void InitializePayload(CloudPolicyClient* client, bool include_device_info); const std::string server_url_; - - DISALLOW_COPY_AND_ASSIGN(ReportingJobConfigurationBase); }; } // namespace policy
diff --git a/components/policy/core/common/cloud/user_cloud_policy_manager_unittest.cc b/components/policy/core/common/cloud/user_cloud_policy_manager_unittest.cc index fff29181..27f5cf3 100644 --- a/components/policy/core/common/cloud/user_cloud_policy_manager_unittest.cc +++ b/components/policy/core/common/cloud/user_cloud_policy_manager_unittest.cc
@@ -7,7 +7,6 @@ #include <memory> #include "base/callback.h" -#include "base/macros.h" #include "base/sequenced_task_runner.h" #include "base/test/task_environment.h" #include "components/policy/core/common/cloud/cloud_external_data_manager.h" @@ -31,6 +30,11 @@ namespace { class UserCloudPolicyManagerTest : public testing::Test { + public: + UserCloudPolicyManagerTest(const UserCloudPolicyManagerTest&) = delete; + UserCloudPolicyManagerTest& operator=(const UserCloudPolicyManagerTest&) = + delete; + protected: UserCloudPolicyManagerTest() : store_(nullptr) {} @@ -74,9 +78,6 @@ MockConfigurationPolicyObserver observer_; MockUserCloudPolicyStore* store_; // Not owned. std::unique_ptr<UserCloudPolicyManager> manager_; - - private: - DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerTest); }; TEST_F(UserCloudPolicyManagerTest, DisconnectAndRemovePolicy) {
diff --git a/components/policy/core/common/cloud/user_cloud_policy_store_unittest.cc b/components/policy/core/common/cloud/user_cloud_policy_store_unittest.cc index 0d93ef0..a504cd4e 100644 --- a/components/policy/core/common/cloud/user_cloud_policy_store_unittest.cc +++ b/components/policy/core/common/cloud/user_cloud_policy_store_unittest.cc
@@ -8,7 +8,6 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" -#include "base/macros.h" #include "base/run_loop.h" #include "base/test/task_environment.h" #include "base/threading/thread_task_runner_handle.h" @@ -59,6 +58,8 @@ UserCloudPolicyStoreTest() : task_environment_( base::test::SingleThreadTaskEnvironment::MainThreadType::UI) {} + UserCloudPolicyStoreTest(const UserCloudPolicyStoreTest&) = delete; + UserCloudPolicyStoreTest& operator=(const UserCloudPolicyStoreTest&) = delete; void SetUp() override { ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir()); @@ -140,9 +141,6 @@ base::test::SingleThreadTaskEnvironment task_environment_; base::ScopedTempDir tmp_dir_; - - private: - DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyStoreTest); }; TEST_F(UserCloudPolicyStoreTest, LoadWithNoFile) {
diff --git a/components/policy/core/common/policy_pref_names.cc b/components/policy/core/common/policy_pref_names.cc index 24eec8e..8d3f0f6c 100644 --- a/components/policy/core/common/policy_pref_names.cc +++ b/components/policy/core/common/policy_pref_names.cc
@@ -64,10 +64,6 @@ const char kIntensiveWakeUpThrottlingEnabled[] = "policy.intensive_wake_up_throttling_enabled"; -// Boolean policy preference to disable the User-Agent Client Hints feature. -const char kUserAgentClientHintsEnabled[] = - "policy.user_agent_client_hints_enabled"; - // Boolean that controls whether a window spawned from an anchor targeting // _blank receives an opener. TODO(crbug.com/898942): Remove this in Chrome 95. const char kTargetBlankImpliesNoOpener[] =
diff --git a/components/policy/core/common/policy_pref_names.h b/components/policy/core/common/policy_pref_names.h index b4d6171..b245565 100644 --- a/components/policy/core/common/policy_pref_names.h +++ b/components/policy/core/common/policy_pref_names.h
@@ -25,7 +25,6 @@ POLICY_EXPORT extern const char kUrlAllowlist[]; POLICY_EXPORT extern const char kUserPolicyRefreshRate[]; POLICY_EXPORT extern const char kIntensiveWakeUpThrottlingEnabled[]; -POLICY_EXPORT extern const char kUserAgentClientHintsEnabled[]; POLICY_EXPORT extern const char kTargetBlankImpliesNoOpener[]; #if defined(OS_ANDROID) POLICY_EXPORT extern const char kBackForwardCacheEnabled[];
diff --git a/components/policy/core/common/remote_commands/remote_commands_queue_unittest.cc b/components/policy/core/common/remote_commands/remote_commands_queue_unittest.cc index 8d017801..e1a3002 100644 --- a/components/policy/core/common/remote_commands/remote_commands_queue_unittest.cc +++ b/components/policy/core/common/remote_commands/remote_commands_queue_unittest.cc
@@ -8,7 +8,6 @@ #include <string> #include <utility> -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/test/test_mock_time_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -48,14 +47,15 @@ // Mock class for RemoteCommandsQueue::Observer. class MockRemoteCommandsQueueObserver : public RemoteCommandsQueue::Observer { public: - MockRemoteCommandsQueueObserver() {} + MockRemoteCommandsQueueObserver() = default; + MockRemoteCommandsQueueObserver(const MockRemoteCommandsQueueObserver&) = + delete; + MockRemoteCommandsQueueObserver& operator=( + const MockRemoteCommandsQueueObserver&) = delete; // RemoteCommandsQueue::Observer: MOCK_METHOD1(OnJobStarted, void(RemoteCommandJob* command)); MOCK_METHOD1(OnJobFinished, void(RemoteCommandJob* command)); - - private: - DISALLOW_COPY_AND_ASSIGN(MockRemoteCommandsQueueObserver); }; } // namespace @@ -68,6 +68,10 @@ using ::testing::StrictMock; class RemoteCommandsQueueTest : public testing::Test { + public: + RemoteCommandsQueueTest(const RemoteCommandsQueueTest&) = delete; + RemoteCommandsQueueTest& operator=(const RemoteCommandsQueueTest&) = delete; + protected: RemoteCommandsQueueTest(); @@ -99,8 +103,6 @@ base::TimeTicks expected_issued_time); base::ThreadTaskRunnerHandle runner_handle_; - - DISALLOW_COPY_AND_ASSIGN(RemoteCommandsQueueTest); }; RemoteCommandsQueueTest::RemoteCommandsQueueTest()
diff --git a/components/policy/core/common/remote_commands/remote_commands_service.h b/components/policy/core/common/remote_commands/remote_commands_service.h index d88886d..7829347 100644 --- a/components/policy/core/common/remote_commands/remote_commands_service.h +++ b/components/policy/core/common/remote_commands/remote_commands_service.h
@@ -11,7 +11,6 @@ #include "base/callback_forward.h" #include "base/containers/circular_deque.h" -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/core/common/cloud/policy_invalidation_scope.h" @@ -84,6 +83,8 @@ CloudPolicyClient* client, CloudPolicyStore* store, PolicyInvalidationScope scope); + RemoteCommandsService(const RemoteCommandsService&) = delete; + RemoteCommandsService& operator=(const RemoteCommandsService&) = delete; ~RemoteCommandsService() override; // Attempts to fetch remote commands, mainly supposed to be called by @@ -174,8 +175,6 @@ const PolicyInvalidationScope scope_; base::WeakPtrFactory<RemoteCommandsService> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(RemoteCommandsService); }; } // namespace policy
diff --git a/components/policy/core/common/remote_commands/remote_commands_service_unittest.cc b/components/policy/core/common/remote_commands/remote_commands_service_unittest.cc index 5ecab2e1..0f93298 100644 --- a/components/policy/core/common/remote_commands/remote_commands_service_unittest.cc +++ b/components/policy/core/common/remote_commands/remote_commands_service_unittest.cc
@@ -12,7 +12,6 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/containers/queue.h" -#include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/metrics/histogram_tester.h" @@ -70,6 +69,9 @@ true, base::TimeDelta::FromSeconds(kTestCommandExecutionTimeInSeconds))); } + MockTestRemoteCommandFactory(const MockTestRemoteCommandFactory&) = delete; + MockTestRemoteCommandFactory& operator=(const MockTestRemoteCommandFactory&) = + delete; MOCK_METHOD0(BuildTestCommand, TestRemoteCommandJob*()); @@ -84,8 +86,6 @@ } return base::WrapUnique<RemoteCommandJob>(BuildTestCommand()); } - - DISALLOW_COPY_AND_ASSIGN(MockTestRemoteCommandFactory); }; // Expectations for a single FetchRemoteCommands() call. @@ -126,6 +126,10 @@ server_(server) { dm_token_ = kDMToken; } + TestingCloudPolicyClientForRemoteCommands( + const TestingCloudPolicyClientForRemoteCommands&) = delete; + TestingCloudPolicyClientForRemoteCommands& operator=( + const TestingCloudPolicyClientForRemoteCommands&) = delete; ~TestingCloudPolicyClientForRemoteCommands() override { EXPECT_TRUE(expected_fetch_commands_calls_.empty()); @@ -193,13 +197,16 @@ base::queue<FetchCallExpectation> expected_fetch_commands_calls_; TestingRemoteCommandsServer* server_; - - DISALLOW_COPY_AND_ASSIGN(TestingCloudPolicyClientForRemoteCommands); }; // Base class for unit tests regarding remote commands service. class RemoteCommandsServiceTest : public testing::TestWithParam<PolicyInvalidationScope> { + public: + RemoteCommandsServiceTest(const RemoteCommandsServiceTest&) = delete; + RemoteCommandsServiceTest& operator=(const RemoteCommandsServiceTest&) = + delete; + protected: RemoteCommandsServiceTest() : server_(std::make_unique<TestingRemoteCommandsServer>()) { @@ -230,9 +237,6 @@ cloud_policy_client_; MockCloudPolicyStore store_; std::unique_ptr<RemoteCommandsService> remote_commands_service_; - - private: - DISALLOW_COPY_AND_ASSIGN(RemoteCommandsServiceTest); }; // Tests that no command will be fetched if no commands is issued. @@ -400,6 +404,8 @@ class EnsureCalled { public: EnsureCalled() = default; + EnsureCalled(const EnsureCalled&) = delete; + EnsureCalled& operator=(const EnsureCalled&) = delete; ~EnsureCalled() { CHECK(called_times_ == 1); } void Bind(ResultReportedCallback callback) { @@ -414,11 +420,15 @@ private: int called_times_ = 0; ResultReportedCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(EnsureCalled); }; class SignedRemoteCommandsServiceTest : public RemoteCommandsServiceTest { + public: + SignedRemoteCommandsServiceTest(const SignedRemoteCommandsServiceTest&) = + delete; + SignedRemoteCommandsServiceTest& operator=( + const SignedRemoteCommandsServiceTest&) = delete; + protected: SignedRemoteCommandsServiceTest() { StartService(std::make_unique<MockTestRemoteCommandFactory>()); @@ -446,9 +456,6 @@ } EnsureCalled ensure_called_; - - private: - DISALLOW_COPY_AND_ASSIGN(SignedRemoteCommandsServiceTest); }; // Tests that signed remote commands work.
diff --git a/components/policy/core/common/remote_commands/test_remote_command_job.cc b/components/policy/core/common/remote_commands/test_remote_command_job.cc index 11f908a5..3ce235e5 100644 --- a/components/policy/core/common/remote_commands/test_remote_command_job.cc +++ b/components/policy/core/common/remote_commands/test_remote_command_job.cc
@@ -11,7 +11,6 @@ #include "base/callback_helpers.h" #include "base/check_op.h" #include "base/location.h" -#include "base/macros.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" @@ -28,14 +27,14 @@ : public RemoteCommandJob::ResultPayload { public: explicit EchoPayload(const std::string& payload) : payload_(payload) {} + EchoPayload(const EchoPayload&) = delete; + EchoPayload& operator=(const EchoPayload&) = delete; // RemoteCommandJob::ResultPayload: std::unique_ptr<std::string> Serialize() override; private: const std::string payload_; - - DISALLOW_COPY_AND_ASSIGN(EchoPayload); }; std::unique_ptr<std::string> TestRemoteCommandJob::EchoPayload::Serialize() {
diff --git a/components/policy/core/common/remote_commands/test_remote_command_job.h b/components/policy/core/common/remote_commands/test_remote_command_job.h index ed4ed0e..fa15b26 100644 --- a/components/policy/core/common/remote_commands/test_remote_command_job.h +++ b/components/policy/core/common/remote_commands/test_remote_command_job.h
@@ -7,7 +7,6 @@ #include <string> -#include "base/macros.h" #include "base/time/time.h" #include "components/policy/core/common/remote_commands/remote_command_job.h" #include "components/policy/proto/device_management_backend.pb.h" @@ -17,6 +16,8 @@ class TestRemoteCommandJob : public RemoteCommandJob { public: TestRemoteCommandJob(bool succeed, base::TimeDelta execution_duration); + TestRemoteCommandJob(const TestRemoteCommandJob&) = delete; + TestRemoteCommandJob& operator=(const TestRemoteCommandJob&) = delete; // RemoteCommandJob: enterprise_management::RemoteCommand_Type GetType() const override; @@ -36,8 +37,6 @@ const bool succeed_; const base::TimeDelta execution_duration_; - - DISALLOW_COPY_AND_ASSIGN(TestRemoteCommandJob); }; } // namespace policy
diff --git a/components/policy/core/common/remote_commands/testing_remote_commands_server.h b/components/policy/core/common/remote_commands/testing_remote_commands_server.h index 1c73e27..5eb30a1 100644 --- a/components/policy/core/common/remote_commands/testing_remote_commands_server.h +++ b/components/policy/core/common/remote_commands/testing_remote_commands_server.h
@@ -12,7 +12,6 @@ #include <vector> #include "base/callback_forward.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/synchronization/lock.h" @@ -48,6 +47,9 @@ class TestingRemoteCommandsServer { public: TestingRemoteCommandsServer(); + TestingRemoteCommandsServer(const TestingRemoteCommandsServer&) = delete; + TestingRemoteCommandsServer& operator=(const TestingRemoteCommandsServer&) = + delete; virtual ~TestingRemoteCommandsServer(); using RemoteCommandResults = @@ -137,8 +139,6 @@ base::ThreadChecker thread_checker_; base::WeakPtrFactory<TestingRemoteCommandsServer> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(TestingRemoteCommandsServer); }; } // namespace policy
diff --git a/components/policy/core/common/schema_registry_tracking_policy_provider.h b/components/policy/core/common/schema_registry_tracking_policy_provider.h index 592be9d..9f605d3 100644 --- a/components/policy/core/common/schema_registry_tracking_policy_provider.h +++ b/components/policy/core/common/schema_registry_tracking_policy_provider.h
@@ -6,7 +6,6 @@ #define COMPONENTS_POLICY_CORE_COMMON_SCHEMA_REGISTRY_TRACKING_POLICY_PROVIDER_H_ #include "base/compiler_specific.h" -#include "base/macros.h" #include "components/policy/core/common/configuration_policy_provider.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/policy_export.h" @@ -46,6 +45,10 @@ // The |delegate| must outlive this provider. explicit SchemaRegistryTrackingPolicyProvider( ConfigurationPolicyProvider* delegate); + SchemaRegistryTrackingPolicyProvider( + const SchemaRegistryTrackingPolicyProvider&) = delete; + SchemaRegistryTrackingPolicyProvider& operator=( + const SchemaRegistryTrackingPolicyProvider&) = delete; ~SchemaRegistryTrackingPolicyProvider() override; // ConfigurationPolicyProvider: @@ -84,8 +87,6 @@ ConfigurationPolicyProvider* delegate_; InitializationState state_; - - DISALLOW_COPY_AND_ASSIGN(SchemaRegistryTrackingPolicyProvider); }; } // namespace policy
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 1a9096e0..a711b186 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -7242,7 +7242,7 @@ 'tags': ['system-security'], 'desc': '''Controls whether insecure websites are allowed to make requests to more-private network endpoints. - This policy relates to the CORS-RFC1918 specification. See https://wicg.github.io/cors-rfc1918 for more details. + This policy relates to the Private Network Access specification. See https://wicg.github.io/private-network-access/ for more details. A network endpoint is more private than another if: 1) Its IP address is localhost and the other is not. @@ -9103,7 +9103,7 @@ 'features': { 'can_be_recommended': True, 'dynamic_refresh': True, - 'per_profile': False, + 'per_profile': True, }, 'example_value': False, 'id': 480, @@ -20954,7 +20954,7 @@ 'per_profile': True, }, 'default': 0, - 'supported_on': ['chrome.*:93-'], + 'future_on': ['chrome.*'], 'caption': '''Sitelist parsing mode''', 'tags': [], 'desc': '''This policy controls how <ph name="PRODUCT_NAME">Google Chrome</ph> interprets sitelist/greylist policies for the Legacy Browser Support feature. It affects the following policies: <ph name="URL_LIST_POLICY_NAME">BrowserSwitcherUrlList</ph>, <ph name="URL_GREYLIST_POLICY_NAME">BrowserSwitcherUrlGreylist</ph>, <ph name="USE_IE_SITELIST_POLICY_NAME">BrowserSwitcherUseIeSitelist</ph>, <ph name="EXTERNAL_SITELIST_POLICY_NAME">BrowserSwitcherExternalSitelistUrl</ph>, and <ph name="EXTERNAL_GREYLIST_POLICY_NAME">BrowserSwitcherExternalGreylistUrl</ph>. @@ -24643,7 +24643,7 @@ 'owners': ['file://components/client_hints/OWNERS', 'yoavweiss@google.com', 'aarontag@chromium.org'], 'type': 'main', 'schema': { 'type': 'boolean' }, - 'supported_on': ['chrome_os:84-', 'chrome.*:84-', 'android:84-'], + 'supported_on': ['chrome_os:84-93', 'chrome.*:84-93', 'android:84-93'], 'features': { 'per_profile': False, 'dynamic_refresh': True, @@ -24654,13 +24654,11 @@ 'id': 725, 'caption': '''Control the <ph name="PRODUCT_NAME">User-Agent Client Hints</ph> feature.''', 'tags': [], - 'desc': '''When enabled the <ph name="PRODUCT_NAME">User-Agent Client Hints</ph> feature sends granular request headers providing information about the user browser and environment. + 'desc': '''Note that this policy was removed in M94. This policy was intended for short-term adaptation purposes only. + When enabled the <ph name="PRODUCT_NAME">User-Agent Client Hints</ph> feature sends granular request headers providing information about the user browser and environment. This is an additive feature, but the new headers may break some websites that restrict the characters that requests may contain. - - If this policy is enabled or not set the <ph name="PRODUCT_NAME">User-Agent Client Hints</ph> feature is enabled. If the policy is disabled the feature is unavailable. - - This enterprise policy is for short-term adaptation purposes and will be removed in Chrome 94.''', + If this policy is enabled or not set the <ph name="PRODUCT_NAME">User-Agent Client Hints</ph> feature is enabled. If the policy is disabled the feature is unavailable.''', }, { 'name': 'SuggestedContentEnabled',
diff --git a/components/policy/test_support/BUILD.gn b/components/policy/test_support/BUILD.gn index 5e3b9501..2fd51c7 100644 --- a/components/policy/test_support/BUILD.gn +++ b/components/policy/test_support/BUILD.gn
@@ -25,6 +25,8 @@ "request_handler_for_policy.h", "request_handler_for_register_browser.cc", "request_handler_for_register_browser.h", + "request_handler_for_register_device_and_user.cc", + "request_handler_for_register_device_and_user.h", "signature_provider.cc", "signature_provider.h", "test_server_helpers.cc", @@ -61,6 +63,7 @@ "request_handler_for_chrome_desktop_report_unittest.cc", "request_handler_for_policy_unittest.cc", "request_handler_for_register_browser_unittest.cc", + "request_handler_for_register_device_and_user_unittest.cc", "signature_provider_unittest.cc", ]
diff --git a/components/policy/test_support/client_storage.h b/components/policy/test_support/client_storage.h index 082c3fab..ded5076 100644 --- a/components/policy/test_support/client_storage.h +++ b/components/policy/test_support/client_storage.h
@@ -26,6 +26,7 @@ std::string device_id; std::string device_token; std::string machine_name; + std::string username; std::vector<std::string> state_keys; std::set<std::string> allowed_policy_types; };
diff --git a/components/policy/test_support/embedded_policy_test_server.cc b/components/policy/test_support/embedded_policy_test_server.cc index 42efff8..dc10123 100644 --- a/components/policy/test_support/embedded_policy_test_server.cc +++ b/components/policy/test_support/embedded_policy_test_server.cc
@@ -15,17 +15,40 @@ #include "components/policy/test_support/request_handler_for_chrome_desktop_report.h" #include "components/policy/test_support/request_handler_for_policy.h" #include "components/policy/test_support/request_handler_for_register_browser.h" +#include "components/policy/test_support/request_handler_for_register_device_and_user.h" #include "components/policy/test_support/test_server_helpers.h" #include "net/http/http_status_code.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" +using ::net::test_server::BasicHttpResponse; using ::net::test_server::EmbeddedTestServer; using ::net::test_server::HttpRequest; using ::net::test_server::HttpResponse; namespace policy { +namespace { + +std::unique_ptr<HttpResponse> LogStatusAndReturn( + GURL url, + std::unique_ptr<HttpResponse> response) { + if (!response) + return nullptr; + + BasicHttpResponse* basic_response = + static_cast<BasicHttpResponse*>(response.get()); + if (basic_response->code() == net::HTTP_OK) { + DLOG(INFO) << "Request succeeded: " << url; + } else { + DLOG(INFO) << "Request failed with error code " << basic_response->code() + << " (" << basic_response->content() << "): " << url; + } + return response; +} + +} // namespace + const char kFakeDeviceToken[] = "fake_device_management_token"; const char kInvalidEnrollmentToken[] = "invalid_enrollment_token"; @@ -37,22 +60,18 @@ EmbeddedPolicyTestServer::RequestHandler::~RequestHandler() = default; EmbeddedPolicyTestServer::EmbeddedPolicyTestServer() - : EmbeddedPolicyTestServer(std::make_unique<ClientStorage>(), - std::make_unique<PolicyStorage>()) {} - -EmbeddedPolicyTestServer::EmbeddedPolicyTestServer( - std::unique_ptr<ClientStorage> client_storage, - std::unique_ptr<PolicyStorage> policy_storage) : http_server_(EmbeddedTestServer::TYPE_HTTP), - client_storage_(std::move(client_storage)), - policy_storage_(std::move(policy_storage)) { - RegisterHandler(std::make_unique<RequestHandlerForRegisterBrowser>( + client_storage_(std::make_unique<ClientStorage>()), + policy_storage_(std::make_unique<PolicyStorage>()) { + RegisterHandler(std::make_unique<RequestHandlerForApiAuthorization>( client_storage_.get(), policy_storage_.get())); RegisterHandler(std::make_unique<RequestHandlerForChromeDesktopReport>( client_storage_.get(), policy_storage_.get())); RegisterHandler(std::make_unique<RequestHandlerForPolicy>( client_storage_.get(), policy_storage_.get())); - RegisterHandler(std::make_unique<RequestHandlerForApiAuthorization>( + RegisterHandler(std::make_unique<RequestHandlerForRegisterBrowser>( + client_storage_.get(), policy_storage_.get())); + RegisterHandler(std::make_unique<RequestHandlerForRegisterDeviceAndUser>( client_storage_.get(), policy_storage_.get())); http_server_.RegisterDefaultHandler(base::BindRepeating( @@ -78,21 +97,23 @@ std::unique_ptr<HttpResponse> EmbeddedPolicyTestServer::HandleRequest( const HttpRequest& request) { GURL url = request.GetURL(); + DLOG(INFO) << "Request URL: " << url; std::string request_type = KeyValueFromUrl(url, dm_protocol::kParamRequest); auto it = request_handlers_.find(request_type); if (it == request_handlers_.end()) { - DVLOG(1) << "No request handler for: " << url; + LOG(ERROR) << "No request handler for: " << url; return nullptr; } if (!MeetsServerSideRequirements(url)) { - return CreateHttpResponse( - net::HTTP_BAD_REQUEST, - "URL must define device type, app type, and device id."); + return LogStatusAndReturn( + url, CreateHttpResponse( + net::HTTP_BAD_REQUEST, + "URL must define device type, app type, and device id.")); } - return it->second->HandleRequest(request); + return LogStatusAndReturn(url, it->second->HandleRequest(request)); } } // namespace policy
diff --git a/components/policy/test_support/embedded_policy_test_server.h b/components/policy/test_support/embedded_policy_test_server.h index 1c03beb4..e5865031 100644 --- a/components/policy/test_support/embedded_policy_test_server.h +++ b/components/policy/test_support/embedded_policy_test_server.h
@@ -60,8 +60,6 @@ }; EmbeddedPolicyTestServer(); - EmbeddedPolicyTestServer(std::unique_ptr<ClientStorage> client_storage, - std::unique_ptr<PolicyStorage> policy_storage); EmbeddedPolicyTestServer(const EmbeddedPolicyTestServer&) = delete; EmbeddedPolicyTestServer& operator=(const EmbeddedPolicyTestServer&) = delete; virtual ~EmbeddedPolicyTestServer();
diff --git a/components/policy/test_support/embedded_policy_test_server_test_base.cc b/components/policy/test_support/embedded_policy_test_server_test_base.cc index 597768e9..a78a1a2 100644 --- a/components/policy/test_support/embedded_policy_test_server_test_base.cc +++ b/components/policy/test_support/embedded_policy_test_server_test_base.cc
@@ -88,6 +88,17 @@ std::string(dm_protocol::kDMTokenAuthHeaderPrefix).append(device_token)); } +void EmbeddedPolicyTestServerTestBase::SetGoogleLoginTokenHeader( + const std::string& user_email) { + CHECK(resource_request_); + CHECK(!user_email.empty()); + + resource_request_->headers.SetHeader( + dm_protocol::kAuthHeader, + std::string(dm_protocol::kServiceTokenAuthHeaderPrefix) + .append(user_email)); +} + void EmbeddedPolicyTestServerTestBase::SetPayload( const enterprise_management::DeviceManagementRequest& device_management_request) {
diff --git a/components/policy/test_support/embedded_policy_test_server_test_base.h b/components/policy/test_support/embedded_policy_test_server_test_base.h index e321c8ca..43aff03 100644 --- a/components/policy/test_support/embedded_policy_test_server_test_base.h +++ b/components/policy/test_support/embedded_policy_test_server_test_base.h
@@ -44,6 +44,7 @@ void SetRequestTypeParam(const std::string& request_type); void SetEnrollmentTokenHeader(const std::string& enrollment_token); void SetDeviceTokenHeader(const std::string& device_token); + void SetGoogleLoginTokenHeader(const std::string& user_email); void SetPayload(const enterprise_management::DeviceManagementRequest& device_management_request);
diff --git a/components/policy/test_support/policy_storage.h b/components/policy/test_support/policy_storage.h index c370291..e2fc4c5b 100644 --- a/components/policy/test_support/policy_storage.h +++ b/components/policy/test_support/policy_storage.h
@@ -6,6 +6,7 @@ #define COMPONENTS_POLICY_TEST_SUPPORT_POLICY_STORAGE_H_ #include <map> +#include <set> #include <string> namespace policy { @@ -39,6 +40,16 @@ service_account_identity_ = service_account_identity; } + const std::set<std::string>& managed_users() const { return managed_users_; } + void add_managed_user(const std::string& managed_user) { + managed_users_.insert(managed_user); + } + + const std::string& policy_user() const { return policy_user_; } + void set_policy_user(const std::string& policy_user) { + policy_user_ = policy_user; + } + private: // Maps policy types to a serialized proto representing the policies to be // applied for the type (e.g. CloudPolicySettings, @@ -48,6 +59,10 @@ std::string robot_api_auth_code_; std::string service_account_identity_; + + std::set<std::string> managed_users_; + + std::string policy_user_; }; } // namespace policy
diff --git a/components/policy/test_support/request_handler_for_register_device_and_user.cc b/components/policy/test_support/request_handler_for_register_device_and_user.cc new file mode 100644 index 0000000..65e3142 --- /dev/null +++ b/components/policy/test_support/request_handler_for_register_device_and_user.cc
@@ -0,0 +1,127 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/policy/test_support/request_handler_for_register_device_and_user.h" + +#include <set> +#include <string> + +#include "base/guid.h" +#include "base/notreached.h" +#include "base/strings/stringprintf.h" +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/proto/device_management_backend.pb.h" +#include "components/policy/test_support/client_storage.h" +#include "components/policy/test_support/policy_storage.h" +#include "components/policy/test_support/test_server_helpers.h" +#include "net/http/http_status_code.h" +#include "net/test/embedded_test_server/http_request.h" +#include "net/test/embedded_test_server/http_response.h" + +using net::test_server::HttpRequest; +using net::test_server::HttpResponse; + +namespace em = enterprise_management; + +namespace policy { + +namespace { + +void AddAllowedPolicyTypes(em::DeviceRegisterRequest::Type type, + std::set<std::string>* allowed_policy_types) { + switch (type) { + case em::DeviceRegisterRequest::USER: + allowed_policy_types->insert({dm_protocol::kChromeUserPolicyType, + dm_protocol::kChromeExtensionPolicyType}); + break; + case em::DeviceRegisterRequest::DEVICE: + allowed_policy_types->insert( + {dm_protocol::kChromeDevicePolicyType, + dm_protocol::kChromePublicAccountPolicyType, + dm_protocol::kChromeExtensionPolicyType, + dm_protocol::kChromeSigninExtensionPolicyType}); + break; + case em::DeviceRegisterRequest::BROWSER: + allowed_policy_types->insert({dm_protocol::kChromeUserPolicyType, + dm_protocol::kChromeExtensionPolicyType}); + break; + case em::DeviceRegisterRequest::ANDROID_BROWSER: + allowed_policy_types->insert({dm_protocol::kChromeUserPolicyType}); + break; + default: + NOTREACHED(); + } +} + +} // namespace + +RequestHandlerForRegisterDeviceAndUser::RequestHandlerForRegisterDeviceAndUser( + ClientStorage* client_storage, + PolicyStorage* policy_storage) + : EmbeddedPolicyTestServer::RequestHandler(client_storage, policy_storage) { +} + +RequestHandlerForRegisterDeviceAndUser:: + ~RequestHandlerForRegisterDeviceAndUser() = default; + +std::string RequestHandlerForRegisterDeviceAndUser::RequestType() { + return dm_protocol::kValueRequestRegister; +} + +std::unique_ptr<HttpResponse> +RequestHandlerForRegisterDeviceAndUser::HandleRequest( + const HttpRequest& request) { + // Only checks the the oauth token is set, but doesn't use it yet. User will + // be obtained from the policy storage. + // TODO(http://crbug.com/1227123): Add support for authentication. + std::string google_login; + if (!GetGoogleLoginFromRequest(request, &google_login)) + return CreateHttpResponse(net::HTTP_UNAUTHORIZED, "User not authorized."); + + const std::set<std::string>& managed_users = + policy_storage()->managed_users(); + if (managed_users.empty()) { + return CreateHttpResponse(net::HTTP_INTERNAL_SERVER_ERROR, + "No managed users."); + } + + const std::string& policy_user = policy_storage()->policy_user(); + if (managed_users.find("*") == managed_users.end() && + managed_users.find(policy_user) == managed_users.end()) { + return CreateHttpResponse(net::HTTP_FORBIDDEN, "Unmanaged."); + } + + em::DeviceManagementRequest device_management_request; + device_management_request.ParseFromString(request.content); + const em::DeviceRegisterRequest& register_request = + device_management_request.register_request(); + + std::string device_id = + KeyValueFromUrl(request.GetURL(), dm_protocol::kParamDeviceID); + std::string device_token = base::GUID::GenerateRandomV4().AsLowercaseString(); + std::string machine_name = base::StringPrintf( + "%s - %s", register_request.machine_model().c_str(), device_id.c_str()); + + ClientStorage::ClientInfo client_info; + client_info.device_id = device_id; + client_info.device_token = device_token; + client_info.machine_name = machine_name; + client_info.username = policy_user; + AddAllowedPolicyTypes(register_request.type(), + &client_info.allowed_policy_types); + client_storage()->RegisterClient(std::move(client_info)); + + em::DeviceManagementResponse device_management_response; + em::DeviceRegisterResponse* register_response = + device_management_response.mutable_register_response(); + register_response->set_device_management_token(device_token); + register_response->set_machine_name(machine_name); + register_response->set_enrollment_type( + em::DeviceRegisterResponse::ENTERPRISE); + + return CreateHttpResponse(net::HTTP_OK, + device_management_response.SerializeAsString()); +} + +} // namespace policy
diff --git a/components/policy/test_support/request_handler_for_register_device_and_user.h b/components/policy/test_support/request_handler_for_register_device_and_user.h new file mode 100644 index 0000000..f7c59b7f --- /dev/null +++ b/components/policy/test_support/request_handler_for_register_device_and_user.h
@@ -0,0 +1,33 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_POLICY_TEST_SUPPORT_REQUEST_HANDLER_FOR_REGISTER_DEVICE_AND_USER_H_ +#define COMPONENTS_POLICY_TEST_SUPPORT_REQUEST_HANDLER_FOR_REGISTER_DEVICE_AND_USER_H_ + +#include "components/policy/test_support/embedded_policy_test_server.h" + +namespace policy { + +// Handler for request type `register` (registration of devices and managed +// users). +class RequestHandlerForRegisterDeviceAndUser + : public EmbeddedPolicyTestServer::RequestHandler { + public: + RequestHandlerForRegisterDeviceAndUser(ClientStorage* client_storage, + PolicyStorage* policy_storage); + RequestHandlerForRegisterDeviceAndUser( + RequestHandlerForRegisterDeviceAndUser&& handler) = delete; + RequestHandlerForRegisterDeviceAndUser& operator=( + RequestHandlerForRegisterDeviceAndUser&& handler) = delete; + ~RequestHandlerForRegisterDeviceAndUser() override; + + // EmbeddedPolicyTestServer::RequestHandler: + std::string RequestType() override; + std::unique_ptr<net::test_server::HttpResponse> HandleRequest( + const net::test_server::HttpRequest& request) override; +}; + +} // namespace policy + +#endif // COMPONENTS_POLICY_TEST_SUPPORT_REQUEST_HANDLER_FOR_REGISTER_DEVICE_AND_USER_H_
diff --git a/components/policy/test_support/request_handler_for_register_device_and_user_unittest.cc b/components/policy/test_support/request_handler_for_register_device_and_user_unittest.cc new file mode 100644 index 0000000..461ca69 --- /dev/null +++ b/components/policy/test_support/request_handler_for_register_device_and_user_unittest.cc
@@ -0,0 +1,116 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/policy/test_support/request_handler_for_register_browser.h" + +#include "components/policy/core/common/cloud/cloud_policy_constants.h" +#include "components/policy/test_support/client_storage.h" +#include "components/policy/test_support/embedded_policy_test_server_test_base.h" +#include "components/policy/test_support/policy_storage.h" +#include "net/http/http_status_code.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace em = enterprise_management; + +namespace policy { + +namespace { + +constexpr char kDeviceId[] = "fake_device_id"; +constexpr char kAllowedUserEmail[] = "user@example.com"; +constexpr char kDisallowedUserEmail[] = "invalid-user@example.com"; +constexpr char kAllowedUserOAuthToken[] = "oauth-token-for-user"; +constexpr char kDisallowedUserOAuthToken[] = "oauth-token-for-invalid-user"; +constexpr char kMachineModel[] = "iPhone 10"; + +} // namespace + +class RequestHandlerForRegisterDeviceAndUserTest + : public EmbeddedPolicyTestServerTestBase { + protected: + RequestHandlerForRegisterDeviceAndUserTest() = default; + ~RequestHandlerForRegisterDeviceAndUserTest() override = default; + + void SetUp() override { + EmbeddedPolicyTestServerTestBase::SetUp(); + + SetRequestTypeParam(dm_protocol::kValueRequestRegister); + SetAppType(dm_protocol::kValueAppType); + SetDeviceIdParam(kDeviceId); + SetDeviceType(dm_protocol::kValueDeviceType); + } +}; + +TEST_F(RequestHandlerForRegisterDeviceAndUserTest, + HandleRequest_NoEnrollmentToken) { + StartRequestAndWait(); + + EXPECT_EQ(GetResponseCode(), net::HTTP_UNAUTHORIZED); + + EXPECT_EQ(client_storage()->GetNumberOfRegisteredClients(), 0u); +} + +TEST_F(RequestHandlerForRegisterDeviceAndUserTest, + HandleRequest_NoManagedUsers) { + SetGoogleLoginTokenHeader(kAllowedUserOAuthToken); + + StartRequestAndWait(); + + EXPECT_EQ(GetResponseCode(), net::HTTP_INTERNAL_SERVER_ERROR); + + EXPECT_EQ(client_storage()->GetNumberOfRegisteredClients(), 0u); +} + +TEST_F(RequestHandlerForRegisterDeviceAndUserTest, + HandleRequest_UserNotAllowed) { + policy_storage()->add_managed_user(kAllowedUserEmail); + SetGoogleLoginTokenHeader(kDisallowedUserOAuthToken); + policy_storage()->set_policy_user(kDisallowedUserEmail); + + StartRequestAndWait(); + + EXPECT_EQ(GetResponseCode(), net::HTTP_FORBIDDEN); + + EXPECT_EQ(client_storage()->GetNumberOfRegisteredClients(), 0u); +} + +TEST_F(RequestHandlerForRegisterDeviceAndUserTest, HandleRequest_Success) { + policy_storage()->add_managed_user(kAllowedUserEmail); + SetGoogleLoginTokenHeader(kAllowedUserOAuthToken); + policy_storage()->set_policy_user(kAllowedUserEmail); + + em::DeviceManagementRequest device_management_request; + em::DeviceRegisterRequest* register_request = + device_management_request.mutable_register_request(); + register_request->set_machine_model(kMachineModel); + register_request->set_type(em::DeviceRegisterRequest::USER); + SetPayload(device_management_request); + + StartRequestAndWait(); + + EXPECT_EQ(GetResponseCode(), net::HTTP_OK); + + ASSERT_TRUE(HasResponseBody()); + em::DeviceManagementResponse device_management_response = + GetDeviceManagementResponse(); + const em::DeviceRegisterResponse& register_response = + device_management_response.register_response(); + EXPECT_FALSE(register_response.device_management_token().empty()); + EXPECT_FALSE(register_response.machine_name().empty()); + EXPECT_EQ(register_response.enrollment_type(), + em::DeviceRegisterResponse::ENTERPRISE); + + ASSERT_EQ(client_storage()->GetNumberOfRegisteredClients(), 1u); + const ClientStorage::ClientInfo* client_info = + client_storage()->GetClientOrNull(kDeviceId); + ASSERT_NE(client_info, nullptr); + EXPECT_EQ(client_info->device_id, kDeviceId); + EXPECT_EQ(client_info->device_token, + register_response.device_management_token()); + EXPECT_EQ(client_info->machine_name, register_response.machine_name()); + EXPECT_EQ(client_info->username, kAllowedUserEmail); + EXPECT_FALSE(client_info->allowed_policy_types.empty()); +} + +} // namespace policy
diff --git a/components/policy/test_support/signature_provider.h b/components/policy/test_support/signature_provider.h index 7579b34..4d595db 100644 --- a/components/policy/test_support/signature_provider.h +++ b/components/policy/test_support/signature_provider.h
@@ -83,7 +83,7 @@ std::vector<SigningKey> signing_keys_; // The key version to be used if no key version is defined by the client. - int current_key_version_ = 0; + int current_key_version_ = 1; }; } // namespace policy
diff --git a/components/policy/test_support/test_server_helpers.cc b/components/policy/test_support/test_server_helpers.cc index f3a9bbf..758cd12 100644 --- a/components/policy/test_support/test_server_helpers.cc +++ b/components/policy/test_support/test_server_helpers.cc
@@ -37,7 +37,7 @@ auto authorization = request.headers.find(dm_protocol::kAuthHeader); return authorization != request.headers.end() && re2::RE2::FullMatch(authorization->second, - token_header_prefix + "(\\w+)", out); + token_header_prefix + "(.+)", out); } bool GetEnrollmentTokenFromRequest(const HttpRequest& request, @@ -51,6 +51,13 @@ dm_protocol::kDMTokenAuthHeaderPrefix, out); } +bool GetGoogleLoginFromRequest(const net::test_server::HttpRequest& request, + std::string* out) { + return net::GetValueForKeyInQuery(request.GetURL(), "oauth_token", out) || + GetTokenFromAuthorization( + request, dm_protocol::kServiceTokenAuthHeaderPrefix, out); +} + std::unique_ptr<HttpResponse> CreateHttpResponse(net::HttpStatusCode code, const std::string& content) { auto response = std::make_unique<BasicHttpResponse>();
diff --git a/components/policy/test_support/test_server_helpers.h b/components/policy/test_support/test_server_helpers.h index 69ca900..cf6ec00 100644 --- a/components/policy/test_support/test_server_helpers.h +++ b/components/policy/test_support/test_server_helpers.h
@@ -20,8 +20,8 @@ namespace policy { -// Returns the value associated with |key| in |url|'s query or empty string if -// |key| is not present. +// Returns the value associated with `key` in `url`'s query or empty string if +// `key` is not present. std::string KeyValueFromUrl(GURL url, const std::string& key); // Check server-side requirements, as defined in @@ -29,23 +29,29 @@ bool MeetsServerSideRequirements(GURL url); // Returns true if a token is specified in the request URL with prefix -// |token_header_prefix|, in which case the token is copied to |out|. +// `token_header_prefix`, in which case the token is copied to `out`. bool GetTokenFromAuthorization(const net::test_server::HttpRequest& request, const std::string& token_header_prefix, std::string* out); // Returns true if an enrollment token is specified in the request URL, in which -// case the enrollment token is copied to |out|. +// case the enrollment token is copied to `out`. bool GetEnrollmentTokenFromRequest(const net::test_server::HttpRequest& request, std::string* out); // Returns true if a device token is specified in the request URL, in which case -// the device token is copied to |out|. +// the device token is copied to `out`. bool GetDeviceTokenFromRequest(const net::test_server::HttpRequest& request, std::string* out); -// Returns a text/plain HttpResponse with a given |code| and |content|. +// Returns true if an auth toke is specified in the request URL with the +// oauth_token parameter or if it is set as GoogleLogin token from the +// Authorization header. The token is copied to `out` if available. +bool GetGoogleLoginFromRequest(const net::test_server::HttpRequest& request, + std::string* out); + +// Returns a text/plain HttpResponse with a given `code` and `content`. std::unique_ptr<net::test_server::HttpResponse> CreateHttpResponse( net::HttpStatusCode code, const std::string& content);
diff --git a/components/prefs/pref_value_store_unittest.cc b/components/prefs/pref_value_store_unittest.cc index de46efd..3964813 100644 --- a/components/prefs/pref_value_store_unittest.cc +++ b/components/prefs/pref_value_store_unittest.cc
@@ -268,52 +268,50 @@ value = nullptr; ASSERT_TRUE(pref_value_store_->GetValue(prefs::kManagedPref, base::Value::Type::STRING, &value)); - std::string actual_str_value; - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(managed_pref::kManagedValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(managed_pref::kManagedValue, value->GetString()); // Test getting a supervised user value. value = nullptr; ASSERT_TRUE(pref_value_store_->GetValue(prefs::kSupervisedUserPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(supervised_user_pref::kSupervisedUserValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(supervised_user_pref::kSupervisedUserValue, value->GetString()); // Test getting an extension value. value = nullptr; ASSERT_TRUE(pref_value_store_->GetValue(prefs::kExtensionPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(extension_pref::kExtensionValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(extension_pref::kExtensionValue, value->GetString()); // Test getting a command-line value. value = nullptr; ASSERT_TRUE(pref_value_store_->GetValue(prefs::kCommandLinePref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(command_line_pref::kCommandLineValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(command_line_pref::kCommandLineValue, value->GetString()); // Test getting a user-set value. value = nullptr; ASSERT_TRUE(pref_value_store_->GetValue(prefs::kUserPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(user_pref::kUserValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(user_pref::kUserValue, value->GetString()); // Test getting a user set value overwriting a recommended value. value = nullptr; ASSERT_TRUE(pref_value_store_->GetValue(prefs::kRecommendedPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(recommended_pref::kRecommendedValue, - actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(recommended_pref::kRecommendedValue, value->GetString()); // Test getting a default value. value = nullptr; ASSERT_TRUE(pref_value_store_->GetValue(prefs::kDefaultPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(default_pref::kDefaultValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(default_pref::kDefaultValue, value->GetString()); // Test getting a preference value that the |PrefValueStore| // does not contain. @@ -336,50 +334,48 @@ ASSERT_TRUE(pref_value_store_->GetRecommendedValue( prefs::kManagedPref, base::Value::Type::STRING, &value)); - std::string actual_str_value; - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(recommended_pref::kManagedValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(recommended_pref::kManagedValue, value->GetString()); // Test getting recommended value when a supervised user value is present. value = nullptr; ASSERT_TRUE(pref_value_store_->GetRecommendedValue( prefs::kSupervisedUserPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(recommended_pref::kSupervisedUserValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(recommended_pref::kSupervisedUserValue, value->GetString()); // Test getting recommended value when an extension value is present. value = nullptr; ASSERT_TRUE(pref_value_store_->GetRecommendedValue( prefs::kExtensionPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(recommended_pref::kExtensionValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(recommended_pref::kExtensionValue, value->GetString()); // Test getting recommended value when a command-line value is present. value = nullptr; ASSERT_TRUE(pref_value_store_->GetRecommendedValue( prefs::kCommandLinePref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(recommended_pref::kCommandLineValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(recommended_pref::kCommandLineValue, value->GetString()); // Test getting recommended value when a user-set value is present. value = nullptr; ASSERT_TRUE(pref_value_store_->GetRecommendedValue( prefs::kUserPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(recommended_pref::kUserValue, actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(recommended_pref::kUserValue, value->GetString()); // Test getting recommended value when no higher-priority value is present. value = nullptr; ASSERT_TRUE(pref_value_store_->GetRecommendedValue( prefs::kRecommendedPref, base::Value::Type::STRING, &value)); - EXPECT_TRUE(value->GetAsString(&actual_str_value)); - EXPECT_EQ(recommended_pref::kRecommendedValue, - actual_str_value); + ASSERT_TRUE(value->is_string()); + EXPECT_EQ(recommended_pref::kRecommendedValue, value->GetString()); // Test getting recommended value when no recommended value is present. base::Value tmp_dummy_value(true);
diff --git a/components/safe_browsing/content/browser/browser_url_loader_throttle.cc b/components/safe_browsing/content/browser/browser_url_loader_throttle.cc index f1ce391..2c0adc5 100644 --- a/components/safe_browsing/content/browser/browser_url_loader_throttle.cc +++ b/components/safe_browsing/content/browser/browser_url_loader_throttle.cc
@@ -191,8 +191,10 @@ BrowserURLLoaderThrottle::~BrowserURLLoaderThrottle() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (deferred_) - TRACE_EVENT_ASYNC_END0("safe_browsing", "Deferred", this); + if (deferred_) { + TRACE_EVENT_NESTABLE_ASYNC_END0("safe_browsing", "Deferred", + TRACE_ID_LOCAL(this)); + } DeleteCheckerOnIO(); } @@ -267,8 +269,9 @@ deferred_ = true; defer_start_time_ = base::TimeTicks::Now(); *defer = true; - TRACE_EVENT_ASYNC_BEGIN1("safe_browsing", "Deferred", this, "original_url", - original_url_.spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("safe_browsing", "Deferred", + TRACE_ID_LOCAL(this), "original_url", + original_url_.spec()); } const char* BrowserURLLoaderThrottle::NameForLoggingWillProcessResponse() { @@ -301,7 +304,8 @@ if (pending_checks_ == 0 && deferred_) { deferred_ = false; - TRACE_EVENT_ASYNC_END0("safe_browsing", "Deferred", this); + TRACE_EVENT_NESTABLE_ASYNC_END0("safe_browsing", "Deferred", + TRACE_ID_LOCAL(this)); base::UmaHistogramTimes("SafeBrowsing.BrowserThrottle.TotalDelay", total_delay_); delegate_->Resume();
diff --git a/components/safe_browsing/content/renderer/renderer_url_loader_throttle.cc b/components/safe_browsing/content/renderer/renderer_url_loader_throttle.cc index 7548d01..8d9e887 100644 --- a/components/safe_browsing/content/renderer/renderer_url_loader_throttle.cc +++ b/components/safe_browsing/content/renderer/renderer_url_loader_throttle.cc
@@ -24,7 +24,8 @@ RendererURLLoaderThrottle::~RendererURLLoaderThrottle() { if (deferred_) - TRACE_EVENT_ASYNC_END0("safe_browsing", "Deferred", this); + TRACE_EVENT_NESTABLE_ASYNC_END0("safe_browsing", "Deferred", + TRACE_ID_LOCAL(this)); } void RendererURLLoaderThrottle::DetachFromCurrentSequence() { @@ -110,8 +111,9 @@ deferred_ = true; defer_start_time_ = base::TimeTicks::Now(); *defer = true; - TRACE_EVENT_ASYNC_BEGIN1("safe_browsing", "Deferred", this, "original_url", - original_url_.spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("safe_browsing", "Deferred", + TRACE_ID_LOCAL(this), "original_url", + original_url_.spec()); } const char* RendererURLLoaderThrottle::NameForLoggingWillProcessResponse() { @@ -182,7 +184,8 @@ if (pending_checks_ == 0 && deferred_) { deferred_ = false; - TRACE_EVENT_ASYNC_END0("safe_browsing", "Deferred", this); + TRACE_EVENT_NESTABLE_ASYNC_END0("safe_browsing", "Deferred", + TRACE_ID_LOCAL(this)); base::UmaHistogramTimes("SafeBrowsing.RendererThrottle.TotalDelay", total_delay_); delegate_->Resume(); @@ -220,7 +223,8 @@ total_delay_ = base::TimeTicks::Now() - defer_start_time_; deferred_ = false; - TRACE_EVENT_ASYNC_END0("safe_browsing", "Deferred", this); + TRACE_EVENT_NESTABLE_ASYNC_END0("safe_browsing", "Deferred", + TRACE_ID_LOCAL(this)); delegate_->Resume(); } }
diff --git a/components/safe_browsing/core/browser/safe_browsing_url_checker_impl.cc b/components/safe_browsing/core/browser/safe_browsing_url_checker_impl.cc index a832b19..2d84dce 100644 --- a/components/safe_browsing/core/browser/safe_browsing_url_checker_impl.cc +++ b/components/safe_browsing/core/browser/safe_browsing_url_checker_impl.cc
@@ -169,8 +169,8 @@ database_manager_->CancelCheck(this); } const GURL& url = urls_[next_index_].url; - TRACE_EVENT_ASYNC_END1("safe_browsing", "CheckUrl", this, "url", - url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_END1("safe_browsing", "CheckUrl", + TRACE_ID_LOCAL(this), "url", url.spec()); } } @@ -241,7 +241,8 @@ threat_type, SB_THREAT_TYPE_MAX + 1); } - TRACE_EVENT_ASYNC_END1("safe_browsing", "CheckUrl", this, "url", url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_END1("safe_browsing", "CheckUrl", + TRACE_ID_LOCAL(this), "url", url.spec()); const bool is_prefetch = (load_flags_ & net::LOAD_PREFETCH); @@ -401,8 +402,8 @@ SBThreatType threat_type = CheckWebUIUrls(url); if (threat_type != safe_browsing::SB_THREAT_TYPE_SAFE) { state_ = STATE_CHECKING_URL; - TRACE_EVENT_ASYNC_BEGIN1("safe_browsing", "CheckUrl", this, "url", - url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "safe_browsing", "CheckUrl", TRACE_ID_LOCAL(this), "url", url.spec()); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, @@ -412,8 +413,8 @@ break; } - TRACE_EVENT_ASYNC_BEGIN1("safe_browsing", "CheckUrl", this, "url", - url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("safe_browsing", "CheckUrl", + TRACE_ID_LOCAL(this), "url", url.spec()); // Start a timer to abort the check if it takes too long. timer_.Start(FROM_HERE, @@ -477,8 +478,8 @@ timer_.Stop(); RecordCheckUrlTimeout(/*timed_out=*/false); - TRACE_EVENT_ASYNC_END1("safe_browsing", "CheckUrl", this, "url", - url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_END1("safe_browsing", "CheckUrl", + TRACE_ID_LOCAL(this), "url", url.spec()); if (!RunNextCallback(true, false)) return;
diff --git a/components/services/heap_profiling/connection_manager.cc b/components/services/heap_profiling/connection_manager.cc index 068915bc..818c6fd 100644 --- a/components/services/heap_profiling/connection_manager.cc +++ b/components/services/heap_profiling/connection_manager.cc
@@ -164,7 +164,6 @@ void ConnectionManager::DumpProcessesForTracing( bool strip_path_from_mapped_files, - bool write_proto, DumpProcessesForTracingCallback callback, VmRegions vm_regions) { base::AutoLock lock(connections_lock_); @@ -185,11 +184,6 @@ for (auto& it : connections_) { base::ProcessId pid = it.first; Connection* connection = it.second.get(); - // TODO(ssid): Stop writing JSON to traces when proto output is enabled, - // https://crbug.com/1228548. - if (write_proto) - connection->client->AddHeapProfileToTrace(base::DoNothing()); - connection->client->RetrieveHeapProfile(base::BindOnce( &ConnectionManager::HeapProfileRetrieved, weak_factory_.GetWeakPtr(), tracking, pid, connection->process_type, strip_path_from_mapped_files,
diff --git a/components/services/heap_profiling/connection_manager.h b/components/services/heap_profiling/connection_manager.h index 6f4b002e..4048cf9d 100644 --- a/components/services/heap_profiling/connection_manager.h +++ b/components/services/heap_profiling/connection_manager.h
@@ -53,7 +53,6 @@ // returns. The dump is complete when the callback provided in the args is // fired. void DumpProcessesForTracing(bool strip_path_from_mapped_files, - bool write_proto, DumpProcessesForTracingCallback callback, VmRegions vm_regions);
diff --git a/components/services/heap_profiling/heap_profiling_service.cc b/components/services/heap_profiling/heap_profiling_service.cc index 713ae6f..4763ea62 100644 --- a/components/services/heap_profiling/heap_profiling_service.cc +++ b/components/services/heap_profiling/heap_profiling_service.cc
@@ -59,14 +59,12 @@ // memory_instrumentation::mojom::HeapProfiler implementation: void DumpProcessesForTracing( bool strip_path_from_mapped_files, - bool write_proto, DumpProcessesForTracingCallback callback) override { std::vector<base::ProcessId> pids = connection_manager_.GetConnectionPidsThatNeedVmRegions(); if (pids.empty()) { connection_manager_.DumpProcessesForTracing( - strip_path_from_mapped_files, write_proto, std::move(callback), - VmRegions()); + strip_path_from_mapped_files, std::move(callback), VmRegions()); return; } @@ -77,18 +75,17 @@ base::BindOnce(&ProfilingServiceImpl:: OnGetVmRegionsCompleteForDumpProcessesForTracing, weak_factory_.GetWeakPtr(), strip_path_from_mapped_files, - write_proto, std::move(callback))); + std::move(callback))); } private: void OnGetVmRegionsCompleteForDumpProcessesForTracing( bool strip_path_from_mapped_files, - bool write_proto, DumpProcessesForTracingCallback callback, VmRegions vm_regions) { - connection_manager_.DumpProcessesForTracing( - strip_path_from_mapped_files, write_proto, std::move(callback), - std::move(vm_regions)); + connection_manager_.DumpProcessesForTracing(strip_path_from_mapped_files, + std::move(callback), + std::move(vm_regions)); } mojo::Receiver<memory_instrumentation::mojom::HeapProfiler>
diff --git a/components/services/heap_profiling/public/cpp/BUILD.gn b/components/services/heap_profiling/public/cpp/BUILD.gn index 2ac0a14..fa8c70e 100644 --- a/components/services/heap_profiling/public/cpp/BUILD.gn +++ b/components/services/heap_profiling/public/cpp/BUILD.gn
@@ -26,14 +26,6 @@ "//base:debugging_buildflags", "//base/allocator:buildflags", ] - - if (!is_ios) { - sources += [ - "heap_profiling_trace_source.cc", - "heap_profiling_trace_source.h", - ] - deps += [ "//services/tracing/public/cpp:cpp" ] - } } source_set("unit_tests") { @@ -49,13 +41,4 @@ "//base/test:test_support", "//testing/gtest", ] - if (!is_ios) { - sources += [ "heap_profiling_trace_source_unittest.cc" ] - deps += [ - "//services/tracing:test_utils", - "//services/tracing/public/cpp:cpp", - "//third_party/perfetto/protos/perfetto/trace:lite", - "//third_party/perfetto/protos/perfetto/trace/profiling:lite", - ] - } }
diff --git a/components/services/heap_profiling/public/cpp/DEPS b/components/services/heap_profiling/public/cpp/DEPS index 10e43b3..0ba279a 100644 --- a/components/services/heap_profiling/public/cpp/DEPS +++ b/components/services/heap_profiling/public/cpp/DEPS
@@ -1,6 +1,3 @@ include_rules = [ "+components/services/heap_profiling/public", - "+services/tracing/public", - "+third_party/perfetto/include/perfetto/ext/tracing", - "+third_party/perfetto/protos/perfetto/trace", ]
diff --git a/components/services/heap_profiling/public/cpp/heap_profiling_trace_source.cc b/components/services/heap_profiling/public/cpp/heap_profiling_trace_source.cc deleted file mode 100644 index 31391d6b..0000000 --- a/components/services/heap_profiling/public/cpp/heap_profiling_trace_source.cc +++ /dev/null
@@ -1,139 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/services/heap_profiling/public/cpp/heap_profiling_trace_source.h" - -#include "base/profiler/frame.h" -#include "base/profiler/module_cache.h" -#include "base/trace_event/trace_event.h" -#include "components/services/heap_profiling/public/cpp/merge_samples.h" -#include "services/tracing/public/cpp/perfetto/interning_index.h" -#include "services/tracing/public/cpp/perfetto/perfetto_producer.h" -#include "services/tracing/public/cpp/perfetto/perfetto_traced_process.h" -#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" -#include "services/tracing/public/mojom/perfetto_service.mojom.h" -#include "third_party/perfetto/include/perfetto/ext/tracing/core/trace_writer.h" -#include "third_party/perfetto/protos/perfetto/trace/profiling/profile_packet.pbzero.h" -#include "third_party/perfetto/protos/perfetto/trace/trace_packet.pbzero.h" - -namespace heap_profiling { - -HeapProfilingTraceSource::HeapProfilingTraceSource() - : DataSourceBase(tracing::mojom::kNativeHeapProfilerSourceName) { - tracing::PerfettoTracedProcess::Get()->AddDataSource(this); -} - -HeapProfilingTraceSource::~HeapProfilingTraceSource() = default; - -// static -HeapProfilingTraceSource* HeapProfilingTraceSource::GetInstance() { - static base::NoDestructor<HeapProfilingTraceSource> instance; - return instance.get(); -} - -void HeapProfilingTraceSource::StartTracingImpl( - tracing::PerfettoProducer* producer, - const perfetto::DataSourceConfig& data_source_config) { - base::AutoLock l(lock_); - trace_writer_ = - producer->CreateTraceWriter(data_source_config.target_buffer()); - stack_profiler_writer_ = - std::make_unique<tracing::TracingSamplerProfiler::StackProfileWriter>( - data_source_config.chrome_config().privacy_filtering_enabled()); -} - -void HeapProfilingTraceSource::StopTracingImpl( - base::OnceClosure stop_complete_callback) { - base::AutoLock l(lock_); - stack_profiler_writer_.reset(); - trace_writer_.reset(); - std::move(stop_complete_callback).Run(); -} - -void HeapProfilingTraceSource::Flush( - base::RepeatingClosure flush_complete_callback) { - flush_complete_callback.Run(); -} - -bool HeapProfilingTraceSource::AddToTraceIfEnabled( - const std::vector<base::SamplingHeapProfiler::Sample>& samples) { - base::AutoLock l(lock_); - if (!trace_writer_) - return false; - - base::ModuleCache module_cache; - - uint64_t timestamp = TRACE_TIME_TICKS_NOW().since_origin().InNanoseconds(); - - stack_profiler_writer_->ResetEmittedState(); - - { - // Write initial packet on sequence to specify incremental state is reset. - perfetto::TraceWriter::TracePacketHandle trace_packet; - trace_packet = trace_writer_->NewTracePacket(); - - trace_packet->set_timestamp(timestamp); - trace_packet->set_incremental_state_cleared(true); - } - - // Write each sample in a new packet to keep the packet size small. - auto merged_samples = MergeSamples(samples); - - uint32_t pid = base::GetCurrentProcId(); - uint64_t index = 0; - for (auto& pair : merged_samples) { - perfetto::TraceWriter::TracePacketHandle trace_packet; - trace_packet = trace_writer_->NewTracePacket(); - - trace_packet->set_timestamp(timestamp); - - const base::SamplingHeapProfiler::Sample& sample = pair.first; - const SampleValue& value = pair.second; - - std::vector<base::Frame> frames; - frames.reserve(sample.stack.size()); - for (const void* frame : sample.stack) { - uintptr_t address = reinterpret_cast<uintptr_t>(frame); - const base::ModuleCache::Module* module = - module_cache.GetModuleForAddress(address); - frames.emplace_back(address, module); - } - tracing::InterningID callstack_id = - stack_profiler_writer_->GetCallstackIDAndMaybeEmit(frames, - &trace_packet); - - auto* profile_packet = trace_packet->set_profile_packet(); - profile_packet->set_continued(true); - profile_packet->set_index(index); - index++; - auto* process_dump = profile_packet->add_process_dumps(); - process_dump->set_pid(pid); - process_dump->set_heap_name(sample.allocator == - base::PoissonAllocationSampler::kMalloc - ? "malloc" - : "partition_alloc"); - process_dump->set_timestamp(timestamp); - - auto* sample_proto = process_dump->add_samples(); - sample_proto->set_self_allocated(value.total); - sample_proto->set_alloc_count(value.count); - sample_proto->set_callstack_id(callstack_id); - } - - { - // Write the end packet with continued=false to mark the current profile - // done. - perfetto::TraceWriter::TracePacketHandle trace_packet; - trace_packet = trace_writer_->NewTracePacket(); - - trace_packet->set_timestamp(timestamp); - - auto* profile_packet = trace_packet->set_profile_packet(); - profile_packet->set_continued(false); - profile_packet->set_index(index); - } - return true; -} - -} // namespace heap_profiling
diff --git a/components/services/heap_profiling/public/cpp/heap_profiling_trace_source.h b/components/services/heap_profiling/public/cpp/heap_profiling_trace_source.h deleted file mode 100644 index 6a195b4..0000000 --- a/components/services/heap_profiling/public/cpp/heap_profiling_trace_source.h +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_SERVICES_HEAP_PROFILING_PUBLIC_CPP_HEAP_PROFILING_TRACE_SOURCE_H_ -#define COMPONENTS_SERVICES_HEAP_PROFILING_PUBLIC_CPP_HEAP_PROFILING_TRACE_SOURCE_H_ - -#include <vector> - -#include "base/no_destructor.h" -#include "base/sampling_heap_profiler/sampling_heap_profiler.h" -#include "base/synchronization/lock.h" -#include "base/thread_annotations.h" -#include "services/tracing/public/cpp/perfetto/perfetto_traced_process.h" -#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" - -namespace perfetto { -class TraceWriter; -} - -namespace heap_profiling { - -// Perfetto tracing data source for heap profiler. This writes the heap profiles -// to trace in proto format. -class HeapProfilingTraceSource - : public tracing::PerfettoTracedProcess::DataSourceBase { - public: - static HeapProfilingTraceSource* GetInstance(); - - // PerfettoTracedProcess::DataSourceBase implementation: - void StartTracingImpl( - tracing::PerfettoProducer* producer, - const perfetto::DataSourceConfig& data_source_config) override; - void StopTracingImpl(base::OnceClosure stop_complete_callback) override; - void Flush(base::RepeatingClosure flush_complete_callback) override; - - // Writes heap profile to trace. Returns true if tracing was enabled and heap - // profile was added to the trace, false otherwise. - bool AddToTraceIfEnabled( - const std::vector<base::SamplingHeapProfiler::Sample>& samples); - - HeapProfilingTraceSource(const HeapProfilingTraceSource&) = delete; - HeapProfilingTraceSource& operator=(const HeapProfilingTraceSource&) = delete; - - private: - friend class base::NoDestructor<HeapProfilingTraceSource>; - - HeapProfilingTraceSource(); - ~HeapProfilingTraceSource() override; - - // Start and stop calls are made from tracing sequence. AddToTrace() is called - // on sequence used by ProfilingClient. It is possible that the tracing - // sequence is blocked until heap profiles are finished when stopping. It is - // ok to wait until profile is finished to stop tracing session. - base::Lock lock_; - std::unique_ptr<perfetto::TraceWriter> trace_writer_ GUARDED_BY(lock_); - std::unique_ptr<tracing::TracingSamplerProfiler::StackProfileWriter> - stack_profiler_writer_ GUARDED_BY(lock_); -}; - -} // namespace heap_profiling - -#endif // COMPONENTS_SERVICES_HEAP_PROFILING_PUBLIC_CPP_HEAP_PROFILING_TRACE_SOURCE_H_
diff --git a/components/services/heap_profiling/public/cpp/heap_profiling_trace_source_unittest.cc b/components/services/heap_profiling/public/cpp/heap_profiling_trace_source_unittest.cc deleted file mode 100644 index 2f7a1ee..0000000 --- a/components/services/heap_profiling/public/cpp/heap_profiling_trace_source_unittest.cc +++ /dev/null
@@ -1,119 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/services/heap_profiling/public/cpp/heap_profiling_trace_source.h" - -#include "base/run_loop.h" -#include "base/test/task_environment.h" -#include "services/tracing/public/cpp/perfetto/perfetto_traced_process.h" -#include "services/tracing/public/cpp/perfetto/producer_test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/perfetto/protos/perfetto/trace/profiling/profile_packet.pb.h" -#include "third_party/perfetto/protos/perfetto/trace/trace_packet.pb.h" - -namespace heap_profiling { -namespace { - -class HeapProfilingProtoExporterTest : public testing::Test { - public: - void SetUp() override { - tracing::PerfettoTracedProcess::ResetTaskRunnerForTesting(); - tracing::PerfettoTracedProcess::GetTaskRunner()->GetOrCreateTaskRunner(); - - auto perfetto_wrapper = std::make_unique<base::tracing::PerfettoTaskRunner>( - task_environment_.GetMainThreadTaskRunner()); - - producer_ = std::make_unique<tracing::TestProducerClient>( - std::move(perfetto_wrapper)); - } - - void TearDown() override { - // Be sure there is no pending/running tasks. - task_environment_.RunUntilIdle(); - } - - void BeginTrace() { - HeapProfilingTraceSource::GetInstance()->StartTracing( - /*data_source_id=*/1, producer_.get(), perfetto::DataSourceConfig()); - } - - void EndTracing() { - base::RunLoop wait_for_end; - HeapProfilingTraceSource::GetInstance()->StopTracing( - wait_for_end.QuitClosure()); - wait_for_end.Run(); - } - - tracing::TestProducerClient* producer() const { return producer_.get(); } - - protected: - std::unique_ptr<tracing::TestProducerClient> producer_; - - private: - base::test::TaskEnvironment task_environment_; -}; - -using Sample = base::SamplingHeapProfiler::Sample; -std::vector<Sample> MakeTestSamples() { - std::vector<Sample> samples{Sample(10, 100, 1), Sample(5, 102, 2), - Sample(7, 103, 3)}; - void* frame1 = reinterpret_cast<void*>(333); - void* frame2 = reinterpret_cast<void*>(666); - void* frame3 = reinterpret_cast<void*>(999); - samples[0].stack = {frame1}; - samples[1].stack = {frame1, frame2}; - samples[2].stack = {frame3, frame2, frame1}; - return samples; -} - -TEST_F(HeapProfilingProtoExporterTest, ProfilingDisabled) { - BeginTrace(); - EndTracing(); - EXPECT_EQ(producer()->GetFinalizedPacketCount(), 0u); -} - -TEST_F(HeapProfilingProtoExporterTest, ProfilingWithoutTracing) { - auto samples = MakeTestSamples(); - HeapProfilingTraceSource::GetInstance()->AddToTraceIfEnabled(samples); - BeginTrace(); - EndTracing(); - HeapProfilingTraceSource::GetInstance()->AddToTraceIfEnabled(samples); - EXPECT_EQ(producer()->GetFinalizedPacketCount(), 0u); -} - -TEST_F(HeapProfilingProtoExporterTest, TraceFormat) { - auto samples = MakeTestSamples(); - BeginTrace(); - HeapProfilingTraceSource::GetInstance()->AddToTraceIfEnabled(samples); - EndTracing(); - ASSERT_EQ(producer()->GetFinalizedPacketCount(), 5u); - - const auto& packets = producer_->finalized_packets(); - EXPECT_TRUE(packets[0]->incremental_state_cleared()); - EXPECT_FALSE(packets[1]->incremental_state_cleared()); - EXPECT_FALSE(packets[2]->incremental_state_cleared()); - EXPECT_FALSE(packets[3]->incremental_state_cleared()); - EXPECT_FALSE(packets[4]->incremental_state_cleared()); - - EXPECT_TRUE(packets[1]->profile_packet().continued()); - EXPECT_TRUE(packets[2]->profile_packet().continued()); - EXPECT_TRUE(packets[3]->profile_packet().continued()); - EXPECT_FALSE(packets[4]->profile_packet().continued()); - - EXPECT_EQ(packets[1]->profile_packet().index(), 0u); - EXPECT_EQ(packets[2]->profile_packet().index(), 1u); - EXPECT_EQ(packets[3]->profile_packet().index(), 2u); - EXPECT_EQ(packets[4]->profile_packet().index(), 3u); - - for (unsigned i = 1; i <= 3; ++i) { - const auto& process_dump = packets[i]->profile_packet().process_dumps(0); - EXPECT_TRUE(process_dump.has_pid()); - EXPECT_TRUE(process_dump.has_timestamp()); - EXPECT_EQ(process_dump.samples(0).self_allocated(), samples[i - 1].total); - EXPECT_EQ(process_dump.samples(0).callstack_id(), i); - } -} - -} // namespace -} // namespace heap_profiling
diff --git a/components/services/heap_profiling/public/cpp/profiling_client.cc b/components/services/heap_profiling/public/cpp/profiling_client.cc index d0ee8eed..5ec310be 100644 --- a/components/services/heap_profiling/public/cpp/profiling_client.cc +++ b/components/services/heap_profiling/public/cpp/profiling_client.cc
@@ -19,10 +19,6 @@ #include "base/trace_event/memory_dump_manager.h" #include "build/build_config.h" -#if !defined(OS_IOS) -#include "components/services/heap_profiling/public/cpp/heap_profiling_trace_source.h" -#endif - #if defined(OS_ANDROID) && BUILDFLAG(CAN_UNWIND_WITH_CFI_TABLE) && \ defined(OFFICIAL_BUILD) #include "base/trace_event/cfi_backtrace_android.h" @@ -76,11 +72,6 @@ #else StartProfilingInternal(std::move(params), std::move(callback)); #endif - -#if !defined(OS_IOS) - // Create trace source so that it registers itself to the tracing system. - HeapProfilingTraceSource::GetInstance(); -#endif } namespace { @@ -205,22 +196,4 @@ std::move(callback).Run(std::move(profile)); } -void ProfilingClient::AddHeapProfileToTrace( - AddHeapProfileToTraceCallback callback) { - auto* profiler = base::SamplingHeapProfiler::Get(); - std::vector<base::SamplingHeapProfiler::Sample> samples = - profiler->GetSamples(/*profile_id=*/0); - -#if !defined(OS_IOS) - bool success = - HeapProfilingTraceSource::GetInstance()->AddToTraceIfEnabled(samples); -#else - bool success = false; - // Tracing is not supported in iOS. - NOTREACHED(); -#endif - - std::move(callback).Run(success); -} - } // namespace heap_profiling
diff --git a/components/services/heap_profiling/public/cpp/profiling_client.h b/components/services/heap_profiling/public/cpp/profiling_client.h index 8f434d85..b8958f1 100644 --- a/components/services/heap_profiling/public/cpp/profiling_client.h +++ b/components/services/heap_profiling/public/cpp/profiling_client.h
@@ -23,7 +23,6 @@ void StartProfiling(mojom::ProfilingParamsPtr params, StartProfilingCallback callback) override; void RetrieveHeapProfile(RetrieveHeapProfileCallback callback) override; - void AddHeapProfileToTrace(AddHeapProfileToTraceCallback callback) override; void BindToInterface(mojo::PendingReceiver<mojom::ProfilingClient> receiver);
diff --git a/components/services/heap_profiling/public/mojom/heap_profiling_client.mojom b/components/services/heap_profiling/public/mojom/heap_profiling_client.mojom index ee062fd..b9f9b8c 100644 --- a/components/services/heap_profiling/public/mojom/heap_profiling_client.mojom +++ b/components/services/heap_profiling/public/mojom/heap_profiling_client.mojom
@@ -77,10 +77,5 @@ // There is currently no mechanism to stop recording allocations. StartProfiling(ProfilingParams params) => (); - // Captures and returns a snapshot of the heap profile of the current process. RetrieveHeapProfile() => (HeapProfile profile); - - // Captures a snapshot of the heap profile and adds to Perfetto traces in - // proto format. - AddHeapProfileToTrace() => (bool success); };
diff --git a/components/signin/ios/browser/account_consistency_service.h b/components/signin/ios/browser/account_consistency_service.h index 7220a445..bfdf917 100644 --- a/components/signin/ios/browser/account_consistency_service.h +++ b/components/signin/ios/browser/account_consistency_service.h
@@ -55,7 +55,8 @@ // callback once the Gaia cookies have been restored and returns YES on // success. Note that in order to avoid redirect loops this method applies a // one hour time restriction in between restoration calls. - BOOL RestoreGaiaCookies(base::OnceClosure cookies_restored_callback); + BOOL RestoreGaiaCookies( + base::OnceCallback<void(BOOL)> cookies_restored_callback); // Enqueues a request to set the CHROME_CONNECTED cookie for the domain of the // |url|. The cookie is set if it is not already on the domain. @@ -91,6 +92,17 @@ void OnDeleteCookiesFinished(base::OnceClosure callback, uint32_t num_cookies_deleted); + // Triggers a Gaia cookie update on the Google domain. Calls + // |cookies_restored_callback| with whether the Gaia cookies were restored. + void TriggerGaiaCookieChangeIfDeleted( + base::OnceCallback<void(BOOL)> cookies_restored_callback, + const net::CookieAccessResultList& cookie_list, + const net::CookieAccessResultList& excluded_cookies); + + // Runs the list of callbacks with |has_cookie_changed| to indicate whether + // the cookies required a restore call. + void RunGaiaCookiesRestoredCallbacks(BOOL has_cookie_changed); + // IdentityManager::Observer implementation. void OnPrimaryAccountChanged( const signin::PrimaryAccountChangeEvent& event) override; @@ -118,7 +130,7 @@ base::Time last_gaia_cookie_update_time_; // List of callbacks to be called following GAIA cookie restoration. - std::vector<base::OnceClosure> gaia_cookies_restored_callbacks_; + std::vector<base::OnceCallback<void(BOOL)>> gaia_cookies_restored_callbacks_; // Handlers reacting on GAIA responses with the X-Chrome-Manage-Accounts // header set.
diff --git a/components/signin/ios/browser/account_consistency_service.mm b/components/signin/ios/browser/account_consistency_service.mm index 3d5a2f7..0768d0f 100644 --- a/components/signin/ios/browser/account_consistency_service.mm +++ b/components/signin/ios/browser/account_consistency_service.mm
@@ -137,8 +137,8 @@ web::WebStatePolicyDecider::PolicyDecisionCallback callback) override; void WebStateDestroyed() override; - // Loads |url| in the current tab. - void NavigateToURL(GURL url); + // Handles the AddAccount request depending on |has_cookie_changed|. + void HandleAddAccountRequest(GURL url, BOOL has_cookie_changed); bool show_consistency_promo_ = false; AccountConsistencyService* account_consistency_service_; // Weak. @@ -255,7 +255,7 @@ !params.continue_url.empty() && !continue_url.is_valid()) << "Invalid continuation URL: \"" << continue_url << "\""; if (account_consistency_service_->RestoreGaiaCookies(base::BindOnce( - &AccountConsistencyHandler::NavigateToURL, + &AccountConsistencyHandler::HandleAddAccountRequest, weak_ptr_factory_.GetWeakPtr(), continue_url))) { // Continue URL will be processed in a callback once Gaia cookies // have been restored. @@ -292,8 +292,16 @@ std::move(callback).Run(PolicyDecision::Cancel()); } -void AccountConsistencyService::AccountConsistencyHandler::NavigateToURL( - GURL url) { +void AccountConsistencyService::AccountConsistencyHandler:: + HandleAddAccountRequest(GURL url, BOOL has_cookie_changed) { + if (!has_cookie_changed) { + // If the cookies on the device did not need to be updated then the user + // is not in an inconsistent state (where the identities on the device + // are different than those on the web). Fallback to asking the user to + // add an account. + [delegate_ onAddAccount]; + return; + } web_state_->OpenURL(web::WebState::OpenURLParams( url, web::Referrer(), WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_AUTO_TOPLEVEL, false)); @@ -347,21 +355,62 @@ AccountConsistencyService::~AccountConsistencyService() {} BOOL AccountConsistencyService::RestoreGaiaCookies( - base::OnceClosure cookies_restored_callback) { - // Only processes a single restoration attempt for a given amount of time to - // avoid redirect loops. + base::OnceCallback<void(BOOL)> cookies_restored_callback) { + // We currently enforce a time threshold to update the Gaia cookie + // for signed-in users to prevent calling the expensive method + // |GetAllCookies| in the cookie manager. if (last_gaia_cookie_update_time_.is_null() || base::Time::Now() - last_gaia_cookie_update_time_ > GetDelayThresholdToUpdateGaiaCookie()) { - gaia_cookies_restored_callbacks_.push_back( - std::move(cookies_restored_callback)); - identity_manager_->GetAccountsCookieMutator()->ForceTriggerOnCookieChange(); + network::mojom::CookieManager* cookie_manager = + browser_state_->GetCookieManager(); + cookie_manager->GetCookieList( + GaiaUrls::GetInstance()->secure_google_url(), + net::CookieOptions::MakeAllInclusive(), + base::BindOnce( + &AccountConsistencyService::TriggerGaiaCookieChangeIfDeleted, + base::Unretained(this), std::move(cookies_restored_callback))); last_gaia_cookie_update_time_ = base::Time::Now(); return YES; } return NO; } +void AccountConsistencyService::TriggerGaiaCookieChangeIfDeleted( + base::OnceCallback<void(BOOL)> cookies_restored_callback, + const net::CookieAccessResultList& cookie_list, + const net::CookieAccessResultList& unused_excluded_cookies) { + gaia_cookies_restored_callbacks_.push_back( + std::move(cookies_restored_callback)); + + for (const auto& cookie : cookie_list) { + if (cookie.cookie.Name() == GaiaConstants::kGaiaSigninCookieName) { + LogIOSGaiaCookiesState( + GaiaCookieStateOnSignedInNavigation::kGaiaCookiePresentOnNavigation); + RunGaiaCookiesRestoredCallbacks(/*has_cookie_changed=*/NO); + return; + } + } + + // The SAPISID cookie may have been deleted previous to this update due to + // ITP restrictions marking Google domains as potential trackers. + LogIOSGaiaCookiesState( + GaiaCookieStateOnSignedInNavigation:: + kGaiaCookieAbsentOnGoogleAssociatedDomainNavigation); + + // Re-generate cookie to ensure that the user is properly signed in. + identity_manager_->GetAccountsCookieMutator()->ForceTriggerOnCookieChange(); +} + +void AccountConsistencyService::RunGaiaCookiesRestoredCallbacks( + BOOL has_cookie_changed) { + std::vector<base::OnceCallback<void(BOOL)>> callbacks; + std::swap(gaia_cookies_restored_callbacks_, callbacks); + for (base::OnceCallback<void(BOOL)>& callback : callbacks) { + std::move(callback).Run(has_cookie_changed); + } +} + void AccountConsistencyService::SetWebStateHandler( web::WebState* web_state, id<ManageAccountsDelegate> delegate) { @@ -511,12 +560,7 @@ // If signed-in accounts have been recently restored through GAIA cookie // restoration then run the relevant callback to finish the update process. - if (accounts_in_cookie_jar_info.signed_in_accounts.size() > 0 && - !gaia_cookies_restored_callbacks_.empty()) { - std::vector<base::OnceClosure> callbacks; - std::swap(gaia_cookies_restored_callbacks_, callbacks); - for (base::OnceClosure& callback : callbacks) { - std::move(callback).Run(); - } + if (accounts_in_cookie_jar_info.signed_in_accounts.size() > 0) { + RunGaiaCookiesRestoredCallbacks(/*has_cookie_changed=*/YES); } }
diff --git a/components/startup_metric_utils/browser/startup_metric_utils.cc b/components/startup_metric_utils/browser/startup_metric_utils.cc index bb280e4..95be873 100644 --- a/components/startup_metric_utils/browser/startup_metric_utils.cc +++ b/components/startup_metric_utils/browser/startup_metric_utils.cc
@@ -249,12 +249,14 @@ base::TimeTicks end_ticks) { UmaHistogramWithTemperature(histogram_function, histogram_basename, end_ticks - begin_ticks); - TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1("startup", histogram_basename.c_str(), - 0, begin_ticks, "Temperature", - g_startup_temperature); - TRACE_EVENT_ASYNC_END_WITH_TIMESTAMP1("startup", histogram_basename.c_str(), - 0, end_ticks, "Temperature", - g_startup_temperature); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP1( + "startup", histogram_basename.c_str(), + TRACE_ID_WITH_SCOPE(histogram_basename.c_str(), 0), begin_ticks, + "Temperature", g_startup_temperature); + TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP1( + "startup", histogram_basename.c_str(), + TRACE_ID_WITH_SCOPE(histogram_basename.c_str(), 0), end_ticks, + "Temperature", g_startup_temperature); } // Extension to the UmaHistogramWithTraceAndTemperature that records a
diff --git a/components/subresource_filter/content/browser/content_subresource_filter_throttle_manager_unittest.cc b/components/subresource_filter/content/browser/content_subresource_filter_throttle_manager_unittest.cc index fad1823b..f39d2a8 100644 --- a/components/subresource_filter/content/browser/content_subresource_filter_throttle_manager_unittest.cc +++ b/components/subresource_filter/content/browser/content_subresource_filter_throttle_manager_unittest.cc
@@ -1377,7 +1377,7 @@ } TEST_P(ContentSubresourceFilterThrottleManagerTest, - ReadyToCommitNavigationThenRenderFrameDeletes_MetricsNotRecoded) { + ReadyToCommitNavigationThenRenderFrameDeletes_MetricsNotRecorded) { NavigateAndCommitMainFrame(GURL(kTestURLWithDryRun)); ExpectActivationSignalForFrame(main_rfh(), true /* expect_activation */);
diff --git a/components/subresource_filter/content/browser/subresource_filter_safe_browsing_client.cc b/components/subresource_filter/content/browser/subresource_filter_safe_browsing_client.cc index 13c4530..18800d0 100644 --- a/components/subresource_filter/content/browser/subresource_filter_safe_browsing_client.cc +++ b/components/subresource_filter/content/browser/subresource_filter_safe_browsing_client.cc
@@ -56,10 +56,10 @@ auto* raw_request = request.get(); DCHECK(requests_.find(raw_request) == requests_.end()); requests_[raw_request] = std::move(request); - TRACE_EVENT_ASYNC_BEGIN1(TRACE_DISABLED_BY_DEFAULT("loading"), - "SubresourceFilterSBCheck", raw_request, - "check_result", - std::make_unique<base::trace_event::TracedValue>()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + TRACE_DISABLED_BY_DEFAULT("loading"), "SubresourceFilterSBCheck", + TRACE_ID_LOCAL(raw_request), "check_result", + std::make_unique<base::trace_event::TracedValue>()); raw_request->Start(url); // Careful, |raw_request| can be destroyed after this line. } @@ -68,9 +68,9 @@ SubresourceFilterSafeBrowsingClientRequest* request, const CheckResult& check_result) { DCHECK_CURRENTLY_ON(content::BrowserThread::IO); - TRACE_EVENT_ASYNC_END1(TRACE_DISABLED_BY_DEFAULT("loading"), - "SubresourceFilterSBCheck", request, "check_result", - check_result.ToTracedValue()); + TRACE_EVENT_NESTABLE_ASYNC_END1( + TRACE_DISABLED_BY_DEFAULT("loading"), "SubresourceFilterSBCheck", + TRACE_ID_LOCAL(request), "check_result", check_result.ToTracedValue()); throttle_task_runner_->PostTask( FROM_HERE, base::BindOnce(&SubresourceFilterSafeBrowsingActivationThrottle::
diff --git a/components/subresource_filter/core/common/indexed_ruleset.cc b/components/subresource_filter/core/common/indexed_ruleset.cc index 2eb67a4..cd2fb42 100644 --- a/components/subresource_filter/core/common/indexed_ruleset.cc +++ b/components/subresource_filter/core/common/indexed_ruleset.cc
@@ -165,20 +165,37 @@ const bool is_third_party = first_party.IsThirdParty(url); const EmbedderConditionsMatcher embedder_conditions_matcher; - const url_pattern_index::flat::UrlRule* blocklist_rule = blocklist_.FindMatch( - url, first_party.origin(), element_type, - proto::ACTIVATION_TYPE_UNSPECIFIED, is_third_party, disable_generic_rules, - embedder_conditions_matcher, FindRuleStrategy::kAny); - const url_pattern_index::flat::UrlRule* allowlist_rule = nullptr; - if (blocklist_rule) { - allowlist_rule = - allowlist_.FindMatch(url, first_party.origin(), element_type, - proto::ACTIVATION_TYPE_UNSPECIFIED, is_third_party, - disable_generic_rules, embedder_conditions_matcher, - FindRuleStrategy::kAny); - return allowlist_rule ? allowlist_rule : blocklist_rule; + auto find_match = + [&](const url_pattern_index::UrlPatternIndexMatcher& matcher) { + return matcher.FindMatch(url, first_party.origin(), element_type, + proto::ACTIVATION_TYPE_UNSPECIFIED, + is_third_party, disable_generic_rules, + embedder_conditions_matcher, + FindRuleStrategy::kAny); + }; + + // Always check the allowlist for subdocuments. For other forms of resources, + // it is not necessary to differentiate between the resource not matching a + // blocklist rule and matching an allowlist rule. For subdocuments, matching + // an allowlist rule can still override ad tagging decisions even if the + // subdocument url did not match a blocklist rule. + // + // To optimize the subdocument case, we only check the blocklist if an + // allowlist rule was not matched. + if (element_type == proto::ELEMENT_TYPE_SUBDOCUMENT) { + auto* allowlist_rule = find_match(allowlist_); + if (allowlist_rule) + return allowlist_rule; + return find_match(blocklist_); } - return nullptr; + + // For non-subdocument elements, only check the allowlist if there is a + // matched blocklist rule to prevent unnecessary lookups. + auto* blocklist_rule = find_match(blocklist_); + if (!blocklist_rule) + return nullptr; + auto* allowlist_rule = find_match(allowlist_); + return allowlist_rule ? allowlist_rule : blocklist_rule; } } // namespace subresource_filter
diff --git a/components/subresource_filter/core/common/indexed_ruleset_unittest.cc b/components/subresource_filter/core/common/indexed_ruleset_unittest.cc index c0c34cef..da52efce 100644 --- a/components/subresource_filter/core/common/indexed_ruleset_unittest.cc +++ b/components/subresource_filter/core/common/indexed_ruleset_unittest.cc
@@ -129,17 +129,38 @@ GetLoadPolicy("http://example.org?param=image1")); } +TEST_F(SubresourceFilterIndexedRulesetTest, SimpleBlocklistSubdocument) { + ASSERT_TRUE(AddSimpleRule("?param=")); + Finish(); + + EXPECT_EQ(LoadPolicy::ALLOW, GetLoadPolicy("https://example.com")); + EXPECT_EQ(LoadPolicy::DISALLOW, + GetLoadPolicy("http://example.org?param=image1", + /*document_origin=*/"", testing::kSubdocument)); +} + TEST_F(SubresourceFilterIndexedRulesetTest, SimpleAllowlist) { ASSERT_TRUE(AddSimpleAllowlistRule("example.com/?filter_out=")); Finish(); // This should not return EXPLICITLY_ALLOW because there is no corresponding // blocklist rule for the allowlist rule. To optimize speed, allowlist rules - // are only checked if a rule was matched with a blocklist rule. + // are only checked if a rule was matched with a blocklist rule unless it + // is a subdocument resource. EXPECT_EQ(LoadPolicy::ALLOW, GetLoadPolicy("https://example.com?filter_out=true")); } +TEST_F(SubresourceFilterIndexedRulesetTest, SimpleAllowlistSubdocument) { + ASSERT_TRUE(AddSimpleAllowlistRule("example.com/?filter_out=")); + Finish(); + + // Verify allowlist rules are always checked for subdocument element types. + EXPECT_EQ(LoadPolicy::EXPLICITLY_ALLOW, + GetLoadPolicy("https://example.com?filter_out=true", + /*document_origin=*/"", testing::kSubdocument)); +} + TEST_F(SubresourceFilterIndexedRulesetTest, SimpleAllowlistWithMatchingBlocklist) { ASSERT_TRUE(AddSimpleRule("example.com/?filter_out=")); @@ -150,6 +171,17 @@ GetLoadPolicy("https://example.com?filter_out=true")); } +TEST_F(SubresourceFilterIndexedRulesetTest, + SimpleAllowlistWithMatchingBlocklistSubdocument) { + ASSERT_TRUE(AddSimpleRule("example.com/?filter_out=")); + ASSERT_TRUE(AddSimpleAllowlistRule("example.com/?filter_out=")); + Finish(); + + EXPECT_EQ(LoadPolicy::EXPLICITLY_ALLOW, + GetLoadPolicy("https://example.com?filter_out=true", + /*document_origin=*/"", testing::kSubdocument)); +} + // Ensure patterns containing non-ascii characters are disallowed. TEST_F(SubresourceFilterIndexedRulesetTest, NonAsciiPatterns) { // non-ascii character é.
diff --git a/components/sync/model/sync_change_processor.h b/components/sync/model/sync_change_processor.h index 13c70e0..9ae696b 100644 --- a/components/sync/model/sync_change_processor.h +++ b/components/sync/model/sync_change_processor.h
@@ -32,14 +32,6 @@ virtual absl::optional<ModelError> ProcessSyncChanges( const base::Location& from_here, const SyncChangeList& change_list) = 0; - - // Fills a list of SyncData. This should create an up to date representation - // of all the data known to the ChangeProcessor for |datatype|, and - // should match/be a subset of the server's view of that datatype. - // - // WARNING: This can be a potentially slow & memory intensive operation and - // should only be used when absolutely necessary / sparingly. - virtual SyncDataList GetAllSyncData(ModelType type) const = 0; }; } // namespace syncer
diff --git a/components/sync/model/syncable_service_based_bridge.cc b/components/sync/model/syncable_service_based_bridge.cc index f983902..0c8a0603 100644 --- a/components/sync/model/syncable_service_based_bridge.cc +++ b/components/sync/model/syncable_service_based_bridge.cc
@@ -193,13 +193,6 @@ return absl::nullopt; } - SyncDataList GetAllSyncData(ModelType type) const override { - // This function is not supported and not exercised by the relevant - // datatypes (that are integrated with this bridge). - NOTREACHED(); - return SyncDataList(); - } - private: const ModelType type_; const base::RepeatingCallback<void(const absl::optional<ModelError>&)>
diff --git a/components/sync/test/model/fake_sync_change_processor.cc b/components/sync/test/model/fake_sync_change_processor.cc index ac5f4a9..a33c3307 100644 --- a/components/sync/test/model/fake_sync_change_processor.cc +++ b/components/sync/test/model/fake_sync_change_processor.cc
@@ -20,10 +20,6 @@ return absl::nullopt; } -SyncDataList FakeSyncChangeProcessor::GetAllSyncData(ModelType type) const { - return data_; -} - const SyncChangeList& FakeSyncChangeProcessor::changes() const { return changes_; } @@ -32,12 +28,4 @@ return changes_; } -const SyncDataList& FakeSyncChangeProcessor::data() const { - return data_; -} - -SyncDataList& FakeSyncChangeProcessor::data() { - return data_; -} - } // namespace syncer
diff --git a/components/sync/test/model/fake_sync_change_processor.h b/components/sync/test/model/fake_sync_change_processor.h index 824a36c3..39fc42d 100644 --- a/components/sync/test/model/fake_sync_change_processor.h +++ b/components/sync/test/model/fake_sync_change_processor.h
@@ -23,20 +23,11 @@ const base::Location& from_here, const SyncChangeList& change_list) override; - // SyncChangeProcessor implementation. - // - // Returns data(). - SyncDataList GetAllSyncData(ModelType type) const override; - - virtual const SyncChangeList& changes() const; - virtual SyncChangeList& changes(); - - virtual const SyncDataList& data() const; - virtual SyncDataList& data(); + const SyncChangeList& changes() const; + SyncChangeList& changes(); private: SyncChangeList changes_; - SyncDataList data_; DISALLOW_COPY_AND_ASSIGN(FakeSyncChangeProcessor); };
diff --git a/components/sync/test/model/sync_change_processor_wrapper_for_test.cc b/components/sync/test/model/sync_change_processor_wrapper_for_test.cc index 517863f..f362f56 100644 --- a/components/sync/test/model/sync_change_processor_wrapper_for_test.cc +++ b/components/sync/test/model/sync_change_processor_wrapper_for_test.cc
@@ -34,10 +34,4 @@ return process_sync_changes_.Run(from_here, change_list); } -SyncDataList SyncChangeProcessorWrapperForTest::GetAllSyncData( - ModelType type) const { - NOTREACHED(); - return SyncDataList(); -} - } // namespace syncer
diff --git a/components/sync/test/model/sync_change_processor_wrapper_for_test.h b/components/sync/test/model/sync_change_processor_wrapper_for_test.h index 4aa2f47..6b26f69 100644 --- a/components/sync/test/model/sync_change_processor_wrapper_for_test.h +++ b/components/sync/test/model/sync_change_processor_wrapper_for_test.h
@@ -30,7 +30,6 @@ absl::optional<ModelError> ProcessSyncChanges( const base::Location& from_here, const SyncChangeList& change_list) override; - SyncDataList GetAllSyncData(ModelType type) const override; private: const base::RepeatingCallback<absl::optional<ModelError>(
diff --git a/components/sync_preferences/pref_service_syncable_unittest.cc b/components/sync_preferences/pref_service_syncable_unittest.cc index 21f517cb..40fcfe4e 100644 --- a/components/sync_preferences/pref_service_syncable_unittest.cc +++ b/components/sync_preferences/pref_service_syncable_unittest.cc
@@ -104,10 +104,6 @@ void FailNextProcessSyncChanges() { fail_next_ = true; } - syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override { - return syncer::SyncDataList(); - } - private: syncer::SyncChangeList* output_; bool fail_next_;
diff --git a/components/viz/service/debugger/viz_debugger.h b/components/viz/service/debugger/viz_debugger.h index 7d698ee..a2c5bb0 100644 --- a/components/viz/service/debugger/viz_debugger.h +++ b/components/viz/service/debugger/viz_debugger.h
@@ -343,9 +343,9 @@ #define DBG_DRAW_RECT(anno, rect) DBG_DRAW_RECT_OPT(anno, DBG_OPT_BLACK, rect) -#define DBG_FLAG_FBOOL(anno, fun_name) \ - namespace { \ - constexp bool fun_name() { return false; } \ +#define DBG_FLAG_FBOOL(anno, fun_name) \ + namespace { \ + constexpr bool fun_name() { return false; } \ } #endif // BUILDFLAG(USE_VIZ_DEBUGGER)
diff --git a/components/viz/service/debugger/viz_debugger_unittest.cc b/components/viz/service/debugger/viz_debugger_unittest.cc index 7aa307b..da7bc01 100644 --- a/components/viz/service/debugger/viz_debugger_unittest.cc +++ b/components/viz/service/debugger/viz_debugger_unittest.cc
@@ -411,4 +411,24 @@ } // namespace } // namespace viz -#endif // VIZ_DEBUGGER_IS_ON() +#else // VIZ_DEBUGGER_IS_ON() + +class VisualDebuggerTest : public testing::Test {}; + +DBG_FLAG_FBOOL("unit.test.fake.anno", flag_default_value_check) + +TEST_F(VisualDebuggerTest, TestDebugFlagAnnoAndFunction) { + // Visual debugger is disabled at build level this check should always return + // false. + EXPECT_FALSE(viz::VizDebugger::GetInstance()->IsEnabled()); + // The default value for a bool flag when the visual debugger is disabled is + // false. + EXPECT_FALSE(flag_default_value_check()); +} + +// For optimization purposes the flag fbool values return false as a constexpr. +// This allows the compiler to constant propagate and remove unused codepaths. +static_assert(flag_default_value_check() == false, + "Default value when debugger is disabled is false."); + +#endif
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index fc0aa93..949c0e10a 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -882,6 +882,8 @@ "file_system/file_system_manager_impl.h", "file_system/file_system_url_loader_factory.cc", "file_system/file_system_url_loader_factory.h", + "file_system_access/file_system_access_access_handle_host_impl.cc", + "file_system_access/file_system_access_access_handle_host_impl.h", "file_system_access/file_system_access_data_transfer_token_impl.cc", "file_system_access/file_system_access_data_transfer_token_impl.h", "file_system_access/file_system_access_directory_handle_impl.cc",
diff --git a/content/browser/accessibility/accessibility_tree_formatter_utils_mac.mm b/content/browser/accessibility/accessibility_tree_formatter_utils_mac.mm index dc7f46d..00d56e73 100644 --- a/content/browser/accessibility/accessibility_tree_formatter_utils_mac.mm +++ b/content/browser/accessibility/accessibility_tree_formatter_utils_mac.mm
@@ -83,14 +83,26 @@ // a working solution that works nicely in both cases. Use LOG(ERROR) for now // as a console warning. - // Get a target to invoke an attribute for. First, check the storage if it has - // an associated target for the property node, then query the tree indexer if - // the property node refers to a DOM id or line index of an accessible object. - // If the property node doesn't provide a target then use the default one - // (if any). + // Executes a scripting statement coded in a given property node. + // The statement represents a chainable sequence of attribute calls, where + // each subsequent call is invoked on an object returned by a previous call. + // For example, p.AXChildren[0].AXRole will unroll into a sequence of + // `p.AXChildren`, `(p.AXChildren)[0]` and `((p.AXChildren)[0]).AXRole`. + + // Get an initial target to invoke an attribute for. First, check the storage + // if it has an associated target for the property node, then query the tree + // indexer if the property node refers to a DOM id or line index of + // an accessible object. If the property node doesn't provide a target then + // use the default one (if any, the default node is provided in case of + // a tree dumping only, the scripts never have default target). id target = nil; - // Case 1: try to get a target from the storage. + // Case 1: try to get a target from the storage. The target may refer to + // a variable which is kept in the storage. For example, + // `text_leaf:= p.AXChildren[0]` will define `text_leaf` variable and put it + // into the storage, and then the variable value will be extracted from + // the storage for other instruction referring the variable, for example, + // `text_leaf.AXRole`. if (storage_) { auto storage_iterator = storage_->find(property_node.name_or_value); if (storage_iterator != storage_->end()) { @@ -102,14 +114,20 @@ } } } - // Case 2: try to get target from the tree indexer. + // Case 2: try to get target from the tree indexer. The target may refer to + // an accessible element by DOM id or by a line number (:LINE_NUM format) in + // a result accessible tree. The tree indexer keeps the mappings between + // accesible elements and their DOM ids and line numbers. if (!target) target = line_indexer->NodeBy(property_node.name_or_value); // Case 3: no target either indicates an error or the property node is a - // scalar value and thus nothing to invoke or, if default target is given, - // then the target is deemed (|node| is null) and we should use the default - // target. + // scalar value (for example, `0` in `AXChildren[0]`) and thus nothing to + // invoke or, if default target is given, i.e. |node| is not null, then + // the target is deemed and we use the default target. The latter case is + // about ax tree dumping where a scripting instruction with no target can be + // used. For example, `AXRole` property filter means it is applied to all + // nodes and `AXRole` attribute should be called for all nodes in the tree. if (!target) { if (property_node.IsTarget()) return OptionalNSObject::Error(); @@ -131,14 +149,15 @@ // Invoke the call chain. while (current_node) { auto target_optional = InvokeFor(target, *current_node); + // Result of the current step is either null or error. Don't go any further. if (!target_optional.IsNotNil()) { - LOG(ERROR) << "Null result of " << current_node->ToFlatString(); return target_optional; } target = *target_optional; current_node = current_node->next.get(); } + // Variable case: store the variable value in the storage. if (!property_node.key.empty()) (*storage_)[property_node.key] = target;
diff --git a/content/browser/browser_main.cc b/content/browser/browser_main.cc index 65668ab..55ae5cd 100644 --- a/content/browser/browser_main.cc +++ b/content/browser/browser_main.cc
@@ -20,10 +20,12 @@ class ScopedBrowserMainEvent { public: ScopedBrowserMainEvent() { - TRACE_EVENT_ASYNC_BEGIN0("startup", "BrowserMain", 0); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("startup", "BrowserMain", + TRACE_ID_WITH_SCOPE("BrowserMain", 0)); } ~ScopedBrowserMainEvent() { - TRACE_EVENT_ASYNC_END0("startup", "BrowserMain", 0); + TRACE_EVENT_NESTABLE_ASYNC_END0("startup", "BrowserMain", + TRACE_ID_WITH_SCOPE("BrowserMain", 0)); } };
diff --git a/content/browser/browsing_data/browsing_data_remover_impl.cc b/content/browser/browsing_data/browsing_data_remover_impl.cc index 2579a536..495b790 100644 --- a/content/browser/browsing_data/browsing_data_remover_impl.cc +++ b/content/browser/browsing_data/browsing_data_remover_impl.cc
@@ -703,9 +703,11 @@ size_t num_erased = pending_sub_tasks_.erase(data_type); DCHECK_EQ(num_erased, 1U); - TRACE_EVENT_ASYNC_END1("browsing_data", "BrowsingDataRemoverImpl", - static_cast<int>(data_type), "data_type", - static_cast<int>(data_type)); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "browsing_data", "BrowsingDataRemoverImpl", + TRACE_ID_WITH_SCOPE("BrowsingDataRemoverImpl", + static_cast<int>(data_type)), + "data_type", static_cast<int>(data_type)); if (!pending_sub_tasks_.empty()) return; @@ -744,9 +746,11 @@ auto result = pending_sub_tasks_.insert(data_type); DCHECK(result.second) << "Task already started: " << static_cast<int>(data_type); - TRACE_EVENT_ASYNC_BEGIN1("browsing_data", "BrowsingDataRemoverImpl", - static_cast<int>(data_type), "data_type", - static_cast<int>(data_type)); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "browsing_data", "BrowsingDataRemoverImpl", + TRACE_ID_WITH_SCOPE("BrowsingDataRemoverImpl", + static_cast<int>(data_type)), + "data_type", static_cast<int>(data_type)); return base::BindOnce(&BrowsingDataRemoverImpl::OnTaskComplete, GetWeakPtr(), data_type); }
diff --git a/content/browser/client_hints/client_hints.cc b/content/browser/client_hints/client_hints.cc index 0f47772..b74edd57 100644 --- a/content/browser/client_hints/client_hints.cc +++ b/content/browser/client_hints/client_hints.cc
@@ -386,6 +386,10 @@ features::kPrefersColorSchemeClientHintHeader); } +bool UserAgentClientHintEnabled() { + return base::FeatureList::IsEnabled(features::kUserAgentClientHint); +} + void AddUAHeader(net::HttpRequestHeaders* headers, network::mojom::WebClientHintsType type, const std::string& value) { @@ -611,7 +615,7 @@ FrameTreeNode* frame_tree_node, net::HttpRequestHeaders* headers) { DCHECK(frame_tree_node); - if (!delegate->UserAgentClientHintEnabled() || + if (!UserAgentClientHintEnabled() || !ShouldAddClientHints(url, frame_tree_node, delegate)) { return; } @@ -669,7 +673,7 @@ AddLangHeader(headers, context); } - if (delegate->UserAgentClientHintEnabled()) { + if (UserAgentClientHintEnabled()) { UpdateNavigationRequestClientUaHeadersImpl( url, delegate, is_ua_override_on, frame_tree_node, ClientUaHeaderCallType::kDuringCreation, headers); @@ -780,7 +784,7 @@ absl::optional<std::vector<network::mojom::WebClientHintsType>> parsed = blink::FilterAcceptCH(headers->accept_ch.value(), LangClientHintEnabled(), - delegate->UserAgentClientHintEnabled(), + UserAgentClientHintEnabled(), PrefersColorSchemeClientHintEnabled()); if (!parsed.has_value()) return absl::nullopt;
diff --git a/content/browser/devtools/protocol/input_handler.cc b/content/browser/devtools/protocol/input_handler.cc index db2b991..2654c86 100644 --- a/content/browser/devtools/protocol/input_handler.cc +++ b/content/browser/devtools/protocol/input_handler.cc
@@ -1604,8 +1604,9 @@ if (!interaction_marker_name.empty()) { // TODO(alexclarke): Can we move this elsewhere? It doesn't really fit here. - TRACE_EVENT_COPY_ASYNC_BEGIN0("benchmark", interaction_marker_name.c_str(), - id); + TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN0( + "benchmark", interaction_marker_name.c_str(), + TRACE_ID_WITH_SCOPE(interaction_marker_name.c_str(), id)); } root_view->host()->QueueSyntheticGesture( @@ -1625,8 +1626,9 @@ std::unique_ptr<SynthesizeScrollGestureCallback> callback, SyntheticGesture::Result result) { if (!interaction_marker_name.empty()) { - TRACE_EVENT_COPY_ASYNC_END0("benchmark", interaction_marker_name.c_str(), - id); + TRACE_EVENT_COPY_NESTABLE_ASYNC_END0( + "benchmark", interaction_marker_name.c_str(), + TRACE_ID_WITH_SCOPE(interaction_marker_name.c_str(), id)); } if (repeat_count > 0) {
diff --git a/content/browser/file_system_access/file_system_access_access_handle_host_impl.cc b/content/browser/file_system_access/file_system_access_access_handle_host_impl.cc new file mode 100644 index 0000000..5204774 --- /dev/null +++ b/content/browser/file_system_access/file_system_access_access_handle_host_impl.cc
@@ -0,0 +1,41 @@ +// Copyright 2021 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/file_system_access/file_system_access_access_handle_host_impl.h" + +namespace content { + +FileSystemAccessAccessHandleHostImpl::FileSystemAccessAccessHandleHostImpl( + FileSystemAccessManagerImpl* manager, + base::PassKey<FileSystemAccessManagerImpl> /*pass_key*/, + mojo::PendingReceiver<blink::mojom::FileSystemAccessAccessHandleHost> + receiver) + : receiver_(this, std::move(receiver)), manager_(manager) { + DCHECK(manager_); + + receiver_.set_disconnect_handler( + base::BindOnce(&FileSystemAccessAccessHandleHostImpl::OnDisconnect, + base::Unretained(this))); +} + +FileSystemAccessAccessHandleHostImpl::~FileSystemAccessAccessHandleHostImpl() = + default; + +void FileSystemAccessAccessHandleHostImpl::Close(CloseCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + std::move(callback).Run(); + + receiver_.reset(); + manager_->RemoveAccessHandleHost(this); +} + +void FileSystemAccessAccessHandleHostImpl::OnDisconnect() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + receiver_.reset(); + manager_->RemoveAccessHandleHost(this); +} + +} // namespace content
diff --git a/content/browser/file_system_access/file_system_access_access_handle_host_impl.h b/content/browser/file_system_access/file_system_access_access_handle_host_impl.h new file mode 100644 index 0000000..869a6dfe --- /dev/null +++ b/content/browser/file_system_access/file_system_access_access_handle_host_impl.h
@@ -0,0 +1,53 @@ +// Copyright 2021 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_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_ACCESS_HANDLE_HOST_IMPL_H_ +#define CONTENT_BROWSER_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_ACCESS_HANDLE_HOST_IMPL_H_ + +#include "content/browser/file_system_access/file_system_access_manager_impl.h" +#include "content/common/content_export.h" +#include "third_party/blink/public/mojom/file_system_access/file_system_access_access_handle_host.mojom.h" + +namespace content { + +// This is the browser side implementation of the +// FileSystemAccessHandleHost mojom interface. Instances of this class are +// owned by the FileSystemAccessManagerImpl instance passed in to the +// constructor. +class CONTENT_EXPORT FileSystemAccessAccessHandleHostImpl + : public blink::mojom::FileSystemAccessAccessHandleHost { + public: + // Crates an AccessHandleHost that acts as an exclusive write lock on the + // file. AccessHandleHosts should only be created via the + // FileSystemAccessManagerImpl. + FileSystemAccessAccessHandleHostImpl( + FileSystemAccessManagerImpl* manager, + base::PassKey<FileSystemAccessManagerImpl> pass_key, + mojo::PendingReceiver<blink::mojom::FileSystemAccessAccessHandleHost> + receiver); + FileSystemAccessAccessHandleHostImpl( + const FileSystemAccessAccessHandleHostImpl&) = delete; + FileSystemAccessAccessHandleHostImpl& operator=( + const FileSystemAccessAccessHandleHostImpl&) = delete; + ~FileSystemAccessAccessHandleHostImpl() override; + + // blink::mojom::FileSystemAccessFileHandleHost: + void Close(CloseCallback callback) override; + + private: + // If the mojo pipe is severed before Close() is invoked, the lock will be + // released from the OnDisconnect method. + void OnDisconnect(); + + mojo::Receiver<blink::mojom::FileSystemAccessAccessHandleHost> receiver_; + + // The FileSystemAccessManagerImpl that owns this instance. + FileSystemAccessManagerImpl* const manager_; + + SEQUENCE_CHECKER(sequence_checker_); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_ACCESS_HANDLE_HOST_IMPL_H_
diff --git a/content/browser/file_system_access/file_system_access_file_handle_impl.cc b/content/browser/file_system_access/file_system_access_file_handle_impl.cc index 47c20bcb..984414d 100644 --- a/content/browser/file_system_access/file_system_access_file_handle_impl.cc +++ b/content/browser/file_system_access/file_system_access_file_handle_impl.cc
@@ -9,6 +9,7 @@ #include "base/guid.h" #include "base/logging.h" #include "base/strings/stringprintf.h" +#include "content/browser/file_system_access/file_system_access_access_handle_host_impl.h" #include "content/browser/file_system_access/file_system_access_error.h" #include "content/browser/file_system_access/file_system_access_handle_base.h" #include "content/browser/file_system_access/file_system_access_transfer_token_impl.h" @@ -154,11 +155,11 @@ if (!IsAccessHandleEnabled()) { mojo::ReportBadMessage("File System Access Access Handle not enabled"); - std::move(callback).Run( - file_system_access_error::FromStatus( - FileSystemAccessStatus::kInvalidState, - "File System Access Access Handle not enabled"), - blink::mojom::FileSystemAccessAccessHandleFilePtr()); + std::move(callback).Run(file_system_access_error::FromStatus( + FileSystemAccessStatus::kInvalidState, + "File System Access Access Handle not enabled"), + blink::mojom::FileSystemAccessAccessHandleFilePtr(), + mojo::NullRemote()); return; } @@ -167,7 +168,8 @@ file_system_access_error::FromStatus( FileSystemAccessStatus::kInvalidState, "Access handles may only be created on temporary file systems"), - blink::mojom::FileSystemAccessAccessHandleFilePtr()); + blink::mojom::FileSystemAccessAccessHandleFilePtr(), + mojo::NullRemote()); return; } @@ -183,7 +185,8 @@ OpenAccessHandleCallback callback) { std::move(callback).Run( std::move(result), - blink::mojom::FileSystemAccessAccessHandleFilePtr()); + blink::mojom::FileSystemAccessAccessHandleFilePtr(), + mojo::NullRemote()); }), std::move(callback)); } @@ -200,10 +203,14 @@ file_delegate_host_receiver = file_delegate_host_remote.InitWithNewPipeAndPassReceiver(); + mojo::PendingRemote<blink::mojom::FileSystemAccessAccessHandleHost> + access_handle_host_remote = manager()->CreateAccessHandleHost(url()); + std::move(callback).Run( file_system_access_error::Ok(), blink::mojom::FileSystemAccessAccessHandleFile::NewIncognitoFileDelegate( - std::move(file_delegate_host_remote))); + std::move(file_delegate_host_remote)), + std::move(access_handle_host_remote)); } void FileSystemAccessFileHandleImpl::DoOpenFile( @@ -226,12 +233,16 @@ base::OnceClosure /*on_close_callback*/) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + mojo::PendingRemote<blink::mojom::FileSystemAccessAccessHandleHost> + access_handle_host_remote = manager()->CreateAccessHandleHost(url()); + blink::mojom::FileSystemAccessErrorPtr result = file_system_access_error::FromFileError(file.error_details()); std::move(callback).Run( std::move(result), blink::mojom::FileSystemAccessAccessHandleFile::NewRegularFile( - std::move(file))); + std::move(file)), + std::move(access_handle_host_remote)); } void FileSystemAccessFileHandleImpl::IsSameEntry(
diff --git a/content/browser/file_system_access/file_system_access_file_handle_impl_unittest.cc b/content/browser/file_system_access/file_system_access_file_handle_impl_unittest.cc index 941c8ab..bb83aace 100644 --- a/content/browser/file_system_access/file_system_access_file_handle_impl_unittest.cc +++ b/content/browser/file_system_access/file_system_access_file_handle_impl_unittest.cc
@@ -266,12 +266,16 @@ handle_->OpenAccessHandle( base::BindLambdaForTesting( [&](blink::mojom::FileSystemAccessErrorPtr result, - blink::mojom::FileSystemAccessAccessHandleFilePtr file) { + blink::mojom::FileSystemAccessAccessHandleFilePtr file, + mojo::PendingRemote< + blink::mojom::FileSystemAccessAccessHandleHost> + access_handle_remote) { EXPECT_EQ(result->status, blink::mojom::FileSystemAccessStatus::kOk); // File should be valid and no incognito remote is needed. EXPECT_TRUE(file->is_regular_file()); EXPECT_TRUE(file->get_regular_file().IsValid()); + EXPECT_TRUE(access_handle_remote.is_valid()); }) .Then(loop.QuitClosure())); loop.Run(); @@ -282,12 +286,16 @@ handle_->OpenAccessHandle( base::BindLambdaForTesting( [&](blink::mojom::FileSystemAccessErrorPtr result, - blink::mojom::FileSystemAccessAccessHandleFilePtr file) { + blink::mojom::FileSystemAccessAccessHandleFilePtr file, + mojo::PendingRemote< + blink::mojom::FileSystemAccessAccessHandleHost> + access_handle_remote) { EXPECT_EQ(result->status, blink::mojom::FileSystemAccessStatus::kOk); // Incognito remote should be valid and no file is needed. EXPECT_TRUE(file->is_incognito_file_delegate()); EXPECT_TRUE(file->get_incognito_file_delegate().is_valid()); + EXPECT_TRUE(access_handle_remote.is_valid()); }) .Then(loop.QuitClosure())); loop.Run();
diff --git a/content/browser/file_system_access/file_system_access_manager_impl.cc b/content/browser/file_system_access/file_system_access_manager_impl.cc index e317b66..375f405 100644 --- a/content/browser/file_system_access/file_system_access_manager_impl.cc +++ b/content/browser/file_system_access/file_system_access_manager_impl.cc
@@ -22,6 +22,7 @@ #include "base/task/thread_pool.h" #include "build/build_config.h" #include "content/browser/file_system_access/file_system_access.pb.h" +#include "content/browser/file_system_access/file_system_access_access_handle_host_impl.h" #include "content/browser/file_system_access/file_system_access_data_transfer_token_impl.h" #include "content/browser/file_system_access/file_system_access_directory_handle_impl.h" #include "content/browser/file_system_access/file_system_access_error.h" @@ -927,6 +928,23 @@ return writer_weak; } +mojo::PendingRemote<blink::mojom::FileSystemAccessAccessHandleHost> +FileSystemAccessManagerImpl::CreateAccessHandleHost( + const storage::FileSystemURL& /*url*/) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + mojo::PendingRemote<blink::mojom::FileSystemAccessAccessHandleHost> result; + auto receiver = result.InitWithNewPipeAndPassReceiver(); + + auto handle = std::make_unique<FileSystemAccessAccessHandleHostImpl>( + this, PassKey(), std::move(receiver)); + access_handle_host_receivers_.insert(std::move(handle)); + + // TODO(fivedots): Register an access handle (exclusive) lock on the provided + // URL. + return result; +} + void FileSystemAccessManagerImpl::CreateTransferToken( const FileSystemAccessFileHandleImpl& file, mojo::PendingReceiver<blink::mojom::FileSystemAccessTransferToken> @@ -1264,6 +1282,14 @@ DCHECK_EQ(1u, count_removed); } +void FileSystemAccessManagerImpl::RemoveAccessHandleHost( + FileSystemAccessAccessHandleHostImpl* access_handle) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + size_t count_removed = access_handle_host_receivers_.erase(access_handle); + DCHECK_EQ(1u, count_removed); +} + void FileSystemAccessManagerImpl::RemoveToken( const base::UnguessableToken& token) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
diff --git a/content/browser/file_system_access/file_system_access_manager_impl.h b/content/browser/file_system_access/file_system_access_manager_impl.h index 82b2625..21f46fde 100644 --- a/content/browser/file_system_access/file_system_access_manager_impl.h +++ b/content/browser/file_system_access/file_system_access_manager_impl.h
@@ -26,6 +26,7 @@ #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/bindings/unique_receiver_set.h" #include "storage/browser/file_system/file_system_url.h" +#include "third_party/blink/public/mojom/file_system_access/file_system_access_access_handle_host.mojom.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_data_transfer_token.mojom.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_file_writer.mojom.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom.h" @@ -42,6 +43,7 @@ class FileSystemAccessTransferTokenImpl; class FileSystemAccessDataTransferTokenImpl; class FileSystemAccessFileWriterImpl; +class FileSystemAccessAccessHandleHostImpl; class StoragePartitionImpl; // This is the browser side implementation of the @@ -84,7 +86,7 @@ const storage::IsolatedContext::ScopedFSHandle file_system; }; - // The caller is responsible for ensuring that |permission_context| outlives + // The caller is responsible for ensuring that `permission_context` outlives // this instance. FileSystemAccessManagerImpl( scoped_refptr<storage::FileSystemContext> context, @@ -176,6 +178,10 @@ bool auto_close, download::QuarantineConnectionCallback quarantine_connection_callback); + // Creates a new FileSystemAccessHandleHost for a given URL. + mojo::PendingRemote<blink::mojom::FileSystemAccessAccessHandleHost> + CreateAccessHandleHost(const storage::FileSystemURL& url); + // Create a transfer token for a specific file or directory. void CreateTransferToken( const FileSystemAccessFileHandleImpl& file, @@ -230,11 +236,16 @@ auto_file_picker_result_for_test_ = result_entry; } - // Remove |writer| from |writer_receivers|. It is an error to try to remove + // Remove `writer` from `writer_receivers_`. It is an error to try to remove // a writer that doesn't exist. void RemoveFileWriter(FileSystemAccessFileWriterImpl* writer); - // Remove |token| from |transfer_tokens_|. It is an error to try to remove + // Remove `access_handle` from `access_handle_host_receivers_`. It is an error + // to try to remove an access handle that doesn't exist. + void RemoveAccessHandleHost( + FileSystemAccessAccessHandleHostImpl* access_handle); + + // Remove `token` from `transfer_tokens_`. It is an error to try to remove // a token that doesn't exist. void RemoveToken(const base::UnguessableToken& token); @@ -384,6 +395,9 @@ base::flat_set<std::unique_ptr<FileSystemAccessFileWriterImpl>, base::UniquePtrComparator> writer_receivers_; + base::flat_set<std::unique_ptr<FileSystemAccessAccessHandleHostImpl>, + base::UniquePtrComparator> + access_handle_host_receivers_; bool off_the_record_;
diff --git a/content/browser/indexed_db/indexed_db_tracing.h b/content/browser/indexed_db/indexed_db_tracing.h index f70bee7e..11a2cb9 100644 --- a/content/browser/indexed_db/indexed_db_tracing.h +++ b/content/browser/indexed_db/indexed_db_tracing.h
@@ -15,9 +15,9 @@ TRACE_EVENT2("IndexedDB", (a), (b), (b_val), (c), (c_val)); #define IDB_ASYNC_TRACE_BEGIN(a, id) \ - TRACE_EVENT_ASYNC_BEGIN0("IndexedDB", (a), (id)); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("IndexedDB", (a), (id)); #define IDB_ASYNC_TRACE_END(a, id) \ - TRACE_EVENT_ASYNC_END0("IndexedDB", (a), (id)); + TRACE_EVENT_NESTABLE_ASYNC_END0("IndexedDB", (a), (id)); #define IDB_TRACE_COUNTER1(a, value) TRACE_COUNTER1("IndexedDB", (a), (value))
diff --git a/content/browser/loader/navigation_url_loader_impl.cc b/content/browser/loader/navigation_url_loader_impl.cc index 08ebbef..9e01ff17 100644 --- a/content/browser/loader/navigation_url_loader_impl.cc +++ b/content/browser/loader/navigation_url_loader_impl.cc
@@ -1158,8 +1158,8 @@ download_policy_(request_info_->common_params->download_policy) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1( - "navigation", "Navigation timeToResponseStarted", this, + TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP1( + "navigation", "Navigation timeToResponseStarted", TRACE_ID_LOCAL(this), request_info_->common_params->navigation_start, "FrameTreeNode id", frame_tree_node_id_); @@ -1324,9 +1324,9 @@ // TODO(https://crbug.com/1068896): Remove // "Navigation.NavigationURLLoaderImplIOPostTime" histogram as well. - TRACE_EVENT_ASYNC_END2("navigation", "Navigation timeToResponseStarted", this, - "&NavigationURLLoaderImpl", static_cast<void*>(this), - "success", true); + TRACE_EVENT_NESTABLE_ASYNC_END2( + "navigation", "Navigation timeToResponseStarted", TRACE_ID_LOCAL(this), + "&NavigationURLLoaderImpl", static_cast<void*>(this), "success", true); if (is_download) download_policy_.RecordHistogram(); @@ -1366,9 +1366,9 @@ void NavigationURLLoaderImpl::NotifyRequestFailed( const network::URLLoaderCompletionStatus& status) { - TRACE_EVENT_ASYNC_END2("navigation", "Navigation timeToResponseStarted", this, - "&NavigationURLLoaderImpl", static_cast<void*>(this), - "success", false); + TRACE_EVENT_NESTABLE_ASYNC_END2( + "navigation", "Navigation timeToResponseStarted", TRACE_ID_LOCAL(this), + "&NavigationURLLoaderImpl", static_cast<void*>(this), "success", false); delegate_->OnRequestFailed(status); }
diff --git a/content/browser/navigation_browsertest.cc b/content/browser/navigation_browsertest.cc index c2a46356..72d22a315 100644 --- a/content/browser/navigation_browsertest.cc +++ b/content/browser/navigation_browsertest.cc
@@ -1668,7 +1668,7 @@ WebContentsConsoleObserver console_observer(web_contents()); console_observer.SetPattern( "Throttling navigation to prevent the browser from hanging. See " - "https://crbug.com/882238. Command line switch " + "https://crbug.com/1038223. Command line switch " "--disable-ipc-flooding-protection can be used to bypass the " "protection"); @@ -1695,7 +1695,7 @@ WebContentsConsoleObserver console_observer(web_contents()); console_observer.SetPattern( "Throttling navigation to prevent the browser from hanging. See " - "https://crbug.com/882238. Command line switch " + "https://crbug.com/1038223. Command line switch " "--disable-ipc-flooding-protection can be used to bypass the " "protection");
diff --git a/content/browser/prerender/prerender_host.cc b/content/browser/prerender/prerender_host.cc index 2c790181..23fdc572 100644 --- a/content/browser/prerender/prerender_host.cc +++ b/content/browser/prerender/prerender_host.cc
@@ -106,6 +106,13 @@ } ~PageHolder() override { + // If we are still waiting on test loop, we can assume the page loading step + // has been cancelled and the PageHolder is being discarded without + // completing loading the page. + if (on_wait_loading_finished_) + std::move(on_wait_loading_finished_) + .Run(PrerenderHost::LoadingOutcome::kPrerenderingCancelled); + if (frame_tree_) frame_tree_->Shutdown(); } @@ -120,8 +127,9 @@ bool to_different_document) override {} void DidStopLoading() override { - if (on_stopped_loading_for_tests_) { - std::move(on_stopped_loading_for_tests_).Run(); + if (on_wait_loading_finished_) { + std::move(on_wait_loading_finished_) + .Run(PrerenderHost::LoadingOutcome::kLoadingCompleted); } } @@ -218,24 +226,38 @@ return ActivateResult(FinalStatus::kActivated, std::move(page)); } - void WaitForLoadCompletionForTesting() { + PrerenderHost::LoadingOutcome WaitForLoadCompletionForTesting() { + PrerenderHost::LoadingOutcome status = + PrerenderHost::LoadingOutcome::kLoadingCompleted; if (!frame_tree_->IsLoading()) - return; + return status; base::RunLoop loop; - on_stopped_loading_for_tests_ = loop.QuitClosure(); + on_wait_loading_finished_ = + base::BindOnce(&PrerenderHost::PageHolder::FinishWaitingForTesting, + loop.QuitClosure(), &status); loop.Run(); + return status; } FrameTree* frame_tree() { return frame_tree_.get(); } private: + static void FinishWaitingForTesting(base::OnceClosure on_close, // IN-TEST + PrerenderHost::LoadingOutcome* result, + PrerenderHost::LoadingOutcome status) { + *result = status; + std::move(on_close).Run(); + } + // WebContents where this prerenderer is embedded. WebContentsImpl& web_contents_; - // This can be called when |frame_tree_| is destroyed so it must be - // destructed after |frame_tree_|. - base::OnceClosure on_stopped_loading_for_tests_; + // Used for testing, this closure is only set when waiting a page to be + // either loaded for pre-rendering. |frame_tree_| provides us with a trigger + // for when the page is loaded. + base::OnceCallback<void(PrerenderHost::LoadingOutcome)> + on_wait_loading_finished_; // Frame tree created for the prerenderer to load the page and prepare it for // a future activation. During activation, the prerendered page will be taken @@ -581,8 +603,8 @@ page_holder_->frame_tree()->root()->frame_tree_node_id(); } -void PrerenderHost::WaitForLoadStopForTesting() { - page_holder_->WaitForLoadCompletionForTesting(); // IN-TEST +PrerenderHost::LoadingOutcome PrerenderHost::WaitForLoadStopForTesting() { + return page_holder_->WaitForLoadCompletionForTesting(); // IN-TEST } void PrerenderHost::RecordFinalStatus(FinalStatus status) {
diff --git a/content/browser/prerender/prerender_host.h b/content/browser/prerender/prerender_host.h index 4a29855..1e81f51 100644 --- a/content/browser/prerender/prerender_host.h +++ b/content/browser/prerender/prerender_host.h
@@ -119,8 +119,14 @@ void RecordFinalStatus(base::PassKey<PrerenderHostRegistry>, FinalStatus status); - // Waits until the page load finishes. - void WaitForLoadStopForTesting(); + enum class LoadingOutcome { + kLoadingCompleted, + kPrerenderingCancelled, + }; + + // Waits until the page load finishes. Returns the loading status indicating + // how the operation was finished. + LoadingOutcome WaitForLoadStopForTesting(); const GURL& GetInitialUrl() const; @@ -139,6 +145,10 @@ bool is_ready_for_activation() const { return is_ready_for_activation_; } + const absl::optional<FinalStatus>& final_status() const { + return final_status_; + } + private: class PageHolder;
diff --git a/content/browser/renderer_host/media/media_stream_dispatcher_host.h b/content/browser/renderer_host/media/media_stream_dispatcher_host.h index 88fff65..01424dbe 100644 --- a/content/browser/renderer_host/media/media_stream_dispatcher_host.h +++ b/content/browser/renderer_host/media/media_stream_dispatcher_host.h
@@ -24,7 +24,7 @@ // MediaStreamDispatcherHost is a delegate for Media Stream API messages used by // MediaStreamImpl. There is one MediaStreamDispatcherHost per -// RenderProcessHost, the former owned by the latter. +// RenderFrameHost, the former owned by the latter. class CONTENT_EXPORT MediaStreamDispatcherHost : public blink::mojom::MediaStreamDispatcherHost { public:
diff --git a/content/browser/renderer_host/render_widget_targeter.cc b/content/browser/renderer_host/render_widget_targeter.cc index 10eb52cb..ffb600b 100644 --- a/content/browser/renderer_host/render_widget_targeter.cc +++ b/content/browser/renderer_host/render_widget_targeter.cc
@@ -59,7 +59,7 @@ : id_(next_id_++), start_time_(base::TimeTicks::Now()), metric_name_(metric_name) { - TRACE_EVENT_ASYNC_BEGIN0( + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( kTracingCategory, metric_name_, TRACE_ID_WITH_SCOPE("UmaTracker", TRACE_ID_LOCAL(id_))); } @@ -67,7 +67,7 @@ TracingUmaTracker(TracingUmaTracker&& tracker) = default; void StopAndRecord() { - TRACE_EVENT_ASYNC_END0( + TRACE_EVENT_NESTABLE_ASYNC_END0( kTracingCategory, metric_name_, TRACE_ID_WITH_SCOPE("UmaTracker", TRACE_ID_LOCAL(id_))); UmaHistogramTimes(metric_name_, base::TimeTicks::Now() - start_time_);
diff --git a/content/browser/service_worker/service_worker_container_host.cc b/content/browser/service_worker/service_worker_container_host.cc index 5aca9f4..8249863 100644 --- a/content/browser/service_worker/service_worker_container_host.cc +++ b/content/browser/service_worker/service_worker_container_host.cc
@@ -192,8 +192,9 @@ } int64_t trace_id = base::TimeTicks::Now().since_origin().InMicroseconds(); - TRACE_EVENT_ASYNC_BEGIN2( - "ServiceWorker", "ServiceWorkerContainerHost::Register", trace_id, + TRACE_EVENT_NESTABLE_ASYNC_BEGIN2( + "ServiceWorker", "ServiceWorkerContainerHost::Register", + TRACE_ID_WITH_SCOPE("ServiceWorkerContainerHost::Register", trace_id), "Scope", options->scope.spec(), "Script URL", script_url.spec()); // Wrap the callback with default invoke before passing it, since @@ -257,9 +258,11 @@ } int64_t trace_id = base::TimeTicks::Now().since_origin().InMicroseconds(); - TRACE_EVENT_ASYNC_BEGIN1("ServiceWorker", - "ServiceWorkerContainerHost::GetRegistration", - trace_id, "Client URL", client_url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "ServiceWorker", "ServiceWorkerContainerHost::GetRegistration", + TRACE_ID_WITH_SCOPE("ServiceWorkerContainerHost::GetRegistration", + trace_id), + "Client URL", client_url.spec()); // The client_url may be cross-origin if "disable-web-security" is active, // make sure we get the correct key. @@ -295,9 +298,10 @@ } int64_t trace_id = base::TimeTicks::Now().since_origin().InMicroseconds(); - TRACE_EVENT_ASYNC_BEGIN0("ServiceWorker", - "ServiceWorkerContainerHost::GetRegistrations", - trace_id); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( + "ServiceWorker", "ServiceWorkerContainerHost::GetRegistrations", + TRACE_ID_WITH_SCOPE("ServiceWorkerContainerHost::GetRegistrations", + trace_id)); context_->registry()->GetRegistrationsForStorageKey( key_, base::BindOnce( &ServiceWorkerContainerHost::GetRegistrationsComplete, @@ -317,9 +321,9 @@ return; } - TRACE_EVENT_ASYNC_BEGIN0( + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( "ServiceWorker", "ServiceWorkerContainerHost::GetRegistrationForReady", - this); + TRACE_ID_LOCAL(this)); DCHECK(!get_ready_callback_); get_ready_callback_ = std::make_unique<GetRegistrationForReadyCallback>(std::move(callback)); @@ -1208,9 +1212,9 @@ ServiceWorkerRegistration* registration = MatchRegistration(); if (!registration || !registration->active_version()) return; - TRACE_EVENT_ASYNC_END1("ServiceWorker", - "ServiceWorkerContainerHost::GetRegistrationForReady", - this, "Registration ID", registration->id()); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "ServiceWorker", "ServiceWorkerContainerHost::GetRegistrationForReady", + TRACE_ID_LOCAL(this), "Registration ID", registration->id()); if (!context_) { // Here no need to run or destroy |get_ready_callback_|, which will destroy // together with |receiver_| when |this| destroys. @@ -1369,10 +1373,11 @@ int64_t registration_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - TRACE_EVENT_ASYNC_END2("ServiceWorker", - "ServiceWorkerContainerHost::Register", trace_id, - "Status", blink::ServiceWorkerStatusToString(status), - "Registration ID", registration_id); + TRACE_EVENT_NESTABLE_ASYNC_END2( + "ServiceWorker", "ServiceWorkerContainerHost::Register", + TRACE_ID_WITH_SCOPE("ServiceWorkerContainerHost::Register", trace_id), + "Status", blink::ServiceWorkerStatusToString(status), "Registration ID", + registration_id); // kErrorInvalidArguments means the renderer gave unexpectedly bad arguments, // so terminate it. @@ -1430,8 +1435,10 @@ scoped_refptr<ServiceWorkerRegistration> registration) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - TRACE_EVENT_ASYNC_END2( - "ServiceWorker", "ServiceWorkerContainerHost::GetRegistration", trace_id, + TRACE_EVENT_NESTABLE_ASYNC_END2( + "ServiceWorker", "ServiceWorkerContainerHost::GetRegistration", + TRACE_ID_WITH_SCOPE("ServiceWorkerContainerHost::GetRegistration", + trace_id), "Status", blink::ServiceWorkerStatusToString(status), "Registration ID", registration ? registration->id() : blink::mojom::kInvalidServiceWorkerRegistrationId); @@ -1479,8 +1486,10 @@ registrations) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - TRACE_EVENT_ASYNC_END1( - "ServiceWorker", "ServiceWorkerContainerHost::GetRegistrations", trace_id, + TRACE_EVENT_NESTABLE_ASYNC_END1( + "ServiceWorker", "ServiceWorkerContainerHost::GetRegistrations", + TRACE_ID_WITH_SCOPE("ServiceWorkerContainerHost::GetRegistrations", + trace_id), "Status", blink::ServiceWorkerStatusToString(status)); if (!context_) {
diff --git a/content/browser/service_worker/service_worker_registry.cc b/content/browser/service_worker/service_worker_registry.cc index c1f61a4..72bf1c9 100644 --- a/content/browser/service_worker/service_worker_registry.cc +++ b/content/browser/service_worker/service_worker_registry.cc
@@ -199,9 +199,11 @@ // trace event id. int64_t trace_event_id = base::Time::Now().ToDeltaSinceWindowsEpoch().InMicroseconds(); - TRACE_EVENT_ASYNC_BEGIN1( + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( "ServiceWorker", "ServiceWorkerRegistry::FindRegistrationForClientUrl", - trace_event_id, "URL", client_url.spec()); + TRACE_ID_WITH_SCOPE("ServiceWorkerRegistry::FindRegistrationForClientUrl", + trace_event_id), + "URL", client_url.spec()); CreateInvokerAndStartRemoteCall( &storage::mojom::ServiceWorkerStorageControl:: FindRegistrationForClientUrl, @@ -920,9 +922,12 @@ installing_registration->is_deleted() ? blink::ServiceWorkerStatusCode::kErrorNotFound : blink::ServiceWorkerStatusCode::kOk; - TRACE_EVENT_ASYNC_END2( + TRACE_EVENT_NESTABLE_ASYNC_END2( "ServiceWorker", - "ServiceWorkerRegistry::FindRegistrationForClientUrl", trace_event_id, + "ServiceWorkerRegistry::FindRegistrationForClientUrl", + TRACE_ID_WITH_SCOPE( + "ServiceWorkerRegistry::FindRegistrationForClientUrl", + trace_event_id), "Status", blink::ServiceWorkerStatusToString(status), "Info", (installing_status == blink::ServiceWorkerStatusCode::kOk) ? "Installing registration is found" @@ -950,9 +955,11 @@ } } - TRACE_EVENT_ASYNC_END1( + TRACE_EVENT_NESTABLE_ASYNC_END1( "ServiceWorker", "ServiceWorkerRegistry::FindRegistrationForClientUrl", - trace_event_id, "Status", blink::ServiceWorkerStatusToString(status)); + TRACE_ID_WITH_SCOPE("ServiceWorkerRegistry::FindRegistrationForClientUrl", + trace_event_id), + "Status", blink::ServiceWorkerStatusToString(status)); CompleteFindNow(std::move(registration), status, std::move(callback)); }
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index bd7f1cab..a95e76a 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -639,10 +639,10 @@ event_type); InflightRequest* request_rawptr = request.get(); int request_id = inflight_requests_.Add(std::move(request)); - TRACE_EVENT_ASYNC_BEGIN2("ServiceWorker", "ServiceWorkerVersion::Request", - request_rawptr, "Request id", request_id, - "Event type", - ServiceWorkerMetrics::EventTypeToString(event_type)); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN2( + "ServiceWorker", "ServiceWorkerVersion::Request", + TRACE_ID_LOCAL(request_rawptr), "Request id", request_id, "Event type", + ServiceWorkerMetrics::EventTypeToString(event_type)); base::TimeTicks expiration_time = tick_clock_->NowTicks() + timeout; bool is_inserted = false; @@ -701,8 +701,9 @@ request->event_type, tick_clock_->NowTicks() - request->start_time_ticks, was_handled, fetch_count); - TRACE_EVENT_ASYNC_END1("ServiceWorker", "ServiceWorkerVersion::Request", - request, "Handled", was_handled); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "ServiceWorker", "ServiceWorkerVersion::Request", TRACE_ID_LOCAL(request), + "Handled", was_handled); request_timeouts_.erase(request->timeout_iter); inflight_requests_.Remove(request_id); @@ -1240,10 +1241,12 @@ void ServiceWorkerVersion::OnStopping() { DCHECK(stop_time_.is_null()); RestartTick(&stop_time_); - TRACE_EVENT_ASYNC_BEGIN2("ServiceWorker", "ServiceWorkerVersion::StopWorker", - stop_time_.since_origin().InMicroseconds(), "Script", - script_url_.spec(), "Version Status", - VersionStatusToString(status_)); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN2( + "ServiceWorker", "ServiceWorkerVersion::StopWorker", + TRACE_ID_WITH_SCOPE("ServiceWorkerVersion::StopWorker", + stop_time_.since_origin().InMicroseconds()), + "Script", script_url_.spec(), "Version Status", + VersionStatusToString(status_)); // Endpoint isn't available after calling EmbeddedWorkerInstance::Stop(). // This needs to be set here without waiting until the worker is actually @@ -1317,9 +1320,11 @@ base::span<const uint8_t> data) { int64_t callback_id = base::Time::Now().ToDeltaSinceWindowsEpoch().InMicroseconds(); - TRACE_EVENT_ASYNC_BEGIN1("ServiceWorker", - "ServiceWorkerVersion::SetCachedMetadata", - callback_id, "URL", url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "ServiceWorker", "ServiceWorkerVersion::SetCachedMetadata", + TRACE_ID_WITH_SCOPE("ServiceWorkerVersion::SetCachedMetadata", + callback_id), + "URL", url.spec()); script_cache_map_.WriteMetadata( url, data, base::BindOnce(&ServiceWorkerVersion::OnSetCachedMetadataFinished, @@ -1329,9 +1334,11 @@ void ServiceWorkerVersion::ClearCachedMetadata(const GURL& url) { int64_t callback_id = base::Time::Now().ToDeltaSinceWindowsEpoch().InMicroseconds(); - TRACE_EVENT_ASYNC_BEGIN1("ServiceWorker", - "ServiceWorkerVersion::ClearCachedMetadata", - callback_id, "URL", url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "ServiceWorker", "ServiceWorkerVersion::ClearCachedMetadata", + TRACE_ID_WITH_SCOPE("ServiceWorkerVersion::ClearCachedMetadata", + callback_id), + "URL", url.spec()); script_cache_map_.ClearMetadata( url, base::BindOnce(&ServiceWorkerVersion::OnClearCachedMetadataFinished, weak_factory_.GetWeakPtr(), callback_id)); @@ -1641,18 +1648,22 @@ void ServiceWorkerVersion::OnSetCachedMetadataFinished(int64_t callback_id, size_t size, int result) { - TRACE_EVENT_ASYNC_END1("ServiceWorker", - "ServiceWorkerVersion::SetCachedMetadata", callback_id, - "result", result); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "ServiceWorker", "ServiceWorkerVersion::SetCachedMetadata", + TRACE_ID_WITH_SCOPE("ServiceWorkerVersion::SetCachedMetadata", + callback_id), + "result", result); for (auto& observer : observers_) observer.OnCachedMetadataUpdated(this, size); } void ServiceWorkerVersion::OnClearCachedMetadataFinished(int64_t callback_id, int result) { - TRACE_EVENT_ASYNC_END1("ServiceWorker", - "ServiceWorkerVersion::ClearCachedMetadata", - callback_id, "result", result); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "ServiceWorker", "ServiceWorkerVersion::ClearCachedMetadata", + TRACE_ID_WITH_SCOPE("ServiceWorkerVersion::ClearCachedMetadata", + callback_id), + "result", result); for (auto& observer : observers_) observer.OnCachedMetadataUpdated(this, 0); } @@ -1836,8 +1847,9 @@ case EmbeddedWorkerStatus::STOPPED: if (start_callbacks_.empty()) { int trace_id = NextTraceId(); - TRACE_EVENT_ASYNC_BEGIN2( - "ServiceWorker", "ServiceWorkerVersion::StartWorker", trace_id, + TRACE_EVENT_NESTABLE_ASYNC_BEGIN2( + "ServiceWorker", "ServiceWorkerVersion::StartWorker", + TRACE_ID_WITH_SCOPE("ServiceWorkerVersion::StartWorker", trace_id), "Script", script_url_.spec(), "Purpose", ServiceWorkerMetrics::EventTypeToString(purpose)); start_callbacks_.push_back( @@ -2080,9 +2092,10 @@ bool is_browser_startup_complete, blink::ServiceWorkerStatusCode status) { if (trace_id != kInvalidTraceId) { - TRACE_EVENT_ASYNC_END1("ServiceWorker", "ServiceWorkerVersion::StartWorker", - trace_id, "Status", - blink::ServiceWorkerStatusToString(status)); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "ServiceWorker", "ServiceWorkerVersion::StartWorker", + TRACE_ID_WITH_SCOPE("ServiceWorkerVersion::StartWorker", trace_id), + "Status", blink::ServiceWorkerStatusToString(status)); } base::TimeTicks start_time = start_time_; ClearTick(&start_time_); @@ -2129,8 +2142,9 @@ if (!request) return false; - TRACE_EVENT_ASYNC_END1("ServiceWorker", "ServiceWorkerVersion::Request", - request, "Error", "Timeout"); + TRACE_EVENT_NESTABLE_ASYNC_END1("ServiceWorker", + "ServiceWorkerVersion::Request", + TRACE_ID_LOCAL(request), "Error", "Timeout"); std::move(request->error_callback) .Run(blink::ServiceWorkerStatusCode::kErrorTimeout); inflight_requests_.Remove(info.id); @@ -2239,9 +2253,11 @@ } if (!stop_time_.is_null()) { - TRACE_EVENT_ASYNC_END1("ServiceWorker", "ServiceWorkerVersion::StopWorker", - stop_time_.since_origin().InMicroseconds(), - "Restart", should_restart); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "ServiceWorker", "ServiceWorkerVersion::StopWorker", + TRACE_ID_WITH_SCOPE("ServiceWorkerVersion::StopWorker", + stop_time_.since_origin().InMicroseconds()), + "Restart", should_restart); ClearTick(&stop_time_); } StopTimeoutTimer(); @@ -2264,8 +2280,9 @@ base::IDMap<std::unique_ptr<InflightRequest>>::iterator iter( &inflight_requests_); while (!iter.IsAtEnd()) { - TRACE_EVENT_ASYNC_END1("ServiceWorker", "ServiceWorkerVersion::Request", - iter.GetCurrentValue(), "Error", "Worker Stopped"); + TRACE_EVENT_NESTABLE_ASYNC_END1( + "ServiceWorker", "ServiceWorkerVersion::Request", + TRACE_ID_LOCAL(iter.GetCurrentValue()), "Error", "Worker Stopped"); std::move(iter.GetCurrentValue()->error_callback) .Run(blink::ServiceWorkerStatusCode::kErrorFailed); iter.Advance();
diff --git a/content/browser/storage_partition_impl.cc b/content/browser/storage_partition_impl.cc index a7584ed4..3b3d91b2 100644 --- a/content/browser/storage_partition_impl.cc +++ b/content/browser/storage_partition_impl.cc
@@ -2208,9 +2208,10 @@ << static_cast<int>(data_type); static int tracing_id = 0; - TRACE_EVENT_ASYNC_BEGIN1("browsing_data", "StoragePartitionImpl", - ++tracing_id, "data_type", - static_cast<int>(data_type)); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "browsing_data", "StoragePartitionImpl", + TRACE_ID_WITH_SCOPE("StoragePartitionImpl", ++tracing_id), "data_type", + static_cast<int>(data_type)); return base::BindOnce( &StoragePartitionImpl::DataDeletionHelper::OnTaskComplete, base::Unretained(this), data_type, tracing_id); @@ -2228,7 +2229,9 @@ } size_t num_erased = pending_tasks_.erase(data_type); DCHECK_EQ(num_erased, 1U) << static_cast<int>(data_type); - TRACE_EVENT_ASYNC_END0("browsing_data", "StoragePartitionImpl", tracing_id); + TRACE_EVENT_NESTABLE_ASYNC_END0( + "browsing_data", "StoragePartitionImpl", + TRACE_ID_WITH_SCOPE("StoragePartitionImpl", tracing_id)); if (pending_tasks_.empty()) { std::move(callback_).Run();
diff --git a/content/browser/tracing/tracing_controller_impl_data_endpoint.cc b/content/browser/tracing/tracing_controller_impl_data_endpoint.cc index 6b639980..6d2d651 100644 --- a/content/browser/tracing/tracing_controller_impl_data_endpoint.cc +++ b/content/browser/tracing/tracing_controller_impl_data_endpoint.cc
@@ -96,7 +96,11 @@ base::File temp_file = CreateAndOpenTemporaryFileInDir(file_path_.DirName(), &pending_file_path_); if (temp_file.IsValid()) { - file_ = FileToFILE(std::move(temp_file), "w"); + // On Android, fdsan prohibits associating a new stream with a file while + // it's still owned by base::File. So we have to close it first and then + // reopen as FILE*. + temp_file.Close(); + file_ = base::OpenFile(pending_file_path_, "w"); } else { LOG(WARNING) << "Unable to use temporary file " << pending_file_path_ << ": "
diff --git a/content/browser/webid/README.md b/content/browser/webid/README.md new file mode 100644 index 0000000..664293c7 --- /dev/null +++ b/content/browser/webid/README.md
@@ -0,0 +1,112 @@ +# WebID Browser side + +This folder contains the implementation of the browser side logic for +[WebID](https://wicg.github.io/WebID/README.html) feature. It is responsible for making all of the +network requests needed to implement a WebID request and also controls what UI and at which point in +the process is shown to the user. + +## Anatomy of a WebID request + +A WebID request is initiated by a [Relying +Party](https://wicg.github.io/WebID/glossary.html#relying-party-rp) (RP) in order to perform a +federated identity related operation e.g., authenticate, logout etc., with an [Identity +Provider](https://wicg.github.io/WebID/glossary.html#identity-provider-idp) (IDP). + +While RP and IDP could belong to the same site (or origin) but the most interesting and common case +is where RP and IDP belong to different sites and thus this operation is a cross-site communication +and subject to additional scrutiny by the browser. + + +Here is the basic process in Chromium for a WebID request: + +1. The RP renderer process creates a new request via async javascript APIs which return a promise. + - See [WebID.idl](../../../third_party/blink/renderer/modules/webid/web_id.idl) for supported + methods. + - The logic for handling and validation of these request lives in + [`web_id.cc`](../../../third_party/blink/renderer/modules/webid/web_id.cc) + - Also in certain situations WebID can be activated passively by a navigation throttle that + identifies an OAuth request being passed over a top-level navigation. + +1. Renderer process passes this request to the browser process via the + [`federated_auth_request.mojo`](../../../third_party/blink/public/mojom/webid/federated_auth_request.mojom) + mojo interface. +1. Browser process handles the requests. This handling often requires multiple fetch requests to the + IDP and showing appropriate UI (e.g., account chooser, permission dialog) to the user. Most of + the implementation of this step lives in this directory. +1. A successful authentication request often result in an [OIDC + idtoken](https://openid.net/specs/openid-connect-core-1_0.html#IDToken) to being generated by the + IDP. This idtoken is then passed to the RP renderer process via the mojo interface. +1. A failed request is often result in passing an appropriate error message to the RP renderer + process via the mojo interface. +1. The RP renderer process resolves or rejects the returned promise based on the response that it + receives from the browser process and completing the request. + +## Network Fetches + +As explained before, the cross-site nature of WebID communication means that there is additional +scrutiny and enforcement for them by the browser. This enforcements occur in the browser process so +that they cannot be side-stepped by a malicious renderer process. This is why all of WebID network +requests occur in the browser process. + +**TODO**: Explain various fetches that occur in +[idp_network_request_manager.h](idp_network_request_manager.h) in particular +which storage partition are used for them, any special caching logics, or request parameter +processing. + +## Permission Grants + +As part of the WebID request flow user often has to grant RP and IDP special permissions to allow +cross-site communications. This exact UX for granting of these permissions depends on the mode that +is used. + +Here are the permissions that are currently used: + +- **Request Permission**: This tracks the fact that the user has allowed the IDP to learn about the + user activity on the RP and includes their origins. In particular with this permission granted, + then browser shares RP-identifying info (e.g., client_id) as part of credentialed + (user-identifying) requests. This is implemented by + [federated_identity_request_permission_context.h](../../../chrome/browser/webid/federated_identity_request_permission_context.h). +- **Sharing Permission**: This tracks the fact that the user has allowed the IDP to share their + information with the RP and includes their origins. In particular with this permission granted, + then browser shares user-identifying info (e.g., id token) with the RP. This is implemented by + [federated_identity_sharing_permission_context.h](../../../chrome/browser/webid/federated_identity_sharing_permission_context.h). +- **Account Specific Sharing Permission**: This is a specialized form of sharing permission in which the + browser also remembers the specific account for which the user granted the sharing permission. + This allows a more fine grained control. It is only used with the mediation-oriented mode and is + implemented by + [federated_identity_sharing_permission_context.h](../../../chrome/browser/webid/federated_identity_sharing_permission_context.h). + + + +**Note**: The account identifier used by the account specific sharing permission comes from the user +selection in the account selector UI in the browser. This is a reasonable choice. However it is +possible for the final id token generated by th IDP to be for a different account (as denoted by its +`subject` field in OIDC). This is considered a bug and it is because the browser currently does not +have any enforcement to ensure these two accounts are the same. The browser may (and probably will) +add such enforcements after its starts inspecting the returned idtoken so this behavior should not +be relied upon. + + +## UI + +Currently we support two different modes for WebID with their own specific UX and UI: +[permission-oriented mode](https://wicg.github.io/WebID/README.html#the-permission-oriented-api), +and [mediation-oriented mode](https://wicg.github.io/WebID/README.html#the-mediation-oriented-api). + +At the moment the mediation UI is only implemented on +[Android](../../../chrome/browser/ui/android/webid/README.md) and on Desktop platforms no UI is shown and +instead we pretend that the first account is selected. + +In contrast the permission UI is only implemented for [Desktop +platforms](../../../chrome/browser/ui/views/webid/) but not on Android. + + +## Key Classes + +- `FederatedAuthRequestImpl`: Concrete implementation of the mojo interface to initiate a WebID + request. It contains most of the business logic and state necessary for WebID requests. +- `IdPNetworkRequestManager`: Handles all fetches needed for WebID. It ensures we use the right + storage partition and cookie jar for each request. This class is stateless itself. +- `FederatedAuthResponseImpl`: Concrete implementation of the mojo interface to provide a WebID + response. This is means to be used by IDP login page to complete its process by providing + an id token.
diff --git a/content/public/browser/client_hints_controller_delegate.h b/content/public/browser/client_hints_controller_delegate.h index 5891f05..0200b5b 100644 --- a/content/public/browser/client_hints_controller_delegate.h +++ b/content/public/browser/client_hints_controller_delegate.h
@@ -41,8 +41,6 @@ virtual bool IsJavaScriptAllowed(const GURL& url) = 0; - virtual bool UserAgentClientHintEnabled() = 0; - virtual blink::UserAgentMetadata GetUserAgentMetadata() = 0; virtual void PersistClientHints(
diff --git a/content/public/test/prerender_test_util.cc b/content/public/test/prerender_test_util.cc index d559d7a..2a2d7bc 100644 --- a/content/public/test/prerender_test_util.cc +++ b/content/public/test/prerender_test_util.cc
@@ -240,7 +240,8 @@ void PrerenderTestHelper::WaitForPrerenderLoadCompletion(int host_id) { auto* host = GetPrerenderHostById(GetWebContents(), host_id); ASSERT_NE(host, nullptr); - host->WaitForLoadStopForTesting(); + auto status = host->WaitForLoadStopForTesting(); + EXPECT_EQ(status, PrerenderHost::LoadingOutcome::kLoadingCompleted); } // static @@ -256,7 +257,8 @@ host = registry.FindHostByUrlForTesting(gurl); ASSERT_NE(host, nullptr); } - host->WaitForLoadStopForTesting(); + auto status = host->WaitForLoadStopForTesting(); + EXPECT_EQ(status, PrerenderHost::LoadingOutcome::kLoadingCompleted); } void PrerenderTestHelper::WaitForPrerenderLoadCompletion(const GURL& gurl) {
diff --git a/content/renderer/mhtml_handle_writer.cc b/content/renderer/mhtml_handle_writer.cc index 1fd2c74..b5480296f 100644 --- a/content/renderer/mhtml_handle_writer.cc +++ b/content/renderer/mhtml_handle_writer.cc
@@ -25,8 +25,9 @@ void MHTMLHandleWriter::WriteContents( std::vector<blink::WebThreadSafeData> mhtml_contents) { - TRACE_EVENT_ASYNC_BEGIN0("page-serialization", - "Writing MHTML contents to handle", this); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("page-serialization", + "Writing MHTML contents to handle", + TRACE_ID_LOCAL(this)); DCHECK(mhtml_write_start_time_.is_null()); mhtml_write_start_time_ = base::TimeTicks::Now(); @@ -39,8 +40,9 @@ // Only record UMA if WriteContents has been called. if (!mhtml_write_start_time_.is_null()) { - TRACE_EVENT_ASYNC_END0("page-serialization", - "WriteContentsImpl (MHTMLHandleWriter)", this); + TRACE_EVENT_NESTABLE_ASYNC_END0("page-serialization", + "WriteContentsImpl (MHTMLHandleWriter)", + TRACE_ID_LOCAL(this)); base::TimeDelta mhtml_write_time = base::TimeTicks::Now() - mhtml_write_start_time_; UMA_HISTOGRAM_TIMES(
diff --git a/content/renderer/renderer_main.cc b/content/renderer/renderer_main.cc index a28996d..cf87927 100644 --- a/content/renderer/renderer_main.cc +++ b/content/renderer/renderer_main.cc
@@ -107,7 +107,9 @@ int RendererMain(const MainFunctionParams& parameters) { // Don't use the TRACE_EVENT0 macro because the tracing infrastructure doesn't // expect synchronous events around the main loop of a thread. - TRACE_EVENT_ASYNC_BEGIN1("startup", "RendererMain", 0, "zygote_child", false); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("startup", "RendererMain", + TRACE_ID_WITH_SCOPE("RendererMain", 0), + "zygote_child", false); base::trace_event::TraceLog::GetInstance()->set_process_name("Renderer"); base::trace_event::TraceLog::GetInstance()->SetProcessSortIndex( @@ -235,8 +237,9 @@ // the tracing SMB on our behalf due to the zygote sandbox. if (parameters.zygote_child) { tracing::EnableStartupTracingIfNeeded(); - TRACE_EVENT_ASYNC_BEGIN1("startup", "RendererMain", 0, "zygote_child", - true); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("startup", "RendererMain", + TRACE_ID_WITH_SCOPE("RendererMain", 0), + "zygote_child", true); } #endif // OS_POSIX && !OS_ANDROID && !OS_MAC @@ -257,9 +260,13 @@ if (pool) pool->Recycle(); #endif - TRACE_EVENT_ASYNC_BEGIN0("toplevel", "RendererMain.START_MSG_LOOP", 0); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( + "toplevel", "RendererMain.START_MSG_LOOP", + TRACE_ID_WITH_SCOPE("RendererMain.START_MSG_LOOP", 0)); run_loop.Run(); - TRACE_EVENT_ASYNC_END0("toplevel", "RendererMain.START_MSG_LOOP", 0); + TRACE_EVENT_NESTABLE_ASYNC_END0( + "toplevel", "RendererMain.START_MSG_LOOP", + TRACE_ID_WITH_SCOPE("RendererMain.START_MSG_LOOP", 0)); } #if defined(LEAK_SANITIZER) @@ -269,7 +276,8 @@ #endif } platform.PlatformUninitialize(); - TRACE_EVENT_ASYNC_END0("startup", "RendererMain", 0); + TRACE_EVENT_NESTABLE_ASYNC_END0("startup", "RendererMain", + TRACE_ID_WITH_SCOPE("RendererMain", 0)); return 0; }
diff --git a/content/renderer/service_worker/web_service_worker_provider_impl.cc b/content/renderer/service_worker/web_service_worker_provider_impl.cc index 25a967d..a36f0794 100644 --- a/content/renderer/service_worker/web_service_worker_provider_impl.cc +++ b/content/renderer/service_worker/web_service_worker_provider_impl.cc
@@ -89,9 +89,10 @@ return; } - TRACE_EVENT_ASYNC_BEGIN2( + TRACE_EVENT_NESTABLE_ASYNC_BEGIN2( "ServiceWorker", "WebServiceWorkerProviderImpl::RegisterServiceWorker", - this, "Scope", pattern.spec(), "Script URL", script_url.spec()); + TRACE_ID_LOCAL(this), "Scope", pattern.spec(), "Script URL", + script_url.spec()); // TODO(asamidoi): Create this options in // ServiceWorkerContainer::RegisterServiceWorker() and pass it as an argument @@ -128,9 +129,9 @@ return; } - TRACE_EVENT_ASYNC_BEGIN1("ServiceWorker", - "WebServiceWorkerProviderImpl::GetRegistration", - this, "Document URL", document_url.spec()); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( + "ServiceWorker", "WebServiceWorkerProviderImpl::GetRegistration", + TRACE_ID_LOCAL(this), "Document URL", document_url.spec()); context_->container_host()->GetRegistration( document_url, base::BindOnce(&WebServiceWorkerProviderImpl::OnDidGetRegistration, @@ -150,8 +151,9 @@ return; } - TRACE_EVENT_ASYNC_BEGIN0( - "ServiceWorker", "WebServiceWorkerProviderImpl::GetRegistrations", this); + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( + "ServiceWorker", "WebServiceWorkerProviderImpl::GetRegistrations", + TRACE_ID_LOCAL(this)); context_->container_host()->GetRegistrations( base::BindOnce(&WebServiceWorkerProviderImpl::OnDidGetRegistrations, weak_factory_.GetWeakPtr(), std::move(callbacks))); @@ -163,9 +165,9 @@ return; } - TRACE_EVENT_ASYNC_BEGIN0( + TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( "ServiceWorker", "WebServiceWorkerProviderImpl::GetRegistrationForReady", - this); + TRACE_ID_LOCAL(this)); context_->container_host()->GetRegistrationForReady(base::BindOnce( &WebServiceWorkerProviderImpl::OnDidGetRegistrationForReady, weak_factory_.GetWeakPtr(), std::move(callback))); @@ -220,9 +222,10 @@ blink::mojom::ServiceWorkerErrorType error, const absl::optional<std::string>& error_msg, blink::mojom::ServiceWorkerRegistrationObjectInfoPtr registration) { - TRACE_EVENT_ASYNC_END2( + TRACE_EVENT_NESTABLE_ASYNC_END2( "ServiceWorker", "WebServiceWorkerProviderImpl::RegisterServiceWorker", - this, "Error", ServiceWorkerUtils::MojoEnumToString(error), "Message", + TRACE_ID_LOCAL(this), "Error", + ServiceWorkerUtils::MojoEnumToString(error), "Message", error_msg ? *error_msg : "Success"); if (error != blink::mojom::ServiceWorkerErrorType::kNone) { DCHECK(error_msg); @@ -246,10 +249,11 @@ blink::mojom::ServiceWorkerErrorType error, const absl::optional<std::string>& error_msg, blink::mojom::ServiceWorkerRegistrationObjectInfoPtr registration) { - TRACE_EVENT_ASYNC_END2("ServiceWorker", - "WebServiceWorkerProviderImpl::GetRegistration", this, - "Error", ServiceWorkerUtils::MojoEnumToString(error), - "Message", error_msg ? *error_msg : "Success"); + TRACE_EVENT_NESTABLE_ASYNC_END2( + "ServiceWorker", "WebServiceWorkerProviderImpl::GetRegistration", + TRACE_ID_LOCAL(this), "Error", + ServiceWorkerUtils::MojoEnumToString(error), "Message", + error_msg ? *error_msg : "Success"); if (error != blink::mojom::ServiceWorkerErrorType::kNone) { DCHECK(error_msg); DCHECK(!registration); @@ -276,10 +280,11 @@ absl::optional< std::vector<blink::mojom::ServiceWorkerRegistrationObjectInfoPtr>> infos) { - TRACE_EVENT_ASYNC_END2("ServiceWorker", - "WebServiceWorkerProviderImpl::GetRegistrations", this, - "Error", ServiceWorkerUtils::MojoEnumToString(error), - "Message", error_msg ? *error_msg : "Success"); + TRACE_EVENT_NESTABLE_ASYNC_END2( + "ServiceWorker", "WebServiceWorkerProviderImpl::GetRegistrations", + TRACE_ID_LOCAL(this), "Error", + ServiceWorkerUtils::MojoEnumToString(error), "Message", + error_msg ? *error_msg : "Success"); if (error != blink::mojom::ServiceWorkerErrorType::kNone) { DCHECK(error_msg); DCHECK(!infos); @@ -305,9 +310,9 @@ void WebServiceWorkerProviderImpl::OnDidGetRegistrationForReady( GetRegistrationForReadyCallback callback, blink::mojom::ServiceWorkerRegistrationObjectInfoPtr registration) { - TRACE_EVENT_ASYNC_END0( + TRACE_EVENT_NESTABLE_ASYNC_END0( "ServiceWorker", "WebServiceWorkerProviderImpl::GetRegistrationForReady", - this); + TRACE_ID_LOCAL(this)); // TODO(leonhsl): Currently the only reason that we allow nullable // |registration| is: impl of the mojo method // GetRegistrationForReady() needs to respond some non-sense params even if it
diff --git a/content/test/mock_client_hints_controller_delegate.cc b/content/test/mock_client_hints_controller_delegate.cc index c0a100b..2436fb2 100644 --- a/content/test/mock_client_hints_controller_delegate.cc +++ b/content/test/mock_client_hints_controller_delegate.cc
@@ -4,8 +4,6 @@ #include "content/test/mock_client_hints_controller_delegate.h" -#include "base/feature_list.h" -#include "content/public/common/content_features.h" #include "content/public/common/origin_util.h" #include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "url/gurl.h" @@ -28,10 +26,6 @@ return true; } -bool MockClientHintsControllerDelegate::UserAgentClientHintEnabled() { - return base::FeatureList::IsEnabled(features::kUserAgentClientHint); -} - blink::UserAgentMetadata MockClientHintsControllerDelegate::GetUserAgentMetadata() { return metadata_;
diff --git a/content/test/mock_client_hints_controller_delegate.h b/content/test/mock_client_hints_controller_delegate.h index 64dbd82..7bfcee8 100644 --- a/content/test/mock_client_hints_controller_delegate.h +++ b/content/test/mock_client_hints_controller_delegate.h
@@ -28,8 +28,6 @@ bool IsJavaScriptAllowed(const GURL& url) override; - bool UserAgentClientHintEnabled() override; - blink::UserAgentMetadata GetUserAgentMetadata() override; void PersistClientHints( const url::Origin& primary_origin,
diff --git a/fuchsia/base/test/context_provider_test_connector.cc b/fuchsia/base/test/context_provider_test_connector.cc index 43a2022..1372ac38 100644 --- a/fuchsia/base/test/context_provider_test_connector.cc +++ b/fuchsia/base/test/context_provider_test_connector.cc
@@ -71,14 +71,6 @@ } // namespace -fidl::InterfaceHandle<fuchsia::io::Directory> StartWebEngineForTests( - fidl::InterfaceRequest<fuchsia::sys::ComponentController> - component_controller_request, - const base::CommandLine& command_line) { - return StartWebEngineForTestsInternal(std::move(component_controller_request), - command_line, false); -} - fuchsia::web::ContextProviderPtr ConnectContextProvider( fidl::InterfaceRequest<fuchsia::sys::ComponentController> component_controller_request,
diff --git a/fuchsia/base/test/context_provider_test_connector.h b/fuchsia/base/test/context_provider_test_connector.h index 25542f7..a3e59f1 100644 --- a/fuchsia/base/test/context_provider_test_connector.h +++ b/fuchsia/base/test/context_provider_test_connector.h
@@ -14,15 +14,6 @@ namespace cr_fuchsia { -// Starts a WebEngine instance for tests. -// WebEngine logs will be included in the test output but not in the Fuchsia -// system log. -fidl::InterfaceHandle<fuchsia::io::Directory> StartWebEngineForTests( - fidl::InterfaceRequest<fuchsia::sys::ComponentController> - component_controller_request, - const base::CommandLine& command_line = - base::CommandLine(base::CommandLine::NO_PROGRAM)); - // Starts a WebEngine and connects a ContextProvider instance for tests. // WebEngine logs will be included in the test output but not in the Fuchsia // system log.
diff --git a/fuchsia/runners/cast/cast_runner_integration_test.cc b/fuchsia/runners/cast/cast_runner_integration_test.cc index 0f8a8cf9..2978d18 100644 --- a/fuchsia/runners/cast/cast_runner_integration_test.cc +++ b/fuchsia/runners/cast/cast_runner_integration_test.cc
@@ -505,7 +505,6 @@ }; sys::ServiceDirectory StartCastRunner( - fidl::InterfaceHandle<fuchsia::io::Directory> web_engine_host_directory, CastRunnerFeatures runner_features, fidl::InterfaceRequest<fuchsia::sys::ComponentController> component_controller_request) { @@ -539,14 +538,6 @@ launch_info.directory_request = cast_runner_services_dir.NewRequest().TakeChannel(); - // Redirect ContextProvider to |web_engine_host_directory|. - launch_info.additional_services = - std::make_unique<fuchsia::sys::ServiceList>(); - launch_info.additional_services->host_directory = - web_engine_host_directory.TakeChannel(); - launch_info.additional_services->names.push_back( - fuchsia::web::ContextProvider::Name_); - fuchsia::sys::LauncherPtr launcher; base::ComponentContextForProcess()->svc()->Connect(launcher.NewRequest()); launcher->CreateComponent(std::move(launch_info), @@ -573,16 +564,9 @@ protected: explicit CastRunnerIntegrationTest(CastRunnerFeatures runner_features) { - StartAndPublishWebEngine(); - // Start CastRunner. - fidl::InterfaceHandle<::fuchsia::io::Directory> incoming_services; - services_for_cast_runner_.GetOrCreateDirectory("svc")->Serve( - ::fuchsia::io::OPEN_RIGHT_READABLE | ::fuchsia::io::OPEN_RIGHT_WRITABLE, - incoming_services.NewRequest().TakeChannel()); - sys::ServiceDirectory cast_runner_services = - StartCastRunner(std::move(incoming_services), runner_features, - cast_runner_controller_.ptr().NewRequest()); + sys::ServiceDirectory cast_runner_services = StartCastRunner( + runner_features, cast_runner_controller_.ptr().NewRequest()); // Connect to the CastRunner's fuchsia.sys.Runner interface. cast_runner_ = cast_runner_services.Connect<fuchsia::sys::Runner>(); @@ -596,27 +580,6 @@ EXPECT_TRUE(test_server_.Start()); } - void StartAndPublishWebEngine() { - fidl::InterfaceHandle<fuchsia::io::Directory> web_engine_outgoing_dir = - cr_fuchsia::StartWebEngineForTests( - web_engine_controller_.ptr().NewRequest()); - sys::ServiceDirectory web_engine_outgoing_services( - std::move(web_engine_outgoing_dir)); - ignore_result(services_for_cast_runner_ - .RemovePublicService<fuchsia::web::ContextProvider>()); - ASSERT_EQ(services_for_cast_runner_.AddPublicService( - std::make_unique<vfs::Service>( - [web_engine_outgoing_services = - std::move(web_engine_outgoing_services)]( - zx::channel channel, async_dispatcher_t* dispatcher) { - web_engine_outgoing_services.Connect( - fuchsia::web::ContextProvider::Name_, - std::move(channel)); - }), - fuchsia::web::ContextProvider::Name_), - ZX_OK); - } - base::test::SingleThreadTaskEnvironment task_environment_{ base::test::SingleThreadTaskEnvironment::MainThreadType::IO}; net::EmbeddedTestServer test_server_; @@ -679,7 +642,6 @@ // disconnecting yet, so attempts to launch Cast components could fail. // WebContentRunner::CreateFrameWithParams() will synchronously verify that // the web.Context is not-yet-closed, to work-around that. - StartAndPublishWebEngine(); TestCastComponent second_component(cast_runner_.get()); second_component.app_config_manager()->AddApp(kTestAppId, app_url); second_component.CreateComponentContextAndStartComponent(kTestAppId);
diff --git a/gpu/command_buffer/build_webgpu_cmd_buffer.py b/gpu/command_buffer/build_webgpu_cmd_buffer.py index 07b6c8e..9ff5913 100755 --- a/gpu/command_buffer/build_webgpu_cmd_buffer.py +++ b/gpu/command_buffer/build_webgpu_cmd_buffer.py
@@ -84,6 +84,10 @@ 'request_device_properties_size * sizeof(char)', }, }, + 'DestroyServer': { + 'impl_func': False, + 'internal': True, + }, } def main(argv):
diff --git a/gpu/command_buffer/client/webgpu_cmd_helper_autogen.h b/gpu/command_buffer/client/webgpu_cmd_helper_autogen.h index e17e061..2758247 100644 --- a/gpu/command_buffer/client/webgpu_cmd_helper_autogen.h +++ b/gpu/command_buffer/client/webgpu_cmd_helper_autogen.h
@@ -67,4 +67,11 @@ } } +void DestroyServer() { + webgpu::cmds::DestroyServer* c = GetCmdSpace<webgpu::cmds::DestroyServer>(); + if (c) { + c->Init(); + } +} + #endif // GPU_COMMAND_BUFFER_CLIENT_WEBGPU_CMD_HELPER_AUTOGEN_H_
diff --git a/gpu/command_buffer/client/webgpu_implementation.cc b/gpu/command_buffer/client/webgpu_implementation.cc index eaa2fce..a155f47f 100644 --- a/gpu/command_buffer/client/webgpu_implementation.cc +++ b/gpu/command_buffer/client/webgpu_implementation.cc
@@ -419,9 +419,13 @@ void WebGPUImplementation::DisconnectContextAndDestroyServer() { // Treat this like a context lost since the context is no longer usable. - // TODO(crbug.com/1160459): Also send a message to eagerly free server-side - // resources. OnGpuControlLostContextMaybeReentrant(); + +#if BUILDFLAG(USE_DAWN) + // Send a message to eagerly free server-side resources. + helper_->DestroyServer(); + helper_->Flush(); +#endif } ReservedTexture WebGPUImplementation::ReserveTexture(WGPUDevice device) {
diff --git a/gpu/command_buffer/common/webgpu_cmd_format_autogen.h b/gpu/command_buffer/common/webgpu_cmd_format_autogen.h index a82850b..6f91209 100644 --- a/gpu/command_buffer/common/webgpu_cmd_format_autogen.h +++ b/gpu/command_buffer/common/webgpu_cmd_format_autogen.h
@@ -282,4 +282,30 @@ offsetof(RequestDevice, request_device_properties_size) == 28, "offset of RequestDevice request_device_properties_size should be 28"); +struct DestroyServer { + typedef DestroyServer ValueType; + static const CommandId kCmdId = kDestroyServer; + static const cmd::ArgFlags kArgFlags = cmd::kFixed; + static const uint8_t cmd_flags = CMD_FLAG_SET_TRACE_LEVEL(3); + + static uint32_t ComputeSize() { + return static_cast<uint32_t>(sizeof(ValueType)); // NOLINT + } + + void SetHeader() { header.SetCmd<ValueType>(); } + + void Init() { SetHeader(); } + + void* Set(void* cmd) { + static_cast<ValueType*>(cmd)->Init(); + return NextCmdAddress<ValueType>(cmd); + } + + gpu::CommandHeader header; +}; + +static_assert(sizeof(DestroyServer) == 4, "size of DestroyServer should be 4"); +static_assert(offsetof(DestroyServer, header) == 0, + "offset of DestroyServer header should be 0"); + #endif // GPU_COMMAND_BUFFER_COMMON_WEBGPU_CMD_FORMAT_AUTOGEN_H_
diff --git a/gpu/command_buffer/common/webgpu_cmd_format_test_autogen.h b/gpu/command_buffer/common/webgpu_cmd_format_test_autogen.h index 3234f419..ae13151 100644 --- a/gpu/command_buffer/common/webgpu_cmd_format_test_autogen.h +++ b/gpu/command_buffer/common/webgpu_cmd_format_test_autogen.h
@@ -112,4 +112,13 @@ CheckBytesWrittenMatchesExpectedSize(next_cmd, sizeof(cmd)); } +TEST_F(WebGPUFormatTest, DestroyServer) { + cmds::DestroyServer& cmd = *GetBufferAs<cmds::DestroyServer>(); + void* next_cmd = cmd.Set(&cmd); + EXPECT_EQ(static_cast<uint32_t>(cmds::DestroyServer::kCmdId), + cmd.header.command); + EXPECT_EQ(sizeof(cmd), cmd.header.size * 4u); + CheckBytesWrittenMatchesExpectedSize(next_cmd, sizeof(cmd)); +} + #endif // GPU_COMMAND_BUFFER_COMMON_WEBGPU_CMD_FORMAT_TEST_AUTOGEN_H_
diff --git a/gpu/command_buffer/common/webgpu_cmd_ids_autogen.h b/gpu/command_buffer/common/webgpu_cmd_ids_autogen.h index 3e70690..4241d0f 100644 --- a/gpu/command_buffer/common/webgpu_cmd_ids_autogen.h +++ b/gpu/command_buffer/common/webgpu_cmd_ids_autogen.h
@@ -16,7 +16,8 @@ OP(AssociateMailboxImmediate) /* 257 */ \ OP(DissociateMailbox) /* 258 */ \ OP(RequestAdapter) /* 259 */ \ - OP(RequestDevice) /* 260 */ + OP(RequestDevice) /* 260 */ \ + OP(DestroyServer) /* 261 */ enum CommandId { kOneBeforeStartPoint =
diff --git a/gpu/command_buffer/service/webgpu_decoder_impl.cc b/gpu/command_buffer/service/webgpu_decoder_impl.cc index 09ed847..7c7b763 100644 --- a/gpu/command_buffer/service/webgpu_decoder_impl.cc +++ b/gpu/command_buffer/service/webgpu_decoder_impl.cc
@@ -474,6 +474,7 @@ std::unordered_map<uint32_t, WGPUBackendType> device_backend_types_; bool has_polling_work_ = false; + bool destroyed_ = false; scoped_refptr<gl::GLContext> gl_context_; scoped_refptr<gl::GLSurface> gl_surface_; @@ -554,7 +555,11 @@ void WebGPUDecoderImpl::Destroy(bool have_context) { associated_shared_image_map_.clear(); + known_devices_.clear(); + device_backend_types_.clear(); wire_server_ = nullptr; + + destroyed_ = true; } ContextResult WebGPUDecoderImpl::Initialize() { @@ -777,6 +782,12 @@ const unsigned int arg_count = size - 1; unsigned int command_index = command - kFirstWebGPUCommand; if (command_index < base::size(command_info)) { + // Prevent all further WebGPU commands from being processed if the server + // is destroyed. + if (destroyed_) { + result = error::kLostContext; + break; + } const CommandInfo& info = command_info[command_index]; unsigned int info_arg_count = static_cast<unsigned int>(info.arg_count); if ((info.arg_flags == cmd::kFixed && arg_count == info_arg_count) || @@ -892,6 +903,14 @@ sizeof(return_request_device_info))); } +error::Error WebGPUDecoderImpl::HandleDestroyServer( + uint32_t immediate_data_size, + const volatile void* cmd_data) { + Destroy(false); + + return error::kNoError; +} + error::Error WebGPUDecoderImpl::HandleRequestAdapter( uint32_t immediate_data_size, const volatile void* cmd_data) {
diff --git a/gpu/command_buffer/tests/webgpu_test.cc b/gpu/command_buffer/tests/webgpu_test.cc index d27af67..dd59e917 100644 --- a/gpu/command_buffer/tests/webgpu_test.cc +++ b/gpu/command_buffer/tests/webgpu_test.cc
@@ -291,6 +291,52 @@ EXPECT_TRUE(called); } +TEST_F(WebGPUTest, RequestAdapterAfterServerDestroyed) { + if (!WebGPUSupported()) { + LOG(ERROR) << "Test skipped because WebGPU isn't supported"; + return; + } + + Initialize(WebGPUTest::Options()); + + webgpu()->DisconnectContextAndDestroyServer(); + + bool called = false; + webgpu()->RequestAdapterAsync( + webgpu::PowerPreference::kDefault, + base::BindOnce( + [](bool* called, int32_t adapter_id, const WGPUDeviceProperties&, + const char*) { + EXPECT_EQ(adapter_id, -1); + *called = true; + }, + &called)); + RunPendingTasks(); + EXPECT_TRUE(called); +} + +TEST_F(WebGPUTest, RequestDeviceAfterServerDestroyed) { + if (!WebGPUSupported()) { + LOG(ERROR) << "Test skipped because WebGPU isn't supported"; + return; + } + + Initialize(WebGPUTest::Options()); + + webgpu()->DisconnectContextAndDestroyServer(); + + bool called = false; + webgpu()->RequestDeviceAsync(GetAdapterId(), GetDeviceProperties(), + base::BindOnce( + [](bool* called, WGPUDevice device) { + EXPECT_EQ(device, nullptr); + *called = true; + }, + &called)); + RunPendingTasks(); + EXPECT_TRUE(called); +} + TEST_F(WebGPUTest, RequestDeviceWitUnsupportedExtension) { if (!WebGPUSupported()) { LOG(ERROR) << "Test skipped because WebGPU isn't supported";
diff --git a/gpu/command_buffer/webgpu_cmd_buffer_functions.txt b/gpu/command_buffer/webgpu_cmd_buffer_functions.txt index 8ac5f0da..654ec8ff 100644 --- a/gpu/command_buffer/webgpu_cmd_buffer_functions.txt +++ b/gpu/command_buffer/webgpu_cmd_buffer_functions.txt
@@ -11,3 +11,4 @@ GL_APICALL void GL_APIENTRY wgDissociateMailbox (GLuint texture_id, GLuint texture_generation); GL_APICALL void GL_APIENTRY wgRequestAdapter (GLuint64 request_adapter_serial, EnumClassPowerPreference power_preference = PowerPreference::kDefault); GL_APICALL void GL_APIENTRY wgRequestDevice (GLuint64 request_device_serial, GLuint adapter_service_id, GLuint device_id, GLuint device_generation, const char* dawn_request_device_properties, size_t request_device_properties_size); +GL_APICALL void GL_APIENTRY wgDestroyServer (void);
diff --git a/infra/config/scripts/branch.py b/infra/config/scripts/branch.py index fd20b3d..ba42e8d 100755 --- a/infra/config/scripts/branch.py +++ b/infra/config/scripts/branch.py
@@ -80,13 +80,7 @@ f.write(settings) -BRANCH_TYPES = ('standard', 'desktop-extended-stable', 'cros-lts', 'lts') - -# TODO(gbeaty) Remove this once buildbucket picks up property change for -# branch-config-verifier -BRANCH_TYPE_MAPPING = { - 'lts': 'cros-lts', -} +BRANCH_TYPES = ('standard', 'desktop-extended-stable', 'cros-lts') def set_type(settings_json, branch_types): @@ -94,7 +88,6 @@ assert t in BRANCH_TYPES, 'Unknown branch_type {!r}'.format(t) settings = json.loads(settings_json) - branch_types = [BRANCH_TYPE_MAPPING.get(t, t) for t in branch_types] settings.update(branch_types=branch_types) return json.dumps(settings, indent=4) + '\n'
diff --git a/infra/config/scripts/tests/branch_unit_test.py b/infra/config/scripts/tests/branch_unit_test.py index 297a13e..d0726c4 100755 --- a/infra/config/scripts/tests/branch_unit_test.py +++ b/infra/config/scripts/tests/branch_unit_test.py
@@ -108,27 +108,6 @@ } """)) - def test_set_type_mapped(self): - input = textwrap.dedent("""\ - { - "project": "chromium-mMM", - "project_title": "Chromium MMM", - "ref": "refs/branch-heads/AAAA" - }""") - output = branch.set_type(input, ['lts']) - self.assertEqual( - output, - textwrap.dedent("""\ - { - "project": "chromium-mMM", - "project_title": "Chromium MMM", - "ref": "refs/branch-heads/AAAA", - "branch_types": [ - "cros-lts" - ] - } - """)) - if __name__ == '__main__': unittest.main()
diff --git a/ios/chrome/app/application_delegate/app_state.h b/ios/chrome/app/application_delegate/app_state.h index de3236e..9931046 100644 --- a/ios/chrome/app/application_delegate/app_state.h +++ b/ios/chrome/app/application_delegate/app_state.h
@@ -97,6 +97,10 @@ // resets. @property(nonatomic, readonly) BOOL firstSceneHasInitializedUI; +// YES if the views being presented should only support the portrait +// orientation. +@property(nonatomic, readonly) BOOL portraitOnly; + // Saves the launchOptions to be used from -newTabFromLaunchOptions. If the // application is in background, initialize the browser to basic. If not, launch // the browser.
diff --git a/ios/chrome/app/application_delegate/app_state.mm b/ios/chrome/app/application_delegate/app_state.mm index 6323ffb..9ede7e8a 100644 --- a/ios/chrome/app/application_delegate/app_state.mm +++ b/ios/chrome/app/application_delegate/app_state.mm
@@ -60,6 +60,7 @@ #include "ios/web/public/thread/web_task_traits.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" +#include "ui/base/device_form_factor.h" #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." @@ -221,6 +222,16 @@ [self.observers appState:self didTransitionFromInitStage:previousInitStage]; } +- (BOOL)portraitOnly { + if (ui::GetDeviceFormFactor() != ui::DEVICE_FORM_FACTOR_PHONE) { + return NO; + } + + // Return YES if the First Run UI is showing. + return self.initStage == InitStageFirstRun && + self.startupInformation.isFirstRun; +} + #pragma mark - Public methods. - (void)applicationDidEnterBackground:(UIApplication*)application @@ -649,7 +660,7 @@ #pragma mark - SceneStateObserver -- (void)sceneStateHasInitializedUI:(SceneState*)sceneState { +- (void)sceneStateDidEnableUI:(SceneState*)sceneState { if (self.firstSceneHasInitializedUI) { return; }
diff --git a/ios/chrome/app/first_run_app_state_agent.mm b/ios/chrome/app/first_run_app_state_agent.mm index 6a6987a..5b369fb8 100644 --- a/ios/chrome/app/first_run_app_state_agent.mm +++ b/ios/chrome/app/first_run_app_state_agent.mm
@@ -50,7 +50,8 @@ @interface FirstRunAppAgent () <AppStateObserver, PolicyWatcherBrowserAgentObserving, - FirstRunCoordinatorDelegate> + FirstRunCoordinatorDelegate, + SceneStateObserver> // The app state for the app. @property(nonatomic, weak, readonly) AppState* appState; @@ -97,6 +98,17 @@ [appState addObserver:self]; } +#pragma mark - SceneStateObserver + +- (void)sceneStateDidDisableUI:(SceneState*)sceneState { + [self.firstRunCoordinator stop]; + + [self tearDownPolicyWatcher]; + + [sceneState removeObserver:self]; + self.presentingSceneState = nil; +} + #pragma mark - AppStateObserver - (void)appState:(AppState*)appState @@ -145,6 +157,8 @@ // Select the first scene that the app declares as initialized to present // the FRE UI on. self.presentingSceneState = sceneState; + [self.presentingSceneState addObserver:self]; + self.presentingInterface = self.presentingSceneState.interfaceProvider.currentInterface; self.mainBrowser = @@ -193,8 +207,13 @@ } - (void)tearDownPolicyWatcher { + if (!_policyWatcherObserverBridge) { + return; + } + PolicyWatcherBrowserAgent::FromBrowser(self.mainBrowser) ->RemoveObserver(_policyWatcherObserverBridge.get()); + _policyWatcherObserverBridge = nil; } - (void)showFirstRunUI {
diff --git a/ios/chrome/app/main_application_delegate.mm b/ios/chrome/app/main_application_delegate.mm index 341261b..2ddb7a5 100644 --- a/ios/chrome/app/main_application_delegate.mm +++ b/ios/chrome/app/main_application_delegate.mm
@@ -171,6 +171,15 @@ [_appState application:application didDiscardSceneSessions:sceneSessions]; } +- (UIInterfaceOrientationMask)application:(UIApplication*)application + supportedInterfaceOrientationsForWindow:(UIWindow*)window { + if (_appState.portraitOnly) { + return UIInterfaceOrientationMaskPortrait; + } + // Apply a no-op mask by default. + return UIInterfaceOrientationMaskAll; +} + #pragma mark - Scenes lifecycle - (NSInteger)foregroundSceneCount {
diff --git a/ios/chrome/browser/context_menu/BUILD.gn b/ios/chrome/browser/context_menu/BUILD.gn index c5a2f2e67..dc39891 100644 --- a/ios/chrome/browser/context_menu/BUILD.gn +++ b/ios/chrome/browser/context_menu/BUILD.gn
@@ -20,6 +20,7 @@ "//ios/chrome/test/earl_grey:eg_test_support+eg2", "//ios/testing/earl_grey:eg_test_support+eg2", "//ios/third_party/earl_grey2:test_lib", + "//ios/web/common:features", "//ios/web/public/test:element_selector", "//net:test_support", "//url",
diff --git a/ios/chrome/browser/context_menu/context_menu_egtest.mm b/ios/chrome/browser/context_menu/context_menu_egtest.mm index d49271a..7498dfd2 100644 --- a/ios/chrome/browser/context_menu/context_menu_egtest.mm +++ b/ios/chrome/browser/context_menu/context_menu_egtest.mm
@@ -18,8 +18,10 @@ #import "ios/chrome/test/earl_grey/chrome_earl_grey_ui.h" #import "ios/chrome/test/earl_grey/chrome_matchers.h" #import "ios/chrome/test/earl_grey/chrome_test_case.h" +#import "ios/chrome/test/earl_grey/chrome_xcui_actions.h" #import "ios/testing/earl_grey/disabled_test_macros.h" #import "ios/testing/earl_grey/earl_grey_test.h" +#include "ios/web/common/features.h" #include "ios/web/public/test/element_selector.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" @@ -415,13 +417,25 @@ // Tap the tools menu to dismiss the popover. [[EarlGrey selectElementWithMatcher:chrome_test_util::ToolsMenuButton()] performAction:grey_tap()]; + } else if (web::features::UseWebViewNativeContextMenuSystem()) { + // Tap the drop shadow to dismiss the popover. + chrome_test_util::TapAtOffsetOf(nil, 0, CGVectorMake(0.5, 0.95)); } else { TapOnContextMenuButton(chrome_test_util::CancelButton()); } // Make sure the context menu disappeared. - [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] - assertWithMatcher:grey_nil()]; + ConditionBlock condition = ^{ + NSError* error = nil; + [[EarlGrey selectElementWithMatcher:OpenLinkInNewTabButton()] + assertWithMatcher:grey_nil() + error:&error]; + return error == nil; + }; + + GREYAssert(base::test::ios::WaitUntilConditionOrTimeout( + base::test::ios::kWaitForUIElementTimeout, condition), + @"Waiting for the context menu to disappear"); } // Display the context menu one last time. @@ -449,17 +463,22 @@ assertWithMatcher:grey_sufficientlyVisible()]; [[EarlGrey selectElementWithMatcher: chrome_test_util::ButtonWithAccessibilityLabelId( - IDS_IOS_CONTENT_CONTEXT_OPENLINKNEWINCOGNITOTAB)] + web::features::UseWebViewNativeContextMenuSystem() + ? IDS_IOS_OPEN_IN_INCOGNITO_ACTION_TITLE + : IDS_IOS_CONTENT_CONTEXT_OPENLINKNEWINCOGNITOTAB)] assertWithMatcher:grey_sufficientlyVisible()]; [[EarlGrey selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( IDS_IOS_CONTENT_CONTEXT_ADDTOREADINGLIST)] assertWithMatcher:grey_sufficientlyVisible()]; - [[EarlGrey - selectElementWithMatcher:chrome_test_util::ButtonWithAccessibilityLabelId( - IDS_IOS_CONTENT_CONTEXT_COPY)] + [[EarlGrey selectElementWithMatcher: + chrome_test_util::ButtonWithAccessibilityLabelId( + web::features::UseWebViewNativeContextMenuSystem() + ? IDS_IOS_COPY_LINK_ACTION_TITLE + : IDS_IOS_CONTENT_CONTEXT_COPY)] assertWithMatcher:grey_sufficientlyVisible()]; - if (![ChromeEarlGrey isIPadIdiom]) { + if (![ChromeEarlGrey isIPadIdiom] && + !web::features::UseWebViewNativeContextMenuSystem()) { [[EarlGrey selectElementWithMatcher: chrome_test_util::ButtonWithAccessibilityLabelId(IDS_CANCEL)] assertWithMatcher:grey_sufficientlyVisible()];
diff --git a/ios/chrome/browser/crash_report/BUILD.gn b/ios/chrome/browser/crash_report/BUILD.gn index cbc3292f..fb7275c 100644 --- a/ios/chrome/browser/crash_report/BUILD.gn +++ b/ios/chrome/browser/crash_report/BUILD.gn
@@ -99,6 +99,7 @@ "crash_reporter_breadcrumb_observer_unittest.mm", "crash_reporter_url_observer_unittest.mm", "crash_restore_helper_unittest.mm", + "main_thread_freeze_detector_unittest.mm", "synthetic_crash_report_util_unittest.mm", ] deps = [
diff --git a/ios/chrome/browser/crash_report/crash_helper.mm b/ios/chrome/browser/crash_report/crash_helper.mm index 8aeb31a..4abe2433 100644 --- a/ios/chrome/browser/crash_report/crash_helper.mm +++ b/ios/chrome/browser/crash_report/crash_helper.mm
@@ -60,6 +60,7 @@ // begin uploading when possible. void ProcessIntermediateDumps() { crash_reporter::ProcessIntermediateDumps(); + [[MainThreadFreezeDetector sharedInstance] processIntermediateDumps]; crash_reporter::StartProcessingPendingReports(); } @@ -216,6 +217,8 @@ if (crash_reporter::IsCrashpadRunning()) { crash_reporter::SetUploadConsent(enabled); + [[MainThreadFreezeDetector sharedInstance] prepareCrashReportsForUpload:^(){ + }]; return; }
diff --git a/ios/chrome/browser/crash_report/main_thread_freeze_detector.h b/ios/chrome/browser/crash_report/main_thread_freeze_detector.h index a07a943..1086b9f 100644 --- a/ios/chrome/browser/crash_report/main_thread_freeze_detector.h +++ b/ios/chrome/browser/crash_report/main_thread_freeze_detector.h
@@ -37,13 +37,24 @@ // Enables or disables the main thread watchdog. This will also start or stop // the monitoring of the main thread. - (void)setEnabled:(BOOL)enabled; -// Prepare the UTE report before breakpad is allowed to upload reports. -// Call completion on main thread when complete. -// If this is called multiple timed before |completion| is called, only the -// latest |completion| block will be called. -// The function will queue the UTE report to be uploaded if there is no newer -// crash report in the Breakpad directory. +// Prepare the UTE report before the crash handler starts to uploading them. +// If using Breakpad: +// Call completion on main thread when complete. If this is called multiple +// times before |completion| is called, only the latest |completion| block will +// be called. The function will queue the UTE report to be uploaded if there is +// no newer crash report in the Breakpad directory. +// If using Crashpad: +// Completion unused by Crashpad. Because -prepareCrashReportsForUpload is +// called early enough on startup, Crashpad has not processed crash intermediate +// dumps yet. Since the UTE directory should be cleared to avoid duplicate UTE +// reports, move any UTE reports from the previous session to a to-be-processed +// location to be used by -processIntermediateDumps. - (void)prepareCrashReportsForUpload:(ProceduralBlock)completion; +// Crashpad only. Tell Crashpad to process UTE intermediate dumps if there are +// no newer crash reports. This should only be called after +// crash_reporter::ProcessIntermediateDumps(), otherwise there would be no +// way to see if a crash happened after the UTE report was generated. +- (void)processIntermediateDumps; @end #endif // IOS_CHROME_BROWSER_CRASH_REPORT_MAIN_THREAD_FREEZE_DETECTOR_H_
diff --git a/ios/chrome/browser/crash_report/main_thread_freeze_detector.mm b/ios/chrome/browser/crash_report/main_thread_freeze_detector.mm index 0a3e4240..18ecb8e 100644 --- a/ios/chrome/browser/crash_report/main_thread_freeze_detector.mm +++ b/ios/chrome/browser/crash_report/main_thread_freeze_detector.mm
@@ -6,6 +6,7 @@ #include "base/debug/debugger.h" #include "base/metrics/histogram_macros.h" +#include "base/strings/sys_string_conversions.h" #include "base/time/time.h" #include "components/crash/core/app/crashpad.h" #include "components/crash/core/common/crash_key.h" @@ -46,7 +47,8 @@ enum class IOSMainThreadFreezeDetectionNotRunningAfterReportBlock { kAfterBreakpadRef = 0, kAfterFileManagerUTEMove = 1, - kMaxValue = kAfterFileManagerUTEMove, + kAfterCrashpadDumpWithoutCrash = 2, + kMaxValue = kAfterCrashpadDumpWithoutCrash, }; } // namespace @@ -77,9 +79,13 @@ // "dump": the file name of the .dmp file in |_UTEDirectory|, // "config": the file name of the config file in |_UTEDirectory|, // "date": the date at which the UTE file was generated. + // NOTE: Fields are unused with crashpad. NSDictionary* _lastSessionFreezeInfo; // The directory containing the UTE crash reports. NSString* _UTEDirectory; + // The directory containing UTE crash reports eligible for crashpad + // processing. + NSString* _UTEPendingCrashpadDirectory; // The block to call (on main thread) once the UTE report is restored in the // breakpad directory. ProceduralBlock _restorationCompletion; @@ -121,6 +127,19 @@ NSCachesDirectory, NSUserDomainMask, YES)[0]; _UTEDirectory = [cacheDirectory stringByAppendingPathComponent:@"UTE"]; + [[[NSFileManager alloc] init] createDirectoryAtPath:_UTEDirectory + withIntermediateDirectories:YES + attributes:nil + error:nil]; + + _UTEPendingCrashpadDirectory = + [cacheDirectory stringByAppendingPathComponent:@"UTE_CrashpadPending"]; + [[[NSFileManager alloc] init] + createDirectoryAtPath:_UTEPendingCrashpadDirectory + withIntermediateDirectories:YES + attributes:nil + error:nil]; + // Like breakpad, the feature is created immediately in the enabled state as // the settings are not available yet when it is started. _enabled = YES; @@ -193,6 +212,10 @@ // It will be cleared on completion of processing the previous session. NSFileManager* fileManager = [[NSFileManager alloc] init]; [fileManager removeItemAtPath:_UTEDirectory error:nil]; + [fileManager createDirectoryAtPath:_UTEDirectory + withIntermediateDirectories:NO + attributes:nil + error:nil]; } [self runInFreezeDetectionQueue]; } @@ -206,7 +229,20 @@ if (crash_reporter::IsCrashpadRunning()) { static crash_reporter::CrashKeyString<4> key("hang-report"); crash_reporter::ScopedCrashKeyString auto_clear(&key, "yes"); - crash_reporter::DumpWithoutCrashAndDeferProcessing(); + base::FilePath path(base::SysNSStringToUTF8(_UTEDirectory)); + crash_reporter::DumpWithoutCrashAndDeferProcessingAtPath(path); + if (!self.running) { + UMA_HISTOGRAM_ENUMERATION( + kUMAMainThreadFreezeDetectionNotRunningAfterReport, + IOSMainThreadFreezeDetectionNotRunningAfterReportBlock:: + kAfterCrashpadDumpWithoutCrash); + return; + } + // Fields unused by Crashpad. Change to bool if Breakpad is deprecated. + [[NSUserDefaults standardUserDefaults] + setObject:@{@"dump" : @"", @"config" : @"", @"date" : [NSDate date]} + forKey:@(kNsUserDefaultKeyLastSessionInfo)]; + self.reportGenerated = YES; return; } @@ -253,12 +289,6 @@ NSString* UTEDumpFile = [_UTEDirectory stringByAppendingPathComponent:[dumpFile lastPathComponent]]; NSFileManager* fileManager = [[NSFileManager alloc] init]; - - // Clear previous reports if they exist. - [fileManager createDirectoryAtPath:_UTEDirectory - withIntermediateDirectories:NO - attributes:nil - error:nil]; [fileManager moveItemAtPath:configFile toPath:UTEConfigFile error:nil]; [fileManager moveItemAtPath:dumpFile toPath:UTEDumpFile error:nil]; if (!self.running) { @@ -278,6 +308,41 @@ self.reportGenerated = YES; } +- (void)processIntermediateDumps { + NSFileManager* fileManager = [[NSFileManager alloc] init]; + NSArray<NSString*>* UTEPendingDirectoryContents = + [fileManager contentsOfDirectoryAtPath:_UTEPendingCrashpadDirectory + error:NULL]; + if (!UTEPendingDirectoryContents.count) + return; + + // Get the most recent crash capture_time. -GetReports is already sorted + // by newest first so just grab the first one. + time_t newest_crash = 0; + std::vector<crash_reporter::Report> reports; + crash_reporter::GetReports(&reports); + if (reports.size()) + newest_crash = reports[0].capture_time; + + // Process any hang reports that have a modification time newer than the + // newest crash. + for (NSString* pendingFile : UTEPendingDirectoryContents) { + NSString* hang_report = [_UTEPendingCrashpadDirectory + stringByAppendingPathComponent:pendingFile]; + NSDate* UTECrashDate = [[fileManager attributesOfItemAtPath:hang_report + error:nil] + objectForKey:NSFileModificationDate]; + time_t crash_time = + static_cast<time_t>([UTECrashDate timeIntervalSince1970]); + if (crash_time > newest_crash) { + base::FilePath path(base::SysNSStringToUTF8(hang_report)); + crash_reporter::ProcessIntermediateDump(path); + } + } + // Delete the directory when done to clear any un-processed reports. + [fileManager removeItemAtPath:_UTEPendingCrashpadDirectory error:nil]; +} + - (void)prepareCrashReportsForUpload:(ProceduralBlock)completion { DCHECK(completion); _restorationCompletion = completion; @@ -290,19 +355,37 @@ } - (void)restoreLastSessionReportIfNeeded { - NSString* cacheDirectory = NSSearchPathForDirectoriesInDomains( - NSCachesDirectory, NSUserDomainMask, YES)[0]; - NSString* breakpadDirectory = - [cacheDirectory stringByAppendingPathComponent:@"Breakpad"]; if (!_lastSessionFreezeInfo) { return; } - // Tests that the dump file still exist. NSFileManager* fileManager = [[NSFileManager alloc] init]; + if (crash_reporter::IsCrashpadRunning()) { + NSArray<NSString*>* UTEDirectoryContents = + [fileManager contentsOfDirectoryAtPath:_UTEDirectory error:NULL]; + if (UTEDirectoryContents.count != 1) + return; + + // Backup hang_report to a new location. See -processIntermediateDumps for + // why this is necessary. + NSString* hang_report = + [_UTEDirectory stringByAppendingPathComponent:UTEDirectoryContents[0]]; + NSString* save_hang_report = [_UTEPendingCrashpadDirectory + stringByAppendingPathComponent:UTEDirectoryContents[0]]; + [fileManager moveItemAtPath:hang_report toPath:save_hang_report error:nil]; + return; + } + + // Tests that the dump file still exist. NSString* dumpFile = [_lastSessionFreezeInfo objectForKey:@"dump"]; + if (![dumpFile length]) + return; NSString* UTEDumpFile = [_UTEDirectory stringByAppendingPathComponent:dumpFile]; + NSString* cacheDirectory = NSSearchPathForDirectoriesInDomains( + NSCachesDirectory, NSUserDomainMask, YES)[0]; + NSString* breakpadDirectory = + [cacheDirectory stringByAppendingPathComponent:@"Breakpad"]; NSString* breakpadDumpFile = [breakpadDirectory stringByAppendingPathComponent:dumpFile]; if (!UTEDumpFile || ![fileManager fileExistsAtPath:UTEDumpFile]) { @@ -356,6 +439,11 @@ // |_freezeDetectionQueue| and is called directly from the main thread // |prepareToUpload| which mean that main thread was responding recently. [fileManager removeItemAtPath:_UTEDirectory error:nil]; + [fileManager createDirectoryAtPath:_UTEDirectory + withIntermediateDirectories:NO + attributes:nil + error:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ [self handleSessionRestorationCompletion]; });
diff --git a/ios/chrome/browser/crash_report/main_thread_freeze_detector_unittest.mm b/ios/chrome/browser/crash_report/main_thread_freeze_detector_unittest.mm new file mode 100644 index 0000000..38128b0f --- /dev/null +++ b/ios/chrome/browser/crash_report/main_thread_freeze_detector_unittest.mm
@@ -0,0 +1,47 @@ +// Copyright 2021 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 <Foundation/Foundation.h> + +#import "base/test/ios/wait_util.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "testing/platform_test.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +namespace { + +using MainThreadFreezeDetectorTest = PlatformTest; + +// Tests that moving a file preserves the NSFileModificationDate. +TEST_F(MainThreadFreezeDetectorTest, FileMoveSameModificationDate) { + NSFileManager* file_manager = [[NSFileManager alloc] init]; + NSString* temp_dir = file_manager.temporaryDirectory.path; + NSString* contents = @"test_NSFileModificationDate"; + NSString* filename1 = [[NSProcessInfo processInfo] globallyUniqueString]; + NSString* filename2 = [[NSProcessInfo processInfo] globallyUniqueString]; + NSString* original_file = [temp_dir stringByAppendingPathComponent:filename1]; + NSString* new_file = [temp_dir stringByAppendingPathComponent:filename2]; + ASSERT_TRUE([contents writeToFile:original_file + atomically:YES + encoding:NSUTF8StringEncoding + error:NULL]); + + NSDate* date1 = [[file_manager attributesOfItemAtPath:original_file error:nil] + objectForKey:NSFileModificationDate]; + // Spin the run loop so, if the move below uses an updated modification date, + // |date2| will not match (which would be a test failure). + base::test::ios::SpinRunLoopWithMinDelay( + base::TimeDelta::FromMilliseconds(40)); + ASSERT_TRUE([file_manager moveItemAtPath:original_file + toPath:new_file + error:nil]); + NSDate* date2 = [[file_manager attributesOfItemAtPath:new_file error:nil] + objectForKey:NSFileModificationDate]; + ASSERT_TRUE([date1 isEqualToDate:date2]); +} + +} // namespace
diff --git a/ios/chrome/browser/policy/browser_policy_connector_ios.h b/ios/chrome/browser/policy/browser_policy_connector_ios.h index 6800171..90bebe6 100644 --- a/ios/chrome/browser/policy/browser_policy_connector_ios.h +++ b/ios/chrome/browser/policy/browser_policy_connector_ios.h
@@ -8,7 +8,6 @@ #include <memory> #include <string> -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "components/enterprise/browser/controller/chrome_browser_cloud_management_controller.h" #include "components/policy/core/browser/browser_policy_connector.h" @@ -32,6 +31,9 @@ BrowserPolicyConnectorIOS( const policy::HandlerListFactory& handler_list_factory); + BrowserPolicyConnectorIOS(const BrowserPolicyConnectorIOS&) = delete; + BrowserPolicyConnectorIOS& operator=(const BrowserPolicyConnectorIOS&) = + delete; ~BrowserPolicyConnectorIOS() override; @@ -78,8 +80,6 @@ chrome_browser_cloud_management_controller_; policy::MachineLevelUserCloudPolicyManager* machine_level_user_cloud_policy_manager_ = nullptr; - - DISALLOW_COPY_AND_ASSIGN(BrowserPolicyConnectorIOS); }; #endif // IOS_CHROME_BROWSER_POLICY_BROWSER_POLICY_CONNECTOR_IOS_H_
diff --git a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm index 3dea8b61..ac4da5c4 100644 --- a/ios/chrome/browser/ui/browser_view/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view/browser_view_controller.mm
@@ -5045,12 +5045,16 @@ AddSameConstraints(self.view, self.blockingView); self.blockingView.alpha = 1; [self.omniboxHandler cancelOmniboxEdit]; - // Resign the first responder. This achieves multiple goals: // 1. The keyboard is dismissed. // 2. Hardware keyboard events (such as space to scroll) will be ignored. UIResponder* firstResponder = GetFirstResponder(); [firstResponder resignFirstResponder]; + // Close presented view controllers, e.g. share sheets. + if (self.presentedViewController) { + [self dismissViewControllerAnimated:NO completion:nil]; + } + } else { [UIView animateWithDuration:0.2 animations:^{
diff --git a/ios/chrome/browser/ui/content_suggestions/BUILD.gn b/ios/chrome/browser/ui/content_suggestions/BUILD.gn index 4a257bc..ae037c11 100644 --- a/ios/chrome/browser/ui/content_suggestions/BUILD.gn +++ b/ios/chrome/browser/ui/content_suggestions/BUILD.gn
@@ -14,8 +14,6 @@ "content_suggestions_coordinator.mm", "content_suggestions_favicon_mediator.h", "content_suggestions_favicon_mediator.mm", - "content_suggestions_header_view_controller.h", - "content_suggestions_header_view_controller.mm", "content_suggestions_mediator.h", "content_suggestions_mediator.mm", "content_suggestions_metrics_recorder.h", @@ -107,7 +105,6 @@ "//ios/public/provider/chrome/browser/images", "//ios/public/provider/chrome/browser/signin", "//ios/public/provider/chrome/browser/ui", - "//ios/public/provider/chrome/browser/voice", "//ui/base", "//ui/strings", ] @@ -142,6 +139,8 @@ "content_suggestions_header_synchronizing.h", "content_suggestions_header_view.h", "content_suggestions_header_view.mm", + "content_suggestions_header_view_controller.h", + "content_suggestions_header_view_controller.mm", "content_suggestions_header_view_controller_delegate.h", "content_suggestions_layout.h", "content_suggestions_layout.mm", @@ -167,7 +166,9 @@ "resources:ntp_search_icon", "//base", "//components/strings", + "//ios/chrome/app/strings", "//ios/chrome/browser", + "//ios/chrome/browser/ntp", "//ios/chrome/browser/ui:feature_flags", "//ios/chrome/browser/ui/bubble", "//ios/chrome/browser/ui/collection_view", @@ -193,6 +194,8 @@ "//ios/chrome/common/ui/util", "//ios/public/provider/chrome/browser", "//ios/public/provider/chrome/browser/discover_feed", + "//ios/public/provider/chrome/browser/ui", + "//ios/public/provider/chrome/browser/voice", "//ios/web/common", "//ui/base", ]
diff --git a/ios/chrome/browser/ui/first_run/first_run_coordinator.mm b/ios/chrome/browser/ui/first_run/first_run_coordinator.mm index e255077..3f1944b 100644 --- a/ios/chrome/browser/ui/first_run/first_run_coordinator.mm +++ b/ios/chrome/browser/ui/first_run/first_run_coordinator.mm
@@ -36,6 +36,8 @@ @property(nonatomic, readonly, weak) id<SyncPresenter> presenter; // The main browser that can be used for authentication. @property(nonatomic, readonly) Browser* mainBrowser; +// YES if First Run was completed. +@property(nonatomic, assign) BOOL completed; @end @@ -73,14 +75,22 @@ - (void)stop { void (^completion)(void) = ^{ - base::UmaHistogramEnumeration("FirstRun.Stage", first_run::kComplete); - WriteFirstRunSentinel(); - - // If the remaining screens have been skipped, additional actions will be - // executed. - [self.delegate didFinishPresentingScreensWithSubsequentActionsTriggered: - self.screensSkipped]; }; + if (self.completed) { + completion = ^{ + base::UmaHistogramEnumeration("FirstRun.Stage", first_run::kComplete); + WriteFirstRunSentinel(); + + // If the remaining screens have been skipped, additional actions will be + // executed. + [self.delegate didFinishPresentingScreensWithSubsequentActionsTriggered: + self.screensSkipped]; + }; + } + + [self.childCoordinator stop]; + self.childCoordinator = nil; + [self.baseViewController dismissViewControllerAnimated:YES completion:completion]; } @@ -97,7 +107,7 @@ [self.childCoordinator stop]; self.childCoordinator = nil; self.screensSkipped = YES; - [self.delegate willFinishPresentingScreens]; + [self willFinishPresentingScreens]; } - (void)skipAllAndShowSyncSettings { @@ -121,7 +131,7 @@ // If no more screen need to be present, call delegate to stop presenting // screens. if (type == kFirstRunCompleted) { - [self.delegate willFinishPresentingScreens]; + [self willFinishPresentingScreens]; return; } self.childCoordinator = [self createChildCoordinatorWithScreenType:type]; @@ -157,4 +167,9 @@ return nil; } +- (void)willFinishPresentingScreens { + self.completed = YES; + [self.delegate willFinishPresentingScreens]; +} + @end
diff --git a/ios/chrome/browser/ui/first_run/fre_field_trial.cc b/ios/chrome/browser/ui/first_run/fre_field_trial.cc index 8d26764..dafed5b 100644 --- a/ios/chrome/browser/ui/first_run/fre_field_trial.cc +++ b/ios/chrome/browser/ui/first_run/fre_field_trial.cc
@@ -49,9 +49,9 @@ case version_info::Channel::CANARY: case version_info::Channel::DEV: case version_info::Channel::BETA: - enabled_percent = 0; - control_percent = 0; - default_percent = 100; + enabled_percent = 50; + control_percent = 50; + default_percent = 0; break; case version_info::Channel::STABLE: enabled_percent = 0;
diff --git a/ios/chrome/browser/ui/first_run/welcome_to_chrome_view.mm b/ios/chrome/browser/ui/first_run/welcome_to_chrome_view.mm index ff6af27..d068a2d3 100644 --- a/ios/chrome/browser/ui/first_run/welcome_to_chrome_view.mm +++ b/ios/chrome/browser/ui/first_run/welcome_to_chrome_view.mm
@@ -17,9 +17,6 @@ #import "ios/chrome/browser/ui/elements/text_view_selection_disabled.h" #include "ios/chrome/browser/ui/fancy_ui/primary_action_button.h" #include "ios/chrome/browser/ui/first_run/first_run_util.h" -#import "ios/chrome/browser/ui/util/CRUILabel+AttributeUtils.h" -#import "ios/chrome/browser/ui/util/label_link_controller.h" -#import "ios/chrome/browser/ui/util/label_observer.h" #include "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" #include "ios/chrome/common/string_util.h" @@ -55,6 +52,29 @@ } } +// Sets the line height for |label| via attributed text. +void SetLabelLineHeight(UILabel* label, CGFloat line_height) { + NSMutableAttributedString* updated_text = [label.attributedText mutableCopy]; + if (updated_text.length == 0) + return; + + NSParagraphStyle* style = + [updated_text attribute:NSParagraphStyleAttributeName + atIndex:0 + effectiveRange:nullptr]; + if (!style) + style = [NSParagraphStyle defaultParagraphStyle]; + + NSMutableParagraphStyle* updated_style = [style mutableCopy]; + [updated_style setMinimumLineHeight:line_height]; + [updated_style setMaximumLineHeight:line_height]; + [updated_text addAttribute:NSParagraphStyleAttributeName + value:updated_style + range:NSMakeRange(0, [updated_text length])]; + + label.attributedText = updated_text; +} + // Tags used to embed TOS link. NSString* const kBeginTOSLinkTag = @"BEGIN_LINK_TOS[ \t]*"; NSString* const kEndTOSLinkTag = @"[ \t]*END_LINK_TOS"; @@ -84,7 +104,6 @@ // Font sizes. const CGFloat kTitleLabelFontSize[SIZE_CLASS_COUNT] = {24.0, 36.0}; const CGFloat kTOSTOSTextViewFontSize[SIZE_CLASS_COUNT] = {14.0, 21.0}; -const CGFloat kLegacyTOSLabelLineHeight[SIZE_CLASS_COUNT] = {20.0, 32.0}; const CGFloat kOptInLabelFontSize[SIZE_CLASS_COUNT] = {13.0, 19.0}; const CGFloat kOptInLabelLineHeight[SIZE_CLASS_COUNT] = {18.0, 26.0}; const CGFloat kManagedLabelFontSize[SIZE_CLASS_COUNT] = {13.0, 19.0}; @@ -116,20 +135,9 @@ UILabel* _managedLabel; UIImageView* _enterpriseIcon; PrimaryActionButton* _OKButton; - - // Used for iOS 12 compatibility. - UILabel* _legacyTOSLabel; - LabelLinkController* _legacyTOSLabelLinkController; } // Subview properties are lazily instantiated upon their first use. - -// The "Terms of Service" legacy label used for iOS 12 compatibility. -@property(strong, nonatomic, readonly) UILabel* legacyTOSLabel; -// Legacy observer for setting the size of the TOSLabel with cr_lineHeight used -// for iOS 12 compatibility. -@property(strong, nonatomic) LabelObserver* legacyTOSObserver; - // A container view used to layout and center subviews. @property(strong, nonatomic, readonly) UIView* containerView; // The "Welcome to Chrome" label that appears at the top of the view. @@ -140,12 +148,8 @@ @property(strong, nonatomic) TextViewSelectionDisabled* TOSTextView; // The stats reporting opt-in label. @property(strong, nonatomic, readonly) UILabel* optInLabel; -// Observer for setting the size of the optInLabel with cr_lineHeight. -@property(strong, nonatomic) LabelObserver* optInObserver; // The stats reporting opt-in checkbox button. @property(strong, nonatomic, readonly) UIButton* checkBoxButton; -// Observer for setting the size of the managedLabel with cr_lineHeight. -@property(strong, nonatomic) LabelObserver* managedObserver; // The Chrome logo image view. @property(strong, nonatomic, readonly) UIImageView* enterpriseIcon; // The "Accept & Continue" button. @@ -200,7 +204,6 @@ // and finding the initial and final location of the logo. self.titleLabel.alpha = 0.0; self.TOSTextView.alpha = 0.0; - self.legacyTOSLabel.alpha = 0.0; self.optInLabel.alpha = 0.0; self.checkBoxButton.alpha = 0.0; self.managedLabel.alpha = 0.0; @@ -224,7 +227,6 @@ [weakSelf imageView].frame = finalLogoFrame; [weakSelf titleLabel].alpha = 1.0; [weakSelf TOSTextView].alpha = 1.0; - [weakSelf legacyTOSLabel].alpha = 1.0; [weakSelf optInLabel].alpha = 1.0; [weakSelf managedLabel].alpha = 1.0; [weakSelf enterpriseIcon].alpha = 1.0; @@ -234,12 +236,6 @@ completion:nil]; } -- (void)dealloc { - [self.legacyTOSObserver stopObserving]; - - [self.optInObserver stopObserving]; -} - #pragma mark - Accessors - (BOOL)isCheckBoxSelected { @@ -285,26 +281,9 @@ return _TOSTextView; } -- (UILabel*)legacyTOSLabel { - if (!_legacyTOSLabel) { - _legacyTOSLabel = [[UILabel alloc] initWithFrame:CGRectZero]; - // Add an observer to the label to be able to keep the cr_lineHeight. - self.legacyTOSObserver = [LabelObserver observerForLabel:_legacyTOSLabel]; - [self.legacyTOSObserver startObserving]; - - [_legacyTOSLabel setNumberOfLines:0]; - [_legacyTOSLabel setTextAlignment:NSTextAlignmentCenter]; - } - return _legacyTOSLabel; -} - - (UILabel*)optInLabel { if (!_optInLabel) { _optInLabel = [[UILabel alloc] initWithFrame:CGRectZero]; - // Add an observer to the label to be able to keep the cr_lineHeight. - self.optInObserver = [LabelObserver observerForLabel:_optInLabel]; - [self.optInObserver startObserving]; - [_optInLabel setNumberOfLines:0]; [_optInLabel setText:l10n_util::GetNSString(IDS_IOS_FIRSTRUN_NEW_OPT_IN_LABEL)]; @@ -337,10 +316,6 @@ - (UILabel*)managedLabel { if (!_managedLabel) { _managedLabel = [[UILabel alloc] initWithFrame:CGRectZero]; - // Add an observer to the label to be able to keep the cr_lineHeight. - self.managedObserver = [LabelObserver observerForLabel:_managedLabel]; - [self.managedObserver startObserving]; - [_managedLabel setNumberOfLines:0]; [_managedLabel setText:l10n_util::GetNSString(IDS_IOS_FIRSTRUN_BROWSER_MANAGED)]; @@ -394,11 +369,7 @@ [self addSubview:self.containerView]; [self.containerView addSubview:self.titleLabel]; [self.containerView addSubview:self.imageView]; - if (@available(iOS 13.5, *)) { - [self.containerView addSubview:self.TOSTextView]; - } else { - [self.containerView addSubview:self.legacyTOSLabel]; - } + [self.containerView addSubview:self.TOSTextView]; [self.containerView addSubview:self.optInLabel]; [self.containerView addSubview:self.checkBoxButton]; if ([self isBrowserManaged]) { @@ -422,11 +393,7 @@ [super layoutSubviews]; [self layoutTitleLabel]; [self layoutImageView]; - if (@available(iOS 13.5, *)) { - [self layoutTOSTextView]; - } else { - [self layoutLegacyTOSLabel]; - } + [self layoutTOSTextView]; [self layoutOptInLabel]; [self layoutCheckBoxButton]; if ([self isBrowserManaged]) { @@ -479,45 +446,6 @@ self.TOSTextView.frame = AlignRectOriginAndSizeToPixels(frame); } -- (void)layoutLegacyTOSLabel { - // The TOS label is centered and laid out below |imageView| as specified by - // kTOSLabelTopPadding. - CGSize containerSize = self.containerView.bounds.size; - containerSize.height = CGFLOAT_MAX; - self.legacyTOSLabel.frame = {CGPointZero, containerSize}; - const StringWithTag parsedString = ParseStringWithTag( - l10n_util::GetNSString(IDS_IOS_FIRSTRUN_AGREE_TO_TERMS), kBeginTOSLinkTag, - kEndTOSLinkTag); - DCHECK(parsedString.range != NSMakeRange(NSNotFound, 0)); - self.legacyTOSLabel.text = parsedString.string; - - __weak WelcomeToChromeView* weakSelf = self; - ProceduralBlockWithURL action = ^(const GURL& url) { - WelcomeToChromeView* strongSelf = weakSelf; - if (!strongSelf) - return; - if (url == kTermsOfServiceUrl) { - [[strongSelf delegate] welcomeToChromeViewDidTapTOSLink]; - } else { - NOTREACHED(); - } - }; - - _legacyTOSLabelLinkController = - [[LabelLinkController alloc] initWithLabel:_legacyTOSLabel action:action]; - [_legacyTOSLabelLinkController addLinkWithRange:parsedString.range - url:GURL(kTermsOfServiceUrl)]; - [_legacyTOSLabelLinkController setLinkColor:[UIColor colorNamed:kBlueColor]]; - - CGSize TOSLabelSize = [self.legacyTOSLabel sizeThatFits:containerSize]; - CGFloat TOSLabelTopPadding = - kTOSTextViewTopPadding[[self heightSizeClassIdiom]]; - self.legacyTOSLabel.frame = AlignRectOriginAndSizeToPixels( - CGRectMake((containerSize.width - TOSLabelSize.width) / 2.0, - CGRectGetMaxY(self.imageView.frame) + TOSLabelTopPadding, - TOSLabelSize.width, TOSLabelSize.height)); -} - - (void)layoutOptInLabel { // The opt in label is laid out to the right (or left in RTL) of the check box // button and below |TOSLabel| as specified by kOptInLabelPadding. @@ -533,17 +461,10 @@ kOptInLabelPadding[[self heightSizeClassIdiom]]; CGFloat optInLabelOriginX = base::i18n::IsRTL() ? 0.0f : optInLabelSidePadding; - if (@available(iOS 13.5, *)) { - self.optInLabel.frame = AlignRectOriginAndSizeToPixels( - CGRectMake(optInLabelOriginX, - CGRectGetMaxY(self.TOSTextView.frame) + optInLabelTopPadding, - optInLabelSize.width, optInLabelSize.height)); - } else { - self.optInLabel.frame = AlignRectOriginAndSizeToPixels(CGRectMake( - optInLabelOriginX, - CGRectGetMaxY(self.legacyTOSLabel.frame) + optInLabelTopPadding, - optInLabelSize.width, optInLabelSize.height)); - } + self.optInLabel.frame = AlignRectOriginAndSizeToPixels( + CGRectMake(optInLabelOriginX, + CGRectGetMaxY(self.TOSTextView.frame) + optInLabelTopPadding, + optInLabelSize.width, optInLabelSize.height)); } - (void)layoutCheckBoxButton { @@ -662,11 +583,7 @@ [self configureContainerView]; [self configureTitleLabel]; [self configureImageView]; - if (@available(iOS 13.5, *)) { - [self configureTOSTextView]; - } else { - [self configureLegacyTOSLabel]; - } + [self configureTOSTextView]; [self configureOptInLabel]; if ([self isBrowserManaged]) { [self configureManagedLabel]; @@ -733,23 +650,16 @@ - (void)configureOptInLabel { self.optInLabel.font = [[MDCTypography fontLoader] regularFontOfSize:kOptInLabelFontSize[[self widthSizeClassIdiom]]]; - self.optInLabel.cr_lineHeight = - kOptInLabelLineHeight[[self widthSizeClassIdiom]]; + SetLabelLineHeight(self.optInLabel, + kOptInLabelLineHeight[[self widthSizeClassIdiom]]); } - (void)configureManagedLabel { self.managedLabel.font = [[MDCTypography fontLoader] regularFontOfSize:kManagedLabelFontSize[[self widthSizeClassIdiom]]]; - self.managedLabel.cr_lineHeight = - kManagedLabelLineHeight[[self widthSizeClassIdiom]]; self.managedLabel.textColor = [UIColor colorNamed:kTextSecondaryColor]; -} - -- (void)configureLegacyTOSLabel { - self.legacyTOSLabel.font = [[MDCTypography fontLoader] - regularFontOfSize:kTOSTOSTextViewFontSize[[self widthSizeClassIdiom]]]; - self.legacyTOSLabel.cr_lineHeight = - kLegacyTOSLabelLineHeight[[self widthSizeClassIdiom]]; + SetLabelLineHeight(self.managedLabel, + kManagedLabelLineHeight[[self widthSizeClassIdiom]]); } - (void)configureContainerView {
diff --git a/ios/chrome/browser/ui/main/scene_controller.mm b/ios/chrome/browser/ui/main/scene_controller.mm index 651340f..4efbff6 100644 --- a/ios/chrome/browser/ui/main/scene_controller.mm +++ b/ios/chrome/browser/ui/main/scene_controller.mm
@@ -691,8 +691,8 @@ return; } - BOOL initializingUIInColdStart = level > SceneActivationLevelBackground && - !self.sceneState.hasInitializedUI; + BOOL initializingUIInColdStart = + level > SceneActivationLevelBackground && !self.sceneState.UIEnabled; if (initializingUIInColdStart) { [self initializeUI]; // Add the scene to the list of connected scene, to restore in case of @@ -735,8 +735,7 @@ [self recordWindowCreationForSceneState:self.sceneState]; - if (self.sceneState.hasInitializedUI && - level == SceneActivationLevelUnattached) { + if (self.sceneState.UIEnabled && level == SceneActivationLevelUnattached) { if (base::ios::IsMultipleScenesSupported()) { // If Multiple scenes are not supported, the session shouldn't be // removed as it can be used for normal restoration. @@ -797,12 +796,12 @@ } - (void)initializeUI { - if (self.sceneState.hasInitializedUI) { + if (self.sceneState.UIEnabled) { return; } [self startUpChromeUI]; - self.sceneState.hasInitializedUI = YES; + self.sceneState.UIEnabled = YES; } // Returns YES if restore prompt can be shown. @@ -1105,7 +1104,7 @@ // This method completely destroys all of the UI. It should be called when the // scene is disconnected. - (void)teardownUI { - if (!self.sceneState.hasInitializedUI) { + if (!self.sceneState.UIEnabled) { return; // Nothing to do. } @@ -1137,11 +1136,15 @@ PolicyWatcherBrowserAgent::FromBrowser(self.mainInterface.browser) ->RemoveObserver(_policyWatcherObserverBridge.get()); + // TODO(crbug.com/1229306): Consider moving this at the beginning of + // teardownUI to indicate that the UI is about to be torn down and that the + // dependencies depending on the browser UI models has to be cleaned up + // agent). + self.sceneState.UIEnabled = NO; + [self.browserViewWrangler shutdown]; self.browserViewWrangler = nil; - self.sceneState.hasInitializedUI = NO; - [self.sceneState.appState removeObserver:self]; } @@ -1971,7 +1974,7 @@ } - (void)tabGridDismissTransitionDidEnd:(TabGridCoordinator*)tabGrid { - if (!self.sceneState.hasInitializedUI) { + if (!self.sceneState.UIEnabled) { return; } [self finishActivatingBrowserDismissingTabSwitcher:YES];
diff --git a/ios/chrome/browser/ui/main/scene_state.h b/ios/chrome/browser/ui/main/scene_state.h index 8e80a7f..4df3f7b4 100644 --- a/ios/chrome/browser/ui/main/scene_state.h +++ b/ios/chrome/browser/ui/main/scene_state.h
@@ -102,8 +102,9 @@ // |UISceneDelegate scene:continueUserActivity:| and needs to be opened. @property(nonatomic) NSUserActivity* pendingUserActivity; -// A flag that keeps track of the UI initialization for the controlled scene. -@property(nonatomic, assign) BOOL hasInitializedUI; +// YES if the UI is enabled. The browser UI objects are available when this is +// YES. +@property(nonatomic, assign) BOOL UIEnabled; // YES if the QR scanner is visible. @property(nonatomic, assign) BOOL QRScannerVisible;
diff --git a/ios/chrome/browser/ui/main/scene_state.mm b/ios/chrome/browser/ui/main/scene_state.mm index 497a610e6..0afa35d 100644 --- a/ios/chrome/browser/ui/main/scene_state.mm +++ b/ios/chrome/browser/ui/main/scene_state.mm
@@ -145,13 +145,16 @@ [self.observers sceneState:self transitionedToActivationLevel:newLevel]; } -- (void)setHasInitializedUI:(BOOL)hasInitializedUI { - if (_hasInitializedUI == hasInitializedUI) { +- (void)setUIEnabled:(BOOL)UIEnabled { + if (_UIEnabled == UIEnabled) { return; } - _hasInitializedUI = hasInitializedUI; - if (hasInitializedUI) { - [self.observers sceneStateHasInitializedUI:self]; + + _UIEnabled = UIEnabled; + if (UIEnabled) { + [self.observers sceneStateDidEnableUI:self]; + } else { + [self.observers sceneStateDidDisableUI:self]; } }
diff --git a/ios/chrome/browser/ui/main/scene_state_observer.h b/ios/chrome/browser/ui/main/scene_state_observer.h index 8b31ff3..69d379c 100644 --- a/ios/chrome/browser/ui/main/scene_state_observer.h +++ b/ios/chrome/browser/ui/main/scene_state_observer.h
@@ -26,8 +26,12 @@ - (void)sceneStateWillHideModalOverlay:(SceneState*)sceneState; // Notifies when presentingModalOverlay has been set to false. - (void)sceneStateDidHideModalOverlay:(SceneState*)sceneState; -// Notifies when hasInitializedUI has been set. -- (void)sceneStateHasInitializedUI:(SceneState*)sceneState; +// Notifies when UIEnabled has been set to true. Is only fired once during the +// scene's life period when the scene UI has initialized. +- (void)sceneStateDidEnableUI:(SceneState*)sceneState; +// Notifies when UIEnabled has been set to false. Is only fired once during the +// scene's life period when the scene UI is tearing down. +- (void)sceneStateDidDisableUI:(SceneState*)sceneState; // Notifies when URLContexts have been added to |URLContextsToOpen|. - (void)sceneState:(SceneState*)sceneState hasPendingURLs:(NSSet<UIOpenURLContext*>*)URLContexts;
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_coordinator.mm b/ios/chrome/browser/ui/ntp/new_tab_page_coordinator.mm index 5e1afdb4..cdcf6b8 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_coordinator.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_coordinator.mm
@@ -434,7 +434,11 @@ } - (void)focusFakebox { - [self.contentSuggestionsCoordinator.headerController focusFakebox]; + if (self.discoverFeedViewController) { + [self.ntpViewController focusFakebox]; + } else { + [self.contentSuggestionsCoordinator.headerController focusFakebox]; + } } - (void)reload {
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.h b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.h index 4233a0d..7eb1b7c 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.h +++ b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.h
@@ -34,7 +34,8 @@ overscrollDelegate; // The content suggestions header, containing the fake omnibox and the doodle. -@property(nonatomic, weak) UIViewController* headerController; +@property(nonatomic, weak) + ContentSuggestionsHeaderViewController* headerController; // Delegate for actions relating to the NTP content. @property(nonatomic, weak) id<NewTabPageContentDelegate> ntpContentDelegate; @@ -87,6 +88,9 @@ // Returns the current height of the content suggestions content. - (CGFloat)contentSuggestionsContentHeight; +// Scrolls up the collection view enough to focus the omnibox. +- (void)focusFakebox; + @end #endif // IOS_CHROME_BROWSER_UI_NTP_NEW_TAB_PAGE_VIEW_CONTROLLER_H_
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm index 5584cdc7..1cab856 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.mm
@@ -8,6 +8,7 @@ #import "base/check.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizing.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_layout.h" #import "ios/chrome/browser/ui/content_suggestions/discover_feed_metrics_recorder.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h" @@ -72,6 +73,9 @@ // The scroll position when a scrolling event starts. @property(nonatomic, assign) int scrollStartPosition; +// Whether the omnibox should be focused once the collection view appears. +@property(nonatomic, assign) BOOL shouldFocusFakebox; + @end @implementation NewTabPageViewController @@ -200,6 +204,12 @@ // Updates omnibox to ensure that the dimensions are correct when navigating // back to the NTP. [self.headerSynchronizer updateFakeOmniboxForScrollPosition]; + + if (self.shouldFocusFakebox && [self collectionViewHasLoaded]) { + [self.headerController focusFakebox]; + self.shouldFocusFakebox = NO; + } + self.viewDidAppear = YES; } @@ -331,6 +341,17 @@ .height; } +- (void)focusFakebox { + // The fakebox should only be focused once the collection view has reached its + // minimum height. If this is not the case yet, we wait until viewDidAppear + // before focusing the fakebox. + if ([self collectionViewHasLoaded]) { + [self.headerController focusFakebox]; + } else { + self.shouldFocusFakebox = YES; + } +} + #pragma mark - UIScrollViewDelegate - (void)scrollViewDidScroll:(UIScrollView*)scrollView { @@ -623,6 +644,15 @@ self.view.safeAreaInsets.top; } +// Whether the collection view has attained its minimum height. +// The fake omnibox never actually disappears; the NTP just scrolls enough so +// that it's hidden behind the real one when it's focused. When the NTP hasn't +// fully loaded yet, there isn't enough height to scroll it behind the real +// omnibox, so they would both show. +- (BOOL)collectionViewHasLoaded { + return self.collectionView.contentSize.height > 0; +} + #pragma mark - Setters // Sets whether or not the NTP is scrolled into the feed and notifies the
diff --git a/ios/chrome/browser/ui/toolbar/BUILD.gn b/ios/chrome/browser/ui/toolbar/BUILD.gn index 32198a5..df2f620 100644 --- a/ios/chrome/browser/ui/toolbar/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/BUILD.gn
@@ -214,6 +214,7 @@ "//ios/chrome/test/earl_grey:eg_test_support+eg2", "//ios/testing/earl_grey:eg_test_support+eg2", "//ios/third_party/earl_grey2:test_lib", + "//ios/web/common:features", "//ios/web/public/test:element_selector", "//ios/web/public/test/http_server", "//net:test_support",
diff --git a/ios/chrome/browser/ui/toolbar/adaptive_toolbar_egtest.mm b/ios/chrome/browser/ui/toolbar/adaptive_toolbar_egtest.mm index 54e663c..0222193 100644 --- a/ios/chrome/browser/ui/toolbar/adaptive_toolbar_egtest.mm +++ b/ios/chrome/browser/ui/toolbar/adaptive_toolbar_egtest.mm
@@ -17,6 +17,7 @@ #include "ios/testing/earl_grey/disabled_test_macros.h" #import "ios/testing/earl_grey/disabled_test_macros.h" #import "ios/testing/earl_grey/earl_grey_test.h" +#include "ios/web/common/features.h" #include "ios/web/public/test/element_selector.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" @@ -508,7 +509,9 @@ true /* menu should appear */)]; [[EarlGrey selectElementWithMatcher: chrome_test_util::StaticTextWithAccessibilityLabelId( - IDS_IOS_CONTENT_CONTEXT_OPENLINKNEWINCOGNITOTAB)] + web::features::UseWebViewNativeContextMenuSystem() + ? IDS_IOS_OPEN_IN_INCOGNITO_ACTION_TITLE + : IDS_IOS_CONTENT_CONTEXT_OPENLINKNEWINCOGNITOTAB)] performAction:grey_tap()]; // Check the buttons status.
diff --git a/ios/web/common/features.mm b/ios/web/common/features.mm index 75a05b53..c7f0a011 100644 --- a/ios/web/common/features.mm +++ b/ios/web/common/features.mm
@@ -49,8 +49,8 @@ const base::Feature kRecordSnapshotSize{"RecordSnapshotSize", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kWebViewNativeContextMenu{ - "WebViewNativeContextMenu", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kWebViewNativeContextMenu{"WebViewNativeContextMenu", + base::FEATURE_ENABLED_BY_DEFAULT}; const char kWebViewNativeContextMenuName[] = "type"; const char kWebViewNativeContextMenuParameterSystem[] = "system"; @@ -80,7 +80,8 @@ return false; std::string field_trial_param = base::GetFieldTrialParamValueByFeature( kWebViewNativeContextMenu, kWebViewNativeContextMenuName); - return field_trial_param == kWebViewNativeContextMenuParameterSystem; + return field_trial_param.empty() || + field_trial_param == kWebViewNativeContextMenuParameterSystem; } return false; }
diff --git a/media/fuchsia/cdm/service/BUILD.gn b/media/fuchsia/cdm/service/BUILD.gn index b87b99f..7cd4ac5 100644 --- a/media/fuchsia/cdm/service/BUILD.gn +++ b/media/fuchsia/cdm/service/BUILD.gn
@@ -20,6 +20,7 @@ deps = [ "//fuchsia/base", "//media/fuchsia/mojom", + "//third_party/fuchsia-sdk/sdk/pkg/fit-promise", "//url", ] } @@ -35,6 +36,7 @@ "//media", "//testing/gmock", "//testing/gtest", + "//third_party/fuchsia-sdk/sdk/pkg/fit-promise", "//url", ]
diff --git a/media/fuchsia/cdm/service/fuchsia_cdm_manager.cc b/media/fuchsia/cdm/service/fuchsia_cdm_manager.cc index a90f9921..861afb29 100644 --- a/media/fuchsia/cdm/service/fuchsia_cdm_manager.cc +++ b/media/fuchsia/cdm/service/fuchsia_cdm_manager.cc
@@ -6,6 +6,7 @@ #include <fuchsia/media/drm/cpp/fidl.h> #include <lib/fidl/cpp/binding_set.h> +#include <lib/fpromise/promise.h> #include "base/bind.h" #include "base/callback.h" @@ -216,8 +217,8 @@ key_system_->AddDataStore( data_store_id, std::move(params), - [this, data_store_id, - storage_path](fit::result<void, fuchsia::media::drm::Error> result) { + [this, data_store_id, storage_path]( + fpromise::result<void, fuchsia::media::drm::Error> result) { if (result.is_error()) { DLOG(ERROR) << "Failed to add data store " << data_store_id << ", path: " << storage_path;
diff --git a/media/fuchsia/cdm/service/fuchsia_cdm_manager_unittest.cc b/media/fuchsia/cdm/service/fuchsia_cdm_manager_unittest.cc index 4e6ef5a9..346b2c3 100644 --- a/media/fuchsia/cdm/service/fuchsia_cdm_manager_unittest.cc +++ b/media/fuchsia/cdm/service/fuchsia_cdm_manager_unittest.cc
@@ -8,6 +8,7 @@ #include <fuchsia/media/drm/cpp/fidl_test_base.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/fidl/cpp/interface_request.h> +#include <lib/fpromise/promise.h> #include <map> #include "base/bind.h" @@ -138,7 +139,7 @@ Invoke([&](uint32_t data_store_id, drm::KeySystem::AddDataStoreCallback callback) { added_data_store_id = data_store_id; - callback(fit::ok()); + callback(fpromise::ok()); }))); EXPECT_CALL(mock_key_system(kKeySystem), CreateContentDecryptionModule2(_, _)) @@ -164,7 +165,7 @@ Invoke([&](uint32_t data_store_id, drm::KeySystem::AddDataStoreCallback callback) { added_data_store_id = data_store_id; - callback(fit::ok()); + callback(fpromise::ok()); }))); // Create a CDM to force a KeySystem binding @@ -194,7 +195,7 @@ AddDataStore(Eq(added_data_store_id), _, _)) .WillOnce( WithArgs<2>(Invoke([](drm::KeySystem::AddDataStoreCallback callback) { - callback(fit::ok()); + callback(fpromise::ok()); }))); base::RunLoop recreate_run_loop; @@ -226,7 +227,7 @@ EXPECT_CALL(mock_key_system(kKeySystem), AddDataStore(Eq(1u), _, _)) .WillOnce( WithArgs<2>(Invoke([](drm::KeySystem::AddDataStoreCallback callback) { - callback(fit::ok()); + callback(fpromise::ok()); }))); EXPECT_CALL(mock_key_system(kKeySystem), CreateContentDecryptionModule2(Eq(1u), _)) @@ -262,12 +263,12 @@ EXPECT_CALL(mock_key_system(kKeySystem), AddDataStore(Eq(1u), _, _)) .WillOnce( WithArgs<2>(Invoke([](drm::KeySystem::AddDataStoreCallback callback) { - callback(fit::ok()); + callback(fpromise::ok()); }))); EXPECT_CALL(mock_key_system(kKeySystem), AddDataStore(Eq(2u), _, _)) .WillOnce( WithArgs<2>(Invoke([](drm::KeySystem::AddDataStoreCallback callback) { - callback(fit::ok()); + callback(fpromise::ok()); }))); EXPECT_CALL(mock_key_system(kKeySystem), CreateContentDecryptionModule2(Eq(1u), _))
diff --git a/net/disk_cache/simple/simple_histogram_macros.h b/net/disk_cache/simple/simple_histogram_macros.h index d7d36f38..f6768a0 100644 --- a/net/disk_cache/simple/simple_histogram_macros.h +++ b/net/disk_cache/simple/simple_histogram_macros.h
@@ -13,33 +13,40 @@ // media), while making it easy to report histograms and have all names // precomputed. -#define SIMPLE_CACHE_THUNK(uma_type, args) UMA_HISTOGRAM_##uma_type args +#define SIMPLE_CACHE_THUNK(uma_prefix, uma_type, args) \ + uma_prefix##_HISTOGRAM_##uma_type args // TODO(pasko): add histograms for shader cache as soon as it becomes possible // for a user to get shader cache with the |SimpleBackendImpl| without altering // any flags. -#define SIMPLE_CACHE_UMA(uma_type, uma_name, cache_type, ...) \ - do { \ - switch (cache_type) { \ - case net::DISK_CACHE: \ - SIMPLE_CACHE_THUNK(uma_type, \ - ("SimpleCache.Http." uma_name, ##__VA_ARGS__)); \ - break; \ - case net::APP_CACHE: \ - SIMPLE_CACHE_THUNK(uma_type, \ - ("SimpleCache.App." uma_name, ##__VA_ARGS__)); \ - break; \ - case net::GENERATED_BYTE_CODE_CACHE: \ - SIMPLE_CACHE_THUNK(uma_type, \ - ("SimpleCache.Code." uma_name, ##__VA_ARGS__)); \ - break; \ - case net::GENERATED_NATIVE_CODE_CACHE: \ - case net::SHADER_CACHE: \ - break; \ - default: \ - NOTREACHED(); \ - break; \ - } \ +#define SIMPLE_CACHE_HISTO(uma_prefix, uma_type, uma_name, cache_type, ...) \ + do { \ + switch (cache_type) { \ + case net::DISK_CACHE: \ + SIMPLE_CACHE_THUNK(uma_prefix, uma_type, \ + ("SimpleCache.Http." uma_name, ##__VA_ARGS__)); \ + break; \ + case net::APP_CACHE: \ + SIMPLE_CACHE_THUNK(uma_prefix, uma_type, \ + ("SimpleCache.App." uma_name, ##__VA_ARGS__)); \ + break; \ + case net::GENERATED_BYTE_CODE_CACHE: \ + SIMPLE_CACHE_THUNK(uma_prefix, uma_type, \ + ("SimpleCache.Code." uma_name, ##__VA_ARGS__)); \ + break; \ + case net::GENERATED_NATIVE_CODE_CACHE: \ + case net::SHADER_CACHE: \ + break; \ + default: \ + NOTREACHED(); \ + break; \ + } \ } while (0) +#define SIMPLE_CACHE_UMA(uma_type, uma_name, cache_type, ...) \ + SIMPLE_CACHE_HISTO(UMA, uma_type, uma_name, cache_type, ##__VA_ARGS__) + +#define SIMPLE_CACHE_LOCAL(uma_type, uma_name, cache_type, ...) \ + SIMPLE_CACHE_HISTO(LOCAL, uma_type, uma_name, cache_type, ##__VA_ARGS__) + #endif // NET_DISK_CACHE_SIMPLE_SIMPLE_HISTOGRAM_MACROS_H_
diff --git a/net/disk_cache/simple/simple_index.cc b/net/disk_cache/simple/simple_index.cc index 55abd97..37bd23ac 100644 --- a/net/disk_cache/simple/simple_index.cc +++ b/net/disk_cache/simple/simple_index.cc
@@ -410,12 +410,6 @@ // Take all live key hashes from the index and sort them by time. eviction_in_progress_ = true; eviction_start_time_ = base::TimeTicks::Now(); - SIMPLE_CACHE_UMA( - MEMORY_KB, "Eviction.CacheSizeOnStart2", cache_type_, - static_cast<base::HistogramBase::Sample>(cache_size_ / kBytesInKb)); - SIMPLE_CACHE_UMA( - MEMORY_KB, "Eviction.MaxCacheSizeOnStart2", cache_type_, - static_cast<base::HistogramBase::Sample>(max_size_ / kBytesInKb)); bool use_size_heuristic = (cache_type_ != net::GENERATED_BYTE_CODE_CACHE); @@ -453,10 +447,6 @@ SIMPLE_CACHE_UMA(TIMES, "Eviction.TimeToSelectEntries", cache_type_, base::TimeTicks::Now() - eviction_start_time_); - SIMPLE_CACHE_UMA( - MEMORY_KB, "Eviction.SizeOfEvicted2", cache_type_, - static_cast<base::HistogramBase::Sample>( - evicted_so_far_size / kBytesInKb)); delegate_->DoomEntries( &entry_hashes, base::BindOnce(&SimpleIndex::EvictionDone, AsWeakPtr())); @@ -505,13 +495,9 @@ // Ignore the result of eviction. We did our best. eviction_in_progress_ = false; - SIMPLE_CACHE_UMA(BOOLEAN, "Eviction.Result", cache_type_, result == net::OK); SIMPLE_CACHE_UMA(TIMES, "Eviction.TimeToDone", cache_type_, base::TimeTicks::Now() - eviction_start_time_); - SIMPLE_CACHE_UMA( - MEMORY_KB, "Eviction.SizeWhenDone2", cache_type_, - static_cast<base::HistogramBase::Sample>(cache_size_ / kBytesInKb)); } // static @@ -602,11 +588,6 @@ SIMPLE_CACHE_UMA( MEMORY_KB, "MaxCacheSizeOnInit", cache_type_, static_cast<base::HistogramBase::Sample>(max_size_ / kBytesInKb)); - if (max_size_ > 0) { - SIMPLE_CACHE_UMA(PERCENTAGE, "PercentFullOnInit", cache_type_, - static_cast<base::HistogramBase::Sample>( - (cache_size_ * 100) / max_size_)); - } // Run all callbacks waiting for the index to come up. for (auto it = to_run_when_initialized_.begin(), @@ -641,10 +622,6 @@ // Cancel any pending writes since we are about to write to disk now. write_to_disk_timer_.AbandonAndStop(); - SIMPLE_CACHE_UMA(CUSTOM_COUNTS, - "IndexNumEntriesOnWrite", cache_type_, - entries_set_.size(), 0, 100000, 50); - base::OnceClosure after_write; if (cleanup_tracker_) { // Make anyone synchronizing with our cleanup wait for the index to be
diff --git a/net/disk_cache/simple/simple_index_file.cc b/net/disk_cache/simple/simple_index_file.cc index 8427ca1..8f00888 100644 --- a/net/disk_cache/simple/simple_index_file.cc +++ b/net/disk_cache/simple/simple_index_file.cc
@@ -15,6 +15,7 @@ #include "base/pickle.h" #include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" +#include "build/build_config.h" #include "net/disk_cache/simple/simple_entry_format.h" #include "net/disk_cache/simple/simple_histogram_macros.h" #include "net/disk_cache/simple/simple_index.h" @@ -67,18 +68,6 @@ SimpleIndex::INITIALIZE_METHOD_MAX); } -void UmaRecordIndexWriteReason(SimpleIndex::IndexWriteToDiskReason reason, - net::CacheType cache_type) { - SIMPLE_CACHE_UMA(ENUMERATION, "IndexWriteReason", cache_type, reason, - SimpleIndex::INDEX_WRITE_REASON_MAX); -} - -void UmaRecordIndexWriteReasonAtLoad(SimpleIndex::IndexWriteToDiskReason reason, - net::CacheType cache_type) { - SIMPLE_CACHE_UMA(ENUMERATION, "IndexWriteReasonAtLoad", cache_type, reason, - SimpleIndex::INDEX_WRITE_REASON_MAX); -} - void UmaRecordStaleIndexQuality(int missed_entry_count, int extra_entry_count, net::CacheType cache_type) { @@ -372,7 +361,6 @@ const SimpleIndex::EntrySet& entry_set, uint64_t cache_size, base::OnceClosure callback) { - UmaRecordIndexWriteReason(reason, cache_type_); IndexMetadata index_metadata(reason, entry_set.size(), cache_size); std::unique_ptr<base::Pickle> pickle = Serialize(cache_type, index_metadata, entry_set); @@ -405,11 +393,6 @@ UmaRecordIndexFileState(INDEX_STATE_CORRUPT, cache_type); } else { if (cache_last_modified <= last_cache_seen_by_index) { - if (out_result->index_write_reason != - SimpleIndex::INDEX_WRITE_REASON_MAX) { - UmaRecordIndexWriteReasonAtLoad(out_result->index_write_reason, - cache_type); - } base::Time latest_dir_mtime; simple_util::GetMTime(cache_directory, &latest_dir_mtime); if (LegacyIsIndexFileStale(latest_dir_mtime, index_file_path)) {
diff --git a/net/disk_cache/simple/simple_synchronous_entry.cc b/net/disk_cache/simple/simple_synchronous_entry.cc index 3943482..8cb0cabc 100644 --- a/net/disk_cache/simple/simple_synchronous_entry.cc +++ b/net/disk_cache/simple/simple_synchronous_entry.cc
@@ -17,6 +17,7 @@ #include "base/memory/ptr_util.h" #include "base/metrics/field_trial_params.h" #include "base/metrics/histogram_macros.h" +#include "base/metrics/histogram_macros_local.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_piece.h" #include "base/timer/elapsed_timer.h" @@ -40,24 +41,23 @@ void RecordSyncOpenResult(net::CacheType cache_type, OpenEntryResult result) { DCHECK_LT(result, OPEN_ENTRY_MAX); - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncOpenResult", cache_type, result, OPEN_ENTRY_MAX); + SIMPLE_CACHE_LOCAL(ENUMERATION, "SyncOpenResult", cache_type, result, + OPEN_ENTRY_MAX); } void RecordWriteResult(net::CacheType cache_type, SyncWriteResult result) { - SIMPLE_CACHE_UMA(ENUMERATION, "SyncWriteResult", cache_type, result, - SYNC_WRITE_RESULT_MAX); + SIMPLE_CACHE_LOCAL(ENUMERATION, "SyncWriteResult", cache_type, result, + SYNC_WRITE_RESULT_MAX); } void RecordCheckEOFResult(net::CacheType cache_type, CheckEOFResult result) { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncCheckEOFResult", cache_type, - result, CHECK_EOF_RESULT_MAX); + SIMPLE_CACHE_LOCAL(ENUMERATION, "SyncCheckEOFResult", cache_type, result, + CHECK_EOF_RESULT_MAX); } void RecordCloseResult(net::CacheType cache_type, CloseResult result) { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncCloseResult", cache_type, result, CLOSE_RESULT_MAX); + SIMPLE_CACHE_LOCAL(ENUMERATION, "SyncCloseResult", cache_type, result, + CLOSE_RESULT_MAX); } void RecordOpenPrefetchMode(net::CacheType cache_type, OpenPrefetchMode mode) { @@ -66,7 +66,7 @@ } void RecordDiskCreateLatency(net::CacheType cache_type, base::TimeDelta delay) { - SIMPLE_CACHE_UMA(TIMES, "DiskCreateLatency", cache_type, delay); + SIMPLE_CACHE_LOCAL(TIMES, "DiskCreateLatency", cache_type, delay); } bool CanOmitEmptyFile(int file_index) { @@ -1161,9 +1161,8 @@ if (!MaybeOpenFile(i, &error)) { RecordSyncOpenResult(cache_type_, OPEN_ENTRY_PLATFORM_FILE_ERROR); - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncOpenPlatformFileError", cache_type_, - -error, -base::File::FILE_ERROR_MAX); + SIMPLE_CACHE_LOCAL(ENUMERATION, "SyncOpenPlatformFileError", cache_type_, + -error, -base::File::FILE_ERROR_MAX); while (--i >= 0) CloseFile(i); return false; @@ -1216,9 +1215,8 @@ for (int i = 0; i < kSimpleEntryNormalFileCount; ++i) { base::File::Error error; if (!MaybeCreateFile(i, FILE_NOT_REQUIRED, &error)) { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncCreatePlatformFileError", cache_type_, - -error, -base::File::FILE_ERROR_MAX); + SIMPLE_CACHE_LOCAL(ENUMERATION, "SyncCreatePlatformFileError", + cache_type_, -error, -base::File::FILE_ERROR_MAX); while (--i >= 0) CloseFile(i); return false;
diff --git a/printing/android/java/src/org/chromium/printing/PrintManagerDelegateImpl.java b/printing/android/java/src/org/chromium/printing/PrintManagerDelegateImpl.java index 150b4d75eb..2f03cee 100644 --- a/printing/android/java/src/org/chromium/printing/PrintManagerDelegateImpl.java +++ b/printing/android/java/src/org/chromium/printing/PrintManagerDelegateImpl.java
@@ -16,6 +16,7 @@ import android.text.TextUtils; import org.chromium.base.Log; +import org.chromium.base.annotations.RemovableInRelease; import java.util.List; @@ -38,9 +39,8 @@ mPrintManager.print(printJobName, documentAdapter, attributes); } + @RemovableInRelease private void dumpJobStatesForDebug() { - if (!Log.isLoggable(TAG, Log.VERBOSE)) return; - List<PrintJob> printJobs = mPrintManager.getPrintJobs(); String[] states = new String[printJobs.size()];
diff --git a/sandbox/linux/BUILD.gn b/sandbox/linux/BUILD.gn index 2f778dd0..ccbbc917 100644 --- a/sandbox/linux/BUILD.gn +++ b/sandbox/linux/BUILD.gn
@@ -443,6 +443,7 @@ "system_headers/linux_ptrace.h", "system_headers/linux_seccomp.h", "system_headers/linux_signal.h", + "system_headers/linux_stat.h", "system_headers/linux_syscalls.h", "system_headers/linux_time.h", "system_headers/linux_ucontext.h",
diff --git a/sandbox/linux/integration_tests/seccomp_broker_process_unittest.cc b/sandbox/linux/integration_tests/seccomp_broker_process_unittest.cc index 9da9c68..8a94198 100644 --- a/sandbox/linux/integration_tests/seccomp_broker_process_unittest.cc +++ b/sandbox/linux/integration_tests/seccomp_broker_process_unittest.cc
@@ -34,6 +34,7 @@ #include "sandbox/linux/syscall_broker/broker_file_permission.h" #include "sandbox/linux/syscall_broker/broker_process.h" #include "sandbox/linux/system_headers/linux_seccomp.h" +#include "sandbox/linux/system_headers/linux_stat.h" #include "sandbox/linux/system_headers/linux_syscalls.h" #include "sandbox/linux/tests/scoped_temporary_file.h" #include "sandbox/linux/tests/test_utils.h" @@ -202,6 +203,26 @@ // not accept this as a valid error number. E.g. bionic accepts up to 255, glibc // and musl up to 4096. const int kFakeErrnoSentinel = 254; + +void ConvertKernelStatToLibcStat(default_stat_struct& in_stat, + struct stat& out_stat) { + out_stat.st_dev = in_stat.st_dev; + out_stat.st_ino = in_stat.st_ino; + out_stat.st_mode = in_stat.st_mode; + out_stat.st_nlink = in_stat.st_nlink; + out_stat.st_uid = in_stat.st_uid; + out_stat.st_gid = in_stat.st_gid; + out_stat.st_rdev = in_stat.st_rdev; + out_stat.st_size = in_stat.st_size; + out_stat.st_blksize = in_stat.st_blksize; + out_stat.st_blocks = in_stat.st_blocks; + out_stat.st_atim.tv_sec = in_stat.st_atime_; + out_stat.st_atim.tv_nsec = in_stat.st_atime_nsec_; + out_stat.st_mtim.tv_sec = in_stat.st_mtime_; + out_stat.st_mtim.tv_nsec = in_stat.st_mtime_nsec_; + out_stat.st_ctim.tv_sec = in_stat.st_ctime_; + out_stat.st_ctim.tv_nsec = in_stat.st_ctime_nsec_; +} } // namespace // There are a variety of ways to make syscalls in a sandboxed process. One is @@ -217,6 +238,10 @@ virtual int Open(const char* filepath, int flags) = 0; virtual int Access(const char* filepath, int mode) = 0; + // NOTE: we use struct stat instead of default_stat_struct, to make the libc + // syscaller simpler. Copying from default_stat_struct (the structure returned + // from a stat sycall) to struct stat (the structure exposed by a libc to its + // users) is simpler than going in the opposite direction. virtual int Stat(const char* filepath, bool follow_links, struct stat* statbuf) = 0; @@ -243,8 +268,12 @@ int Stat(const char* filepath, bool follow_links, struct stat* statbuf) override { - return broker_->GetBrokerClientSignalBased()->Stat(filepath, follow_links, - statbuf); + default_stat_struct buf; + int ret = broker_->GetBrokerClientSignalBased()->DefaultStatForTesting( + filepath, follow_links, &buf); + if (ret >= 0) + ConvertKernelStatToLibcStat(buf, *statbuf); + return ret; } int Rename(const char* oldpath, const char* newpath) override { @@ -300,10 +329,13 @@ int Stat(const char* filepath, bool follow_links, struct stat* statbuf) override { - int ret = follow_links ? syscall(__NR_stat, filepath, statbuf) - : syscall(__NR_lstat, filepath, statbuf); + struct kernel_stat buf; + int ret = syscall(__NR_newfstatat, AT_FDCWD, filepath, &buf, + follow_links ? 0 : AT_SYMLINK_NOFOLLOW); if (ret < 0) return -errno; + + ConvertKernelStatToLibcStat(buf, *statbuf); return ret; }
diff --git a/sandbox/linux/seccomp-bpf-helpers/DEPS b/sandbox/linux/seccomp-bpf-helpers/DEPS index 4419fd1..95d1bb6 100644 --- a/sandbox/linux/seccomp-bpf-helpers/DEPS +++ b/sandbox/linux/seccomp-bpf-helpers/DEPS
@@ -3,5 +3,4 @@ "+sandbox/linux/seccomp-bpf", "+sandbox/linux/services", "+sandbox/linux/system_headers", - "+third_party/lss/linux_syscall_support.h", ]
diff --git a/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc b/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc index 903e702..76c3930 100644 --- a/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc +++ b/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc
@@ -37,10 +37,6 @@ #include "sandbox/linux/system_headers/linux_time.h" #include "sandbox/linux/tests/unit_tests.h" -#if !defined(OS_ANDROID) -#include "third_party/lss/linux_syscall_support.h" // for MAKE_PROCESS_CPUCLOCK -#endif - namespace sandbox { namespace {
diff --git a/sandbox/linux/services/syscall_wrappers.cc b/sandbox/linux/services/syscall_wrappers.cc index fcfd2aa..3bec18a 100644 --- a/sandbox/linux/services/syscall_wrappers.cc +++ b/sandbox/linux/services/syscall_wrappers.cc
@@ -4,6 +4,7 @@ #include "sandbox/linux/services/syscall_wrappers.h" +#include <fcntl.h> #include <pthread.h> #include <sched.h> #include <setjmp.h> @@ -14,11 +15,13 @@ #include <unistd.h> #include <cstring> +#include "base/check.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "build/build_config.h" #include "sandbox/linux/system_headers/capability.h" #include "sandbox/linux/system_headers/linux_signal.h" +#include "sandbox/linux/system_headers/linux_stat.h" #include "sandbox/linux/system_headers/linux_syscalls.h" namespace sandbox { @@ -217,7 +220,7 @@ #undef STR #undef XSTR -#endif +#endif // defined(ARCH_CPU_X86_FAMILY) int sys_sigaction(int signum, const struct sigaction* act, @@ -241,7 +244,7 @@ #error "Unsupported architecture." #endif } -#endif +#endif // defined(ARCH_CPU_X86_FAMILY) } LinuxSigAction linux_oldact = {}; @@ -259,6 +262,47 @@ return result; } -#endif // defined(MEMORY_SANITIZER) +#endif // !defined(OS_NACL_NONSFI) + +int sys_stat(const char* path, struct kernel_stat* stat_buf) { + int res; +#if !defined(__NR_stat) + res = syscall(__NR_newfstatat, AT_FDCWD, path, stat_buf, 0); +#else + res = syscall(__NR_stat, path, stat_buf); +#endif + if (res == 0) + MSAN_UNPOISON(stat_buf, sizeof(*stat_buf)); + return res; +} + +int sys_lstat(const char* path, struct kernel_stat* stat_buf) { + int res; +#if !defined(__NR_lstat) + res = syscall(__NR_newfstatat, AT_FDCWD, path, stat_buf, AT_SYMLINK_NOFOLLOW); +#else + res = syscall(__NR_lstat, path, stat_buf); +#endif + if (res == 0) + MSAN_UNPOISON(stat_buf, sizeof(*stat_buf)); + return res; +} + +int sys_fstatat64(int dirfd, + const char* pathname, + struct kernel_stat64* stat_buf, + int flags) { +#if defined(__NR_fstatat64) + int res = syscall(__NR_fstatat64, dirfd, pathname, stat_buf, flags); + if (res == 0) + MSAN_UNPOISON(stat_buf, sizeof(*stat_buf)); + return res; +#else // defined(__NR_fstatat64) + // We should not reach here on 64-bit systems, as the *stat*64() are only + // necessary on 32-bit. + RAW_CHECK(false); + return -ENOSYS; +#endif +} } // namespace sandbox
diff --git a/sandbox/linux/services/syscall_wrappers.h b/sandbox/linux/services/syscall_wrappers.h index 1975bfb..b55340e4 100644 --- a/sandbox/linux/services/syscall_wrappers.h +++ b/sandbox/linux/services/syscall_wrappers.h
@@ -17,6 +17,8 @@ struct rlimit64; struct cap_hdr; struct cap_data; +struct kernel_stat; +struct kernel_stat64; namespace sandbox { @@ -84,6 +86,19 @@ const struct sigaction* act, struct sigaction* oldact); +// Some architectures do not have stat() and lstat() syscalls. In that case, +// these wrappers will use newfstatat(), which is available on all other +// architectures, with the same capabilities as stat() and lstat(). +SANDBOX_EXPORT int sys_stat(const char* path, struct kernel_stat* stat_buf); +SANDBOX_EXPORT int sys_lstat(const char* path, struct kernel_stat* stat_buf); + +// Takes care of unpoisoning |stat_buf| for MSAN. Check-fails if fstatat64() is +// not a supported syscall on the current platform. +SANDBOX_EXPORT int sys_fstatat64(int dirfd, + const char* pathname, + struct kernel_stat64* stat_buf, + int flags); + } // namespace sandbox #endif // SANDBOX_LINUX_SERVICES_SYSCALL_WRAPPERS_H_
diff --git a/sandbox/linux/services/syscall_wrappers_unittest.cc b/sandbox/linux/services/syscall_wrappers_unittest.cc index 32820f6..64b9cea 100644 --- a/sandbox/linux/services/syscall_wrappers_unittest.cc +++ b/sandbox/linux/services/syscall_wrappers_unittest.cc
@@ -5,15 +5,19 @@ #include "sandbox/linux/services/syscall_wrappers.h" #include <stdint.h> +#include <string.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> -#include <cstring> +#include "base/logging.h" +#include "base/memory/page_size.h" #include "base/posix/eintr_wrapper.h" #include "build/build_config.h" #include "sandbox/linux/system_headers/linux_signal.h" +#include "sandbox/linux/system_headers/linux_stat.h" +#include "sandbox/linux/tests/scoped_temporary_file.h" #include "sandbox/linux/tests/test_utils.h" #include "sandbox/linux/tests/unit_tests.h" #include "testing/gtest/include/gtest/gtest.h" @@ -93,6 +97,129 @@ linux_sigset); } +TEST(SyscallWrappers, Stat) { + // Create a file to stat, with 12 bytes of data. + ScopedTemporaryFile tmp_file; + EXPECT_EQ(12, write(tmp_file.fd(), "blahblahblah", 12)); + + // To test we have the correct stat structures for each kernel/platform, we + // will right-align them on a page, with a guard page after. + char* two_pages = static_cast<char*>(TestUtils::MapPagesOrDie(2)); + TestUtils::MprotectLastPageOrDie(two_pages, 2); + char* page1_end = two_pages + base::GetPageSize(); + + // First, check that calling stat with |stat_buf| pointing to the last byte on + // a page causes EFAULT. + int res = sys_stat(tmp_file.full_file_name(), + reinterpret_cast<struct kernel_stat*>(page1_end - 1)); + ASSERT_EQ(res, -1); + ASSERT_EQ(errno, EFAULT); + + // Now, check that we have the correctly sized stat structure. + struct kernel_stat* sb = reinterpret_cast<struct kernel_stat*>( + page1_end - sizeof(struct kernel_stat)); + // Memset to c's so we can check the kernel zero'd the padding... + memset(sb, 'c', sizeof(struct kernel_stat)); + res = sys_stat(tmp_file.full_file_name(), sb); + ASSERT_EQ(res, 0); + + // Following fields may never be consistent but should be non-zero. + // Don't trust the platform to define fields with any particular sign. + EXPECT_NE(0u, static_cast<unsigned int>(sb->st_dev)); + EXPECT_NE(0u, static_cast<unsigned int>(sb->st_ino)); + EXPECT_NE(0u, static_cast<unsigned int>(sb->st_mode)); + EXPECT_NE(0u, static_cast<unsigned int>(sb->st_blksize)); + EXPECT_NE(0u, static_cast<unsigned int>(sb->st_blocks)); + +// We are the ones that made the file. +// Note: normally gid and uid overflow on backwards-compatible 32-bit systems +// and we end up with dummy uids and gids in place here. +#if defined(ARCH_CPU_64_BITS) + EXPECT_EQ(geteuid(), sb->st_uid); + EXPECT_EQ(getegid(), sb->st_gid); +#endif + + // Wrote 12 bytes above which should fit in one block. + EXPECT_EQ(12u, sb->st_size); + + // Can't go backwards in time, 1500000000 was some time ago. + EXPECT_LT(1500000000u, static_cast<unsigned int>(sb->st_atime_)); + EXPECT_LT(1500000000u, static_cast<unsigned int>(sb->st_mtime_)); + EXPECT_LT(1500000000u, static_cast<unsigned int>(sb->st_ctime_)); + + // Checking the padding for good measure. +#if defined(__x86_64__) + EXPECT_EQ(0u, sb->__pad0); + EXPECT_EQ(0u, sb->__unused4[0]); + EXPECT_EQ(0u, sb->__unused4[1]); + EXPECT_EQ(0u, sb->__unused4[2]); +#elif defined(__aarch64__) + EXPECT_EQ(0u, sb->__pad1); + EXPECT_EQ(0, sb->__pad2); + EXPECT_EQ(0u, sb->__unused4); + EXPECT_EQ(0u, sb->__unused5); +#endif +} + +TEST(SyscallWrappers, LStat) { + // Create a file to stat, with 12 bytes of data. + ScopedTemporaryFile tmp_file; + EXPECT_EQ(12, write(tmp_file.fd(), "blahblahblah", 12)); + + // Also create a symlink. + std::string symlink_name; + { + ScopedTemporaryFile tmp_file2; + symlink_name = tmp_file2.full_file_name(); + } + int rc = symlink(tmp_file.full_file_name(), symlink_name.c_str()); + if (rc != 0) { + PLOG(ERROR) << "Couldn't symlink " << symlink_name << " to target " + << tmp_file.full_file_name(); + GTEST_FAIL(); + } + + struct kernel_stat lstat_info; + rc = sys_lstat(symlink_name.c_str(), &lstat_info); + if (rc < 0 && errno == EOVERFLOW) { + GTEST_SKIP(); + } + if (rc != 0) { + PLOG(ERROR) << "Couldn't sys_lstat " << symlink_name; + GTEST_FAIL(); + } + + struct kernel_stat stat_info; + rc = sys_stat(symlink_name.c_str(), &stat_info); + if (rc < 0 && errno == EOVERFLOW) { + GTEST_SKIP(); + } + if (rc != 0) { + PLOG(ERROR) << "Couldn't sys_stat " << symlink_name; + GTEST_FAIL(); + } + + struct kernel_stat tmp_file_stat_info; + rc = sys_stat(tmp_file.full_file_name(), &tmp_file_stat_info); + if (rc < 0 && errno == EOVERFLOW) { + GTEST_SKIP(); + } + if (rc != 0) { + PLOG(ERROR) << "Couldn't sys_stat " << tmp_file.full_file_name(); + GTEST_FAIL(); + } + + // lstat should produce information about a symlink. + ASSERT_TRUE(S_ISLNK(lstat_info.st_mode)); + + // stat-ing symlink_name and tmp_file should produce the same inode. + ASSERT_EQ(stat_info.st_ino, tmp_file_stat_info.st_ino); + + // lstat-ing symlink_name should give a different inode than stat-ing + // symlink_name. + ASSERT_NE(stat_info.st_ino, lstat_info.st_ino); +} + } // namespace } // namespace sandbox
diff --git a/sandbox/linux/syscall_broker/DEPS b/sandbox/linux/syscall_broker/DEPS index c477f7d..149c463 100644 --- a/sandbox/linux/syscall_broker/DEPS +++ b/sandbox/linux/syscall_broker/DEPS
@@ -1,4 +1,5 @@ include_rules = [ - "+sandbox/linux/system_headers", "+sandbox/linux/bpf_dsl", + "+sandbox/linux/services", + "+sandbox/linux/system_headers", ]
diff --git a/sandbox/linux/syscall_broker/broker_client.cc b/sandbox/linux/syscall_broker/broker_client.cc index 6b1b5be4..e24f659 100644 --- a/sandbox/linux/syscall_broker/broker_client.cc +++ b/sandbox/linux/syscall_broker/broker_client.cc
@@ -166,7 +166,7 @@ int BrokerClient::Stat(const char* pathname, bool follow_links, - struct stat* sb) const { + struct kernel_stat* sb) const { if (!pathname || !sb) return -EFAULT; @@ -181,7 +181,7 @@ int BrokerClient::Stat64(const char* pathname, bool follow_links, - struct stat64* sb) const { + struct kernel_stat64* sb) const { if (!pathname || !sb) return -EFAULT;
diff --git a/sandbox/linux/syscall_broker/broker_client.h b/sandbox/linux/syscall_broker/broker_client.h index 05e14c83..26ca781 100644 --- a/sandbox/linux/syscall_broker/broker_client.h +++ b/sandbox/linux/syscall_broker/broker_client.h
@@ -61,10 +61,10 @@ int Rmdir(const char* path) const override; int Stat(const char* pathname, bool follow_links, - struct stat* sb) const override; + struct kernel_stat* sb) const override; int Stat64(const char* pathname, bool follow_links, - struct stat64* sb) const override; + struct kernel_stat64* sb) const override; int Unlink(const char* unlink) const override; private:
diff --git a/sandbox/linux/syscall_broker/broker_host.cc b/sandbox/linux/syscall_broker/broker_host.cc index 1cd03a1..1cdc01a 100644 --- a/sandbox/linux/syscall_broker/broker_host.cc +++ b/sandbox/linux/syscall_broker/broker_host.cc
@@ -20,9 +20,11 @@ #include "base/files/scoped_file.h" #include "base/logging.h" #include "base/posix/eintr_wrapper.h" +#include "sandbox/linux/services/syscall_wrappers.h" #include "sandbox/linux/syscall_broker/broker_command.h" #include "sandbox/linux/syscall_broker/broker_permission_list.h" #include "sandbox/linux/syscall_broker/broker_simple_message.h" +#include "sandbox/linux/system_headers/linux_stat.h" #include "sandbox/linux/system_headers/linux_syscalls.h" namespace sandbox { @@ -193,10 +195,12 @@ RAW_CHECK(reply->AddIntToMessage(-permission_list.denied_errno())); return; } + if (command_type == COMMAND_STAT) { - struct stat sb; - int sts = - follow_links ? stat(file_to_access, &sb) : lstat(file_to_access, &sb); + struct kernel_stat sb; + + int sts = follow_links ? sandbox::sys_stat(file_to_access, &sb) + : sandbox::sys_lstat(file_to_access, &sb); if (sts < 0) { RAW_CHECK(reply->AddIntToMessage(-errno)); return; @@ -205,10 +209,12 @@ RAW_CHECK( reply->AddDataToMessage(reinterpret_cast<char*>(&sb), sizeof(sb))); } else { +#if defined(__NR_fstatat64) DCHECK(command_type == COMMAND_STAT64); - struct stat64 sb; - int sts = follow_links ? stat64(file_to_access, &sb) - : lstat64(file_to_access, &sb); + struct kernel_stat64 sb; + + int sts = sandbox::sys_fstatat64(AT_FDCWD, file_to_access, &sb, + follow_links ? 0 : AT_SYMLINK_NOFOLLOW); if (sts < 0) { RAW_CHECK(reply->AddIntToMessage(-errno)); return; @@ -216,6 +222,11 @@ RAW_CHECK(reply->AddIntToMessage(0)); RAW_CHECK( reply->AddDataToMessage(reinterpret_cast<char*>(&sb), sizeof(sb))); +#else // defined(__NR_fstatat64) + // We should not reach here on 64-bit systems, as the *stat*64() are only + // necessary on 32-bit. + RAW_CHECK(false); +#endif } }
diff --git a/sandbox/linux/syscall_broker/broker_process_unittest.cc b/sandbox/linux/syscall_broker/broker_process_unittest.cc index 55ba6bcc..c65f25a 100644 --- a/sandbox/linux/syscall_broker/broker_process_unittest.cc +++ b/sandbox/linux/syscall_broker/broker_process_unittest.cc
@@ -811,7 +811,7 @@ const char* bad_leading_path5 = "/mbogo/fictitioux"; const char* bad_leading_path6 = "/mbogo/fictitiousa"; - struct stat sb; + default_stat_struct sb; { // Actual file with permissions to see file but command not allowed. @@ -824,7 +824,7 @@ memset(&sb, 0, sizeof(sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( tempfile_name, follow_links, &sb)); } @@ -840,7 +840,7 @@ memset(&sb, 0, sizeof(sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( nonesuch_name, follow_links, &sb)); } { @@ -852,7 +852,7 @@ memset(&sb, 0, sizeof(sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( tempfile_name, follow_links, &sb)); } { @@ -864,38 +864,39 @@ ASSERT_TRUE(open_broker.Init(base::BindOnce(&NoOpCallback))); memset(&sb, 0, sizeof(sb)); - EXPECT_EQ(-ENOENT, open_broker.GetBrokerClientSignalBased()->Stat( - nonesuch_name, follow_links, &sb)); + EXPECT_EQ(-ENOENT, + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( + nonesuch_name, follow_links, &sb)); // Gets denied all the way back to root since no create permission. EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( leading_path1, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( leading_path2, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( leading_path3, follow_links, &sb)); // Not fooled by substrings. EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path1, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path2, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path3, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path4, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path5, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path6, follow_links, &sb)); } { @@ -907,37 +908,41 @@ ASSERT_TRUE(open_broker.Init(base::BindOnce(&NoOpCallback))); memset(&sb, 0, sizeof(sb)); - EXPECT_EQ(-ENOENT, open_broker.GetBrokerClientSignalBased()->Stat( - nonesuch_name, follow_links, &sb)); + EXPECT_EQ(-ENOENT, + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( + nonesuch_name, follow_links, &sb)); // Gets ENOENT all the way back to root since it has create permission. - EXPECT_EQ(-ENOENT, open_broker.GetBrokerClientSignalBased()->Stat( - leading_path1, follow_links, &sb)); - EXPECT_EQ(-ENOENT, open_broker.GetBrokerClientSignalBased()->Stat( - leading_path2, follow_links, &sb)); + EXPECT_EQ(-ENOENT, + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( + leading_path1, follow_links, &sb)); + EXPECT_EQ(-ENOENT, + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( + leading_path2, follow_links, &sb)); // But can always get the root. - EXPECT_EQ(0, open_broker.GetBrokerClientSignalBased()->Stat( - leading_path3, follow_links, &sb)); + EXPECT_EQ(0, + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( + leading_path3, follow_links, &sb)); // Not fooled by substrings. EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path1, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path2, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path3, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path4, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path5, follow_links, &sb)); EXPECT_EQ(-kFakeErrnoSentinel, - open_broker.GetBrokerClientSignalBased()->Stat( + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( bad_leading_path6, follow_links, &sb)); } { @@ -949,8 +954,9 @@ ASSERT_TRUE(open_broker.Init(base::BindOnce(&NoOpCallback))); memset(&sb, 0, sizeof(sb)); - EXPECT_EQ(0, open_broker.GetBrokerClientSignalBased()->Stat( - tempfile_name, follow_links, &sb)); + EXPECT_EQ(0, + open_broker.GetBrokerClientSignalBased()->DefaultStatForTesting( + tempfile_name, follow_links, &sb)); // Following fields may never be consistent but should be non-zero. // Don't trust the platform to define fields with any particular sign. @@ -968,9 +974,9 @@ EXPECT_EQ(12, sb.st_size); // Can't go backwards in time, 1500000000 was some time ago. - EXPECT_LT(1500000000u, static_cast<unsigned int>(sb.st_atime)); - EXPECT_LT(1500000000u, static_cast<unsigned int>(sb.st_mtime)); - EXPECT_LT(1500000000u, static_cast<unsigned int>(sb.st_ctime)); + EXPECT_LT(1500000000u, static_cast<unsigned int>(sb.st_atime_)); + EXPECT_LT(1500000000u, static_cast<unsigned int>(sb.st_mtime_)); + EXPECT_LT(1500000000u, static_cast<unsigned int>(sb.st_ctime_)); } }
diff --git a/sandbox/linux/syscall_broker/remote_syscall_arg_handler_unittest.cc b/sandbox/linux/syscall_broker/remote_syscall_arg_handler_unittest.cc index fffa9bb7..f517a98 100644 --- a/sandbox/linux/syscall_broker/remote_syscall_arg_handler_unittest.cc +++ b/sandbox/linux/syscall_broker/remote_syscall_arg_handler_unittest.cc
@@ -16,6 +16,7 @@ #include "base/memory/page_size.h" #include "base/posix/unix_domain_socket.h" #include "base/test/bind.h" +#include "sandbox/linux/tests/test_utils.h" #include "sandbox/linux/tests/unit_tests.h" #include "testing/gtest/include/gtest/gtest.h" @@ -52,19 +53,6 @@ } } -void* MapPagesOrDie(size_t num_pages) { - void* addr = mmap(nullptr, num_pages * base::GetPageSize(), - PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); - PCHECK(addr); - return addr; -} - -void MprotectLastPageOrDie(char* addr, size_t num_pages) { - size_t last_page_offset = (num_pages - 1) * base::GetPageSize(); - PCHECK(mprotect(addr + last_page_offset, base::GetPageSize(), PROT_NONE) >= - 0); -} - pid_t ForkWaitingChild(base::OnceCallback<void(int)> after_parent_signals_callback = base::DoNothing(), base::ScopedFD* parent_sync_fd = nullptr) { @@ -105,13 +93,13 @@ size_t total_pages = (test_config.start_at + test_config.total_size + base::GetPageSize() - 1) / base::GetPageSize(); - char* mmap_addr = static_cast<char*>(MapPagesOrDie(total_pages)); + char* mmap_addr = static_cast<char*>(TestUtils::MapPagesOrDie(total_pages)); char* addr = mmap_addr + test_config.start_at; FillBufferWithPath(addr, test_config.total_size, test_config.include_null_byte); if (test_config.last_page_inaccessible) - MprotectLastPageOrDie(mmap_addr, total_pages); + TestUtils::MprotectLastPageOrDie(mmap_addr, total_pages); pid_t pid = ForkWaitingChild(); munmap(mmap_addr, base::GetPageSize() * total_pages); @@ -212,7 +200,7 @@ } SANDBOX_TEST(BrokerRemoteSyscallArgHandler, ReadChildExited) { - void* addr = MapPagesOrDie(1); + void* addr = TestUtils::MapPagesOrDie(1); FillBufferWithPath(static_cast<char*>(addr), strlen(kPathPart) + 1, true); base::ScopedFD parent_sync, child_sync; @@ -240,10 +228,10 @@ } SANDBOX_TEST(BrokerRemoteSyscallArgHandler, BasicWrite) { - void* read_from = MapPagesOrDie(1); + void* read_from = TestUtils::MapPagesOrDie(1); const size_t write_size = base::GetPageSize(); FillBufferWithPath(static_cast<char*>(read_from), write_size, false); - char* write_to = static_cast<char*>(MapPagesOrDie(1)); + char* write_to = static_cast<char*>(TestUtils::MapPagesOrDie(1)); base::ScopedFD parent_signal_fd; const std::vector<int> empty_fd_vec; @@ -278,8 +266,8 @@ } SANDBOX_TEST(BrokerRemoteSyscallArgHandler, WriteToInvalidAddress) { - char* write_to = static_cast<char*>(MapPagesOrDie(1)); - MprotectLastPageOrDie(write_to, 1); + char* write_to = static_cast<char*>(TestUtils::MapPagesOrDie(1)); + TestUtils::MprotectLastPageOrDie(write_to, 1); base::ScopedFD parent_signal_fd; const std::vector<int> empty_fd_vec; @@ -295,11 +283,11 @@ } SANDBOX_TEST(BrokerRemoteSyscallArgHandler, WritePartiallyToInvalidAddress) { - char* read_from = static_cast<char*>(MapPagesOrDie(2)); + char* read_from = static_cast<char*>(TestUtils::MapPagesOrDie(2)); const size_t write_size = base::GetPageSize(); FillBufferWithPath(static_cast<char*>(read_from), write_size, false); - char* write_to = static_cast<char*>(MapPagesOrDie(2)); - MprotectLastPageOrDie(write_to, 2); + char* write_to = static_cast<char*>(TestUtils::MapPagesOrDie(2)); + TestUtils::MprotectLastPageOrDie(write_to, 2); write_to += base::GetPageSize() / 2; base::ScopedFD parent_signal_fd; const std::vector<int> empty_fd_vec; @@ -314,7 +302,7 @@ } SANDBOX_TEST(BrokerRemoteSyscallArgHandler, WriteChildExited) { - char* addr = static_cast<char*>(MapPagesOrDie(1)); + char* addr = static_cast<char*>(TestUtils::MapPagesOrDie(1)); FillBufferWithPath(static_cast<char*>(addr), strlen(kPathPart) + 1, true); base::ScopedFD parent_sync, child_sync;
diff --git a/sandbox/linux/syscall_broker/syscall_dispatcher.cc b/sandbox/linux/syscall_broker/syscall_dispatcher.cc index b9ee93c..8a42397 100644 --- a/sandbox/linux/syscall_broker/syscall_dispatcher.cc +++ b/sandbox/linux/syscall_broker/syscall_dispatcher.cc
@@ -19,8 +19,18 @@ #define BROKER_UNPOISON_STRING(x) #endif +int SyscallDispatcher::DefaultStatForTesting(const char* pathname, + bool follow_links, + default_stat_struct* sb) { +#if defined(__NR_fstatat64) + return Stat64(pathname, follow_links, sb); +#elif defined(__NR_newfstatat) + return Stat(pathname, follow_links, sb); +#endif +} + int SyscallDispatcher::PerformStatat(const arch_seccomp_data& args, - bool arch64) { + bool stat64) { if (static_cast<int>(args.args[0]) != AT_FDCWD) return -EPERM; // Only allow the AT_SYMLINK_NOFOLLOW flag which is used by some libc @@ -30,13 +40,29 @@ const bool follow_links = !(static_cast<int>(args.args[3]) & AT_SYMLINK_NOFOLLOW); - if (arch64) { + if (stat64) { return Stat64(reinterpret_cast<const char*>(args.args[1]), follow_links, - reinterpret_cast<struct stat64*>(args.args[2])); + reinterpret_cast<struct kernel_stat64*>(args.args[2])); } return Stat(reinterpret_cast<const char*>(args.args[1]), follow_links, - reinterpret_cast<struct stat*>(args.args[2])); + reinterpret_cast<struct kernel_stat*>(args.args[2])); +} + +int SyscallDispatcher::PerformUnlinkat(const arch_seccomp_data& args) { + if (static_cast<int>(args.args[0]) != AT_FDCWD) + return -EPERM; + + int flags = static_cast<int>(args.args[2]); + + if (flags == AT_REMOVEDIR) { + return Rmdir(reinterpret_cast<const char*>(args.args[1])); + } + + if (flags != 0) + return -EPERM; + + return Unlink(reinterpret_cast<const char*>(args.args[1])); } int SyscallDispatcher::DispatchSyscall(const arch_seccomp_data& args) { @@ -127,59 +153,42 @@ #if defined(__NR_stat) case __NR_stat: return Stat(reinterpret_cast<const char*>(args.args[0]), true, - reinterpret_cast<struct stat*>(args.args[1])); + reinterpret_cast<struct kernel_stat*>(args.args[1])); #endif #if defined(__NR_stat64) case __NR_stat64: return Stat64(reinterpret_cast<const char*>(args.args[0]), true, - reinterpret_cast<struct stat64*>(args.args[1])); + reinterpret_cast<struct kernel_stat64*>(args.args[1])); #endif #if defined(__NR_lstat) case __NR_lstat: // See https://crbug.com/847096 BROKER_UNPOISON_STRING(reinterpret_cast<const char*>(args.args[0])); return Stat(reinterpret_cast<const char*>(args.args[0]), false, - reinterpret_cast<struct stat*>(args.args[1])); + reinterpret_cast<struct kernel_stat*>(args.args[1])); #endif #if defined(__NR_lstat64) case __NR_lstat64: // See https://crbug.com/847096 BROKER_UNPOISON_STRING(reinterpret_cast<const char*>(args.args[0])); return Stat64(reinterpret_cast<const char*>(args.args[0]), false, - reinterpret_cast<struct stat64*>(args.args[1])); -#endif -#if defined(__NR_fstatat) - case __NR_fstatat: - return PerformStatat(args, /*arch64=*/false); + reinterpret_cast<struct kernel_stat64*>(args.args[1])); #endif #if defined(__NR_fstatat64) case __NR_fstatat64: - return PerformStatat(args, /*arch64=*/true); + return PerformStatat(args, /*stat64=*/true); #endif #if defined(__NR_newfstatat) case __NR_newfstatat: - return PerformStatat(args, /*arch64=*/false); + return PerformStatat(args, /*stat64=*/false); #endif #if defined(__NR_unlink) case __NR_unlink: return Unlink(reinterpret_cast<const char*>(args.args[0])); #endif #if defined(__NR_unlinkat) - case __NR_unlinkat: { - if (static_cast<int>(args.args[0]) != AT_FDCWD) - return -EPERM; - - int flags = static_cast<int>(args.args[2]); - - if (flags == AT_REMOVEDIR) { - return Rmdir(reinterpret_cast<const char*>(args.args[1])); - } - - if (flags != 0) - return -EPERM; - - return Unlink(reinterpret_cast<const char*>(args.args[1])); - } + case __NR_unlinkat: + return PerformUnlinkat(args); #endif // defined(__NR_unlinkat) default: RAW_CHECK(false);
diff --git a/sandbox/linux/syscall_broker/syscall_dispatcher.h b/sandbox/linux/syscall_broker/syscall_dispatcher.h index d8b8874a..1d6653c 100644 --- a/sandbox/linux/syscall_broker/syscall_dispatcher.h +++ b/sandbox/linux/syscall_broker/syscall_dispatcher.h
@@ -9,13 +9,15 @@ #include <cstddef> #include "sandbox/linux/system_headers/linux_seccomp.h" +#include "sandbox/linux/system_headers/linux_stat.h" +#include "sandbox/sandbox_export.h" namespace sandbox { namespace syscall_broker { // An abstract class that defines all the system calls we perform for the // sandboxed process. -class SyscallDispatcher { +class SANDBOX_EXPORT SyscallDispatcher { public: // Emulates access()/faccessat(). // X_OK will always return an error in practice since the broker process @@ -40,19 +42,34 @@ virtual int Rmdir(const char* path) const = 0; // Emulates stat()/stat64()/lstat()/lstat64()/fstatat()/newfstatat(). + // Stat64 is only available on 32-bit systems. virtual int Stat(const char* pathname, bool follow_links, - struct stat* sb) const = 0; + struct kernel_stat* sb) const = 0; virtual int Stat64(const char* pathname, bool follow_links, - struct stat64* sb) const = 0; + struct kernel_stat64* sb) const = 0; // Emulates unlink()/unlinkat(). virtual int Unlink(const char* unlink) const = 0; + // Different architectures use a different syscall from the stat family by + // default in glibc. E.g. 32-bit systems use *stat*64() and fill out struct + // kernel_stat64, whereas 64-bit systems use *stat*() and fill out struct + // kernel_stat. Some tests want to call the SyscallDispatcher directly, and + // should be using the default stat in order to test against glibc. + int DefaultStatForTesting(const char* pathname, + bool follow_links, + default_stat_struct* sb); + // Validates the args passed to a *statat*() syscall and performs the syscall - // using Stat() or Stat64(). - int PerformStatat(const arch_seccomp_data& args, bool arch64); + // using Stat(), or on 32-bit systems it uses Stat64() for the *statat64() + // syscalls. + int PerformStatat(const arch_seccomp_data& args, bool stat64); + + // Validates the args passed to an unlinkat() syscall and performs the syscall + // using either Unlink() or Rmdir(). + int PerformUnlinkat(const arch_seccomp_data& args); // Reads the syscall number and arguments, imposes some policy (e.g. the *at() // system calls must only allow AT_FDCWD as the first argument), and
diff --git a/sandbox/linux/system_headers/linux_stat.h b/sandbox/linux/system_headers/linux_stat.h new file mode 100644 index 0000000..35788eb --- /dev/null +++ b/sandbox/linux/system_headers/linux_stat.h
@@ -0,0 +1,188 @@ +// Copyright 2021 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 SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_STAT_H_ +#define SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_STAT_H_ + +#include <stdint.h> + +#include "build/build_config.h" +#include "sandbox/linux/system_headers/linux_syscalls.h" + +#if defined(ARCH_CPU_MIPS_FAMILY) +#if defined(ARCH_CPU_64_BITS) +struct kernel_stat { +#else +struct kernel_stat64 { +#endif + unsigned st_dev; + unsigned __pad0[3]; + unsigned long long st_ino; + unsigned st_mode; + unsigned st_nlink; + unsigned st_uid; + unsigned st_gid; + unsigned st_rdev; + unsigned __pad1[3]; + long long st_size; + unsigned st_atime_; + unsigned st_atime_nsec_; + unsigned st_mtime_; + unsigned st_mtime_nsec_; + unsigned st_ctime_; + unsigned st_ctime_nsec_; + unsigned st_blksize; + unsigned __pad2; + unsigned long long st_blocks; +}; +#else +struct kernel_stat64 { + unsigned long long st_dev; + unsigned char __pad0[4]; + unsigned __st_ino; + unsigned st_mode; + unsigned st_nlink; + unsigned st_uid; + unsigned st_gid; + unsigned long long st_rdev; + unsigned char __pad3[4]; + long long st_size; + unsigned st_blksize; + unsigned long long st_blocks; + unsigned st_atime_; + unsigned st_atime_nsec_; + unsigned st_mtime_; + unsigned st_mtime_nsec_; + unsigned st_ctime_; + unsigned st_ctime_nsec_; + unsigned long long st_ino; +}; +#endif + +#if defined(__i386__) || defined(__ARM_ARCH_3__) || defined(__ARM_EABI__) +struct kernel_stat { + /* The kernel headers suggest that st_dev and st_rdev should be 32bit + * quantities encoding 12bit major and 20bit minor numbers in an interleaved + * format. In reality, we do not see useful data in the top bits. So, + * we'll leave the padding in here, until we find a better solution. + */ + unsigned short st_dev; + short pad1; + unsigned st_ino; + unsigned short st_mode; + unsigned short st_nlink; + unsigned short st_uid; + unsigned short st_gid; + unsigned short st_rdev; + short pad2; + unsigned st_size; + unsigned st_blksize; + unsigned st_blocks; + unsigned st_atime_; + unsigned st_atime_nsec_; + unsigned st_mtime_; + unsigned st_mtime_nsec_; + unsigned st_ctime_; + unsigned st_ctime_nsec_; + unsigned __unused4; + unsigned __unused5; +}; +#elif defined(__x86_64__) +struct kernel_stat { + uint64_t st_dev; + uint64_t st_ino; + uint64_t st_nlink; + unsigned st_mode; + unsigned st_uid; + unsigned st_gid; + unsigned __pad0; + uint64_t st_rdev; + int64_t st_size; + int64_t st_blksize; + int64_t st_blocks; + uint64_t st_atime_; + uint64_t st_atime_nsec_; + uint64_t st_mtime_; + uint64_t st_mtime_nsec_; + uint64_t st_ctime_; + uint64_t st_ctime_nsec_; + int64_t __unused4[3]; +}; +#elif (defined(ARCH_CPU_MIPS_FAMILY) && defined(ARCH_CPU_32_BITS)) +struct kernel_stat { + unsigned st_dev; + int st_pad1[3]; + unsigned st_ino; + unsigned st_mode; + unsigned st_nlink; + unsigned st_uid; + unsigned st_gid; + unsigned st_rdev; + int st_pad2[2]; + long st_size; + int st_pad3; + long st_atime_; + long st_atime_nsec_; + long st_mtime_; + long st_mtime_nsec_; + long st_ctime_; + long st_ctime_nsec_; + int st_blksize; + int st_blocks; + int st_pad4[14]; +}; +#elif defined(__aarch64__) +struct kernel_stat { + unsigned long st_dev; + unsigned long st_ino; + unsigned int st_mode; + unsigned int st_nlink; + unsigned int st_uid; + unsigned int st_gid; + unsigned long st_rdev; + unsigned long __pad1; + long st_size; + int st_blksize; + int __pad2; + long st_blocks; + long st_atime_; + unsigned long st_atime_nsec_; + long st_mtime_; + unsigned long st_mtime_nsec_; + long st_ctime_; + unsigned long st_ctime_nsec_; + unsigned int __unused4; + unsigned int __unused5; +}; +#endif + +// On 32-bit systems, we default to the 64-bit stat struct like libc +// implementations do. Otherwise we default to the normal stat struct which is +// already 64-bit. +// These defines make it easy to call the right syscall to fill out a 64-bit +// stat struct, which is the default in libc implementations but requires +// different syscall names on 32 and 64-bit platforms. +#if defined(__NR_fstatat64) + +namespace sandbox { +using default_stat_struct = struct kernel_stat64; +} // namespace sandbox + +#define __NR_fstatat_default __NR_fstatat64 +#define __NR_fstat_default __NR_fstat64 + +#elif defined(__NR_newfstatat) + +namespace sandbox { +using default_stat_struct = struct kernel_stat; +} // namespace sandbox + +#define __NR_fstatat_default __NR_newfstatat +#define __NR_fstat_default __NR_fstat + +#else +#error "one of fstatat64 and newfstatat must be defined" +#endif + +#endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_STAT_H_
diff --git a/sandbox/linux/system_headers/linux_time.h b/sandbox/linux/system_headers/linux_time.h index 780f24d..f18c806 100644 --- a/sandbox/linux/system_headers/linux_time.h +++ b/sandbox/linux/system_headers/linux_time.h
@@ -11,6 +11,32 @@ #define CPUCLOCK_CLOCK_MASK 3 #endif +#if !defined(CPUCLOCK_PROF) +#define CPUCLOCK_PROF 0 +#endif + +#if !defined(CPUCLOCK_VIRT) +#define CPUCLOCK_VIRT 1 +#endif + +#if !defined(CPUCLOCK_SCHED) +#define CPUCLOCK_SCHED 2 +#endif + +#if !defined(CPUCLOCK_PERTHREAD_MASK) +#define CPUCLOCK_PERTHREAD_MASK 4 +#endif + +#if !defined(MAKE_PROCESS_CPUCLOCK) +#define MAKE_PROCESS_CPUCLOCK(pid, clock) \ + ((int)(~(unsigned)(pid) << 3) | (int)(clock)) +#endif + +#if !defined(MAKE_THREAD_CPUCLOCK) +#define MAKE_THREAD_CPUCLOCK(tid, clock) \ + ((int)(~(unsigned)(tid) << 3) | (int)((clock) | CPUCLOCK_PERTHREAD_MASK)) +#endif + #if !defined(CLOCKFD) #define CLOCKFD 3 #endif
diff --git a/sandbox/linux/tests/test_utils.cc b/sandbox/linux/tests/test_utils.cc index 847c20b..cf6041a 100644 --- a/sandbox/linux/tests/test_utils.cc +++ b/sandbox/linux/tests/test_utils.cc
@@ -5,12 +5,14 @@ #include "sandbox/linux/tests/test_utils.h" #include <errno.h> +#include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "base/check_op.h" +#include "base/memory/page_size.h" #include "base/posix/eintr_wrapper.h" namespace sandbox { @@ -39,4 +41,17 @@ } } +void* TestUtils::MapPagesOrDie(size_t num_pages) { + void* addr = mmap(nullptr, num_pages * base::GetPageSize(), + PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + PCHECK(addr); + return addr; +} + +void TestUtils::MprotectLastPageOrDie(char* addr, size_t num_pages) { + size_t last_page_offset = (num_pages - 1) * base::GetPageSize(); + PCHECK(mprotect(addr + last_page_offset, base::GetPageSize(), PROT_NONE) >= + 0); +} + } // namespace sandbox
diff --git a/sandbox/linux/tests/test_utils.h b/sandbox/linux/tests/test_utils.h index 7cf9749f..43b028b1 100644 --- a/sandbox/linux/tests/test_utils.h +++ b/sandbox/linux/tests/test_utils.h
@@ -19,6 +19,8 @@ // makes sure that if fork() succeeded the child exits // and the parent waits for it. static void HandlePostForkReturn(pid_t pid); + static void* MapPagesOrDie(size_t num_pages); + static void MprotectLastPageOrDie(char* addr, size_t num_pages); private: DISALLOW_IMPLICIT_CONSTRUCTORS(TestUtils);
diff --git a/sandbox/policy/linux/bpf_broker_policy_linux.cc b/sandbox/policy/linux/bpf_broker_policy_linux.cc index 2963bb9..6dc8c05 100644 --- a/sandbox/policy/linux/bpf_broker_policy_linux.cc +++ b/sandbox/policy/linux/bpf_broker_policy_linux.cc
@@ -93,8 +93,8 @@ return Allow(); break; #endif -#if defined(__NR_fstatat) - case __NR_fstatat: +#if defined(__NR_fstatat64) + case __NR_fstatat64: if (allowed_command_set_.test(syscall_broker::COMMAND_STAT)) return Allow(); break;
diff --git a/services/network/public/cpp/simple_url_loader.cc b/services/network/public/cpp/simple_url_loader.cc index 38c9386..4d2f1c6f 100644 --- a/services/network/public/cpp/simple_url_loader.cc +++ b/services/network/public/cpp/simple_url_loader.cc
@@ -78,6 +78,11 @@ public: explicit StringUploadDataPipeGetter(const std::string& upload_string) : upload_string_(upload_string) {} + + StringUploadDataPipeGetter(const StringUploadDataPipeGetter&) = delete; + StringUploadDataPipeGetter& operator=(const StringUploadDataPipeGetter&) = + delete; + ~StringUploadDataPipeGetter() override = default; // Returns a mojo::PendingRemote<mojom::DataPipeGetter> for a new upload @@ -178,8 +183,6 @@ size_t write_position_ = 0; const std::string upload_string_; - - DISALLOW_COPY_AND_ASSIGN(StringUploadDataPipeGetter); }; class BodyHandler; @@ -189,6 +192,10 @@ public: SimpleURLLoaderImpl(std::unique_ptr<ResourceRequest> resource_request, const net::NetworkTrafficAnnotationTag& annotation_tag); + + SimpleURLLoaderImpl(const SimpleURLLoaderImpl&) = delete; + SimpleURLLoaderImpl& operator=(const SimpleURLLoaderImpl&) = delete; + ~SimpleURLLoaderImpl() override; // SimpleURLLoader implementation. @@ -384,8 +391,6 @@ SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<SimpleURLLoaderImpl> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(SimpleURLLoaderImpl); }; // Utility class to drive the pipe reading a response body. Can be created on @@ -397,6 +402,9 @@ public: Delegate() {} + Delegate(const Delegate&) = delete; + Delegate& operator=(const Delegate&) = delete; + // The specified amount of data was read from the pipe. The Delegate should // return net::OK to continue reading, or a value indicating an error if the // pipe should be closed. A return value of net::ERR_IO_PENDING means that @@ -415,10 +423,7 @@ virtual void OnDone(net::Error error, int64_t total_bytes) = 0; protected: - virtual ~Delegate() {} - - private: - DISALLOW_COPY_AND_ASSIGN(Delegate); + virtual ~Delegate() = default; }; BodyReader(Delegate* delegate, int64_t max_body_size) @@ -426,6 +431,9 @@ DCHECK_GE(max_body_size_, 0); } + BodyReader(const BodyReader&) = delete; + BodyReader& operator=(const BodyReader&) = delete; + // Makes the reader start reading from |body_data_pipe|. May only be called // once. The reader will continuously to try to read from the pipe (without // blocking the thread), calling OnDataRead as data is read, until one of the @@ -568,8 +576,6 @@ net::Error pending_error_ = net::OK; base::WeakPtrFactory<BodyReader> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(BodyReader); }; // Class to drive the pipe for reading the body, handle the results of the body @@ -583,7 +589,11 @@ bool want_download_progress) : simple_url_loader_(simple_url_loader), want_download_progress_(want_download_progress) {} - virtual ~BodyHandler() {} + + BodyHandler(const BodyHandler&) = delete; + BodyHandler& operator=(const BodyHandler&) = delete; + + virtual ~BodyHandler() = default; // Called by SimpleURLLoader with the data pipe received from the URLLoader. // The BodyHandler is responsible for reading from it and monitoring it for @@ -621,8 +631,6 @@ private: SimpleURLLoaderImpl* const simple_url_loader_; bool const want_download_progress_; - - DISALLOW_COPY_AND_ASSIGN(BodyHandler); }; // BodyHandler implementation for consuming the response as a string. @@ -638,7 +646,10 @@ max_body_size_(max_body_size), body_as_string_callback_(std::move(body_as_string_callback)) {} - ~SaveToStringBodyHandler() override {} + SaveToStringBodyHandler(const SaveToStringBodyHandler&) = delete; + SaveToStringBodyHandler& operator=(const SaveToStringBodyHandler&) = delete; + + ~SaveToStringBodyHandler() override = default; // BodyHandler implementation: @@ -691,8 +702,6 @@ SimpleURLLoader::BodyAsStringCallback body_as_string_callback_; std::unique_ptr<BodyReader> body_reader_; - - DISALLOW_COPY_AND_ASSIGN(SaveToStringBodyHandler); }; // BodyHandler that discards the response body. @@ -704,7 +713,10 @@ : BodyHandler(simple_url_loader, false /* no download progress */), headers_only_callback_(std::move(headers_only_callback)) {} - ~HeadersOnlyBodyHandler() override {} + HeadersOnlyBodyHandler(const HeadersOnlyBodyHandler&) = delete; + HeadersOnlyBodyHandler& operator=(const HeadersOnlyBodyHandler&) = delete; + + ~HeadersOnlyBodyHandler() override = default; // BodyHandler implementation void OnStartLoadingResponseBody( @@ -743,8 +755,6 @@ SimpleURLLoader::HeadersOnlyCallback headers_only_callback_; std::unique_ptr<BodyReader> body_reader_; - - DISALLOW_COPY_AND_ASSIGN(HeadersOnlyBodyHandler); }; // BodyHandler implementation for saving the response to a file @@ -776,6 +786,9 @@ : base::RepeatingCallback<void(int64_t)>()); } + SaveToFileBodyHandler(const SaveToFileBodyHandler&) = delete; + SaveToFileBodyHandler& operator=(const SaveToFileBodyHandler&) = delete; + ~SaveToFileBodyHandler() override { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (file_writer_) { @@ -870,6 +883,9 @@ DCHECK(create_temp_file_ || !path_.empty()); } + FileWriter(const FileWriter&) = delete; + FileWriter& operator=(const FileWriter&) = delete; + // Starts reading from |body_data_pipe| and writing to the file. void StartWriting(mojo::ScopedDataPipeConsumerHandle body_data_pipe, OnDoneCallback on_done_callback) { @@ -1040,8 +1056,6 @@ // True if a file was successfully created. Set to false when the file is // destroyed. bool owns_file_ = false; - - DISALLOW_COPY_AND_ASSIGN(FileWriter); }; // Called by FileWriter::Destroy after deleting a partially downloaded file. @@ -1068,8 +1082,6 @@ SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<SaveToFileBodyHandler> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(SaveToFileBodyHandler); }; // Class to handle streaming data to the consumer as it arrives @@ -1082,7 +1094,11 @@ : BodyHandler(simple_url_loader, want_download_progress), stream_consumer_(stream_consumer) {} - ~DownloadAsStreamBodyHandler() override {} + DownloadAsStreamBodyHandler(const DownloadAsStreamBodyHandler&) = delete; + DownloadAsStreamBodyHandler& operator=(const DownloadAsStreamBodyHandler&) = + delete; + + ~DownloadAsStreamBodyHandler() override = default; // BodyHandler implementation: @@ -1153,8 +1169,6 @@ bool in_recursive_call_ = false; base::WeakPtrFactory<DownloadAsStreamBodyHandler> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(DownloadAsStreamBodyHandler); }; SimpleURLLoaderImpl::SimpleURLLoaderImpl(
diff --git a/services/network/public/cpp/simple_url_loader.h b/services/network/public/cpp/simple_url_loader.h index 802a617..a06b472 100644 --- a/services/network/public/cpp/simple_url_loader.h +++ b/services/network/public/cpp/simple_url_loader.h
@@ -14,8 +14,8 @@ #include "base/callback_forward.h" #include "base/component_export.h" -#include "base/macros.h" -#include "services/network/public/mojom/url_response_head.mojom.h" +#include "services/network/public/cpp/url_loader_completion_status.h" +#include "services/network/public/mojom/url_response_head.mojom-forward.h" #include "third_party/abseil-cpp/absl/types/optional.h" class GURL; @@ -152,6 +152,9 @@ static void SetTimeoutTickClockForTest( const base::TickClock* timeout_tick_clock); + SimpleURLLoader(const SimpleURLLoader&) = delete; + SimpleURLLoader& operator=(const SimpleURLLoader&) = delete; + virtual ~SimpleURLLoader(); // Starts the request using |url_loader_factory|. The SimpleURLLoader will @@ -381,9 +384,6 @@ protected: SimpleURLLoader(); - - private: - DISALLOW_COPY_AND_ASSIGN(SimpleURLLoader); }; } // namespace network
diff --git a/services/network/trust_tokens/trust_token_key_commitment_controller_unittest.cc b/services/network/trust_tokens/trust_token_key_commitment_controller_unittest.cc index 8e12f32..19aedd9 100644 --- a/services/network/trust_tokens/trust_token_key_commitment_controller_unittest.cc +++ b/services/network/trust_tokens/trust_token_key_commitment_controller_unittest.cc
@@ -21,6 +21,7 @@ #include "services/network/public/mojom/trust_tokens.mojom-forward.h" #include "services/network/public/mojom/trust_tokens.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" +#include "services/network/public/mojom/url_response_head.mojom.h" #include "services/network/test/test_url_loader_factory.h" #include "services/network/test/test_utils.h" #include "services/network/trust_tokens/trust_token_key_commitment_controller.h"
diff --git a/services/resource_coordinator/BUILD.gn b/services/resource_coordinator/BUILD.gn index a99688cd..6c5ec81 100644 --- a/services/resource_coordinator/BUILD.gn +++ b/services/resource_coordinator/BUILD.gn
@@ -63,7 +63,7 @@ "//mojo/public/cpp/bindings", "//services/resource_coordinator/public/cpp:resource_coordinator_cpp", "//services/resource_coordinator/public/cpp/memory_instrumentation:memory_instrumentation", - "//services/tracing:test_utils", + "//services/tracing:tests", "//testing/gmock", "//testing/gtest", ]
diff --git a/services/resource_coordinator/memory_instrumentation/coordinator_impl.cc b/services/resource_coordinator/memory_instrumentation/coordinator_impl.cc index e838c6a..741e35d 100644 --- a/services/resource_coordinator/memory_instrumentation/coordinator_impl.cc +++ b/services/resource_coordinator/memory_instrumentation/coordinator_impl.cc
@@ -65,10 +65,7 @@ : next_dump_id_(0), client_process_timeout_(base::TimeDelta::FromSeconds(15)), use_proto_writer_(!base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kUseMemoryTrackingJsonWriter)), - write_proto_heap_profile_( - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kUseHeapProfilingProtoWriter)) { + switches::kUseMemoryTrackingJsonWriter)) { DCHECK(!g_coordinator_impl); g_coordinator_impl = this; base::trace_event::MemoryDumpManager::GetInstance()->set_tracing_process_id( @@ -411,7 +408,7 @@ ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( - strip_path_from_mapped_files, write_proto_heap_profile_, + strip_path_from_mapped_files, base::BindOnce(&CoordinatorImpl::OnDumpProcessesForTracing, weak_ptr_factory_.GetWeakPtr(), request->dump_guid));
diff --git a/services/resource_coordinator/memory_instrumentation/coordinator_impl.h b/services/resource_coordinator/memory_instrumentation/coordinator_impl.h index 2042b25f..22e1a7e 100644 --- a/services/resource_coordinator/memory_instrumentation/coordinator_impl.h +++ b/services/resource_coordinator/memory_instrumentation/coordinator_impl.h
@@ -190,7 +190,6 @@ this}; const bool use_proto_writer_; - const bool write_proto_heap_profile_; THREAD_CHECKER(thread_checker_); base::WeakPtrFactory<CoordinatorImpl> weak_ptr_factory_{this};
diff --git a/services/resource_coordinator/memory_instrumentation/switches.cc b/services/resource_coordinator/memory_instrumentation/switches.cc index 82f7149..18ae9fea 100644 --- a/services/resource_coordinator/memory_instrumentation/switches.cc +++ b/services/resource_coordinator/memory_instrumentation/switches.cc
@@ -11,7 +11,6 @@ const char kDisableChromeTracingComputation[] = "disable-chrome-tracing-computation"; const char kUseMemoryTrackingJsonWriter[] = "use-memory-tracking-json-writer"; -const char kUseHeapProfilingProtoWriter[] = "use-heap-profiling-proto-writer"; } // namespace switches } // namespace memory_instrumentation
diff --git a/services/resource_coordinator/memory_instrumentation/switches.h b/services/resource_coordinator/memory_instrumentation/switches.h index 9a871451..af03fb2 100644 --- a/services/resource_coordinator/memory_instrumentation/switches.h +++ b/services/resource_coordinator/memory_instrumentation/switches.h
@@ -12,7 +12,6 @@ // alongside the definition of their values in the .cc file. extern const char kDisableChromeTracingComputation[]; extern const char kUseMemoryTrackingJsonWriter[]; -extern const char kUseHeapProfilingProtoWriter[]; } // namespace switches } // namespace memory_instrumentation
diff --git a/services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom b/services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom index fce4c9b..58b0290 100644 --- a/services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom +++ b/services/resource_coordinator/public/mojom/memory_instrumentation/memory_instrumentation.mojom
@@ -286,9 +286,7 @@ // |strip_path_from_mapped_files| should only be true for traces that will be // uploaded to the crash servers - this strips potential PII, but prevents // symbolization of local builds. - // |write_proto| will additionally write proto heap profiles to traces. - DumpProcessesForTracing(bool strip_path_from_mapped_files, - bool write_proto) => + DumpProcessesForTracing(bool strip_path_from_mapped_files) => (array<HeapProfileResult> results); };
diff --git a/services/tracing/BUILD.gn b/services/tracing/BUILD.gn index 908db1a..2b03e80e 100644 --- a/services/tracing/BUILD.gn +++ b/services/tracing/BUILD.gn
@@ -60,8 +60,6 @@ sources = [ "perfetto/test_utils.cc", "perfetto/test_utils.h", - "public/cpp/perfetto/producer_test_utils.cc", - "public/cpp/perfetto/producer_test_utils.h", ] deps = [ @@ -71,7 +69,6 @@ "//testing/gtest", "//third_party/perfetto/protos/perfetto/common:lite", "//third_party/perfetto/protos/perfetto/trace:lite", - "//third_party/perfetto/protos/perfetto/trace/chrome:lite", ] if (is_posix) { @@ -89,6 +86,8 @@ "perfetto/consumer_host_unittest.cc", "perfetto/perfetto_integration_unittest.cc", "perfetto/privacy_filtering_check_unittest.cc", + "public/cpp/perfetto/producer_test_utils.cc", + "public/cpp/perfetto/producer_test_utils.h", "public/cpp/perfetto/trace_event_data_source_unittest.cc", "public/cpp/perfetto/trace_packet_tokenizer_unittest.cc", "public/cpp/perfetto/traced_value_proto_writer_unittest.cc",
diff --git a/services/tracing/public/cpp/perfetto/perfetto_config.cc b/services/tracing/public/cpp/perfetto/perfetto_config.cc index b0265e0..a105d06 100644 --- a/services/tracing/public/cpp/perfetto/perfetto_config.cc +++ b/services/tracing/public/cpp/perfetto/perfetto_config.cc
@@ -66,10 +66,6 @@ perfetto_config, tracing::mojom::kMemoryInstrumentationDataSourceName, chrome_config_string, privacy_filtering_enabled, convert_to_legacy_json, client_priority, json_agent_label_filter); - AddDataSourceConfig( - perfetto_config, tracing::mojom::kNativeHeapProfilerSourceName, - chrome_config_string, privacy_filtering_enabled, convert_to_legacy_json, - client_priority, json_agent_label_filter); } // Capture actual trace events.
diff --git a/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h b/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h index 921120cd..1eee5776 100644 --- a/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h +++ b/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h
@@ -58,7 +58,7 @@ // field |profiler_| to be thread-safe. class COMPONENT_EXPORT(TRACING_CPP) TracingSamplerProfiler { public: - class COMPONENT_EXPORT(TRACING_CPP) StackProfileWriter { + class StackProfileWriter { public: explicit StackProfileWriter(bool should_enable_filtering); ~StackProfileWriter();
diff --git a/services/tracing/public/mojom/perfetto_service.mojom b/services/tracing/public/mojom/perfetto_service.mojom index 68e5efd..07a13093 100644 --- a/services/tracing/public/mojom/perfetto_service.mojom +++ b/services/tracing/public/mojom/perfetto_service.mojom
@@ -22,8 +22,6 @@ const string kJavaHeapProfilerSourceName = "org.chromium.java_heap_profiler"; const string kReachedCodeProfilerSourceName = "org.chromium.reached_code_profiler"; -const string kNativeHeapProfilerSourceName = - "org.chromium.native_heap_profiler"; // Brief description of the flow: There's a per-process ProducerClient which // connects to the central PerfettoService and establishes a two-way connection
diff --git a/services/video_capture/OWNERS b/services/video_capture/OWNERS index 3caeb94..558abee 100644 --- a/services/video_capture/OWNERS +++ b/services/video_capture/OWNERS
@@ -1,4 +1,5 @@ -guidou@chromium.org +handellm@google.com +hbos@chromium.org # Original (legacy) owners. per-file *video*=mcasas@chromium.org
diff --git a/skia/BUILD.gn b/skia/BUILD.gn index cf16ad2f..d8233ae 100644 --- a/skia/BUILD.gn +++ b/skia/BUILD.gn
@@ -60,6 +60,7 @@ "SK_CODEC_DECODES_WEBP", "SK_ENCODE_PNG", "SK_ENCODE_WEBP", + "SK_ENABLE_SKSL", "SK_USER_CONFIG_HEADER=\"../../skia/config/SkUserConfig.h\"", ]
diff --git a/sql/database.cc b/sql/database.cc index cfaec86..ebad24b 100644 --- a/sql/database.cc +++ b/sql/database.cc
@@ -12,6 +12,7 @@ #include <algorithm> #include <memory> +#include "base/dcheck_is_on.h" #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/files/file_util.h" @@ -489,7 +490,7 @@ // SQLITE_ERROR often indicates some sort of mismatch between the statement // and the schema, possibly due to a failed schema migration. if (error == SQLITE_ERROR) { - static const char kVersionSql[] = + static constexpr char kVersionSql[] = "SELECT value FROM meta WHERE key='version'"; sqlite3_stmt* sqlite_statement; // When the number of bytes passed to sqlite3_prepare_v3() includes the null @@ -524,7 +525,7 @@ // |rootpage| is not interesting for debugging, without the contents of the // database. The COALESCE is because certain automatic elements will have a // |name| but no |sql|, - static const char kSchemaSql[] = + static constexpr char kSchemaSql[] = "SELECT COALESCE(sql,name) FROM sqlite_master"; rc = sqlite3_prepare_v3(db_, kSchemaSql, sizeof(kSchemaSql), SQLITE_PREPARE_NO_VTAB, &sqlite_statement, @@ -1252,11 +1253,17 @@ absl::optional<base::ScopedBlockingCall> scoped_blocking_call; InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call); +#if DCHECK_IS_ON() + const char* unused_sql = nullptr; + const char** unused_sql_ptr = &unused_sql; +#else + constexpr const char** unused_sql_ptr = nullptr; +#endif // DCHECK_IS_ON() // TODO(pwnall): Cached statements (but not unique statements) should be // prepared with prepFlags set to SQLITE_PREPARE_PERSISTENT. sqlite3_stmt* sqlite_statement; int rc = sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(), - &sqlite_statement, /* pzTail= */ nullptr); + &sqlite_statement, unused_sql_ptr); if (rc != SQLITE_OK) { OnSqliteError(rc, nullptr, sql); @@ -1277,6 +1284,12 @@ return base::MakeRefCounted<StatementRef>(nullptr, nullptr, false); } + +#if DCHECK_IS_ON() + DCHECK_EQ(unused_sql, sql + std::strlen(sql)) + << "Unused text: " << std::string(unused_sql) << "\n" + << "in prepared SQL statement: " << std::string(sql); +#endif // DCHECK_IS_ON() return base::MakeRefCounted<StatementRef>(this, sqlite_statement, true); } @@ -1311,13 +1324,25 @@ return false; } +#if DCHECK_IS_ON() + const char* unused_sql = nullptr; + const char** unused_sql_ptr = &unused_sql; +#else + constexpr const char** unused_sql_ptr = nullptr; +#endif // DCHECK_IS_ON() + sqlite3_stmt* sqlite_statement = nullptr; if (sqlite3_prepare_v3(db_, sql, /* nByte= */ -1, SqlitePrepareFlags(), - &sqlite_statement, - /* pzTail= */ nullptr) != SQLITE_OK) { + &sqlite_statement, unused_sql_ptr) != SQLITE_OK) { return false; } +#if DCHECK_IS_ON() + DCHECK_EQ(unused_sql, sql + std::strlen(sql)) + << "Unused text: " << std::string(unused_sql) << "\n" + << "in SQL statement: " << std::string(sql); +#endif // DCHECK_IS_ON() + sqlite3_finalize(sqlite_statement); return true; }
diff --git a/sql/database_unittest.cc b/sql/database_unittest.cc index cf468306..c92f997 100644 --- a/sql/database_unittest.cc +++ b/sql/database_unittest.cc
@@ -6,6 +6,7 @@ #include <stddef.h> #include <stdint.h> +#include <cstdint> #include "base/bind.h" #include "base/files/file_util.h" @@ -505,6 +506,69 @@ << "SQL compilation errors should call the error callback"; } +TEST_P(SQLDatabaseTest, GetUniqueStatement_ExtraContents) { + sql::Statement minimal(db_->GetUniqueStatement("SELECT 1")); + sql::Statement extra_semicolon(db_->GetUniqueStatement("SELECT 1;")); + + // It would be nice to flag trailing comments too, as they cost binary size. + // However, there's no easy way of doing that. + sql::Statement trailing_comment( + db_->GetUniqueStatement("SELECT 1 -- Comment")); + + EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1;SELECT 2")) + << "Extra statement without whitespace"; + EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1; SELECT 2")) + << "Extra statement separated by whitespace"; + EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1;-- Comment")) + << "Comment without whitespace"; + EXPECT_DCHECK_DEATH(db_->GetUniqueStatement("SELECT 1; -- Comment")) + << "Comment separated by whitespace"; +} + +TEST_P(SQLDatabaseTest, GetCachedStatement_ExtraContents) { + sql::Statement minimal(db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1")); + sql::Statement extra_semicolon( + db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;")); + + // It would be nice to flag trailing comments too, as they cost binary size. + // However, there's no easy way of doing that. + sql::Statement trailing_comment( + db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1 -- Comment")); + + EXPECT_DCHECK_DEATH( + db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;SELECT 2")) + << "Extra statement without whitespace"; + EXPECT_DCHECK_DEATH( + db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; SELECT 2")) + << "Extra statement separated by whitespace"; + EXPECT_DCHECK_DEATH( + db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1;-- Comment")) + << "Comment without whitespace"; + EXPECT_DCHECK_DEATH( + db_->GetCachedStatement(SQL_FROM_HERE, "SELECT 1; -- Comment")) + << "Comment separated by whitespace"; +} + +TEST_P(SQLDatabaseTest, IsSQLValid_ExtraContents) { + EXPECT_TRUE(db_->IsSQLValid("SELECT 1")); + EXPECT_TRUE(db_->IsSQLValid("SELECT 1;")) + << "Trailing semicolons are currently tolerated"; + + // It would be nice to flag trailing comments too, as they cost binary size. + // However, there's no easy way of doing that. + EXPECT_TRUE(db_->IsSQLValid("SELECT 1 -- Comment")) + << "Trailing comments are currently tolerated"; + + EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1;SELECT 2")) + << "Extra statement without whitespace"; + EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1; SELECT 2")) + << "Extra statement separated by whitespace"; + EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1;-- Comment")) + << "Comment without whitespace"; + EXPECT_DCHECK_DEATH(db_->IsSQLValid("SELECT 1; -- Comment")) + << "Comment separated by whitespace"; +} + // Test that Database::Raze() results in a database without the // tables from the original database. TEST_P(SQLDatabaseTest, Raze) {
diff --git a/storage/browser/file_system/file_system_quota_client_unittest.cc b/storage/browser/file_system/file_system_quota_client_unittest.cc index 6170c8e2..5be987c8 100644 --- a/storage/browser/file_system/file_system_quota_client_unittest.cc +++ b/storage/browser/file_system/file_system_quota_client_unittest.cc
@@ -158,25 +158,24 @@ } void InitializeOriginFiles(storage::mojom::QuotaClient& quota_client, - const TestFile* files, - int num_files) { - for (int i = 0; i < num_files; i++) { - base::FilePath path = base::FilePath().AppendASCII(files[i].name); - if (files[i].isDirectory) { - ASSERT_TRUE(CreateFileSystemDirectory(path, files[i].origin_url, - files[i].type)); + const std::vector<TestFile>& files) { + for (const TestFile& file : files) { + base::FilePath path = base::FilePath().AppendASCII(file.name); + if (file.isDirectory) { + ASSERT_TRUE( + CreateFileSystemDirectory(path, file.origin_url, file.type)); if (path.empty()) { // Create the usage cache. // HACK--we always create the root [an empty path] first. If we // create it later, this will fail due to a quota mismatch. If we // call this before we create the root, it succeeds, but hasn't // actually created the cache. - ASSERT_EQ(0, GetStorageKeyUsage(quota_client, files[i].origin_url, - files[i].type)); + ASSERT_EQ( + 0, GetStorageKeyUsage(quota_client, file.origin_url, file.type)); } } else { - ASSERT_TRUE(CreateFileSystemFile(path, files[i].size, - files[i].origin_url, files[i].type)); + ASSERT_TRUE( + CreateFileSystemFile(path, file.size, file.origin_url, file.type)); } } } @@ -185,15 +184,14 @@ // directory before adding a file or directory to it, so that we can just // count the basename of each addition. A recursive creation of a path, which // created more than one directory in a single shot, would break this. - int64_t ComputeFilePathsCostForOriginAndType(const TestFile* files, - int num_files, - const std::string& origin_url, - StorageType type) { + int64_t ComputeFilePathsCostForOriginAndType( + const base::span<const TestFile> files, + const std::string& origin_url, + StorageType type) { int64_t file_paths_cost = 0; - for (int i = 0; i < num_files; i++) { - if (files[i].type == type && - GURL(files[i].origin_url) == GURL(origin_url)) { - base::FilePath path = base::FilePath().AppendASCII(files[i].name); + for (const TestFile& file : files) { + if (file.type == type && GURL(file.origin_url) == GURL(origin_url)) { + base::FilePath path = base::FilePath().AppendASCII(file.name); if (!path.empty()) { file_paths_cost += ObfuscatedFileUtil::ComputeFilePathCost(path); } @@ -254,10 +252,7 @@ TEST_F(FileSystemQuotaClientTest, NoFileTest) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { - {true, "", 0, kDummyURL1, kTemporary}, - }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); + InitializeOriginFiles(quota_client, {{true, "", 0, kDummyURL1, kTemporary}}); for (int i = 0; i < 2; i++) { EXPECT_EQ(0, GetStorageKeyUsage(quota_client, kDummyURL1, kTemporary)); @@ -266,13 +261,13 @@ TEST_F(FileSystemQuotaClientTest, OneFileTest) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { + const std::vector<TestFile> kFiles = { {true, "", 0, kDummyURL1, kTemporary}, {false, "foo", 4921, kDummyURL1, kTemporary}, }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); - const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( - kFiles, base::size(kFiles), kDummyURL1, kTemporary); + InitializeOriginFiles(quota_client, kFiles); + const int64_t file_paths_cost = + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kTemporary); for (int i = 0; i < 2; i++) { EXPECT_EQ(4921 + file_paths_cost, @@ -282,14 +277,14 @@ TEST_F(FileSystemQuotaClientTest, TwoFilesTest) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { + const std::vector<TestFile> kFiles = { {true, "", 0, kDummyURL1, kTemporary}, {false, "foo", 10310, kDummyURL1, kTemporary}, {false, "bar", 41, kDummyURL1, kTemporary}, }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); - const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( - kFiles, base::size(kFiles), kDummyURL1, kTemporary); + InitializeOriginFiles(quota_client, kFiles); + const int64_t file_paths_cost = + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kTemporary); for (int i = 0; i < 2; i++) { EXPECT_EQ(10310 + 41 + file_paths_cost, @@ -299,15 +294,15 @@ TEST_F(FileSystemQuotaClientTest, EmptyFilesTest) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { + const std::vector<TestFile> kFiles = { {true, "", 0, kDummyURL1, kTemporary}, {false, "foo", 0, kDummyURL1, kTemporary}, {false, "bar", 0, kDummyURL1, kTemporary}, {false, "baz", 0, kDummyURL1, kTemporary}, }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); - const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( - kFiles, base::size(kFiles), kDummyURL1, kTemporary); + InitializeOriginFiles(quota_client, kFiles); + const int64_t file_paths_cost = + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kTemporary); for (int i = 0; i < 2; i++) { EXPECT_EQ(file_paths_cost, @@ -317,15 +312,15 @@ TEST_F(FileSystemQuotaClientTest, SubDirectoryTest) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { + const std::vector<TestFile> kFiles = { {true, "", 0, kDummyURL1, kTemporary}, {true, "dirtest", 0, kDummyURL1, kTemporary}, {false, "dirtest/foo", 11921, kDummyURL1, kTemporary}, {false, "bar", 4814, kDummyURL1, kTemporary}, }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); - const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( - kFiles, base::size(kFiles), kDummyURL1, kTemporary); + InitializeOriginFiles(quota_client, kFiles); + const int64_t file_paths_cost = + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kTemporary); for (int i = 0; i < 2; i++) { EXPECT_EQ(11921 + 4814 + file_paths_cost, @@ -335,7 +330,7 @@ TEST_F(FileSystemQuotaClientTest, MultiTypeTest) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { + const std::vector<TestFile> kFiles = { {true, "", 0, kDummyURL1, kTemporary}, {true, "dirtest", 0, kDummyURL1, kTemporary}, {false, "dirtest/foo", 133, kDummyURL1, kTemporary}, @@ -345,13 +340,11 @@ {false, "dirtest/foo", 193, kDummyURL1, kPersistent}, {false, "bar", 9, kDummyURL1, kPersistent}, }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); + InitializeOriginFiles(quota_client, kFiles); const int64_t file_paths_cost_temporary = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - kDummyURL1, kTemporary); + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kTemporary); const int64_t file_paths_cost_persistent = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - kDummyURL1, kTemporary); + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kTemporary); for (int i = 0; i < 2; i++) { EXPECT_EQ(133 + 14 + file_paths_cost_temporary, @@ -363,7 +356,7 @@ TEST_F(FileSystemQuotaClientTest, MultiDomainTest) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { + const std::vector<TestFile> kFiles = { {true, "", 0, kDummyURL1, kTemporary}, {true, "dir1", 0, kDummyURL1, kTemporary}, {false, "dir1/foo", 1331, kDummyURL1, kTemporary}, @@ -381,19 +374,15 @@ {false, "dom/fan", 2013, kDummyURL2, kPersistent}, {false, "baz", 18, kDummyURL2, kPersistent}, }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); + InitializeOriginFiles(quota_client, kFiles); const int64_t file_paths_cost_temporary1 = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - kDummyURL1, kTemporary); + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kTemporary); const int64_t file_paths_cost_persistent1 = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - kDummyURL1, kPersistent); + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kPersistent); const int64_t file_paths_cost_temporary2 = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - kDummyURL2, kTemporary); + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL2, kTemporary); const int64_t file_paths_cost_persistent2 = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - kDummyURL2, kPersistent); + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL2, kPersistent); for (int i = 0; i < 2; i++) { EXPECT_EQ(1331 + 134 + file_paths_cost_temporary1, @@ -409,14 +398,14 @@ TEST_F(FileSystemQuotaClientTest, GetUsage_MultipleTasks) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { + const std::vector<TestFile> kFiles = { {true, "", 0, kDummyURL1, kTemporary}, {false, "foo", 11, kDummyURL1, kTemporary}, {false, "bar", 22, kDummyURL1, kTemporary}, }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); - const int64_t file_paths_cost = ComputeFilePathsCostForOriginAndType( - kFiles, base::size(kFiles), kDummyURL1, kTemporary); + InitializeOriginFiles(quota_client, kFiles); + const int64_t file_paths_cost = + ComputeFilePathsCostForOriginAndType(kFiles, kDummyURL1, kTemporary); // Dispatching three GetUsage tasks. set_additional_callback_count(0); @@ -439,12 +428,12 @@ TEST_F(FileSystemQuotaClientTest, GetStorageKeysForType) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { - {true, "", 0, kDummyURL1, kTemporary}, - {true, "", 0, kDummyURL2, kTemporary}, - {true, "", 0, kDummyURL3, kPersistent}, - }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); + InitializeOriginFiles(quota_client, + { + {true, "", 0, kDummyURL1, kTemporary}, + {true, "", 0, kDummyURL2, kTemporary}, + {true, "", 0, kDummyURL3, kPersistent}, + }); std::vector<StorageKey> storage_keys = GetStorageKeysForType(quota_client, kTemporary); @@ -467,12 +456,13 @@ const char* kURL3 = "http://foo.com:1/"; const char* kURL4 = "http://foo2.com/"; const char* kURL5 = "http://foo.com:2/"; - const TestFile kFiles[] = { - {true, "", 0, kURL1, kTemporary}, {true, "", 0, kURL2, kTemporary}, - {true, "", 0, kURL3, kTemporary}, {true, "", 0, kURL4, kTemporary}, - {true, "", 0, kURL5, kPersistent}, - }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); + InitializeOriginFiles(quota_client, { + {true, "", 0, kURL1, kTemporary}, + {true, "", 0, kURL2, kTemporary}, + {true, "", 0, kURL3, kTemporary}, + {true, "", 0, kURL4, kTemporary}, + {true, "", 0, kURL5, kPersistent}, + }); std::vector<StorageKey> storage_keys = GetStorageKeysForHost(quota_client, kTemporary, "foo.com"); @@ -495,7 +485,7 @@ TEST_F(FileSystemQuotaClientTest, DeleteOriginTest) { FileSystemQuotaClient quota_client(GetFileSystemContext()); - const TestFile kFiles[] = { + const std::vector<TestFile> kFiles = { {true, "", 0, "http://foo.com/", kTemporary}, {false, "a", 1, "http://foo.com/", kTemporary}, {true, "", 0, "https://foo.com/", kTemporary}, @@ -511,22 +501,22 @@ {true, "", 0, "https://bar.com/", kTemporary}, {false, "g", 64, "https://bar.com/", kTemporary}, }; - InitializeOriginFiles(quota_client, kFiles, base::size(kFiles)); + InitializeOriginFiles(quota_client, kFiles); const int64_t file_paths_cost_temporary_foo_https = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - "https://foo.com/", kTemporary); + ComputeFilePathsCostForOriginAndType(kFiles, "https://foo.com/", + kTemporary); const int64_t file_paths_cost_persistent_foo = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - "http://foo.com/", kPersistent); + ComputeFilePathsCostForOriginAndType(kFiles, "http://foo.com/", + kPersistent); const int64_t file_paths_cost_temporary_bar = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - "http://bar.com/", kTemporary); + ComputeFilePathsCostForOriginAndType(kFiles, "http://bar.com/", + kTemporary); const int64_t file_paths_cost_temporary_bar_https = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - "https://bar.com/", kTemporary); + ComputeFilePathsCostForOriginAndType(kFiles, "https://bar.com/", + kTemporary); const int64_t file_paths_cost_persistent_bar_https = - ComputeFilePathsCostForOriginAndType(kFiles, base::size(kFiles), - "https://bar.com/", kPersistent); + ComputeFilePathsCostForOriginAndType(kFiles, "https://bar.com/", + kPersistent); DeleteStorageKeyData("a_client, "http://foo.com/", kTemporary); base::RunLoop().RunUntilIdle();
diff --git a/testing/buildbot/chromium.android.fyi.json b/testing/buildbot/chromium.android.fyi.json index 836f656..8c190e4 100644 --- a/testing/buildbot/chromium.android.fyi.json +++ b/testing/buildbot/chromium.android.fyi.json
@@ -9910,6 +9910,424 @@ } ] }, + "android-cronet-x86-dbg-10-tests": { + "gtest_tests": [ + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "cronet_sample_test_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "named_caches": [ + { + "name": "avd_generic_android29", + "path": ".android" + }, + { + "name": "system_images_android_29_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "optional_dimensions": { + "60": [ + { + "caches": "avd_generic_android29" + } + ] + }, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cronet_sample_test_apk", + "test_id_prefix": "ninja://components/cronet/android:cronet_sample_test_apk/" + }, + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "cronet_smoketests_missing_native_library_instrumentation_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "named_caches": [ + { + "name": "avd_generic_android29", + "path": ".android" + }, + { + "name": "system_images_android_29_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "optional_dimensions": { + "60": [ + { + "caches": "avd_generic_android29" + } + ] + }, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cronet_smoketests_missing_native_library_instrumentation_apk", + "test_id_prefix": "ninja://components/cronet/android:cronet_smoketests_missing_native_library_instrumentation_apk/" + }, + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "cronet_smoketests_platform_only_instrumentation_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "named_caches": [ + { + "name": "avd_generic_android29", + "path": ".android" + }, + { + "name": "system_images_android_29_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "optional_dimensions": { + "60": [ + { + "caches": "avd_generic_android29" + } + ] + }, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cronet_smoketests_platform_only_instrumentation_apk", + "test_id_prefix": "ninja://components/cronet/android:cronet_smoketests_platform_only_instrumentation_apk/" + }, + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "cronet_test_instrumentation_apk" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "named_caches": [ + { + "name": "avd_generic_android29", + "path": ".android" + }, + { + "name": "system_images_android_29_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "optional_dimensions": { + "60": [ + { + "caches": "avd_generic_android29" + } + ] + }, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cronet_test_instrumentation_apk", + "test_id_prefix": "ninja://components/cronet/android:cronet_test_instrumentation_apk/" + }, + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "cronet_tests_android" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "named_caches": [ + { + "name": "avd_generic_android29", + "path": ".android" + }, + { + "name": "system_images_android_29_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "optional_dimensions": { + "60": [ + { + "caches": "avd_generic_android29" + } + ] + }, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cronet_tests_android", + "test_id_prefix": "ninja://components/cronet/android:cronet_tests_android/" + }, + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "cronet_unittests_android" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "named_caches": [ + { + "name": "avd_generic_android29", + "path": ".android" + }, + { + "name": "system_images_android_29_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "optional_dimensions": { + "60": [ + { + "caches": "avd_generic_android29" + } + ] + }, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "cronet_unittests_android", + "test_id_prefix": "ninja://components/cronet/android:cronet_unittests_android/" + }, + { + "args": [ + "--gs-results-bucket=chromium-result-details", + "--recover-devices", + "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" + ], + "merge": { + "args": [ + "--bucket", + "chromium-result-details", + "--test-name", + "net_unittests" + ], + "script": "//build/android/pylib/results/presentation/test_results_presentation.py" + }, + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "cipd_packages": [ + { + "cipd_package": "infra/tools/luci/logdog/butler/${platform}", + "location": "bin", + "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" + } + ], + "named_caches": [ + { + "name": "avd_generic_android29", + "path": ".android" + }, + { + "name": "system_images_android_29_google_apis_x86", + "path": ".emulator_sdk" + } + ], + "optional_dimensions": { + "60": [ + { + "caches": "avd_generic_android29" + } + ] + }, + "output_links": [ + { + "link": [ + "https://luci-logdog.appspot.com/v/?s", + "=android%2Fswarming%2Flogcats%2F", + "${TASK_ID}%2F%2B%2Funified_logcats" + ], + "name": "shard #${SHARD_INDEX} logcats" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 4 + }, + "test": "net_unittests", + "test_id_prefix": "ninja://net:net_unittests/" + } + ] + }, "android-pie-arm64-wpt-rel-non-cq": { "isolated_scripts": [ {
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 1cc469bd..6f2f9c7 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -24251,424 +24251,6 @@ } ] }, - "android-cronet-x86-dbg-10-tests": { - "gtest_tests": [ - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "cronet_sample_test_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "named_caches": [ - { - "name": "avd_generic_android29", - "path": ".android" - }, - { - "name": "system_images_android_29_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "avd_generic_android29" - } - ] - }, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cronet_sample_test_apk", - "test_id_prefix": "ninja://components/cronet/android:cronet_sample_test_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "cronet_smoketests_missing_native_library_instrumentation_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "named_caches": [ - { - "name": "avd_generic_android29", - "path": ".android" - }, - { - "name": "system_images_android_29_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "avd_generic_android29" - } - ] - }, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cronet_smoketests_missing_native_library_instrumentation_apk", - "test_id_prefix": "ninja://components/cronet/android:cronet_smoketests_missing_native_library_instrumentation_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "cronet_smoketests_platform_only_instrumentation_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "named_caches": [ - { - "name": "avd_generic_android29", - "path": ".android" - }, - { - "name": "system_images_android_29_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "avd_generic_android29" - } - ] - }, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cronet_smoketests_platform_only_instrumentation_apk", - "test_id_prefix": "ninja://components/cronet/android:cronet_smoketests_platform_only_instrumentation_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "cronet_test_instrumentation_apk" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "named_caches": [ - { - "name": "avd_generic_android29", - "path": ".android" - }, - { - "name": "system_images_android_29_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "avd_generic_android29" - } - ] - }, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cronet_test_instrumentation_apk", - "test_id_prefix": "ninja://components/cronet/android:cronet_test_instrumentation_apk/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "cronet_tests_android" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "named_caches": [ - { - "name": "avd_generic_android29", - "path": ".android" - }, - { - "name": "system_images_android_29_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "avd_generic_android29" - } - ] - }, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cronet_tests_android", - "test_id_prefix": "ninja://components/cronet/android:cronet_tests_android/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "cronet_unittests_android" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "named_caches": [ - { - "name": "avd_generic_android29", - "path": ".android" - }, - { - "name": "system_images_android_29_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "avd_generic_android29" - } - ] - }, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" - }, - "test": "cronet_unittests_android", - "test_id_prefix": "ninja://components/cronet/android:cronet_unittests_android/" - }, - { - "args": [ - "--gs-results-bucket=chromium-result-details", - "--recover-devices", - "--avd-config=../../tools/android/avd/proto/generic_android29.textpb" - ], - "merge": { - "args": [ - "--bucket", - "chromium-result-details", - "--test-name", - "net_unittests" - ], - "script": "//build/android/pylib/results/presentation/test_results_presentation.py" - }, - "resultdb": { - "enable": true - }, - "swarming": { - "can_use_on_swarming_builders": true, - "cipd_packages": [ - { - "cipd_package": "infra/tools/luci/logdog/butler/${platform}", - "location": "bin", - "revision": "git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c" - } - ], - "named_caches": [ - { - "name": "avd_generic_android29", - "path": ".android" - }, - { - "name": "system_images_android_29_google_apis_x86", - "path": ".emulator_sdk" - } - ], - "optional_dimensions": { - "60": [ - { - "caches": "avd_generic_android29" - } - ] - }, - "output_links": [ - { - "link": [ - "https://luci-logdog.appspot.com/v/?s", - "=android%2Fswarming%2Flogcats%2F", - "${TASK_ID}%2F%2B%2Funified_logcats" - ], - "name": "shard #${SHARD_INDEX} logcats" - } - ], - "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", - "shards": 4 - }, - "test": "net_unittests", - "test_id_prefix": "ninja://net:net_unittests/" - } - ] - }, "android-cronet-x86-rel": { "additional_compile_targets": [ "cronet_package",
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 1f787d8..edea87e 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -134,9 +134,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader", "--flag-specific=skia-vulkan-swiftshader" ], "isolate_name": "blink_web_tests", @@ -80455,9 +80453,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader", "--flag-specific=skia-vulkan-swiftshader" ], "isolate_name": "blink_web_tests", @@ -82512,9 +82508,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader", "--flag-specific=skia-vulkan-swiftshader" ], "isolate_name": "blink_web_tests", @@ -84639,9 +84633,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader", "--flag-specific=skia-vulkan-swiftshader" ], "isolate_name": "blink_web_tests",
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index d11b1d31..2f06cac 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -12276,9 +12276,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-gl=any", "--flag-specific=skia-gl" ], "isolate_name": "blink_web_tests", @@ -12358,9 +12356,7 @@ "--skipped=always", "--driver-logging", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=native", "--flag-specific=skia-vulkan-native" ], "isolate_name": "blink_web_tests", @@ -12722,9 +12718,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-gl=any", "--flag-specific=skia-gl" ], "isolate_name": "blink_web_tests", @@ -12804,9 +12798,7 @@ "--skipped=always", "--driver-logging", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=native", "--flag-specific=skia-vulkan-native" ], "isolate_name": "blink_web_tests",
diff --git a/testing/buildbot/chromium.linux.json b/testing/buildbot/chromium.linux.json index edf3d090..1ac8343c 100644 --- a/testing/buildbot/chromium.linux.json +++ b/testing/buildbot/chromium.linux.json
@@ -11702,9 +11702,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader", "--flag-specific=skia-vulkan-swiftshader" ], "isolate_name": "blink_web_tests", @@ -15612,9 +15610,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader", "--flag-specific=skia-vulkan-swiftshader" ], "isolate_name": "blink_web_tests", @@ -17612,9 +17608,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader", "--flag-specific=skia-vulkan-swiftshader" ], "isolate_name": "blink_web_tests", @@ -19596,9 +19590,7 @@ "--fuzzy-diff", "--skipped=always", "--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer", "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization", - "--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader", "--flag-specific=skia-vulkan-swiftshader" ], "isolate_name": "blink_web_tests",
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index 87d3c19..d858c0c8 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -2485,9 +2485,7 @@ '--fuzzy-diff', '--skipped=always', '--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter', - '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer', '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization', - '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-gl=any', '--flag-specific=skia-gl', ], 'isolate_name': 'blink_web_tests', @@ -2516,9 +2514,7 @@ '--skipped=always', '--driver-logging', '--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter', - '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer', '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization', - '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=native', '--flag-specific=skia-vulkan-native', ], 'isolate_name': 'blink_web_tests', @@ -5156,9 +5152,7 @@ '--fuzzy-diff', '--skipped=always', '--test-list=../../testing/buildbot/filters/gpu.skiarenderer_vulkan_blink_web_tests.filter', - '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer', '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization', - '--additional-expectations=../../third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader', '--flag-specific=skia-vulkan-swiftshader', ], 'isolate_name': 'blink_web_tests',
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index b30b3a6..0ccb9ca 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -795,16 +795,6 @@ 'isolated_scripts': 'cronet_dbg_isolated_scripts', }, }, - 'android-cronet-x86-dbg-10-tests': { - 'mixins': [ - 'enable_resultdb', - '10-x86-emulator', - ], - 'test_suites': { - 'gtest_tests': 'cronet_gtests', - }, - 'os_type': 'android', - }, 'android-cronet-x86-rel': { 'additional_compile_targets': [ 'cronet_package', @@ -1075,6 +1065,16 @@ 'gtest_tests': 'android_12_emulator_gtests', } }, + 'android-cronet-x86-dbg-10-tests': { + 'mixins': [ + 'enable_resultdb', + '10-x86-emulator', + ], + 'test_suites': { + 'gtest_tests': 'cronet_gtests', + }, + 'os_type': 'android', + }, 'android-pie-arm64-wpt-rel-non-cq': { 'mixins': [ 'enable_resultdb',
diff --git a/testing/trigger_scripts/base_test_triggerer.py b/testing/trigger_scripts/base_test_triggerer.py index 0d6a53e..eb9acec 100755 --- a/testing/trigger_scripts/base_test_triggerer.py +++ b/testing/trigger_scripts/base_test_triggerer.py
@@ -149,7 +149,6 @@ def list_bots(self, dimensions, - verbose, server='chromium-swarm.appspot.com'): """List bots having specified bot dimensions. @@ -162,8 +161,7 @@ for key in sorted(dimensions): args.extend(['-dimension', '%s=%s' % (key, dimensions[key])]) - if verbose: - logging.info('Running Go `swarming` with args: %s', args) + logging.info('Running Go `swarming` with args: %s', args) with tempfile.NamedTemporaryFile(delete=False) as result_json: result_json.close() @@ -177,7 +175,6 @@ def query_swarming(self, api, query_args, - verbose, limit='0', server='chromium-swarm.appspot.com'): try: @@ -189,7 +186,7 @@ ] # Append the query at the end args.append(('%s?%s' % (api, encoded_args))) - ret = self.run_swarming(args, verbose) + ret = self.run_swarming(args) if ret: raise Exception('Error running swarming.py') return self.read_encoded_json_from_temp_file(temp_file) @@ -223,20 +220,18 @@ with open(output_file, 'w') as f: json.dump(merged_json, f) - def run_swarming(self, args, verbose): - if verbose: - logging.info('Running Swarming with args: %s', args) + def run_swarming(self, args): + logging.info('Running Swarming with args: %s', args) return subprocess.call([sys.executable, SWARMING_PY] + args) def run_swarming_go(self, args, - verbose, json_path, shard_index, shards, merged_json=None): - if verbose: - logging.info('Running Go `swarming` with args: %s', args) + + logging.info('Running Go `swarming` with args: %s', args) if merged_json is None: merged_json = {} @@ -263,12 +258,12 @@ self.write_json_to_file(merged_json, json_path) return ret - def prune_test_specific_configs(self, args, verbose): + def prune_test_specific_configs(self, args): # Ability for base class to further prune configs to # run tests on. pass - def select_config_indices(self, args, verbose): + def select_config_indices(self, args): # Main implementation for base class to determine which bot config to # trigger for each shard. # @@ -284,7 +279,7 @@ else: return [args.shard_index] - def generate_shard_map(self, args, buildername, selected_config, verbose): + def generate_shard_map(self, args, buildername, selected_config): """Returns shard map generated on runtime if needed.""" pass @@ -299,14 +294,17 @@ Returns: Exit code for the script. """ + if args.multiple_dimension_script_verbose: + logging.basicConfig(level=logging.DEBUG) + # crbug/1140389: debug print outs logging.info('DEBUG: init: %s', remaining) - verbose = args.multiple_dimension_script_verbose + self.parse_bot_configs(args) # Prunes config list to the exact set of configurations to trigger jobs # on. This logic is specific to the base class if they want to prune # list further. - self.prune_test_specific_configs(args, verbose) + self.prune_test_specific_configs(args) # In the remaining arguments, find the Swarming dimensions that are # specified by the bot configs and remove them, because for each shard, @@ -321,10 +319,10 @@ logging.info('DEBUG: After filtered: %s', filtered_remaining_args) merged_json = {} - selected_config = self.select_config_indices(args, verbose) + selected_config = self.select_config_indices(args) shard_map = self.generate_shard_map( args, self._findBuilderName(filtered_remaining_args), - selected_config, verbose) + selected_config) # Choose selected configs for this run of the test suite. for shard_index, bot_index in selected_config: # For each shard that we're going to distribute, do the following: @@ -345,7 +343,7 @@ # crbug/1140389: debug print outs logging.info('DEBUG: Before calling swarming: %s', args_to_pass) - ret = self.run_swarming_go(args_to_pass, verbose, json_temp, + ret = self.run_swarming_go(args_to_pass, json_temp, shard_index, args.shards, merged_json) if ret:
diff --git a/testing/trigger_scripts/perf_device_trigger.py b/testing/trigger_scripts/perf_device_trigger.py index bd96eec..e9a8efbd 100755 --- a/testing/trigger_scripts/perf_device_trigger.py +++ b/testing/trigger_scripts/perf_device_trigger.py
@@ -106,15 +106,17 @@ self._query_swarming_for_eligible_bot_configs( self._dimensions)) - def generate_shard_map(self, args, buildername, selected_config, verbose): + if args.multiple_dimension_script_verbose: + logging.basicConfig(level=logging.DEBUG) + + def generate_shard_map(self, args, buildername, selected_config): shard_map = None num_of_shards = len(selected_config) builder = bot_platforms.find_bot_platform(buildername) if args.use_dynamic_shards and builder and num_of_shards: - if verbose: - print( - 'Generating dynamic shardmap for builder: %s with %d shards' - % (buildername, num_of_shards)) + logging.info( + 'Generating dynamic shardmap for builder: %s with %d shards', + buildername, num_of_shards) shard_map = generate_perf_sharding.GenerateShardMap( builder=builder, num_of_shards=num_of_shards) for shard_index, bot_index in selected_config: @@ -145,7 +147,7 @@ for _, bot in self._eligible_bots_by_ids.iteritems(): self._bot_configs.append(bot.as_json_config()) - def select_config_indices(self, args, verbose): + def select_config_indices(self, args): if args.multiple_trigger_configs: configs = [] # If specific bot ids were passed in, we want to trigger a job for @@ -154,10 +156,10 @@ for index in range(len(self.indices_to_trigger(args))): configs.append((index, index)) if args.use_dynamic_shards: - return self._select_config_indices_with_dynamic_sharding(verbose) - return self._select_config_indices_with_soft_affinity(args, verbose) + return self._select_config_indices_with_dynamic_sharding() + return self._select_config_indices_with_soft_affinity(args) - def _select_config_indices_with_dynamic_sharding(self, verbose): + def _select_config_indices_with_dynamic_sharding(self): alive_bot_ids = [ bot_id for bot_id, b in self._eligible_bots_by_ids.iteritems() if b.is_alive() @@ -171,22 +173,20 @@ for i in range(trigger_count)] selected_config.sort() - if verbose: - for shard_index, bot_index in selected_config: - print('Shard %d\n\tBot: %s' % - (shard_index, self._bot_configs[bot_index]['id'])) + for shard_index, bot_index in selected_config: + logging.info('Shard %d\n\tBot: %s', shard_index, + self._bot_configs[bot_index]['id']) return selected_config - def _select_config_indices_with_soft_affinity(self, args, verbose): + def _select_config_indices_with_soft_affinity(self, args): trigger_count = len(self.indices_to_trigger(args)) # First make sure the number of shards doesn't exceed the # number of eligible bots. This means there is a config error somewhere. if trigger_count > len(self._eligible_bots_by_ids): - if verbose: - self._print_device_affinity_info({}, {}, - self._eligible_bots_by_ids, - trigger_count) + self._print_device_affinity_info({}, {}, + self._eligible_bots_by_ids, + trigger_count) raise ValueError( 'Not enough available machines exist in swarming ' 'pool. Shards requested (%d) exceeds available bots ' @@ -222,9 +222,8 @@ if not bot and unallocated_healthy_bots: shard_to_bot_assignment_map[shard_index] = \ unallocated_healthy_bots.pop() - if verbose: - print('First time shard %d has been triggered' % - shard_index) + logging.info('First time shard %d has been triggered', + shard_index) elif not bot: shard_to_bot_assignment_map[ shard_index] = unallocated_bad_bots.pop() @@ -236,11 +235,10 @@ dead_bot = bot healthy_bot = unallocated_healthy_bots.pop() shard_to_bot_assignment_map[shard_index] = healthy_bot - if verbose: - print( - 'Device affinity broken for shard #%d. bot %s is dead,' - ' new mapping to bot %s' % - (shard_index, dead_bot.id(), healthy_bot.id())) + logging.info( + 'Device affinity broken for shard #%d. bot %s is dead,' + ' new mapping to bot %s', shard_index, dead_bot.id(), + healthy_bot.id()) # Now populate the indices into the bot_configs array selected_configs = [] @@ -249,16 +247,15 @@ (shard_index, self._find_bot_config_index( shard_to_bot_assignment_map[shard_index].id()))) - if verbose: - self._print_device_affinity_info(shard_to_bot_assignment_map, - existing_shard_bot_to_shard_map, - self._eligible_bots_by_ids, - trigger_count) + self._print_device_affinity_info(shard_to_bot_assignment_map, + existing_shard_bot_to_shard_map, + self._eligible_bots_by_ids, + trigger_count) return selected_configs def _print_device_affinity_info(self, new_map, existing_map, health_map, num_shards): - print() + logging.info('') for shard_index in xrange(num_shards): existing = existing_map.get(shard_index, None) new = new_map.get(shard_index, None) @@ -268,8 +265,8 @@ new_id = '' if new: new_id = new.id() - print('Shard %d\n\tprevious: %s\n\tnew: %s' % - (shard_index, existing_id, new_id)) + logging.info('Shard %d\n\tprevious: %s\n\tnew: %s', shard_index, + existing_id, new_id) healthy_bots = [] dead_bots = [] @@ -278,12 +275,12 @@ healthy_bots.append(b.id()) else: dead_bots.append(b.id()) - print('Shards needed: %d' % num_shards) - print('Total bots (dead + healthy): %d' % - (len(dead_bots) + len(healthy_bots))) - print('Healthy bots, %d: %s' % (len(healthy_bots), healthy_bots)) - print('Dead Bots, %d: %s' % (len(dead_bots), dead_bots)) - print() + logging.info('Shards needed: %d', num_shards) + logging.info('Total bots (dead + healthy): %d', + len(dead_bots) + len(healthy_bots)) + logging.info('Healthy bots, %d: %s', len(healthy_bots), healthy_bots) + logging.info('Dead Bots, %d: %s', len(dead_bots), dead_bots) + logging.info('') def _query_swarming_for_eligible_bot_configs(self, dimensions): """Query Swarming to figure out which bots are available. @@ -294,7 +291,6 @@ """ query_result = self.list_bots(dimensions, - True, server=self._swarming_server) perf_bots = {} for bot in query_result: @@ -346,7 +342,6 @@ query_result = self.query_swarming( 'tasks/list', values_with_shard, - True, limit='1', server=self._swarming_server) except Exception: @@ -354,7 +349,6 @@ if self._sharded_query_failed: query_result = self.query_swarming('tasks/list', values, - True, limit='1', server=self._swarming_server)
diff --git a/testing/trigger_scripts/perf_device_trigger_unittest.py b/testing/trigger_scripts/perf_device_trigger_unittest.py index 115e0e2..87718b5 100755 --- a/testing/trigger_scripts/perf_device_trigger_unittest.py +++ b/testing/trigger_scripts/perf_device_trigger_unittest.py
@@ -51,23 +51,20 @@ def list_bots(self, dimensions, - verbose, server='chromium-swarm.appspot.com'): return self._list_bots_result - def run_swarming(self, args, verbose): - del verbose #unused + def run_swarming(self, args): self._swarming_runs.append(args) def run_swarming_go(self, args, - verbose, _json_path, _shard_index, _shard, _merged_json=None): self._triggered_with_swarming_go += 1 - self.run_swarming(args, verbose) + self.run_swarming(args) class UnitTest(unittest.TestCase):
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 7f3f0253..cf5227f 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -3858,6 +3858,24 @@ ] } ], + "GroupAutoCreationAndroid": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "params": { + "enable_tab_group_auto_creation": "false" + }, + "enable_features": [ + "TabGridLayoutAndroid" + ] + } + ] + } + ], "GwpAsanAndroid": [ { "platforms": [
diff --git a/third_party/.gitignore b/third_party/.gitignore index e3900cce..ed18f8d 100644 --- a/third_party/.gitignore +++ b/third_party/.gitignore
@@ -7,6 +7,8 @@ /adobe/flash/symbols /aemu-linux-arm64 /aemu-linux-x64 +/aemu-mac-arm64 +/aemu-mac-x64 /amd/ /android_build_tools/aapt2/aapt2 /android_build_tools/aapt2/lib64/*.so
diff --git a/third_party/blink/common/switches.cc b/third_party/blink/common/switches.cc index b0fefa7..688a75e 100644 --- a/third_party/blink/common/switches.cc +++ b/third_party/blink/common/switches.cc
@@ -126,13 +126,5 @@ // the platform default is used. const char kTouchTextSelectionStrategy[] = "touch-selection-strategy"; -// Used to communicate managed policy for the UserAgentClientHint feature. -// This feature is typically controlled by base::Feature (see -// renderer/platform/scheduler/common/features.*) but requires an enterprise -// policy override. - -extern const char kUserAgentClientHintDisable[] = - "user-agent-client-hint-disable"; - } // namespace switches } // namespace blink
diff --git a/third_party/blink/public/common/switches.h b/third_party/blink/public/common/switches.h index 8c4c2a46..680cb47 100644 --- a/third_party/blink/public/common/switches.h +++ b/third_party/blink/public/common/switches.h
@@ -47,7 +47,6 @@ BLINK_COMMON_EXPORT extern const char kShowPaintRects[]; BLINK_COMMON_EXPORT extern const char kTouchTextSelectionStrategy[]; -BLINK_COMMON_EXPORT extern const char kUserAgentClientHintDisable[]; } // namespace switches } // namespace blink
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index 385078b..99d90b8f 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -65,6 +65,7 @@ "fetch/fetch_api_request.mojom", "fetch/fetch_api_response.mojom", "file/file_utilities.mojom", + "file_system_access/file_system_access_access_handle_host.mojom", "file_system_access/file_system_access_data_transfer_token.mojom", "file_system_access/file_system_access_directory_handle.mojom", "file_system_access/file_system_access_error.mojom",
diff --git a/third_party/blink/public/mojom/file_system_access/file_system_access_access_handle_host.mojom b/third_party/blink/public/mojom/file_system_access/file_system_access_access_handle_host.mojom new file mode 100644 index 0000000..1caaf94 --- /dev/null +++ b/third_party/blink/public/mojom/file_system_access/file_system_access_access_handle_host.mojom
@@ -0,0 +1,29 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module blink.mojom; + +// Exclusive lock for an AccessHandle created by the renderer. +// +// The interface is consumed by Blink in the renderer process. The interface is +// currently implemented in the browser process, and will eventually move to the +// Storage Service. +// +// This interface currently serves as a lock. The renderer gets exclusive access +// to the associated file while it keeps this interface's mojo pipe open. +interface FileSystemAccessAccessHandleHost { + // Promises to the browser that the file and AccessHandle were closed. This + // allows the browser to release the exclusive write lock held on the owning + // FileSystemFileHandle. + // + // Well-behaved renderers will call this method after closing the associated + // file descriptor received by the + // FileSystemAccessFileHandle.OpenAccessHandle(). + // + // A compromised renderer may lie and call this method without closing its + // corresponding file descriptor. This may allow it to observe writes from + // other renderers to the same (origin-scoped) file, so no cross-origin data + // would be leaked. + Close() => (); +};
diff --git a/third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom b/third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom index db9f4f0..8cfa1bd3 100644 --- a/third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom +++ b/third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom
@@ -8,6 +8,7 @@ import "mojo/public/mojom/base/file.mojom"; import "third_party/blink/public/mojom/blob/blob.mojom"; import "third_party/blink/public/mojom/blob/serialized_blob.mojom"; +import "third_party/blink/public/mojom/file_system_access/file_system_access_access_handle_host.mojom"; import "third_party/blink/public/mojom/file_system_access/file_system_access_error.mojom"; import "third_party/blink/public/mojom/file_system_access/file_system_access_file_writer.mojom"; import "third_party/blink/public/mojom/file_system_access/file_system_access_transfer_token.mojom"; @@ -46,10 +47,10 @@ // Returns an error if the file does not exist. Remove() => (FileSystemAccessError result); - // TODO(fivedots): Change the return type to a host object once the access - // handle locking implementation is clearer. - // Returns a file object which can be used initiate file operations from the renderer. - OpenAccessHandle() => (FileSystemAccessError result, FileSystemAccessAccessHandleFile? file); + // Returns a file object and an access handle host. The file can be used to + // initiate file operations from the renderer. The access handle host acts as + // an exclusive write lock while the mojo pipe remains open. + OpenAccessHandle() => (FileSystemAccessError result, FileSystemAccessAccessHandleFile? file, pending_remote<FileSystemAccessAccessHandleHost>? access_handle_host); // Returns true if |other| represents the same file on disk as this handle. IsSameEntry(pending_remote<FileSystemAccessTransferToken> other) =>
diff --git a/third_party/blink/renderer/bindings/bindings.gni b/third_party/blink/renderer/bindings/bindings.gni index 240500b..0964a07 100644 --- a/third_party/blink/renderer/bindings/bindings.gni +++ b/third_party/blink/renderer/bindings/bindings.gni
@@ -130,8 +130,6 @@ "core/v8/v8_code_cache.h", "core/v8/v8_context_snapshot.cc", "core/v8/v8_context_snapshot.h", - "core/v8/v8_dom_configuration.cc", - "core/v8/v8_dom_configuration.h", "core/v8/v8_embedder_graph_builder.cc", "core/v8/v8_embedder_graph_builder.h", "core/v8/v8_event_listener_info.h",
diff --git a/third_party/blink/renderer/bindings/core/v8/custom_wrappable_adapter.cc b/third_party/blink/renderer/bindings/core/v8/custom_wrappable_adapter.cc index 1ab638f..58c9172 100644 --- a/third_party/blink/renderer/bindings/core/v8/custom_wrappable_adapter.cc +++ b/third_party/blink/renderer/bindings/core/v8/custom_wrappable_adapter.cc
@@ -4,7 +4,7 @@ #include "third_party/blink/renderer/bindings/core/v8/custom_wrappable_adapter.h" -#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h" +#include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h" #include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h" @@ -15,7 +15,7 @@ void InstallCustomWrappableTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world, - v8::Local<v8::Template> v8_template); + v8::Local<v8::Template> interface_template); const WrapperTypeInfo custom_wrappable_info = { gin::kEmbedderBlink, @@ -29,13 +29,21 @@ WrapperTypeInfo::kCustomWrappableKind, }; -void InstallCustomWrappableTemplate(v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::Template> v8_template) { - V8DOMConfiguration::InitializeDOMInterfaceTemplate( - isolate, v8_template.As<v8::FunctionTemplate>(), - custom_wrappable_info.interface_name, v8::Local<v8::FunctionTemplate>(), - kV8DefaultWrapperInternalFieldCount); +void InstallCustomWrappableTemplate( + v8::Isolate* isolate, + const DOMWrapperWorld& world, + v8::Local<v8::Template> interface_template) { + v8::Local<v8::FunctionTemplate> interface_function_template = + interface_template.As<v8::FunctionTemplate>(); + v8::Local<v8::ObjectTemplate> instance_object_template = + interface_function_template->InstanceTemplate(); + v8::Local<v8::ObjectTemplate> prototype_object_template = + interface_function_template->PrototypeTemplate(); + v8::Local<v8::FunctionTemplate> parent_interface_template; + bindings::SetupIDLInterfaceTemplate( + isolate, &custom_wrappable_info, instance_object_template, + prototype_object_template, interface_function_template, + parent_interface_template); } } // namespace
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.cc b/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.cc deleted file mode 100644 index 54ed4ad..0000000 --- a/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.cc +++ /dev/null
@@ -1,922 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h" - -#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h" -#include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h" -#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" -#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" - -namespace blink { - -namespace { - -template <class Configuration> -bool WorldConfigurationApplies(const Configuration& config, - const DOMWrapperWorld& world) { - const auto current_world_config = world.IsMainWorld() - ? V8DOMConfiguration::kMainWorld - : V8DOMConfiguration::kNonMainWorlds; - return config.world_configuration & current_world_config; -} - -template <> -bool WorldConfigurationApplies( - const V8DOMConfiguration::SymbolKeyedMethodConfiguration&, - const DOMWrapperWorld&) { - return true; -} - -void DoInstallAttribute( - v8::Local<v8::ObjectTemplate> object_template, - v8::Local<v8::Name> name, - const V8DOMConfiguration::AttributeConfiguration& attribute) { - v8::SideEffectType getter_side_effect_type = - attribute.getter_side_effect_type == V8DOMConfiguration::kHasNoSideEffect - ? v8::SideEffectType::kHasNoSideEffect - : v8::SideEffectType::kHasSideEffect; - switch (static_cast<V8DOMConfiguration::AttributeGetterBehavior>( - attribute.getter_behavior)) { - case V8DOMConfiguration::kAlwaysCallGetter: - object_template->SetNativeDataProperty( - name, attribute.getter, attribute.setter, v8::Local<v8::Value>(), - static_cast<v8::PropertyAttribute>(attribute.attribute), - v8::Local<v8::AccessorSignature>(), v8::AccessControl::DEFAULT, - getter_side_effect_type); - break; - case V8DOMConfiguration::kReplaceWithDataProperty: - DCHECK(!attribute.setter); - DCHECK_EQ(attribute.world_configuration, V8DOMConfiguration::kAllWorlds); - object_template->SetLazyDataProperty( - name, attribute.getter, v8::Local<v8::Value>(), - static_cast<v8::PropertyAttribute>(attribute.attribute), - getter_side_effect_type); - break; - } -} - -void DoInstallAttribute( - v8::Local<v8::Context> context, - v8::Local<v8::Object> object, - v8::Local<v8::Name> name, - const V8DOMConfiguration::AttributeConfiguration& attribute) { - v8::SideEffectType getter_side_effect_type = - attribute.getter_side_effect_type == V8DOMConfiguration::kHasNoSideEffect - ? v8::SideEffectType::kHasNoSideEffect - : v8::SideEffectType::kHasSideEffect; - switch (static_cast<V8DOMConfiguration::AttributeGetterBehavior>( - attribute.getter_behavior)) { - case V8DOMConfiguration::kAlwaysCallGetter: - object - ->SetNativeDataProperty( - context, name, attribute.getter, attribute.setter, - v8::Local<v8::Value>(), - static_cast<v8::PropertyAttribute>(attribute.attribute), - getter_side_effect_type) - .ToChecked(); - break; - case V8DOMConfiguration::kReplaceWithDataProperty: - DCHECK(!attribute.setter); - DCHECK_EQ(attribute.world_configuration, V8DOMConfiguration::kAllWorlds); - object - ->SetLazyDataProperty( - context, name, attribute.getter, v8::Local<v8::Value>(), - static_cast<v8::PropertyAttribute>(attribute.attribute), - getter_side_effect_type) - .ToChecked(); - break; - } -} - -void InstallAttributeInternal( - v8::Isolate* isolate, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const V8DOMConfiguration::AttributeConfiguration& attribute, - const DOMWrapperWorld& world) { - if (!WorldConfigurationApplies(attribute, world)) - return; - - v8::Local<v8::Name> name = V8AtomicString(isolate, attribute.name); - const unsigned location = attribute.property_location_configuration; - DCHECK(location); - if (location & V8DOMConfiguration::kOnInstance) - DoInstallAttribute(instance_template, name, attribute); - if (location & V8DOMConfiguration::kOnPrototype) - DoInstallAttribute(prototype_template, name, attribute); - if (location & V8DOMConfiguration::kOnInterface) - NOTREACHED(); -} - -void InstallAttributeInternal( - v8::Isolate* isolate, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - const V8DOMConfiguration::AttributeConfiguration& config, - const DOMWrapperWorld& world) { - DCHECK(!instance.IsEmpty() || !prototype.IsEmpty()); - if (!WorldConfigurationApplies(config, world)) - return; - - v8::Local<v8::Name> name = V8AtomicString(isolate, config.name); - const unsigned location = config.property_location_configuration; - DCHECK(location); - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - if (location & V8DOMConfiguration::kOnInstance && !instance.IsEmpty()) - DoInstallAttribute(context, instance, name, config); - if (location & V8DOMConfiguration::kOnPrototype && !prototype.IsEmpty()) - DoInstallAttribute(context, prototype, name, config); - if (location & V8DOMConfiguration::kOnInterface) - NOTREACHED(); -} - -enum class AccessorType { - Getter, - Setter, -}; - -template <class FunctionOrTemplate> -v8::Local<FunctionOrTemplate> CreateAccessorFunctionOrTemplate( - v8::Isolate*, - v8::FunctionCallback, - V8PrivateProperty::CachedAccessor, - v8::Local<v8::Value> data, - v8::Local<v8::Signature>, - const char* name, - AccessorType, - V8DOMConfiguration::AccessCheckConfiguration access_check_configuration, - v8::SideEffectType side_effect_type = v8::SideEffectType::kHasSideEffect); - -template <> -v8::Local<v8::FunctionTemplate> -CreateAccessorFunctionOrTemplate<v8::FunctionTemplate>( - v8::Isolate* isolate, - v8::FunctionCallback callback, - V8PrivateProperty::CachedAccessor cached_property_key, - v8::Local<v8::Value> data, - v8::Local<v8::Signature> signature, - const char* name, - AccessorType type, - V8DOMConfiguration::AccessCheckConfiguration access_check_configuration, - v8::SideEffectType side_effect_type) { - v8::Local<v8::FunctionTemplate> function_template; - if (callback) { - // https://heycam.github.io/webidl/#dfn-attribute-getter has: - // - // 5. Perform ! SetFunctionLength(|F|, 0). - // - // https://heycam.github.io/webidl/#dfn-attribute-setter has: - // - // 7. Perform ! SetFunctionLength(|F|, 1). - int length = type == AccessorType::Getter ? 0 : 1; - - if (cached_property_key != V8PrivateProperty::CachedAccessor::kNone) { - function_template = v8::FunctionTemplate::NewWithCache( - isolate, callback, - V8PrivateProperty::GetCachedAccessor(isolate, cached_property_key) - .GetPrivate(), - data, signature, length, side_effect_type); - } else { - function_template = v8::FunctionTemplate::New( - isolate, callback, data, signature, length, - v8::ConstructorBehavior::kThrow, side_effect_type); - } - - if (!function_template.IsEmpty()) { - function_template->SetAcceptAnyReceiver( - access_check_configuration == V8DOMConfiguration::kDoNotCheckAccess); - - // https://heycam.github.io/webidl/#dfn-attribute-getter has: - // - // 3. Let |name| be the string "get " prepended to |attribute|’s - // identifier. - // - // 4. Perform ! SetFunctionName(|F|, |name|). - // - // https://heycam.github.io/webidl/#dfn-attribute-setter has: - // - // 5. Let |name| be the string "set " prepended to |id|. - // - // 6. Perform ! SetFunctionName(|F|, |name|). - // - // SetClassName on a FunctionTemplate that doesn't have a prototype just - // sets the .name property of the generated function. - WTF::StringBuilder full_name_builder; - full_name_builder.Append(type == AccessorType::Getter ? "get " : "set ", - 4); - full_name_builder.Append(name); - function_template->SetClassName( - V8AtomicString(isolate, full_name_builder.ToString())); - } - } - return function_template; -} - -template <> -v8::Local<v8::Function> CreateAccessorFunctionOrTemplate<v8::Function>( - v8::Isolate* isolate, - v8::FunctionCallback callback, - V8PrivateProperty::CachedAccessor, - v8::Local<v8::Value> data, - v8::Local<v8::Signature> signature, - const char* name, - AccessorType type, - V8DOMConfiguration::AccessCheckConfiguration access_check_configuration, - v8::SideEffectType side_effect_type) { - if (!callback) - return v8::Local<v8::Function>(); - - v8::Local<v8::FunctionTemplate> function_template = - CreateAccessorFunctionOrTemplate<v8::FunctionTemplate>( - isolate, callback, V8PrivateProperty::CachedAccessor::kNone, data, - signature, name, type, access_check_configuration, side_effect_type); - if (function_template.IsEmpty()) - return v8::Local<v8::Function>(); - - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Function> function; - if (!function_template->GetFunction(context).ToLocal(&function)) - return v8::Local<v8::Function>(); - return function; -} - -// Returns true iff |target| is the empty handle to v8::Object. -// Returns false especially when |target| is a handle to v8::ObjectTemplate. -bool IsObjectAndEmpty(v8::Local<v8::Object> target) { - return target.IsEmpty(); -} - -bool IsObjectAndEmpty(v8::Local<v8::Function> target) { - return target.IsEmpty(); -} - -bool IsObjectAndEmpty(v8::Local<v8::ObjectTemplate> target) { - return false; -} - -bool IsObjectAndEmpty(v8::Local<v8::FunctionTemplate> target) { - return false; -} - -template <class ObjectOrTemplate, class FunctionOrTemplate> -void InstallAccessorInternal( - v8::Isolate* isolate, - v8::Local<ObjectOrTemplate> instance_or_template, - v8::Local<ObjectOrTemplate> prototype_or_template, - v8::Local<FunctionOrTemplate> interface_or_template, - v8::Local<v8::Signature> signature, - const V8DOMConfiguration::AccessorConfiguration& config, - const DOMWrapperWorld& world) { - DCHECK(!IsObjectAndEmpty(instance_or_template) || - !IsObjectAndEmpty(prototype_or_template) || - !IsObjectAndEmpty(interface_or_template)); - if (!WorldConfigurationApplies(config, world)) - return; - - v8::Local<v8::String> name = V8AtomicString(isolate, config.name); - v8::FunctionCallback getter_callback = config.getter; - v8::FunctionCallback setter_callback = config.setter; - auto cached_property_key = V8PrivateProperty::CachedAccessor::kNone; - bool is_window_document = static_cast<V8PrivateProperty::CachedAccessor>( - config.cached_property_key) == - V8PrivateProperty::CachedAccessor::kWindowDocument; - if (!is_window_document || world.IsMainWorld()) { - cached_property_key = static_cast<V8PrivateProperty::CachedAccessor>( - config.cached_property_key); - } - - // Support [LegacyLenientThis] and attributes with Promise types by not - // specifying the signature. V8 does not do the type checking against holder - // if no signature is specified. Note that info.Holder() passed to callbacks - // will be *unsafe*. - if (config.holder_check_configuration == - V8DOMConfiguration::kDoNotCheckHolder) - signature = v8::Local<v8::Signature>(); - - V8DOMConfiguration::AccessCheckConfiguration getter_access_check = - static_cast<V8DOMConfiguration::AccessCheckConfiguration>( - config.getter_access_check_configuration); - V8DOMConfiguration::AccessCheckConfiguration setter_access_check = - static_cast<V8DOMConfiguration::AccessCheckConfiguration>( - config.setter_access_check_configuration); - - const unsigned location = config.property_location_configuration; - v8::SideEffectType getter_side_effect_type = - config.getter_side_effect_type == V8DOMConfiguration::kHasNoSideEffect - ? v8::SideEffectType::kHasNoSideEffect - : v8::SideEffectType::kHasSideEffect; - DCHECK(location); - if (location & - (V8DOMConfiguration::kOnInstance | V8DOMConfiguration::kOnPrototype)) { - v8::Local<FunctionOrTemplate> getter = - CreateAccessorFunctionOrTemplate<FunctionOrTemplate>( - isolate, getter_callback, cached_property_key, - v8::Local<v8::Value>(), signature, config.name, - AccessorType::Getter, getter_access_check, getter_side_effect_type); - v8::Local<FunctionOrTemplate> setter = - CreateAccessorFunctionOrTemplate<FunctionOrTemplate>( - isolate, setter_callback, V8PrivateProperty::CachedAccessor::kNone, - v8::Local<v8::Value>(), signature, config.name, - AccessorType::Setter, setter_access_check); - if (location & V8DOMConfiguration::kOnInstance && - !IsObjectAndEmpty(instance_or_template)) { - instance_or_template->SetAccessorProperty( - name, getter, setter, - static_cast<v8::PropertyAttribute>(config.attribute)); - } - if (location & V8DOMConfiguration::kOnPrototype && - !IsObjectAndEmpty(prototype_or_template)) { - prototype_or_template->SetAccessorProperty( - name, getter, setter, - static_cast<v8::PropertyAttribute>(config.attribute)); - } - } - if (location & V8DOMConfiguration::kOnInterface && - !IsObjectAndEmpty(interface_or_template)) { - // Attributes installed on the interface object must be static - // attributes, so no need to specify a signature, i.e. no need to do - // type check against a holder. - v8::Local<FunctionOrTemplate> getter = - CreateAccessorFunctionOrTemplate<FunctionOrTemplate>( - isolate, getter_callback, V8PrivateProperty::CachedAccessor::kNone, - v8::Local<v8::Value>(), v8::Local<v8::Signature>(), config.name, - AccessorType::Getter, getter_access_check, getter_side_effect_type); - v8::Local<FunctionOrTemplate> setter = - CreateAccessorFunctionOrTemplate<FunctionOrTemplate>( - isolate, setter_callback, V8PrivateProperty::CachedAccessor::kNone, - v8::Local<v8::Value>(), v8::Local<v8::Signature>(), config.name, - AccessorType::Setter, setter_access_check); - interface_or_template->SetAccessorProperty( - name, getter, setter, - static_cast<v8::PropertyAttribute>(config.attribute)); - } -} - -v8::Local<v8::Primitive> ValueForConstant( - v8::Isolate* isolate, - const V8DOMConfiguration::ConstantConfiguration& constant) { - v8::Local<v8::Primitive> value; - switch (constant.type) { - case V8DOMConfiguration::kConstantTypeShort: - case V8DOMConfiguration::kConstantTypeLong: - case V8DOMConfiguration::kConstantTypeUnsignedShort: - value = v8::Integer::New(isolate, constant.ivalue); - break; - case V8DOMConfiguration::kConstantTypeUnsignedLong: - value = v8::Integer::NewFromUnsigned(isolate, constant.ivalue); - break; - case V8DOMConfiguration::kConstantTypeFloat: - case V8DOMConfiguration::kConstantTypeDouble: - value = v8::Number::New(isolate, constant.dvalue); - break; - default: - NOTREACHED(); - } - return value; -} - -void InstallConstantInternal( - v8::Isolate* isolate, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const V8DOMConfiguration::ConstantConfiguration& constant) { - v8::Local<v8::String> constant_name = V8AtomicString(isolate, constant.name); - v8::PropertyAttribute attributes = - static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); - v8::Local<v8::Primitive> value = ValueForConstant(isolate, constant); - interface_template->Set(constant_name, value, attributes); - prototype_template->Set(constant_name, value, attributes); -} - -void InstallConstantInternal( - v8::Isolate* isolate, - v8::Local<v8::Function> interface, - v8::Local<v8::Object> prototype, - const V8DOMConfiguration::ConstantConfiguration& constant) { - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - v8::Local<v8::Name> name = V8AtomicString(isolate, constant.name); - v8::PropertyAttribute attributes = - static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); - v8::Local<v8::Primitive> value = ValueForConstant(isolate, constant); - interface->DefineOwnProperty(context, name, value, attributes).ToChecked(); - prototype->DefineOwnProperty(context, name, value, attributes).ToChecked(); -} - -template <class Configuration> -void AddMethodToTemplate(v8::Isolate* isolate, - v8::Local<v8::Template> v8_template, - v8::Local<v8::FunctionTemplate> function_template, - const Configuration& method) { - v8_template->Set(method.MethodName(isolate), function_template, - static_cast<v8::PropertyAttribute>(method.attribute)); -} - -template <> -void AddMethodToTemplate( - v8::Isolate* isolate, - v8::Local<v8::Template> v8_template, - v8::Local<v8::FunctionTemplate> function_template, - const V8DOMConfiguration::SymbolKeyedMethodConfiguration& method) { - // The order matters here: if the Symbol is added first, the Function object - // will have no associated name. For example, WebIDL states, among other - // things, that a pair iterator's @@iterator Function object's name must be - // set to "entries". - if (method.symbol_alias) { - v8_template->Set(V8AtomicString(isolate, method.symbol_alias), - function_template); - } - v8_template->Set(method.MethodName(isolate), function_template, - static_cast<v8::PropertyAttribute>(method.attribute)); -} - -template <class Configuration> -void InstallMethodInternal(v8::Isolate* isolate, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature> signature, - const Configuration& method, - const DOMWrapperWorld& world, - const v8::CFunction* v8_c_function = nullptr) { - if (!WorldConfigurationApplies(method, world)) - return; - - v8::FunctionCallback callback = method.callback; - // Promise-returning functions need to return a reject promise when - // an exception occurs. This includes a case that the receiver object is not - // of the type. So, we disable the type check of the receiver object on V8 - // side so that V8 won't throw. Instead, we do the check on Blink side and - // convert an exception to a reject promise. - if (method.holder_check_configuration == - V8DOMConfiguration::kDoNotCheckHolder) - signature = v8::Local<v8::Signature>(); - - DCHECK(method.property_location_configuration); - v8::SideEffectType side_effect_type = - method.side_effect_type == V8DOMConfiguration::kHasNoSideEffect - ? v8::SideEffectType::kHasNoSideEffect - : v8::SideEffectType::kHasSideEffect; - if (method.property_location_configuration & - (V8DOMConfiguration::kOnInstance | V8DOMConfiguration::kOnPrototype)) { - v8::Local<v8::FunctionTemplate> function_template = - v8::FunctionTemplate::New( - isolate, callback, v8::Local<v8::Value>(), signature, method.length, - v8::ConstructorBehavior::kThrow, side_effect_type, v8_c_function); - function_template->SetAcceptAnyReceiver( - method.access_check_configuration == - V8DOMConfiguration::kDoNotCheckAccess); - if (method.property_location_configuration & - V8DOMConfiguration::kOnInstance) { - AddMethodToTemplate(isolate, instance_template, function_template, - method); - } - if (method.property_location_configuration & - V8DOMConfiguration::kOnPrototype) { - AddMethodToTemplate(isolate, prototype_template, function_template, - method); - } - } - if (method.property_location_configuration & - V8DOMConfiguration::kOnInterface) { - // Operations installed on the interface object must be static methods, so - // no need to specify a signature, i.e. no need to do type check against a - // holder. - v8::Local<v8::FunctionTemplate> function_template = - v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), - v8::Local<v8::Signature>(), method.length, - v8::ConstructorBehavior::kThrow, - side_effect_type); - // Similarly, there is no need to do an access check for static methods, as - // there is no holder to check against. - AddMethodToTemplate(isolate, interface_template, function_template, method); - } -} - -void InstallMethodInternal( - v8::Isolate* isolate, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature> signature, - const V8DOMConfiguration::MethodConfiguration& config, - const DOMWrapperWorld& world) { - DCHECK(!instance.IsEmpty() || !prototype.IsEmpty() || !interface.IsEmpty()); - if (!WorldConfigurationApplies(config, world)) - return; - - v8::Local<v8::String> name = config.MethodName(isolate); - v8::FunctionCallback callback = config.callback; - // Promise-returning functions need to return a reject promise when - // an exception occurs. This includes a case that the receiver object is not - // of the type. So, we disable the type check of the receiver object on V8 - // side so that V8 won't throw. Instead, we do the check on Blink side and - // convert an exception to a reject promise. - if (config.holder_check_configuration == - V8DOMConfiguration::kDoNotCheckHolder) - signature = v8::Local<v8::Signature>(); - - const unsigned location = config.property_location_configuration; - v8::SideEffectType side_effect_type = - config.side_effect_type == V8DOMConfiguration::kHasNoSideEffect - ? v8::SideEffectType::kHasNoSideEffect - : v8::SideEffectType::kHasSideEffect; - DCHECK(location); - if (location & - (V8DOMConfiguration::kOnInstance | V8DOMConfiguration::kOnPrototype)) { - v8::Local<v8::FunctionTemplate> function_template = - v8::FunctionTemplate::New( - isolate, callback, v8::Local<v8::Value>(), signature, config.length, - v8::ConstructorBehavior::kThrow, side_effect_type); - function_template->SetAcceptAnyReceiver( - config.access_check_configuration == - V8DOMConfiguration::kDoNotCheckAccess); - v8::Local<v8::Function> function = - function_template->GetFunction(isolate->GetCurrentContext()) - .ToLocalChecked(); - function->SetName(name); - if (location & V8DOMConfiguration::kOnInstance && !instance.IsEmpty()) { - instance - ->DefineOwnProperty( - isolate->GetCurrentContext(), name, function, - static_cast<v8::PropertyAttribute>(config.attribute)) - .ToChecked(); - } - if (location & V8DOMConfiguration::kOnPrototype && !prototype.IsEmpty()) { - prototype - ->DefineOwnProperty( - isolate->GetCurrentContext(), name, function, - static_cast<v8::PropertyAttribute>(config.attribute)) - .ToChecked(); - } - } - if (location & V8DOMConfiguration::kOnInterface && !interface.IsEmpty()) { - // Operations installed on the interface object must be static - // operations, so no need to specify a signature, i.e. no need to do - // type check against a holder. - v8::Local<v8::FunctionTemplate> function_template = - v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), - v8::Local<v8::Signature>(), config.length, - v8::ConstructorBehavior::kThrow, - side_effect_type); - v8::Local<v8::Function> function = - function_template->GetFunction(isolate->GetCurrentContext()) - .ToLocalChecked(); - function->SetName(name); - interface->DefineOwnProperty(isolate->GetCurrentContext(), name, function, static_cast<v8::PropertyAttribute>(config.attribute)).ToChecked(); - } -} - -} // namespace - -void V8DOMConfiguration::InstallAttributes( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const AttributeConfiguration* attributes, - size_t attribute_count) { - for (size_t i = 0; i < attribute_count; ++i) - InstallAttributeInternal(isolate, instance_template, prototype_template, - attributes[i], world); -} - -void V8DOMConfiguration::InstallAttributes( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - const AttributeConfiguration* attributes, - size_t attribute_count) { - for (size_t i = 0; i < attribute_count; ++i) { - InstallAttributeInternal(isolate, instance, prototype, attributes[i], - world); - } -} - -void V8DOMConfiguration::InstallAttribute( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const AttributeConfiguration& attribute) { - InstallAttributeInternal(isolate, instance_template, prototype_template, - attribute, world); -} - -void V8DOMConfiguration::InstallAttribute( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - const AttributeConfiguration& attribute) { - InstallAttributeInternal(isolate, instance, prototype, attribute, world); -} - -void V8DOMConfiguration::InstallAccessors( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature> signature, - const AccessorConfiguration* accessors, - size_t accessor_count) { - for (size_t i = 0; i < accessor_count; ++i) - InstallAccessorInternal(isolate, instance_template, prototype_template, - interface_template, signature, accessors[i], world); -} - -void V8DOMConfiguration::InstallAccessors( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature> signature, - const AccessorConfiguration* accessors, - size_t accessor_count) { - for (size_t i = 0; i < accessor_count; ++i) { - InstallAccessorInternal(isolate, instance, prototype, interface, signature, - accessors[i], world); - } -} - -void V8DOMConfiguration::InstallAccessor( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature> signature, - const AccessorConfiguration& accessor) { - InstallAccessorInternal(isolate, instance_template, prototype_template, - interface_template, signature, accessor, world); -} - -void V8DOMConfiguration::InstallAccessor( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature> signature, - const AccessorConfiguration& accessor) { - InstallAccessorInternal(isolate, instance, prototype, interface, signature, - accessor, world); -} - -void V8DOMConfiguration::InstallConstants( - v8::Isolate* isolate, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const ConstantConfiguration* constants, - size_t constant_count) { - for (size_t i = 0; i < constant_count; ++i) { - InstallConstantInternal(isolate, interface_template, prototype_template, - constants[i]); - } -} - -void V8DOMConfiguration::InstallConstant( - v8::Isolate* isolate, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const ConstantConfiguration& constant) { - InstallConstantInternal(isolate, interface_template, prototype_template, - constant); -} - -void V8DOMConfiguration::InstallConstant( - v8::Isolate* isolate, - v8::Local<v8::Function> interface, - v8::Local<v8::Object> prototype, - const ConstantConfiguration& constant) { - InstallConstantInternal(isolate, interface, prototype, constant); -} - -void V8DOMConfiguration::InstallConstants( - v8::Isolate* isolate, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const ConstantCallbackConfiguration* constants, - size_t constant_count) { - for (size_t i = 0; i < constant_count; ++i) { - v8::Local<v8::String> name = V8AtomicString(isolate, constants[i].name); - interface_template->SetNativeDataProperty( - name, constants[i].getter, nullptr, v8::Local<v8::Value>(), - static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete), - v8::Local<v8::AccessorSignature>(), v8::DEFAULT, - v8::SideEffectType::kHasNoSideEffect, - v8::SideEffectType::kHasSideEffect); - prototype_template->SetNativeDataProperty( - name, constants[i].getter, nullptr, v8::Local<v8::Value>(), - static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete), - v8::Local<v8::AccessorSignature>(), v8::DEFAULT, - v8::SideEffectType::kHasNoSideEffect, - v8::SideEffectType::kHasSideEffect); - } -} - -void V8DOMConfiguration::InstallConstants( - v8::Isolate* isolate, - v8::Local<v8::Function> interface_object, - v8::Local<v8::Object> prototype_object, - const V8DOMConfiguration::ConstantConfiguration* constants, - size_t constant_count) { - for (size_t i = 0; i < constant_count; ++i) { - InstallConstantInternal(isolate, interface_object, prototype_object, - constants[i]); - } -} - -void V8DOMConfiguration::InstallConstantWithGetter( - v8::Isolate* isolate, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const char* name, - v8::AccessorNameGetterCallback getter) { - v8::Local<v8::String> constant_name = V8AtomicString(isolate, name); - v8::PropertyAttribute attributes = - static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); - interface_template->SetNativeDataProperty(constant_name, getter, nullptr, - v8::Local<v8::Value>(), attributes); - prototype_template->SetNativeDataProperty(constant_name, getter, nullptr, - v8::Local<v8::Value>(), attributes); -} - -void V8DOMConfiguration::InstallMethods( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature> signature, - const MethodConfiguration* methods, - size_t method_count) { - for (size_t i = 0; i < method_count; ++i) - InstallMethodInternal(isolate, instance_template, prototype_template, - interface_template, signature, methods[i], world); -} - -void V8DOMConfiguration::InstallMethods( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature> signature, - const NoAllocDirectCallMethodConfiguration* methods, - size_t method_count) { - for (size_t i = 0; i < method_count; ++i) { - InstallMethodInternal( - isolate, instance_template, prototype_template, interface_template, - signature, methods[i].method_config, world, &methods[i].v8_c_function); - } -} - -void V8DOMConfiguration::InstallMethod( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature> signature, - const MethodConfiguration& method) { - InstallMethodInternal(isolate, instance_template, prototype_template, - interface_template, signature, method, world); -} - -void V8DOMConfiguration::InstallMethods(v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature> signature, - const MethodConfiguration* methods, - size_t method_count) { - for (size_t i = 0; i < method_count; ++i) { - InstallMethodInternal(isolate, instance, prototype, interface, signature, - methods[i], world); - } -} - -void V8DOMConfiguration::InstallMethod(v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature> signature, - const MethodConfiguration& method) { - InstallMethodInternal(isolate, instance, prototype, interface, signature, - method, world); -} - -void V8DOMConfiguration::InstallMethod( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::Signature> signature, - const SymbolKeyedMethodConfiguration& method) { - InstallMethodInternal(isolate, v8::Local<v8::ObjectTemplate>(), - prototype_template, v8::Local<v8::FunctionTemplate>(), - signature, method, world); -} - -void V8DOMConfiguration::InitializeDOMInterfaceTemplate( - v8::Isolate* isolate, - v8::Local<v8::FunctionTemplate> interface_template, - const char* interface_name, - v8::Local<v8::FunctionTemplate> parent_interface_template, - uint32_t v8_internal_field_count) { - interface_template->SetClassName(V8AtomicString(isolate, interface_name)); - interface_template->ReadOnlyPrototype(); - v8::Local<v8::ObjectTemplate> instance_template = - interface_template->InstanceTemplate(); - v8::Local<v8::ObjectTemplate> prototype_template = - interface_template->PrototypeTemplate(); - instance_template->SetInternalFieldCount(v8_internal_field_count); - - // We intentionally don't set the class string to the platform object - // (|instanceTemplate|), and set the class string "InterfaceName", without - // "Prototype", to the prototype object (|prototypeTemplate|) despite a fact - // that the current WebIDL spec (as of Feb 2017) requires to set the class - // string "InterfaceName" for the platform objects and - // "InterfaceNamePrototype" for the interface prototype object, because we - // think it's more consistent with ECMAScript 2016. - // See also https://crbug.com/643712 - // https://heycam.github.io/webidl/#es-platform-objects - // https://heycam.github.io/webidl/#interface-prototype-object - // - // Note that V8 minor GC does not collect an object which has an own property. - // So, if we set the class string to the platform object as an own property, - // it prevents V8 minor GC to collect the object (V8 minor GC only collects - // an empty object). If set, a web test fast/dom/minor-dom-gc.html fails. - SetClassString(isolate, prototype_template, interface_name); - - if (!parent_interface_template.IsEmpty()) { - interface_template->Inherit(parent_interface_template); - // Marks the prototype object as one of native-backed objects. - // This is needed since bug 110436 asks WebKit to tell native-initiated - // prototypes from pure-JS ones. This doesn't mark kinds "root" classes - // like Node, where setting this changes prototype chain structure. - // The value of this field is not used, only the count. - prototype_template->SetInternalFieldCount(kV8PrototypeInternalFieldcount); - } -} - -v8::Local<v8::FunctionTemplate> V8DOMConfiguration::DomClassTemplate( - v8::Isolate* isolate, - const DOMWrapperWorld& world, - WrapperTypeInfo* wrapper_type_info, - InstallTemplateFunction configure_dom_class_template) { - V8PerIsolateData* data = V8PerIsolateData::From(isolate); - v8::Local<v8::FunctionTemplate> interface_template = - data->FindV8Template(world, wrapper_type_info).As<v8::FunctionTemplate>(); - if (!interface_template.IsEmpty()) - return interface_template; - - // We assume all constructors have no JS-observable side effect. - interface_template = v8::FunctionTemplate::New( - isolate, V8ObjectConstructor::IsValidConstructorMode); - configure_dom_class_template(isolate, world, interface_template); - data->AddV8Template(world, wrapper_type_info, interface_template); - return interface_template; -} - -void V8DOMConfiguration::SetClassString( - v8::Isolate* isolate, - v8::Local<v8::ObjectTemplate> object_template, - const char* class_string) { - object_template->Set( - v8::Symbol::GetToStringTag(isolate), - V8AtomicString(isolate, class_string), - static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontEnum)); -} - -} // namespace blink
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h b/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h deleted file mode 100644 index a88efd6..0000000 --- a/third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h +++ /dev/null
@@ -1,444 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_DOM_CONFIGURATION_H_ -#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_DOM_CONFIGURATION_H_ - -#include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" -#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" -#include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h" -#include "third_party/blink/renderer/platform/bindings/v8_private_property.h" -#include "v8/include/v8-fast-api-calls.h" -#include "v8/include/v8.h" - -namespace blink { - -class CORE_EXPORT V8DOMConfiguration final { - STATIC_ONLY(V8DOMConfiguration); - - public: - // The following Configuration structs and install methods are used for - // setting multiple properties on ObjectTemplate / FunctionTemplate, used - // from the generated bindings initialization (ConfigureXXXTemplate). - // This greatly reduces the binary size by moving from code driven setup to - // data table driven setup. - - // Bitflags to show where the member will be defined. - enum PropertyLocationConfiguration : unsigned { - kOnInstance = 1 << 0, - kOnPrototype = 1 << 1, - kOnInterface = 1 << 2, - }; - - // TODO(dcheng): Make these enum classes. - enum HolderCheckConfiguration : unsigned { - kCheckHolder, - kDoNotCheckHolder, - }; - - enum AccessCheckConfiguration : unsigned { - kCheckAccess, - kDoNotCheckAccess, - }; - - enum SideEffectConfiguration : unsigned { - kHasSideEffect, - kHasNoSideEffect, - }; - - enum AttributeGetterBehavior : unsigned { - // The getter will be called each time the property is gotten. - kAlwaysCallGetter, - // After the first access, the property will be turned into a plain data - // property, taking the value returned by the getter. - kReplaceWithDataProperty, - }; - - // Bit field to select which worlds the member will be defined in. - enum WorldConfiguration : unsigned { - kMainWorld = 1 << 0, - kNonMainWorlds = 1 << 1, - kAllWorlds = kMainWorld | kNonMainWorlds, - }; - - // AttributeConfiguration translates into calls to SetNativeDataProperty() on - // either of instance or prototype object (or their object template). - struct AttributeConfiguration { - DISALLOW_NEW(); - - public: - AttributeConfiguration& operator=(const AttributeConfiguration&) = delete; - - const char* name; - v8::AccessorNameGetterCallback getter; - v8::AccessorNameSetterCallback setter; - - // v8::PropertyAttribute - unsigned attribute : 8; - // PropertyLocationConfiguration - unsigned property_location_configuration : 3; - // HolderCheckConfiguration - unsigned holder_check_configuration : 1; - // SideEffectConfiguration - unsigned getter_side_effect_type : 1; - // AttributeGetterBehavior - unsigned getter_behavior : 1; - // WorldConfiguration - unsigned world_configuration : 2; - }; - - static void InstallAttributes( - v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const AttributeConfiguration*, - size_t attribute_count); - static void InstallAttribute(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const AttributeConfiguration&); - - // If an empty handle is passed as |instance| or |prototype|, that object is - // ignored and no properties are installed on that object. - static void InstallAttributes(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - const AttributeConfiguration*, - size_t attribute_count); - static void InstallAttribute(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - const AttributeConfiguration&); - - // AccessorConfiguration translates into calls to SetAccessorProperty() on - // either of instance, prototype, or interface object (or their object - // template). - struct AccessorConfiguration { - DISALLOW_NEW(); - - public: - AccessorConfiguration& operator=(const AccessorConfiguration&) = delete; - - const char* name; - v8::FunctionCallback getter; - v8::FunctionCallback setter; - // V8PrivateProperty::CachedAccessor - unsigned cached_property_key : 2; - // v8::PropertyAttribute - unsigned attribute : 8; - // PropertyLocationConfiguration - unsigned property_location_configuration : 3; - // HolderCheckConfiguration - unsigned holder_check_configuration : 1; - // AccessCheckConfiguration - unsigned getter_access_check_configuration : 1; - unsigned setter_access_check_configuration : 1; - // SideEffectConfiguration - unsigned getter_side_effect_type : 1; - // WorldConfiguration - unsigned world_configuration : 2; - }; - - static void InstallAccessors( - v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature>, - const AccessorConfiguration*, - size_t accessor_count); - static void InstallAccessor( - v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature>, - const AccessorConfiguration&); - - // If an empty handle is passed as |instance|, |prototype|, or |interface|, - // then that object is ignored and no properties are installed on that object. - static void InstallAccessors(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature>, - const AccessorConfiguration*, - size_t accessor_count); - static void InstallAccessor(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature>, - const AccessorConfiguration&); - - enum ConstantType { - kConstantTypeShort, - kConstantTypeLong, - kConstantTypeUnsignedShort, - kConstantTypeUnsignedLong, - kConstantTypeFloat, - kConstantTypeDouble - }; - - // ConstantConfiguration translates into calls to Set() for setting up an - // object's constants. It sets the constant on both the FunctionTemplate and - // the ObjectTemplate. PropertyAttributes is always ReadOnly. - struct ConstantConfiguration { - DISALLOW_NEW(); - - public: - constexpr ConstantConfiguration(const char* name, - ConstantType type, - int value) - : name(name), type(type), ivalue(value) {} - constexpr ConstantConfiguration(const char* name, - ConstantType type, - double value) - : name(name), type(type), dvalue(value) {} - ConstantConfiguration& operator=(const ConstantConfiguration&) = delete; - - const char* name; - ConstantType type; - union { - int ivalue; - double dvalue; - }; - }; - - struct ConstantCallbackConfiguration { - DISALLOW_NEW(); - - public: - constexpr ConstantCallbackConfiguration( - const char* name, - v8::AccessorNameGetterCallback getter) - : name(name), getter(getter) {} - ConstantCallbackConfiguration(const ConstantCallbackConfiguration&) = - delete; - - ConstantCallbackConfiguration& operator=( - const ConstantCallbackConfiguration&) = delete; - - const char* name; - v8::AccessorNameGetterCallback getter; - }; - - // Constant installation - // - // installConstants and installConstant are used for simple constants. They - // install constants using v8::Template::Set(), which results in a property - // that is much faster to access from scripts. - // installConstantWithGetter is used when some C++ code needs to be executed - // when the constant is accessed, e.g. to handle deprecation or measuring - // usage. The property appears the same to scripts, but is slower to access. - static void InstallConstants( - v8::Isolate*, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const ConstantConfiguration*, - size_t constant_count); - static void InstallConstant( - v8::Isolate*, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const ConstantConfiguration&); - - static void InstallConstant(v8::Isolate*, - v8::Local<v8::Function> interface, - v8::Local<v8::Object> prototype, - const ConstantConfiguration&); - - static void InstallConstants( - v8::Isolate* isolate, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const ConstantCallbackConfiguration*, - size_t constant_count); - - static void InstallConstants(v8::Isolate* isolate, - v8::Local<v8::Function> interface_object, - v8::Local<v8::Object> prototype_object, - const ConstantConfiguration* constants, - size_t constant_count); - - static void InstallConstantWithGetter( - v8::Isolate*, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::ObjectTemplate> prototype_template, - const char* name, - v8::AccessorNameGetterCallback); - - // MethodConfiguration translates into calls to Set() for setting up an - // object's callbacks. It sets a method on instance, prototype or - // interface object (or their object tepmplate). - struct MethodConfiguration { - DISALLOW_NEW(); - - public: - MethodConfiguration& operator=(const MethodConfiguration&) = delete; - - v8::Local<v8::String> MethodName(v8::Isolate* isolate) const { - return V8AtomicString(isolate, name); - } - - const char* name; - v8::FunctionCallback callback; - int length; - // v8::PropertyAttribute - unsigned attribute : 8; - // PropertyLocationConfiguration - unsigned property_location_configuration : 3; - // HolderCheckConfiguration - unsigned holder_check_configuration : 1; - // AccessCheckConfiguration - unsigned access_check_configuration : 1; - // SideEffectConfiguration - unsigned side_effect_type : 1; - // WorldConfiguration - unsigned world_configuration : 2; - }; - - struct SymbolKeyedMethodConfiguration { - DISALLOW_NEW(); - - public: - SymbolKeyedMethodConfiguration& operator=( - const SymbolKeyedMethodConfiguration&) = delete; - - v8::Local<v8::Name> MethodName(v8::Isolate* isolate) const { - return get_symbol(isolate); - } - - v8::Local<v8::Symbol> (*get_symbol)(v8::Isolate*); - const char* symbol_alias; - v8::FunctionCallback callback; - // SymbolKeyedMethodConfiguration doesn't support per-world bindings. - int length; - // v8::PropertyAttribute - unsigned attribute : 8; - // PropertyLocationConfiguration - unsigned property_location_configuration : 3; - // HolderCheckConfiguration - unsigned holder_check_configuration : 1; - // AccessCheckConfiguration - unsigned access_check_configuration : 1; - // SideEffectConfiguration - unsigned side_effect_type : 1; - }; - - struct NoAllocDirectCallMethodConfiguration { - DISALLOW_NEW(); - - public: - NoAllocDirectCallMethodConfiguration& operator=( - const NoAllocDirectCallMethodConfiguration&) = delete; - - MethodConfiguration method_config; - v8::CFunction v8_c_function; - }; - - static void InstallMethods(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature>, - const MethodConfiguration*, - size_t method_count); - static void InstallMethods(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature>, - const NoAllocDirectCallMethodConfiguration*, - size_t method_count); - - static void InstallMethod(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::ObjectTemplate> instance_template, - v8::Local<v8::ObjectTemplate> prototype_template, - v8::Local<v8::FunctionTemplate> interface_template, - v8::Local<v8::Signature>, - const MethodConfiguration&); - static void InstallMethod(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::ObjectTemplate>, - v8::Local<v8::Signature>, - const SymbolKeyedMethodConfiguration&); - - // If an empty handle is passed as |instance|, |prototype|, or |interface|, - // then that object is ignored and no properties are installed on that object. - static void InstallMethods(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature>, - const MethodConfiguration*, - size_t method_count); - static void InstallMethod(v8::Isolate*, - const DOMWrapperWorld&, - v8::Local<v8::Object> instance, - v8::Local<v8::Object> prototype, - v8::Local<v8::Function> interface, - v8::Local<v8::Signature>, - const MethodConfiguration&); - - static void InitializeDOMInterfaceTemplate( - v8::Isolate*, - v8::Local<v8::FunctionTemplate> interface_template, - const char* interface_name, - v8::Local<v8::FunctionTemplate> parent_interface_template, - uint32_t v8_internal_field_count); - - static v8::Local<v8::FunctionTemplate> DomClassTemplate( - v8::Isolate*, - const DOMWrapperWorld&, - WrapperTypeInfo*, - InstallTemplateFunction); - - // Sets the class string of platform objects, interface prototype objects, - // etc. See also http://heycam.github.io/webidl/#dfn-class-string - static void SetClassString(v8::Isolate*, - v8::Local<v8::ObjectTemplate>, - const char* class_string); -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_V8_DOM_CONFIGURATION_H_
diff --git a/third_party/blink/renderer/core/dom/node.cc b/third_party/blink/renderer/core/dom/node.cc index cb601af..768d4f3 100644 --- a/third_party/blink/renderer/core/dom/node.cc +++ b/third_party/blink/renderer/core/dom/node.cc
@@ -3039,7 +3039,7 @@ return false; } -bool Node::WillRespondToMouseMoveEvents() { +bool Node::WillRespondToMouseMoveEvents() const { if (IsDisabledFormControl(this)) return false; return HasEventListeners(event_type_names::kMousemove) ||
diff --git a/third_party/blink/renderer/core/dom/node.h b/third_party/blink/renderer/core/dom/node.h index 55de04c..ab0a31b 100644 --- a/third_party/blink/renderer/core/dom/node.h +++ b/third_party/blink/renderer/core/dom/node.h
@@ -819,7 +819,7 @@ void ClearFlatTreeNodeData(); void ClearFlatTreeNodeDataIfHostChanged(const ContainerNode& parent); - virtual bool WillRespondToMouseMoveEvents(); + virtual bool WillRespondToMouseMoveEvents() const; virtual bool WillRespondToMouseClickEvents(); enum ShadowTreesTreatment {
diff --git a/third_party/blink/renderer/core/frame/attribution_source_params.idl b/third_party/blink/renderer/core/frame/attribution_source_params.idl index 14c5ef9..c055595 100644 --- a/third_party/blink/renderer/core/frame/attribution_source_params.idl +++ b/third_party/blink/renderer/core/frame/attribution_source_params.idl
@@ -7,6 +7,6 @@ required USVString attributionDestination; required DOMString attributionSourceEventId; USVString attributionReportTo; - unsigned long long attributionExpiry; + long long attributionExpiry; long long attributionSourcePriority; };
diff --git a/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc b/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc index 768fe101..6a3d8f7 100644 --- a/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc +++ b/third_party/blink/renderer/core/frame/navigation_rate_limiter.cc
@@ -53,7 +53,7 @@ mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kWarning, "Throttling navigation to prevent the browser from hanging. See " - "https://crbug.com/882238. Command line switch " + "https://crbug.com/1038223. Command line switch " "--disable-ipc-flooding-protection can be used to bypass the " "protection")); }
diff --git a/third_party/blink/renderer/core/html/conversion_measurement_parsing.cc b/third_party/blink/renderer/core/html/conversion_measurement_parsing.cc index 0b43632..9ba998cf 100644 --- a/third_party/blink/renderer/core/html/conversion_measurement_parsing.cc +++ b/third_party/blink/renderer/core/html/conversion_measurement_parsing.cc
@@ -26,9 +26,9 @@ namespace { -absl::optional<uint64_t> ParseExpiry(const String& expiry) { +absl::optional<int64_t> ParseExpiry(const String& expiry) { bool expiry_is_valid = false; - uint64_t parsed_expiry = expiry.ToUInt64Strict(&expiry_is_valid); + int64_t parsed_expiry = expiry.ToInt64Strict(&expiry_is_valid); return expiry_is_valid ? absl::make_optional(parsed_expiry) : absl::nullopt; } @@ -56,7 +56,7 @@ const String& impression_data_string, const String& conversion_destination_string, const absl::optional<String>& reporting_origin_string, - absl::optional<uint64_t> impression_expiry_milliseconds, + absl::optional<int64_t> impression_expiry_milliseconds, absl::optional<int64_t> attribution_source_priority, HTMLAnchorElement* element, bool allow_invalid_impression_data) { @@ -192,7 +192,7 @@ absl::optional<WebImpression> GetImpressionForAnchor( HTMLAnchorElement* element) { - absl::optional<uint64_t> expiry; + absl::optional<int64_t> expiry; if (element->hasAttribute(html_names::kAttributionexpiryAttr)) { expiry = ParseExpiry( element->FastGetAttribute(html_names::kAttributionexpiryAttr)
diff --git a/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc b/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc index ca7c5c7..5bad6de 100644 --- a/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc +++ b/third_party/blink/renderer/core/html/forms/slider_thumb_element.cc
@@ -236,7 +236,7 @@ HTMLDivElement::DefaultEventHandler(event); } -bool SliderThumbElement::WillRespondToMouseMoveEvents() { +bool SliderThumbElement::WillRespondToMouseMoveEvents() const { const HTMLInputElement* input = HostInput(); if (input && !input->IsDisabledFormControl() && in_drag_mode_) return true;
diff --git a/third_party/blink/renderer/core/html/forms/slider_thumb_element.h b/third_party/blink/renderer/core/html/forms/slider_thumb_element.h index a554003a..6eb2976e 100644 --- a/third_party/blink/renderer/core/html/forms/slider_thumb_element.h +++ b/third_party/blink/renderer/core/html/forms/slider_thumb_element.h
@@ -52,7 +52,7 @@ void DragFrom(const LayoutPoint&); void DefaultEventHandler(Event&) override; - bool WillRespondToMouseMoveEvents() override; + bool WillRespondToMouseMoveEvents() const override; bool WillRespondToMouseClickEvents() override; void DetachLayoutTree(bool performing_reattach) override; const AtomicString& ShadowPseudoId() const override;
diff --git a/third_party/blink/renderer/core/html/forms/spin_button_element.cc b/third_party/blink/renderer/core/html/forms/spin_button_element.cc index b70a2b4..4d383573 100644 --- a/third_party/blink/renderer/core/html/forms/spin_button_element.cc +++ b/third_party/blink/renderer/core/html/forms/spin_button_element.cc
@@ -146,7 +146,7 @@ event.SetDefaultHandled(); } -bool SpinButtonElement::WillRespondToMouseMoveEvents() { +bool SpinButtonElement::WillRespondToMouseMoveEvents() const { if (GetLayoutBox() && ShouldRespondToMouseEvents()) return true; @@ -216,7 +216,7 @@ Step(up_down_state_ == kUp ? 1 : -1); } -bool SpinButtonElement::ShouldRespondToMouseEvents() { +bool SpinButtonElement::ShouldRespondToMouseEvents() const { return !spin_button_owner_ || spin_button_owner_->ShouldSpinButtonRespondToMouseEvents(); }
diff --git a/third_party/blink/renderer/core/html/forms/spin_button_element.h b/third_party/blink/renderer/core/html/forms/spin_button_element.h index dad46a7..d6079335a 100644 --- a/third_party/blink/renderer/core/html/forms/spin_button_element.h +++ b/third_party/blink/renderer/core/html/forms/spin_button_element.h
@@ -67,7 +67,7 @@ void Step(int amount); - bool WillRespondToMouseMoveEvents() override; + bool WillRespondToMouseMoveEvents() const override; bool WillRespondToMouseClickEvents() override; void ForwardEvent(Event&); @@ -88,7 +88,7 @@ void StartRepeatingTimer(); void StopRepeatingTimer(); void RepeatingTimerFired(TimerBase*); - bool ShouldRespondToMouseEvents(); + bool ShouldRespondToMouseEvents() const; bool IsMouseFocusable() const override { return false; } Member<SpinButtonOwner> spin_button_owner_;
diff --git a/third_party/blink/renderer/core/input/event_handler_test.cc b/third_party/blink/renderer/core/input/event_handler_test.cc index f530937..fbbc94cf 100644 --- a/third_party/blink/renderer/core/input/event_handler_test.cc +++ b/third_party/blink/renderer/core/input/event_handler_test.cc
@@ -975,6 +975,25 @@ ASSERT_TRUE(Selection().IsHandleVisible()); } +// Tests that touch adjustment algorithm can handle editable elements without +// layout objects. +// +// TODO(mustaq): A fix for https://crbug.com/1230045 can make this test +// obsolete. +TEST_F(EventHandlerTest, TouchAdjustmentOnEditableDisplayContents) { + SetHtmlInnerHTML( + "<div style='display:contents' contenteditable='true'>TEXT</div>"); + TapEventBuilder single_tap_event(FloatPoint(1, 1), 1); + GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( + single_tap_event); + + LongPressEventBuilder long_press_event(FloatPoint(1, 1)); + GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( + long_press_event); + + // This test passes if it doesn't crash. +} + TEST_F(EventHandlerTest, dragEndInNewDrag) { SetHtmlInnerHTML( "<style>.box { width: 100px; height: 100px; display: block; }</style>"
diff --git a/third_party/blink/renderer/core/loader/base_fetch_context.cc b/third_party/blink/renderer/core/loader/base_fetch_context.cc index 8502dcac..07ce40cf 100644 --- a/third_party/blink/renderer/core/loader/base_fetch_context.cc +++ b/third_party/blink/renderer/core/loader/base_fetch_context.cc
@@ -137,7 +137,7 @@ // One exception, however, is that a custom UA is sometimes set without // specifying accomponying client hints, in which case we disable sending // them. - if (ClientHintsPreferences::UserAgentClientHintEnabled() && ua) { + if (RuntimeEnabledFeatures::UserAgentClientHintEnabled() && ua) { // ShouldSendClientHint is called to make sure UA is controlled by // Permissions Policy. if (ShouldSendClientHint(ClientHintsMode::kStandard, policy, @@ -285,7 +285,7 @@ } // Only send User Agent hints if the info is available - if (ClientHintsPreferences::UserAgentClientHintEnabled() && ua) { + if (RuntimeEnabledFeatures::UserAgentClientHintEnabled() && ua) { if (ShouldSendClientHint(ClientHintsMode::kStandard, policy, resource_origin, is_1p_origin, network::mojom::blink::WebClientHintsType::kUAArch,
diff --git a/third_party/blink/renderer/core/page/touch_adjustment.cc b/third_party/blink/renderer/core/page/touch_adjustment.cc index aeac4227..3a39c79 100644 --- a/third_party/blink/renderer/core/page/touch_adjustment.cc +++ b/third_party/blink/renderer/core/page/touch_adjustment.cc
@@ -89,7 +89,8 @@ const IntRect&, const SubtargetGeometry&); -// Takes non-const Node* because isContentEditable is a non-const function. +// Takes non-const |Node*| because |Node::WillRespondToMouseClickEvents()| is +// non-const. bool NodeRespondsToTapGesture(Node* node) { if (node->WillRespondToMouseClickEvents() || node->WillRespondToMouseMoveEvents()) @@ -286,7 +287,8 @@ // line-breaks. for (unsigned i = 0; i < candidates.size(); i++) { Node* candidate = candidates[i]; - // Skip nodes who's responders are ancestors of other responders. This gives + + // Skip nodes whose responders are ancestors of other responders. This gives // preference to the inner-most event-handlers. So that a link is always // preferred even when contained in an element that monitors all // click-events. @@ -294,6 +296,7 @@ DCHECK(responding_node); if (ancestors_to_responders_set.Contains(responding_node)) continue; + // Consolidate bounds for editable content. if (editable_ancestors.Contains(candidate)) continue; @@ -301,7 +304,10 @@ if (HasEditableStyle(*candidate)) { Node* replacement = candidate; Node* parent = candidate->ParentOrShadowHostNode(); - while (parent && HasEditableStyle(*parent)) { + + // Ignore parents without layout objects. E.g. editable elements with + // display:contents. https://crbug.com/1196872 + while (parent && HasEditableStyle(*parent) && parent->GetLayoutObject()) { replacement = parent; if (editable_ancestors.Contains(replacement)) { replacement = nullptr;
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.cc b/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.cc index df7a886..21668f9a 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.cc +++ b/third_party/blink/renderer/modules/file_system_access/file_system_file_handle.cc
@@ -111,21 +111,25 @@ mojo_ptr_->OpenAccessHandle(WTF::Bind( [](ScriptPromiseResolver* resolver, FileSystemAccessErrorPtr result, - mojom::blink::FileSystemAccessAccessHandleFilePtr file) { + mojom::blink::FileSystemAccessAccessHandleFilePtr file, + mojo::PendingRemote<mojom::blink::FileSystemAccessAccessHandleHost> + access_handle_remote) { if (result->status != mojom::blink::FileSystemAccessStatus::kOk) { file_system_access_error::Reject(resolver, *result); return; } DCHECK(!file.is_null()); + DCHECK(access_handle_remote.is_valid()); + + ExecutionContext* context = resolver->GetExecutionContext(); + if (!context) + return; FileSystemAccessFileDelegate* file_delegate = nullptr; if (file->is_regular_file()) { file_delegate = FileSystemAccessFileDelegate::Create( std::move(file->get_regular_file())); } else if (file->is_incognito_file_delegate()) { - ExecutionContext* context = resolver->GetExecutionContext(); - if (!context) - return; file_delegate = FileSystemAccessFileDelegate::CreateForIncognito( context, std::move(file->get_incognito_file_delegate())); } @@ -139,7 +143,8 @@ return; } resolver->Resolve(MakeGarbageCollected<FileSystemSyncAccessHandle>( - std::move(file_delegate))); + context, std::move(file_delegate), + std::move(access_handle_remote))); }, WrapPersistent(resolver)));
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.cc b/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.cc index 03a1446..9d713be 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.cc +++ b/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.cc
@@ -7,12 +7,40 @@ namespace blink { FileSystemSyncAccessHandle::FileSystemSyncAccessHandle( - FileSystemAccessFileDelegate* file_delegate) - : file_delegate_(file_delegate) {} + ExecutionContext* context, + FileSystemAccessFileDelegate* file_delegate, + mojo::PendingRemote<mojom::blink::FileSystemAccessAccessHandleHost> + access_handle_remote) + : file_delegate_(file_delegate), access_handle_remote_(context) { + access_handle_remote_.Bind( + std::move(access_handle_remote), + context->GetTaskRunner(TaskType::kMiscPlatformAPI)); + DCHECK(access_handle_remote_.is_bound()); +} + +ScriptPromise FileSystemSyncAccessHandle::close(ScriptState* script_state) { + auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); + auto promise = resolver->Promise(); + + // TODO(fivedots): Add logic to close file delegate, and deal with + // closures during IO operations, as done in Storage Foundation API. + + if (!access_handle_remote_.is_bound()) { + // If the backend went away, no need to tell it that the handle was closed. + resolver->Resolve(); + return promise; + } + + access_handle_remote_->Close( + WTF::Bind([](ScriptPromiseResolver* resolver) { resolver->Resolve(); }, + WrapPersistent(resolver))); + return promise; +} void FileSystemSyncAccessHandle::Trace(Visitor* visitor) const { ScriptWrappable::Trace(visitor); visitor->Trace(file_delegate_); + visitor->Trace(access_handle_remote_); } } // namespace blink
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.h b/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.h index c752e79..376b12f5 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.h +++ b/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.h
@@ -5,9 +5,14 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_FILE_SYSTEM_ACCESS_FILE_SYSTEM_SYNC_ACCESS_HANDLE_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_FILE_SYSTEM_ACCESS_FILE_SYSTEM_SYNC_ACCESS_HANDLE_H_ +#include "third_party/blink/public/mojom/file_system_access/file_system_access_access_handle_host.mojom-blink.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_file_handle.mojom-blink.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_access_file_delegate.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" +#include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" namespace blink { @@ -16,17 +21,27 @@ public: explicit FileSystemSyncAccessHandle( - FileSystemAccessFileDelegate* file_delegate); + ExecutionContext* context, + FileSystemAccessFileDelegate* file_delegate, + mojo::PendingRemote<mojom::blink::FileSystemAccessAccessHandleHost> + access_handle_host); FileSystemSyncAccessHandle(const FileSystemSyncAccessHandle&) = delete; FileSystemSyncAccessHandle& operator=(const FileSystemSyncAccessHandle&) = delete; + ScriptPromise close(ScriptState*); + // GarbageCollected void Trace(Visitor* visitor) const override; private: + // Interface that provides file-like access to the backing storage. Member<FileSystemAccessFileDelegate> file_delegate_; + + // Mojo pipe that holds the renderer's write lock on the file. + HeapMojoRemote<mojom::blink::FileSystemAccessAccessHandleHost> + access_handle_remote_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.idl b/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.idl index 884be24..5d01c0d 100644 --- a/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.idl +++ b/third_party/blink/renderer/modules/file_system_access/file_system_sync_access_handle.idl
@@ -9,4 +9,6 @@ Exposed=DedicatedWorker, RuntimeEnabled=FileSystemAccessAccessHandle, SecureContext -] interface FileSystemSyncAccessHandle {}; +] interface FileSystemSyncAccessHandle { + [CallWith=ScriptState] Promise<void> close(); +};
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc index 2bb07be..443d6e95 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.cc
@@ -112,7 +112,7 @@ classList().Add(kClosedCSSClass); } -bool MediaControlVolumeSliderElement::WillRespondToMouseMoveEvents() { +bool MediaControlVolumeSliderElement::WillRespondToMouseMoveEvents() const { if (!isConnected() || !GetDocument().IsActive()) return false;
diff --git a/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.h b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.h index c22d508..5bc08666 100644 --- a/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.h +++ b/third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.h
@@ -27,7 +27,7 @@ void CloseSlider(); // MediaControlInputElement overrides. - bool WillRespondToMouseMoveEvents() override; + bool WillRespondToMouseMoveEvents() const override; bool WillRespondToMouseClickEvents() override; void OnMediaKeyboardEvent(Event* event) { DefaultEventHandler(*event); }
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_impl.h b/third_party/blink/renderer/modules/media_controls/media_controls_impl.h index 07e1ad1..1d66036e 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_impl.h +++ b/third_party/blink/renderer/modules/media_controls/media_controls_impl.h
@@ -315,7 +315,7 @@ // Node bool IsMediaControls() const override { return true; } - bool WillRespondToMouseMoveEvents() override { return true; } + bool WillRespondToMouseMoveEvents() const override { return true; } void DefaultEventHandler(Event&) override; bool ContainsRelatedTarget(Event*);
diff --git a/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc b/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc index a3e0c0d6..24bf236 100644 --- a/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc +++ b/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.cc
@@ -46,12 +46,6 @@ } } -bool ClientHintsPreferences::UserAgentClientHintEnabled() { - return RuntimeEnabledFeatures::UserAgentClientHintEnabled() && - !base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kUserAgentClientHintDisable); -} - void ClientHintsPreferences::UpdateFromHttpEquivAcceptCH( const String& header_value, const KURL& url, @@ -72,7 +66,7 @@ FilterAcceptCH( network::ParseClientHintsHeader(header_value.Latin1()), RuntimeEnabledFeatures::LangClientHintHeaderEnabled(), - UserAgentClientHintEnabled(), + RuntimeEnabledFeatures::UserAgentClientHintEnabled(), RuntimeEnabledFeatures::PrefersColorSchemeClientHintHeaderEnabled()); if (!parsed_ch.has_value()) return;
diff --git a/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h b/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h index 67cd5992..198b569 100644 --- a/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h +++ b/third_party/blink/renderer/platform/loader/fetch/client_hints_preferences.h
@@ -52,8 +52,6 @@ // hints are allowed only on HTTP URLs that belong to secure contexts. static bool IsClientHintsAllowed(const KURL&); - static bool UserAgentClientHintEnabled(); - WebEnabledClientHints GetWebEnabledClientHints() const; private:
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer b/third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer deleted file mode 100644 index cdc26c59..0000000 --- a/third_party/blink/web_tests/FlagExpectations/enable-features=UseSkiaRenderer +++ /dev/null
@@ -1,47 +0,0 @@ -# tags: [ Android Fuchsia Linux Mac Mac10.12 Mac10.13 Win Win7 Win10 ] -# tags: [ Release Debug ] -# results: [ Timeout Crash Pass Failure Slow Skip ] - -# Needs rebaseline, but images depend on multiple flags. -crbug.com/1087413 css3/blending/background-blend-mode-gradient-gradient.html [ Failure Pass ] - -# One portion of the image is offset. -crbug.com/1002522 fast/canvas/canvas-toDataURL-webp.html [ Skip ] - -# Needs rebaseline. -crbug.com/1039401 [ Linux ] css3/filters/effect-blur-hw.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/background/background-repeat-round-auto1.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/background/background-repeat-round-border.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/background/background-repeat-round-content.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/background/background-repeat-round-padding.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/blending/background-blend-mode-default-value.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/blending/background-blend-mode-multiple-background-layers.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/blending/background-blend-mode-single-layer-no-blending.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/blending/effect-background-blend-mode-stacking.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/blending/mix-blend-mode-isolated-group-1.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/blending/mix-blend-mode-isolated-group-2.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/blending/mix-blend-mode-isolated-group-3.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/masking/mask-repeat-round-auto1.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/masking/mask-repeat-round-border.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/masking/mask-repeat-round-content.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] css3/masking/mask-repeat-round-padding.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] images/color-profile-background-image-cover.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] images/color-profile-background-image-repeat.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] images/rgb-png-with-cmyk-color-profile.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] media/video-controls-hide-on-move-outside-controls.html [ Failure Pass ] -crbug.com/1175758 [ Linux ] virtual/android/fullscreen/model/fully-exit-fullscreen-single.html [ Failure Pass ] -[ Linux ] transforms/shadows.html [ Skip ] -crbug.com/1215248 [ Linux ] images/color-profile-mask-image-svg.html [ Failure ] - -# Flaky on Windows. -crbug.com/1026375 [ Win ] media/video-currentTime-delay.html [ Pass Timeout ] -crbug.com/1026375 [ Win ] media/encrypted-media/encrypted-media-playback-setmediakeys-before-src.html [ Pass Timeout ] -crbug.com/1026375 [ Win ] media/controls/video-enter-exit-fullscreen-while-hovering-shows-controls.html [ Failure Pass ] -crbug.com/1026375 [ Win ] media/video-pause-immediately.html [ Failure Pass ] - -# Flaky on Linux. -crbug.com/1150545 [ Linux ] virtual/android/fullscreen/video-scrolled-iframe.html [ Pass Timeout ] - -# Failing on Linux & Windows. -crbug.com/1086181 [ Linux ] media/controls-layout-direction.html [ Failure ] -crbug.com/1086181 [ Win10 ] media/controls-layout-direction.html [ Failure ]
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization b/third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization index 28e5246..0d5fec8 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization +++ b/third_party/blink/web_tests/FlagExpectations/enable-gpu-rasterization
@@ -2,18 +2,43 @@ # tags: [ Release Debug ] # results: [ Timeout Crash Pass Failure Slow Skip ] -# Flaky Input Related Tests -crbug.com/1026375 [ Win ] media/controls/video-enter-exit-fullscreen-without-hovering-doesnt-show-controls.html [ Failure Pass ] -crbug.com/1026375 [ Win ] media/media-controls-tap-show-controls-without-activating.html [ Failure Pass ] -crbug.com/1026375 [ Win ] media/video-controls-auto-hide-after-play-by-touch.html [ Failure Pass ] -crbug.com/1026375 [ Win ] media/video-controls-hide-after-touch-on-control.html [ Failure Pass ] -crbug.com/1026375 [ Win ] media/video-controls-hide-on-move-outside-controls.html [ Failure Pass ] -crbug.com/1026375 [ Win ] media/video-controls-visibility-multimodal-touch-after-mouse.html [ Failure Pass ] -crbug.com/1026375 [ Win ] media/video-persistence.html [ Failure Pass ] +# Needs rebaseline, but images depend on multiple flags. +crbug.com/1087413 css3/blending/background-blend-mode-gradient-gradient.html [ Failure Pass ] + +# One portion of the image is offset. +crbug.com/1002522 fast/canvas/canvas-toDataURL-webp.html [ Skip ] + +# Needs rebaseline. +crbug.com/1039401 css3/filters/effect-blur-hw.html [ Failure Pass ] +crbug.com/1175758 css3/background/background-repeat-round-auto1.html [ Failure Pass ] +crbug.com/1175758 css3/background/background-repeat-round-border.html [ Failure Pass ] +crbug.com/1175758 css3/background/background-repeat-round-content.html [ Failure Pass ] +crbug.com/1175758 css3/background/background-repeat-round-padding.html [ Failure Pass ] +crbug.com/1175758 css3/blending/background-blend-mode-default-value.html [ Failure Pass ] +crbug.com/1175758 css3/blending/background-blend-mode-multiple-background-layers.html [ Failure Pass ] +crbug.com/1175758 css3/blending/background-blend-mode-single-layer-no-blending.html [ Failure Pass ] +crbug.com/1175758 css3/blending/effect-background-blend-mode-stacking.html [ Failure Pass ] +crbug.com/1175758 css3/blending/mix-blend-mode-isolated-group-1.html [ Failure Pass ] +crbug.com/1175758 css3/blending/mix-blend-mode-isolated-group-2.html [ Failure Pass ] +crbug.com/1175758 css3/blending/mix-blend-mode-isolated-group-3.html [ Failure Pass ] +crbug.com/1175758 css3/masking/mask-repeat-round-auto1.html [ Failure Pass ] +crbug.com/1175758 css3/masking/mask-repeat-round-border.html [ Failure Pass ] +crbug.com/1175758 css3/masking/mask-repeat-round-content.html [ Failure Pass ] +crbug.com/1175758 css3/masking/mask-repeat-round-padding.html [ Failure Pass ] +crbug.com/1175758 images/color-profile-background-image-cover.html [ Failure Pass ] +crbug.com/1175758 images/color-profile-background-image-repeat.html [ Failure Pass ] +crbug.com/1175758 images/rgb-png-with-cmyk-color-profile.html [ Failure Pass ] +crbug.com/1175758 media/video-controls-hide-on-move-outside-controls.html [ Failure Pass ] +crbug.com/1175758 virtual/android/fullscreen/model/fully-exit-fullscreen-single.html [ Failure Pass ] +transforms/shadows.html [ Skip ] +crbug.com/1215248 images/color-profile-mask-image-svg.html [ Failure ] + +# Flaky on Linux. +crbug.com/1150545 virtual/android/fullscreen/video-scrolled-iframe.html [ Pass Timeout ] + +# Failing on Linux. +crbug.com/1086181 media/controls-layout-direction.html [ Failure ] # Needs Rebaseline -crbug.com/993384 [ Win ] animations/missing-values-last-keyframe.html [ Failure Pass ] -crbug.com/993384 [ Win ] css3/filters/effect-reference-colorspace.html [ Failure Pass ] -crbug.com/993384 [ Linux ] css3/filters/effect-reference-colorspace.html [ Failure Pass ] -crbug.com/993384 [ Win ] css3/filters/effect-reference-subregion.html [ Failure Pass ] -crbug.com/993384 [ Linux ] css3/filters/effect-reference-subregion.html [ Failure Pass ] +crbug.com/993384 css3/filters/effect-reference-colorspace.html [ Failure Pass ] +crbug.com/993384 css3/filters/effect-reference-subregion.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/FlagExpectations/skia-gl b/third_party/blink/web_tests/FlagExpectations/skia-gl new file mode 100644 index 0000000..36169eca --- /dev/null +++ b/third_party/blink/web_tests/FlagExpectations/skia-gl
@@ -0,0 +1,26 @@ +# tags: [ Android Fuchsia Linux Mac Mac10.12 Mac10.13 Win Win7 Win10 ] +# tags: [ Release Debug ] +# results: [ Timeout Crash Pass Failure Slow Skip ] + +# Need a Skia GL specific baseline. +crbug.com/993384 compositing/geometry/vertical-scroll-composited.html [ Skip ] +crbug.com/993384 compositing/lots-of-img-layers.html [ Skip ] +crbug.com/993384 css3/blending/background-blend-mode-crossfade-image-gradient.html [ Skip ] +crbug.com/993384 css3/blending/background-blend-mode-gradient-image.html [ Skip ] +crbug.com/993384 css3/blending/background-blend-mode-image-color.html [ Skip ] +crbug.com/993384 css3/blending/background-blend-mode-image-image.html [ Skip ] +crbug.com/993384 css3/blending/background-blend-mode-image-svg.html [ Skip ] +crbug.com/993384 css3/blending/background-blend-mode-tiled-gradient.html [ Skip ] +crbug.com/993384 css3/blending/effect-background-blend-mode-tiled.html [ Skip ] +crbug.com/993384 css3/blending/effect-background-blend-mode.html [ Skip ] +crbug.com/993384 css3/masking/mask-repeat-space-border.html [ Skip ] +crbug.com/993384 images/color-profile-background-image-space.html [ Skip ] +crbug.com/993384 media/video-layer-crash.html [ Skip ] +crbug.com/993384 transforms/transformed-document-element.html [ Skip ] +crbug.com/993384 transforms/3d/point-mapping/3d-point-mapping-deep.html [ Skip ] + +# Viewport image is the wrong size. +crbug.com/1009718 images/huge-image-viewport-scale.html [ Skip ] + +# Alpha Blending Video Failures +crbug.com/1094635 media/alpha-video-playback.html [ Skip ]
diff --git a/third_party/blink/web_tests/FlagExpectations/use-vulkan=native b/third_party/blink/web_tests/FlagExpectations/skia-vulkan-native similarity index 100% rename from third_party/blink/web_tests/FlagExpectations/use-vulkan=native rename to third_party/blink/web_tests/FlagExpectations/skia-vulkan-native
diff --git a/third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader b/third_party/blink/web_tests/FlagExpectations/skia-vulkan-swiftshader similarity index 96% rename from third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader rename to third_party/blink/web_tests/FlagExpectations/skia-vulkan-swiftshader index 36a28df8..d897e8b 100644 --- a/third_party/blink/web_tests/FlagExpectations/use-vulkan=swiftshader +++ b/third_party/blink/web_tests/FlagExpectations/skia-vulkan-swiftshader
@@ -47,3 +47,6 @@ media/color-profile-video-poster-image.html [ Skip ] transforms/shadows.html [ Skip ] +# Flaky test. +crbug.com/1229016 fast/canvas/canvas-composite-video.html [ Failure Pass ] +
diff --git a/third_party/blink/web_tests/FlagExpectations/use-gl=any b/third_party/blink/web_tests/FlagExpectations/use-gl=any deleted file mode 100644 index 7a1b8612..0000000 --- a/third_party/blink/web_tests/FlagExpectations/use-gl=any +++ /dev/null
@@ -1,44 +0,0 @@ -# tags: [ Android Fuchsia Linux Mac Mac10.12 Mac10.13 Win Win7 Win10 ] -# tags: [ Release Debug ] -# results: [ Timeout Crash Pass Failure Slow Skip ] - -# Need a Skia GL specific baseline. -crbug.com/993384 compositing/geometry/vertical-scroll-composited.html [ Skip ] -crbug.com/993384 compositing/lots-of-img-layers.html [ Skip ] -crbug.com/993384 css3/blending/background-blend-mode-crossfade-image-gradient.html [ Skip ] -crbug.com/993384 css3/blending/background-blend-mode-gradient-image.html [ Skip ] -crbug.com/993384 css3/blending/background-blend-mode-image-color.html [ Skip ] -crbug.com/993384 css3/blending/background-blend-mode-image-image.html [ Skip ] -crbug.com/993384 css3/blending/background-blend-mode-image-svg.html [ Skip ] -crbug.com/993384 css3/blending/background-blend-mode-tiled-gradient.html [ Skip ] -crbug.com/993384 css3/blending/effect-background-blend-mode-tiled.html [ Skip ] -crbug.com/993384 css3/blending/effect-background-blend-mode.html [ Skip ] -crbug.com/993384 css3/masking/mask-repeat-space-border.html [ Skip ] -crbug.com/993384 images/color-profile-background-image-space.html [ Skip ] -crbug.com/993384 media/video-layer-crash.html [ Skip ] -crbug.com/993384 transforms/transformed-document-element.html [ Skip ] -crbug.com/993384 transforms/3d/point-mapping/3d-point-mapping-deep.html [ Skip ] - -# Windows only rebaselines needed. -crbug.com/993384 [ Win ] compositing/geometry/clipping-foreground.html [ Skip ] -crbug.com/993384 [ Win ] compositing/iframes/composited-iframe-alignment.html [ Skip ] -crbug.com/993384 [ Win ] compositing/masks/mask-with-added-filters.html [ Skip ] -crbug.com/993384 [ Win ] css2.1/t090501-c414-flt-02-d-g.html [ Skip ] -crbug.com/993384 [ Win ] css2.1/t090501-c414-flt-03-b-g.html [ Skip ] -crbug.com/993384 [ Win ] css2.1/t100304-c43-rpl-bbx-01-d-g.html [ Skip ] -crbug.com/993384 [ Win ] css3/blending/background-blend-mode-default-value.html [ Skip ] -crbug.com/993384 [ Win ] css3/blending/background-blend-mode-gradient-gradient.html [ Skip ] -crbug.com/993384 [ Win ] images/color-profile-image-filter-all.html [ Skip ] -crbug.com/993384 [ Win ] transforms/svg-vs-css.xhtml [ Skip ] - -# Incorrect clipping of the SVG image -crbug.com/1043227 [ Win ] images/color-profile-svg-fill-text.html [ Skip ] - -# Viewport image is the wrong size. -crbug.com/1009718 images/huge-image-viewport-scale.html [ Skip ] - -# Input or Playback flaky -crbug.com/1060773 [ Win ] media/video-controls-visibility-multimodal-mouse-after-touch.html [ Skip ] - -# Alpha Blending Video Failures -crbug.com/1094635 media/alpha-video-playback.html [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index fa0adf8..dd7bddf 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -2611,6 +2611,9 @@ crbug.com/626703 external/wpt/service-workers/service-worker/worker-interception.https.html [ Failure ] # ====== New tests from wpt-importer added here ====== +crbug.com/626703 [ Linux ] virtual/layout_ng_block_frag/external/wpt/css/css-multicol/crashtests/multicol-cached-consumed-bsize-crash.html [ Crash ] +crbug.com/626703 [ Mac10.15 ] virtual/layout_ng_block_frag/external/wpt/css/css-multicol/crashtests/multicol-cached-consumed-bsize-crash.html [ Crash ] +crbug.com/626703 [ Win10 ] virtual/layout_ng_block_frag/external/wpt/css/css-multicol/crashtests/multicol-cached-consumed-bsize-crash.html [ Crash ] crbug.com/626703 [ Win10 ] external/wpt/wasm/jsapi/exception/basic.tentative.any.html [ Failure Timeout ] crbug.com/626703 external/wpt/density-size-correction/density-corrected-image-svg-aspect-ratio-cross-origin.sub.html [ Failure ] crbug.com/626703 [ Mac10.12 ] external/wpt/html/browsers/browsing-the-web/navigating-across-documents/replace-before-load/location-setter-user-click.html [ Timeout ] @@ -4284,7 +4287,6 @@ crbug.com/709227 external/wpt/html/canvas/offscreen/pixel-manipulation/2d.imageData.create2.nonfinite.worker.html [ Failure ] crbug.com/709227 external/wpt/html/canvas/offscreen/pixel-manipulation/2d.imageData.get.nonfinite.worker.html [ Failure ] crbug.com/709227 external/wpt/html/canvas/offscreen/pixel-manipulation/2d.imageData.put.nonfinite.worker.html [ Failure ] -crbug.com/709227 external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.worker.html [ Failure ] crbug.com/709227 external/wpt/html/canvas/offscreen/the-offscreen-canvas/size.attributes.idl.worker.html [ Failure ] # ====== Tests from enabling .any.js/.worker.js tests end here ======== @@ -7311,7 +7313,7 @@ # Sheriff 2021-07-13 crbug.com/1220114 [ Linux ] external/wpt/webrtc-encoded-transform/RTCPeerConnection-insertable-streams-simulcast.https.html [ Failure Pass Timeout ] crbug.com/1228788 [ Linux ] external/wpt/webrtc-encoded-transform/RTCPeerConnection-insertable-streams-audio.https.html [ Failure Pass ] -crbug.com/1228772 [ Linux ] external/wpt/webrtc/simulcast/h264.https.html [ Crash Failure Pass ] +crbug.com/1228772 [ Linux ] external/wpt/webrtc/simulcast/h264.https.html [ Crash Failure Pass Timeout ] crbug.com/1228772 [ Linux ] virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-mandatory-getStats.https.html [ Failure Pass ] crbug.com/1228959 [ Linux ] virtual/scroll-unification/fast/scroll-snap/snaps-after-wheel-scrolling-single-tick.html [ Failure Pass ] @@ -7371,3 +7373,6 @@ crbug.com/835943 http/tests/appcache/non-html.xhtml [ Crash Failure Pass Timeout ] crbug.com/1181886 external/wpt/pointerevents/pointerevent_movementxy.html?* [ Failure Pass Timeout ] crbug.com/1161244 external/wpt/html/cross-origin-opener-policy/popup-coop-by-sw-from-coop.https.html?* [ Pass Timeout ] + +# Sheriff 2021-07-19 +crbug.com/1230534 [ Linux ] external/wpt/webrtc/simulcast/vp8.https.html [ Pass Timeout ]
diff --git a/third_party/blink/web_tests/WebGPUExpectations b/third_party/blink/web_tests/WebGPUExpectations index a1a19341..388d301 100644 --- a/third_party/blink/web_tests/WebGPUExpectations +++ b/third_party/blink/web_tests/WebGPUExpectations
@@ -54,7 +54,6 @@ [ Linux ] wpt_internal/webgpu/cts.html?q=webgpu:web_platform,copyToTexture,canvas:copy_contents_from_gl_context_canvas:* [ Timeout Crash ] wpt_internal/webgpu/cts.html?q=webgpu:api,validation,createTexture:sampleCount,various_sampleCount_with_all_formats:* [ Failure Crash ] -crbug.com/dawn/759 [ Linux ] wpt_internal/webgpu/cts.html?q=webgpu:api,operation,rendering,draw:vertex_attributes,basic:* [ Failure ] crbug.com/1203413 [ Mac ] wpt_internal/webgpu/cts.html?worker=1&q=webgpu:api,validation,buffer,mapping:* [ Crash ] # Test completes and passes, but then somehow times out consistently. @@ -168,6 +167,8 @@ crbug.com/dawn/796 wpt_internal/webgpu/cts.html?q=webgpu:api,validation,createBindGroupLayout:max_resources_per_stage,in_pipeline_layout:* [ Failure ] # maxColorAttachments 4 -> 8 crbug.com/dawn/796 wpt_internal/webgpu/cts.html?q=webgpu:api,validation,render_pass_descriptor:OOB_color_attachment_indices_are_handled:* [ Failure ] +# maxInterStageShaderComponents 64 -> 60 (crbug.com/dawn/759 [ Linux ][ Failure ] on NVIDIA will be recovered after the tests are fixed) +crbug.com/dawn/802 wpt_internal/webgpu/cts.html?q=webgpu:api,operation,rendering,draw:vertex_attributes,basic:* [ Skip ] ### ### Test bugs (fixed upstream)
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index febaa40e..672b4f99 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -512,6 +512,13 @@ ] ], "crashtests": { + "multicol-cached-consumed-bsize-crash.html": [ + "f82bddfef1c1f7f9f32abeb0dad4a215db807f9a", + [ + null, + {} + ] + ], "multicol-dynamic-contain-crash.html": [ "e20a6e70e32c911856b2ef44cc4c1e8ac1694d18", [ @@ -266954,7 +266961,7 @@ }, "offscreen": { "META.yml": [ - "d3e4c387e8b5b9d27ea3dea6febdc1d9a662e4f0", + "d0524194c9186da948d150da7b36f0f1144a61f9", [] ], "manual": { @@ -267092,6 +267099,16 @@ "31bf7882298ab07a8c62aa47d0f90533c6dc8a75", [] ] + }, + "the-offscreen-canvas": { + "2d-getcontext-options.any-expected.txt": [ + "5451d9c75a2a03f6ab2ed11abc88d60a6fe14d2e", + [] + ], + "2d-getcontext-options.any.worker-expected.txt": [ + "5451d9c75a2a03f6ab2ed11abc88d60a6fe14d2e", + [] + ] } }, "resources": { @@ -267162,7 +267179,7 @@ [] ], "spec.yaml": [ - "9ccadf7b9293253f56a79f02149d2fe360a59677", + "d8397ee94b1f169f502404c223139fee86cf4721", [] ], "templates-offscreen.yaml": [ @@ -267240,7 +267257,7 @@ [] ], "the-canvas-element.yaml": [ - "ec4c4e6d07bf605dea1820d3ebdce98aa8605676", + "5abee0300771f18fa648f5413bad6f2e7e8618d5", [] ], "the-canvas-state.yaml": [ @@ -267314,7 +267331,7 @@ [] ], "the-offscreen-canvas.yaml": [ - "2ca8f9a9587ea0a4d35c6db122f0d2aad94ed986", + "2bffbf2a9726d509c298cc52cd75bdee525f39b9", [] ], "transformations.yaml": [ @@ -273920,6 +273937,10 @@ ] }, "the-canvas-element": { + "2d-getcontext-options-expected.txt": [ + "b08b3ed5a64478c70273e79716716169f45fe633", + [] + ], "2d.scaled.png": [ "875407769ff19385c8be8b1dfd4eafc8a2e285be", [] @@ -390908,7 +390929,7 @@ ] }, "about-blank.https.sub.html": [ - "edc98b363e46471b3e5db54b6b5a0b827dbb0a6d", + "556d528aa05e5c08f624cddd1fd226205ce7731a", [ null, {} @@ -410416,6 +410437,17 @@ ] }, "the-offscreen-canvas": { + "2d-getcontext-options.any.js": [ + "c530ed4bc01a4f6cd01a36f3f3fae14186a662ff", + [ + "html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any.html", + {} + ], + [ + "html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any.worker.html", + {} + ] + ], "2d.canvas.readonly.html": [ "b1760e62c6f83aad782961750a241a71c44b7f15", [ @@ -410458,17 +410490,31 @@ {} ] ], - "2d.getcontext.extraargs.html": [ - "0cc3052ea3caa6c7777cbb5558a4cd3feb0cddee", + "2d.getcontext.extraargs.cache.html": [ + "e288ed408cc32dda1d93b47aa8a72e1997ca8373", [ null, {} ] ], - "2d.getcontext.extraargs.worker.js": [ - "9f9eeb06327710af87d510a1d58b6ab9d38b8c9b", + "2d.getcontext.extraargs.cache.worker.js": [ + "3b22e2f8f4c73ab828bd5d11a30b65aea83e3c58", [ - "html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.worker.html", + "html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.cache.worker.html", + {} + ] + ], + "2d.getcontext.extraargs.create.html": [ + "c71c239579e9ea3cd1aa1a5c3b5a5901f5e86965", + [ + null, + {} + ] + ], + "2d.getcontext.extraargs.create.worker.js": [ + "1504256fd0221b02d2ed107dc3c8d59cc7d46275", + [ + "html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.create.worker.html", {} ] ], @@ -418636,6 +418682,13 @@ ] }, "the-canvas-element": { + "2d-getcontext-options.html": [ + "748513ab584823ee5ced22f4929bb53fc77ac35a", + [ + null, + {} + ] + ], "2d.canvas.context.html": [ "b9d26011e283e7cf07470e51d6f0857a32e7af65", [ @@ -418664,8 +418717,15 @@ {} ] ], - "2d.getcontext.extraargs.html": [ - "38867fbeb5e262755786c52690f1e975e238ae08", + "2d.getcontext.extraargs.cache.html": [ + "18d700645166611b0891d53301bef31c62c14ad1", + [ + null, + {} + ] + ], + "2d.getcontext.extraargs.create.html": [ + "980d1036953d2187fb4622772b96bd88f573c044", [ null, {} @@ -421583,6 +421643,13 @@ {} ] ], + "button-submit-remove-jssubmit.html": [ + "6e71d958d6c4614aff586b4f2ba3f69e95d4ec0b", + [ + null, + {} + ] + ], "button-type-enumerated-ascii-case-insensitive.html": [ "30a2c24a80bab390c3401ee70c8bdc985cd8a21d", [ @@ -422012,6 +422079,13 @@ {} ] ], + "input-submit-remove-jssubmit.html": [ + "f992ff9ed54d4bde669f45d3b8b725fd5a6e86a5", + [ + null, + {} + ] + ], "input-type-button.html": [ "0f269355a5116b177395ccb34abcf7093c2b2eba", [ @@ -458338,7 +458412,7 @@ ], "inheritance": { "iframe-inheritance-about-blank.html": [ - "60f91a5e47b431feb8784a650a8c6ad304e904f8", + "fc7d39a4cf1c2a63728860e2f37f2962e8bf244f", [ null, {}
diff --git a/third_party/blink/web_tests/external/wpt/css/css-multicol/crashtests/multicol-cached-consumed-bsize-crash.html b/third_party/blink/web_tests/external/wpt/css/css-multicol/crashtests/multicol-cached-consumed-bsize-crash.html new file mode 100644 index 0000000..f82bddf --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-multicol/crashtests/multicol-cached-consumed-bsize-crash.html
@@ -0,0 +1,15 @@ +<link rel="help" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1715098"> +<style> +:not(table) { + column-width: 0; + margin-right: 91%; +} +#a { + column-span: all; + display: -webkit-box; +} +</style> +<textarea>a</textarea> +<del>a</del> +<q style="float: left">a</q> +<br id="a"></br>
diff --git a/third_party/blink/web_tests/external/wpt/file-system-access/resources/message-target.js b/third_party/blink/web_tests/external/wpt/file-system-access/resources/message-target.js index 6fe3ba4..211caeb 100644 --- a/third_party/blink/web_tests/external/wpt/file-system-access/resources/message-target.js +++ b/third_party/blink/web_tests/external/wpt/file-system-access/resources/message-target.js
@@ -108,8 +108,8 @@ // success to the sender. let success = true; try { - //TODO(fivedots): Close access handle once the method is available. - await message_data.file_handle.createSyncAccessHandle(); + const access_handle = await message_data.file_handle.createSyncAccessHandle(); + await access_handle.close(); } catch (error) { success = false; }
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub.html b/third_party/blink/web_tests/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub.html index edc98b36..556d528 100644 --- a/third_party/blink/web_tests/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub.html +++ b/third_party/blink/web_tests/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub.html
@@ -31,8 +31,7 @@ testGetter(1, false, "child2"); async function insertAboutBlankIframe() { - const iframe = document.createElement("iframe"); - document.body.append(iframe); + const iframe = await createBlankIframe(); // Now create and add the script, but don't navigate anywhere (since we want // to stay on the initial about:blank). @@ -52,4 +51,13 @@ await setBothDocumentDomains(iframe.contentWindow); } + +function createBlankIframe() { + const iframe = document.createElement("iframe"); + const promise = new Promise(resolve => { + iframe.addEventListener("load", resolve); + }); + document.body.append(iframe); + return promise; +} </script>
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/element/path-objects/2d.path.roundrect.nonfinite.html b/third_party/blink/web_tests/external/wpt/html/canvas/element/path-objects/2d.path.roundrect.nonfinite.html index ec3a7e41..91c1abf3 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/element/path-objects/2d.path.roundrect.nonfinite.html +++ b/third_party/blink/web_tests/external/wpt/html/canvas/element/path-objects/2d.path.roundrect.nonfinite.html
@@ -91,6 +91,18 @@ ctx.roundRect(0, 50, Infinity, Infinity, [Infinity]); ctx.roundRect(0, 50, Infinity, 1, [Infinity]); ctx.roundRect(0, 50, 1, Infinity, [Infinity]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, Infinity)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, -Infinity)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, NaN)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(Infinity, 10)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(-Infinity, 10)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(NaN, 10)]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: Infinity}]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: -Infinity}]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: NaN}]); +ctx.roundRect(0, 0, 100, 100, [{x: Infinity, y: 10}]); +ctx.roundRect(0, 0, 100, 100, [{x: -Infinity, y: 10}]); +ctx.roundRect(0, 0, 100, 100, [{x: NaN, y: 10}]); ctx.lineTo(100, 50); ctx.lineTo(0, 50); ctx.fillStyle = '#0f0';
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/element/path-objects/2d.path.roundrect.radius.negative.html b/third_party/blink/web_tests/external/wpt/html/canvas/element/path-objects/2d.path.roundrect.radius.negative.html index 37489d2..c7c0bda 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/element/path-objects/2d.path.roundrect.radius.negative.html +++ b/third_party/blink/web_tests/external/wpt/html/canvas/element/path-objects/2d.path.roundrect.radius.negative.html
@@ -21,6 +21,10 @@ assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [-1])}); assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [1, -1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(-1, 1), 1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(1, -1)])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: -1, y: 1}, 1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: 1, y: -1}])}); });
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/META.yml b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/META.yml index d3e4c38..d0524194 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/META.yml +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/META.yml
@@ -4,3 +4,4 @@ - annevk - kenrussell - fserb + - Cwiiis
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.nonfinite.html b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.nonfinite.html index de4613a..6d41959 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.nonfinite.html +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.nonfinite.html
@@ -92,6 +92,18 @@ ctx.roundRect(0, 50, Infinity, Infinity, [Infinity]); ctx.roundRect(0, 50, Infinity, 1, [Infinity]); ctx.roundRect(0, 50, 1, Infinity, [Infinity]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, Infinity)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, -Infinity)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, NaN)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(Infinity, 10)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(-Infinity, 10)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(NaN, 10)]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: Infinity}]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: -Infinity}]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: NaN}]); +ctx.roundRect(0, 0, 100, 100, [{x: Infinity, y: 10}]); +ctx.roundRect(0, 0, 100, 100, [{x: -Infinity, y: 10}]); +ctx.roundRect(0, 0, 100, 100, [{x: NaN, y: 10}]); ctx.lineTo(100, 50); ctx.lineTo(0, 50); ctx.fillStyle = '#0f0';
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.nonfinite.worker.js b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.nonfinite.worker.js index 8abb4439..64c770d 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.nonfinite.worker.js +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.nonfinite.worker.js
@@ -88,6 +88,18 @@ ctx.roundRect(0, 50, Infinity, Infinity, [Infinity]); ctx.roundRect(0, 50, Infinity, 1, [Infinity]); ctx.roundRect(0, 50, 1, Infinity, [Infinity]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, Infinity)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, -Infinity)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, NaN)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(Infinity, 10)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(-Infinity, 10)]); +ctx.roundRect(0, 0, 100, 100, [new DOMPoint(NaN, 10)]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: Infinity}]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: -Infinity}]); +ctx.roundRect(0, 0, 100, 100, [{x: 10, y: NaN}]); +ctx.roundRect(0, 0, 100, 100, [{x: Infinity, y: 10}]); +ctx.roundRect(0, 0, 100, 100, [{x: -Infinity, y: 10}]); +ctx.roundRect(0, 0, 100, 100, [{x: NaN, y: 10}]); ctx.lineTo(100, 50); ctx.lineTo(0, 50); ctx.fillStyle = '#0f0';
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.radius.negative.html b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.radius.negative.html index afedca2..a718cc5 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.radius.negative.html +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.radius.negative.html
@@ -22,6 +22,10 @@ assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [-1])}); assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [1, -1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(-1, 1), 1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(1, -1)])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: -1, y: 1}, 1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: 1, y: -1}])}); t.done(); });
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.radius.negative.worker.js b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.radius.negative.worker.js index 9fc4e8f..93e573b 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.radius.negative.worker.js +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/path-objects/2d.path.roundrect.radius.negative.worker.js
@@ -18,6 +18,10 @@ assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [-1])}); assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [1, -1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(-1, 1), 1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(1, -1)])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: -1, y: 1}, 1])}); +assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: 1, y: -1}])}); t.done(); });
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any-expected.txt b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any-expected.txt new file mode 100644 index 0000000..5451d9c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL 2d-getcontext-options assert_array_equals: order of operations (caching) lengths differ, expected array ["alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently"] length 5, got ["alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently", "alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently"] length 10 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any.js b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any.js new file mode 100644 index 0000000..c530ed4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any.js
@@ -0,0 +1,40 @@ +test(() => { + const expected = [ + "alpha", + "colorSpace", + "colorSpace toString", + "desynchronized", + "willReadFrequently", + ]; + const actual = []; + const options = { + get alpha() { + actual.push("alpha"); + return true; + }, + get willReadFrequently() { + actual.push("willReadFrequently"); + return false; + }, + get desynchronized() { + actual.push("desynchronized"); + return false; + }, + get colorSpace() { + actual.push("colorSpace"); + return { + toString() { + actual.push("colorSpace toString"); + return "srgb"; + } + }; + }, + }; + + const canvas = new OffscreenCanvas(100, 50); + const context = canvas.getContext('2d', options); + assert_not_equals(context, null, "context"); + assert_array_equals(actual, expected, "order of operations (creation)"); + assert_equals(canvas.getContext('2d', options), context, "cached context"); + assert_array_equals(actual, expected, "order of operations (caching)"); +});
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any.worker-expected.txt b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any.worker-expected.txt new file mode 100644 index 0000000..5451d9c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d-getcontext-options.any.worker-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL 2d-getcontext-options assert_array_equals: order of operations (caching) lengths differ, expected array ["alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently"] length 5, got ["alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently", "alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently"] length 10 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.cache.html b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.cache.html new file mode 100644 index 0000000..e288ed4 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.cache.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. --> +<title>OffscreenCanvas test: 2d.getcontext.extraargs.cache</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/html/canvas/resources/canvas-tests.js"></script> + +<h1>2d.getcontext.extraargs.cache</h1> +<p class="desc">The 2D context doesn't throw with extra getContext arguments (cached)</p> + + +<script> +var t = async_test("The 2D context doesn't throw with extra getContext arguments (cached)"); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var offscreenCanvas = new OffscreenCanvas(100, 50); +var ctx = offscreenCanvas.getContext('2d'); + +_assertDifferent(offscreenCanvas.getContext('2d', false, {}, [], 1, "2"), null, "offscreenCanvas.getContext('2d', false, {}, [], 1, \"2\")", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', 123), null, "offscreenCanvas.getContext('2d', 123)", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', "test"), null, "offscreenCanvas.getContext('2d', \"test\")", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', undefined), null, "offscreenCanvas.getContext('2d', undefined)", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', null), null, "offscreenCanvas.getContext('2d', null)", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', Symbol.hasInstance), null, "offscreenCanvas.getContext('2d', Symbol.hasInstance)", "null"); +t.done(); + +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.cache.worker.js b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.cache.worker.js new file mode 100644 index 0000000..3b22e2f8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.cache.worker.js
@@ -0,0 +1,28 @@ +// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. +// OffscreenCanvas test in a worker:2d.getcontext.extraargs.cache +// Description:The 2D context doesn't throw with extra getContext arguments (cached) +// Note: + +importScripts("/resources/testharness.js"); +importScripts("/html/canvas/resources/canvas-tests.js"); + +var t = async_test("The 2D context doesn't throw with extra getContext arguments (cached)"); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var offscreenCanvas = new OffscreenCanvas(100, 50); +var ctx = offscreenCanvas.getContext('2d'); + +_assertDifferent(offscreenCanvas.getContext('2d', false, {}, [], 1, "2"), null, "offscreenCanvas.getContext('2d', false, {}, [], 1, \"2\")", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', 123), null, "offscreenCanvas.getContext('2d', 123)", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', "test"), null, "offscreenCanvas.getContext('2d', \"test\")", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', undefined), null, "offscreenCanvas.getContext('2d', undefined)", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', null), null, "offscreenCanvas.getContext('2d', null)", "null"); +_assertDifferent(offscreenCanvas.getContext('2d', Symbol.hasInstance), null, "offscreenCanvas.getContext('2d', Symbol.hasInstance)", "null"); +t.done(); + +}); +done();
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.create.html b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.create.html new file mode 100644 index 0000000..c71c239 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.create.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. --> +<title>OffscreenCanvas test: 2d.getcontext.extraargs.create</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/html/canvas/resources/canvas-tests.js"></script> + +<h1>2d.getcontext.extraargs.create</h1> +<p class="desc">The 2D context doesn't throw with extra getContext arguments (new context)</p> + + +<script> +var t = async_test("The 2D context doesn't throw with extra getContext arguments (new context)"); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var offscreenCanvas = new OffscreenCanvas(100, 50); +var ctx = offscreenCanvas.getContext('2d'); + +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', false, {}, [], 1, "2"), null, "(new OffscreenCanvas(100, 50)).getContext('2d', false, {}, [], 1, \"2\")", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', 123), null, "(new OffscreenCanvas(100, 50)).getContext('2d', 123)", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', "test"), null, "(new OffscreenCanvas(100, 50)).getContext('2d', \"test\")", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', undefined), null, "(new OffscreenCanvas(100, 50)).getContext('2d', undefined)", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', null), null, "(new OffscreenCanvas(100, 50)).getContext('2d', null)", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', Symbol.hasInstance), null, "(new OffscreenCanvas(100, 50)).getContext('2d', Symbol.hasInstance)", "null"); +t.done(); + +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.create.worker.js b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.create.worker.js new file mode 100644 index 0000000..1504256 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.create.worker.js
@@ -0,0 +1,28 @@ +// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. +// OffscreenCanvas test in a worker:2d.getcontext.extraargs.create +// Description:The 2D context doesn't throw with extra getContext arguments (new context) +// Note: + +importScripts("/resources/testharness.js"); +importScripts("/html/canvas/resources/canvas-tests.js"); + +var t = async_test("The 2D context doesn't throw with extra getContext arguments (new context)"); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var offscreenCanvas = new OffscreenCanvas(100, 50); +var ctx = offscreenCanvas.getContext('2d'); + +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', false, {}, [], 1, "2"), null, "(new OffscreenCanvas(100, 50)).getContext('2d', false, {}, [], 1, \"2\")", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', 123), null, "(new OffscreenCanvas(100, 50)).getContext('2d', 123)", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', "test"), null, "(new OffscreenCanvas(100, 50)).getContext('2d', \"test\")", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', undefined), null, "(new OffscreenCanvas(100, 50)).getContext('2d', undefined)", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', null), null, "(new OffscreenCanvas(100, 50)).getContext('2d', null)", "null"); +_assertDifferent((new OffscreenCanvas(100, 50)).getContext('2d', Symbol.hasInstance), null, "(new OffscreenCanvas(100, 50)).getContext('2d', Symbol.hasInstance)", "null"); +t.done(); + +}); +done();
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.html b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.html deleted file mode 100644 index 0cc3052e..0000000 --- a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.html +++ /dev/null
@@ -1,33 +0,0 @@ -<!DOCTYPE html> -<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. --> -<title>OffscreenCanvas test: 2d.getcontext.extraargs</title> -<script src="/resources/testharness.js"></script> -<script src="/resources/testharnessreport.js"></script> -<script src="/html/canvas/resources/canvas-tests.js"></script> - -<h1>2d.getcontext.extraargs</h1> -<p class="desc">The 2D context ignores extra getContext arguments</p> - - -<script> -var t = async_test("The 2D context ignores extra getContext arguments"); -var t_pass = t.done.bind(t); -var t_fail = t.step_func(function(reason) { - throw reason; -}); -t.step(function() { - -var offscreenCanvas = new OffscreenCanvas(100, 50); -var ctx = offscreenCanvas.getContext('2d'); - -var offscreenCanvas2 = new OffscreenCanvas(100, 50); -_assertDifferent(offscreenCanvas2.getContext('2d', false, {}, [], 1, "2"), null, "offscreenCanvas2.getContext('2d', false, {}, [], 1, \"2\")", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', 123), null, "offscreenCanvas2.getContext('2d', 123)", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', "test"), null, "offscreenCanvas2.getContext('2d', \"test\")", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', undefined), null, "offscreenCanvas2.getContext('2d', undefined)", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', null), null, "offscreenCanvas2.getContext('2d', null)", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', Symbol.hasInstance), null, "offscreenCanvas2.getContext('2d', Symbol.hasInstance)", "null"); -t.done(); - -}); -</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.worker.js b/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.worker.js deleted file mode 100644 index 9f9eeb0..0000000 --- a/third_party/blink/web_tests/external/wpt/html/canvas/offscreen/the-offscreen-canvas/2d.getcontext.extraargs.worker.js +++ /dev/null
@@ -1,29 +0,0 @@ -// DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. -// OffscreenCanvas test in a worker:2d.getcontext.extraargs -// Description:The 2D context ignores extra getContext arguments -// Note: - -importScripts("/resources/testharness.js"); -importScripts("/html/canvas/resources/canvas-tests.js"); - -var t = async_test("The 2D context ignores extra getContext arguments"); -var t_pass = t.done.bind(t); -var t_fail = t.step_func(function(reason) { - throw reason; -}); -t.step(function() { - -var offscreenCanvas = new OffscreenCanvas(100, 50); -var ctx = offscreenCanvas.getContext('2d'); - -var offscreenCanvas2 = new OffscreenCanvas(100, 50); -_assertDifferent(offscreenCanvas2.getContext('2d', false, {}, [], 1, "2"), null, "offscreenCanvas2.getContext('2d', false, {}, [], 1, \"2\")", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', 123), null, "offscreenCanvas2.getContext('2d', 123)", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', "test"), null, "offscreenCanvas2.getContext('2d', \"test\")", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', undefined), null, "offscreenCanvas2.getContext('2d', undefined)", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', null), null, "offscreenCanvas2.getContext('2d', null)", "null"); -_assertDifferent(offscreenCanvas2.getContext('2d', Symbol.hasInstance), null, "offscreenCanvas2.getContext('2d', Symbol.hasInstance)", "null"); -t.done(); - -}); -done();
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/tools/spec.yaml b/third_party/blink/web_tests/external/wpt/html/canvas/tools/spec.yaml index 9ccadf7..d8397ee 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/tools/spec.yaml +++ b/third_party/blink/web_tests/external/wpt/html/canvas/tools/spec.yaml
@@ -38,7 +38,7 @@ - id: context.2d text: "When the getContext() method of a canvas element is to return a new object for the contextId 2d, the user agent *must* return a new CanvasRenderingContext2D object." - id: context.2d.extraargs - text: "When the getContext() method of a canvas element is to return a new object for the contextId 2d, the user agent *must* return a new CanvasRenderingContext2D object. Any additional arguments are ignored." + text: "If options is not an object, then set options to null." - id: toDataURL.noarguments text: "When a user agent is to create a serialization of the image as a file, <...> if there are no arguments, in the PNG format."
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/path-objects.yaml b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/path-objects.yaml index 5225600..1eb0ac1 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/path-objects.yaml +++ b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/path-objects.yaml
@@ -1779,6 +1779,18 @@ ctx.moveTo(0, 0); ctx.lineTo(100, 0); @nonfinite ctx.roundRect(<0 Infinity -Infinity NaN>, <50 Infinity -Infinity NaN>, <1 Infinity -Infinity NaN>, <1 Infinity -Infinity NaN>, <[0] [Infinity] [-Infinity] [NaN] [Infinity,0] [-Infinity,0] [NaN,0] [0,Infinity] [0,-Infinity] [0,NaN] [Infinity,0,0] [-Infinity,0,0] [NaN,0,0] [0,Infinity,0] [0,-Infinity,0] [0,NaN,0] [0,0,Infinity] [0,0,-Infinity] [0,0,NaN] [Infinity,0,0,0] [-Infinity,0,0,0] [NaN,0,0,0] [0,Infinity,0,0] [0,-Infinity,0,0] [0,NaN,0,0] [0,0,Infinity,0] [0,0,-Infinity,0] [0,0,NaN,0] [0,0,0,Infinity] [0,0,0,-Infinity] [0,0,0,NaN]>); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, Infinity)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, -Infinity)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, NaN)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(Infinity, 10)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(-Infinity, 10)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(NaN, 10)]); + ctx.roundRect(0, 0, 100, 100, [{x: 10, y: Infinity}]); + ctx.roundRect(0, 0, 100, 100, [{x: 10, y: -Infinity}]); + ctx.roundRect(0, 0, 100, 100, [{x: 10, y: NaN}]); + ctx.roundRect(0, 0, 100, 100, [{x: Infinity, y: 10}]); + ctx.roundRect(0, 0, 100, 100, [{x: -Infinity, y: 10}]); + ctx.roundRect(0, 0, 100, 100, [{x: NaN, y: 10}]); ctx.lineTo(100, 50); ctx.lineTo(0, 50); ctx.fillStyle = '#0f0'; @@ -2424,6 +2436,10 @@ code: | assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [-1])}); assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [1, -1])}); + assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(-1, 1), 1])}); + assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(1, -1)])}); + assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: -1, y: 1}, 1])}); + assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: 1, y: -1}])}); - name: 2d.path.ellipse.basics desc: Verify canvas throws error when drawing ellipse with negative radii.
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/the-canvas-element.yaml b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/the-canvas-element.yaml index ec4c4e6..5abee03 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/the-canvas-element.yaml +++ b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/element/the-canvas-element.yaml
@@ -20,8 +20,20 @@ @assert canvas.getContext('null') === null; @assert canvas.getContext('undefined') === null; -- name: 2d.getcontext.extraargs - desc: The 2D context ignores extra getContext arguments +- name: 2d.getcontext.extraargs.create + desc: The 2D context doesn't throw with extra getContext arguments (new context) + testing: + - context.2d.extraargs + code: | + @assert document.createElement("canvas").getContext('2d', false, {}, [], 1, "2") !== null; + @assert document.createElement("canvas").getContext('2d', 123) !== null; + @assert document.createElement("canvas").getContext('2d', "test") !== null; + @assert document.createElement("canvas").getContext('2d', undefined) !== null; + @assert document.createElement("canvas").getContext('2d', null) !== null; + @assert document.createElement("canvas").getContext('2d', Symbol.hasInstance) !== null; + +- name: 2d.getcontext.extraargs.cache + desc: The 2D context doesn't throw with extra getContext arguments (cached) testing: - context.2d.extraargs code: |
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/path-objects.yaml b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/path-objects.yaml index ea97135..1e221f9 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/path-objects.yaml +++ b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/path-objects.yaml
@@ -1755,6 +1755,18 @@ ctx.moveTo(0, 0); ctx.lineTo(100, 0); @nonfinite ctx.roundRect(<0 Infinity -Infinity NaN>, <50 Infinity -Infinity NaN>, <1 Infinity -Infinity NaN>, <1 Infinity -Infinity NaN>, <[0] [Infinity] [-Infinity] [NaN] [Infinity,0] [-Infinity,0] [NaN,0] [0,Infinity] [0,-Infinity] [0,NaN] [Infinity,0,0] [-Infinity,0,0] [NaN,0,0] [0,Infinity,0] [0,-Infinity,0] [0,NaN,0] [0,0,Infinity] [0,0,-Infinity] [0,0,NaN] [Infinity,0,0,0] [-Infinity,0,0,0] [NaN,0,0,0] [0,Infinity,0,0] [0,-Infinity,0,0] [0,NaN,0,0] [0,0,Infinity,0] [0,0,-Infinity,0] [0,0,NaN,0] [0,0,0,Infinity] [0,0,0,-Infinity] [0,0,0,NaN]>); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, Infinity)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, -Infinity)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(10, NaN)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(Infinity, 10)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(-Infinity, 10)]); + ctx.roundRect(0, 0, 100, 100, [new DOMPoint(NaN, 10)]); + ctx.roundRect(0, 0, 100, 100, [{x: 10, y: Infinity}]); + ctx.roundRect(0, 0, 100, 100, [{x: 10, y: -Infinity}]); + ctx.roundRect(0, 0, 100, 100, [{x: 10, y: NaN}]); + ctx.roundRect(0, 0, 100, 100, [{x: Infinity, y: 10}]); + ctx.roundRect(0, 0, 100, 100, [{x: -Infinity, y: 10}]); + ctx.roundRect(0, 0, 100, 100, [{x: NaN, y: 10}]); ctx.lineTo(100, 50); ctx.lineTo(0, 50); ctx.fillStyle = '#0f0'; @@ -2435,6 +2447,10 @@ code: | assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [-1])}); assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [1, -1])}); + assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(-1, 1), 1])}); + assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [new DOMPoint(1, -1)])}); + assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: -1, y: 1}, 1])}); + assert_throws_js(RangeError, () => { ctx.roundRect(0, 0, 0, 0, [{x: 1, y: -1}])}); t.done(); - name: 2d.path.fill.overlap
diff --git a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/the-offscreen-canvas.yaml b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/the-offscreen-canvas.yaml index 2ca8f9a..2bffbf2 100644 --- a/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/the-offscreen-canvas.yaml +++ b/third_party/blink/web_tests/external/wpt/html/canvas/tools/yaml/offscreen/the-offscreen-canvas.yaml
@@ -27,18 +27,30 @@ @assert offscreenCanvas2.getContext('2d') !== null; t.done(); -- name: 2d.getcontext.extraargs - desc: The 2D context ignores extra getContext arguments +- name: 2d.getcontext.extraargs.create + desc: The 2D context doesn't throw with extra getContext arguments (new context) testing: - context.2d.extraargs code: | - var offscreenCanvas2 = new OffscreenCanvas(100, 50); - @assert offscreenCanvas2.getContext('2d', false, {}, [], 1, "2") !== null; - @assert offscreenCanvas2.getContext('2d', 123) !== null; - @assert offscreenCanvas2.getContext('2d', "test") !== null; - @assert offscreenCanvas2.getContext('2d', undefined) !== null; - @assert offscreenCanvas2.getContext('2d', null) !== null; - @assert offscreenCanvas2.getContext('2d', Symbol.hasInstance) !== null; + @assert (new OffscreenCanvas(100, 50)).getContext('2d', false, {}, [], 1, "2") !== null; + @assert (new OffscreenCanvas(100, 50)).getContext('2d', 123) !== null; + @assert (new OffscreenCanvas(100, 50)).getContext('2d', "test") !== null; + @assert (new OffscreenCanvas(100, 50)).getContext('2d', undefined) !== null; + @assert (new OffscreenCanvas(100, 50)).getContext('2d', null) !== null; + @assert (new OffscreenCanvas(100, 50)).getContext('2d', Symbol.hasInstance) !== null; + t.done(); + +- name: 2d.getcontext.extraargs.cache + desc: The 2D context doesn't throw with extra getContext arguments (cached) + testing: + - context.2d.extraargs + code: | + @assert offscreenCanvas.getContext('2d', false, {}, [], 1, "2") !== null; + @assert offscreenCanvas.getContext('2d', 123) !== null; + @assert offscreenCanvas.getContext('2d', "test") !== null; + @assert offscreenCanvas.getContext('2d', undefined) !== null; + @assert offscreenCanvas.getContext('2d', null) !== null; + @assert offscreenCanvas.getContext('2d', Symbol.hasInstance) !== null; t.done(); - name: 2d.getcontext.unique
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d-getcontext-options-expected.txt b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d-getcontext-options-expected.txt new file mode 100644 index 0000000..b08b3ed5a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d-getcontext-options-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Options conversion for getContext("2d") assert_array_equals: order of operations (caching) lengths differ, expected array ["alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently"] length 5, got ["alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently", "alpha", "colorSpace", "colorSpace toString", "desynchronized", "willReadFrequently"] length 10 +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d-getcontext-options.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d-getcontext-options.html new file mode 100644 index 0000000..748513a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d-getcontext-options.html
@@ -0,0 +1,46 @@ +<!DOCTYPE html> +<title>Options conversion for getContext("2d")</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +test(() => { + const expected = [ + "alpha", + "colorSpace", + "colorSpace toString", + "desynchronized", + "willReadFrequently", + ]; + const actual = []; + const options = { + get alpha() { + actual.push("alpha"); + return true; + }, + get willReadFrequently() { + actual.push("willReadFrequently"); + return false; + }, + get desynchronized() { + actual.push("desynchronized"); + return false; + }, + get colorSpace() { + actual.push("colorSpace"); + return { + toString() { + actual.push("colorSpace toString"); + return "srgb"; + } + }; + }, + }; + + const canvas = document.createElement("canvas"); + const context = canvas.getContext('2d', options); + assert_not_equals(context, null, "context"); + assert_array_equals(actual, expected, "order of operations (creation)"); + assert_equals(canvas.getContext('2d', options), context, "cached context"); + assert_array_equals(actual, expected, "order of operations (caching)"); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.cache.html similarity index 81% rename from third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.html rename to third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.cache.html index 38867fbe..18d70064 100644 --- a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.html +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.cache.html
@@ -1,14 +1,14 @@ <!DOCTYPE html> <!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. --> -<title>Canvas test: 2d.getcontext.extraargs</title> +<title>Canvas test: 2d.getcontext.extraargs.cache</title> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/html/canvas/resources/canvas-tests.js"></script> <link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css"> <body class="show_output"> -<h1>2d.getcontext.extraargs</h1> -<p class="desc">The 2D context ignores extra getContext arguments</p> +<h1>2d.getcontext.extraargs.cache</h1> +<p class="desc">The 2D context doesn't throw with extra getContext arguments (cached)</p> <p class="output">Actual output:</p> @@ -16,7 +16,7 @@ <ul id="d"></ul> <script> -var t = async_test("The 2D context ignores extra getContext arguments"); +var t = async_test("The 2D context doesn't throw with extra getContext arguments (cached)"); _addTest(function(canvas, ctx) { _assertDifferent(canvas.getContext('2d', false, {}, [], 1, "2"), null, "canvas.getContext('2d', false, {}, [], 1, \"2\")", "null");
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.create.html b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.create.html new file mode 100644 index 0000000..980d103 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/embedded-content/the-canvas-element/2d.getcontext.extraargs.create.html
@@ -0,0 +1,32 @@ +<!DOCTYPE html> +<!-- DO NOT EDIT! This test has been generated by /html/canvas/tools/gentest.py. --> +<title>Canvas test: 2d.getcontext.extraargs.create</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/html/canvas/resources/canvas-tests.js"></script> +<link rel="stylesheet" href="/html/canvas/resources/canvas-tests.css"> +<body class="show_output"> + +<h1>2d.getcontext.extraargs.create</h1> +<p class="desc">The 2D context doesn't throw with extra getContext arguments (new context)</p> + + +<p class="output">Actual output:</p> +<canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas> + +<ul id="d"></ul> +<script> +var t = async_test("The 2D context doesn't throw with extra getContext arguments (new context)"); +_addTest(function(canvas, ctx) { + +_assertDifferent(document.createElement("canvas").getContext('2d', false, {}, [], 1, "2"), null, "document.createElement(\"canvas\").getContext('2d', false, {}, [], 1, \"2\")", "null"); +_assertDifferent(document.createElement("canvas").getContext('2d', 123), null, "document.createElement(\"canvas\").getContext('2d', 123)", "null"); +_assertDifferent(document.createElement("canvas").getContext('2d', "test"), null, "document.createElement(\"canvas\").getContext('2d', \"test\")", "null"); +_assertDifferent(document.createElement("canvas").getContext('2d', undefined), null, "document.createElement(\"canvas\").getContext('2d', undefined)", "null"); +_assertDifferent(document.createElement("canvas").getContext('2d', null), null, "document.createElement(\"canvas\").getContext('2d', null)", "null"); +_assertDifferent(document.createElement("canvas").getContext('2d', Symbol.hasInstance), null, "document.createElement(\"canvas\").getContext('2d', Symbol.hasInstance)", "null"); + + +}); +</script> +
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-submit-remove-jssubmit.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-submit-remove-jssubmit.html new file mode 100644 index 0000000..6e71d95 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-button-element/button-submit-remove-jssubmit.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<link rel="help" href="https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-2"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<iframe name="frame" id="frame"></iframe> +<form id="form" target="frame" action="does_not_exist.html"> + <input id="input" name="name" value="foo"> + <button id="submitbutton" type="submit">Submit</button> +</form> + +<script> +async_test(t => { + window.addEventListener('load', () => { + const frame = document.getElementById('frame'); + frame.addEventListener('load', t.step_func_done(() => { + const expected = (new URL("does_not_exist.html?name=bar", location.href)).href; + assert_equals(frame.contentWindow.location.href, expected); + })); + + const form = document.getElementById('form'); + const input = document.getElementById('input'); + const submitButton = document.getElementById('submitbutton'); + submitButton.addEventListener('click', event => { + submitButton.remove(); + form.submit(); + input.value = "bar"; + form.submit(); + input.value = "baz"; + }); + + submitButton.click(); + }); +}, 'This test will pass if a form navigation successfully occurs when clicking a <button type=submit> element with a onclick event handler which removes the button and then calls form.submit().'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-input-element/input-submit-remove-jssubmit.html b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-input-element/input-submit-remove-jssubmit.html new file mode 100644 index 0000000..f992ff9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/semantics/forms/the-input-element/input-submit-remove-jssubmit.html
@@ -0,0 +1,36 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<link rel="help" href="https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-2"> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> + +<iframe name="frame" id="frame"></iframe> +<form id="form" target="frame" action="does_not_exist.html"> + <input id="input" name="name" value="foo"> + <input id="submitbutton" type="submit"></input> +</form> + +<script> +async_test(t => { + window.addEventListener('load', () => { + const frame = document.getElementById('frame'); + frame.addEventListener('load', t.step_func_done(() => { + const expected = (new URL("does_not_exist.html?name=bar", location.href)).href; + assert_equals(frame.contentWindow.location.href, expected); + })); + + const form = document.getElementById('form'); + const input = document.getElementById('input'); + const submitButton = document.getElementById('submitbutton'); + submitButton.addEventListener('click', event => { + submitButton.remove(); + form.submit(); + input.value = "bar"; + form.submit(); + input.value = "baz"; + }); + + submitButton.click(); + }); +}, 'This test will pass if a form navigation successfully occurs when clicking a <input type=submit> element with a onclick event handler which removes the input and then calls form.submit().'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/mediacapture-insertable-streams/MediaStreamTrackGenerator-video.https.html b/third_party/blink/web_tests/external/wpt/mediacapture-insertable-streams/MediaStreamTrackGenerator-video.https.html index a1289b60..3042f038 100644 --- a/third_party/blink/web_tests/external/wpt/mediacapture-insertable-streams/MediaStreamTrackGenerator-video.https.html +++ b/third_party/blink/web_tests/external/wpt/mediacapture-insertable-streams/MediaStreamTrackGenerator-video.https.html
@@ -84,25 +84,25 @@ video.srcObject = new MediaStream([generator]); video.play(); - // Allow async setup of the track generator and stream. - await new Promise(r => t.step_timeout(r, 1)); + // Wait for the video element to be connected to the generator and + // generate the frame. + video.onloadstart = () => generator.writable.getWriter().write(videoFrame); - await generator.writable.getWriter().write(videoFrame); - - await t.step_wait(() => video.currentTime > 0, "video has played"); - - - const canvas = document.createElement("canvas"); - canvas.width = originalWidth; - canvas.height = originalHeight; - const context = canvas.getContext('2d'); - context.drawImage(video, 0, 0); - // Pick a pixel in the centre of the video and check that it has the colour of the frame provided. - const pixel = context.getImageData(videoFrame.displayWidth/2, videoFrame.displayHeight/2, 1, 1); - assertPixel(t, pixel.data, pixelColour); + return new Promise((resolve)=> { + video.ontimeupdate = t.step_func(() => { + const canvas = document.createElement("canvas"); + canvas.width = originalWidth; + canvas.height = originalHeight; + const context = canvas.getContext('2d'); + context.drawImage(video, 0, 0); + // Pick a pixel in the centre of the video and check that it has the colour of the frame provided. + const pixel = context.getImageData(videoFrame.displayWidth/2, videoFrame.displayHeight/2, 1, 1); + assertPixel(t, pixel.data, pixelColour); + resolve(); + }); + }); }, 'Tests that frames are actually rendered correctly in a stream used for a video element.'); - promise_test(async t => { const generator = new MediaStreamTrackGenerator("video"); t.add_cleanup(() => generator.stop());
diff --git a/third_party/blink/web_tests/external/wpt/referrer-policy/generic/inheritance/iframe-inheritance-about-blank.html b/third_party/blink/web_tests/external/wpt/referrer-policy/generic/inheritance/iframe-inheritance-about-blank.html index 60f91a5..fc7d39a 100644 --- a/third_party/blink/web_tests/external/wpt/referrer-policy/generic/inheritance/iframe-inheritance-about-blank.html +++ b/third_party/blink/web_tests/external/wpt/referrer-policy/generic/inheritance/iframe-inheritance-about-blank.html
@@ -63,42 +63,45 @@ }); const iframe = document.createElement("iframe"); + +iframe.addEventListener("load", function() { + const iframe_script = iframe.contentDocument.createElement('script'); + iframe_script.textContent = ` + // Test fetch() API with default "client" referrer. + fetch("${location.origin}/common/security-features/subresource/xhr.py?name=testFetchClientReferrer") + .then(r => r.json()) + .then(j => { + top.postMessage({test: "testFetchClientReferrer", referrer: j.headers.referer}, "*") + }).catch(e => { + top.postMessage({test: "testFetchClientReferrer", referrer: "FAILURE"}, "*"); + }); + + // Test fetch() API with custom URL referrer. + fetch("${location.origin}/common/security-features/subresource/xhr.py?name=URL", + {referrer: "${location.href}/custom"}) + .then(r => r.json()) + .then(j => { + top.postMessage({test: "testFetchURLReferrer", referrer: j.headers.referer}, "*") + }).catch(e => { + top.postMessage({test: "testFetchURLReferrer", referrer: "FAILURE"}, "*"); + }); + + // Test document.referrer. + top.postMessage({test: "testDocumentReferrer", referrer: document.referrer}, "*"); + + // Test a subresource being fetched by the iframe. + const subresource_script = document.createElement('script'); + subresource_script.src = "${location.origin}/common/security-features/subresource/referrer.py"; + subresource_script.onload = e => { + top.postMessage({test: "testSubresource", referrer: window.referrer}, "*"); + } + subresource_script.onerror = function(e) { + top.postMessage({test: "testSubresource", referrer: "FAILURE"}, "*"); + }; + document.head.appendChild(subresource_script); + `; + iframe.contentDocument.body.appendChild(iframe_script); +}); + document.body.appendChild(iframe); - -const iframe_script = iframe.contentDocument.createElement('script'); -iframe_script.textContent = ` - // Test fetch() API with default "client" referrer. - fetch("${location.origin}/common/security-features/subresource/xhr.py?name=testFetchClientReferrer") - .then(r => r.json()) - .then(j => { - top.postMessage({test: "testFetchClientReferrer", referrer: j.headers.referer}, "*") - }).catch(e => { - top.postMessage({test: "testFetchClientReferrer", referrer: "FAILURE"}, "*"); - }); - - // Test fetch() API with custom URL referrer. - fetch("${location.origin}/common/security-features/subresource/xhr.py?name=URL", - {referrer: "${location.href}/custom"}) - .then(r => r.json()) - .then(j => { - top.postMessage({test: "testFetchURLReferrer", referrer: j.headers.referer}, "*") - }).catch(e => { - top.postMessage({test: "testFetchURLReferrer", referrer: "FAILURE"}, "*"); - }); - - // Test document.referrer. - top.postMessage({test: "testDocumentReferrer", referrer: document.referrer}, "*"); - - // Test a subresource being fetched by the iframe. - const subresource_script = document.createElement('script'); - subresource_script.src = "${location.origin}/common/security-features/subresource/referrer.py"; - subresource_script.onload = e => { - top.postMessage({test: "testSubresource", referrer: window.referrer}, "*"); - } - subresource_script.onerror = function(e) { - top.postMessage({test: "testSubresource", referrer: "FAILURE"}, "*"); - }; - document.head.appendChild(subresource_script); -`; -iframe.contentDocument.body.appendChild(iframe_script); </script>
diff --git a/third_party/blink/web_tests/virtual/no-auto-wpt-origin-isolation/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub-expected.txt b/third_party/blink/web_tests/virtual/no-auto-wpt-origin-isolation/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub-expected.txt new file mode 100644 index 0000000..13cd7342 --- /dev/null +++ b/third_party/blink/web_tests/virtual/no-auto-wpt-origin-isolation/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub-expected.txt
@@ -0,0 +1,13 @@ +This is a testharness.js-based test. +Harness Error. harness_status.status = 1 , harness_status.message = TypeError: Cannot read properties of undefined (reading 'createElement') +NOTRUN parent to about:blank: message event must occur +NOTRUN parent to about:blank: setting document.domain must give sync access +NOTRUN about:blank to child2: messageerror event must occur +NOTRUN about:blank to child2: setting document.domain must not give sync access +NOTRUN child2 to about:blank: messageerror event must occur +NOTRUN child2 to about:blank: setting document.domain must not give sync access +NOTRUN parent: originAgentCluster must equal true +NOTRUN about:blank: originAgentCluster must equal true +NOTRUN child2: originAgentCluster must equal false +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/not-site-per-process/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub-expected.txt b/third_party/blink/web_tests/virtual/not-site-per-process/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub-expected.txt new file mode 100644 index 0000000..13cd7342 --- /dev/null +++ b/third_party/blink/web_tests/virtual/not-site-per-process/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/about-blank.https.sub-expected.txt
@@ -0,0 +1,13 @@ +This is a testharness.js-based test. +Harness Error. harness_status.status = 1 , harness_status.message = TypeError: Cannot read properties of undefined (reading 'createElement') +NOTRUN parent to about:blank: message event must occur +NOTRUN parent to about:blank: setting document.domain must give sync access +NOTRUN about:blank to child2: messageerror event must occur +NOTRUN about:blank to child2: setting document.domain must not give sync access +NOTRUN child2 to about:blank: messageerror event must occur +NOTRUN child2 to about:blank: setting document.domain must not give sync access +NOTRUN parent: originAgentCluster must equal true +NOTRUN about:blank: originAgentCluster must equal true +NOTRUN child2: originAgentCluster must equal false +Harness: the test ran to completion. +
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index a610081..d0cf979 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -539,7 +539,7 @@ 'chromium.memory': { 'Linux ASan LSan Builder': 'asan_lsan_release_trybot', - 'Linux CFI': 'cfi_full_cfi_icall_cfi_diag_goma_thin_lto_release_static_dcheck_always_on_goma', + 'Linux CFI': 'cfi_full_cfi_icall_cfi_diag_thin_lto_release_static_dcheck_always_on_goma', 'Linux Chromium OS ASan LSan Builder': 'asan_lsan_chromeos_release_trybot', 'Linux ChromiumOS MSan Builder': 'chromeos_msan_release_bot', 'Linux MSan Builder': 'msan_release_bot', @@ -1043,7 +1043,7 @@ 'linux-xenial-rel': 'gpu_tests_release_trybot_no_symbols_use_dummy_lastchange_code_coverage', 'linux_chromium_archive_rel_ng': 'release_bot', 'linux_chromium_asan_rel_ng': 'asan_lsan_release_trybot', - 'linux_chromium_cfi_rel_ng': 'cfi_full_cfi_icall_cfi_diag_goma_thin_lto_release_static_dcheck_always_on_goma', + 'linux_chromium_cfi_rel_ng': 'cfi_full_cfi_icall_cfi_diag_thin_lto_release_static_dcheck_always_on_goma', 'linux_chromium_chromeos_asan_rel_ng': 'asan_lsan_chromeos_release_trybot', 'linux_chromium_chromeos_msan_rel_ng': 'chromeos_msan_release_bot', 'linux_chromium_clobber_deterministic': 'release_trybot', @@ -1733,8 +1733,8 @@ 'cfi_full', 'cfi_icall', 'cfi_diag', 'cfi_recover', 'thin_lto', 'release', 'static', 'goma', ], - 'cfi_full_cfi_icall_cfi_diag_goma_thin_lto_release_static_dcheck_always_on_goma': [ - 'cfi_full', 'cfi_icall', 'cfi_diag', 'thin_lto', 'goma_thin_lto', 'release', 'static', 'dcheck_always_on', 'goma', + 'cfi_full_cfi_icall_cfi_diag_thin_lto_release_static_dcheck_always_on_goma': [ + 'cfi_full', 'cfi_icall', 'cfi_diag', 'thin_lto', 'release', 'static', 'dcheck_always_on', 'goma', ], 'chromeos_amd64-generic': [ @@ -3616,10 +3616,6 @@ 'gn_args': 'use_thin_lto=true', }, - 'goma_thin_lto': { - 'gn_args': 'use_goma_thin_lto=true', - }, - 'thin_lto_opt': { 'gn_args': 'use_thin_lto=true thin_lto_enable_optimizations=true', },
diff --git a/tools/mb/mb_config_expectations/chromium.memory.json b/tools/mb/mb_config_expectations/chromium.memory.json index 925c4c7..5f988715 100644 --- a/tools/mb/mb_config_expectations/chromium.memory.json +++ b/tools/mb/mb_config_expectations/chromium.memory.json
@@ -21,7 +21,6 @@ "use_cfi_diag": true, "use_cfi_icall": true, "use_goma": true, - "use_goma_thin_lto": true, "use_thin_lto": true } },
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.linux.json b/tools/mb/mb_config_expectations/tryserver.chromium.linux.json index e37fe57..c9eb7162 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.linux.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.linux.json
@@ -866,7 +866,6 @@ "use_cfi_diag": true, "use_cfi_icall": true, "use_goma": true, - "use_goma_thin_lto": true, "use_thin_lto": true } },
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 73a81d4..29a57c2 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -867,6 +867,14 @@ <description>Please enter the description of this user action.</description> </action> +<action name="Accel_NewIncognitoWindow"> + <owner>rhalavati@chromium.org</owner> + <owner>chrome-incognito@google.com</owner> + <description> + User pressed CMD+Shift+N to open a new Incognito window. + </description> +</action> + <action name="Accel_NewTab_T"> <owner>Please list the metric's owners. Add more owner tags as needed.</owner> <description>Please enter the description of this user action.</description>
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 0bb57bec..4ab432f 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -43164,6 +43164,9 @@ Freeze detection stopped after moving the hang report out of the Breakpad directory and into the |UTE| directory. </int> + <int value="2" label="After Crashpad DumpWithoutCrash"> + Freeze detection stopped after calling DumpWithCrash from Crashpad. + </int> </enum> <enum name="IOSMenuAction"> @@ -78258,6 +78261,9 @@ <int value="22" label="Manage Google account"/> <int value="23" label="Clear YouTube history"/> <int value="24" label="Change Google password"/> + <int value="25" label="Incognito-mode clear browsing data"/> + <int value="26" label="Close Incognito windows"/> + <int value="27" label="Play Chrome Dino game"/> </enum> <enum name="SuggestionsResponseState">
diff --git a/tools/metrics/histograms/histograms_xml/chrome/histograms.xml b/tools/metrics/histograms/histograms_xml/chrome/histograms.xml index d99908fa..852a977 100644 --- a/tools/metrics/histograms/histograms_xml/chrome/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/chrome/histograms.xml
@@ -157,6 +157,9 @@ <histogram name="ChromeColors.ColorApplied" enum="ChromeColorsInfo" expires_after="2021-08-22"> + <obsolete> + Removed 2021-07. + </obsolete> <owner>alexilin@chromium.org</owner> <owner>jkrcal@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/histograms_xml/simple/histograms.xml b/tools/metrics/histograms/histograms_xml/simple/histograms.xml index 8195107..89053fd 100644 --- a/tools/metrics/histograms/histograms_xml/simple/histograms.xml +++ b/tools/metrics/histograms/histograms_xml/simple/histograms.xml
@@ -22,7 +22,7 @@ <histograms> <histogram base="true" name="SimpleCache.CacheSizeOnInit" units="KB" - expires_after="M94"> + expires_after="2022-07-01"> <owner>jkarlin@chromium.org</owner> <owner>shivanisha@chromium.org</owner> <summary> @@ -70,7 +70,7 @@ </histogram> <histogram base="true" name="SimpleCache.CreationToIndex" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -80,7 +80,7 @@ </histogram> <histogram base="true" name="SimpleCache.CreationToIndexFail" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -103,7 +103,7 @@ </histogram> <histogram base="true" name="SimpleCache.DiskCloseLatency" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -113,7 +113,7 @@ </histogram> <histogram base="true" name="SimpleCache.DiskCreateLatency" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -123,7 +123,7 @@ </histogram> <histogram base="true" name="SimpleCache.DiskDoomLatency" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -133,7 +133,7 @@ </histogram> <histogram base="true" name="SimpleCache.DiskOpenLatency" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -143,7 +143,7 @@ </histogram> <histogram base="true" name="SimpleCache.DiskWriteLatency" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -153,7 +153,7 @@ </histogram> <histogram base="true" name="SimpleCache.EntryCreationTime" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -196,18 +196,25 @@ <histogram base="true" name="SimpleCache.Eviction.CacheSizeOnStart2" units="KB" expires_after="M85"> + <obsolete> + Removed in July 2021. + </obsolete> <owner>morlovich@chromium.org</owner> <summary>The size of the cache at the beginning of an eviction.</summary> </histogram> <histogram base="true" name="SimpleCache.Eviction.EntryCount" units="units" - expires_after="M85"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> + <owner>wanderview@chromium.org</owner> <summary>The number of entries to be erased in an eviction.</summary> </histogram> <histogram base="true" name="SimpleCache.Eviction.MaxCacheSizeOnStart2" units="KB" expires_after="M85"> + <obsolete> + Removed in July 2021. + </obsolete> <owner>morlovich@chromium.org</owner> <summary> The maximum allowed size of the cache at the beginning of an eviction. @@ -216,6 +223,9 @@ <histogram base="true" name="SimpleCache.Eviction.Result" enum="BooleanSuccess" expires_after="2021-07-01"> + <obsolete> + Removed in July 2021. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary>The result of an eviction.</summary> @@ -223,6 +233,9 @@ <histogram base="true" name="SimpleCache.Eviction.SizeOfEvicted2" units="KB" expires_after="2021-07-01"> + <obsolete> + Removed in July 2021. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary>The amount of memory freed in an eviction.</summary> @@ -230,27 +243,30 @@ <histogram base="true" name="SimpleCache.Eviction.SizeWhenDone2" units="KB" expires_after="2021-07-01"> + <obsolete> + Removed in July 2021. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary>The size of the cache after running an eviction.</summary> </histogram> <histogram base="true" name="SimpleCache.Eviction.TimeToDone" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary>Time spent completing an eviction.</summary> </histogram> <histogram base="true" name="SimpleCache.Eviction.TimeToSelectEntries" - units="ms" expires_after="2021-07-01"> + units="ms" expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary>Time spent selecting entries for eviction.</summary> </histogram> <histogram name="SimpleCache.FileDescriptorLimiterAction" - enum="SimpleCache.FileDescriptorLimiterOp" expires_after="2021-07-01"> + enum="SimpleCache.FileDescriptorLimiterOp" expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -261,7 +277,7 @@ </histogram> <histogram base="true" name="SimpleCache.HeaderSize" units="bytes" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -271,14 +287,14 @@ </histogram> <histogram base="true" name="SimpleCache.IndexCreatedEntryCount" units="units" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary>The number of entries in a newly created index file.</summary> </histogram> <histogram base="true" name="SimpleCache.IndexFileStateOnLoad" - enum="SimpleIndexState" expires_after="2021-07-01"> + enum="SimpleIndexState" expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -287,15 +303,16 @@ </histogram> <histogram base="true" name="SimpleCache.IndexInitializeMethod" - enum="SimpleCacheIndexInitializeMethod" expires_after="2021-07-01"> + enum="SimpleCacheIndexInitializeMethod" expires_after="2022-07-01"> <owner>wanderview@chromium.org</owner> <owner>morlovich@chromium.org</owner> <summary>The method used to initialize the simple cache index.</summary> </histogram> <histogram base="true" name="SimpleCache.IndexNumEntriesOnInit" units="entries" - expires_after="M85"> + expires_after="2022-07-01"> <owner>jkarlin@chromium.org</owner> + <owner>morlovich@chromium.org</owner> <summary> The number of entries in the index at the time that the index has finished initializing. @@ -304,13 +321,16 @@ <histogram base="true" name="SimpleCache.IndexNumEntriesOnWrite" units="units" expires_after="2021-07-01"> + <obsolete> + Removed in July 2021. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary>The number of entries written to the index on a flush.</summary> </histogram> <histogram base="true" name="SimpleCache.IndexRestoreTime" units="ms" - expires_after="2021-07-01"> + expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -321,6 +341,9 @@ <histogram base="true" name="SimpleCache.IndexWriteReason" enum="SimpleCacheIndexWriteReason" expires_after="2021-07-01"> + <obsolete> + Removed in July 2021. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -331,6 +354,9 @@ <histogram base="true" name="SimpleCache.IndexWriteReasonAtLoad" enum="SimpleCacheIndexWriteReason" expires_after="2021-07-01"> + <obsolete> + Removed in July 2021. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -341,8 +367,9 @@ </histogram> <histogram base="true" name="SimpleCache.MaxCacheSizeOnInit" units="KB" - expires_after="M85"> + expires_after="2022-07-01"> <owner>jkarlin@chromium.org</owner> + <owner>morlovich@chromium.org</owner> <summary> The maximum allowed size of the cache at the time that the index has finished initializing. @@ -350,7 +377,7 @@ </histogram> <histogram base="true" name="SimpleCache.OpenEntryIndexState" - enum="SimpleCacheOpenEntryIndexState" expires_after="2021-07-01"> + enum="SimpleCacheOpenEntryIndexState" expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -372,6 +399,9 @@ <histogram base="true" name="SimpleCache.PercentFullOnInit" units="%" expires_after="M85"> + <obsolete> + Removed July 2021. + </obsolete> <owner>jkarlin@chromium.org</owner> <summary> The fullness (in percent) of the cache at the time that the index has @@ -395,7 +425,7 @@ </histogram> <histogram base="true" name="SimpleCache.StaleIndexExtraEntryCount" - units="entries" expires_after="2021-07-01"> + units="entries" expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -406,7 +436,7 @@ </histogram> <histogram base="true" name="SimpleCache.StaleIndexMissedEntryCount" - units="entries" expires_after="2021-07-01"> + units="entries" expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -417,7 +447,7 @@ </histogram> <histogram base="true" name="SimpleCache.StaleIndexQuality" - enum="SimpleCacheStaleIndexQuality" expires_after="2021-07-01"> + enum="SimpleCacheStaleIndexQuality" expires_after="2022-07-01"> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -428,6 +458,11 @@ <histogram base="true" name="SimpleCache.SyncCheckEOFResult" enum="SimpleCacheSyncCheckEOFResult" expires_after="2021-07-01"> + <obsolete> + As of July 2021, no longer logged in UMA data. Kept as a local histogram + (data not sent to UMA) so it appears in chrome://histograms for local + debugging. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -438,6 +473,11 @@ <histogram base="true" name="SimpleCache.SyncCloseResult" enum="SimpleCacheSyncCloseResult" expires_after="2021-07-01"> + <obsolete> + As of July 2021, no longer logged in UMA data. Kept as a local histogram + (data not sent to UMA) so it appears in chrome://histograms for local + debugging. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -447,6 +487,11 @@ <histogram base="true" name="SimpleCache.SyncCreatePlatformFileError" enum="PlatformFileError" expires_after="2021-07-01"> + <obsolete> + As of July 2021, no longer logged in UMA data. Kept as a local histogram + (data not sent to UMA) so it appears in chrome://histograms for local + debugging. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -457,6 +502,11 @@ <histogram base="true" name="SimpleCache.SyncOpenPlatformFileError" enum="PlatformFileError" expires_after="2021-07-01"> + <obsolete> + As of July 2021, no longer logged in UMA data. Kept as a local histogram + (data not sent to UMA) so it appears in chrome://histograms for local + debugging. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -477,6 +527,11 @@ <histogram base="true" name="SimpleCache.SyncOpenResult" enum="SimpleCacheSyncOpenResult" expires_after="2021-07-01"> + <obsolete> + As of July 2021, no longer logged in UMA data. Kept as a local histogram + (data not sent to UMA) so it appears in chrome://histograms for local + debugging. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary> @@ -487,6 +542,11 @@ <histogram base="true" name="SimpleCache.SyncWriteResult" enum="SimpleCacheSyncWriteResult" expires_after="2021-07-01"> + <obsolete> + As of July 2021, no longer logged in UMA data. Kept as a local histogram + (data not sent to UMA) so it appears in chrome://histograms for local + debugging. + </obsolete> <owner>morlovich@chromium.org</owner> <owner>wanderview@chromium.org</owner> <summary>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 271d414..8cb7915 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -2,15 +2,15 @@ "trace_processor_shell": { "win": { "hash": "0b17dcefc3d3da9d145909566c7b3033c25976f9", - "remote_path": "perfetto_binaries/trace_processor_shell/win/c647483ca5ff97691d327dc2224995e47d3dc899/trace_processor_shell.exe" + "remote_path": "perfetto_binaries/trace_processor_shell/win/b72f3ccca5e6ec7e47a05a947156e6378d08b2a7/trace_processor_shell.exe" }, "mac": { "hash": "4a3e7a5523cb8d69a7299e11ac3673c929484f62", - "remote_path": "perfetto_binaries/trace_processor_shell/mac/c647483ca5ff97691d327dc2224995e47d3dc899/trace_processor_shell" + "remote_path": "perfetto_binaries/trace_processor_shell/mac/cb9aee60bd100feb1079c736444a3b72c410730d/trace_processor_shell" }, "linux": { "hash": "34e1c74c72b1eac03af8dc01901c7838c390a1c2", - "remote_path": "perfetto_binaries/trace_processor_shell/linux/c647483ca5ff97691d327dc2224995e47d3dc899/trace_processor_shell" + "remote_path": "perfetto_binaries/trace_processor_shell/linux/cb9aee60bd100feb1079c736444a3b72c410730d/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc b/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc index abd9ad8..4c94ddb 100644 --- a/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc +++ b/tools/traffic_annotation/auditor/traffic_annotation_auditor.cc
@@ -148,8 +148,9 @@ build_path_.IsAbsolute() ? build_path_ : absolute_source_path_.Append(build_path_); source_tree.MapPath("", - absolute_source_path_.Append(FILE_PATH_LITERAL("tools")) - .Append(FILE_PATH_LITERAL("traffic_annotation")) + absolute_source_path_.Append(FILE_PATH_LITERAL("chrome")) + .Append(FILE_PATH_LITERAL("browser")) + .Append(FILE_PATH_LITERAL("privacy")) .MaybeAsASCII()); source_tree.MapPath("", absolute_build_path_.Append(FILE_PATH_LITERAL("gen")) .Append(FILE_PATH_LITERAL("components"))
diff --git a/tools/traffic_annotation/bin/README.md b/tools/traffic_annotation/bin/README.md index 0f6188b..b191c55 100644 --- a/tools/traffic_annotation/bin/README.md +++ b/tools/traffic_annotation/bin/README.md
@@ -59,4 +59,5 @@ The following line will be updated by the above script, and the modified README should be committed along with the updated .sha1 checksums. -LASTCHANGE=29828294b2aec6ace08ea0136cb7fcf164d5e166-refs/heads/master@{#854268} +LASTCHANGE=08e1d61372f41498f01361807b498b6f083f425a-refs/heads/master@{#902419} +LASTCHANGE_YEAR=2021
diff --git a/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 b/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 index 9b396a5..2753d4e 100644 --- a/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1 +++ b/tools/traffic_annotation/bin/linux64/traffic_annotation_auditor.sha1
@@ -1 +1 @@ -92b1ddf7d9e20a91e3147c442a602a12976bf9f1 \ No newline at end of file +705e6bca3d8da6b5a78dd62947f08308b26510be \ No newline at end of file
diff --git a/tools/traffic_annotation/bin/win32/traffic_annotation_auditor.exe.sha1 b/tools/traffic_annotation/bin/win32/traffic_annotation_auditor.exe.sha1 index b5e88f4b..eaf42c1 100644 --- a/tools/traffic_annotation/bin/win32/traffic_annotation_auditor.exe.sha1 +++ b/tools/traffic_annotation/bin/win32/traffic_annotation_auditor.exe.sha1
@@ -1 +1 @@ -fe7bb9064cce90227aa3ab81469d714406eaff21 \ No newline at end of file +f4362222ab0503dfb92582e300c71420642e220b \ No newline at end of file
diff --git a/tools/traffic_annotation/scripts/check_annotations.py b/tools/traffic_annotation/scripts/check_annotations.py index cb88328e..f87f566a 100755 --- a/tools/traffic_annotation/scripts/check_annotations.py +++ b/tools/traffic_annotation/scripts/check_annotations.py
@@ -19,7 +19,7 @@ # If this test starts failing, please set TEST_IS_ENABLED to "False" and file a # bug to get this reenabled, and cc the people listed in # //tools/traffic_annotation/OWNERS. -TEST_IS_ENABLED = False +TEST_IS_ENABLED = True # If the auditor.py part of this test starts failing, please set # TEST_PYTHON_AUDITOR to "False" and file a bug (see comment above).
diff --git a/ui/android/java/src/org/chromium/ui/modelutil/PropertyModel.java b/ui/android/java/src/org/chromium/ui/modelutil/PropertyModel.java index 765f23991..d37bb0e 100644 --- a/ui/android/java/src/org/chromium/ui/modelutil/PropertyModel.java +++ b/ui/android/java/src/org/chromium/ui/modelutil/PropertyModel.java
@@ -14,7 +14,7 @@ import androidx.appcompat.content.res.AppCompatResources; import androidx.core.util.ObjectsCompat; -import org.chromium.build.BuildConfig; +import org.chromium.base.annotations.RemovableInRelease; import java.util.ArrayList; import java.util.Collection; @@ -273,8 +273,9 @@ mData = startingValues; } + @RemovableInRelease private void validateKey(PropertyKey key) { - if (BuildConfig.ENABLE_ASSERTS && !mData.containsKey(key)) { + if (!mData.containsKey(key)) { throw new IllegalArgumentException( "Invalid key passed in: " + key + ". Current data is: " + mData.toString()); } @@ -464,8 +465,9 @@ mData = values; } + @RemovableInRelease private void validateKey(PropertyKey key) { - if (BuildConfig.ENABLE_ASSERTS && !mData.containsKey(key)) { + if (!mData.containsKey(key)) { throw new IllegalArgumentException("Invalid key passed in: " + key); } }
diff --git a/ui/android/junit/src/org/chromium/ui/modelutil/PropertyModelTest.java b/ui/android/junit/src/org/chromium/ui/modelutil/PropertyModelTest.java index c79fb29..9c7b127 100644 --- a/ui/android/junit/src/org/chromium/ui/modelutil/PropertyModelTest.java +++ b/ui/android/junit/src/org/chromium/ui/modelutil/PropertyModelTest.java
@@ -18,7 +18,6 @@ import org.robolectric.annotation.Config; import org.chromium.base.test.BaseRobolectricTestRunner; -import org.chromium.build.BuildConfig; import org.chromium.ui.modelutil.PropertyModel.WritableBooleanPropertyKey; import org.chromium.ui.modelutil.PropertyModel.WritableFloatPropertyKey; import org.chromium.ui.modelutil.PropertyModel.WritableIntPropertyKey; @@ -211,8 +210,6 @@ @Test public void ensureValidKey() { - if (!BuildConfig.ENABLE_ASSERTS) return; - PropertyModel model = new PropertyModel(BOOLEAN_PROPERTY_A, BOOLEAN_PROPERTY_B); thrown.expect(IllegalArgumentException.class); model.set(BOOLEAN_PROPERTY_C, true);
diff --git a/ui/views/accessibility/ax_aura_obj_cache.cc b/ui/views/accessibility/ax_aura_obj_cache.cc index 10242f58..df73f76 100644 --- a/ui/views/accessibility/ax_aura_obj_cache.cc +++ b/ui/views/accessibility/ax_aura_obj_cache.cc
@@ -158,8 +158,11 @@ AXAuraObjWrapper* AXAuraObjCache::GetFocus() { View* focused_view = GetFocusedView(); - while (focused_view && focused_view->GetViewAccessibility().IsIgnored()) + while (focused_view && + (focused_view->GetViewAccessibility().IsIgnored() || + focused_view->GetViewAccessibility().propagate_focus_to_ancestor())) { focused_view = focused_view->parent(); + } if (!focused_view) return nullptr;
diff --git a/ui/views/accessibility/ax_aura_obj_cache_unittest.cc b/ui/views/accessibility/ax_aura_obj_cache_unittest.cc index cd9ebff..047de61 100644 --- a/ui/views/accessibility/ax_aura_obj_cache_unittest.cc +++ b/ui/views/accessibility/ax_aura_obj_cache_unittest.cc
@@ -249,11 +249,13 @@ ASSERT_EQ(ax::mojom::Role::kGroup, GetData(cache.GetFocus()).role); ASSERT_EQ(ax_child, cache.GetFocus()); + // Ignore should cause focus to move upwards. child->GetViewAccessibility().OverrideIsIgnored(true); ASSERT_EQ(ax::mojom::Role::kTextField, GetData(cache.GetFocus()).role); ASSERT_EQ(ax_parent, cache.GetFocus()); - parent->GetViewAccessibility().OverrideIsIgnored(true); + // Propagate focus to ancestor should also cause focus to move upward. + parent->GetViewAccessibility().set_propagate_focus_to_ancestor(true); ASSERT_EQ(ax::mojom::Role::kWindow, GetData(cache.GetFocus()).role); ASSERT_EQ(cache.GetOrCreate(widget->GetRootView()), cache.GetFocus());
diff --git a/ui/views/accessibility/view_accessibility.h b/ui/views/accessibility/view_accessibility.h index 0565142f..b607e5d 100644 --- a/ui/views/accessibility/view_accessibility.h +++ b/ui/views/accessibility/view_accessibility.h
@@ -216,6 +216,14 @@ // native accessibility object associated with this view. gfx::NativeViewAccessible GetFocusedDescendant(); + // Ignores focus on the backing view (to this ViewAccessibility) in favor of + // an backing ancestor view for accessibility focus. + void set_propagate_focus_to_ancestor(bool value) { + propagate_focus_to_ancestor_ = value; + } + + bool propagate_focus_to_ancestor() { return propagate_focus_to_ancestor_; } + // Used for testing. Allows a test to watch accessibility events. const AccessibilityEventsCallback& accessibility_events_callback() const; void set_accessibility_events_callback(AccessibilityEventsCallback callback); @@ -271,6 +279,9 @@ // This view's child tree id. absl::optional<ui::AXTreeID> child_tree_id_; + // Whether to ignore accessibility focus on in favor of an ancestor. + bool propagate_focus_to_ancestor_ = false; + #if defined(USE_AURA) && !BUILDFLAG(IS_CHROMEOS_ASH) // Each instance of ViewAccessibility that's associated with a root View // owns an ViewsAXTreeManager. For other Views, this should be nullptr.
diff --git a/ui/views/view.cc b/ui/views/view.cc index fbca4e6..99bfc06 100644 --- a/ui/views/view.cc +++ b/ui/views/view.cc
@@ -1234,6 +1234,10 @@ if (widget) return widget->GetNativeTheme(); + // CHECK here to ensure we catch fallthrough to the global NativeTheme + // instance on all Chromium builds (crbug.com/1056756). + CHECK(false); + return ui::NativeTheme::GetInstanceForNativeUi(); }
diff --git a/weblayer/browser/client_hints_factory.cc b/weblayer/browser/client_hints_factory.cc index a3ac815..4ad7aca 100644 --- a/weblayer/browser/client_hints_factory.cc +++ b/weblayer/browser/client_hints_factory.cc
@@ -7,12 +7,9 @@ #include "components/client_hints/browser/client_hints.h" #include "components/embedder_support/user_agent_utils.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/prefs/pref_service.h" #include "weblayer/browser/browser_process.h" #include "weblayer/browser/host_content_settings_map_factory.h" -class PrefService; - namespace weblayer { // static @@ -39,11 +36,10 @@ KeyedService* ClientHintsFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { - PrefService* local_state = BrowserProcess::GetInstance()->GetLocalState(); return new client_hints::ClientHints( context, BrowserProcess::GetInstance()->GetNetworkQualityTracker(), HostContentSettingsMapFactory::GetForBrowserContext(context), - embedder_support::GetUserAgentMetadata(), local_state); + embedder_support::GetUserAgentMetadata()); } content::BrowserContext* ClientHintsFactory::GetBrowserContextToUse(