diff --git a/DEPS b/DEPS index 709974f..6017640 100644 --- a/DEPS +++ b/DEPS
@@ -277,11 +277,11 @@ # screen-ai CIPD packages # TODO(b/281483558): Use a tag to download the latest version of screen-ai # (e.g. 'version:121.3') and find a way to automate updating //DEPS with it. - 'screen_ai_linux': 'version:123.9', - 'screen_ai_macos_amd64': 'version:123.9', - 'screen_ai_macos_arm64': 'version:123.9', - 'screen_ai_windows_amd64': 'version:123.9', - 'screen_ai_windows_386': 'version:123.9', + 'screen_ai_linux': 'version:124.00', + 'screen_ai_macos_amd64': 'version:124.00', + 'screen_ai_macos_arm64': 'version:124.00', + 'screen_ai_windows_amd64': 'version:124.00', + 'screen_ai_windows_386': 'version:124.00', # siso CIPD package version. 'siso_version': 'git_revision:4524544994f4eac131378143f498ee4d0b7d1f36', @@ -304,19 +304,19 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'src_internal_revision': '6b8f06285faa0d9e7e9dbc8b30f6fe8f2c73df36', + 'src_internal_revision': '08c6d52feed1b28526673b31c960af555f673b3d', # 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': '6a50e5207dedc0ad967beb987c97a6c17b316dbf', + 'skia_revision': 'bea3840c4307aea5cb9a691b4c1f48db1882d9e9', # 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': '00ad28834aceb9cf29d5a118497a175067902d26', + 'v8_revision': '9a7273cb2581805e0a6c283fd1469b7804df56a4', # 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': '5c78d084206f095337c663ac7747e02fdc5b72d9', + 'angle_revision': 'da1fbbc6497d299d488beba33fc56d068ab01c45', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -383,7 +383,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling chromium_variations # and whatever else without interference from each other. - 'chromium_variations_revision': 'a347efc4c1f5abb194a8b4e9b26d374a86af3050', + 'chromium_variations_revision': '4f6faffd4655ac33ce079be7e4e8b7b5eb5debb7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling CrossBench # and whatever else without interference from each other. @@ -399,7 +399,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': 'fb2f1f877cd5e7c86bcbf681c271bb3171121ca2', + 'devtools_frontend_revision': '9f8a3d4c3d9f00977d355782005554a096b3d1d1', # 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. @@ -423,7 +423,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': 'ddc1dd344b11360f51b621506a363f297ae2aa8c', + 'dawn_revision': 'e201fce6bc0bb4626e8d520857df8c21f9459826', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -930,7 +930,7 @@ 'src/clank': { 'url': Var('chrome_git') + '/clank/internal/apps.git' + '@' + - '620d29ecf663bd64f394abe63a9dfcd074ccf82e', + 'e8ea8ba6aa94a95f24d12e785f2602153c069d94', 'condition': 'checkout_android and checkout_src_internal', }, @@ -1305,7 +1305,7 @@ Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), 'src/third_party/devtools-frontend-internal': { - 'url': Var('chrome_git') + '/devtools/devtools-internal.git' + '@' + 'ab637d2bb43890b3a3fd4d3f83317e6e3bed42a8', + 'url': Var('chrome_git') + '/devtools/devtools-internal.git' + '@' + '8bfede243c85f66eb062119d3ac9b1bd54d92202', 'condition': 'checkout_src_internal', }, @@ -1548,7 +1548,7 @@ 'packages': [ { 'package': 'chromium/third_party/kotlinc', - 'version': 't124SWrNvQMrBqfiKvRIZ_e7uk6FXfYYrXFw6s7hiBwC', + 'version': 'tTF6GjpaBABskkNJqSoDgeXpbdlbjV1F46x9lYzBxBgC', }, ], 'condition': 'checkout_android', @@ -2012,7 +2012,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '07855ae5dc6bf9a8c632cce1de54e6fd219b3c14', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'da648b596043e999975bbf7053b3294c9039738a', + Var('webrtc_git') + '/src.git' + '@' + '6866da182230618c8cd8653c5894c9791a2b0470', # Wuffs' canonical repository is at github.com/google/wuffs, but we use # Skia's mirror of Wuffs, the same as in upstream Skia's DEPS file.
diff --git a/android_webview/browser/aw_feature_map.cc b/android_webview/browser/aw_feature_map.cc index b366b073..0b939422 100644 --- a/android_webview/browser/aw_feature_map.cc +++ b/android_webview/browser/aw_feature_map.cc
@@ -23,6 +23,7 @@ const base::Feature* const kFeaturesExposedToJava[] = { &features::kWebViewDisplayCutout, &features::kWebViewExitReasonMetric, + &features::kWebViewInvokeZoomPickerOnGSU, &features::kWebViewMixedContentAutoupgrades, &features::kWebViewTestFeature, &features::kWebViewJavaJsBridgeMojo,
diff --git a/android_webview/common/aw_features.cc b/android_webview/common/aw_features.cc index 4f409e3..40aa8bf6 100644 --- a/android_webview/common/aw_features.cc +++ b/android_webview/common/aw_features.cc
@@ -215,6 +215,13 @@ "WebViewInjectPlatformJsApis", base::FEATURE_ENABLED_BY_DEFAULT); +// If enabled zoom picker is invoked on every kGestureScrollUpdate consumed ack, +// otherwise the zoom picker is persistently shown from scroll start to scroll +// end plus the usual delay in hiding. +BASE_FEATURE(kWebViewInvokeZoomPickerOnGSU, + "WebViewInvokeZoomPickerOnGSU", + base::FEATURE_DISABLED_BY_DEFAULT); + // Whether to use initial network state during initialization to speed up // startup. BASE_FEATURE(kWebViewUseInitialNetworkStateAtStartup,
diff --git a/android_webview/common/aw_features.h b/android_webview/common/aw_features.h index bdb9348..ec8c819 100644 --- a/android_webview/common/aw_features.h +++ b/android_webview/common/aw_features.h
@@ -28,6 +28,7 @@ BASE_DECLARE_FEATURE(kWebViewHitTestInBlinkOnTouchStart); BASE_DECLARE_FEATURE(kWebViewImageDrag); BASE_DECLARE_FEATURE(kWebViewInjectPlatformJsApis); +BASE_DECLARE_FEATURE(kWebViewInvokeZoomPickerOnGSU); // Feature parameter for `network::features::kMaskedDomainList` which is // defined in //services/network. extern const base::FeatureParam<int> kWebViewIpProtectionExclusionCriteria;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwContents.java b/android_webview/java/src/org/chromium/android_webview/AwContents.java index cc22c0f3..a9f35e3 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwContents.java +++ b/android_webview/java/src/org/chromium/android_webview/AwContents.java
@@ -895,11 +895,19 @@ @Override public void onScrollUpdateGestureConsumed() { mScrollAccessibilityHelper.postViewScrolledAccessibilityEventCallback(); - mZoomControls.invokeZoomPicker(); + if (AwFeatureMap.isEnabled(AwFeatures.WEBVIEW_INVOKE_ZOOM_PICKER_ON_GSU)) { + mZoomControls.invokeZoomPicker(); + } } @Override public void onScrollStarted(int scrollOffsetY, int scrollExtentY, boolean isDirectionUp) { + if (!AwFeatureMap.isEnabled(AwFeatures.WEBVIEW_INVOKE_ZOOM_PICKER_ON_GSU)) { + // This needs to be paired with call to setAutoDismissed(true) and a call to invoke + // zoom picker, so that a delayed hide task is posted by android. This is happening + // on scroll end below. + mZoomControls.setAutoDismissed(false); + } mZoomControls.invokeZoomPicker(); if (mAwFrameMetricsListener != null) { mAwFrameMetricsListener.onWebContentsScrollStateUpdate( @@ -909,6 +917,12 @@ @Override public void onScrollEnded(int scrollOffsetY, int scrollExtentY) { + if (!AwFeatureMap.isEnabled(AwFeatures.WEBVIEW_INVOKE_ZOOM_PICKER_ON_GSU)) { + mZoomControls.setAutoDismissed(true); + // A call to invoke is required so that a delayed hide task can be posted by + // android. + mZoomControls.invokeZoomPicker(); + } if (mAwFrameMetricsListener != null) { mAwFrameMetricsListener.onWebContentsScrollStateUpdate( /* isScrolling= */ false, mId);
diff --git a/android_webview/java/src/org/chromium/android_webview/AwZoomControls.java b/android_webview/java/src/org/chromium/android_webview/AwZoomControls.java index 001ec5f7c..30111ac 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwZoomControls.java +++ b/android_webview/java/src/org/chromium/android_webview/AwZoomControls.java
@@ -48,6 +48,13 @@ } } + public void setAutoDismissed(boolean autoDismiss) { + android.widget.ZoomButtonsController zoomController = getZoomController(); + if (zoomController != null) { + zoomController.setAutoDismissed(autoDismiss); + } + } + @SuppressWarnings("deprecation") public void dismissZoomPicker() { android.widget.ZoomButtonsController zoomController = getZoomController();
diff --git a/ash/accessibility/accessibility_controller.h b/ash/accessibility/accessibility_controller.h index 18f4274..61bce89f 100644 --- a/ash/accessibility/accessibility_controller.h +++ b/ash/accessibility/accessibility_controller.h
@@ -497,9 +497,7 @@ void ToggleDictationFromSource(DictationToggleSource source); // Enables Dictation if the feature is currently disabled. Toggles (starts or - // stops) Dictation if the feature is currently enabled. Note: this behavior - // is currently behind a feature flag - if the feature flag is off, then this - // method behaves like ToggleDictationFromSource. + // stops) Dictation if the feature is currently enabled. void EnableOrToggleDictationFromSource(DictationToggleSource source); // Shows a nudge explaining that a user's dictation language was upgraded to
diff --git a/ash/system/power/power_notification_controller.cc b/ash/system/power/power_notification_controller.cc index 908dbd1d..1bc51b4 100644 --- a/ash/system/power/power_notification_controller.cc +++ b/ash/system/power/power_notification_controller.cc
@@ -106,6 +106,28 @@ /*buckets=*/100); } +// Record remaining battery time in second when the device transitions from a +// critical state to charging state upon connecting the charger. +void MaybeRecordTimeToEmptyPluggedIn( + bool was_in_critical_state, + bool line_power_was_connected, + const std::optional<base::TimeDelta> remaining_time) { + if (!remaining_time.has_value()) { + return; + } + + bool line_power_is_connected = PowerStatus::Get()->IsLinePowerConnected(); + if (!line_power_was_connected && line_power_is_connected && + was_in_critical_state) { + base::UmaHistogramCustomCounts( + "Ash.PowerNotification.TimeToEmptyPluggedIn", + remaining_time->InSeconds(), + /*min=*/0, + /*exclusive_max=*/base::Minutes(10).InSeconds(), + /*buckets=*/100); + } +} + } // namespace const char PowerNotificationController::kUsbNotificationId[] = "usb-charger"; @@ -151,6 +173,11 @@ std::make_unique<BatteryNotification>(message_center_, this); } else if (notification_state_ == NOTIFICATION_NONE) { battery_notification_.reset(); + // Maybe record remaining battery time when the device transitions from a + // critical state to charging state upon connecting the charger. + MaybeRecordTimeToEmptyPluggedIn( + was_in_critical_state_, line_power_was_connected_, + remaining_time_to_empty_from_critical_state_); } else if (battery_notification_.get()) { battery_notification_->Update(); } @@ -158,6 +185,9 @@ battery_was_full_ = PowerStatus::Get()->IsBatteryFull(); usb_charger_was_connected_ = PowerStatus::Get()->IsUsbChargerConnected(); line_power_was_connected_ = PowerStatus::Get()->IsLinePowerConnected(); + remaining_time_to_empty_from_critical_state_ = + PowerStatus::Get()->GetBatteryTimeToEmpty(); + was_in_critical_state_ = GetNotificationState() == NOTIFICATION_CRITICAL; } bool PowerNotificationController::MaybeShowUsbChargerNotification() {
diff --git a/ash/system/power/power_notification_controller.h b/ash/system/power/power_notification_controller.h index 79c5bdcc..4b366a4a 100644 --- a/ash/system/power/power_notification_controller.h +++ b/ash/system/power/power_notification_controller.h
@@ -115,6 +115,15 @@ // Was line power connected the last time onPowerStatusChanged() was called? bool line_power_was_connected_ = false; + // Was the battery in critical state the last time onPowerStatusChanged() was + // called? + bool was_in_critical_state_ = false; + + // The remaining battery time the last time OnPowerStatusChanged() was called. + // This value is utilized to determine the remaining battery time at the + // moment the charger is connected. + std::optional<base::TimeDelta> remaining_time_to_empty_from_critical_state_; + // Has the user already dismissed a low-power notification? Should be set // back to false when all power sources are disconnected. bool usb_notification_dismissed_ = false;
diff --git a/ash/system/power/power_notification_controller_unittest.cc b/ash/system/power/power_notification_controller_unittest.cc index 353b30af..8b54777 100644 --- a/ash/system/power/power_notification_controller_unittest.cc +++ b/ash/system/power/power_notification_controller_unittest.cc
@@ -812,7 +812,7 @@ } TEST_F(PowerNotificationControllerTest, - HistogramTest_RemainingMinutesForCriticalState) { + HistogramTest_TimeToEmptyForCriticalState) { // Verify no initial histogram data is recorded. histogram_tester_->ExpectTotalCount( "Ash.PowerNotification.TimeToEmptyForCritialState", 0); @@ -839,6 +839,8 @@ proto, PowerNotificationController::NOTIFICATION_CRITICAL, true, true); histogram_tester_->ExpectTotalCount( "Ash.PowerNotification.TimeToEmptyForCritialState", 1); + histogram_tester_->ExpectBucketCount( + "Ash.PowerNotification.TimeToEmptyForCritialState", 300, 1); // Trigger another update; the state remains critical, so no additional // metrics should be emitted. @@ -848,6 +850,56 @@ "Ash.PowerNotification.TimeToEmptyForCritialState", 1); } +TEST_F(PowerNotificationControllerTest, HistogramTest_TimeToEmptyPluggedIn) { + // Verify no initial histogram data is recorded. + histogram_tester_->ExpectTotalCount( + "Ash.PowerNotification.TimeToEmptyPluggedIn", 0); + + // Set the default power state. + PowerSupplyProperties proto = DefaultPowerSupplyProperties(); + EXPECT_EQ(PowerNotificationController::NOTIFICATION_NONE, + notification_state()); + + // Simulate plugging in the charger without any critical state. + proto.set_external_power( + power_manager::PowerSupplyProperties_ExternalPower_AC); + UpdateNotificationState(proto, PowerNotificationController::NOTIFICATION_NONE, + false, false); + histogram_tester_->ExpectTotalCount( + "Ash.PowerNotification.TimeToEmptyPluggedIn", 0); + + // Simulate unplugging the charger. + proto.set_external_power( + power_manager::PowerSupplyProperties_ExternalPower_DISCONNECTED); + UpdateNotificationState(proto, PowerNotificationController::NOTIFICATION_NONE, + false, false); + histogram_tester_->ExpectTotalCount( + "Ash.PowerNotification.TimeToEmptyPluggedIn", 0); + + // Transition to critical state. + proto.set_battery_time_to_empty_sec( + PowerNotificationController::kCriticalMinutes * 60); + UpdateNotificationState( + proto, PowerNotificationController::NOTIFICATION_CRITICAL, true, false); + + // Simulate plugging in the charger while in a critical state. + proto.set_external_power( + power_manager::PowerSupplyProperties_ExternalPower_AC); + UpdateNotificationState(proto, PowerNotificationController::NOTIFICATION_NONE, + false, true); + histogram_tester_->ExpectTotalCount( + "Ash.PowerNotification.TimeToEmptyPluggedIn", 1); + histogram_tester_->ExpectBucketCount( + "Ash.PowerNotification.TimeToEmptyPluggedIn", 300, 1); + + // Trigger another update, the state remain normal, no additional metric + // should be emitted. + UpdateNotificationState(proto, PowerNotificationController::NOTIFICATION_NONE, + false, false); + histogram_tester_->ExpectTotalCount( + "Ash.PowerNotification.TimeToEmptyPluggedIn", 1); +} + INSTANTIATE_TEST_SUITE_P( All, PowerNotificationControllerWithBatterySaverTest,
diff --git a/ash/webui/diagnostics_ui/resources/overview_card.ts b/ash/webui/diagnostics_ui/resources/overview_card.ts index 0c5517e..51fd27e 100644 --- a/ash/webui/diagnostics_ui/resources/overview_card.ts +++ b/ash/webui/diagnostics_ui/resources/overview_card.ts
@@ -19,8 +19,8 @@ */ export class OverviewCardElement extends PolymerElement { - static get is(): string { - return 'overview-card'; + static get is(): 'overview-card' { + return 'overview-card' as const; } static get template(): HTMLTemplateElement { @@ -90,7 +90,7 @@ declare global { interface HTMLElementTagNameMap { - 'overview-card': OverviewCardElement; + [OverviewCardElement.is]: OverviewCardElement; } }
diff --git a/base/allocator/partition_allocator/src/partition_alloc/aarch64_support.h b/base/allocator/partition_allocator/src/partition_alloc/aarch64_support.h index 4d01be71..663fd89 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/aarch64_support.h +++ b/base/allocator/partition_allocator/src/partition_alloc/aarch64_support.h
@@ -35,7 +35,7 @@ constexpr bool IsMteEnabled(uint64_t ifunc_hwcap, struct __ifunc_arg_t* ifunc_hw) { #if defined(ARCH_CPU_ARM64) && defined(HAS_HW_CAPS) && \ - PA_BUILDFLAG(HAS_MEMORY_TAGGING) + BUILDFLAG(HAS_MEMORY_TAGGING) return (ifunc_hwcap & _IFUNC_ARG_HWCAP) && (ifunc_hw->_hwcap2 & HWCAP2_MTE); #else return false;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager.cc b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager.cc index a2d6939..d3900304 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager.cc
@@ -21,7 +21,7 @@ #include "partition_alloc/reservation_offset_table.h" #include "partition_alloc/thread_isolation/alignment.h" -#if BUILDFLAG(IS_APPLE) || PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(IS_APPLE) || BUILDFLAG(ENABLE_THREAD_ISOLATION) #include <sys/mman.h> #endif @@ -40,7 +40,7 @@ } // namespace -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) namespace { @@ -125,7 +125,7 @@ PA_CHECK(!(ptr & kSuperPageOffsetMask)); PA_CHECK(!(length & kSuperPageOffsetMask)); address_begin_ = ptr; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) address_end_ = ptr + length; PA_DCHECK(address_begin_ < address_end_); #endif @@ -204,7 +204,7 @@ bit_hint_ = end_bit; } uintptr_t address = address_begin_ + beg_bit * kSuperPageSize; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_DCHECK(address + requested_size <= address_end_); #endif return address; @@ -246,7 +246,7 @@ PA_DCHECK(!(free_size & kSuperPageOffsetMask)); PA_DCHECK(address_begin_ <= address); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_DCHECK(address + free_size <= address_end_); #endif @@ -301,19 +301,19 @@ bool AddressPoolManager::GetStats(AddressSpaceStats* stats) { // Get 64-bit pool stats. GetPoolStats(kRegularPoolHandle, &stats->regular_pool_stats); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) GetPoolStats(kBRPPoolHandle, &stats->brp_pool_stats); -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (IsConfigurablePoolAvailable()) { GetPoolStats(kConfigurablePoolHandle, &stats->configurable_pool_stats); } -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) GetPoolStats(kThreadIsolatedPoolHandle, &stats->thread_isolated_pool_stats); #endif return true; } -#else // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#else // BUILDFLAG(HAS_64_BIT_POINTERS) static_assert( kSuperPageSize % AddressPoolManagerBitmap::kBytesPer1BitOfBRPPoolBitmap == @@ -380,7 +380,7 @@ size_t length) { ScopedGuard scoped_lock(AddressPoolManagerBitmap::GetLock()); // When ENABLE_BACKUP_REF_PTR_SUPPORT is off, BRP pool isn't used. -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (handle == kBRPPoolHandle) { PA_DCHECK( (length % AddressPoolManagerBitmap::kBytesPer1BitOfBRPPoolBitmap) == 0); @@ -412,7 +412,7 @@ (length >> AddressPoolManagerBitmap::kBitShiftOfBRPPoolBitmap) - AddressPoolManagerBitmap::kGuardBitsOfBRPPoolBitmap); } else -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) { PA_DCHECK(handle == kRegularPoolHandle); PA_DCHECK( @@ -434,7 +434,7 @@ ScopedGuard scoped_lock(AddressPoolManagerBitmap::GetLock()); // When ENABLE_BACKUP_REF_PTR_SUPPORT is off, BRP pool isn't used. -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (handle == kBRPPoolHandle) { PA_DCHECK( (length % AddressPoolManagerBitmap::kBytesPer1BitOfBRPPoolBitmap) == 0); @@ -449,7 +449,7 @@ (length >> AddressPoolManagerBitmap::kBitShiftOfBRPPoolBitmap) - AddressPoolManagerBitmap::kGuardBitsOfBRPPoolBitmap); } else -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) { PA_DCHECK(handle == kRegularPoolHandle); PA_DCHECK( @@ -520,7 +520,7 @@ // Get 32-bit pool usage. stats->regular_pool_stats.usage = CountUsedSuperPages(regular_pool_bits, kRegularPoolBitsPerSuperPage); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) static_assert( kSuperPageSize % AddressPoolManagerBitmap::kBytesPer1BitOfBRPPoolBitmap == 0, @@ -542,11 +542,11 @@ stats->blocklist_hit_count = AddressPoolManagerBitmap::blocklist_hit_count_.load( std::memory_order_relaxed); -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) return true; } -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) void AddressPoolManager::DumpStats(AddressSpaceStatsDumper* dumper) { AddressSpaceStats stats{}; @@ -555,7 +555,7 @@ } } -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // This function just exists to static_assert the layout of the private fields // in Pool. void AddressPoolManager::AssertThreadIsolatedLayout() { @@ -566,6 +566,6 @@ static_assert(alloc_bitset_offset % PA_THREAD_ISOLATED_ALIGN_SZ == 0); static_assert(sizeof(AddressPoolManager) % PA_THREAD_ISOLATED_ALIGN_SZ == 0); } -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager.h b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager.h index c241616f..e1bfe28f 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager.h +++ b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager.h
@@ -59,7 +59,7 @@ AddressPoolManager(const AddressPoolManager&) = delete; AddressPoolManager& operator=(const AddressPoolManager&) = delete; -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) void Add(pool_handle handle, uintptr_t address, size_t length); void Remove(pool_handle handle); @@ -69,7 +69,7 @@ // Return the base address of a pool. uintptr_t GetPoolBaseAddress(pool_handle handle); -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) // Reserves address space from the pool. uintptr_t Reserve(pool_handle handle, @@ -99,7 +99,7 @@ private: friend class AddressPoolManagerForTesting; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // If we use a thread isolated pool, we need to write-protect its metadata. // Allow the function to get access to the pool pointer. friend void WriteProtectThreadIsolatedGlobals(ThreadIsolationOption); @@ -113,11 +113,11 @@ // if PartitionAlloc is wholly unused in this process.) bool GetStats(AddressSpaceStats* stats); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) static void AssertThreadIsolatedLayout(); -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) class Pool { public: @@ -162,14 +162,14 @@ size_t total_bits_ = 0; uintptr_t address_begin_ = 0; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) uintptr_t address_end_ = 0; #endif -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) friend class AddressPoolManager; friend void WriteProtectThreadIsolatedGlobals(ThreadIsolationOption); -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) }; PA_ALWAYS_INLINE Pool* GetPool(pool_handle handle) { @@ -199,7 +199,7 @@ #endif Pool pools_[kNumPools]; -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) static PA_CONSTINIT AddressPoolManager singleton_; };
diff --git a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.cc b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.cc index a8f9bc6..ace3db9 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.cc
@@ -25,12 +25,12 @@ AddressPoolManagerBitmap::regular_pool_bits_; // GUARDED_BY(GetLock()) std::bitset<AddressPoolManagerBitmap::kBRPPoolBits> AddressPoolManagerBitmap::brp_pool_bits_; // GUARDED_BY(GetLock()) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) std::array<std::atomic_bool, AddressPoolManagerBitmap::kAddressSpaceSize / kSuperPageSize> AddressPoolManagerBitmap::brp_forbidden_super_page_map_; std::atomic_size_t AddressPoolManagerBitmap::blocklist_hit_count_; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.h b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.h index 654a64b5..3036330 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.h +++ b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.h
@@ -102,7 +102,7 @@ brp_pool_bits_)[address >> kBitShiftOfBRPPoolBitmap]; } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) static void BanSuperPageFromBRPPool(uintptr_t address) { brp_forbidden_super_page_map_[address >> kSuperPageShift].store( true, std::memory_order_relaxed); @@ -126,7 +126,7 @@ } static void IncrementBlocklistHitCount() { ++blocklist_hit_count_; } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) private: friend class AddressPoolManager; @@ -136,11 +136,11 @@ static std::bitset<kRegularPoolBits> regular_pool_bits_ PA_GUARDED_BY(GetLock()); static std::bitset<kBRPPoolBits> brp_pool_bits_ PA_GUARDED_BY(GetLock()); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) static std::array<std::atomic_bool, kAddressSpaceSize / kSuperPageSize> brp_forbidden_super_page_map_; static std::atomic_size_t blocklist_hit_count_; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) }; } // namespace internal @@ -154,7 +154,7 @@ PA_DCHECK(!internal::AddressPoolManagerBitmap::IsManagedByBRPPool(address)); #endif return internal::AddressPoolManagerBitmap::IsManagedByRegularPool(address) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) || internal::AddressPoolManagerBitmap::IsManagedByBRPPool(address) #endif ;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_unittest.cc index cec16b8..50ccac9 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_unittest.cc
@@ -24,12 +24,11 @@ void DumpStats( const partition_alloc::AddressSpaceStats* address_space_stats) override { regular_pool_usage_ = address_space_stats->regular_pool_stats.usage; -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) regular_pool_largest_reservation_ = address_space_stats->regular_pool_stats.largest_available_reservation; #endif -#if !BUILDFLAG(HAS_64_BIT_POINTERS) && \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if !BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) blocklist_size_ = address_space_stats->blocklist_size; #endif } @@ -39,7 +38,7 @@ size_t blocklist_size_ = 0; }; -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) class AddressPoolManagerForTesting : public AddressPoolManager { public: @@ -278,7 +277,7 @@ ASSERT_EQ(dumper.regular_pool_largest_reservation_, kPageCnt); } -#else // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#else // BUILDFLAG(HAS_64_BIT_POINTERS) TEST(PartitionAllocAddressPoolManagerTest, IsManagedByRegularPool) { constexpr size_t kAllocCount = 8; @@ -328,7 +327,7 @@ } } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) TEST(PartitionAllocAddressPoolManagerTest, IsManagedByBRPPool) { constexpr size_t kAllocCount = 4; // Totally (1+3+7+11) * 2MB = 44MB allocation @@ -376,7 +375,7 @@ EXPECT_FALSE(AddressPoolManager::IsManagedByBRPPool(addrs[i])); } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) TEST(PartitionAllocAddressPoolManagerTest, RegularPoolUsageChanges) { AddressSpaceStatsDumperForTesting dumper{}; @@ -401,6 +400,6 @@ EXPECT_EQ(dumper.regular_pool_usage_, usage_before); } -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization.cc b/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization.cc index 64bf3efc..bc73fc0 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization.cc
@@ -18,7 +18,7 @@ uintptr_t GetRandomPageBase() { uintptr_t random = static_cast<uintptr_t>(internal::RandomValue()); -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) random <<= 32ULL; random |= static_cast<uintptr_t>(internal::RandomValue()); @@ -26,7 +26,7 @@ // OS and build configuration. random &= internal::ASLRMask(); random += internal::ASLROffset(); -#else // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#else // BUILDFLAG(HAS_64_BIT_POINTERS) #if BUILDFLAG(IS_WIN) // On win32 host systems the randomization plus huge alignment causes // excessive fragmentation. Plus most of these systems lack ASLR, so the @@ -42,7 +42,7 @@ #endif // BUILDFLAG(IS_WIN) random &= internal::ASLRMask(); random += internal::ASLROffset(); -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) PA_DCHECK(!(random & internal::PageAllocationGranularityOffsetMask())); return random;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization_unittest.cc index e635769..3879f28 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/address_space_randomization_unittest.cc
@@ -135,8 +135,8 @@ return; // bit is always 0. } -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) - // Do fewer checks when PA_BUILDFLAG(PA_DCHECK_IS_ON). Exercized code only +#if BUILDFLAG(PA_DCHECK_IS_ON) + // Do fewer checks when BUILDFLAG(PA_DCHECK_IS_ON). Exercized code only // changes when the random number generator does, which should be almost // never. However it's expensive to run all the tests. So keep iterations // faster for local development builds, while having the stricter version run
diff --git a/base/allocator/partition_allocator/src/partition_alloc/address_space_stats.h b/base/allocator/partition_allocator/src/partition_alloc/address_space_stats.h index f87549e..6f69553 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/address_space_stats.h +++ b/base/allocator/partition_allocator/src/partition_alloc/address_space_stats.h
@@ -19,25 +19,25 @@ // On 32-bit, pools are mainly logical entities, intermingled with // allocations not managed by PartitionAlloc. The "largest available // reservation" is not possible to measure in that case. -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) size_t largest_available_reservation = 0; #endif }; struct AddressSpaceStats { PoolStats regular_pool_stats; -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PoolStats brp_pool_stats; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(HAS_64_BIT_POINTERS) PoolStats configurable_pool_stats; #else -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) size_t blocklist_size; // measured in super pages size_t blocklist_hit_count; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) PoolStats thread_isolated_pool_stats; #endif };
diff --git a/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer.cc b/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer.cc index 04b3646..b4d9e66 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer.cc
@@ -5,7 +5,7 @@ #include "partition_alloc/compressed_pointer.h" #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) namespace partition_alloc::internal { @@ -26,4 +26,4 @@ } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer.h b/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer.h index 3b2410c..d6ec1e8c 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer.h +++ b/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer.h
@@ -14,7 +14,7 @@ #include "partition_alloc/partition_alloc_base/component_export.h" #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) #if !BUILDFLAG(GLUE_CORE_POOLS) #error "Pointer compression only works with glued pools" @@ -23,7 +23,7 @@ #error "Pointer compression currently supports constant pool size" #endif -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION) namespace partition_alloc { @@ -33,7 +33,7 @@ constexpr bool IsDecayedSame = std::is_same_v<std::decay_t<T1>, std::decay_t<T2>>; -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) // Pointer compression works by storing only the 'useful' 32-bit part of the // pointer. The other half (the base) is stored in a global variable @@ -118,11 +118,11 @@ friend class PartitionAddressSpace; }; -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION) } // namespace internal -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) template <typename T> class PA_TRIVIAL_ABI CompressedPointer final { @@ -232,7 +232,7 @@ static constexpr size_t kMinimalRequiredAlignment = 8; static_assert((1 << kOverallBitsToShift) == kMinimalRequiredAlignment); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_DCHECK(reinterpret_cast<uintptr_t>(ptr) % kMinimalRequiredAlignment == 0); PA_DCHECK(internal::CompressedPointerBaseGlobal::IsSet()); @@ -243,7 +243,7 @@ PA_DCHECK(!ptr || (base & kCorePoolsBaseMask) == (reinterpret_cast<uintptr_t>(ptr) & kCorePoolsBaseMask)); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) const auto uptr = reinterpret_cast<uintptr_t>(ptr); // Shift the pointer and truncate. @@ -444,7 +444,7 @@ return static_cast<CompressedPointer<T>>(a) >= b; } -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION) // Simple wrapper over the raw pointer. template <typename T>
diff --git a/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer_unittest.cc index d47b43d..52de3bf 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/compressed_pointer_unittest.cc
@@ -47,14 +47,14 @@ } // Test that pointer types are trivial. -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) static_assert( std::is_trivially_default_constructible_v<CompressedPointer<Base>>); static_assert(std::is_trivially_copy_constructible_v<CompressedPointer<Base>>); static_assert(std::is_trivially_move_constructible_v<CompressedPointer<Base>>); static_assert(std::is_trivially_copy_assignable_v<CompressedPointer<Base>>); static_assert(std::is_trivially_move_assignable_v<CompressedPointer<Base>>); -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION) static_assert( std::is_trivially_default_constructible_v<UncompressedPointer<Base>>); static_assert( @@ -72,16 +72,16 @@ template <typename TagType> class CompressedPointerTest : public ::testing::Test { public: -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) template <typename T> using PointerType = std::conditional_t<std::is_same_v<TagType, CompressedTypeTag>, CompressedPointer<T>, UncompressedPointer<T>>; -#else // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#else // BUILDFLAG(ENABLE_POINTER_COMPRESSION) template <typename T> using PointerType = UncompressedPointer<T>; -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION) CompressedPointerTest() : allocator_(PartitionOptions{}) {} @@ -89,7 +89,7 @@ PartitionAllocator allocator_; }; -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) using ObjectTypes = ::testing::Types<UncompressedTypeTag, CompressedTypeTag>; #else using ObjectTypes = ::testing::Types<UncompressedTypeTag>;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/encoded_next_freelist.h b/base/allocator/partition_allocator/src/partition_alloc/encoded_next_freelist.h index 24562dd..14f133b 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/encoded_next_freelist.h +++ b/base/allocator/partition_allocator/src/partition_alloc/encoded_next_freelist.h
@@ -177,7 +177,7 @@ // SetNext() is either called on the freelist head, when provisioning new // slots, or when GetNext() has been called before, no need to pass the // size. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Regular freelists always point to an entry within the same super page. // // This is most likely a PartitionAlloc bug if this triggers. @@ -186,7 +186,7 @@ (SlotStartPtr2Addr(entry) & kSuperPageBaseMask))) { FreelistCorruptionDetected(0); } -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) encoded_next_ = EncodedFreelistPtr(entry); #if PA_CONFIG(HAS_FREELIST_SHADOW_ENTRY) @@ -281,7 +281,7 @@ const bool same_super_page = (here_address & kSuperPageBaseMask) == (next_address & kSuperPageBaseMask); -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) bool marked_as_free_in_bitmap = !FreeSlotBitmapSlotIsUsed(next_address); #else constexpr bool marked_as_free_in_bitmap = true;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/extended_api.cc b/base/allocator/partition_allocator/src/partition_alloc/extended_api.cc index b8d4156a7..8d3132b 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/extended_api.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/extended_api.cc
@@ -36,7 +36,7 @@ root->settings.with_thread_cache = true; } -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) void DisablePartitionAllocThreadCacheForProcess() { PA_CHECK(allocator_shim::internal::PartitionAllocMalloc:: AllocatorConfigurationFinalized()); @@ -45,7 +45,7 @@ DisableThreadCacheForRootIfEnabled( allocator_shim::internal::PartitionAllocMalloc::OriginalAllocator()); } -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } // namespace @@ -63,7 +63,7 @@ ThreadCacheProcessScopeForTesting::ThreadCacheProcessScopeForTesting( PartitionRoot* root) : root_(root) { -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) auto* regular_allocator = allocator_shim::internal::PartitionAllocMalloc::Allocator(); regular_was_enabled_ = @@ -86,13 +86,13 @@ PA_CHECK(!ThreadCache::IsValid(ThreadCache::Get())); EnablePartitionAllocThreadCacheForRootIfDisabled(root_); ThreadCache::SwapForTesting(root_); -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) PA_CHECK(ThreadCache::Get()); } ThreadCacheProcessScopeForTesting::~ThreadCacheProcessScopeForTesting() { -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) auto* regular_allocator = allocator_shim::internal::PartitionAllocMalloc::Allocator(); bool regular_enabled = @@ -122,7 +122,7 @@ DisableThreadCacheForRootIfEnabled(root_); ThreadCache::SwapForTesting(nullptr); -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } #endif // PA_CONFIG(THREAD_CACHE_SUPPORTED)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/extended_api.h b/base/allocator/partition_allocator/src/partition_alloc/extended_api.h index b3577c8..1040c99c 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/extended_api.h +++ b/base/allocator/partition_allocator/src/partition_alloc/extended_api.h
@@ -32,7 +32,7 @@ private: PartitionRoot* root_ = nullptr; -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) bool regular_was_enabled_ = false; #endif };
diff --git a/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap.h b/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap.h index e9708013f..a7f38df 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap.h +++ b/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap.h
@@ -15,7 +15,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" #include "partition_alloc/partition_alloc_constants.h" -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) namespace partition_alloc::internal { @@ -92,7 +92,7 @@ *cell &= ~CellWithAOne(bit_index); } -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Checks if the cells that are meant to contain only unset bits are really 0. auto [begin_cell, begin_bit_index] = GetFreeSlotBitmapCellPtrAndBitIndex(begin_addr); @@ -131,11 +131,11 @@ for (FreeSlotBitmapCellType* cell = begin_cell; cell < end_cell; ++cell) { PA_DCHECK(*cell == 0u); } -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) } } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#endif // BUILDFLAG(USE_FREESLOT_BITMAP) #endif // PARTITION_ALLOC_FREESLOT_BITMAP_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap_constants.h b/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap_constants.h index 8faf77a..b22946e 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap_constants.h +++ b/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap_constants.h
@@ -28,7 +28,7 @@ PA_ALWAYS_INLINE PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR size_t ReservedFreeSlotBitmapSize() { -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) return base::bits::AlignUp(kFreeSlotBitmapSize, PartitionPageSize()); #else return 0; @@ -37,7 +37,7 @@ PA_ALWAYS_INLINE PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR size_t CommittedFreeSlotBitmapSize() { -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) return base::bits::AlignUp(kFreeSlotBitmapSize, SystemPageSize()); #else return 0; @@ -49,7 +49,7 @@ return ReservedFreeSlotBitmapSize() / PartitionPageSize(); } -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) PA_ALWAYS_INLINE uintptr_t SuperPageFreeSlotBitmapAddr(uintptr_t super_page) { PA_DCHECK(!(super_page % kSuperPageAlignment)); return super_page + PartitionPageSize();
diff --git a/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap_unittest.cc index 69329d66..ad4f7c7 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/freeslot_bitmap_unittest.cc
@@ -18,8 +18,7 @@ // This test is disabled when MEMORY_TOOL_REPLACES_ALLOCATOR is defined because // we cannot locate the freeslot bitmap address in that case. -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) && \ - !defined(MEMORY_TOOL_REPLACES_ALLOCATOR) +#if BUILDFLAG(USE_FREESLOT_BITMAP) && !defined(MEMORY_TOOL_REPLACES_ALLOCATOR) namespace partition_alloc::internal { @@ -203,5 +202,5 @@ } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(USE_FREESLOT_BITMAP) && +#endif // BUILDFLAG(USE_FREESLOT_BITMAP) && // !defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/gwp_asan_support.cc b/base/allocator/partition_allocator/src/partition_alloc/gwp_asan_support.cc index ef7cf31..2295f27 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/gwp_asan_support.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/gwp_asan_support.cc
@@ -4,7 +4,7 @@ #include "partition_alloc/gwp_asan_support.h" -#if PA_BUILDFLAG(ENABLE_GWP_ASAN_SUPPORT) +#if BUILDFLAG(ENABLE_GWP_ASAN_SUPPORT) #include "partition_alloc/build_config.h" #include "partition_alloc/freeslot_bitmap_constants.h" @@ -129,4 +129,4 @@ } // namespace partition_alloc -#endif // PA_BUILDFLAG(ENABLE_GWP_ASAN_SUPPORT) +#endif // BUILDFLAG(ENABLE_GWP_ASAN_SUPPORT)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/gwp_asan_support.h b/base/allocator/partition_allocator/src/partition_alloc/gwp_asan_support.h index 6e8b28f..7af944fa 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/gwp_asan_support.h +++ b/base/allocator/partition_allocator/src/partition_alloc/gwp_asan_support.h
@@ -8,7 +8,7 @@ #include "partition_alloc/partition_alloc_base/component_export.h" #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(ENABLE_GWP_ASAN_SUPPORT) +#if BUILDFLAG(ENABLE_GWP_ASAN_SUPPORT) #include <cstddef> #include <cstdint> @@ -115,6 +115,6 @@ } // namespace partition_alloc -#endif // PA_BUILDFLAG(ENABLE_GWP_ASAN_SUPPORT) +#endif // BUILDFLAG(ENABLE_GWP_ASAN_SUPPORT) #endif // PARTITION_ALLOC_GWP_ASAN_SUPPORT_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/hardening_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/hardening_unittest.cc index 0c22686..f6c11653 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/hardening_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/hardening_unittest.cc
@@ -117,7 +117,7 @@ root.get_freelist_dispatcher()->EmplaceAndInitForTest( root.ObjectToSlotStart(data), to_corrupt, true); -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) // This part crashes with freeslot bitmap because it detects freelist // corruptions, which is rather desirable behavior. EXPECT_DEATH_IF_SUPPORTED(root.Alloc(kAllocSize), ""); @@ -132,11 +132,11 @@ void* new_data2 = root.Alloc(kAllocSize); // Now we have a pointer to the middle of an existing allocation. EXPECT_EQ(new_data2, to_corrupt); -#endif // PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#endif // BUILDFLAG(USE_FREESLOT_BITMAP) } #endif // !BUILDFLAG(IS_ANDROID) -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) #if PA_USE_DEATH_TESTS() && PA_CONFIG(HAS_FREELIST_SHADOW_ENTRY) TEST(HardeningTest, ConstructPoolOffsetFromStackPointerCrashing) { int num_to_corrupt = 12345; @@ -201,7 +201,7 @@ root.get_freelist_dispatcher()->EmplaceAndInitForTest( root.ObjectToSlotStart(data), to_corrupt, true); -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) // This part crashes with freeslot bitmap because it detects freelist // corruptions, which is rather desirable behavior. EXPECT_DEATH_IF_SUPPORTED(root.Alloc(kAllocSize), ""); @@ -216,10 +216,10 @@ void* new_data2 = root.Alloc(kAllocSize); // Now we have a pointer to the middle of an existing allocation. EXPECT_EQ(new_data2, to_corrupt); -#endif // PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#endif // BUILDFLAG(USE_FREESLOT_BITMAP) } #endif // !BUILDFLAG(IS_ANDROID) -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) } // namespace } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/in_slot_metadata.h b/base/allocator/partition_allocator/src/partition_alloc/in_slot_metadata.h index b39607f..219cdad8 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/in_slot_metadata.h +++ b/base/allocator/partition_allocator/src/partition_alloc/in_slot_metadata.h
@@ -49,7 +49,7 @@ #endif // BUILDFLAG(IS_APPLE) } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) namespace { // Utility functions to define a bit field. @@ -189,7 +189,7 @@ // Similar to |Acquire()|, but for raw_ptr<T, DisableDanglingPtrDetection> // instead of raw_ptr<T>. PA_ALWAYS_INLINE void AcquireFromUnprotectedPtr() { -#if PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) CheckCookieIfSupported(); CountType old_count = count_.fetch_add(kUnprotectedPtrInc, std::memory_order_relaxed); @@ -209,7 +209,7 @@ // Check underflow. PA_DCHECK(old_count & kPtrCountMask); -#if PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) // If a dangling raw_ptr<> was detected, report it. if (PA_UNLIKELY((old_count & kDanglingRawPtrDetectedBit) == kDanglingRawPtrDetectedBit)) { @@ -224,7 +224,7 @@ // Similar to |Release()|, but for raw_ptr<T, DisableDanglingPtrDetection> // instead of raw_ptr<T>. PA_ALWAYS_INLINE bool ReleaseFromUnprotectedPtr() { -#if PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) CheckCookieIfSupported(); CountType old_count = @@ -359,7 +359,7 @@ // If there are some dangling raw_ptr<>. Turn on the error flag, and // emit the `DanglingPtrDetected` once to embedders. PA_ALWAYS_INLINE void CheckDanglingPointersOnFree(CountType count) { -#if PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) // The `kPtrCountMask` counts the number of raw_ptr<T>. It is expected to be // zero when there are no unexpected dangling pointers. if (PA_LIKELY((count & kPtrCountMask) == 0)) { @@ -384,7 +384,7 @@ partition_alloc::internal::DanglingRawPtrDetected( reinterpret_cast<uintptr_t>(this)); -#endif // PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#endif // BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) } // The common parts shared by Release() and ReleaseFromUnprotectedPtr(). @@ -477,7 +477,7 @@ static constexpr size_t kInSlotMetadataBufferSize = sizeof(InSlotMetadata); -#if PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) #if PA_CONFIG(IN_SLOT_METADATA_CHECK_COOKIE) || \ PA_CONFIG(IN_SLOT_METADATA_STORE_REQUESTED_SIZE) @@ -486,7 +486,7 @@ static constexpr size_t kInSlotMetadataSizeShift = 3; #endif -#else // PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#else // BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) #if PA_CONFIG(IN_SLOT_METADATA_CHECK_COOKIE) && \ PA_CONFIG(IN_SLOT_METADATA_STORE_REQUESTED_SIZE) @@ -540,8 +540,7 @@ if (PA_LIKELY(slot_start & SystemPageOffsetMask())) { uintptr_t refcount_address = slot_start + slot_size - sizeof(InSlotMetadata); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_CHECK(refcount_address % alignof(InSlotMetadata) == 0); #endif // TODO(bartekn): Plumb the tag from the callers, so that MTE tag can be @@ -553,8 +552,7 @@ (slot_start & kSuperPageBaseMask) + SystemPageSize() * 2); size_t index = ((slot_start & kSuperPageOffsetMask) >> SystemPageShift()) << GetInSlotMetadataIndexMultiplierShift(); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_CHECK(sizeof(InSlotMetadata) * index <= SystemPageSize()); #endif return table_base + index; @@ -564,11 +562,11 @@ static_assert(sizeof(InSlotMetadata) <= kInSlotMetadataBufferSize, "InSlotMetadata should fit into the in-slot buffer."); -#else // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#else // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) static constexpr size_t kInSlotMetadataBufferSize = 0; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) constexpr size_t kInSlotMetadataSizeAdjustment = kInSlotMetadataBufferSize;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer.cc b/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer.cc index f138fed..f6f1acb9 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer.cc
@@ -10,7 +10,7 @@ #include "partition_alloc/partition_alloc_check.h" #include "partition_alloc/partition_alloc_config.h" -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) #include "partition_alloc/starscan/pcscan.h" #endif @@ -65,7 +65,7 @@ // // Lastly decommit empty slot spans and lastly try to discard unused pages at // the end of the remaining active slots. -#if PA_CONFIG(STARSCAN_ENABLE_STARSCAN_ON_RECLAIM) && PA_BUILDFLAG(USE_STARSCAN) +#if PA_CONFIG(STARSCAN_ENABLE_STARSCAN_ON_RECLAIM) && BUILDFLAG(USE_STARSCAN) { using PCScan = internal::PCScan; const auto invocation_mode = flags & PurgeFlags::kAggressiveReclaim @@ -74,7 +74,7 @@ PCScan::PerformScanIfNeeded(invocation_mode); } #endif // PA_CONFIG(STARSCAN_ENABLE_STARSCAN_ON_RECLAIM) && - // PA_BUILDFLAG(USE_STARSCAN) + // BUILDFLAG(USE_STARSCAN) #if PA_CONFIG(THREAD_CACHE_SUPPORTED) // Don't completely empty the thread cache outside of low memory situations,
diff --git a/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer_unittest.cc index 66a103b..81b2161 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/memory_reclaimer_unittest.cc
@@ -16,7 +16,7 @@ #include "partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h" #include "testing/gtest/include/gtest/gtest.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ PA_CONFIG(THREAD_CACHE_SUPPORTED) #include "partition_alloc/extended_api.h" #include "partition_alloc/thread_cache.h" @@ -101,7 +101,7 @@ } } -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ PA_CONFIG(THREAD_CACHE_SUPPORTED) namespace { @@ -142,7 +142,7 @@ EXPECT_LT(tcache->CachedMemory(), cached_size / 2); } -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ // PA_CONFIG(THREAD_CACHE_SUPPORTED) } // namespace partition_alloc
diff --git a/base/allocator/partition_allocator/src/partition_alloc/page_allocator.h b/base/allocator/partition_allocator/src/partition_alloc/page_allocator.h index 51004ee..6e73c6a 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/page_allocator.h +++ b/base/allocator/partition_allocator/src/partition_alloc/page_allocator.h
@@ -41,7 +41,7 @@ kReadWriteExecute, }; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) constexpr explicit PageAccessibilityConfiguration(Permissions permissions) : permissions(permissions) {} constexpr PageAccessibilityConfiguration( @@ -51,13 +51,13 @@ #else constexpr explicit PageAccessibilityConfiguration(Permissions permissions) : permissions(permissions) {} -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) Permissions permissions; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // Tag the page with a Memory Protection Key. Use 0 for none. ThreadIsolationOption thread_isolation; -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) }; // Use for De/RecommitSystemPages API.
diff --git a/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.h b/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.h index 82d755b..809c5ff6 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.h +++ b/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_posix.h
@@ -215,14 +215,14 @@ uintptr_t address, size_t length, PageAccessibilityConfiguration accessibility) { -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) if (accessibility.thread_isolation.enabled) { return 0 == MprotectWithThreadIsolation(reinterpret_cast<void*>(address), length, GetAccessFlags(accessibility), accessibility.thread_isolation); } -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) return 0 == WrapEINTR(mprotect)(reinterpret_cast<void*>(address), length, GetAccessFlags(accessibility)); } @@ -233,13 +233,13 @@ PageAccessibilityConfiguration accessibility) { int access_flags = GetAccessFlags(accessibility); int ret; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) if (accessibility.thread_isolation.enabled) { ret = MprotectWithThreadIsolation(reinterpret_cast<void*>(address), length, GetAccessFlags(accessibility), accessibility.thread_isolation); } else -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) { ret = WrapEINTR(mprotect)(reinterpret_cast<void*>(address), length, GetAccessFlags(accessibility)); @@ -299,14 +299,14 @@ bool change_permissions = accessibility_disposition == PageAccessibilityDisposition::kRequireUpdate; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // This is not guaranteed, show that we're serious. // // More specifically, several callers have had issues with assuming that // memory is zeroed, this would hopefully make these bugs more visible. We // don't memset() everything, because ranges can be very large, and doing it // over the entire range could make Chrome unusable with - // PA_BUILDFLAG(PA_DCHECK_IS_ON). + // BUILDFLAG(PA_DCHECK_IS_ON). // // Only do it when we are about to change the permissions, since we don't know // the previous permissions, and cannot restore them.
diff --git a/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_win.h b/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_win.h index 76d76fc..90811615 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_win.h +++ b/base/allocator/partition_allocator/src/partition_alloc/page_allocator_internals_win.h
@@ -28,7 +28,7 @@ case ERROR_COMMITMENT_MINIMUM: // Page file is too small. case ERROR_COMMITMENT_LIMIT: -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // Not enough memory resources are available to process this command. // // It is not entirely clear whether this error pertains to out of address
diff --git a/base/allocator/partition_allocator/src/partition_alloc/page_allocator_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/page_allocator_unittest.cc index 4b204b8..d7b714a 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/page_allocator_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/page_allocator_unittest.cc
@@ -37,12 +37,12 @@ #include "partition_alloc/arm_bti_test_functions.h" -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) #include <arm_acle.h> #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) #define MTE_KILLED_BY_SIGNAL_AVAILABLE #endif -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) #if !defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.cc index 5504b3f..df407d3 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.cc
@@ -31,13 +31,13 @@ #include <windows.h> #endif // BUILDFLAG(IS_WIN) -#if PA_CONFIG(ENABLE_SHADOW_METADATA) || PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if PA_CONFIG(ENABLE_SHADOW_METADATA) || BUILDFLAG(ENABLE_THREAD_ISOLATION) #include <sys/mman.h> #endif namespace partition_alloc::internal { -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) namespace { @@ -143,7 +143,7 @@ size_t regular_pool_size = RegularPoolSize(); size_t brp_pool_size = BRPPoolSize(); -#if PA_BUILDFLAG(GLUE_CORE_POOLS) +#if BUILDFLAG(GLUE_CORE_POOLS) // Gluing core pools (regular & BRP) makes sense only when both pools are of // the same size. This the only way we can check belonging to either of the // two with a single bitmask operation. @@ -165,7 +165,7 @@ } setup_.brp_pool_base_address_ = setup_.regular_pool_base_address_ + regular_pool_size; -#else // PA_BUILDFLAG(GLUE_CORE_POOLS) +#else // BUILDFLAG(GLUE_CORE_POOLS) #if PA_CONFIG(ENABLE_SHADOW_METADATA) int regular_pool_fd = memfd_create("/regular_pool", MFD_CLOEXEC); #else @@ -200,12 +200,12 @@ HandlePoolAllocFailure(); } setup_.brp_pool_base_address_ = base_address + kForbiddenZoneSize; -#endif // PA_BUILDFLAG(GLUE_CORE_POOLS) +#endif // BUILDFLAG(GLUE_CORE_POOLS) #if PA_CONFIG(DYNAMICALLY_SELECT_POOL_SIZE) setup_.regular_pool_base_mask_ = ~(regular_pool_size - 1); setup_.brp_pool_base_mask_ = ~(brp_pool_size - 1); -#if PA_BUILDFLAG(GLUE_CORE_POOLS) +#if BUILDFLAG(GLUE_CORE_POOLS) // When PA_GLUE_CORE_POOLS is on, the BRP pool is placed at the end of the // regular pool, effectively forming one virtual pool of a twice bigger // size. Adjust the mask appropriately. @@ -222,7 +222,7 @@ // Sanity check pool alignment. PA_DCHECK(!(setup_.regular_pool_base_address_ & (regular_pool_size - 1))); PA_DCHECK(!(setup_.brp_pool_base_address_ & (brp_pool_size - 1))); -#if PA_BUILDFLAG(GLUE_CORE_POOLS) +#if BUILDFLAG(GLUE_CORE_POOLS) PA_DCHECK(!(setup_.regular_pool_base_address_ & (glued_pool_sizes - 1))); #endif @@ -237,7 +237,7 @@ PA_DCHECK(IsInBRPPool(setup_.brp_pool_base_address_)); PA_DCHECK(IsInBRPPool(setup_.brp_pool_base_address_ + brp_pool_size - 1)); PA_DCHECK(!IsInBRPPool(setup_.brp_pool_base_address_ + brp_pool_size)); -#if PA_BUILDFLAG(GLUE_CORE_POOLS) +#if BUILDFLAG(GLUE_CORE_POOLS) PA_DCHECK(!IsInCorePools(setup_.regular_pool_base_address_ - 1)); PA_DCHECK(IsInCorePools(setup_.regular_pool_base_address_)); PA_DCHECK( @@ -248,7 +248,7 @@ PA_DCHECK(IsInCorePools(setup_.brp_pool_base_address_)); PA_DCHECK(IsInCorePools(setup_.brp_pool_base_address_ + brp_pool_size - 1)); PA_DCHECK(!IsInCorePools(setup_.brp_pool_base_address_ + brp_pool_size)); -#endif // PA_BUILDFLAG(GLUE_CORE_POOLS) +#endif // BUILDFLAG(GLUE_CORE_POOLS) #if PA_CONFIG(STARSCAN_USE_CARD_TABLE) // Reserve memory for PCScan quarantine card table. @@ -280,9 +280,9 @@ brp_pool_shadow_address - setup_.brp_pool_base_address_; #endif -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) CompressedPointerBaseGlobal::SetBase(setup_.regular_pool_base_address_); -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION) } void PartitionAddressSpace::InitConfigurablePool(uintptr_t pool_base, @@ -290,7 +290,7 @@ // The ConfigurablePool must only be initialized once. PA_CHECK(!IsConfigurablePoolInitialized()); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // It's possible that the thread isolated pool has been initialized first, in // which case the setup_ memory has been made read-only. Remove the protection // temporarily. @@ -311,7 +311,7 @@ AddressPoolManager::GetInstance().Add( kConfigurablePoolHandle, setup_.configurable_pool_base_address_, size); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // Put the metadata protection back in place. if (IsThreadIsolatedPoolInitialized()) { WriteProtectThreadIsolatedGlobals(setup_.thread_isolation_); @@ -319,7 +319,7 @@ #endif } -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) void PartitionAddressSpace::InitThreadIsolatedPool( ThreadIsolationOption thread_isolation) { // The ThreadIsolated pool can't be initialized with conflicting settings. @@ -354,24 +354,24 @@ // TODO(crbug.com/40238514): support PA_ENABLE_SHADOW_METADATA } -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) void PartitionAddressSpace::UninitForTesting() { -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) UninitThreadIsolatedPoolForTesting(); // IN-TEST #endif -#if PA_BUILDFLAG(GLUE_CORE_POOLS) +#if BUILDFLAG(GLUE_CORE_POOLS) // The core pools (regular & BRP) were allocated using a single allocation of // double size. FreePages(setup_.regular_pool_base_address_, 2 * RegularPoolSize()); -#else // PA_BUILDFLAG(GLUE_CORE_POOLS) +#else // BUILDFLAG(GLUE_CORE_POOLS) FreePages(setup_.regular_pool_base_address_, RegularPoolSize()); // For BRP pool, the allocation region includes a "forbidden zone" before the // pool. const size_t kForbiddenZoneSize = PageAllocationGranularity(); FreePages(setup_.brp_pool_base_address_ - kForbiddenZoneSize, BRPPoolSize() + kForbiddenZoneSize); -#endif // PA_BUILDFLAG(GLUE_CORE_POOLS) +#endif // BUILDFLAG(GLUE_CORE_POOLS) // Do not free pages for the configurable pool, because its memory is owned // by someone else, but deinitialize it nonetheless. setup_.regular_pool_base_address_ = kUninitializedPoolBaseAddress; @@ -379,13 +379,13 @@ setup_.configurable_pool_base_address_ = kUninitializedPoolBaseAddress; setup_.configurable_pool_base_mask_ = 0; AddressPoolManager::GetInstance().ResetForTesting(); -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) CompressedPointerBaseGlobal::ResetBaseForTesting(); -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION) } void PartitionAddressSpace::UninitConfigurablePoolForTesting() { -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // It's possible that the thread isolated pool has been initialized first, in // which case the setup_ memory has been made read-only. Remove the protection // temporarily. @@ -396,7 +396,7 @@ AddressPoolManager::GetInstance().Remove(kConfigurablePoolHandle); setup_.configurable_pool_base_address_ = kUninitializedPoolBaseAddress; setup_.configurable_pool_base_mask_ = 0; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // Put the metadata protection back in place. if (IsThreadIsolatedPoolInitialized()) { WriteProtectThreadIsolatedGlobals(setup_.thread_isolation_); @@ -404,11 +404,11 @@ #endif } -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) void PartitionAddressSpace::UninitThreadIsolatedPoolForTesting() { if (IsThreadIsolatedPoolInitialized()) { UnprotectThreadIsolatedGlobals(); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) ThreadIsolationSettings::settings.enabled = false; #endif @@ -427,6 +427,6 @@ #endif -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h b/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h index f48a8965..54edf02 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h
@@ -22,12 +22,12 @@ #include "partition_alloc/partition_alloc_forward.h" #include "partition_alloc/thread_isolation/alignment.h" -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) #include "partition_alloc/thread_isolation/thread_isolation.h" #endif // The feature is not applicable to 32-bit address space. -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) namespace partition_alloc { @@ -69,13 +69,13 @@ pool_handle pool = kNullPoolHandle; uintptr_t base = 0; uintptr_t base_mask = 0; -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (IsInBRPPool(address)) { pool = kBRPPoolHandle; base = setup_.brp_pool_base_address_; base_mask = BRPPoolBaseMask(); } else -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (IsInRegularPool(address)) { pool = kRegularPoolHandle; base = setup_.regular_pool_base_address_; @@ -85,7 +85,7 @@ pool = kConfigurablePoolHandle; base = setup_.configurable_pool_base_address_; base_mask = setup_.configurable_pool_base_mask_; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) } else if (IsInThreadIsolatedPool(address)) { pool = kThreadIsolatedPoolHandle; base = setup_.thread_isolated_pool_base_address_; @@ -116,7 +116,7 @@ // // This function must only be called from the main thread. static void InitConfigurablePool(uintptr_t pool_base, size_t size); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) static void InitThreadIsolatedPool(ThreadIsolationOption thread_isolation); static void UninitThreadIsolatedPoolForTesting(); #endif @@ -140,7 +140,7 @@ kUninitializedPoolBaseAddress; } -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) PA_ALWAYS_INLINE static bool IsThreadIsolatedPoolInitialized() { return setup_.thread_isolated_pool_base_address_ != kUninitializedPoolBaseAddress; @@ -172,7 +172,7 @@ return (address & brp_pool_base_mask) == setup_.brp_pool_base_address_; } -#if PA_BUILDFLAG(GLUE_CORE_POOLS) +#if BUILDFLAG(GLUE_CORE_POOLS) // Checks whether the address belongs to either regular or BRP pool. // Returns false for nullptr. PA_ALWAYS_INLINE static bool IsInCorePools(uintptr_t address) { @@ -198,7 +198,7 @@ return RegularPoolSize() * 2; } #endif // PA_CONFIG(DYNAMICALLY_SELECT_POOL_SIZE) -#endif // PA_BUILDFLAG(GLUE_CORE_POOLS) +#endif // BUILDFLAG(GLUE_CORE_POOLS) PA_ALWAYS_INLINE static uintptr_t OffsetInBRPPool(uintptr_t address) { PA_DCHECK(IsInBRPPool(address)); @@ -215,7 +215,7 @@ return setup_.configurable_pool_base_address_; } -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // Returns false for nullptr. PA_ALWAYS_INLINE static bool IsInThreadIsolatedPool(uintptr_t address) { return (address & kThreadIsolatedPoolBaseMask) == @@ -258,7 +258,7 @@ } #endif // PA_CONFIG(DYNAMICALLY_SELECT_POOL_SIZE) -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) PA_ALWAYS_INLINE static constexpr size_t ThreadIsolatedPoolSize() { return kThreadIsolatedPoolSize; } @@ -287,7 +287,7 @@ static constexpr size_t kBRPPoolSize = kPoolMaxSize; static_assert(std::has_single_bit(kRegularPoolSize)); static_assert(std::has_single_bit(kBRPPoolSize)); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) static constexpr size_t kThreadIsolatedPoolSize = kGiB / 4; static_assert(std::has_single_bit(kThreadIsolatedPoolSize)); #endif @@ -324,7 +324,7 @@ static constexpr uintptr_t kBRPPoolBaseMask = ~kBRPPoolOffsetMask; #endif // !PA_CONFIG(DYNAMICALLY_SELECT_POOL_SIZE) -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) static constexpr uintptr_t kThreadIsolatedPoolOffsetMask = static_cast<uintptr_t>(kThreadIsolatedPoolSize) - 1; static constexpr uintptr_t kThreadIsolatedPoolBaseMask = @@ -346,23 +346,23 @@ uintptr_t regular_pool_base_address_ = kUninitializedPoolBaseAddress; uintptr_t brp_pool_base_address_ = kUninitializedPoolBaseAddress; uintptr_t configurable_pool_base_address_ = kUninitializedPoolBaseAddress; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) uintptr_t thread_isolated_pool_base_address_ = kUninitializedPoolBaseAddress; #endif #if PA_CONFIG(DYNAMICALLY_SELECT_POOL_SIZE) uintptr_t regular_pool_base_mask_ = 0; uintptr_t brp_pool_base_mask_ = 0; -#if PA_BUILDFLAG(GLUE_CORE_POOLS) +#if BUILDFLAG(GLUE_CORE_POOLS) uintptr_t core_pools_base_mask_ = 0; #endif #endif // PA_CONFIG(DYNAMICALLY_SELECT_POOL_SIZE) uintptr_t configurable_pool_base_mask_ = 0; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) ThreadIsolationOption thread_isolation_; #endif }; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) static_assert(sizeof(PoolSetup) % SystemPageSize() == 0, "PoolSetup has to fill a page(s)"); #else @@ -382,7 +382,7 @@ static std::ptrdiff_t brp_pool_shadow_offset_; #endif -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // If we use thread isolation, we need to write-protect its metadata. // Allow the function to get access to the PoolSetup. friend void WriteProtectThreadIsolatedGlobals(ThreadIsolationOption); @@ -417,10 +417,10 @@ PA_DCHECK(!internal::PartitionAddressSpace::IsInBRPPool(address)); #endif return internal::PartitionAddressSpace::IsInRegularPool(address) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) || internal::PartitionAddressSpace::IsInBRPPool(address) #endif -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) || internal::PartitionAddressSpace::IsInThreadIsolatedPool(address) #endif || internal::PartitionAddressSpace::IsInConfigurablePool(address); @@ -436,13 +436,13 @@ return internal::PartitionAddressSpace::IsInBRPPool(address); } -#if PA_BUILDFLAG(GLUE_CORE_POOLS) +#if BUILDFLAG(GLUE_CORE_POOLS) // Checks whether the address belongs to either regular or BRP pool. // Returns false for nullptr. PA_ALWAYS_INLINE bool IsManagedByPartitionAllocCorePools(uintptr_t address) { return internal::PartitionAddressSpace::IsInCorePools(address); } -#endif // PA_BUILDFLAG(GLUE_CORE_POOLS) +#endif // BUILDFLAG(GLUE_CORE_POOLS) // Returns false for nullptr. PA_ALWAYS_INLINE bool IsManagedByPartitionAllocConfigurablePool( @@ -450,7 +450,7 @@ return internal::PartitionAddressSpace::IsInConfigurablePool(address); } -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // Returns false for nullptr. PA_ALWAYS_INLINE bool IsManagedByPartitionAllocThreadIsolatedPool( uintptr_t address) { @@ -464,6 +464,6 @@ } // namespace partition_alloc -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) #endif // PARTITION_ALLOC_PARTITION_ADDRESS_SPACE_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc-inl.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc-inl.h index c9aba6d..a5a47358 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc-inl.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc-inl.h
@@ -51,7 +51,7 @@ #pragma optimize("", on) #endif -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) // Used to memset() memory for debugging purposes only. PA_ALWAYS_INLINE void DebugMemset(void* ptr, int value, size_t size) { // Only set the first 512kiB of the allocation. This is enough to detect uses @@ -59,13 +59,13 @@ // faster. Note that for direct-mapped allocations, memory is decomitted at // free() time, so freed memory usage cannot happen. -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) LiftThreadIsolationScope lift_thread_isolation_restrictions; #endif size_t size_to_memset = std::min(size, size_t{1} << 19); memset(ptr, value, size_to_memset); } -#endif // PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#endif // BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) // Returns true if we've hit the end of a random-length period. We don't want to // invoke `RandomValue` too often, because we call this function in a hot spot
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc.cc index 18d9997c..358e913 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc.cc
@@ -20,7 +20,7 @@ #include "partition_alloc/partition_root.h" #include "partition_alloc/partition_stats.h" -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) #include "partition_alloc/starscan/pcscan.h" #endif @@ -72,7 +72,7 @@ internal::MaxSystemPagesPerRegularSlotSpan() <= 16, "System pages per slot span must be no greater than 16."); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) STATIC_ASSERT_OR_PA_CHECK( internal::GetInSlotMetadataIndexMultiplierShift() < std::numeric_limits<size_t>::max() / 2, @@ -93,14 +93,14 @@ internal::SystemPageSize(), "InSlotMetadata table size must be smaller than or equal to " "<= SystemPageSize()."); -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_DCHECK(on_out_of_memory); internal::g_oom_handling_function = on_out_of_memory; } void PartitionAllocGlobalUninitForTesting() { -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) internal::PartitionAddressSpace::UninitThreadIsolatedPoolForTesting(); #endif internal::g_oom_handling_function = nullptr; @@ -113,12 +113,12 @@ } void PartitionAllocator::init(PartitionOptions opts) { -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) PA_CHECK(opts.thread_cache == PartitionOptions::kDisabled) << "Cannot use a thread cache when PartitionAlloc is malloc()."; #endif partition_root_.Init(opts); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // The MemoryReclaimer won't have write access to the partition, so skip // registration. const bool use_memory_reclaimer = !opts.thread_isolation.enabled;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_allocation_data.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_allocation_data.h index afe38ae..27cf44ed 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_allocation_data.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_allocation_data.h
@@ -31,7 +31,7 @@ // In the allocation observer path, it's interesting which reporting mode is // enabled. -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) AllocationNotificationData& SetMteReportingMode( TagViolationReportingMode mode) { mte_reporting_mode_ = mode; @@ -45,13 +45,13 @@ constexpr TagViolationReportingMode mte_reporting_mode() const { return TagViolationReportingMode::kUndefined; } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) private: void* address_ = nullptr; size_t size_ = 0; const char* type_name_ = nullptr; -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) TagViolationReportingMode mte_reporting_mode_ = TagViolationReportingMode::kUndefined; #endif @@ -66,7 +66,7 @@ // In the free observer path, it's interesting which reporting mode is // enabled. -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) FreeNotificationData& SetMteReportingMode(TagViolationReportingMode mode) { mte_reporting_mode_ = mode; return *this; @@ -79,14 +79,14 @@ constexpr TagViolationReportingMode mte_reporting_mode() const { return TagViolationReportingMode::kUndefined; } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) private: void* address_ = nullptr; -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) TagViolationReportingMode mte_reporting_mode_ = TagViolationReportingMode::kUndefined; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) }; } // namespace partition_alloc
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/apple/mach_logging.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/apple/mach_logging.h index b3ff53a..70995fc 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/apple/mach_logging.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/apple/mach_logging.h
@@ -47,7 +47,7 @@ } // namespace partition_alloc::internal::logging -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) #define PA_MACH_DVLOG_IS_ON(verbose_level) PA_VLOG_IS_ON(verbose_level) #else #define PA_MACH_DVLOG_IS_ON(verbose_level) 0 @@ -91,9 +91,9 @@ PA_LAZY_STREAM(PA_MACH_VLOG_STREAM(verbose_level, mach_err), \ PA_MACH_DVLOG_IS_ON(verbose_level) && (condition)) -#define PA_MACH_DCHECK(condition, mach_err) \ - PA_LAZY_STREAM(PA_MACH_LOG_STREAM(FATAL, mach_err), \ - PA_BUILDFLAG(PA_DCHECK_IS_ON) && !(condition)) \ +#define PA_MACH_DCHECK(condition, mach_err) \ + PA_LAZY_STREAM(PA_MACH_LOG_STREAM(FATAL, mach_err), \ + BUILDFLAG(PA_DCHECK_IS_ON) && !(condition)) \ << "Check failed: " #condition << ". " #endif // PARTITION_ALLOC_PARTITION_ALLOC_BASE_APPLE_MACH_LOGGING_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/check.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/check.h index 2709d9a..cc28f21f 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/check.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/check.h
@@ -185,7 +185,7 @@ #endif -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) #define PA_BASE_DCHECK(condition) \ PA_LAZY_CHECK_STREAM( \
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace.cc index 5436ffd..993885ce 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace.cc
@@ -19,7 +19,7 @@ namespace partition_alloc::internal::base::debug { namespace { -#if PA_BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) +#if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) #if defined(__arm__) && defined(__GNUC__) && !defined(__clang__) // GCC and LLVM generate slightly different frames on ARM, see @@ -141,11 +141,11 @@ return 0; } -#endif // PA_BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) +#endif // BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) } // namespace -#if PA_BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) +#if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) // We force this function to be inlined into its callers (e.g. // TraceStackFramePointers()) in all build modes so we don't have to worry about @@ -199,7 +199,7 @@ #endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS) -#if PA_BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) +#if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) uintptr_t GetStackEnd() { #if BUILDFLAG(IS_ANDROID) // Bionic reads proc/maps on every call to pthread_getattr_np() when called
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace.h index ce35d49..7627e7e 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace.h
@@ -15,7 +15,7 @@ namespace partition_alloc::internal::base::debug { // Returns end of the stack, or 0 if we couldn't get it. -#if PA_BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) +#if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE) uintptr_t GetStackEnd(); #endif @@ -37,7 +37,7 @@ uintptr_t offset); #endif -#if PA_BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) +#if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) // For stack scanning to be efficient it's very important for the thread to // be started by Chrome. In that case we naturally terminate unwinding once @@ -67,7 +67,7 @@ size_t skip_initial, bool enable_scanning = kEnableScanningByDefault); -#endif // PA_BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) +#endif // BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) } // namespace partition_alloc::internal::base::debug
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace_linux.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace_linux.cc index dbe5f684..851543e 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace_linux.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/debug/stack_trace_linux.cc
@@ -13,7 +13,7 @@ // NOTE: This code MUST be async-signal safe (it's used by in-process // stack dumping signal handler). NO malloc or stdio is allowed here. -#if PA_BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) +#if BUILDFLAG(PA_CAN_UNWIND_WITH_FRAME_POINTERS) // Regarding Linux and Android, backtrace API internally invokes malloc(). // So the API is not available inside memory allocation. Instead try tracing // using frame pointers.
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/fuchsia/fuchsia_logging.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/fuchsia/fuchsia_logging.h index 2108e69..0901fe9 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/fuchsia/fuchsia_logging.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/fuchsia/fuchsia_logging.h
@@ -54,17 +54,17 @@ #define PA_ZX_DLOG(severity, zx_err) \ PA_LAZY_STREAM(PA_ZX_LOG_STREAM(severity, zx_err), PA_DLOG_IS_ON(severity)) -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) #define PA_ZX_DLOG_IF(severity, condition, zx_err) \ PA_LAZY_STREAM(PA_ZX_LOG_STREAM(severity, zx_err), \ PA_DLOG_IS_ON(severity) && (condition)) -#else // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#else // BUILDFLAG(PA_DCHECK_IS_ON) #define PA_ZX_DLOG_IF(severity, condition, zx_err) PA_EAT_STREAM_PARAMETERS -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) -#define PA_ZX_DCHECK(condition, zx_err) \ - PA_LAZY_STREAM(PA_ZX_LOG_STREAM(DCHECK, zx_err), \ - PA_BUILDFLAG(PA_DCHECK_IS_ON) && !(condition)) \ +#define PA_ZX_DCHECK(condition, zx_err) \ + PA_LAZY_STREAM(PA_ZX_LOG_STREAM(DCHECK, zx_err), \ + BUILDFLAG(PA_DCHECK_IS_ON) && !(condition)) \ << "Check failed: " #condition << ". " #endif // PARTITION_ALLOC_PARTITION_ALLOC_BASE_FUCHSIA_FUCHSIA_LOGGING_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/fuchsia/fuchsia_logging_pa_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/fuchsia/fuchsia_logging_pa_unittest.cc index c333b80..271d4483 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/fuchsia/fuchsia_logging_pa_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/fuchsia/fuchsia_logging_pa_unittest.cc
@@ -28,7 +28,7 @@ TEST(FuchsiaLoggingTestPA, FuchsiaLogging) { MockLogSource mock_log_source; constexpr int kTimes = -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) 2; #else 1;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/log_message.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/log_message.cc index db61a86..cfe371e 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/log_message.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/log_message.cc
@@ -63,13 +63,13 @@ } // namespace -#if PA_BUILDFLAG(PA_DCHECK_IS_CONFIGURABLE) +#if BUILDFLAG(PA_DCHECK_IS_CONFIGURABLE) // In DCHECK-enabled Chrome builds, allow the meaning of LOGGING_DCHECK to be // determined at run-time. We default it to ERROR, to avoid it triggering // crashes before the run-time has explicitly chosen the behaviour. PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE) logging::LogSeverity LOGGING_DCHECK = LOGGING_ERROR; -#endif // PA_BUILDFLAG(PA_DCHECK_IS_CONFIGURABLE) +#endif // BUILDFLAG(PA_DCHECK_IS_CONFIGURABLE) // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have // an object of the correct type on the LHS of the unused part of the ternary
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/log_message.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/log_message.h index 24ebcdf..b50d353 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/log_message.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/log_message.h
@@ -41,7 +41,7 @@ // LOGGING_DFATAL is LOGGING_FATAL in DCHECK-enabled builds, ERROR in normal // mode. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) constexpr LogSeverity LOGGING_DFATAL = LOGGING_FATAL; #else constexpr LogSeverity LOGGING_DFATAL = LOGGING_ERROR;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/logging.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/logging.h index 1a243b3..b612f96 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/logging.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/logging.h
@@ -337,7 +337,7 @@ // Definitions for DLOG et al. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) #define PA_DLOG_IS_ON(severity) PA_LOG_IS_ON(severity) #define PA_DLOG_IF(severity, condition) PA_LOG_IF(severity, condition) @@ -347,11 +347,11 @@ #define PA_DVPLOG_IF(verboselevel, condition) \ PA_VPLOG_IF(verboselevel, condition) -#else // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#else // BUILDFLAG(PA_DCHECK_IS_ON) // If !BUILDFLAG(PA_DCHECK_IS_ON), we want to avoid emitting any references to // |condition| (which may reference a variable defined only if -// PA_BUILDFLAG(PA_DCHECK_IS_ON)). Contrast this with DCHECK et al., which has +// BUILDFLAG(PA_DCHECK_IS_ON)). Contrast this with DCHECK et al., which has // different behavior. #define PA_DLOG_IS_ON(severity) false @@ -361,7 +361,7 @@ #define PA_DVLOG_IF(verboselevel, condition) PA_EAT_STREAM_PARAMETERS #define PA_DVPLOG_IF(verboselevel, condition) PA_EAT_STREAM_PARAMETERS -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) #define PA_DLOG(severity) \ PA_LAZY_STREAM(PA_LOG_STREAM(severity), PA_DLOG_IS_ON(severity)) @@ -375,11 +375,11 @@ // Definitions for DCHECK et al. -#if PA_BUILDFLAG(PA_DCHECK_IS_CONFIGURABLE) +#if BUILDFLAG(PA_DCHECK_IS_CONFIGURABLE) PA_COMPONENT_EXPORT(PARTITION_ALLOC_BASE) extern LogSeverity LOGGING_DCHECK; #else constexpr LogSeverity LOGGING_DCHECK = LOGGING_FATAL; -#endif // PA_BUILDFLAG(PA_DCHECK_IS_CONFIGURABLE) +#endif // BUILDFLAG(PA_DCHECK_IS_CONFIGURABLE) // Redefine the standard assert to use our nice log files #undef assert
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/logging_pa_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/logging_pa_unittest.cc index a321e1e..fa8a3a03 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/logging_pa_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/logging_pa_unittest.cc
@@ -26,7 +26,7 @@ TEST(PALoggingTest, BasicLogging) { MockLogSource mock_log_source; constexpr int kTimes = -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) 16; #else 8; @@ -88,7 +88,7 @@ EXPECT_FALSE(PA_LOG_IS_ON(ERROR)); // PA_LOG_IS_ON(FATAL) should always be true. EXPECT_TRUE(PA_LOG_IS_ON(FATAL)); - // If PA_BUILDFLAG(PA_DCHECK_IS_ON) then DFATAL is FATAL. + // If BUILDFLAG(PA_DCHECK_IS_ON) then DFATAL is FATAL. EXPECT_EQ(BUILDFLAG(PA_DCHECK_IS_ON), PA_LOG_IS_ON(DFATAL)); } @@ -131,7 +131,7 @@ } TEST(PALoggingTest, DebugLoggingReleaseBehavior) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) int debug_only_variable = 1; #endif // These should avoid emitting references to |debug_only_variable|
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/memory/ref_counted.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/memory/ref_counted.cc index c31daac7..da9e227 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/memory/ref_counted.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/memory/ref_counted.cc
@@ -21,7 +21,7 @@ return !ref_count_.IsZero(); } -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) RefCountedThreadSafeBase::~RefCountedThreadSafeBase() { PA_BASE_DCHECK(in_dtor_) << "RefCountedThreadSafe object deleted without " "calling Release()";
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/memory/ref_counted.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/memory/ref_counted.h index 592c404..2f06b618 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/memory/ref_counted.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/memory/ref_counted.h
@@ -28,12 +28,12 @@ explicit constexpr RefCountedThreadSafeBase(StartRefCountFromZeroTag) {} explicit constexpr RefCountedThreadSafeBase(StartRefCountFromOneTag) : ref_count_(1) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) needs_adopt_ref_ = true; #endif } -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) ~RefCountedThreadSafeBase(); #else ~RefCountedThreadSafeBase() = default; @@ -59,14 +59,14 @@ friend scoped_refptr<U> AdoptRef(U*); void Adopted() const { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_BASE_DCHECK(needs_adopt_ref_); needs_adopt_ref_ = false; #endif } PA_ALWAYS_INLINE void AddRefImpl() const { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_BASE_DCHECK(!in_dtor_); // This RefCounted object is created with non-zero reference count. // The first reference to such a object has to be made by AdoptRef or @@ -77,7 +77,7 @@ } PA_ALWAYS_INLINE void AddRefWithCheckImpl() const { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_BASE_DCHECK(!in_dtor_); // This RefCounted object is created with non-zero reference count. // The first reference to such a object has to be made by AdoptRef or @@ -88,12 +88,12 @@ } PA_ALWAYS_INLINE bool ReleaseImpl() const { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_BASE_DCHECK(!in_dtor_); PA_BASE_DCHECK(!ref_count_.IsZero()); #endif if (!ref_count_.Decrement()) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) in_dtor_ = true; #endif return true; @@ -102,7 +102,7 @@ } mutable AtomicRefCount ref_count_{0}; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) mutable bool needs_adopt_ref_ = false; mutable bool in_dtor_ = false; #endif
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/cstring_builder.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/cstring_builder.cc index f7442c07..2cafe39 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/cstring_builder.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/strings/cstring_builder.cc
@@ -16,7 +16,7 @@ #include <cstring> #include <limits> -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) #include "partition_alloc/partition_alloc_base/check.h" #define PA_RAW_DCHECK PA_RAW_CHECK #else
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/thread_annotations.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/thread_annotations.h index 525beb3e..a5df5c2f 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/thread_annotations.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/thread_annotations.h
@@ -246,7 +246,7 @@ // The above is imported as-is from abseil-cpp. The following Chromium-specific // synonyms are added for Chromium concepts (SequenceChecker/ThreadChecker). -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Equivalent to PA_GUARDED_BY for SequenceChecker/ThreadChecker. Currently, #define PA_GUARDED_BY_CONTEXT(name) PA_GUARDED_BY(name) @@ -254,11 +254,11 @@ // Equivalent to PA_EXCLUSIVE_LOCKS_REQUIRED for SequenceChecker/ThreadChecker. #define PA_VALID_CONTEXT_REQUIRED(name) PA_EXCLUSIVE_LOCKS_REQUIRED(name) -#else // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#else // BUILDFLAG(PA_DCHECK_IS_ON) #define PA_GUARDED_BY_CONTEXT(name) #define PA_VALID_CONTEXT_REQUIRED(name) -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) #endif // PARTITION_ALLOC_PARTITION_ALLOC_BASE_THREAD_ANNOTATIONS_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix.cc index e399951..dfdb0d1 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix.cc
@@ -95,7 +95,7 @@ g_is_main_thread = false; } } else { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) if (g_thread_id != syscall(__NR_gettid)) { PA_RAW_LOG( FATAL,
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix_for_testing.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix_for_testing.cc index d0bb1eb..c8551ad 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix_for_testing.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_posix_for_testing.cc
@@ -26,7 +26,7 @@ #include <sys/resource.h> #endif -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN) #include "partition_alloc/stack/stack.h" #include "partition_alloc/starscan/pcscan.h" #endif @@ -52,14 +52,14 @@ delegate = thread_params->delegate; -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN) StackTopRegistry::Get().NotifyThreadCreated(); #endif } delegate->ThreadMain(); -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN) StackTopRegistry::Get().NotifyThreadDestroyed(); #endif
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_win_for_testing.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_win_for_testing.cc index 2ff67148..0e82dde 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_win_for_testing.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/threading/platform_thread_win_for_testing.cc
@@ -13,7 +13,7 @@ #include "partition_alloc/partition_alloc_base/threading/platform_thread_for_testing.h" #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN) #include "partition_alloc/stack/stack.h" #include "partition_alloc/starscan/pcscan.h" #endif @@ -63,7 +63,7 @@ GetCurrentProcess(), &platform_handle, 0, FALSE, DUPLICATE_SAME_ACCESS); -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN) StackTopRegistry::Get().NotifyThreadCreated(); #endif @@ -75,7 +75,7 @@ delete thread_params; delegate->ThreadMain(); -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN) StackTopRegistry::Get().NotifyThreadDestroyed(); #endif return 0;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/time/time.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/time/time.h index 9a33219..42bed11 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/time/time.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/time/time.h
@@ -866,14 +866,14 @@ #endif // BUILDFLAG(IS_APPLE) -#if BUILDFLAG(IS_ANDROID) || PA_BUILDFLAG(PA_IS_CHROMEOS_ASH) +#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(PA_IS_CHROMEOS_ASH) // Converts to TimeTicks the value obtained from SystemClock.uptimeMillis(). // Note: this conversion may be non-monotonic in relation to previously // obtained TimeTicks::Now() values because of the truncation (to // milliseconds) performed by uptimeMillis(). static TimeTicks FromUptimeMillis(int64_t uptime_millis_value); -#endif // BUILDFLAG(IS_ANDROID) || PA_BUILDFLAG(PA_IS_CHROMEOS_ASH) +#endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(PA_IS_CHROMEOS_ASH) #if BUILDFLAG(IS_ANDROID) // Converts to TimeTicks the value obtained from System.nanoTime(). This
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_check.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_check.h index 3e8aa7b..d589b03 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_check.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_check.h
@@ -25,7 +25,7 @@ // As a consequence: // - When PartitionAlloc is not malloc(), use the regular macros // - Otherwise, crash immediately. This provides worse error messages though. -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && !PA_BASE_CHECK_WILL_STREAM() +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && !PA_BASE_CHECK_WILL_STREAM() // For official build discard log strings to reduce binary bloat. // See base/check.h for implementation details. @@ -33,11 +33,11 @@ PA_UNLIKELY(!(condition)) ? PA_IMMEDIATE_CRASH() \ : PA_EAT_CHECK_STREAM_PARAMS() -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) #define PA_DCHECK(condition) PA_CHECK(condition) #else #define PA_DCHECK(condition) PA_EAT_CHECK_STREAM_PARAMS(!(condition)) -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) #define PA_PCHECK(condition) \ if (!(condition)) { \ @@ -47,25 +47,25 @@ } \ static_assert(true) -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) #define PA_DPCHECK(condition) PA_PCHECK(condition) #else #define PA_DPCHECK(condition) PA_EAT_CHECK_STREAM_PARAMS(!(condition)) -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) -#else // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && +#else // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && // !PA_BASE_CHECK_WILL_STREAM() #define PA_CHECK(condition) PA_BASE_CHECK(condition) #define PA_DCHECK(condition) PA_BASE_DCHECK(condition) #define PA_PCHECK(condition) PA_BASE_PCHECK(condition) #define PA_DPCHECK(condition) PA_BASE_DPCHECK(condition) -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && // !PA_BASE_CHECK_WILL_STREAM() // Expensive dchecks that run within *Scan. These checks are only enabled in // debug builds with dchecks enabled. #if !defined(NDEBUG) -#define PA_SCAN_DCHECK_IS_ON() PA_BUILDFLAG(PA_DCHECK_IS_ON) +#define PA_SCAN_DCHECK_IS_ON() BUILDFLAG(PA_DCHECK_IS_ON) #else #define PA_SCAN_DCHECK_IS_ON() 0 #endif
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_config.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_config.h index 67f47573..ac33c50c 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_config.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_config.h
@@ -30,20 +30,20 @@ // Assert that the heuristic in partition_alloc.gni is accurate on supported // configurations. -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) static_assert(sizeof(void*) == 8, ""); #else static_assert(sizeof(void*) != 8, ""); #endif // PA_CONFIG(HAS_64_BITS_POINTERS) -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) && \ +#if BUILDFLAG(HAS_64_BIT_POINTERS) && \ (defined(__ARM_NEON) || defined(__ARM_NEON__)) && defined(__ARM_FP) #define PA_CONFIG_STARSCAN_NEON_SUPPORTED() 1 #else #define PA_CONFIG_STARSCAN_NEON_SUPPORTED() 0 #endif -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(IS_IOS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(IS_IOS) // Allow PA to select an alternate pool size at run-time before initialization, // rather than using a single constexpr value. // @@ -54,9 +54,9 @@ #define PA_CONFIG_DYNAMICALLY_SELECT_POOL_SIZE() 1 #else #define PA_CONFIG_DYNAMICALLY_SELECT_POOL_SIZE() 0 -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(IS_IOS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(IS_IOS) -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) && \ +#if BUILDFLAG(HAS_64_BIT_POINTERS) && \ (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID)) #include <linux/version.h> // TODO(bikineev): Enable for ChromeOS. @@ -64,10 +64,10 @@ (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 8, 0)) #else #define PA_CONFIG_STARSCAN_UFFD_WRITE_PROTECTOR_SUPPORTED() 0 -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) && +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) && // (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_ANDROID)) -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) // Use card table to avoid races for PCScan configuration without safepoints. // The card table provides the guaranteee that for a marked card the underling // super-page is fully initialized. @@ -75,7 +75,7 @@ #else // The card table is permanently disabled for 32-bit. #define PA_CONFIG_STARSCAN_USE_CARD_TABLE() 0 -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) // Use batched freeing when sweeping pages. This builds up a freelist in the // scanner thread and appends to the slot-span's freelist only once. @@ -133,7 +133,7 @@ // Too expensive for official builds, as it adds cache misses to all // allocations. On the other hand, we want wide metrics coverage to get // realistic profiles. -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && !defined(OFFICIAL_BUILD) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && !defined(OFFICIAL_BUILD) #define PA_CONFIG_THREAD_CACHE_ALLOC_STATS() 1 #else #define PA_CONFIG_THREAD_CACHE_ALLOC_STATS() 0 @@ -156,12 +156,12 @@ #define PA_CONFIG_HAS_FREELIST_SHADOW_ENTRY() 0 #endif -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) static_assert(sizeof(void*) == 8); #endif // Specifies whether allocation extras need to be added. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) #define PA_CONFIG_EXTRAS_REQUIRED() 1 #else #define PA_CONFIG_EXTRAS_REQUIRED() 0 @@ -201,11 +201,10 @@ // calling malloc() again. // // Limitations: -// - PA_BUILDFLAG(PA_DCHECK_IS_ON) due to runtime cost +// - BUILDFLAG(PA_DCHECK_IS_ON) due to runtime cost // - thread_local TLS to simplify the implementation // - Not on Android due to bot failures -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) && \ - PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ +#if BUILDFLAG(PA_DCHECK_IS_ON) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ PA_CONFIG(THREAD_LOCAL_TLS) && !BUILDFLAG(IS_ANDROID) #define PA_CONFIG_HAS_ALLOCATION_GUARD() 1 #else @@ -236,7 +235,7 @@ // PartitionAlloc uses PartitionRootEnumerator to acquire all // PartitionRoots at BeforeFork and to release at AfterFork. -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_CONFIG(HAS_ATFORK_HANDLER) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_CONFIG(HAS_ATFORK_HANDLER) #define PA_CONFIG_USE_PARTITION_ROOT_ENUMERATOR() 1 #else #define PA_CONFIG_USE_PARTITION_ROOT_ENUMERATOR() 0 @@ -246,11 +245,11 @@ // are on. However, don't do this if that would cause InSlotMetadata to grow // past the size that would fit in InSlotMetadataTable (see // partition_alloc_constants.h), which currently can happen only when DPD is on. -#define PA_CONFIG_IN_SLOT_METADATA_CHECK_COOKIE() \ - (!(BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) && \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)) && \ - (BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS))) +#define PA_CONFIG_IN_SLOT_METADATA_CHECK_COOKIE() \ + (!(BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) && \ + BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)) && \ + (BUILDFLAG(PA_DCHECK_IS_ON) || \ + BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS))) // Use available space in the reference count to store the initially requested // size from the application. This is used for debugging. @@ -291,8 +290,8 @@ // metadatas are placed, and the real metadatas are set to read-only instead. // This feature is only enabled with 64-bit environment because pools work // differently with 32-bits pointers (see glossary). -#if PA_BUILDFLAG(ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS) && \ - PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(ENABLE_SHADOW_METADATA_FOR_64_BITS_POINTERS) && \ + BUILDFLAG(HAS_64_BIT_POINTERS) #define PA_CONFIG_ENABLE_SHADOW_METADATA() 1 #else #define PA_CONFIG_ENABLE_SHADOW_METADATA() 0 @@ -309,23 +308,23 @@ // // The settings has MAYBE_ in the name, because the final decision to enable is // based on the operarting system version check done at run-time. -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && BUILDFLAG(IS_MAC) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && BUILDFLAG(IS_MAC) #define PA_CONFIG_MAYBE_ENABLE_MAC11_MALLOC_SIZE_HACK() 1 #else #define PA_CONFIG_MAYBE_ENABLE_MAC11_MALLOC_SIZE_HACK() 0 #endif -#if PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#if BUILDFLAG(ENABLE_POINTER_COMPRESSION) #if PA_CONFIG(DYNAMICALLY_SELECT_POOL_SIZE) #error "Dynamically selected pool size is currently not supported" #endif -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) // TODO(crbug.com/40243421): Address MTE once it's enabled. #error "Compressed pointers don't support tag in the upper bits" #endif -#endif // PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) +#endif // BUILDFLAG(ENABLE_POINTER_COMPRESSION) // PA_CONFIG(IS_NONCLANG_MSVC): mimics the compound condition used by // Chromium's `//base/compiler_specific.h` to detect true (non-Clang) @@ -337,9 +336,9 @@ #endif // Set GN build override 'assert_cpp_20' to false to disable assertion. -#if PA_BUILDFLAG(ASSERT_CPP_20) +#if BUILDFLAG(ASSERT_CPP_20) static_assert(__cplusplus >= 202002L, "PartitionAlloc targets C++20 or higher."); -#endif // PA_BUILDFLAG(ASSERT_CPP_20) +#endif // BUILDFLAG(ASSERT_CPP_20) #endif // PARTITION_ALLOC_PARTITION_ALLOC_CONFIG_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_constants.h b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_constants.h index 63652bc..1cc238c 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_constants.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_constants.h
@@ -23,7 +23,7 @@ #include <mach/vm_page_size.h> #endif -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) #include "partition_alloc/tagging.h" #endif @@ -286,13 +286,13 @@ kRegularPoolHandle, kBRPPoolHandle, -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) kConfigurablePoolHandle, #endif // New pool_handles will be added here. -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // The thread isolated pool must come last since we write-protect its entry in // the metadata tables, e.g. AddressPoolManager::aligned_pools_ kThreadIsolatedPoolHandle, @@ -314,19 +314,19 @@ // // When pointer compression is enabled, we cannot use large pools (at most // 8GB for each of the glued pools). -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS) || \ - PA_BUILDFLAG(ENABLE_POINTER_COMPRESSION) + BUILDFLAG(ENABLE_POINTER_COMPRESSION) constexpr size_t kPoolMaxSize = 8 * kGiB; #else constexpr size_t kPoolMaxSize = 16 * kGiB; #endif -#else // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#else // BUILDFLAG(HAS_64_BIT_POINTERS) constexpr size_t kPoolMaxSize = 4 * kGiB; #endif constexpr size_t kMaxSuperPagesInPool = kPoolMaxSize / kSuperPageSize; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) static_assert(kThreadIsolatedPoolHandle == kNumPools, "The thread isolated pool must come last since we write-protect " "its metadata."); @@ -338,7 +338,7 @@ // of large areas which are less likely to benefit from MTE protection. constexpr size_t kMaxMemoryTaggingSize = 1024; -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) // Returns whether the tag of |object| overflowed, meaning the containing slot // needs to be moved to quarantine. PA_ALWAYS_INLINE bool HasOverflowTag(void* object) { @@ -348,7 +348,7 @@ "Overflow tag must be in tag bits"); return (reinterpret_cast<uintptr_t>(object) & kPtrTagMask) == kOverflowTag; } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) PA_ALWAYS_INLINE PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR size_t NumPartitionPagesPerSuperPage() { @@ -359,7 +359,7 @@ return kMaxSuperPagesInPool; } -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // In 64-bit mode, the direct map allocation granularity is super page size, // because this is the reservation granularity of the pools. PA_ALWAYS_INLINE constexpr size_t DirectMapAllocationGranularity() { @@ -369,7 +369,7 @@ PA_ALWAYS_INLINE constexpr size_t DirectMapAllocationGranularityShift() { return kSuperPageShift; } -#else // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#else // BUILDFLAG(HAS_64_BIT_POINTERS) // In 32-bit mode, address space is space is a scarce resource. Use the system // allocation granularity, which is the lowest possible address space allocation // unit. However, don't go below partition page size, so that pool bitmaps @@ -383,7 +383,7 @@ DirectMapAllocationGranularityShift() { return std::max(PageAllocationGranularityShift(), PartitionPageShift()); } -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) PA_ALWAYS_INLINE PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR size_t DirectMapAllocationGranularityOffsetMask() { @@ -470,7 +470,7 @@ // PurgeFlags::kDecommitEmptySlotSpans flag will eagerly decommit all entries // in the ring buffer, so with periodic purge enabled, this typically happens // every few seconds. -#if PA_BUILDFLAG(USE_LARGE_EMPTY_SLOT_SPAN_RING) +#if BUILDFLAG(USE_LARGE_EMPTY_SLOT_SPAN_RING) // USE_LARGE_EMPTY_SLOT_SPAN_RING results in two size. kMaxEmptyCacheIndexBits, // which is used when the renderer is in the foreground, and // kMinEmptyCacheIndexBits which is used when the renderer is in the background.
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest.cc index fae9c9c..cba6e61 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest.cc
@@ -70,7 +70,7 @@ #include <sys/time.h> #endif // BUILDFLAG(IS_POSIX) -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_MAC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_MAC) #include <OpenCL/opencl.h> #endif @@ -78,7 +78,7 @@ #include "partition_alloc/partition_alloc_base/mac/mac_util.h" #endif -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) #include <sys/syscall.h> #endif @@ -263,7 +263,7 @@ PartitionAllocTestParam{BucketDistribution::kNeutral, false}); params.emplace_back( PartitionAllocTestParam{BucketDistribution::kDenser, false}); -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) if (CPUHasPkeySupport()) { params.emplace_back( PartitionAllocTestParam{BucketDistribution::kNeutral, true}); @@ -350,11 +350,11 @@ } void InitializeMainTestAllocators() { -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PartitionOptions::EnableToggle enable_backup_ref_ptr = PartitionOptions::kEnabled; #endif -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) int pkey = PkeyAlloc(UseThreadIsolatedPool() ? 0 : PKEY_DISABLE_WRITE); if (pkey != -1) { pkey_ = pkey; @@ -372,22 +372,22 @@ ThreadIsolationOption thread_isolation_opt; if (UseThreadIsolatedPool() && pkey_ != kInvalidPkey) { thread_isolation_opt = ThreadIsolationOption(pkey_); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // BRP and thread isolated mode use different pools, so they can't be // enabled at the same time. enable_backup_ref_ptr = PartitionOptions::kDisabled; #endif } -#endif // PA_BUILDFLAG(ENABLE_PKEYS) +#endif // BUILDFLAG(ENABLE_PKEYS) PartitionOptions opts = GetCommonPartitionOptions(); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) opts.backup_ref_ptr = enable_backup_ref_ptr; #endif -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) opts.thread_isolation = thread_isolation_opt; #endif -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) opts.memory_tagging = { .enabled = partition_alloc::internal::base::CPU::GetInstanceNoAllocation() @@ -395,7 +395,7 @@ ? PartitionOptions::kEnabled : PartitionOptions::kDisabled, }; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) InitializeTestRoot( allocator.root(), opts, PartitionTestOptions{.use_memory_reclaimer = true, @@ -423,7 +423,7 @@ allocator.root()->PurgeMemory(PurgeFlags::kDecommitEmptySlotSpans | PurgeFlags::kDiscardUnusedSystemPages); PartitionAllocGlobalUninitForTesting(); -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) if (pkey_ != kInvalidPkey) { PkeyFree(pkey_); } @@ -443,12 +443,12 @@ static size_t ExtraAllocSize(const PartitionAllocator& allocator) { size_t metadata_size = 0; // Duplicate the logic from PartitionRoot::Init(). -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (allocator.root()->brp_enabled()) { metadata_size = AlignUpInSlotMetadataSizeForApple(kInSlotMetadataSizeAdjustment); } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) return kExtraAllocSizeWithoutMetadata + metadata_size; } @@ -574,7 +574,7 @@ PA_LOG(FATAL) << "Passed DoReturnNullTest"; } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) void RunRefCountReallocSubtest(size_t orig_size, size_t new_size); #endif @@ -590,20 +590,20 @@ bool UseThreadIsolatedPool() const { return GetParam().use_pkey_pool; } bool UseBRPPool() const { -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) return allocator.root()->brp_enabled(); #else return false; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) } partition_alloc::PartitionAllocatorForTesting allocator; -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) partition_alloc::PartitionAllocatorForTesting pkey_allocator; #endif size_t test_bucket_index_; -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) int pkey_ = kInvalidPkey; #endif }; @@ -1101,7 +1101,7 @@ // Check that the realloc copied correctly. char* new_char_ptr = static_cast<char*>(new_ptr); EXPECT_EQ(*new_char_ptr, 'A'); -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) // Subtle: this checks for an old bug where we copied too much from the // source of the realloc. The condition can be detected by a trashing of // the uninitialized value in the space of the upsized allocation. @@ -1217,7 +1217,7 @@ allocator.root()->Free(new_ptr_2); allocator.root()->Free(ptr4); -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) // |SlotSpanMetadata::Free| must poison the slot's contents with // |kFreedByte|. EXPECT_EQ(kFreedByte, @@ -1271,7 +1271,7 @@ allocator.root()->AllocationCapacityFromSlotStart(slot_start); EXPECT_EQ(predicted_capacity, actual_capacity); EXPECT_LT(requested_size, actual_capacity); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (UseBRPPool()) { uintptr_t address = UntagPtr(ptr); for (size_t offset = 0; offset < requested_size; ++offset) { @@ -1280,7 +1280,7 @@ slot_start); } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) allocator.root()->Free(ptr); // Allocate a size that should be a perfect match for a bucket, because it @@ -1295,7 +1295,7 @@ allocator.root()->AllocationCapacityFromSlotStart(slot_start); EXPECT_EQ(predicted_capacity, actual_capacity); EXPECT_EQ(requested_size, actual_capacity); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (UseBRPPool()) { uintptr_t address = UntagPtr(ptr); for (size_t offset = 0; offset < requested_size; offset += 877) { @@ -1304,7 +1304,7 @@ slot_start); } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) allocator.root()->Free(ptr); // Allocate a size that is a system page smaller than a bucket. @@ -1325,7 +1325,7 @@ allocator.root()->AllocationCapacityFromSlotStart(slot_start); EXPECT_EQ(predicted_capacity, actual_capacity); EXPECT_EQ(requested_size + SystemPageSize(), actual_capacity); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (UseBRPPool()) { uintptr_t address = UntagPtr(ptr); for (size_t offset = 0; offset < requested_size; offset += 4999) { @@ -1334,7 +1334,7 @@ slot_start); } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) allocator.root()->Free(ptr); // Allocate the maximum allowed bucketed size. @@ -1348,7 +1348,7 @@ allocator.root()->AllocationCapacityFromSlotStart(slot_start); EXPECT_EQ(predicted_capacity, actual_capacity); EXPECT_EQ(requested_size, actual_capacity); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (UseBRPPool()) { uintptr_t address = UntagPtr(ptr); for (size_t offset = 0; offset < requested_size; offset += 4999) { @@ -1357,7 +1357,7 @@ slot_start); } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // Check that we can write at the end of the reported size too. char* char_ptr = static_cast<char*>(ptr); @@ -1378,7 +1378,7 @@ EXPECT_LT(requested_size, actual_capacity); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (UseBRPPool()) { uintptr_t address = UntagPtr(ptr); for (size_t offset = 0; offset < requested_size; offset += 16111) { @@ -1387,7 +1387,7 @@ slot_start); } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) allocator.root()->Free(ptr); } @@ -1398,7 +1398,7 @@ EXPECT_EQ(requested_size, predicted_capacity); } -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) TEST_P(PartitionAllocTest, MTEProtectsFreedPtr) { // This test checks that Arm's memory tagging extension (MTE) is correctly // protecting freed pointers. @@ -1437,9 +1437,9 @@ // We don't check anything about ptr3, but we do clean it up to avoid DCHECKs. allocator.root()->Free(ptr3); } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) TEST_P(PartitionAllocTest, IsPtrWithinSameAlloc) { if (!UseBRPPool()) { return; @@ -1462,7 +1462,7 @@ kMaxBucketed + SystemPageSize(), kMaxBucketed + PartitionPageSize(), kSuperPageSize}; -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) constexpr size_t kFarFarAwayDelta = 512 * kGiB; #else constexpr size_t kFarFarAwayDelta = kGiB; @@ -1502,7 +1502,7 @@ PtrPosWithinAlloc::kInBounds); EXPECT_EQ(IsPtrWithinSameAlloc(address, address + requested_size / 2, 0u), PtrPosWithinAlloc::kInBounds); -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) EXPECT_EQ(IsPtrWithinSameAlloc(address, address + requested_size - 1, 1u), PtrPosWithinAlloc::kInBounds); EXPECT_EQ(IsPtrWithinSameAlloc(address, address + requested_size, 1u), @@ -1514,7 +1514,7 @@ address, address + requested_size - subtrahend, 4u), PtrPosWithinAlloc::kAllocEnd); } -#else // PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#else // BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) EXPECT_EQ(IsPtrWithinSameAlloc(address, address + requested_size, 0u), PtrPosWithinAlloc::kInBounds); #endif @@ -1537,7 +1537,7 @@ EXPECT_EQ(IsPtrWithinSameAlloc(address + requested_size, address + requested_size + 1, 0u), PtrPosWithinAlloc::kFarOOB); -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) EXPECT_EQ(IsPtrWithinSameAlloc(address + requested_size - 1, address + requested_size - 1, 1u), PtrPosWithinAlloc::kInBounds); @@ -1556,7 +1556,7 @@ address + requested_size - 4 + addend, 4u), PtrPosWithinAlloc::kAllocEnd); } -#else // PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#else // BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) EXPECT_EQ(IsPtrWithinSameAlloc(address + requested_size, address + requested_size, 0u), PtrPosWithinAlloc::kInBounds); @@ -1641,7 +1641,7 @@ allocator.root()->Free(ptr); } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // Test the realloc() contract. TEST_P(PartitionAllocTest, Realloc) { @@ -1668,7 +1668,7 @@ char* char_ptr2 = static_cast<char*>(ptr2); EXPECT_EQ('A', char_ptr2[0]); EXPECT_EQ('A', char_ptr2[size - 1]); -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) EXPECT_EQ(kUninitializedByte, static_cast<unsigned char>(char_ptr2[size])); #endif @@ -1680,7 +1680,7 @@ char* char_ptr = static_cast<char*>(ptr); EXPECT_EQ('A', char_ptr[0]); EXPECT_EQ('A', char_ptr[size - 2]); -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) EXPECT_EQ(kUninitializedByte, static_cast<unsigned char>(char_ptr[size - 1])); #endif @@ -1700,7 +1700,7 @@ char_ptr2 = static_cast<char*>(ptr2); EXPECT_EQ('A', char_ptr2[0]); EXPECT_EQ('A', char_ptr2[size - 1]); -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) EXPECT_EQ(kUninitializedByte, static_cast<unsigned char>(char_ptr2[size])); #endif allocator.root()->Free(ptr2); @@ -1716,7 +1716,7 @@ char_ptr2 = static_cast<char*>(ptr2); EXPECT_EQ('A', char_ptr2[0]); EXPECT_EQ('A', char_ptr2[size / 2 - 1]); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // For single-slot slot spans, the cookie is always placed immediately after // the allocation. EXPECT_EQ(kCookieValue[0], static_cast<unsigned char>(char_ptr2[size / 2])); @@ -2404,7 +2404,7 @@ // Performing them as death tests causes them to be forked into their own // process, so they won't pollute other tests. // -// These tests are *very* slow when PA_BUILDFLAG(PA_DCHECK_IS_ON), because they +// These tests are *very* slow when BUILDFLAG(PA_DCHECK_IS_ON), because they // memset() many GiB of data (see crbug.com/1168168). // TODO(lizeb): make these tests faster. TEST_P(PartitionAllocDeathTest, MAYBE_RepeatedAllocReturnNullDirect) { @@ -2446,7 +2446,7 @@ "Passed DoReturnNullTest"); } -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) // Check that Arm's memory tagging extension (MTE) is correctly protecting // freed pointers. Writes to a free pointer should result in a crash. TEST_P(PartitionAllocDeathTest, MTEProtectsFreedPtr) { @@ -2479,7 +2479,7 @@ }, testing::KilledBySignal(SIGSEGV), ""); } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) // Make sure that malloc(-1) dies. // In the past, we had an integer overflow that would alias malloc(-1) to @@ -2609,8 +2609,7 @@ allocator.root()->Free(fake_freelist_entry); } -// With PA_BUILDFLAG(PA_DCHECK_IS_ON), cookie already handles off-by-one -// detection. +// With BUILDFLAG(PA_DCHECK_IS_ON), cookie already handles off-by-one detection. #if !BUILDFLAG(PA_DCHECK_IS_ON) TEST_P(PartitionAllocDeathTest, OffByOneDetection) { base::CPU cpu; @@ -4161,7 +4160,7 @@ } } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) TEST_P(PartitionAllocTest, RefCountBasic) { if (!UseBRPPool()) { @@ -4379,9 +4378,9 @@ } } #endif // !BUILDFLAG(HAS_64_BIT_POINTERS) -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) -#if PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) // Allocate memory, and reference it from 3 raw_ptr. Among them 2 will be // dangling. @@ -4823,7 +4822,7 @@ #endif //! defined(OFFICIAL_BUILD) || !defined(NDEBUG) #endif // PA_USE_DEATH_TESTS() -#endif // PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#endif // BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) TEST_P(PartitionAllocTest, ReservationOffset) { // For normal buckets, offset should be kOffsetTagNormalBuckets. @@ -4958,11 +4957,10 @@ partition_alloc::internal::base::bits::AlignDown(address, kSuperPageSize); // DCHECKs don't work with EXPECT_DEATH on official builds. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) && \ - (!defined(OFFICIAL_BUILD) || !defined(NDEBUG)) +#if BUILDFLAG(PA_DCHECK_IS_ON) && (!defined(OFFICIAL_BUILD) || !defined(NDEBUG)) // Expect to DCHECK on unallocated region. EXPECT_DEATH_IF_SUPPORTED(IsReservationStart(address_to_check), ""); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) && (!defined(OFFICIAL_BUILD) || +#endif // BUILDFLAG(PA_DCHECK_IS_ON) && (!defined(OFFICIAL_BUILD) || // !defined(NDEBUG)) EXPECT_FALSE(IsManagedByNormalBuckets(address_to_check)); @@ -5044,7 +5042,7 @@ // Not on chromecast, since gtest considers extra output from itself as a test // failure: // https://ci.chromium.org/ui/p/chromium/builders/ci/Cast%20Audio%20Linux/98492/overview -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_USE_DEATH_TESTS() && \ +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_USE_DEATH_TESTS() && \ !BUILDFLAG(PA_IS_CASTOS) namespace { @@ -5121,7 +5119,7 @@ } } -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && // PA_USE_DEATH_TESTS() && !BUILDFLAG(PA_IS_CASTOS) // Checks the bucket index logic. @@ -5339,8 +5337,7 @@ #endif } -#if PA_BUILDFLAG(PA_IS_CAST_ANDROID) && \ - PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(PA_IS_CAST_ANDROID) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) extern "C" { void* __real_malloc(size_t); } // extern "C" @@ -5408,16 +5405,16 @@ allocator.root()->Free(first_ptr); } -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_LINUX) && \ +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_LINUX) && \ defined(ARCH_CPU_64_BITS) TEST_P(PartitionAllocTest, CrashOnUnknownPointer) { int not_a_heap_object = 42; EXPECT_DEATH(allocator.root()->Free(¬_a_heap_object), ""); } -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && // BUILDFLAG(IS_LINUX) && defined(ARCH_CPU_64_BITS) -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_MAC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_MAC) // Adapted from crashpad tests. class ScopedOpenCLNoOpKernel { @@ -5512,7 +5509,7 @@ #endif } -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && // BUILDFLAG(IS_MAC) TEST_P(PartitionAllocTest, SmallSlotSpanWaste) { @@ -5603,7 +5600,7 @@ run_test(1); } -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) TEST_P(PartitionAllocTest, FreeSlotBitmapMarkedAsUsedAfterAlloc) { void* ptr = allocator.root()->Alloc(kTestAllocSize, type_name); uintptr_t slot_start = allocator.root()->ObjectToSlotStart(ptr); @@ -5651,9 +5648,9 @@ allocator.root()->Free(ptr1); } -#endif // PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#endif // BUILDFLAG(USE_FREESLOT_BITMAP) -#if PA_BUILDFLAG(USE_LARGE_EMPTY_SLOT_SPAN_RING) +#if BUILDFLAG(USE_LARGE_EMPTY_SLOT_SPAN_RING) TEST_P(PartitionAllocTest, GlobalEmptySlotSpanRingIndexResets) { // Switch to the larger slot span size, and set the // global_empty_slot_span_ring_index to one less than max.
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.cc index a4111ba..a91b507 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_bucket.cc
@@ -38,7 +38,7 @@ #include "partition_alloc/reservation_offset_table.h" #include "partition_alloc/tagging.h" -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) #include "partition_alloc/starscan/pcscan.h" #endif @@ -73,8 +73,7 @@ PA_IMMEDIATE_CRASH(); // Not required, kept as documentation. } -#if !BUILDFLAG(HAS_64_BIT_POINTERS) && \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if !BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // |start| has to be aligned to kSuperPageSize, but |end| doesn't. This means // that a partial super page is allowed at the end. Since the block list uses // kSuperPageSize granularity, a partial super page is considered blocked if @@ -94,7 +93,7 @@ return true; } #endif // !BUILDFLAG(HAS_64_BIT_POINTERS) && - // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) + // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // Reserves |requested_size| worth of super pages from the specified pool. // If BRP pool is requested this function will honor BRP block list. @@ -123,8 +122,7 @@ // In 32-bit mode, when allocating from BRP pool, verify that the requested // allocation honors the block list. Find a better address otherwise. -#if !BUILDFLAG(HAS_64_BIT_POINTERS) && \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if !BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (pool == kBRPPoolHandle) { constexpr int kMaxRandomAddressTries = 10; for (int i = 0; i < kMaxRandomAddressTries; ++i) { @@ -174,7 +172,7 @@ } } #endif // !BUILDFLAG(HAS_64_BIT_POINTERS) && - // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) + // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) #if !BUILDFLAG(HAS_64_BIT_POINTERS) // Only mark the region as belonging to the pool after it has passed the @@ -266,7 +264,7 @@ const size_t reservation_size = PartitionRoot::GetDirectMapReservationSize( raw_size + padding_for_alignment); PA_DCHECK(reservation_size >= raw_size); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) const size_t available_reservation_size = reservation_size - padding_for_alignment - PartitionRoot::GetDirectMapMetadataAndGuardPagesSize(); @@ -757,7 +755,7 @@ uintptr_t state_bitmap = super_page + PartitionPageSize() + (is_direct_mapped() ? 0 : ReservedFreeSlotBitmapSize()); -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) PA_DCHECK(SuperPageStateBitmapAddr(super_page) == state_bitmap); const size_t state_bitmap_reservation_size = root->IsQuarantineAllowed() ? ReservedStateBitmapSize() : 0; @@ -769,7 +767,7 @@ uintptr_t payload = state_bitmap + state_bitmap_reservation_size; #else uintptr_t payload = state_bitmap; -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) root->next_partition_page = payload; root->next_partition_page_end = root->next_super_page - PartitionPageSize(); @@ -862,7 +860,7 @@ // sure to register the super-page after it has been fully initialized. // Otherwise, the concurrent scanner may try to access |extent->root| which // could be not initialized yet. -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) if (root->IsQuarantineEnabled()) { { ScopedSyscallTimer timer{root}; @@ -873,9 +871,9 @@ } PCScan::RegisterNewSuperPage(root, super_page); } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) // Commit the pages for freeslot bitmap. if (!is_direct_mapped()) { uintptr_t freeslot_bitmap_addr = super_page + PartitionPageSize(); @@ -966,14 +964,14 @@ slot_span->num_unprovisioned_slots <= get_slots_per_span()); -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) const bool use_tagging = root->IsMemoryTaggingEnabled() && slot_size <= kMaxMemoryTaggingSize; if (PA_LIKELY(use_tagging)) { // Ensure the MTE-tag of the memory pointed by |return_slot| is unguessable. TagMemoryRangeRandomly(return_slot, slot_size); } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) // Add all slots that fit within so far committed pages to the free list. PartitionFreelistEntry* prev_entry = nullptr; uintptr_t next_slot_end = next_slot + slot_size; @@ -983,7 +981,7 @@ while (next_slot_end <= commit_end) { void* next_slot_ptr; -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) if (PA_LIKELY(use_tagging)) { // Ensure the MTE-tag of the memory pointed by other provisioned slot is // unguessable. They will be returned to the app as is, and the MTE-tag @@ -993,7 +991,7 @@ // No MTE-tagging for larger slots, just cast. next_slot_ptr = reinterpret_cast<void*>(next_slot); } -#else // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#else // BUILDFLAG(HAS_MEMORY_TAGGING) next_slot_ptr = reinterpret_cast<void*>(next_slot); #endif @@ -1007,22 +1005,22 @@ PA_DCHECK(free_list_entries_added); freelist_dispatcher->SetNext(prev_entry, entry); } -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) FreeSlotBitmapMarkSlotAsFree(next_slot); #endif next_slot = next_slot_end; next_slot_end = next_slot + slot_size; prev_entry = entry; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) free_list_entries_added++; #endif } -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) FreeSlotBitmapMarkSlotAsFree(return_slot); #endif -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // The only provisioned slot not added to the free list is the one being // returned. PA_DCHECK(slots_to_provision == free_list_entries_added + 1);
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_bucket_lookup.h b/base/allocator/partition_allocator/src/partition_alloc/partition_bucket_lookup.h index b2643784..3b12a30 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_bucket_lookup.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_bucket_lookup.h
@@ -44,11 +44,11 @@ (kNumBucketsPerOrderBits + 1); } -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) static_assert(kBitsPerSizeT == 64, ""); #else static_assert(kBitsPerSizeT == 32, ""); -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) // Orders range from 0 to `kBitsPerSizeT`, inclusive. inline constexpr uint8_t kNumOrders = kBitsPerSizeT + 1;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_cookie.h b/base/allocator/partition_allocator/src/partition_alloc/partition_cookie.h index be2ba028..9db2a3e6 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_cookie.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_cookie.h
@@ -14,7 +14,7 @@ static constexpr size_t kCookieSize = 16; // Cookie is enabled for debug builds. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) inline constexpr unsigned char kCookieValue[kCookieSize] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xD0, 0x0D, @@ -42,7 +42,7 @@ PA_ALWAYS_INLINE void PartitionCookieWriteValue(unsigned char* cookie_ptr) {} -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_dcheck_helper.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_dcheck_helper.cc index f1f5a35..0609571 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_dcheck_helper.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_dcheck_helper.cc
@@ -12,7 +12,7 @@ namespace partition_alloc::internal { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) void DCheckIsValidSlotSpan(internal::SlotSpanMetadata* slot_span) { PartitionRoot* root = PartitionRoot::FromSlotSpanMetadata(slot_span); @@ -62,6 +62,6 @@ DCheckRootLockIsAcquired(PartitionRoot::FromSlotSpanMetadata(slot_span)); } -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_dcheck_helper.h b/base/allocator/partition_allocator/src/partition_alloc/partition_dcheck_helper.h index dec2aa2..ace5d32c 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_dcheck_helper.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_dcheck_helper.h
@@ -14,7 +14,7 @@ struct PartitionSuperPageExtentEntry; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // To allow these asserts to have empty bodies in no-DCHECK() builds, while // avoiding issues with circular includes. @@ -22,7 +22,7 @@ // Export symbol if dcheck-is-on. Because the body is not empty. #define PA_EXPORT_IF_DCHECK_IS_ON() PA_COMPONENT_EXPORT(PARTITION_ALLOC) -#else // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#else // BUILDFLAG(PA_DCHECK_IS_ON) // The static_assert() eats follow-on semicolons. #define PA_EMPTY_BODY_IF_DCHECK_IS_OFF() \ @@ -31,7 +31,7 @@ // inline if dcheck-is-off so it's no overhead. #define PA_EXPORT_IF_DCHECK_IS_ON() PA_ALWAYS_INLINE -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) PA_EXPORT_IF_DCHECK_IS_ON() void DCheckIsValidSlotSpan(internal::SlotSpanMetadata* slot_span)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_freelist_entry.h b/base/allocator/partition_allocator/src/partition_alloc/partition_freelist_entry.h index 244e52b..f787eeb 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_freelist_entry.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_freelist_entry.h
@@ -27,7 +27,7 @@ // We are assessing an alternate implementation using an alternate // encoding (pool offsets). When build support is enabled, the // freelist implementation is determined at runtime. -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) #include "partition_alloc/pool_offset_freelist.h" // IWYU pragma: export #endif @@ -37,7 +37,7 @@ static_assert(kSmallestBucket >= sizeof(EncodedNextFreelistEntry), "Need enough space for freelist entries in the smallest slot"); -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) static_assert(kSmallestBucket >= sizeof(PoolOffsetFreelistEntry), "Need enough space for freelist entries in the smallest slot"); #endif @@ -47,22 +47,22 @@ kPoolOffsetFreeList, }; -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) union PartitionFreelistEntry { EncodedNextFreelistEntry encoded_entry_; PoolOffsetFreelistEntry pool_offset_entry_; }; #else using PartitionFreelistEntry = EncodedNextFreelistEntry; -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) static_assert(offsetof(PartitionFreelistEntry, encoded_entry_) == 0ull); static_assert(offsetof(PartitionFreelistEntry, pool_offset_entry_) == 0ull); #endif struct PartitionFreelistDispatcher { -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) static const PartitionFreelistDispatcher* Create( PartitionFreelistEncoding encoding); @@ -186,10 +186,10 @@ } ~PartitionFreelistDispatcher() = default; -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) }; -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) template <PartitionFreelistEncoding encoding> struct PartitionFreelistDispatcherImpl : PartitionFreelistDispatcher { using Entry = @@ -312,7 +312,7 @@ } } } -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) } // namespace partition_alloc::internal #endif // PARTITION_ALLOC_PARTITION_FREELIST_ENTRY_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_lock.h b/base/allocator/partition_allocator/src/partition_alloc/partition_lock.h index d83fa6e..5b3c8d80 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_lock.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_lock.h
@@ -24,8 +24,8 @@ public: inline constexpr Lock(); void Acquire() PA_EXCLUSIVE_LOCK_FUNCTION() { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) LiftThreadIsolationScope lift_thread_isolation_restrictions; #endif @@ -65,8 +65,8 @@ } void Release() PA_UNLOCK_FUNCTION() { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) LiftThreadIsolationScope lift_thread_isolation_restrictions; #endif owning_thread_ref_.store(base::PlatformThreadRef(), @@ -76,8 +76,8 @@ } void AssertAcquired() const PA_ASSERT_EXCLUSIVE_LOCK() { lock_.AssertAcquired(); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) LiftThreadIsolationScope lift_thread_isolation_restrictions; #endif PA_DCHECK(owning_thread_ref_.load(std ::memory_order_acquire) == @@ -87,7 +87,7 @@ void Reinit() PA_UNLOCK_FUNCTION() { lock_.AssertAcquired(); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) owning_thread_ref_.store(base::PlatformThreadRef(), std::memory_order_release); #endif @@ -97,7 +97,7 @@ private: SpinningMutex lock_; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Should in theory be protected by |lock_|, but we need to read it to detect // recursive lock acquisition (and thus, the allocator becoming reentrant). std::atomic<base::PlatformThreadRef> owning_thread_ref_ =
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_lock_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_lock_unittest.cc index 2fc6228..66c942b 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_lock_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_lock_unittest.cc
@@ -165,7 +165,7 @@ // AssertAcquired() is only enforced with DCHECK()s. // DCHECKs don't work with EXPECT_DEATH on official builds. -#if defined(GTEST_HAS_DEATH_TEST) && PA_BUILDFLAG(PA_DCHECK_IS_ON) && \ +#if defined(GTEST_HAS_DEATH_TEST) && BUILDFLAG(PA_DCHECK_IS_ON) && \ (!defined(OFFICIAL_BUILD) || !defined(NDEBUG)) TEST(PartitionAllocLockTest, AssertAcquiredDeathTest) { @@ -201,8 +201,7 @@ base::PlatformThreadForTesting::Join(handle); // DCHECKs don't work with EXPECT_DEATH on official builds. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) && \ - (!defined(OFFICIAL_BUILD) || !defined(NDEBUG)) +#if BUILDFLAG(PA_DCHECK_IS_ON) && (!defined(OFFICIAL_BUILD) || !defined(NDEBUG)) EXPECT_DEATH(lock.AssertAcquired(), ""); #endif } @@ -241,6 +240,6 @@ } #endif // BUILDFLAG(IS_APPLE) -#endif // defined(GTEST_HAS_DEATH_TEST) && PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // defined(GTEST_HAS_DEATH_TEST) && BUILDFLAG(PA_DCHECK_IS_ON) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_page.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_page.cc index 6a2d0ad8..5ce9c65 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_page.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_page.cc
@@ -193,11 +193,11 @@ return; } -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) const PartitionFreelistDispatcher* freelist_dispatcher = PartitionRoot::FromSlotSpanMetadata(this)->get_freelist_dispatcher(); freelist_dispatcher->CheckFreeList(freelist_head, bucket->slot_size); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) // If it's the current active slot span, change it. We bounce the slot span // to the empty list as a force towards defragmentation. @@ -234,7 +234,7 @@ slot_span_start, size_to_decommit, PageAccessibilityDisposition::kAllowKeepForPerf); -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) FreeSlotBitmapReset(slot_span_start, slot_span_start + size_to_decommit, bucket->slot_size); #endif @@ -317,37 +317,37 @@ size_t reservation_size, pool_handle pool) { PA_DCHECK(reservation_start && reservation_size > 0); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // When ENABLE_BACKUP_REF_PTR_SUPPORT is off, BRP pool isn't used. -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (pool == kBRPPoolHandle) { // In 32-bit mode, the beginning of a reservation may be excluded from the // BRP pool, so shift the pointer. Other pools don't have this logic. -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) PA_DCHECK(IsManagedByPartitionAllocBRPPool(reservation_start)); #else PA_DCHECK(IsManagedByPartitionAllocBRPPool( reservation_start + AddressPoolManagerBitmap::kBytesPer1BitOfBRPPoolBitmap * AddressPoolManagerBitmap::kGuardOffsetOfBRPPoolBitmap)); -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) } else -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) { const bool received_expected_pool_handle = pool == kRegularPoolHandle -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) || pool == kThreadIsolatedPoolHandle #endif -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) || (pool == kConfigurablePoolHandle && IsConfigurablePoolAvailable()) #endif ; PA_DCHECK(received_expected_pool_handle); // Non-BRP pools don't need adjustment that BRP needs in 32-bit mode. -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) PA_DCHECK(IsManagedByPartitionAllocThreadIsolatedPool(reservation_start) || IsManagedByPartitionAllocRegularPool(reservation_start) || IsManagedByPartitionAllocConfigurablePool(reservation_start)); @@ -356,7 +356,7 @@ IsManagedByPartitionAllocConfigurablePool(reservation_start)); #endif } -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) PA_DCHECK((reservation_start & kSuperPageOffsetMask) == 0); uintptr_t reservation_end = reservation_start + reservation_size;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_page.h b/base/allocator/partition_allocator/src/partition_alloc/partition_page.h index 43230c3c..2a82685 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_page.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_page.h
@@ -28,17 +28,17 @@ #include "partition_alloc/partition_superpage_extent_entry.h" #include "partition_alloc/reservation_offset_table.h" -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) #include "partition_alloc/starscan/state_bitmap.h" #endif -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) #include "partition_alloc/tagging.h" #endif namespace partition_alloc::internal { -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) using AllocationStateMap = StateBitmap<kSuperPageSize, kSuperPageAlignment, kAlignment>; #endif @@ -376,7 +376,7 @@ PartitionSuperPageToMetadataArea(super_page)); } -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) // Size that should be reserved for state bitmap (if present) inside a super // page. Elements of a super page are partition-page-aligned, hence the returned @@ -408,14 +408,14 @@ SuperPageStateBitmapAddr(super_page)); } -#else // PA_BUILDFLAG(USE_STARSCAN) +#else // BUILDFLAG(USE_STARSCAN) PA_ALWAYS_INLINE PAGE_ALLOCATOR_CONSTANTS_DECLARE_CONSTEXPR size_t ReservedStateBitmapSize() { return 0ull; } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) PA_ALWAYS_INLINE uintptr_t SuperPagePayloadStartOffset(bool is_managed_by_normal_buckets, @@ -481,7 +481,7 @@ uintptr_t address) { uintptr_t super_page = address & kSuperPageBaseMask; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_DCHECK(IsReservationStart(super_page)); DCheckIsWithInSuperPagePayload(address); #endif @@ -556,11 +556,11 @@ PA_ALWAYS_INLINE SlotSpanMetadata* SlotSpanMetadata::FromSlotStart( uintptr_t slot_start) { auto* slot_span = FromAddr(slot_start); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Checks that the pointer is a multiple of slot size. uintptr_t slot_span_start = ToSlotSpanStart(slot_span); PA_DCHECK(!((slot_start - slot_span_start) % slot_span->bucket->slot_size)); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) return slot_span; } @@ -583,13 +583,13 @@ PA_ALWAYS_INLINE SlotSpanMetadata* SlotSpanMetadata::FromObjectInnerAddr( uintptr_t address) { auto* slot_span = FromAddr(address); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Checks that the address is within the expected object boundaries. uintptr_t slot_span_start = ToSlotSpanStart(slot_span); uintptr_t shift_from_slot_start = (address - slot_span_start) % slot_span->bucket->slot_size; DCheckIsValidShiftFromSlotStart(slot_span, shift_from_slot_start); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) return slot_span; } @@ -614,7 +614,7 @@ PA_ALWAYS_INLINE void SlotSpanMetadata::SetFreelistHead( PartitionFreelistEntry* new_head) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // |this| is in the metadata region, hence isn't MTE-tagged. Untag |new_head| // as well. uintptr_t new_head_untagged = UntagPtr(new_head); @@ -682,7 +682,7 @@ PartitionRoot* root, const PartitionFreelistDispatcher* freelist_dispatcher) PA_EXCLUSIVE_LOCKS_REQUIRED(PartitionRootLock(root)) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) DCheckRootLockIsAcquired(root); PA_DCHECK(!(freelist_dispatcher->GetNext(tail, bucket->slot_size))); PA_DCHECK(number_of_freed); @@ -775,7 +775,7 @@ next_slot_span = nullptr; } -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) // Returns the state bitmap from an address within a normal-bucket super page. // It's the caller's responsibility to ensure that the bitmap exists. PA_ALWAYS_INLINE AllocationStateMap* StateBitmapFromAddr(uintptr_t address) { @@ -783,7 +783,7 @@ uintptr_t super_page = address & kSuperPageBaseMask; return SuperPageStateBitmap(super_page); } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) // Iterates over all slot spans in a super-page. |Callback| must return true if // early return is needed. @@ -791,7 +791,7 @@ void IterateSlotSpans(uintptr_t super_page, bool with_quarantine, Callback callback) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_DCHECK(!(super_page % kSuperPageAlignment)); auto* extent_entry = PartitionSuperPageToExtent(super_page); DCheckRootLockIsAcquired(extent_entry->root);
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_page_constants.h b/base/allocator/partition_allocator/src/partition_alloc/partition_page_constants.h index 8a99d537e..773d9ee 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_page_constants.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_page_constants.h
@@ -11,7 +11,7 @@ namespace partition_alloc::internal { -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(IS_APPLE) +#if BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(IS_APPLE) // System page size is not a constant on Apple OSes, but is either 4 or 16kiB // (1 << 12 or 1 << 14), as checked in PartitionRoot::Init(). And // PartitionPageSize() is 4 times the OS page size. @@ -26,7 +26,7 @@ // larger, so it doesn't have as many slots. static constexpr size_t kMaxSlotsPerSlotSpan = PartitionPageSize() / kSmallestBucket; -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(IS_APPLE) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) && BUILDFLAG(IS_APPLE) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_root.cc b/base/allocator/partition_allocator/src/partition_alloc/partition_root.cc index 26110c2d..d7b9419e 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_root.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_root.cc
@@ -34,7 +34,7 @@ #include "partition_alloc/partition_alloc_base/mac/mac_util.h" #endif -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) #include "partition_alloc/starscan/pcscan.h" #endif @@ -54,7 +54,7 @@ namespace partition_alloc::internal { -#if PA_BUILDFLAG(RECORD_ALLOC_INFO) +#if BUILDFLAG(RECORD_ALLOC_INFO) // Even if this is not hidden behind a BUILDFLAG, it should not use any memory // when recording is disabled, since it ends up in the .bss section. AllocInfo g_allocs = {}; @@ -63,9 +63,9 @@ g_allocs.allocs[g_allocs.index.fetch_add(1, std::memory_order_relaxed) % kAllocInfoSize] = {addr, size}; } -#endif // PA_BUILDFLAG(RECORD_ALLOC_INFO) +#endif // BUILDFLAG(RECORD_ALLOC_INFO) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PtrPosWithinAlloc IsPtrWithinSameAlloc(uintptr_t orig_address, uintptr_t test_address, size_t type_size) { @@ -89,7 +89,7 @@ uintptr_t object_end = object_addr + root->GetSlotUsableSize(slot_span); if (test_address < object_addr || object_end < test_address) { return PtrPosWithinAlloc::kFarOOB; -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) } else if (object_end - type_size < test_address) { // Not even a single element of the type referenced by the pointer can fit // between the pointer and the end of the object. @@ -99,7 +99,7 @@ return PtrPosWithinAlloc::kInBounds; } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) } // namespace partition_alloc::internal @@ -201,7 +201,7 @@ #endif // PA_USE_PARTITION_ROOT_ENUMERATOR -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) namespace { @@ -324,7 +324,7 @@ } #endif // BUILDFLAG(IS_APPLE) -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) namespace internal { @@ -565,7 +565,7 @@ num_provisioned_slots - slot_span->num_allocated_slots); } -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) FreeSlotBitmapReset(slot_span_start + (slot_size * num_provisioned_slots), end_addr, slot_size); #endif @@ -765,15 +765,15 @@ } } -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) void DCheckIfManagedByPartitionAllocBRPPool(uintptr_t address) { PA_DCHECK(IsManagedByPartitionAllocBRPPool(address)); } #endif -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) void PartitionAllocThreadIsolationInit(ThreadIsolationOption thread_isolation) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) ThreadIsolationSettings::settings.enabled = true; #endif PartitionAddressSpace::InitThreadIsolatedPool(thread_isolation); @@ -781,7 +781,7 @@ // permissions to to globals afterwards. WriteProtectThreadIsolatedGlobals(thread_isolation); } -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) } // namespace internal @@ -860,7 +860,7 @@ // this function on PartitionRoots without a thread cache. PA_CHECK(!settings.with_thread_cache); auto pool_handle = ChoosePool(); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // The pages managed by thread isolated pool will be free-ed at // UninitThreadIsolatedForTesting(). Don't invoke FreePages() for the pages. if (pool_handle == internal::kThreadIsolatedPoolHandle) { @@ -911,8 +911,7 @@ } #endif // PA_CONFIG(MAYBE_ENABLE_MAC11_MALLOC_SIZE_HACK) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && \ - !BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && !BUILDFLAG(HAS_64_BIT_POINTERS) namespace { std::atomic<bool> g_reserve_brp_guard_region_called; // An address constructed by repeating `kQuarantinedByte` shouldn't never point @@ -947,7 +946,7 @@ } } } // namespace -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && // !BUILDFLAG(HAS_64_BIT_POINTERS) void PartitionRoot::Init(PartitionOptions opts) { @@ -972,26 +971,25 @@ return; } -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // Reserve address space for PartitionAlloc. internal::PartitionAddressSpace::Init(); #endif -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && \ - !BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && !BUILDFLAG(HAS_64_BIT_POINTERS) ReserveBackupRefPtrGuardRegionIfNeeded(); #endif -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) settings.use_cookie = true; #else static_assert(!Settings::use_cookie); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) settings.brp_enabled_ = opts.backup_ref_ptr == PartitionOptions::kEnabled; -#else // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#else // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_CHECK(opts.backup_ref_ptr == PartitionOptions::kDisabled); -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) settings.use_configurable_pool = (opts.use_configurable_pool == PartitionOptions::kAllowed) && IsConfigurablePoolAvailable(); @@ -1016,7 +1014,7 @@ PA_CHECK(!scheduler_loop_quarantine.has_value()); } -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) settings.memory_tagging_enabled_ = opts.memory_tagging.enabled == PartitionOptions::kEnabled; // Memory tagging is not supported in the configurable pool because MTE @@ -1029,24 +1027,24 @@ settings.memory_tagging_reporting_mode_ = opts.memory_tagging.reporting_mode; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) settings.use_pool_offset_freelists = opts.use_pool_offset_freelists == PartitionOptions::kEnabled; // brp_enabled() is not supported in the configurable pool because // BRP requires objects to be in a different Pool. -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_CHECK(!(settings.use_configurable_pool && brp_enabled())); #endif -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) // BRP and thread isolated mode use different pools, so they can't be // enabled at the same time. PA_CHECK(!opts.thread_isolation.enabled || opts.backup_ref_ptr == PartitionOptions::kDisabled); settings.thread_isolation = opts.thread_isolation; -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) #if PA_CONFIG(EXTRAS_REQUIRED) settings.extras_size = 0; @@ -1055,7 +1053,7 @@ settings.extras_size += internal::kPartitionCookieSizeAdjustment; } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (brp_enabled()) { size_t in_slot_metadata_size = internal::AlignUpInSlotMetadataSizeForApple( @@ -1068,17 +1066,17 @@ EnableMac11MallocSizeHackIfNeeded(); #endif } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) #endif // PA_CONFIG(EXTRAS_REQUIRED) settings.quarantine_mode = -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) (opts.star_scan_quarantine == PartitionOptions::kDisallowed ? QuarantineMode::kAlwaysDisabled : QuarantineMode::kDisabledByDefault); #else QuarantineMode::kAlwaysDisabled; -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) // We mark the sentinel slot span as free to make sure it is skipped by our // logic to find a new active slot span. @@ -1129,11 +1127,11 @@ } // Called without the lock, might allocate. -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) PartitionAllocMallocInitOnce(); #endif -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) if (settings.thread_isolation.enabled) { internal::PartitionAllocThreadIsolationInit(settings.thread_isolation); } @@ -1150,10 +1148,10 @@ } PartitionRoot::~PartitionRoot() { -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) PA_CHECK(!settings.with_thread_cache) << "Must not destroy a partition with a thread cache"; -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #if PA_CONFIG(USE_PARTITION_ROOT_ENUMERATOR) if (initialized) { @@ -1236,14 +1234,14 @@ size_t available_reservation_size = current_reservation_size - extent->padding_for_alignment - PartitionRoot::GetDirectMapMetadataAndGuardPagesSize(); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) uintptr_t reservation_start = slot_start & internal::kSuperPageBaseMask; PA_DCHECK(internal::IsReservationStart(reservation_start)); PA_DCHECK(slot_start + available_reservation_size == reservation_start + current_reservation_size - GetDirectMapMetadataAndGuardPagesSize() + internal::PartitionPageSize()); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) PA_DCHECK(new_slot_size > internal::kMaxMemoryTaggingSize); if (new_slot_size == current_slot_size) { @@ -1268,7 +1266,7 @@ // entries in the reservation offset table (for entire reservation_size // region) have been already initialized. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) memset(reinterpret_cast<void*>(slot_start + current_slot_size), internal::kUninitializedByte, recommit_slot_size_growth); #endif @@ -1324,25 +1322,25 @@ // memory as we're already using, so re-use the allocation after updating // statistics (and cookie, if present). if (slot_span->CanStoreRawSize()) { -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && BUILDFLAG(PA_DCHECK_IS_ON) internal::InSlotMetadata* old_ref_count = nullptr; if (PA_LIKELY(brp_enabled())) { old_ref_count = InSlotMetadataPointerFromSlotStartAndSize( slot_start, slot_span->bucket->slot_size); } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && - // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && + // BUILDFLAG(PA_DCHECK_IS_ON) size_t new_raw_size = AdjustSizeForExtrasAdd(new_size); slot_span->SetRawSize(new_raw_size); -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && BUILDFLAG(PA_DCHECK_IS_ON) if (PA_LIKELY(brp_enabled())) { internal::InSlotMetadata* new_ref_count = InSlotMetadataPointerFromSlotStartAndSize( slot_start, slot_span->bucket->slot_size); PA_DCHECK(new_ref_count == old_ref_count); } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && - // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) && + // BUILDFLAG(PA_DCHECK_IS_ON) // Write a new trailing cookie only when it is possible to keep track // raw size (otherwise we wouldn't know where to look for it later). if (settings.use_cookie) { @@ -1367,7 +1365,7 @@ { ::partition_alloc::internal::ScopedGuard guard{ internal::PartitionRootLock(this)}; -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) // Avoid purging if there is PCScan task currently scheduled. Since pcscan // takes snapshot of all allocated pages, decommitting pages here (even // under the lock) is racy. @@ -1375,7 +1373,7 @@ if (PCScan::IsInProgress()) { return; } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) if (flags & PurgeFlags::kDecommitEmptySlotSpans) { DecommitEmptySlotSpans(); @@ -1473,7 +1471,7 @@ max_size_of_committed_pages.load(std::memory_order_relaxed); stats.total_allocated_bytes = total_size_of_allocated_bytes; stats.max_allocated_bytes = max_size_of_allocated_bytes; -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) stats.total_brp_quarantined_bytes = total_size_of_brp_quarantined_bytes.load(std::memory_order_relaxed); stats.total_brp_quarantined_count = @@ -1588,7 +1586,7 @@ ::partition_alloc::internal::ScopedGuard guard{ internal::PartitionRootLock(this)}; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) if (!allow_leaks) { unsigned num_allocated_slots = 0; for (Bucket& bucket : buckets) { @@ -1714,7 +1712,7 @@ sort_active_slot_spans_ = new_value; } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_NOINLINE void PartitionRoot::QuarantineForBrp( const SlotSpanMetadata* slot_span, void* object) { @@ -1726,7 +1724,7 @@ internal::SecureMemset(object, internal::kQuarantinedByte, usable_size); } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // Explicitly define common template instantiations to reduce compile time. #define EXPORT_TEMPLATE \
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_root.h b/base/allocator/partition_allocator/src/partition_alloc/partition_root.h index b4e5abb..96fc2a45 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_root.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_root.h
@@ -78,7 +78,7 @@ #include "partition_alloc/thread_cache.h" #include "partition_alloc/thread_isolation/thread_isolation.h" -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) #include "partition_alloc/starscan/pcscan.h" #endif @@ -96,11 +96,11 @@ } allocs[kAllocInfoSize] = {}; }; -#if PA_BUILDFLAG(RECORD_ALLOC_INFO) +#if BUILDFLAG(RECORD_ALLOC_INFO) extern AllocInfo g_allocs; void RecordAllocOrFree(uintptr_t addr, size_t size); -#endif // PA_BUILDFLAG(RECORD_ALLOC_INFO) +#endif // BUILDFLAG(RECORD_ALLOC_INFO) } // namespace partition_alloc::internal namespace partition_alloc { @@ -108,7 +108,7 @@ namespace internal { // Avoid including partition_address_space.h from this .h file, by moving the // call to IsManagedByPartitionAllocBRPPool into the .cc file. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_COMPONENT_EXPORT(PARTITION_ALLOC) void DCheckIfManagedByPartitionAllocBRPPool(uintptr_t address); #else @@ -182,7 +182,7 @@ TagViolationReportingMode reporting_mode = TagViolationReportingMode::kUndefined; } memory_tagging; -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) ThreadIsolationOption thread_isolation; #endif @@ -210,7 +210,7 @@ using FreeListEntry = internal::PartitionFreelistEntry; using SuperPageExtentEntry = internal::PartitionSuperPageExtentEntry; using DirectMapExtent = internal::PartitionDirectMapExtent; -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) using PCScan = internal::PCScan; #endif @@ -250,28 +250,28 @@ bool with_thread_cache = false; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) bool use_cookie = false; #else static constexpr bool use_cookie = false; -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) bool brp_enabled_ = false; #if PA_CONFIG(MAYBE_ENABLE_MAC11_MALLOC_SIZE_HACK) bool mac11_malloc_size_hack_enabled_ = false; size_t mac11_malloc_size_hack_usable_size_ = 0; #endif // PA_CONFIG(MAYBE_ENABLE_MAC11_MALLOC_SIZE_HACK) size_t in_slot_metadata_size = 0; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) bool use_configurable_pool = false; bool zapping_by_free_flags = false; bool scheduler_loop_quarantine = false; -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) bool memory_tagging_enabled_ = false; TagViolationReportingMode memory_tagging_reporting_mode_ = TagViolationReportingMode::kUndefined; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) ThreadIsolationOption thread_isolation; #endif @@ -326,7 +326,7 @@ // Atomic, because system calls can be made without the lock held. std::atomic<uint64_t> syscall_count{}; std::atomic<uint64_t> syscall_total_time_ns{}; -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) std::atomic<size_t> total_size_of_brp_quarantined_bytes{0}; std::atomic<size_t> total_count_of_brp_quarantined_slots{0}; std::atomic<size_t> cumulative_size_of_brp_quarantined_bytes{0}; @@ -574,13 +574,13 @@ PA_ALWAYS_INLINE size_t AllocationCapacityFromRequestedSize(size_t size) const; -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_ALWAYS_INLINE static internal::InSlotMetadata* InSlotMetadataPointerFromSlotStartAndSize(uintptr_t slot_start, size_t slot_size); PA_ALWAYS_INLINE internal::InSlotMetadata* InSlotMetadataPointerFromObjectForTesting(void* object) const; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_ALWAYS_INLINE bool IsMemoryTaggingEnabled() const; PA_ALWAYS_INLINE TagViolationReportingMode @@ -676,18 +676,18 @@ } internal::pool_handle ChoosePool() const { -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) if (settings.use_configurable_pool) { PA_DCHECK(IsConfigurablePoolAvailable()); return internal::kConfigurablePoolHandle; } #endif -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) if (settings.thread_isolation.enabled) { return internal::kThreadIsolatedPoolHandle; } #endif -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (PA_LIKELY(brp_enabled())) { return internal::kBRPPoolHandle; } else { @@ -695,7 +695,7 @@ } #else return internal::kRegularPoolHandle; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) } PA_ALWAYS_INLINE bool IsQuarantineAllowed() const { @@ -710,7 +710,7 @@ if (PA_UNLIKELY(settings.quarantine_mode != QuarantineMode::kEnabled)) { return false; } -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) if (PA_UNLIKELY(quarantine_always_for_testing)) { return true; } @@ -724,7 +724,7 @@ return true; #else return true; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } PA_ALWAYS_INLINE void SetQuarantineAlwaysForTesting(bool value) { @@ -839,9 +839,9 @@ // TODO(bartekn): Check that the result is indeed a slot start. } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) bool brp_enabled() const { return settings.brp_enabled_; } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_ALWAYS_INLINE bool uses_configurable_pool() const { return settings.use_configurable_pool; @@ -896,12 +896,12 @@ } const internal::PartitionFreelistDispatcher* get_freelist_dispatcher() { -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) if (settings.use_pool_offset_freelists) { return internal::PartitionFreelistDispatcher::Create( internal::PartitionFreelistEncoding::kPoolOffsetFreeList); } -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) return internal::PartitionFreelistDispatcher::Create( internal::PartitionFreelistEncoding::kEncodedFreeList); } @@ -1039,10 +1039,10 @@ PA_ALWAYS_INLINE FreeNotificationData CreateFreeNotificationData(void* address) const; -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_NOINLINE void QuarantineForBrp(const SlotSpanMetadata* slot_span, void* object); -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) #if PA_CONFIG(USE_PARTITION_ROOT_ENUMERATOR) static internal::Lock& GetEnumeratorLock(); @@ -1089,7 +1089,7 @@ #endif }; -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) struct SlotAddressAndSize { uintptr_t slot_start; @@ -1099,13 +1099,13 @@ PA_ALWAYS_INLINE SlotAddressAndSize PartitionAllocGetDirectMapSlotStartAndSizeInBRPPool(uintptr_t address) { PA_DCHECK(IsManagedByPartitionAllocBRPPool(address)); -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // Use this variant of GetDirectMapReservationStart as it has better // performance. uintptr_t offset = OffsetInBRPPool(address); uintptr_t reservation_start = GetDirectMapReservationStart(address, kBRPPoolHandle, offset); -#else // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#else // BUILDFLAG(HAS_64_BIT_POINTERS) uintptr_t reservation_start = GetDirectMapReservationStart(address); #endif if (!reservation_start) { @@ -1123,7 +1123,7 @@ PA_DCHECK(!page_metadata->slot_span_metadata_offset); auto* slot_span = &page_metadata->slot_span_metadata; uintptr_t slot_start = SlotSpanMetadata::ToSlotSpanStart(slot_span); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) auto* direct_map_metadata = PartitionDirectMapMetadata::FromSlotSpanMetadata(slot_span); size_t padding_for_alignment = @@ -1133,7 +1133,7 @@ PartitionPageSize()); PA_DCHECK(slot_start == reservation_start + PartitionPageSize() + padding_for_alignment); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) return SlotAddressAndSize{.slot_start = slot_start, .size = slot_span->bucket->slot_size}; } @@ -1157,12 +1157,12 @@ } auto* slot_span = SlotSpanMetadata::FromAddr(address); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) auto* root = PartitionRoot::FromSlotSpanMetadata(slot_span); // Double check that in-slot metadata is indeed present. Currently that's the // case only when BRP is used. PA_DCHECK(root->brp_enabled()); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) // Get the offset from the beginning of the slot span. uintptr_t slot_span_start = SlotSpanMetadata::ToSlotSpanStart(slot_span); @@ -1182,7 +1182,7 @@ // When BACKUP_REF_PTR_POISON_OOB_PTR is disabled, end-of-allocation pointers // are also considered in-bounds. kInBounds, -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) kAllocEnd, #endif kFarOOB @@ -1216,7 +1216,7 @@ ->IsAlive()); // Iterating over the entire slot can be really expensive. -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) auto hook = PartitionAllocHooks::GetQuarantineOverrideHook(); // If we have a hook the object segment is not necessarily filled // with |kQuarantinedByte|. @@ -1229,7 +1229,7 @@ } DebugMemset(SlotStartAddr2Ptr(slot_start), kFreedByte, slot_span->GetUtilizedSlotSize()); -#endif // PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#endif // BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) root->total_size_of_brp_quarantined_bytes.fetch_sub( slot_span->GetSlotSizeForBookkeeping(), std::memory_order_relaxed); @@ -1238,7 +1238,7 @@ root->RawFreeWithThreadCache(slot_start, slot_span); } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) } // namespace internal @@ -1310,7 +1310,7 @@ IncreaseTotalSizeOfAllocatedBytes( slot_start, slot_span->GetSlotSizeForBookkeeping(), raw_size); -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) if (!slot_span->bucket->is_direct_mapped()) { internal::FreeSlotBitmapMarkSlotAsUsed(slot_start); } @@ -1327,7 +1327,7 @@ AllocationNotificationData notification_data(object, size, type_name); if (IsMemoryTaggingEnabled()) { -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) notification_data.SetMteReportingMode(memory_tagging_reporting_mode()); #endif } @@ -1346,7 +1346,7 @@ CreateDefaultFreeNotificationData(address); if (IsMemoryTaggingEnabled()) { -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) notification_data.SetMteReportingMode(memory_tagging_reporting_mode()); #endif } @@ -1391,20 +1391,20 @@ } PA_ALWAYS_INLINE bool PartitionRoot::IsMemoryTaggingEnabled() const { -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) return settings.memory_tagging_enabled_; #else return false; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } PA_ALWAYS_INLINE TagViolationReportingMode PartitionRoot::memory_tagging_reporting_mode() const { -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) return settings.memory_tagging_reporting_mode_; #else return TagViolationReportingMode::kUndefined; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } // static @@ -1461,7 +1461,7 @@ // // On Android Chromecast devices, this is already checked in PartitionFree() // in the shim. -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && \ (BUILDFLAG(IS_ANDROID) && !BUILDFLAG(PA_IS_CAST_ANDROID)) uintptr_t object_addr = internal::ObjectPtr2Addr(object); PA_CHECK(IsManagedByPartitionAlloc(object_addr)); @@ -1470,7 +1470,7 @@ SlotSpanMetadata* slot_span = SlotSpanMetadata::FromObject(object); PA_DCHECK(PartitionRoot::FromSlotSpanMetadata(slot_span) == this); -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) if (PA_LIKELY(IsMemoryTaggingEnabled())) { const size_t slot_size = slot_span->bucket->slot_size; if (PA_LIKELY(slot_size <= internal::kMaxMemoryTaggingSize)) { @@ -1483,7 +1483,7 @@ object = TaggedSlotStartToObject(retagged_slot_start); } } -#else // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#else // BUILDFLAG(HAS_MEMORY_TAGGING) // We are going to read from |*slot_span| in all branches, but haven't done it // yet. // @@ -1496,7 +1496,7 @@ // Don't do it when memory tagging is enabled, as |*slot_span| has already // been touched above. PA_PREFETCH(slot_span); -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) uintptr_t slot_start = ObjectToSlotStart(object); PA_DCHECK(slot_span == SlotSpanMetadata::FromSlotStart(slot_start)); @@ -1514,7 +1514,7 @@ // For better debuggability, we should do these checks before quarantining. if constexpr (ContainsFlags(flags, FreeFlags::kSchedulerLoopQuarantine)) { if (settings.scheduler_loop_quarantine) { -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // TODO(keishi): Add PA_LIKELY when brp is fully enabled as |brp_enabled| // will be false only for the aligned partition. if (brp_enabled()) { @@ -1522,14 +1522,14 @@ slot_start, slot_span->bucket->slot_size); ref_count->PreReleaseFromAllocator(); } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) GetSchedulerLoopQuarantineBranch().Quarantine(object, slot_span, slot_start); return; } } -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) // TODO(bikineev): Change the condition to PA_LIKELY once PCScan is enabled by // default. if (PA_UNLIKELY(ShouldQuarantine(object))) { @@ -1541,7 +1541,7 @@ return; } } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) FreeNoHooksImmediate(object, slot_span, slot_start); } @@ -1585,7 +1585,7 @@ GetSlotUsableSize(slot_span)); } -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) // TODO(bikineev): Change the condition to PA_LIKELY once PCScan is enabled by // default. if (PA_UNLIKELY(IsQuarantineEnabled())) { @@ -1594,9 +1594,9 @@ internal::StateBitmapFromAddr(slot_start)->Free(slot_start); } } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (PA_LIKELY(brp_enabled())) { auto* ref_count = InSlotMetadataPointerFromSlotStartAndSize( slot_start, slot_span->bucket->slot_size); @@ -1619,10 +1619,10 @@ return; } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // memset() can be really expensive. -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) internal::DebugMemset(internal::SlotStartAddr2Ptr(slot_start), internal::kFreedByte, slot_span->GetUtilizedSlotSize()); #elif PA_CONFIG(ZERO_RANDOMLY_ON_FREE) @@ -1643,7 +1643,7 @@ SlotSpanMetadata* slot_span) { DecreaseTotalSizeOfAllocatedBytes(slot_start, slot_span->GetSlotSizeForBookkeeping()); -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) if (!slot_span->bucket->is_direct_mapped()) { internal::FreeSlotBitmapMarkSlotAsFree(slot_start); } @@ -1809,9 +1809,9 @@ total_size_of_allocated_bytes += len; max_size_of_allocated_bytes = std::max(max_size_of_allocated_bytes, total_size_of_allocated_bytes); -#if PA_BUILDFLAG(RECORD_ALLOC_INFO) +#if BUILDFLAG(RECORD_ALLOC_INFO) partition_alloc::internal::RecordAllocOrFree(addr | 0x01, raw_size); -#endif // PA_BUILDFLAG(RECORD_ALLOC_INFO) +#endif // BUILDFLAG(RECORD_ALLOC_INFO) } PA_ALWAYS_INLINE void PartitionRoot::DecreaseTotalSizeOfAllocatedBytes( @@ -1821,9 +1821,9 @@ // somewhere. PA_DCHECK(total_size_of_allocated_bytes >= len); total_size_of_allocated_bytes -= len; -#if PA_BUILDFLAG(RECORD_ALLOC_INFO) +#if BUILDFLAG(RECORD_ALLOC_INFO) partition_alloc::internal::RecordAllocOrFree(addr | 0x00, len); -#endif // PA_BUILDFLAG(RECORD_ALLOC_INFO) +#endif // BUILDFLAG(RECORD_ALLOC_INFO) } PA_ALWAYS_INLINE void PartitionRoot::IncreaseCommittedPages(size_t len) { @@ -1986,12 +1986,12 @@ PartitionRoot::GetPageAccessibility(bool request_tagging) const { PageAccessibilityConfiguration::Permissions permissions = PageAccessibilityConfiguration::kReadWrite; -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) if (IsMemoryTaggingEnabled() && request_tagging) { permissions = PageAccessibilityConfiguration::kReadWriteTagged; } #endif -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) return PageAccessibilityConfiguration(permissions, settings.thread_isolation); #else return PageAccessibilityConfiguration(permissions); @@ -2001,7 +2001,7 @@ PA_ALWAYS_INLINE PageAccessibilityConfiguration PartitionRoot::PageAccessibilityWithThreadIsolationIfEnabled( PageAccessibilityConfiguration::Permissions permissions) const { -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) return PageAccessibilityConfiguration(permissions, settings.thread_isolation); #endif return PageAccessibilityConfiguration(permissions); @@ -2017,7 +2017,7 @@ return AdjustSizeForExtrasSubtract(slot_span->bucket->slot_size); } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_ALWAYS_INLINE internal::InSlotMetadata* PartitionRoot::InSlotMetadataPointerFromSlotStartAndSize(uintptr_t slot_start, size_t slot_size) { @@ -2031,7 +2031,7 @@ return InSlotMetadataPointerFromSlotStartAndSize( slot_start, slot_span->bucket->slot_size); } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // static PA_ALWAYS_INLINE uint16_t @@ -2080,7 +2080,7 @@ hooks_enabled = PartitionAllocHooks::AreHooksEnabled(); if (hooks_enabled) { auto additional_flags = AllocFlags::kNone; -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) if (IsMemoryTaggingEnabled()) { additional_flags |= AllocFlags::kMemoryShouldBeTaggedForMte; } @@ -2144,7 +2144,7 @@ uintptr_t slot_start = 0; size_t slot_size = 0; -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) const bool is_quarantine_enabled = IsQuarantineEnabled(); // PCScan safepoint. Call before trying to allocate from cache. // TODO(bikineev): Change the condition to PA_LIKELY once PCScan is enabled by @@ -2152,7 +2152,7 @@ if (PA_UNLIKELY(is_quarantine_enabled)) { PCScan::JoinScanIfNeeded(); } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) auto* thread_cache = GetOrCreateThreadCache(); @@ -2174,7 +2174,7 @@ // Keep it in sync! usable_size = AdjustSizeForExtrasSubtract(slot_size); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Make sure that the allocated pointer comes from the same place it would // for a non-thread cache allocation. SlotSpanMetadata* slot_span = SlotSpanMetadata::FromSlotStart(slot_start); @@ -2222,7 +2222,7 @@ // (f) slot_size // // Notes: - // - Cookie exists only in the PA_BUILDFLAG(PA_DCHECK_IS_ON) case. + // - Cookie exists only in the BUILDFLAG(PA_DCHECK_IS_ON) case. // - Think of raw_size as the minimum size required internally to satisfy // the allocation request (i.e. requested_size + extras) // - At most one "empty" or "unused" space can occur at a time. They occur @@ -2259,14 +2259,14 @@ // PA_LIKELY: operator new() calls malloc(), not calloc(). if constexpr (!zero_fill) { // memset() can be really expensive. -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) internal::DebugMemset(object, internal::kUninitializedByte, usable_size); #endif } else if (!is_already_zeroed) { memset(object, 0, usable_size); } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) if (PA_LIKELY(brp_enabled())) { bool needs_mac11_malloc_size_hack = false; #if PA_CONFIG(MAYBE_ENABLE_MAC11_MALLOC_SIZE_HACK) @@ -2287,9 +2287,9 @@ (void)ref_count; #endif } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) // TODO(bikineev): Change the condition to PA_LIKELY once PCScan is enabled by // default. if (PA_UNLIKELY(is_quarantine_enabled)) { @@ -2298,7 +2298,7 @@ internal::StateBitmapFromAddr(slot_start)->Allocate(slot_start); } } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) return object; } @@ -2574,20 +2574,20 @@ size_t); #undef EXPORT_TEMPLATE -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) // Usage in `raw_ptr_backup_ref_impl.cc` is notable enough to merit a // non-internal alias. using ::partition_alloc::internal::PartitionAllocGetSlotStartAndSizeInBRPPool; -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) -#if BUILDFLAG(IS_APPLE) && PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(IS_APPLE) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) PA_COMPONENT_EXPORT(PARTITION_ALLOC) void PartitionAllocMallocHookOnBeforeForkInParent(); PA_COMPONENT_EXPORT(PARTITION_ALLOC) void PartitionAllocMallocHookOnAfterForkInParent(); PA_COMPONENT_EXPORT(PARTITION_ALLOC) void PartitionAllocMallocHookOnAfterForkInChild(); -#endif // BUILDFLAG(IS_APPLE) && PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(IS_APPLE) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } // namespace partition_alloc
diff --git a/base/allocator/partition_allocator/src/partition_alloc/partition_stats.h b/base/allocator/partition_allocator/src/partition_alloc/partition_stats.h index df967b29..2cc61f2 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/partition_stats.h +++ b/base/allocator/partition_allocator/src/partition_alloc/partition_stats.h
@@ -77,7 +77,7 @@ size_t total_active_count; // Total count of active objects in the partition. size_t total_decommittable_bytes; // Total bytes that could be decommitted. size_t total_discardable_bytes; // Total bytes that could be discarded. -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) size_t total_brp_quarantined_bytes; // Total bytes that are quarantined by BRP. size_t total_brp_quarantined_count; // Total number of slots that are
diff --git a/base/allocator/partition_allocator/src/partition_alloc/pointers/instance_tracer.cc b/base/allocator/partition_allocator/src/partition_alloc/pointers/instance_tracer.cc index b61e0ed..9f9c94c 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/pointers/instance_tracer.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/pointers/instance_tracer.cc
@@ -16,7 +16,7 @@ namespace base::internal { -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER) static_assert(BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT), "Instance tracing requires BackupRefPtr support.");
diff --git a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr.h b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr.h index 98eab67..708a3ca 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr.h +++ b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr.h
@@ -27,30 +27,29 @@ #include "partition_alloc/partition_alloc_base/win/win_handle_types.h" #endif -#if PA_BUILDFLAG(USE_PARTITION_ALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC) #include "partition_alloc/partition_alloc_base/check.h" // Live implementation of MiraclePtr being built. -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ - PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) #define PA_RAW_PTR_CHECK(condition) PA_BASE_CHECK(condition) #else // No-op implementation of MiraclePtr being built. // Note that `PA_BASE_DCHECK()` evaporates from non-DCHECK builds, // minimizing impact of generated code. #define PA_RAW_PTR_CHECK(condition) PA_BASE_DCHECK(condition) -#endif // PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || - // PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) -#else // PA_BUILDFLAG(USE_PARTITION_ALLOC) +#endif // BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || + // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) +#else // BUILDFLAG(USE_PARTITION_ALLOC) // Without PartitionAlloc, there's no `PA_BASE_D?CHECK()` implementation // available. #define PA_RAW_PTR_CHECK(condition) -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC) -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) #include "partition_alloc/pointers/raw_ptr_backup_ref_impl.h" -#elif PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) +#elif BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) #include "partition_alloc/pointers/raw_ptr_asan_unowned_impl.h" -#elif PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) +#elif BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) #include "partition_alloc/pointers/raw_ptr_hookable_impl.h" #else #include "partition_alloc/pointers/raw_ptr_noop_impl.h" @@ -108,7 +107,7 @@ kMayDangle = (1 << 0), // Disables any hooks, when building with - // PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL). + // BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL). // // Internal use only. kDisableHooks = (1 << 2), @@ -260,7 +259,7 @@ #undef PA_WINDOWS_HANDLE_TYPE #endif -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) template <RawPtrTraits Traits> using UnderlyingImplForTraits = internal::RawPtrBackupRefImpl< /*AllowDangling=*/partition_alloc::internal::ContainsFlags( @@ -270,14 +269,14 @@ Traits, RawPtrTraits::kDisableBRP)>; -#elif PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) +#elif BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) template <RawPtrTraits Traits> using UnderlyingImplForTraits = internal::RawPtrAsanUnownedImpl< partition_alloc::internal::ContainsFlags(Traits, RawPtrTraits::kAllowPtrArithmetic), partition_alloc::internal::ContainsFlags(Traits, RawPtrTraits::kMayDangle)>; -#elif PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) +#elif BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) template <RawPtrTraits Traits> using UnderlyingImplForTraits = internal::RawPtrHookableImpl< /*EnableHooks=*/!partition_alloc::internal::ContainsFlags( @@ -290,7 +289,7 @@ #endif constexpr bool IsPtrArithmeticAllowed([[maybe_unused]] RawPtrTraits Traits) { -#if PA_BUILDFLAG(ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK) +#if BUILDFLAG(ENABLE_POINTER_ARITHMETIC_TRAIT_CHECK) return partition_alloc::internal::ContainsFlags( Traits, RawPtrTraits::kAllowPtrArithmetic); #else @@ -358,16 +357,16 @@ Traits, RawPtrTraits::kAllowUninitialized)); static constexpr bool kZeroOnMove = - Impl::kMustZeroOnMove || PA_BUILDFLAG(RAW_PTR_ZERO_ON_MOVE); + Impl::kMustZeroOnMove || BUILDFLAG(RAW_PTR_ZERO_ON_MOVE); static constexpr bool kZeroOnDestruct = - Impl::kMustZeroOnDestruct || PA_BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT); + Impl::kMustZeroOnDestruct || BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT); // A non-trivial default ctor is required for complex implementations (e.g. // BackupRefPtr), or even for NoOpImpl when zeroing is requested. -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || \ - PA_BUILDFLAG(RAW_PTR_ZERO_ON_CONSTRUCT) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || \ + BUILDFLAG(RAW_PTR_ZERO_ON_CONSTRUCT) PA_ALWAYS_INLINE constexpr raw_ptr() noexcept { if constexpr (kZeroOnConstruct) { wrapped_ptr_ = nullptr; @@ -378,18 +377,18 @@ // uninitialized). PA_ALWAYS_INLINE constexpr raw_ptr() noexcept = default; static_assert(!kZeroOnConstruct); -#endif // PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || - // PA_BUILDFLAG(RAW_PTR_ZERO_ON_CONSTRUCT) +#endif // BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || + // BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || + // BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || + // BUILDFLAG(RAW_PTR_ZERO_ON_CONSTRUCT) // A non-trivial copy ctor and assignment operator are required for complex // implementations (e.g. BackupRefPtr). Unlike the blocks around, we don't need // these for NoOpImpl even when zeroing is requested; better to keep them // trivial. -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) PA_ALWAYS_INLINE constexpr raw_ptr(const raw_ptr& p) noexcept : wrapped_ptr_(Impl::Duplicate(p.wrapped_ptr_)) { Impl::Trace(tracer_.owner_id(), p.wrapped_ptr_); @@ -412,17 +411,16 @@ #else PA_ALWAYS_INLINE raw_ptr(const raw_ptr&) noexcept = default; PA_ALWAYS_INLINE raw_ptr& operator=(const raw_ptr&) noexcept = default; -#endif // PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) +#endif // BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || + // BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || + // BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) // A non-trivial move ctor and assignment operator are required for complex // implementations (e.g. BackupRefPtr), or even for NoOpImpl when zeroing is // requested. -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || \ - PA_BUILDFLAG(RAW_PTR_ZERO_ON_MOVE) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || BUILDFLAG(RAW_PTR_ZERO_ON_MOVE) PA_ALWAYS_INLINE constexpr raw_ptr(raw_ptr&& p) noexcept { wrapped_ptr_ = p.wrapped_ptr_; Impl::Trace(tracer_.owner_id(), wrapped_ptr_); @@ -450,17 +448,17 @@ PA_ALWAYS_INLINE raw_ptr(raw_ptr&&) noexcept = default; PA_ALWAYS_INLINE raw_ptr& operator=(raw_ptr&&) noexcept = default; static_assert(!kZeroOnMove); -#endif // PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || - // PA_BUILDFLAG(RAW_PTR_ZERO_ON_MOVE) +#endif // BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || + // BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || + // BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || + // BUILDFLAG(RAW_PTR_ZERO_ON_MOVE) // A non-trivial default dtor is required for complex implementations (e.g. // BackupRefPtr), or even for NoOpImpl when zeroing is requested. -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || \ - PA_BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || \ + BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT) PA_ALWAYS_INLINE PA_CONSTEXPR_DTOR ~raw_ptr() noexcept { Impl::ReleaseWrappedPtr(wrapped_ptr_); Impl::Untrace(tracer_.owner_id()); @@ -472,10 +470,10 @@ #else PA_ALWAYS_INLINE ~raw_ptr() noexcept = default; static_assert(!kZeroOnDestruct); -#endif // PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || - // PA_BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT) +#endif // BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || + // BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || + // BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || + // BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT) // Cross-kind copy constructor. // Move is not supported as different traits may use different ref-counts, so @@ -585,8 +583,7 @@ // Make sure that pointer isn't assigned to itself (look at raw_ptr address, // not its contained pointer value). The comparison is only needed when they // are the same type, otherwise they can't be the same raw_ptr object. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) if constexpr (std::is_same_v<raw_ptr, std::decay_t<decltype(ptr)>>) { PA_RAW_PTR_CHECK(this != &ptr); } @@ -607,8 +604,7 @@ // Make sure that pointer isn't assigned to itself (look at raw_ptr address, // not its contained pointer value). The comparison is only needed when they // are the same type, otherwise they can't be the same raw_ptr object. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) if constexpr (std::is_same_v<raw_ptr, std::decay_t<decltype(ptr)>>) { PA_RAW_PTR_CHECK(this != &ptr); } @@ -970,7 +966,7 @@ } PA_ALWAYS_INLINE void ReportIfDangling() const noexcept { -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) Impl::ReportIfDangling(wrapped_ptr_); #endif }
diff --git a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_backup_ref_impl.cc b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_backup_ref_impl.cc index 98e04767..c9f2417 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_backup_ref_impl.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_backup_ref_impl.cc
@@ -19,8 +19,7 @@ template <bool AllowDangling, bool DisableBRP> void RawPtrBackupRefImpl<AllowDangling, DisableBRP>::AcquireInternal( uintptr_t address) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_BASE_CHECK(UseBrp(address)); #endif auto [slot_start, slot_size] = @@ -39,8 +38,7 @@ template <bool AllowDangling, bool DisableBRP> void RawPtrBackupRefImpl<AllowDangling, DisableBRP>::ReleaseInternal( uintptr_t address) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_BASE_CHECK(UseBrp(address)); #endif auto [slot_start, slot_size] = @@ -89,7 +87,7 @@ PA_BASE_CHECK(ptr_pos_within_alloc != partition_alloc::internal::PtrPosWithinAlloc::kFarOOB); -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) return ptr_pos_within_alloc == partition_alloc::internal::PtrPosWithinAlloc::kAllocEnd; #else @@ -100,8 +98,7 @@ template <bool AllowDangling, bool DisableBRP> bool RawPtrBackupRefImpl<AllowDangling, DisableBRP>::IsPointeeAlive( uintptr_t address) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_BASE_CHECK(UseBrp(address)); #endif auto [slot_start, slot_size] = @@ -122,8 +119,7 @@ template struct RawPtrBackupRefImpl</*AllowDangling=*/true, /*DisableBRP=*/true>; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) void CheckThatAddressIsntWithinFirstPartitionPage(uintptr_t address) { if (partition_alloc::internal::IsManagedByDirectMap(address)) { uintptr_t reservation_start = @@ -136,7 +132,7 @@ partition_alloc::PartitionPageSize()); } } -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) || - // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) || + // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) } // namespace base::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_backup_ref_impl.h b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_backup_ref_impl.h index d521162..df1ddf0 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_backup_ref_impl.h +++ b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_backup_ref_impl.h
@@ -30,8 +30,7 @@ namespace base::internal { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_COMPONENT_EXPORT(RAW_PTR) void CheckThatAddressIsntWithinFirstPartitionPage(uintptr_t address); #endif @@ -71,12 +70,11 @@ // address is nullptr. #if PA_HAS_BUILTIN(__builtin_constant_p) if (__builtin_constant_p(address == 0) && (address == 0)) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_BASE_CHECK( !partition_alloc::IsManagedByPartitionAllocBRPPool(address)); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) || - // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) || + // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) return false; } #endif // PA_HAS_BUILTIN(__builtin_constant_p) @@ -102,8 +100,7 @@ // IsManagedByPartitionAllocBRPPool returns true for a valid pointer, // it must be at least partition page away from the beginning of a super // page. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) if (use_brp) { CheckThatAddressIsntWithinFirstPartitionPage(address); } @@ -112,7 +109,7 @@ return use_brp; } -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) // Out-Of-Bounds (OOB) poison bit is set when the pointer has overflowed by // one byte. #if defined(ARCH_CPU_X86_64) @@ -142,12 +139,12 @@ return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(ptr) | OOB_POISON_BIT); } -#else // PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#else // BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) template <typename T> PA_ALWAYS_INLINE static T* UnpoisonPtr(T* ptr) { return ptr; } -#endif // PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#endif // BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) public: // Wraps a pointer. @@ -158,8 +155,7 @@ } uintptr_t address = partition_alloc::UntagPtr(UnpoisonPtr(ptr)); if (IsSupportedAndNotNull(address)) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_BASE_CHECK(ptr != nullptr); #endif AcquireInternal(address); @@ -193,8 +189,7 @@ } uintptr_t address = partition_alloc::UntagPtr(UnpoisonPtr(wrapped_ptr)); if (IsSupportedAndNotNull(address)) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) PA_BASE_CHECK(wrapped_ptr != nullptr); #endif ReleaseInternal(address); @@ -217,9 +212,8 @@ if (partition_alloc::internal::base::is_constant_evaluated()) { return wrapped_ptr; } -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) PA_BASE_CHECK(!IsPtrOOB(wrapped_ptr)); #endif uintptr_t address = partition_alloc::UntagPtr(wrapped_ptr); @@ -227,8 +221,8 @@ PA_BASE_CHECK(wrapped_ptr != nullptr); PA_BASE_CHECK(IsPointeeAlive(address)); // Detects use-after-free. } -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) || - // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) || + // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) return wrapped_ptr; } @@ -241,7 +235,7 @@ return wrapped_ptr; } T* unpoisoned_ptr = UnpoisonPtr(wrapped_ptr); -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) // Some code uses invalid pointer values as indicators, so those values must // be passed through unchanged during extraction. The following check will // pass invalid values through if those values do not fall within the BRP @@ -254,7 +248,7 @@ // OOB conditions, e.g., in code that extracts an end-of-allocation pointer // for use in a loop termination condition. The poison bit would make that // pointer appear to reference a very high address. -#endif // PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#endif // BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) return unpoisoned_ptr; } @@ -318,11 +312,11 @@ constexpr size_t size = sizeof(T); [[maybe_unused]] const bool is_end = CheckPointerWithinSameAlloc(before_addr, after_addr, size); -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) if (is_end) { new_ptr = PoisonOOBPtr(new_ptr); } -#endif // PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#endif // BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) } else { // Check that the new address didn't migrate into the BRP pool, as it // would result in more pointers pointing to an allocation than its @@ -393,7 +387,7 @@ T* unpoisoned_ptr1 = UnpoisonPtr(wrapped_ptr1); T* unpoisoned_ptr2 = UnpoisonPtr(wrapped_ptr2); -#if PA_BUILDFLAG(ENABLE_POINTER_SUBTRACTION_CHECK) +#if BUILDFLAG(ENABLE_POINTER_SUBTRACTION_CHECK) if (partition_alloc::internal::base::is_constant_evaluated()) { return unpoisoned_ptr1 - unpoisoned_ptr2; } @@ -409,7 +403,7 @@ } else { PA_BASE_CHECK(!IsSupportedAndNotNull(address2)); } -#endif // PA_BUILDFLAG(ENABLE_POINTER_SUBTRACTION_CHECK) +#endif // BUILDFLAG(ENABLE_POINTER_SUBTRACTION_CHECK) return unpoisoned_ptr1 - unpoisoned_ptr2; } @@ -451,7 +445,7 @@ } } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER) template <typename T> static constexpr void Trace(uint64_t owner_id, T* wrapped_ptr) { if (partition_alloc::internal::base::is_constant_evaluated()) {
diff --git a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_unittest.cc index 51e9f8b..08dab52 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ptr_unittest.cc
@@ -45,7 +45,7 @@ #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/variant.h" -#if PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) +#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) #include <sanitizer/asan_interface.h> #include "base/debug/asan_service.h" #endif @@ -1338,10 +1338,10 @@ RawPtrCountingImpl::ClearCounters(); size_t number_of_cleared_elements = vector.size(); vector.clear(); -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ - PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || \ - PA_BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT) +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || \ + BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) || \ + BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT) EXPECT_EQ((int)number_of_cleared_elements, RawPtrCountingImpl::release_wrapped_ptr_cnt); #else @@ -1352,9 +1352,9 @@ // BackupRefPtr ships to the Stable channel). EXPECT_EQ(0, RawPtrCountingImpl::release_wrapped_ptr_cnt); std::ignore = number_of_cleared_elements; -#endif // PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || - // PA_BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || - // PA_BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT) +#endif // BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) || + // BUILDFLAG(USE_RAW_PTR_ASAN_UNOWNED_IMPL) || + // BUILDFLAG(RAW_PTR_ZERO_ON_DESTRUCT) } struct BaseStruct { @@ -1588,7 +1588,7 @@ namespace base::internal { -#if PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) && \ +#if BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) && \ !defined(MEMORY_TOOL_REPLACES_ALLOCATOR) void HandleOOM(size_t unused_size) { @@ -1648,10 +1648,10 @@ EXPECT_EQ(*raw_ptr1, *wrapped_ptr1); allocator_.root()->Free(raw_ptr1); -#if DCHECK_IS_ON() || PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#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(g_volatile_int_to_ignore = *wrapped_ptr1, ""); -#else // DCHECK_IS_ON() || PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#else // DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) if (cpu.has_mte()) { // If the hardware supports MTE, the use-after-free should also be caught. EXPECT_DEATH_IF_SUPPORTED(g_volatile_int_to_ignore = *wrapped_ptr1, ""); @@ -1672,7 +1672,7 @@ EXPECT_EQ(partition_alloc::UntagPtr(raw_ptr1), partition_alloc::UntagPtr(raw_ptr3)); allocator_.root()->Free(raw_ptr3); -#endif // DCHECK_IS_ON() || PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#endif // DCHECK_IS_ON() || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) } TEST_F(BackupRefPtrTest, ZeroSized) { @@ -1753,7 +1753,7 @@ void RunBackupRefPtrImplAdvanceTest( partition_alloc::PartitionAllocator& allocator, size_t requested_size) { -#if PA_BUILDFLAG(BACKUP_REF_PTR_EXTRA_OOB_CHECKS) +#if BUILDFLAG(BACKUP_REF_PTR_EXTRA_OOB_CHECKS) char* ptr = static_cast<char*>(allocator.root()->Alloc(requested_size)); raw_ptr<char, AllowPtrArithmetic> protected_ptr = ptr; protected_ptr += 123; @@ -1764,7 +1764,7 @@ // end-of-allocation address should not cause an error immediately, but it may // result in the pointer being poisoned. protected_ptr = protected_ptr + (requested_size + 1) / 2; -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) EXPECT_DEATH_IF_SUPPORTED(*protected_ptr = ' ', ""); protected_ptr -= 1; // This brings the pointer back within // bounds, which causes the poison to be removed. @@ -1785,7 +1785,7 @@ EXPECT_CHECK_DEATH(protected_ptr -= 1); EXPECT_CHECK_DEATH(--protected_ptr); -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) // An array of a size that doesn't cleanly fit into the allocation. This is to // check that one can't access elements that don't fully fit in the // allocation. @@ -1804,11 +1804,11 @@ protected_arr_ptr++; EXPECT_CHECK_DEATH(** protected_arr_ptr = 4); protected_arr_ptr = nullptr; -#endif // PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#endif // BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) protected_ptr = nullptr; allocator.root()->Free(ptr); -#endif // PA_BUILDFLAG(BACKUP_REF_PTR_EXTRA_OOB_CHECKS) +#endif // BUILDFLAG(BACKUP_REF_PTR_EXTRA_OOB_CHECKS) } TEST_F(BackupRefPtrTest, Advance) { @@ -1875,7 +1875,7 @@ checked_cast<ptrdiff_t>(requested_size)); EXPECT_EQ(protected_ptr1 - protected_ptr1_4, -checked_cast<ptrdiff_t>(requested_size)); -#if PA_BUILDFLAG(ENABLE_POINTER_SUBTRACTION_CHECK) +#if BUILDFLAG(ENABLE_POINTER_SUBTRACTION_CHECK) EXPECT_CHECK_DEATH(protected_ptr2 - protected_ptr1); EXPECT_CHECK_DEATH(protected_ptr1 - protected_ptr2); EXPECT_CHECK_DEATH(protected_ptr2 - protected_ptr1_4); @@ -1884,7 +1884,7 @@ EXPECT_CHECK_DEATH(protected_ptr1 - protected_ptr2_2); EXPECT_CHECK_DEATH(protected_ptr2_2 - protected_ptr1_4); EXPECT_CHECK_DEATH(protected_ptr1_4 - protected_ptr2_2); -#endif // PA_BUILDFLAG(ENABLE_POINTER_SUBTRACTION_CHECK) +#endif // BUILDFLAG(ENABLE_POINTER_SUBTRACTION_CHECK) EXPECT_EQ(protected_ptr2_2 - protected_ptr2, 1); EXPECT_EQ(protected_ptr2 - protected_ptr2_2, -1); @@ -1902,7 +1902,7 @@ volatile char g_volatile_char_to_ignore; TEST_F(BackupRefPtrTest, IndexOperator) { -#if PA_BUILDFLAG(BACKUP_REF_PTR_EXTRA_OOB_CHECKS) +#if BUILDFLAG(BACKUP_REF_PTR_EXTRA_OOB_CHECKS) size_t requested_size = GetRequestSizeThatFills512BSlot(); char* ptr = static_cast<char*>(allocator_.root()->Alloc(requested_size)); { @@ -1911,13 +1911,13 @@ std::ignore = array[requested_size - 1]; EXPECT_CHECK_DEATH(std::ignore = array[-1]); EXPECT_CHECK_DEATH(std::ignore = array[requested_size + 1]); -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) EXPECT_DEATH_IF_SUPPORTED(g_volatile_char_to_ignore = array[requested_size], ""); #endif } allocator_.root()->Free(ptr); -#endif // PA_BUILDFLAG(BACKUP_REF_PTR_EXTRA_OOB_CHECKS) +#endif // BUILDFLAG(BACKUP_REF_PTR_EXTRA_OOB_CHECKS) } bool IsQuarantineEmpty(partition_alloc::PartitionAllocator& allocator) { @@ -2098,7 +2098,7 @@ void* ptr = allocator_.root()->Alloc(16); raw_ptr<void> dangling_ptr = ptr; -#if PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) BASE_EXPECT_DEATH( { allocator_.root()->Free(ptr); // Dangling raw_ptr detected. @@ -2196,7 +2196,7 @@ raw_ptr<int> ptr = static_cast<int*>(allocator_.root()->Alloc(sizeof(int), "")); -#if PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#if BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) BASE_EXPECT_DEATH( { allocator_.root()->Free(ptr.get()); // Dangling raw_ptr detected. @@ -2208,7 +2208,7 @@ #else allocator_.root()->Free(ptr.get()); ptr = nullptr; -#endif // PA_BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) +#endif // BUILDFLAG(ENABLE_DANGLING_RAW_PTR_CHECKS) } TEST_F(BackupRefPtrTest, SpatialAlgoCompat) { @@ -2300,7 +2300,7 @@ allocator_.root()->Free(ptr); } -#if PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#if BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) TEST_F(BackupRefPtrTest, Duplicate) { size_t requested_size = allocator_.root()->AdjustSizeForExtrasSubtract(512); char* ptr = static_cast<char*>(allocator_.root()->Alloc(requested_size)); @@ -2327,9 +2327,9 @@ protected_ptr3 = nullptr; allocator_.root()->Free(ptr); } -#endif // PA_BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) +#endif // BUILDFLAG(BACKUP_REF_PTR_POISON_OOB_PTR) -#if PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#if BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) TEST_F(BackupRefPtrTest, WriteAfterFree) { constexpr uint64_t kPayload = 0x1234567890ABCDEF; @@ -2349,7 +2349,7 @@ }, ""); } -#endif // PA_BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) +#endif // BUILDFLAG(PA_EXPENSIVE_DCHECKS_ARE_ON) namespace { constexpr uint8_t kCustomQuarantineByte = 0xff; @@ -2402,8 +2402,7 @@ // Freeing would update the MTE tag so use |TagPtr()| to dereference it // below. allocator_.root()->Free(ptr); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) || \ - PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) +#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS) // Recreate the raw_ptr so we can use a pointer with the updated MTE tag. // Reassigning to |ptr| would hit the PartitionRefCount cookie check rather // than the |IsPointeeAlive()| check. @@ -2433,10 +2432,10 @@ allocator_.root()->Free(sentinel); } -#endif // PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) && +#endif // BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) && // !defined(MEMORY_TOOL_REPLACES_ALLOCATOR) -#if PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) +#if BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) namespace { #define FOR_EACH_RAW_PTR_OPERATION(F) \ @@ -2578,7 +2577,7 @@ EXPECT_EQ(CountingHooks::Get()->unsafely_unwrap_for_duplication_count, 1u); } -#endif // PA_BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) +#endif // BUILDFLAG(USE_RAW_PTR_HOOKABLE_IMPL) TEST(DanglingPtrTest, DetectAndReset) { auto instrumentation = test::DanglingPtrInstrumentation::Create(); @@ -2639,8 +2638,8 @@ EXPECT_EQ(instrumentation->dangling_ptr_released(), 1u); } -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER) && \ - PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER) && \ + BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) TEST(RawPtrInstanceTracerTest, CreateAndDestroy) { auto owned = std::make_unique<int>(8); @@ -2960,7 +2959,7 @@ EXPECT_THAT(InstanceTracer::GetStackTracesForAddressForTest(owned2.get()), IsEmpty()); } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER) && - // PA_BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_INSTANCE_TRACER) && + // BUILDFLAG(USE_RAW_PTR_BACKUP_REF_IMPL) } // namespace base::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref_unittest.cc index 0e859d3..03bcdbf 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/pointers/raw_ref_unittest.cc
@@ -18,10 +18,10 @@ #include "partition_alloc/pointers/raw_ptr_counting_impl_for_test.h" #include "partition_alloc/pointers/raw_ptr_test_support.h" #include "testing/gtest/include/gtest/gtest.h" -#if PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) +#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) #include "base/debug/asan_service.h" #include "base/memory/raw_ptr_asan_service.h" -#endif // PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) +#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) namespace { @@ -561,8 +561,8 @@ // `raw_ref` evaluate to nothing. Therefore, death tests relying on // these CHECKs firing are disabled in their absence. -#if PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) || \ - PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) || PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) || \ + BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) || BUILDFLAG(PA_DCHECK_IS_ON) TEST(RawRefDeathTest, CopyConstructAfterMove) { int i = 1; @@ -802,9 +802,9 @@ } } -#endif // PA_BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) || - // PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) || - // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) || + // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) || + // BUILDFLAG(PA_DCHECK_IS_ON) TEST(RawRef, CTAD) { int i = 1; @@ -962,7 +962,7 @@ CountersMatch()); } -#if PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) +#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) TEST(AsanBackupRefPtrImpl, RawRefGet) { base::debug::AsanService::GetInstance()->Initialize(); @@ -1016,6 +1016,6 @@ [[maybe_unused]] volatile int& ref = *safe_ref; } -#endif // PA_BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) +#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR) } // namespace
diff --git a/base/allocator/partition_allocator/src/partition_alloc/pool_offset_freelist.h b/base/allocator/partition_allocator/src/partition_alloc/pool_offset_freelist.h index 36a954e6..b2213d5d 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/pool_offset_freelist.h +++ b/base/allocator/partition_allocator/src/partition_alloc/pool_offset_freelist.h
@@ -210,7 +210,7 @@ // SetNext() is either called on the freelist head, when provisioning new // slots, or when GetNext() has been called before, no need to pass the // size. -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Regular freelists always point to an entry within the same super page. // // This is most likely a PartitionAlloc bug if this triggers. @@ -219,7 +219,7 @@ (SlotStartPtr2Addr(entry) & kSuperPageBaseMask))) { FreelistCorruptionDetected(0); } -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) encoded_next_ = EncodedPoolOffset(entry); #if PA_CONFIG(HAS_FREELIST_SHADOW_ENTRY) @@ -325,7 +325,7 @@ const bool same_super_page = (here_address & kSuperPageBaseMask) == (next_address & kSuperPageBaseMask); -#if PA_BUILDFLAG(USE_FREESLOT_BITMAP) +#if BUILDFLAG(USE_FREESLOT_BITMAP) // TODO(crbug.com/40274683): Add support for freeslot bitmaps. static_assert(false, "USE_FREESLOT_BITMAP not supported"); #else
diff --git a/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.cc b/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.cc index 0ab06c05c2..656f3a1 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.cc
@@ -8,11 +8,11 @@ namespace partition_alloc::internal { -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) ReservationOffsetTable ReservationOffsetTable::singleton_; #else ReservationOffsetTable::_ReservationOffsetTable ReservationOffsetTable::reservation_offset_table_; -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.h b/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.h index 34d8ce05..b7ba07c3 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.h +++ b/base/allocator/partition_allocator/src/partition_alloc/reservation_offset_table.h
@@ -67,7 +67,7 @@ class PA_COMPONENT_EXPORT(PARTITION_ALLOC) PA_THREAD_ISOLATED_ALIGN ReservationOffsetTable { public: -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // There is one reservation offset table per Pool in 64-bit mode. static constexpr size_t kReservationOffsetTableCoverage = kPoolMaxSize; static constexpr size_t kReservationOffsetTableLength = @@ -78,7 +78,7 @@ static constexpr uint64_t kGiB = 1024 * 1024 * 1024ull; static constexpr size_t kReservationOffsetTableLength = 4 * kGiB / kSuperPageSize; -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) static_assert(kReservationOffsetTableLength < kOffsetTagNormalBuckets, "Offsets should be smaller than kOffsetTagNormalBuckets."); @@ -96,7 +96,7 @@ } } }; -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // If thread isolation support is enabled, we need to write-protect the tables // of the thread isolated pool. For this, we need to pad the tables so that // the thread isolated ones start on a page boundary. @@ -115,10 +115,10 @@ #else // A single table for the entire 32-bit address space. static PA_CONSTINIT struct _ReservationOffsetTable reservation_offset_table_; -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) }; -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) PA_ALWAYS_INLINE uint16_t* GetReservationOffsetTable(pool_handle handle) { PA_DCHECK(kNullPoolHandle < handle && handle <= kNumPools); return ReservationOffsetTable::singleton_.tables[handle - 1].offsets; @@ -148,7 +148,7 @@ ReservationOffsetTable::kReservationOffsetTableLength); return GetReservationOffsetTable(pool) + table_index; } -#else // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#else // BUILDFLAG(HAS_64_BIT_POINTERS) PA_ALWAYS_INLINE uint16_t* GetReservationOffsetTable(uintptr_t address) { return ReservationOffsetTable::reservation_offset_table_.offsets; } @@ -158,10 +158,10 @@ return ReservationOffsetTable::reservation_offset_table_.offsets + ReservationOffsetTable::kReservationOffsetTableLength; } -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) PA_ALWAYS_INLINE uint16_t* ReservationOffsetPointer(uintptr_t address) { -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // In 64-bit mode, find the owning Pool and compute the offset from its base. PartitionAddressSpace::PoolInfo info = GetPoolInfo(address); return ReservationOffsetPointer(info.handle, info.offset); @@ -182,12 +182,12 @@ // If the given address doesn't point to direct-map allocated memory, // returns 0. PA_ALWAYS_INLINE uintptr_t GetDirectMapReservationStart(uintptr_t address) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) bool is_in_brp_pool = IsManagedByPartitionAllocBRPPool(address); bool is_in_regular_pool = IsManagedByPartitionAllocRegularPool(address); bool is_in_configurable_pool = IsManagedByPartitionAllocConfigurablePool(address); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) bool is_in_thread_isolated_pool = IsManagedByPartitionAllocThreadIsolatedPool(address); #endif @@ -196,14 +196,14 @@ #if !BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) PA_DCHECK(!is_in_brp_pool); #endif -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) uint16_t* offset_ptr = ReservationOffsetPointer(address); PA_DCHECK(*offset_ptr != kOffsetTagNotAllocated); if (*offset_ptr == kOffsetTagNormalBuckets) { return 0; } uintptr_t reservation_start = ComputeReservationStart(address, offset_ptr); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // MSVC workaround: the preprocessor seems to choke on an `#if` embedded // inside another macro (PA_DCHECK). #if !BUILDFLAG(HAS_64_BIT_POINTERS) @@ -223,17 +223,17 @@ IsManagedByPartitionAllocRegularPool(reservation_start)); PA_DCHECK(is_in_configurable_pool == IsManagedByPartitionAllocConfigurablePool(reservation_start)); -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) PA_DCHECK(is_in_thread_isolated_pool == IsManagedByPartitionAllocThreadIsolatedPool(reservation_start)); #endif PA_DCHECK(*ReservationOffsetPointer(reservation_start) == 0); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) return reservation_start; } -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // If the given address doesn't point to direct-map allocated memory, // returns 0. // This variant has better performance than the regular one on 64-bit builds if @@ -254,7 +254,7 @@ PA_DCHECK(*ReservationOffsetPointer(reservation_start) == 0); return reservation_start; } -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) // Returns true if |address| is the beginning of the first super page of a // reservation, i.e. either a normal bucket super page, or the first super page
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple.h index e0d4876..3a91ab6 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple.h
@@ -7,7 +7,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include <cstddef> #include "partition_alloc/partition_alloc_base/component_export.h" @@ -66,6 +66,6 @@ } // namespace allocator_shim -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_INTERCEPTION_APPLE_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple.mm b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple.mm index 1aa4345..3554fb2c11 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple.mm +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple.mm
@@ -19,7 +19,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include <CoreFoundation/CoreFoundation.h> #import <Foundation/Foundation.h> #include <mach/mach.h> @@ -630,4 +630,4 @@ } // namespace allocator_shim -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple_unittest.mm b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple_unittest.mm index c043c2f..ffefcca 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple_unittest.mm +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_interception_apple_unittest.mm
@@ -6,7 +6,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include <mach/mach.h> #include "partition_alloc/shim/allocator_shim.h" @@ -72,4 +72,4 @@ } // namespace allocator_shim -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.cc index eb7251e5..9e2909b 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.cc
@@ -9,7 +9,7 @@ #include "partition_alloc/build_config.h" #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h" #endif @@ -48,7 +48,7 @@ // quite likely to keep working in the future. For instance, LLVM for LSAN uses // this mechanism. -#if defined(LIBC_GLIBC) && PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if defined(LIBC_GLIBC) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/shim/allocator_shim_override_glibc_weak_symbols.h" #endif
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h index 9091dd9..3654002 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h
@@ -10,14 +10,14 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include "partition_alloc/build_config.h" #include "partition_alloc/partition_alloc_base/component_export.h" #include "partition_alloc/partition_alloc_base/types/strong_alias.h" #include "partition_alloc/shim/allocator_dispatch.h" #include "partition_alloc/tagging.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(USE_STARSCAN) #include "partition_alloc/starscan/pcscan.h" #endif @@ -91,16 +91,16 @@ #endif // BUILDFLAG(IS_APPLE) #if BUILDFLAG(IS_APPLE) -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) PA_COMPONENT_EXPORT(ALLOCATOR_SHIM) void InitializeDefaultAllocatorPartitionRoot(); bool IsDefaultAllocatorPartitionRootInitialized(); -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // On macOS, the allocator shim needs to be turned on during runtime. PA_COMPONENT_EXPORT(ALLOCATOR_SHIM) void InitializeAllocatorShim(); #endif // BUILDFLAG(IS_APPLE) -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) PA_COMPONENT_EXPORT(ALLOCATOR_SHIM) void EnablePartitionAllocMemoryReclaimer(); using EnableBrp = @@ -137,14 +137,14 @@ PA_COMPONENT_EXPORT(ALLOCATOR_SHIM) void AdjustDefaultAllocatorForForeground(); PA_COMPONENT_EXPORT(ALLOCATOR_SHIM) void AdjustDefaultAllocatorForBackground(); -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) PA_COMPONENT_EXPORT(ALLOCATOR_SHIM) void EnablePCScan(partition_alloc::internal::PCScan::InitConfig); #endif -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } // namespace allocator_shim -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_android.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_android.cc index 7c8f014..c12907c 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_android.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_android.cc
@@ -9,7 +9,7 @@ #include "partition_alloc/build_config.h" #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h" #endif
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_apple.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_apple.cc index 8b9bd37..8cf5a8b43 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_apple.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_apple.cc
@@ -13,7 +13,7 @@ #include "partition_alloc/partition_alloc_check.h" #include "partition_alloc/shim/allocator_interception_apple.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h" #endif @@ -59,7 +59,7 @@ #include "partition_alloc/shim/shim_alloc_functions.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Cpp symbols (new / delete) should always be routed through the shim layer // except on Windows and macOS (except for PartitionAlloc-Everywhere) where the // malloc intercept is deep enough that it also catches the cpp calls. @@ -72,11 +72,11 @@ #include "partition_alloc/shim/allocator_shim_override_cpp_symbols.h" #endif -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/shim/allocator_shim_override_apple_default_zone.h" -#else // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#else // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/shim/allocator_shim_override_apple_symbols.h" -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) namespace allocator_shim {
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.cc index c3a4004..379268f 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.cc
@@ -302,11 +302,11 @@ size, ""); } -#if PA_BUILDFLAG(PA_IS_CAST_ANDROID) +#if BUILDFLAG(PA_IS_CAST_ANDROID) extern "C" { void __real_free(void*); } // extern "C" -#endif // PA_BUILDFLAG(PA_IS_CAST_ANDROID) +#endif // BUILDFLAG(PA_IS_CAST_ANDROID) void PartitionFree(const AllocatorDispatch*, void* object, void* context) { partition_alloc::ScopedDisallowAllocations guard{}; @@ -326,7 +326,7 @@ // malloc() pointer can be passed to PartitionAlloc's free(). If we don't own // the pointer, pass it along. This should not have a runtime cost vs regular // Android, since on Android we have a PA_CHECK() rather than the branch here. -#if PA_BUILDFLAG(PA_IS_CAST_ANDROID) +#if BUILDFLAG(PA_IS_CAST_ANDROID) if (PA_UNLIKELY(!partition_alloc::IsManagedByPartitionAlloc( reinterpret_cast<uintptr_t>(object)) && object)) { @@ -335,7 +335,7 @@ // here. return __real_free(object); } -#endif // PA_BUILDFLAG(PA_IS_CAST_ANDROID) +#endif // BUILDFLAG(PA_IS_CAST_ANDROID) partition_alloc::PartitionRoot::FreeInlineInUnknownRoot< partition_alloc::FreeFlags::kNoHooks>(object); @@ -467,7 +467,7 @@ } // namespace allocator_shim::internal -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) namespace allocator_shim { @@ -574,7 +574,7 @@ #endif // PA_CONFIG(EXTRAS_REQUIRED) } -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) void EnablePCScan(partition_alloc::internal::PCScan::InitConfig config) { partition_alloc::internal::PCScan::Initialize(config); @@ -588,7 +588,7 @@ allocator_shim::NonScannableAllocator::Instance().NotifyPCScanEnabled(); allocator_shim::NonQuarantinableAllocator::Instance().NotifyPCScanEnabled(); } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) void AdjustDefaultAllocatorForForeground() { Allocator()->AdjustForForeground(); @@ -722,4 +722,4 @@ #endif // BUILDFLAG(IS_APPLE) -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h index e6e287e..f65db82 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h
@@ -7,7 +7,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include "partition_alloc/partition_alloc.h" #include "partition_alloc/partition_alloc_base/component_export.h" #include "partition_alloc/shim/allocator_shim.h" @@ -78,7 +78,7 @@ } // namespace internal -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Provide a ConfigurePartitions() helper, to mimic what Chromium uses. This way // we're making it more resilient to ConfigurePartitions() interface changes, so // that we don't have to modify multiple callers. This is particularly important @@ -104,10 +104,10 @@ scheduler_loop_quarantine_capacity_in_bytes, zapping_by_free_flags, use_pool_offset_freelists); } -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } // namespace allocator_shim -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_DEFAULT_DISPATCH_TO_PARTITION_ALLOC_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc_unittest.cc index 20eef1f..3fdecdc 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc_unittest.cc
@@ -22,11 +22,10 @@ #include <malloc/malloc.h> #endif -#if !defined(MEMORY_TOOL_REPLACES_ALLOCATOR) && \ - PA_BUILDFLAG(USE_PARTITION_ALLOC) +#if !defined(MEMORY_TOOL_REPLACES_ALLOCATOR) && BUILDFLAG(USE_PARTITION_ALLOC) namespace allocator_shim::internal { -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Platforms on which we override weak libc symbols. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) @@ -91,7 +90,7 @@ #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Note: the tests below are quite simple, they are used as simple smoke tests // for PartitionAlloc-Everywhere. Most of these directly dispatch to @@ -187,7 +186,7 @@ alignof(partition_alloc::PartitionRoot)); } -#if BUILDFLAG(IS_APPLE) && PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(IS_APPLE) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Make sure that a sequence a "good sizes" grows fast enough. This is // implicitly required by CoreFoundation, and to match Apple's implementation. // Non-regression test for crbug.com/1501312 @@ -200,8 +199,8 @@ } EXPECT_LT(iterations, 100); } -#endif // BUILDFLAG(IS_APPLE) && PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(IS_APPLE) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } // namespace allocator_shim::internal #endif // !defined(MEMORY_TOOL_REPLACES_ALLOCATOR) && - // PA_BUILDFLAG(USE_PARTITION_ALLOC) + // BUILDFLAG(USE_PARTITION_ALLOC)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_apple_symbols.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_apple_symbols.h index 0ee2bd5..b130eb5 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_apple_symbols.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_apple_symbols.h
@@ -11,7 +11,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include "partition_alloc/shim/malloc_zone_functions_apple.h" #include "partition_alloc/third_party/apple_apsl/malloc.h" @@ -72,6 +72,6 @@ } // namespace allocator_shim -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_OVERRIDE_APPLE_SYMBOLS_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_cpp_symbols.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_cpp_symbols.h index d25a4dc..8bda956 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_cpp_symbols.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_cpp_symbols.h
@@ -11,7 +11,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) // Preempt the default new/delete C++ symbols so they call the shim entry // points. This file is strongly inspired by tcmalloc's // libc_override_redefine.h. @@ -35,7 +35,7 @@ #endif SHIM_CPP_SYMBOLS_EXPORT void* operator new(size_t size) { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) return malloc(size); #else return ShimCppNew(size); @@ -43,7 +43,7 @@ } SHIM_CPP_SYMBOLS_EXPORT void operator delete(void* p) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -51,7 +51,7 @@ } SHIM_CPP_SYMBOLS_EXPORT void* operator new[](size_t size) { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) return malloc(size); #else return ShimCppNew(size); @@ -59,7 +59,7 @@ } SHIM_CPP_SYMBOLS_EXPORT void operator delete[](void* p) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -68,7 +68,7 @@ SHIM_CPP_SYMBOLS_EXPORT void* operator new(size_t size, const std::nothrow_t&) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) return malloc(size); #else return ShimCppNewNoThrow(size); @@ -77,7 +77,7 @@ SHIM_CPP_SYMBOLS_EXPORT void* operator new[](size_t size, const std::nothrow_t&) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) return malloc(size); #else return ShimCppNewNoThrow(size); @@ -86,7 +86,7 @@ SHIM_CPP_SYMBOLS_EXPORT void operator delete(void* p, const std::nothrow_t&) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -95,7 +95,7 @@ SHIM_CPP_SYMBOLS_EXPORT void operator delete[](void* p, const std::nothrow_t&) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -103,7 +103,7 @@ } SHIM_CPP_SYMBOLS_EXPORT void operator delete(void* p, size_t) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -111,7 +111,7 @@ } SHIM_CPP_SYMBOLS_EXPORT void operator delete[](void* p, size_t) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -120,7 +120,7 @@ SHIM_CPP_SYMBOLS_EXPORT void* operator new(std::size_t size, std::align_val_t alignment) { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) return aligned_alloc(static_cast<size_t>(alignment), size); #else return ShimCppAlignedNew(size, static_cast<size_t>(alignment)); @@ -130,7 +130,7 @@ SHIM_CPP_SYMBOLS_EXPORT void* operator new(std::size_t size, std::align_val_t alignment, const std::nothrow_t&) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) return aligned_alloc(static_cast<size_t>(alignment), size); #else return ShimCppAlignedNew(size, static_cast<size_t>(alignment)); @@ -139,7 +139,7 @@ SHIM_CPP_SYMBOLS_EXPORT void operator delete(void* p, std::align_val_t) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -149,7 +149,7 @@ SHIM_CPP_SYMBOLS_EXPORT void operator delete(void* p, std::size_t size, std::align_val_t) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -159,7 +159,7 @@ SHIM_CPP_SYMBOLS_EXPORT void operator delete(void* p, std::align_val_t, const std::nothrow_t&) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -168,7 +168,7 @@ SHIM_CPP_SYMBOLS_EXPORT void* operator new[](std::size_t size, std::align_val_t alignment) { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) return aligned_alloc(static_cast<size_t>(alignment), size); #else return ShimCppAlignedNew(size, static_cast<size_t>(alignment)); @@ -178,7 +178,7 @@ SHIM_CPP_SYMBOLS_EXPORT void* operator new[](std::size_t size, std::align_val_t alignment, const std::nothrow_t&) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) return aligned_alloc(static_cast<size_t>(alignment), size); #else return ShimCppAlignedNew(size, static_cast<size_t>(alignment)); @@ -187,7 +187,7 @@ SHIM_CPP_SYMBOLS_EXPORT void operator delete[](void* p, std::align_val_t) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -197,7 +197,7 @@ SHIM_CPP_SYMBOLS_EXPORT void operator delete[](void* p, std::size_t size, std::align_val_t) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); @@ -207,13 +207,13 @@ SHIM_CPP_SYMBOLS_EXPORT void operator delete[](void* p, std::align_val_t, const std::nothrow_t&) __THROW { -#if PA_BUILDFLAG(FORWARD_THROUGH_MALLOC) +#if BUILDFLAG(FORWARD_THROUGH_MALLOC) free(p); #else ShimCppDelete(p); #endif } -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_OVERRIDE_CPP_SYMBOLS_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_glibc_weak_symbols.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_glibc_weak_symbols.h index a060117..1089c1773 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_glibc_weak_symbols.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_glibc_weak_symbols.h
@@ -22,7 +22,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include <features.h> // for __GLIBC__ #include <malloc.h> #include <unistd.h> @@ -123,6 +123,6 @@ shim by setting use_allocator_shim=false in GN args. #endif -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_OVERRIDE_GLIBC_WEAK_SYMBOLS_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_libc_symbols.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_libc_symbols.h index 010f0c2..d60cfa9d 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_libc_symbols.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_libc_symbols.h
@@ -14,7 +14,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include "partition_alloc/build_config.h" #if BUILDFLAG(IS_APPLE) @@ -92,6 +92,6 @@ } // extern "C" -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_OVERRIDE_LIBC_SYMBOLS_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_linker_wrapped_symbols.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_linker_wrapped_symbols.h index 3157d53b..0d4ecd2 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_linker_wrapped_symbols.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_linker_wrapped_symbols.h
@@ -17,7 +17,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include <algorithm> #include <cstring> @@ -178,6 +178,6 @@ } // extern "C" -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_OVERRIDE_LINKER_WRAPPED_SYMBOLS_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_ucrt_symbols_win.h b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_ucrt_symbols_win.h index e46d9af..782a6f7 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_ucrt_symbols_win.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_override_ucrt_symbols_win.h
@@ -14,7 +14,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include "partition_alloc/partition_alloc_base/component_export.h" #include "partition_alloc/partition_alloc_check.h" #include "partition_alloc/shim/allocator_shim_internals.h" @@ -261,6 +261,6 @@ #endif } // extern "C" -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_ALLOCATOR_SHIM_OVERRIDE_UCRT_SYMBOLS_WIN_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_unittest.cc index b937ca3..57dd77e 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_unittest.cc
@@ -423,7 +423,7 @@ // See allocator_shim_override_glibc_weak_symbols.h for why we intercept // internal libc symbols. -#if defined(LIBC_GLIBC) && PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if defined(LIBC_GLIBC) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) void* libc_memalign_ptr = __libc_memalign(512, 56); ASSERT_NE(nullptr, memalign_ptr); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(libc_memalign_ptr) % 512); @@ -467,7 +467,7 @@ #endif // !BUILDFLAG(IS_WIN) -#if defined(LIBC_GLIBC) && PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if defined(LIBC_GLIBC) && BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) free(libc_memalign_ptr); ASSERT_GE(frees_intercepted_by_addr[Hash(memalign_ptr)], 1u); #endif @@ -587,7 +587,7 @@ // PartitionAlloc disallows large allocations to avoid errors with int // overflows. -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) struct TooLarge { char padding1[1UL << 31]; int padding2; @@ -742,7 +742,7 @@ RemoveAllocatorDispatchForTesting(&g_mock_dispatch); } -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // Non-regression test for crbug.com/1166558. TEST_F(AllocatorShimTest, InterceptVasprintf) { // Printing a float which expands to >=30 characters calls vasprintf() in @@ -775,11 +775,11 @@ free(str); } -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #endif // BUILDFLAG(IS_ANDROID) -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_APPLE) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_APPLE) // Non-regression test for crbug.com/1291885. TEST_F(AllocatorShimTest, BatchMalloc) { @@ -798,7 +798,7 @@ EXPECT_GE(good_size, kTestSize); } -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_APPLE) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) && BUILDFLAG(IS_APPLE) TEST_F(AllocatorShimTest, OptimizeAllocatorDispatchTable) { const AllocatorDispatch* prev = GetAllocatorDispatchChainHeadForTesting();
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_win_static.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_win_static.cc index b62a860..1775084 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_win_static.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim_win_static.cc
@@ -9,7 +9,7 @@ #include "partition_alloc/shim/allocator_shim.h" #include "partition_alloc/shim/checked_multiply_win.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h" #endif
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/malloc_zone_functions_apple.h b/base/allocator/partition_allocator/src/partition_alloc/shim/malloc_zone_functions_apple.h index 6180662..7d32024 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/malloc_zone_functions_apple.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/malloc_zone_functions_apple.h
@@ -7,7 +7,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include <malloc/malloc.h> #include <cstddef> @@ -114,6 +114,6 @@ } // namespace allocator_shim -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_MALLOC_ZONE_FUNCTIONS_APPLE_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/nonscannable_allocator.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/nonscannable_allocator.cc index a2b96a43..86bc0ae1 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/nonscannable_allocator.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/nonscannable_allocator.cc
@@ -6,18 +6,18 @@ #include "partition_alloc/partition_root.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h" -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) #include "partition_alloc/internal_allocator.h" #include "partition_alloc/starscan/pcscan.h" #endif -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) namespace allocator_shim::internal { -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) template <bool quarantinable> NonScannableAllocatorImpl<quarantinable>::NonScannableAllocatorImpl() = default; template <bool quarantinable> @@ -35,14 +35,14 @@ template <bool quarantinable> void* NonScannableAllocatorImpl<quarantinable>::Alloc(size_t size) { -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) // TODO(bikineev): Change to LIKELY once PCScan is enabled by default. if (PA_UNLIKELY(pcscan_enabled_.load(std::memory_order_acquire))) { PA_DCHECK(allocator_.get()); return allocator_->root() ->AllocInline<partition_alloc::AllocFlags::kNoHooks>(size); } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) // Otherwise, dispatch to default partition. return allocator_shim::internal::PartitionAllocMalloc::Allocator() ->AllocInline<partition_alloc::AllocFlags::kNoHooks>(size); @@ -50,19 +50,19 @@ template <bool quarantinable> void NonScannableAllocatorImpl<quarantinable>::Free(void* ptr) { -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) if (PA_UNLIKELY(pcscan_enabled_.load(std::memory_order_acquire))) { allocator_->root()->FreeInline<partition_alloc::FreeFlags::kNoHooks>(ptr); return; } -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) partition_alloc::PartitionRoot::FreeInlineInUnknownRoot< partition_alloc::FreeFlags::kNoHooks>(ptr); } template <bool quarantinable> void NonScannableAllocatorImpl<quarantinable>::NotifyPCScanEnabled() { -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) partition_alloc::PartitionOptions opts; opts.star_scan_quarantine = quarantinable ? partition_alloc::PartitionOptions::kAllowed @@ -75,7 +75,7 @@ allocator_->root()); } pcscan_enabled_.store(true, std::memory_order_release); -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) } template class PA_EXPORT_TEMPLATE_DEFINE(PA_COMPONENT_EXPORT(ALLOCATOR_SHIM)) @@ -83,6 +83,6 @@ template class PA_EXPORT_TEMPLATE_DEFINE(PA_COMPONENT_EXPORT(ALLOCATOR_SHIM)) NonScannableAllocatorImpl<false>; -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } // namespace allocator_shim::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/nonscannable_allocator.h b/base/allocator/partition_allocator/src/partition_alloc/shim/nonscannable_allocator.h index b976a7f..bb210e3 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/nonscannable_allocator.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/nonscannable_allocator.h
@@ -14,17 +14,17 @@ #include "partition_alloc/partition_alloc_base/no_destructor.h" #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) #include "partition_alloc/partition_alloc.h" -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) #include "partition_alloc/internal_allocator_forward.h" #endif -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) namespace allocator_shim { -#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#if BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) namespace internal { // Represents allocator that contains memory for data-like objects (that don't @@ -46,14 +46,14 @@ // Returns PartitionRoot corresponding to the allocator, or nullptr if the // allocator is not enabled. partition_alloc::PartitionRoot* root() { -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) if (!allocator_.get()) { return nullptr; } return allocator_->root(); #else return nullptr; -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) } void NotifyPCScanEnabled(); @@ -65,12 +65,12 @@ NonScannableAllocatorImpl(); ~NonScannableAllocatorImpl(); -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) std::unique_ptr<partition_alloc::PartitionAllocator, partition_alloc::internal::InternalPartitionDeleter> allocator_; std::atomic_bool pcscan_enabled_{false}; -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) }; extern template class PA_EXPORT_TEMPLATE_DECLARE( @@ -83,7 +83,7 @@ using NonScannableAllocator = internal::NonScannableAllocatorImpl<true>; using NonQuarantinableAllocator = internal::NonScannableAllocatorImpl<false>; -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) } // namespace allocator_shim
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/winheap_stubs_win.cc b/base/allocator/partition_allocator/src/partition_alloc/shim/winheap_stubs_win.cc index 931ec65f..3318cf9 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/winheap_stubs_win.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/winheap_stubs_win.cc
@@ -104,12 +104,12 @@ static_assert( kMaxWindowsAllocation < std::numeric_limits<unsigned int>::max(), "original_allocation_offset must be able to fit into an unsigned int"); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Magic value used to check that _aligned_free() and _aligned_realloc() are // only ever called on an aligned allocated chunk. static constexpr unsigned int kMagic = 0x12003400; unsigned int magic; -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) }; // Compute how large an allocation we need to fit an allocation with the given @@ -134,18 +134,18 @@ prefix->original_allocation_offset = partition_alloc::internal::base::checked_cast<unsigned int>( address - reinterpret_cast<uintptr_t>(ptr)); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) prefix->magic = AlignedPrefix::kMagic; -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) return reinterpret_cast<void*>(address); } // Return the original allocation from an aligned allocation. void* UnalignAllocation(void* ptr) { AlignedPrefix* prefix = reinterpret_cast<AlignedPrefix*>(ptr) - 1; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) PA_DCHECK(prefix->magic == AlignedPrefix::kMagic); -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) void* unaligned = static_cast<uint8_t*>(ptr) - prefix->original_allocation_offset; PA_CHECK(unaligned < ptr);
diff --git a/base/allocator/partition_allocator/src/partition_alloc/shim/winheap_stubs_win.h b/base/allocator/partition_allocator/src/partition_alloc/shim/winheap_stubs_win.h index be8fd29..65e1766 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/shim/winheap_stubs_win.h +++ b/base/allocator/partition_allocator/src/partition_alloc/shim/winheap_stubs_win.h
@@ -13,7 +13,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#if BUILDFLAG(USE_ALLOCATOR_SHIM) #include "partition_alloc/partition_alloc_base/component_export.h" namespace allocator_shim { @@ -47,6 +47,6 @@ } // namespace allocator_shim -#endif // PA_BUILDFLAG(USE_ALLOCATOR_SHIM) +#endif // BUILDFLAG(USE_ALLOCATOR_SHIM) #endif // PARTITION_ALLOC_SHIM_WINHEAP_STUBS_WIN_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/stack/stack.cc b/base/allocator/partition_allocator/src/partition_alloc/stack/stack.cc index 1f3ce3f..3c4086b 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/stack/stack.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/stack/stack.cc
@@ -136,12 +136,12 @@ } // namespace void Stack::IteratePointers(StackVisitor* visitor) const { -#if PA_BUILDFLAG(STACK_SCAN_SUPPORTED) +#if BUILDFLAG(STACK_SCAN_SUPPORTED) PAPushAllRegistersAndIterateStack(this, visitor, &IteratePointersImpl); // No need to deal with callee-saved registers as they will be kept alive by // the regular conservative stack iteration. IterateSafeStackIfNecessary(visitor); -#endif // PA_BUILDFLAG(STACK_SCAN_SUPPORTED) +#endif // BUILDFLAG(STACK_SCAN_SUPPORTED) } StackTopRegistry::StackTopRegistry() = default;
diff --git a/base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan_internal.cc b/base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan_internal.cc index 3c31ec1..3bb2948 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan_internal.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan_internal.cc
@@ -621,7 +621,7 @@ PA_SCAN_DCHECK(IsManagedByPartitionAllocRegularPool(maybe_ptr)); // First, check if |maybe_ptr| points to a valid super page or a quarantined // card. -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) #if PA_CONFIG(STARSCAN_USE_CARD_TABLE) // Check if |maybe_ptr| points to a quarantined card. if (PA_LIKELY( @@ -642,11 +642,11 @@ return nullptr; } #endif // PA_CONFIG(STARSCAN_USE_CARD_TABLE) -#else // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#else // BUILDFLAG(HAS_64_BIT_POINTERS) if (PA_LIKELY(!IsManagedByPartitionAllocRegularPool(maybe_ptr))) { return nullptr; } -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) // We are certain here that |maybe_ptr| points to an allocated super-page. return StateBitmapFromAddr(maybe_ptr); @@ -785,14 +785,14 @@ size_t quarantine_size() const { return quarantine_size_; } private: -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) PA_ALWAYS_INLINE static uintptr_t RegularPoolBase() { return PartitionAddressSpace::RegularPoolBase(); } PA_ALWAYS_INLINE static uintptr_t RegularPoolMask() { return PartitionAddressSpace::RegularPoolBaseMask(); } -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) PA_SCAN_INLINE void CheckPointer(uintptr_t maybe_ptr_maybe_tagged) { // |maybe_ptr| may have an MTE tag, so remove it first. @@ -1296,7 +1296,7 @@ void PCScanInternal::Initialize(PCScan::InitConfig config) { PA_DCHECK(!is_initialized_); -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // Make sure that pools are initialized. PartitionAddressSpace::Init(); #endif
diff --git a/base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan_unittest.cc index e2d37e1..b22f6505 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/starscan/pcscan_unittest.cc
@@ -24,7 +24,7 @@ #include "partition_alloc/use_death_tests.h" #include "testing/gtest/include/gtest/gtest.h" -#if PA_BUILDFLAG(USE_STARSCAN) +#if BUILDFLAG(USE_STARSCAN) namespace partition_alloc::internal { @@ -786,7 +786,7 @@ TestDanglingReference(*this, source, value, root()); } -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) TEST_F(PartitionAllocPCScanWithMTETest, QuarantineOnlyOnTagOverflow) { using ListType = List<64>; @@ -828,11 +828,11 @@ EXPECT_FALSE(true && "Should never be reached"); } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } // namespace } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(USE_STARSCAN) +#endif // BUILDFLAG(USE_STARSCAN) #endif // defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/starscan/scan_loop.h b/base/allocator/partition_allocator/src/partition_alloc/starscan/scan_loop.h index c3a6252f..619218d 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/starscan/scan_loop.h +++ b/base/allocator/partition_allocator/src/partition_alloc/starscan/scan_loop.h
@@ -97,12 +97,12 @@ void ScanLoop<Derived>::RunUnvectorized(uintptr_t begin, uintptr_t end) { PA_SCAN_DCHECK(!(begin % sizeof(uintptr_t))); PA_SCAN_DCHECK(!(end % sizeof(uintptr_t))); -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) // If the read value is a pointer into the PA region, it's likely // MTE-tagged. Piggyback on |mask| to untag, for efficiency. const uintptr_t mask = Derived::RegularPoolMask() & kPtrUntagMask; const uintptr_t base = Derived::RegularPoolBase(); -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) for (; begin < end; begin += sizeof(uintptr_t)) { // Read the region word-by-word. Everything that we read is a potential // pointer to or inside an object on heap. Such an object should be @@ -110,7 +110,7 @@ // // Keep it MTE-untagged. See DisableMTEScope for details. const uintptr_t maybe_ptr = *reinterpret_cast<uintptr_t*>(begin); -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) if (PA_LIKELY((maybe_ptr & mask) != base)) { continue; } @@ -118,7 +118,7 @@ if (!maybe_ptr) { continue; } -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) derived().CheckPointer(maybe_ptr); } }
diff --git a/base/allocator/partition_allocator/src/partition_alloc/starscan/scan_loop_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/starscan/scan_loop_unittest.cc index 6d7aa81..5c3aedff 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/starscan/scan_loop_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/starscan/scan_loop_unittest.cc
@@ -12,7 +12,7 @@ #include "partition_alloc/partition_alloc_config.h" #include "testing/gtest/include/gtest/gtest.h" -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) namespace partition_alloc::internal { @@ -172,4 +172,4 @@ } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/tagging.cc b/base/allocator/partition_allocator/src/partition_alloc/tagging.cc index 2cfcab49..46b4767 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/tagging.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/tagging.cc
@@ -14,7 +14,7 @@ #include "partition_alloc/partition_alloc_check.h" #include "partition_alloc/partition_alloc_config.h" -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) #include <arm_acle.h> #include <asm/hwcap.h> #include <sys/auxv.h> @@ -48,7 +48,7 @@ #if BUILDFLAG(IS_ANDROID) #include "partition_alloc/partition_alloc_base/files/file_path.h" #include "partition_alloc/partition_alloc_base/native_library.h" -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) #include <malloc.h> #endif // BUILDFLAGS(HAS_MEMORY_TAGGING) #endif // BUILDFLAG(IS_ANDROID) @@ -56,7 +56,7 @@ namespace partition_alloc { void ChangeMemoryTaggingModeForCurrentThreadNoOp(TagViolationReportingMode m) {} -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) using ChangeMemoryTaggingModeForCurrentThreadInternalFn = void(TagViolationReportingMode); @@ -85,10 +85,10 @@ ? &ChangeMemoryTaggingModeForCurrentThreadForMte : &ChangeMemoryTaggingModeForCurrentThreadNoOp; } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) void ChangeMemoryTaggingModeForCurrentThread(TagViolationReportingMode m) -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) __attribute__((ifunc("ResolveChangeMemoryTaggingModeForCurrentThread"))); #else { @@ -101,7 +101,7 @@ #if BUILDFLAG(IS_ANDROID) bool ChangeMemoryTaggingModeForAllThreadsPerProcess( TagViolationReportingMode m) { -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) // In order to support Android NDK API level below 26, we need to call // mallopt via dynamic linker. // int mallopt(int param, int value); @@ -134,7 +134,7 @@ return status != 0; #else return false; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } #endif // BUILDFLAG(IS_ANDROID) @@ -147,7 +147,7 @@ return ret; } -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) void* TagRegionRandomlyForMTE(void* ptr, size_t sz, uint64_t mask) { // Randomly tag a region (MTE-enabled systems only). The first 16-byte // granule is randomly tagged, all other granules in the region are @@ -204,11 +204,11 @@ void* RemaskVoidPtrNoOp(void* ptr) { return ptr; } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } // namespace -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) using RemaskPtrInternalFn = void*(void* ptr); using TagMemoryRangeIncrementInternalFn = void*(void* ptr, size_t size); using TagMemoryRangeRandomlyInternalFn = void*(void* ptr, @@ -247,13 +247,13 @@ __attribute__((ifunc("ResolveTagMemoryRandomly"))); void* RemaskPointerInternal(void* ptr) __attribute__((ifunc("ResolveRemaskPointer"))); -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) TagViolationReportingMode GetMemoryTaggingModeForCurrentThreadNoMte() { return TagViolationReportingMode::kUndefined; } -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) using GetMemoryTaggingModeForCurrentThreadInternalFn = TagViolationReportingMode(); @@ -277,10 +277,10 @@ return IsMteEnabled(hwcap, hw) ? &GetMemoryTaggingModeForCurrentThreadMte : &GetMemoryTaggingModeForCurrentThreadNoMte; } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) TagViolationReportingMode GetMemoryTaggingModeForCurrentThread() -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) __attribute__((ifunc("ResolveGetMemoryTaggingModeForCurrentThread"))); #else { @@ -290,7 +290,7 @@ } // namespace internal -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) && BUILDFLAG(IS_ANDROID) +#if BUILDFLAG(HAS_MEMORY_TAGGING) && BUILDFLAG(IS_ANDROID) bool PermissiveMte::enabled_ = false; // static @@ -314,6 +314,6 @@ } return false; } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) && BUILDFLAG(IS_ANDROID) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) && BUILDFLAG(IS_ANDROID) } // namespace partition_alloc
diff --git a/base/allocator/partition_allocator/src/partition_alloc/tagging.h b/base/allocator/partition_allocator/src/partition_alloc/tagging.h index de2fc78..d01419a 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/tagging.h +++ b/base/allocator/partition_allocator/src/partition_alloc/tagging.h
@@ -17,7 +17,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" #include "partition_alloc/partition_alloc_config.h" -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) && BUILDFLAG(IS_ANDROID) +#if BUILDFLAG(HAS_MEMORY_TAGGING) && BUILDFLAG(IS_ANDROID) #include <csignal> #endif @@ -43,11 +43,11 @@ namespace internal { constexpr uint64_t kMemTagGranuleSize = 16u; -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) constexpr uint64_t kPtrTagMask = 0xff00000000000000uLL; #else constexpr uint64_t kPtrTagMask = 0; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) constexpr uint64_t kPtrUntagMask = ~kPtrTagMask; #if BUILDFLAG(IS_ANDROID) @@ -66,24 +66,24 @@ // These forward-defined functions do not really exist in tagging.cc, they're // resolved by the dynamic linker to MTE-capable versions on the right hardware. -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) PA_COMPONENT_EXPORT(PARTITION_ALLOC) void* TagMemoryRangeIncrementInternal(void* ptr, size_t size); PA_COMPONENT_EXPORT(PARTITION_ALLOC) void* TagMemoryRangeRandomlyInternal(void* ptr, size_t size, uint64_t mask); PA_COMPONENT_EXPORT(PARTITION_ALLOC) void* RemaskPointerInternal(void* ptr); -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) // Increments the tag of the memory range ptr. Useful for provable revocations // (e.g. free). Returns the pointer with the new tag. Ensures that the entire // range is set to the same tag. PA_ALWAYS_INLINE void* TagMemoryRangeIncrement(void* ptr, size_t size) { -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) return TagMemoryRangeIncrementInternal(ptr, size); #else return ptr; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } PA_ALWAYS_INLINE void* TagMemoryRangeIncrement(uintptr_t address, size_t size) { @@ -97,22 +97,22 @@ size_t size, uint64_t mask = 0u) { void* ptr = reinterpret_cast<void*>(address); -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) return reinterpret_cast<void*>( TagMemoryRangeRandomlyInternal(ptr, size, mask)); #else return ptr; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } // Gets a version of ptr that's safe to dereference. template <typename T> PA_ALWAYS_INLINE T* TagPtr(T* ptr) { -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) return reinterpret_cast<T*>(RemaskPointerInternal(ptr)); #else return ptr; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } // Gets a version of |address| that's safe to dereference, and casts to a @@ -123,11 +123,11 @@ // Strips the tag bits off |address|. PA_ALWAYS_INLINE uintptr_t UntagAddr(uintptr_t address) { -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) return address & internal::kPtrUntagMask; #else return address; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } } // namespace internal @@ -138,7 +138,7 @@ return internal::UntagAddr(reinterpret_cast<uintptr_t>(ptr)); } -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) && BUILDFLAG(IS_ANDROID) +#if BUILDFLAG(HAS_MEMORY_TAGGING) && BUILDFLAG(IS_ANDROID) class PA_COMPONENT_EXPORT(PARTITION_ALLOC) PermissiveMte { public: static void SetEnabled(bool enabled); @@ -147,7 +147,7 @@ private: static bool enabled_; }; -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } // namespace partition_alloc
diff --git a/base/allocator/partition_allocator/src/partition_alloc/tagging_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/tagging_unittest.cc index 63295ad..fed08ccb 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/tagging_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/tagging_unittest.cc
@@ -145,7 +145,7 @@ } #endif // defined(ARCH_CPU_64_BITS) -#if PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#if BUILDFLAG(HAS_MEMORY_TAGGING) #if BUILDFLAG(IS_ANDROID) TEST(PartitionAllocMemoryTaggingTest, ChangeMemoryTaggingModeForAllThreadsPerProcess) { @@ -214,6 +214,6 @@ // Restore mode to original. ChangeMemoryTaggingModeForCurrentThread(original_mode); } -#endif // PA_BUILDFLAG(HAS_MEMORY_TAGGING) +#endif // BUILDFLAG(HAS_MEMORY_TAGGING) } // namespace partition_alloc::internal
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_cache.cc b/base/allocator/partition_allocator/src/partition_alloc/thread_cache.cc index cd16aac..c99e448 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_cache.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_cache.cc
@@ -33,7 +33,7 @@ namespace tools { uintptr_t kThreadCacheNeedleArray[kThreadCacheNeedleArraySize] = { kNeedle1, reinterpret_cast<uintptr_t>(&g_instance), -#if PA_BUILDFLAG(RECORD_ALLOC_INFO) +#if BUILDFLAG(RECORD_ALLOC_INFO) reinterpret_cast<uintptr_t>(&internal::g_allocs), #else 0, @@ -179,7 +179,7 @@ internal::ScopedGuard scoped_locker(GetLock()); ThreadCache* tcache = list_head_; while (tcache) { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) // Before fork(), locks are acquired in the parent process. This means that // a concurrent allocation in the parent which must be filled by the central // allocator (i.e. the thread cache bucket is empty) will block inside the @@ -704,17 +704,17 @@ auto* head = bucket.freelist_head; size_t items = 1; // Cannot free the freelist head. while (items < limit) { -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) head = freelist_dispatcher->GetNextForThreadCacheBool( head, crash_on_corruption, bucket.slot_size); #else head = freelist_dispatcher->GetNextForThreadCache<crash_on_corruption>( head, bucket.slot_size); -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) items++; } -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) FreeAfter<crash_on_corruption>( freelist_dispatcher->GetNextForThreadCacheBool( head, crash_on_corruption, bucket.slot_size), @@ -724,7 +724,7 @@ freelist_dispatcher->GetNextForThreadCache<crash_on_corruption>( head, bucket.slot_size), bucket.slot_size); -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) freelist_dispatcher->SetNext(head, nullptr); } bucket.count = limit; @@ -747,13 +747,13 @@ uintptr_t slot_start = internal::SlotStartPtr2Addr(head); const internal::PartitionFreelistDispatcher* freelist_dispatcher = root_->get_freelist_dispatcher(); -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) head = freelist_dispatcher->GetNextForThreadCacheBool( head, crash_on_corruption, slot_size); #else head = freelist_dispatcher->GetNextForThreadCache<crash_on_corruption>( head, slot_size); -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) root_->RawFreeLocked(slot_start); } }
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_cache.h b/base/allocator/partition_allocator/src/partition_alloc/thread_cache.h index 19baa13a..161f806 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_cache.h +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_cache.h
@@ -28,7 +28,7 @@ #include "partition_alloc/partition_stats.h" #include "partition_alloc/partition_tls.h" -#if defined(ARCH_CPU_X86_64) && PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if defined(ARCH_CPU_X86_64) && BUILDFLAG(HAS_64_BIT_POINTERS) #include <algorithm> #endif @@ -44,13 +44,13 @@ // // These two values were chosen randomly, and in particular neither is a valid // pointer on most 64 bit architectures. -#if PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#if BUILDFLAG(HAS_64_BIT_POINTERS) constexpr uintptr_t kNeedle1 = 0xe69e32f3ad9ea63; constexpr uintptr_t kNeedle2 = 0x9615ee1c5eb14caf; #else constexpr uintptr_t kNeedle1 = 0xe69e32f3; constexpr uintptr_t kNeedle2 = 0x9615ee1c; -#endif // PA_BUILDFLAG(HAS_64_BIT_POINTERS) +#endif // BUILDFLAG(HAS_64_BIT_POINTERS) // This array contains, in order: // - kNeedle1 @@ -200,7 +200,7 @@ } while (0) #endif // PA_CONFIG(THREAD_CACHE_ENABLE_STATISTICS) -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) namespace internal { @@ -224,13 +224,13 @@ x \ } -#else // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#else // BUILDFLAG(PA_DCHECK_IS_ON) #define PA_REENTRANCY_GUARD(x) \ do { \ } while (0) -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) // Per-thread cache. *Not* threadsafe, must only be accessed from a single // thread. @@ -469,7 +469,7 @@ PartitionRoot* const root_; const internal::base::PlatformThreadId thread_id_; -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) bool is_in_thread_cache_ = false; #endif @@ -559,7 +559,7 @@ internal::PartitionFreelistEntry* entry = bucket.freelist_head; // TODO(lizeb): Consider removing once crbug.com/1382658 is fixed. #if BUILDFLAG(IS_CHROMEOS) && defined(ARCH_CPU_X86_64) && \ - PA_BUILDFLAG(HAS_64_BIT_POINTERS) + BUILDFLAG(HAS_64_BIT_POINTERS) // x86_64 architecture now supports 57 bits of address space, as of Ice Lake // for Intel. However Chrome OS systems do not ship with kernel support for // it, but with 48 bits, so all canonical addresses have the upper 16 bits @@ -568,7 +568,7 @@ constexpr uintptr_t kCanonicalPointerMask = (1ULL << 48) - 1; PA_CHECK(!(reinterpret_cast<uintptr_t>(entry) & ~kCanonicalPointerMask)); #endif // BUILDFLAG(IS_CHROMEOS) && defined(ARCH_CPU_X86_64) && - // PA_BUILDFLAG(HAS_64_BIT_POINTERS) + // BUILDFLAG(HAS_64_BIT_POINTERS) // Passes the bucket size to |GetNext()|, so that in case of freelist // corruption, we know the bucket size that lead to the crash, helping to @@ -576,13 +576,13 @@ // does not introduce another cache miss. const internal::PartitionFreelistDispatcher* freelist_dispatcher = get_freelist_dispatcher_from_root(); -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) internal::PartitionFreelistEntry* next = freelist_dispatcher->GetNextForThreadCacheTrue(entry, bucket.slot_size); #else internal::PartitionFreelistEntry* next = freelist_dispatcher->GetNextForThreadCache<true>(entry, bucket.slot_size); -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) PA_DCHECK(entry != next); bucket.count--; @@ -599,7 +599,7 @@ PA_ALWAYS_INLINE void ThreadCache::PutInBucket(Bucket& bucket, uintptr_t slot_start) { #if PA_CONFIG(HAS_FREELIST_SHADOW_ENTRY) && defined(ARCH_CPU_X86_64) && \ - PA_BUILDFLAG(HAS_64_BIT_POINTERS) + BUILDFLAG(HAS_64_BIT_POINTERS) // We see freelist corruption crashes happening in the wild. These are likely // due to out-of-bounds accesses in the previous slot, or to a Use-After-Free // somewhere in the code. @@ -646,7 +646,7 @@ address_aligned += 4; } #endif // PA_CONFIG(HAS_FREELIST_SHADOW_ENTRY) && defined(ARCH_CPU_X86_64) && - // PA_BUILDFLAG(HAS_64_BIT_POINTERS) + // BUILDFLAG(HAS_64_BIT_POINTERS) auto* entry = get_freelist_dispatcher_from_root()->EmplaceAndInitForThreadCache(
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_cache_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/thread_cache_unittest.cc index 9c68364..9b83405 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_cache_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_cache_unittest.cc
@@ -88,7 +88,7 @@ PartitionOptions opts; #if !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) opts.thread_cache = PartitionOptions::kEnabled; -#endif // PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) +#endif // BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) opts.star_scan_quarantine = PartitionOptions::kAllowed; opts.use_pool_offset_freelists = (encoding == internal::PartitionFreelistEncoding::kPoolOffsetFreeList) @@ -539,7 +539,7 @@ #if !(BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID) || \ BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)) && \ - PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) + BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) // iOS and MacOS 15 create worker threads internally(start_wqthread). // So thread caches are created for the worker threads, because the threads // allocate memory for initialization (_dispatch_calloc is invoked). @@ -567,7 +567,7 @@ #if !(BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID) || \ BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)) && \ - PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) + BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) internal::ScopedGuard lock(ThreadCacheRegistry::GetLock()); EXPECT_EQ(parent_thread_tcache->prev_for_testing(), nullptr); EXPECT_EQ(parent_thread_tcache->next_for_testing(), nullptr); @@ -676,7 +676,7 @@ ThreadCacheStats wqthread_stats{0}; #if (BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS) || \ BUILDFLAG(IS_LINUX)) && \ - PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) + BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC) { // iOS and MacOS 15 create worker threads internally(start_wqthread). // So thread caches are created for the worker threads, because the threads @@ -1202,13 +1202,13 @@ uint8_t count = 0; auto* head = tcache->bucket_for_testing(index).freelist_head; while (head) { -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) head = freelist_dispatcher->GetNextForThreadCacheTrue( head, tcache->bucket_for_testing(index).slot_size); #else head = freelist_dispatcher->GetNextForThreadCache<true>( head, tcache->bucket_for_testing(index).slot_size); -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) count++; } return count; @@ -1313,11 +1313,11 @@ auto* curr = medium_bucket->active_slot_spans_head->get_freelist_head(); const internal::PartitionFreelistDispatcher* freelist_dispatcher = root()->get_freelist_dispatcher(); -#if PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#if BUILDFLAG(USE_FREELIST_DISPATCHER) curr = freelist_dispatcher->GetNextForThreadCacheTrue(curr, kMediumSize); #else curr = freelist_dispatcher->GetNextForThreadCache<true>(curr, kMediumSize); -#endif // PA_BUILDFLAG(USE_FREELIST_DISPATCHER) +#endif // BUILDFLAG(USE_FREELIST_DISPATCHER) freelist_dispatcher->CorruptNextForTesting(curr, 0x12345678); tcache->TryPurge(); freelist_dispatcher->SetNext(curr, nullptr);
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/alignment.h b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/alignment.h index 9472261..aa7f23e 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/alignment.h +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/alignment.h
@@ -7,7 +7,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) #include "partition_alloc/page_allocator_constants.h" @@ -32,13 +32,13 @@ #define PA_THREAD_ISOLATED_ARRAY_PAD_SZ(Type, count) \ PA_THREAD_ISOLATED_ARRAY_PAD_SZ_WITH_OFFSET(Type, count, 0) -#else // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#else // BUILDFLAG(ENABLE_THREAD_ISOLATION) #define PA_THREAD_ISOLATED_ALIGN #define PA_THREAD_ISOLATED_FILL_PAGE_SZ(size) 0 #define PA_THREAD_ISOLATED_ARRAY_PAD_SZ(Type, size) 0 #define PA_THREAD_ISOLATED_ARRAY_PAD_SZ_WITH_OFFSET(Type, size, offset) 0 -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) #endif // PARTITION_ALLOC_THREAD_ISOLATION_ALIGNMENT_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.cc b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.cc index bba9d1a..f8b1f798 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.cc
@@ -4,7 +4,7 @@ #include "partition_alloc/thread_isolation/pkey.h" -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) #include <sys/mman.h> #include <sys/syscall.h> @@ -61,7 +61,7 @@ asm volatile(".byte 0x0f,0x01,0xef\n" : : "a"(pkru), "c"(0), "d"(0)); } -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) LiftPkeyRestrictionsScope::LiftPkeyRestrictionsScope() : saved_pkey_value_(kDefaultPkeyValue) { @@ -83,8 +83,8 @@ } } -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(ENABLE_PKEYS) +#endif // BUILDFLAG(ENABLE_PKEYS)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.h b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.h index b4a7595..8edb4ed 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.h +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey.h
@@ -7,7 +7,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) #include "partition_alloc/partition_alloc_base/component_export.h" #include "partition_alloc/partition_alloc_base/debug/debugging_buildflags.h" @@ -39,7 +39,7 @@ // Write the pkru register (the current pkey state). void Wrpkru(uint32_t pkru); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) class PA_COMPONENT_EXPORT(PARTITION_ALLOC) LiftPkeyRestrictionsScope { public: @@ -53,10 +53,10 @@ uint32_t saved_pkey_value_; }; -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(ENABLE_PKEYS) +#endif // BUILDFLAG(ENABLE_PKEYS) #endif // PARTITION_ALLOC_THREAD_ISOLATION_PKEY_H_
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey_unittest.cc b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey_unittest.cc index d6ac7f05..5cd7314 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey_unittest.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/pkey_unittest.cc
@@ -8,7 +8,7 @@ #include "partition_alloc/partition_root.h" #include "partition_alloc/thread_isolation/thread_isolation.h" -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) #include <link.h> #include <sys/mman.h> @@ -271,4 +271,4 @@ } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.cc b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.cc index 09bb583..6b83265 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.cc +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.cc
@@ -4,7 +4,7 @@ #include "partition_alloc/thread_isolation/thread_isolation.h" -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) #include "partition_alloc/address_pool_manager.h" #include "partition_alloc/page_allocator.h" @@ -12,13 +12,13 @@ #include "partition_alloc/partition_alloc_constants.h" #include "partition_alloc/reservation_offset_table.h" -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) #include "partition_alloc/thread_isolation/pkey.h" #endif namespace partition_alloc::internal { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) ThreadIsolationSettings ThreadIsolationSettings::settings; #endif @@ -37,7 +37,7 @@ : PageAccessibilityConfiguration::Permissions::kReadWrite)); return; } -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) partition_alloc::internal::TagMemoryWithPkey( thread_isolation.enabled ? thread_isolation.pkey : kDefaultPkey, address, size); @@ -59,7 +59,7 @@ size_t len, int prot, ThreadIsolationOption thread_isolation) { -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) return PkeyMprotect(addr, len, prot, thread_isolation.pkey); #endif } @@ -80,7 +80,7 @@ thread_isolation, pkey_reservation_offset_table, ReservationOffsetTable::kReservationOffsetTableLength); -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) WriteProtectThreadIsolatedVariable(thread_isolation, ThreadIsolationSettings::settings); #endif @@ -92,4 +92,4 @@ } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION)
diff --git a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.h b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.h index b6b63436..58f7da4 100644 --- a/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.h +++ b/base/allocator/partition_allocator/src/partition_alloc/thread_isolation/thread_isolation.h
@@ -7,7 +7,7 @@ #include "partition_alloc/partition_alloc_buildflags.h" -#if PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#if BUILDFLAG(ENABLE_THREAD_ISOLATION) #include <cstddef> #include <cstdint> @@ -15,7 +15,7 @@ #include "partition_alloc/partition_alloc_base/component_export.h" #include "partition_alloc/partition_alloc_base/debug/debugging_buildflags.h" -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) #include "partition_alloc/thread_isolation/pkey.h" #endif @@ -29,21 +29,21 @@ constexpr ThreadIsolationOption() = default; explicit ThreadIsolationOption(bool enabled) : enabled(enabled) {} -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) explicit ThreadIsolationOption(int pkey) : pkey(pkey) { enabled = pkey != internal::kInvalidPkey; } int pkey = -1; -#endif // PA_BUILDFLAG(ENABLE_PKEYS) +#endif // BUILDFLAG(ENABLE_PKEYS) bool enabled = false; bool operator==(const ThreadIsolationOption& other) const { -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) if (pkey != other.pkey) { return false; } -#endif // PA_BUILDFLAG(ENABLE_PKEYS) +#endif // BUILDFLAG(ENABLE_PKEYS) return enabled == other.enabled; } }; @@ -52,19 +52,19 @@ namespace partition_alloc::internal { -#if PA_BUILDFLAG(PA_DCHECK_IS_ON) +#if BUILDFLAG(PA_DCHECK_IS_ON) struct PA_THREAD_ISOLATED_ALIGN ThreadIsolationSettings { bool enabled = false; static ThreadIsolationSettings settings PA_CONSTINIT; }; -#if PA_BUILDFLAG(ENABLE_PKEYS) +#if BUILDFLAG(ENABLE_PKEYS) using LiftThreadIsolationScope = LiftPkeyRestrictionsScope; -#endif // PA_BUILDFLAG(ENABLE_PKEYS) -#endif // PA_BUILDFLAG(PA_DCHECK_IS_ON) +#endif // BUILDFLAG(ENABLE_PKEYS) +#endif // BUILDFLAG(PA_DCHECK_IS_ON) void WriteProtectThreadIsolatedGlobals(ThreadIsolationOption thread_isolation); void UnprotectThreadIsolatedGlobals(); @@ -76,6 +76,6 @@ } // namespace partition_alloc::internal -#endif // PA_BUILDFLAG(ENABLE_THREAD_ISOLATION) +#endif // BUILDFLAG(ENABLE_THREAD_ISOLATION) #endif // PARTITION_ALLOC_THREAD_ISOLATION_THREAD_ISOLATION_H_
diff --git a/build/.clang-tidy b/build/.clang-tidy new file mode 100644 index 0000000..b570314 --- /dev/null +++ b/build/.clang-tidy
@@ -0,0 +1,3 @@ +# TODO(crbug.com/336474469): remove this after enabling the check in parent dir. +InheritParentConfig: true +Checks: misc-include-cleaner
diff --git a/build/.clangd b/build/.clangd new file mode 100644 index 0000000..4b4eca2 --- /dev/null +++ b/build/.clangd
@@ -0,0 +1,4 @@ +# TODO(crbug.com/336474469): remove this after enabling the check in parent dir. +Diagnostics: + UnusedIncludes: Strict + MissingIncludes: Strict
diff --git a/build/rust/std/remap_alloc.cc b/build/rust/std/remap_alloc.cc index 024adb2..7604b204 100644 --- a/build/rust/std/remap_alloc.cc +++ b/build/rust/std/remap_alloc.cc
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include <stdlib.h> + #include <algorithm> #include <cstddef> #include <cstdlib>
diff --git a/build/rust/tests/test_cpp_including_rust/shared_unittests.cc b/build/rust/tests/test_cpp_including_rust/shared_unittests.cc index eb86c92..09a016e8 100644 --- a/build/rust/tests/test_cpp_including_rust/shared_unittests.cc +++ b/build/rust/tests/test_cpp_including_rust/shared_unittests.cc
@@ -6,14 +6,16 @@ #include <memory> -#include "base/allocator/buildflags.h" -#include "base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.h" -#include "base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h" -#include "build/build_config.h" +#include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h" #include "build/buildflag.h" +#include "build/rust/tests/test_rust_shared_library/src/lib.rs.h" #include "testing/gtest/include/gtest/gtest.h" -#include "build/rust/tests/test_rust_shared_library/src/lib.rs.h" +#if BUILDFLAG(HAS_64_BIT_POINTERS) +#include "base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h" +#else +#include "base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.h" +#endif TEST(RustSharedTest, CppCallingIntoRust_BasicFFI) { EXPECT_EQ(7, add_two_ints_via_rust(3, 4));
diff --git a/build/rust/tests/test_cpp_including_rust/static_unittests.cc b/build/rust/tests/test_cpp_including_rust/static_unittests.cc index b83e7e5..b389cd3 100644 --- a/build/rust/tests/test_cpp_including_rust/static_unittests.cc +++ b/build/rust/tests/test_cpp_including_rust/static_unittests.cc
@@ -6,14 +6,16 @@ #include <memory> -#include "base/allocator/buildflags.h" -#include "base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.h" -#include "base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h" -#include "build/build_config.h" +#include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h" #include "build/buildflag.h" +#include "build/rust/tests/test_rust_static_library/src/lib.rs.h" #include "testing/gtest/include/gtest/gtest.h" -#include "build/rust/tests/test_rust_static_library/src/lib.rs.h" +#if BUILDFLAG(HAS_64_BIT_POINTERS) +#include "base/allocator/partition_allocator/src/partition_alloc/partition_address_space.h" +#else +#include "base/allocator/partition_allocator/src/partition_alloc/address_pool_manager_bitmap.h" +#endif TEST(RustStaticTest, CppCallingIntoRust_BasicFFI) { EXPECT_EQ(7, add_two_ints_via_rust(3, 4));
diff --git a/build/rust/tests/test_rust_calling_cpp/cpp_library.cc b/build/rust/tests/test_rust_calling_cpp/cpp_library.cc index cb0a39c3..fd0445ca 100644 --- a/build/rust/tests/test_rust_calling_cpp/cpp_library.cc +++ b/build/rust/tests/test_rust_calling_cpp/cpp_library.cc
@@ -4,6 +4,8 @@ #include "build/rust/tests/test_rust_calling_cpp/cpp_library.h" +#include <cstdint> + int32_t mul_by_2_in_cpp_library(int32_t a) { return a * 2; }
diff --git a/cc/slim/test_frame_sink_impl.cc b/cc/slim/test_frame_sink_impl.cc index f1a82c7..89d4407 100644 --- a/cc/slim/test_frame_sink_impl.cc +++ b/cc/slim/test_frame_sink_impl.cc
@@ -48,8 +48,8 @@ did_not_produce_frame_ = true; } void DidAllocateSharedBitmap(base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id) override {} - void DidDeleteSharedBitmap(const gpu::Mailbox& id) override {} + const viz::SharedBitmapId& id) override {} + void DidDeleteSharedBitmap(const viz::SharedBitmapId& id) override {} void InitializeCompositorFrameSinkType( viz::mojom::CompositorFrameSinkType type) override {} void BindLayerContext(viz::mojom::PendingLayerContextPtr context) override {}
diff --git a/chrome/VERSION b/chrome/VERSION index 9fe9e34..6534049 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=126 MINOR=0 -BUILD=6465 +BUILD=6466 PATCH=0
diff --git a/chrome/android/java/res/xml/unified_account_settings_preferences.xml b/chrome/android/java/res/xml/unified_account_settings_preferences.xml index f5efe4e..0fcbafe 100644 --- a/chrome/android/java/res/xml/unified_account_settings_preferences.xml +++ b/chrome/android/java/res/xml/unified_account_settings_preferences.xml
@@ -53,8 +53,8 @@ android:summary="@string/data_types_switches_summary"/> <PreferenceCategory - android:key="control_your_data_category" - android:title="@string/prefs_control_your_data"/> + android:key="account_advanced_header" + android:title="@string/account_advanced_header"/> <org.chromium.components.browser_ui.settings.ChromeBasePreference android:key="google_activity_controls"
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionControllerUnitTest.java b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionControllerUnitTest.java index c524f6f..1d69933 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionControllerUnitTest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/ContextualPageActionControllerUnitTest.java
@@ -45,7 +45,10 @@ /** Unit tests for {@link ContextualPageActionController} */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) -@EnableFeatures({ChromeFeatureList.CONTEXTUAL_PAGE_ACTIONS}) +@EnableFeatures({ + ChromeFeatureList.CONTEXTUAL_PAGE_ACTIONS, + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING, +}) public class ContextualPageActionControllerUnitTest { private ObservableSupplierImpl<Profile> mProfileSupplier; private ObservableSupplierImpl<Tab> mTabSupplier; @@ -148,6 +151,8 @@ testValues.addFeatureFlagOverride(ChromeFeatureList.CONTEXTUAL_PAGE_ACTIONS, true); testValues.addFieldTrialParamOverride( ChromeFeatureList.CONTEXTUAL_PAGE_ACTIONS, "enable_ui", "false"); + testValues.addFeatureFlagOverride( + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING, true); FeatureList.setTestValues(testValues); createContextualPageActionController();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/PriceTrackingActionProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/PriceTrackingActionProvider.java index abc5f26c..be160dfb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/PriceTrackingActionProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/PriceTrackingActionProvider.java
@@ -11,7 +11,6 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.components.commerce.core.ShoppingService; -import org.chromium.components.embedder_support.util.UrlUtilities; /** Provides price tracking signal for showing contextual page action for a given tab. */ public class PriceTrackingActionProvider implements ContextualPageActionController.ActionProvider { @@ -31,13 +30,6 @@ @Override public void getAction(Tab tab, SignalAccumulator signalAccumulator) { - - if (tab == null || tab.getUrl() == null || !UrlUtilities.isHttpOrHttps(tab.getUrl())) { - signalAccumulator.setHasPriceTracking(false); - signalAccumulator.notifySignalAvailable(); - return; - } - final BookmarkModel bookmarkModel = mBookmarkModelSupplier.get(); bookmarkModel.finishLoadingBookmarkModel( () -> {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/PriceTrackingActionProviderTest.java b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/PriceTrackingActionProviderTest.java index 1e5d468..bb3609b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/PriceTrackingActionProviderTest.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/segmentation_platform/PriceTrackingActionProviderTest.java
@@ -8,8 +8,6 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; import android.os.Handler; @@ -31,13 +29,13 @@ import org.chromium.chrome.browser.commerce.PriceTrackingUtils; import org.chromium.chrome.browser.commerce.PriceTrackingUtilsJni; import org.chromium.chrome.browser.profiles.Profile; +import org.chromium.chrome.browser.profiles.ProfileManager; import org.chromium.chrome.browser.segmentation_platform.ContextualPageActionController.ActionProvider; import org.chromium.chrome.browser.tab.Tab; import org.chromium.components.bookmarks.BookmarkId; import org.chromium.components.commerce.core.ShoppingService; import org.chromium.components.commerce.core.ShoppingService.ProductInfo; import org.chromium.components.commerce.core.ShoppingService.ProductInfoCallback; -import org.chromium.url.JUnitTestGURLs; import java.util.ArrayList; import java.util.List; @@ -116,7 +114,6 @@ @Test public void priceTrackingActionShownSuccessfully() { - doReturn(JUnitTestGURLs.EXAMPLE_URL).when(mMockTab).getUrl(); List<ActionProvider> providers = new ArrayList<>(); PriceTrackingActionProvider provider = new PriceTrackingActionProvider( @@ -130,7 +127,6 @@ @Test public void priceTrackingNotShownForAlreadyPriceTrackedPages() { - doReturn(JUnitTestGURLs.EXAMPLE_URL).when(mMockTab).getUrl(); List<ActionProvider> providers = new ArrayList<>(); PriceTrackingActionProvider provider = new PriceTrackingActionProvider( @@ -139,6 +135,7 @@ SignalAccumulator accumulator = new SignalAccumulator(new Handler(), mMockTab, providers); // URL supports price tracking. setIsUrlPriceTrackableResult(true); + ProfileManager.setLastUsedProfileForTesting(mProfile); // URL is already bookmarked. doReturn(new BookmarkId(1L, 0)).when(mBookmarkModel).getUserBookmarkIdForTab(mMockTab); // Bookmark has price tracking information. @@ -149,7 +146,6 @@ @Test public void priceTrackingNotShownForNonTrackablePages() { - doReturn(JUnitTestGURLs.GOOGLE_URL).when(mMockTab).getUrl(); List<ActionProvider> providers = new ArrayList<>(); PriceTrackingActionProvider provider = new PriceTrackingActionProvider( @@ -158,6 +154,7 @@ SignalAccumulator accumulator = new SignalAccumulator(new Handler(), mMockTab, providers); // URL does not support price tracking. setIsUrlPriceTrackableResult(false); + ProfileManager.setLastUsedProfileForTesting(mProfile); // URL is bookmarked. doReturn(new BookmarkId(1L, 0)).when(mBookmarkModel).getUserBookmarkIdForTab(mMockTab); // Bookmark has no price tracking information. @@ -165,20 +162,4 @@ provider.getAction(mMockTab, accumulator); Assert.assertFalse(accumulator.hasPriceTracking()); } - - @Test - public void priceTrackingNotUsedForNonHttpUrls() { - // Use a non-http(s) url (about:blank). - doReturn(JUnitTestGURLs.ABOUT_BLANK).when(mMockTab).getUrl(); - List<ActionProvider> providers = new ArrayList<>(); - PriceTrackingActionProvider provider = - new PriceTrackingActionProvider( - () -> mShoppingService, () -> mBookmarkModel, () -> mProfile); - providers.add(provider); - SignalAccumulator accumulator = new SignalAccumulator(new Handler(), mMockTab, providers); - provider.getAction(mMockTab, accumulator); - Assert.assertFalse(accumulator.hasPriceTracking()); - // Bookmark model shouldn't be loaded/queried. - verify(mBookmarkModel, never()).finishLoadingBookmarkModel(any()); - } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTest.java index da4ff7a..70d8d7f 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/app/bookmarks/BookmarkTest.java
@@ -94,6 +94,7 @@ import org.chromium.chrome.browser.bookmarks.TestingDelegate; import org.chromium.chrome.browser.commerce.ShoppingFeatures; import org.chromium.chrome.browser.commerce.ShoppingServiceFactory; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.night_mode.ChromeNightModeTestUtils; import org.chromium.chrome.browser.preferences.ChromePreferenceKeys; @@ -141,7 +142,11 @@ /** Tests for the bookmark manager. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) -@DisableFeatures({SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE}) +// TODO(crbug.com/40252540): Disabling the shopping CPA should not be a requirement for these tests. +@DisableFeatures({ + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING, + SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE +}) // TODO(crbug.com/40899175): Investigate batching. @DoNotBatch(reason = "BookmarkTest has behaviours and thus can't be batched.") public class BookmarkTest {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/password_manager/settings/CredentialManagerIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/password_manager/settings/CredentialManagerIntegrationTest.java index 83f9831..40f54a6 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/password_manager/settings/CredentialManagerIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/password_manager/settings/CredentialManagerIntegrationTest.java
@@ -43,6 +43,7 @@ import org.chromium.chrome.browser.sync.SyncTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.R; +import org.chromium.components.signin.identitymanager.ConsentLevel; import org.chromium.ui.test.util.DeviceRestriction; import org.chromium.ui.test.util.GmsCoreVersionRestriction; @@ -107,7 +108,7 @@ DeviceRestriction.RESTRICTION_TYPE_NON_AUTO, GmsCoreVersionRestriction.RESTRICTION_TYPE_VERSION_GE_22W30 }) - public void testUseCredentialManagerFromSafetyCheck() { + public void testUseCredentialManagerFromSafetyCheckForLocal() { mSettingsActivityTestRule.startSettingsActivity(); scrollToSetting(withText(R.string.prefs_safety_check)); onView(withText(R.string.prefs_safety_check)).perform(click()); @@ -119,6 +120,29 @@ assertEquals(0, mFailureCallbackHelper.getCallCount()); } + @Test + @LargeTest + @Restriction({ + DeviceRestriction.RESTRICTION_TYPE_NON_AUTO, + GmsCoreVersionRestriction.RESTRICTION_TYPE_VERSION_GE_22W30 + }) + public void testUseCredentialManagerFromSafetyCheckForAccount() { + mSettingsActivityTestRule.startSettingsActivity(); + scrollToSetting(withText(R.string.prefs_safety_check)); + onView(withText(R.string.prefs_safety_check)).perform(click()); + String testAccount = mSyncTestRule.getPrimaryAccount(ConsentLevel.SYNC).getEmail(); + String checkForAccountText = + ApplicationProvider.getApplicationContext() + .getString(R.string.safety_check_passwords_account_title) + .replace("%1$s", testAccount); + onViewWaiting(withText(checkForAccountText)).perform(click()); + + // Verify that success callback was called. + assertNotNull(mSuccessCallbackHelper.getOnlyPayloadBlocking()); + // Verify that failure callback was not called. + assertEquals(0, mFailureCallbackHelper.getCallCount()); + } + private void scrollToSetting(Matcher<View> matcher) { onView(withId(R.id.recycler_view)) .perform(RecyclerViewActions.scrollTo(hasDescendant(matcher)));
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerCoordinatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerCoordinatorTest.java index 63b17338..b3208fa 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerCoordinatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerCoordinatorTest.java
@@ -58,8 +58,7 @@ }) @EnableFeatures({ SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE, - ChromeFeatureList.ANDROID_IMPROVED_BOOKMARKS, - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS + ChromeFeatureList.ANDROID_IMPROVED_BOOKMARKS }) public class BookmarkManagerCoordinatorTest { @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule();
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediatorTest.java index b4209c1..5f0a061 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/bookmarks/BookmarkManagerMediatorTest.java
@@ -144,8 +144,7 @@ @Config(shadows = {ShadowPostTask.class}) @EnableFeatures({ SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE, - ChromeFeatureList.ANDROID_IMPROVED_BOOKMARKS, - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS + ChromeFeatureList.ANDROID_IMPROVED_BOOKMARKS }) public class BookmarkManagerMediatorTest { private static final GURL EXAMPLE_URL = JUnitTestGURLs.EXAMPLE_URL; @@ -982,10 +981,7 @@ } @Test - @DisableFeatures({ - SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE, - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS - }) + @DisableFeatures(SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE) public void testBuildImprovedBookmarkRow_Folder_Visual() { finishLoading(); mMediator.openFolder(mFolderId1); @@ -1310,10 +1306,7 @@ } @Test - @DisableFeatures({ - SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE, - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS - }) + @DisableFeatures(SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE) public void testParentFolderUpdatedWhenChildDeleted() { finishLoading();
diff --git a/chrome/app/profiles_strings.grdp b/chrome/app/profiles_strings.grdp index bfad910b..8eaa2a4 100644 --- a/chrome/app/profiles_strings.grdp +++ b/chrome/app/profiles_strings.grdp
@@ -113,6 +113,9 @@ <message name="IDS_PROFILES_SIGNIN_PROMO" desc="Text describing the benefits of signing in."> Sign in to get your bookmarks, history, passwords, and other settings on all your devices. </message> + <message name="IDS_PROFILES_VERIFY_ACCOUNT_BUTTON" desc="The label of the button that is shown when the user is in a Signin paused state. When the user clicks this button, they will be prompted to enter their Google Account credentials."> + Verify it’s you + </message> <message name="IDS_PROFILES_CREDIT_CARDS_LINK" desc="Text of the menu item leading to the list of saved credit cards."> Payment methods </message>
diff --git a/chrome/app/profiles_strings_grdp/IDS_PROFILES_VERIFY_ACCOUNT_BUTTON.png.sha1 b/chrome/app/profiles_strings_grdp/IDS_PROFILES_VERIFY_ACCOUNT_BUTTON.png.sha1 new file mode 100644 index 0000000..48da7b7 --- /dev/null +++ b/chrome/app/profiles_strings_grdp/IDS_PROFILES_VERIFY_ACCOUNT_BUTTON.png.sha1
@@ -0,0 +1 @@ +02f49292c5814362ecac5e2cf409c2b218664caa \ No newline at end of file
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 895e4e0..f062005 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -57,9 +57,6 @@ <message name="IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME" desc="Section title for the 'Get the most out of Chrome' page."> Get the most out of Chrome </message> - <message name="IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME_PAGE_BUTTON" desc="Accessibility description for a button navigating the user to the 'Get the most out of Chromne' page."> - Get the most out of Chrome, page - </message> <message name="IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME_BETTER_FOR_YOU" desc="Title of the 'Chrome makes the web work better for you' section of the 'Get the most out of Chrome' page."> Chrome makes the web work better for you </message>
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME_PAGE_BUTTON.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME_PAGE_BUTTON.png.sha1 deleted file mode 100644 index a2adca2..0000000 --- a/chrome/app/settings_strings_grdp/IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME_PAGE_BUTTON.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -ca5efe019b5cc9f98b0526525f648ab4c0c23fa2 \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 74e67f64..d0ffbaad 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1953,8 +1953,6 @@ "privacy_sandbox/tracking_protection_notice_factory.h", "privacy_sandbox/tracking_protection_notice_service.cc", "privacy_sandbox/tracking_protection_notice_service.h", - "search_engine_choice/search_engine_choice_client_side_trial.cc", - "search_engine_choice/search_engine_choice_client_side_trial.h", "search_engine_choice/search_engine_choice_dialog_service.cc", "search_engine_choice/search_engine_choice_dialog_service.h", "search_engine_choice/search_engine_choice_dialog_service_factory.cc", @@ -2284,6 +2282,7 @@ "//components/handoff", "//components/headless/select_file_dialog", "//components/heap_profiling/in_process", + "//components/heap_profiling/in_process:mojom", "//components/heavy_ad_intervention", "//components/history/content/browser", "//components/history/core/browser",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 196f7fb..03a96db 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -704,6 +704,24 @@ {"Disable UI", kContextualPageActions_DisableUi}, }; +const FeatureEntry::FeatureVariation + kContextualPageActionPriceTrackingVariations[] = { + {"Quiet", kContextualPageActionsUiParams_Quiet, + std::size(kContextualPageActionsUiParams_Quiet), nullptr}, + {"Action Chip", kContextualPageActionsUiParams_ActionChip, + std::size(kContextualPageActionsUiParams_ActionChip), nullptr}, + {"Action Chip - 6s", kContextualPageActionsUiParams_ActionChip_6s, + std::size(kContextualPageActionsUiParams_ActionChip_6s), nullptr}, + {"Action Chip - Alternative Color", + kContextualPageActionsUiParams_ActionChip_AltColor, + std::size(kContextualPageActionsUiParams_ActionChip_AltColor), + nullptr}, + {"Action Chip - Alternative Color - 6s", + kContextualPageActionsUiParams_ActionChip_AltColor_6s, + std::size(kContextualPageActionsUiParams_ActionChip_AltColor_6s), + nullptr}, +}; + const FeatureEntry::FeatureParam kContextualPageActionReaderMode_ActionChip_NotRateLimited[] = { {"action_chip", "true"}, @@ -4690,6 +4708,14 @@ segmentation_platform::features::kContextualPageActions, kContextualPageActionsVariations, "ContextualPageActions")}, + {"contextual-page-actions-with-price-tracking", + flag_descriptions::kContextualPageActionsPriceTrackingName, + flag_descriptions::kContextualPageActionsPriceTrackingDescription, + kOsAndroid, + FEATURE_WITH_PARAMS_VALUE_TYPE( + segmentation_platform::features::kContextualPageActionPriceTracking, + kContextualPageActionPriceTrackingVariations, + "ContextualPageActionPriceTracking")}, {"contextual-page-actions-reader-mode", flag_descriptions::kContextualPageActionsReaderModeName, flag_descriptions::kContextualPageActionsReaderModeDescription, kOsAndroid, @@ -11212,6 +11238,12 @@ FEATURE_VALUE_TYPE( password_manager::features::kShowWebauthnSuggestionsOnAutofocus)}, +#if BUILDFLAG(IS_ANDROID) + {"fetch-gaia-hash-on-sign-in", + flag_descriptions::kFetchGaiaHashOnSignInName, + flag_descriptions::kFetchGaiaHashOnSignInDescription, kOsAndroid, + FEATURE_VALUE_TYPE(password_manager::features::kFetchGaiaHashOnSignIn)}, +#endif // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/apps/guest_view/web_view_browsertest.cc b/chrome/browser/apps/guest_view/web_view_browsertest.cc index 655b897..734a581 100644 --- a/chrome/browser/apps/guest_view/web_view_browsertest.cc +++ b/chrome/browser/apps/guest_view/web_view_browsertest.cc
@@ -4767,8 +4767,7 @@ auto* process_map = extensions::ProcessMap::Get(guest->GetBrowserContext()); auto* guest_process = guest->GetProcess(); EXPECT_FALSE(process_map->Contains(guest_process->GetID())); - EXPECT_TRUE( - process_map->GetExtensionsInProcess(guest_process->GetID()).empty()); + EXPECT_FALSE(process_map->GetExtensionIdForProcess(guest_process->GetID())); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser()->profile()); @@ -6158,8 +6157,8 @@ // APIs. auto* process_map = extensions::ProcessMap::Get(guest->GetBrowserContext()); EXPECT_FALSE(process_map->Contains(guest->GetProcess()->GetID())); - EXPECT_TRUE(process_map->GetExtensionsInProcess(guest->GetProcess()->GetID()) - .empty()); + EXPECT_FALSE( + process_map->GetExtensionIdForProcess(guest->GetProcess()->GetID())); EXPECT_EQ(false, content::EvalJs(guest, "!!chrome.webstorePrivate")); EXPECT_EQ(false, content::EvalJs(guest, "!!chrome.dashboardPrivate")); }
diff --git a/chrome/browser/ash/accessibility/accessibility_manager_browsertest.cc b/chrome/browser/ash/accessibility/accessibility_manager_browsertest.cc index 07261b3..dda9c0b 100644 --- a/chrome/browser/ash/accessibility/accessibility_manager_browsertest.cc +++ b/chrome/browser/ash/accessibility/accessibility_manager_browsertest.cc
@@ -1877,8 +1877,8 @@ guest_session_ = std::make_unique<GuestSessionMixin>(&mixin_host_); } else if (GetParam() == user_manager::UserType::kChild) { logged_in_user_mixin_ = std::make_unique<LoggedInUserMixin>( - &mixin_host_, LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), this); + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kChild); } }
diff --git a/chrome/browser/ash/app_mode/kiosk_app_launch_error.cc b/chrome/browser/ash/app_mode/kiosk_app_launch_error.cc index 6bb8ebe5..1e1cdc6 100644 --- a/chrome/browser/ash/app_mode/kiosk_app_launch_error.cc +++ b/chrome/browser/ash/app_mode/kiosk_app_launch_error.cc
@@ -4,8 +4,13 @@ #include "chrome/browser/ash/app_mode/kiosk_app_launch_error.h" +#include <optional> +#include <string> + #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" +#include "base/notreached.h" +#include "base/values.h" #include "chrome/browser/ash/app_mode/kiosk_chrome_app_manager.h" #include "chrome/browser/browser_process.h" #include "chrome/grit/generated_resources.h" @@ -40,6 +45,8 @@ case Error::kPolicyLoadFailed: case Error::kArcAuthFailed: case Error::kUserNotAllowlisted: + case Error::kLacrosDataMigrationStarted: + case Error::kLacrosBackwardDataMigrationStarted: return l10n_util::GetStringUTF8(IDS_KIOSK_APP_FAILED_TO_LAUNCH); case Error::kCryptohomedNotRunning:
diff --git a/chrome/browser/ash/app_mode/kiosk_app_launch_error.h b/chrome/browser/ash/app_mode/kiosk_app_launch_error.h index 5df667b..5794776 100644 --- a/chrome/browser/ash/app_mode/kiosk_app_launch_error.h +++ b/chrome/browser/ash/app_mode/kiosk_app_launch_error.h
@@ -36,8 +36,10 @@ // force-installed extensions. kExtensionsPolicyInvalid = 15, // The policy value of ExtensionInstallForcelist is invalid. - kUserNotAllowlisted = 16, // LoginPerformer disallowed this user. - kMaxValue = kUserNotAllowlisted, // Max value of errors. + kUserNotAllowlisted = 16, // LoginPerformer disallowed this user. + kLacrosDataMigrationStarted = 17, + kLacrosBackwardDataMigrationStarted = 18, + kMaxValue = kLacrosBackwardDataMigrationStarted, // Max value of errors. }; // Returns a message for given `error`.
diff --git a/chrome/browser/ash/child_accounts/child_user_interactive_base_test.h b/chrome/browser/ash/child_accounts/child_user_interactive_base_test.h index 45ccec5d..226b9942 100644 --- a/chrome/browser/ash/child_accounts/child_user_interactive_base_test.h +++ b/chrome/browser/ash/child_accounts/child_user_interactive_base_test.h
@@ -26,9 +26,9 @@ void SetUpOnMainThread() override; protected: - LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, - LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), this}; + LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, + embedded_test_server(), + LoggedInUserMixin::LogInType::kChild}; }; } // namespace ash
diff --git a/chrome/browser/ash/child_accounts/family_user_device_metrics_browsertest.cc b/chrome/browser/ash/child_accounts/family_user_device_metrics_browsertest.cc index d4f19821..5ef3260 100644 --- a/chrome/browser/ash/child_accounts/family_user_device_metrics_browsertest.cc +++ b/chrome/browser/ash/child_accounts/family_user_device_metrics_browsertest.cc
@@ -49,13 +49,7 @@ raw_ptr<FakeChromeUserManager, DanglingUntriaged> user_manager_ = nullptr; LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, - GetLogInType(), - embedded_test_server(), - this, - /*should_launch_browser=*/false, - /*account_id=*/std::nullopt, - /*auth_config=*/std::nullopt, + &mixin_host_, /*test_base=*/this, embedded_test_server(), GetLogInType(), /*include_initial_user=*/IsUserExisting()}; // MixinBasedInProcessBrowserTest: @@ -96,7 +90,8 @@ // Set the device owner to the logged in user. user_manager_->SetOwnerId(logged_in_user_mixin_.GetAccountId()); - logged_in_user_mixin_.LogInUser(); + logged_in_user_mixin_.LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kNoBrowserLaunch}); histogram_tester.ExpectUniqueSample( FamilyUserDeviceMetrics::GetDeviceOwnerHistogramNameForTest(), @@ -111,7 +106,8 @@ // Set the device owner to an arbitrary account that's not logged in. user_manager_->SetOwnerId(kDefaultOwnerAccountId); - logged_in_user_mixin_.LogInUser(); + logged_in_user_mixin_.LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kNoBrowserLaunch}); histogram_tester.ExpectUniqueSample( FamilyUserDeviceMetrics::GetDeviceOwnerHistogramNameForTest(), @@ -121,7 +117,8 @@ IN_PROC_BROWSER_TEST_P(FamilyUserDeviceMetricsTest, SingleUserAdded) { base::HistogramTester histogram_tester; - logged_in_user_mixin_.LogInUser(); + logged_in_user_mixin_.LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kNoBrowserLaunch}); if (IsUserExisting()) { // This user has signed into this device before, so they are not new. @@ -145,7 +142,8 @@ } base::HistogramTester histogram_tester; - logged_in_user_mixin_.LogInUser(); + logged_in_user_mixin_.LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kNoBrowserLaunch}); // Current user + extra user from setup. const int gaia_users_count = 2; @@ -246,7 +244,7 @@ , FamilyUserDeviceMetricsTest, testing::Combine(testing::Values(LoggedInUserMixin::LogInType::kChild, - LoggedInUserMixin::LogInType::kRegular), + LoggedInUserMixin::LogInType::kConsumer), /*IsUserExisting=*/testing::Bool())); class FamilyUserDeviceMetricsManagedDeviceTest @@ -341,7 +339,7 @@ , FamilyUserDeviceMetricsManagedDeviceTest, testing::Combine(testing::Values(LoggedInUserMixin::LogInType::kChild, - LoggedInUserMixin::LogInType::kRegular), + LoggedInUserMixin::LogInType::kConsumer), /*IsUserExisting=*/testing::Bool())); class FamilyUserDeviceMetricsEphemeralUserTest @@ -375,7 +373,7 @@ , FamilyUserDeviceMetricsEphemeralUserTest, testing::Combine(testing::Values(LoggedInUserMixin::LogInType::kChild, - LoggedInUserMixin::LogInType::kRegular), + LoggedInUserMixin::LogInType::kConsumer), /*IsUserExisting=*/testing::Values(false))); } // namespace ash
diff --git a/chrome/browser/ash/child_accounts/parent_access_code/parent_access_service_browsertest.cc b/chrome/browser/ash/child_accounts/parent_access_code/parent_access_service_browsertest.cc index 87a37c7..fdc65cc 100644 --- a/chrome/browser/ash/child_accounts/parent_access_code/parent_access_service_browsertest.cc +++ b/chrome/browser/ash/child_accounts/parent_access_code/parent_access_service_browsertest.cc
@@ -127,14 +127,9 @@ } AccessCodeValues test_values_; - LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, - LoggedInUserMixin::LogInType::kChild, + LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, embedded_test_server(), - this, - true /*should_launch_browser*/, - std::nullopt /*account_id*/, - std::nullopt /*auth_config*/, - true /*include_initial_user*/}; + LoggedInUserMixin::LogInType::kChild}; std::unique_ptr<TestParentAccessServiceObserver> test_observer_; };
diff --git a/chrome/browser/ash/child_accounts/screen_time_controller_browsertest.cc b/chrome/browser/ash/child_accounts/screen_time_controller_browsertest.cc index f548151..e2cfee91 100644 --- a/chrome/browser/ash/child_accounts/screen_time_controller_browsertest.cc +++ b/chrome/browser/ash/child_accounts/screen_time_controller_browsertest.cc
@@ -143,14 +143,9 @@ raw_ptr<Profile, DanglingUntriaged> child_profile_ = nullptr; private: - LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, - LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), - this, - /*should_launch_browser=*/true, - /*account_id=*/std::nullopt, - /*auth_config=*/std::nullopt, - /*include_initial_user=*/false}; + LoggedInUserMixin logged_in_user_mixin_{ + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kChild, /*include_initial_user=*/false}; }; // Tests a simple lock override.
diff --git a/chrome/browser/ash/child_accounts/time_limits/app_time_browsertest.cc b/chrome/browser/ash/child_accounts/time_limits/app_time_browsertest.cc index c7b07bfac..a0f8270 100644 --- a/chrome/browser/ash/child_accounts/time_limits/app_time_browsertest.cc +++ b/chrome/browser/ash/child_accounts/time_limits/app_time_browsertest.cc
@@ -171,9 +171,9 @@ return profile; } - LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, - LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), this}; + LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, + embedded_test_server(), + LoggedInUserMixin::LogInType::kChild}; raw_ptr<ArcAppListPrefs, DanglingUntriaged> arc_app_list_prefs_ = nullptr; std::unique_ptr<arc::FakeAppInstance> arc_app_instance_;
diff --git a/chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.cc b/chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.cc index c962ee8..a1fdfac 100644 --- a/chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.cc +++ b/chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.h" +#include "base/containers/map_util.h" #include "base/functional/bind.h" #include "base/strings/utf_string_conversions.h" #include "base/task/thread_pool.h" @@ -103,7 +104,7 @@ proc_mem_info_list.push_back(std::move(proc_mem_info_mojom)); // We push back to a map that we can use to complete filling out // various information such as extensions - proc_mem_info_map_[proc_mem_info.pid] = &proc_mem_info_list.back(); + proc_mem_info_map_[proc_mem_info.pid] = proc_mem_info_list.back().get(); } proc_data_list_.push_back( mojom::ProcessData::New(base::UTF16ToUTF8(proc_data.name), @@ -121,40 +122,23 @@ !it.IsAtEnd(); it.Advance()) { content::RenderProcessHost* host = it.GetCurrentValue(); // Only add valid processes - if (!host->GetProcess().IsValid()) - continue; - - // Check if process was added in current list - auto entry = proc_mem_info_map_.find(host->GetProcess().Pid()); - - if (entry == proc_mem_info_map_.end()) { + if (!host->GetProcess().IsValid()) { continue; } - auto& proc_mem_info = *entry->second; - content::BrowserContext* browser_context = host->GetBrowserContext(); - extensions::ProcessMap* extension_process_map = - extensions::ProcessMap::Get(browser_context); - - std::set<std::string> extension_ids = - extension_process_map->GetExtensionsInProcess(host->GetID()); + // Check if process was added in current list + auto* proc_mem_info = + base::FindPtrOrNull(proc_mem_info_map_, host->GetProcess().Pid()); + if (!proc_mem_info) { + continue; + } // If no extension can be found in this process then no more work is // needed - if (extension_ids.empty()) { - continue; - } - - extensions::ExtensionRegistry* extension_registry = - extensions::ExtensionRegistry::Get(browser_context); - - auto& ext_data = proc_mem_info->extension_info; - ext_data.reserve(extension_ids.size()); - - for (const extensions::ExtensionId& id : extension_ids) { - const extensions::Extension* extension = - extension_registry->enabled_extensions().GetByID(id); - ext_data.push_back(mojom::ExtensionData::New( + if (const extensions::Extension* extension = + extensions::ProcessMap::Get(host->GetBrowserContext()) + ->GetEnabledExtensionByProcessID(host->GetID())) { + proc_mem_info->extension_info.push_back(mojom::ExtensionData::New( extension->name(), extension->GetVersionForDisplay(), extension->id(), extension->hashed_id().value(), extension->description())); }
diff --git a/chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.h b/chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.h index 6e244ff..73ad71c 100644 --- a/chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.h +++ b/chrome/browser/ash/chromebox_for_meetings/browser/cfm_memory_details.h
@@ -36,7 +36,7 @@ base::GraphicsMemoryInfoKB gpu_meminfo_; std::vector<chromeos::cfm::mojom::ProcessDataPtr> proc_data_list_; - std::map<base::ProcessId, chromeos::cfm::mojom::ProcessMemoryInformationPtr*> + std::map<base::ProcessId, chromeos::cfm::mojom::ProcessMemoryInformation*> proc_mem_info_map_; chromeos::cfm::mojom::CfmBrowser::GetMemoryDetailsCallback callback_; };
diff --git a/chrome/browser/ash/eol_notification_browsertest.cc b/chrome/browser/ash/eol_notification_browsertest.cc index 1adf698..3ff9779 100644 --- a/chrome/browser/ash/eol_notification_browsertest.cc +++ b/chrome/browser/ash/eol_notification_browsertest.cc
@@ -332,8 +332,8 @@ NotificationDisplayServiceMixin notifications_mixin_{&mixin_host_}; ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kConsumer}; private: base::test::ScopedFeatureList scoped_feature_list_; @@ -366,13 +366,8 @@ ash::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, - LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), - this, - /*should_launch_browser=*/true, - AccountId::FromUserEmailGaiaId(policy::PolicyBuilder::kFakeUsername, - policy::PolicyBuilder::kFakeGaiaId)}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kManaged}; private: base::test::ScopedFeatureList scoped_feature_list_; @@ -402,15 +397,8 @@ NotificationDisplayServiceMixin notifications_mixin_{&mixin_host_}; ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, - LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), - this, - /*should_launch_browser=*/true, - /*account_id=*/std::nullopt, - /*auth_config=*/std::nullopt, - /*include_initial_user=*/true, - /*use_embedded_policy_server=*/false}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kChild}; private: base::test::ScopedFeatureList scoped_feature_list_; @@ -438,8 +426,8 @@ EolStatusMixin eol_status_mixin_{&mixin_host_}; NotificationDisplayServiceMixin notifications_mixin_{&mixin_host_}; ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kConsumer}; private: base::test::ScopedFeatureList scoped_feature_list_;
diff --git a/chrome/browser/ash/file_manager/file_manager_browsertest.cc b/chrome/browser/ash/file_manager/file_manager_browsertest.cc index 0b5095e..0d6cc46 100644 --- a/chrome/browser/ash/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/ash/file_manager/file_manager_browsertest.cc
@@ -116,8 +116,9 @@ &mixin_host_, DeviceStateFor(GetOptions().device_mode)); logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( - &mixin_host_, LogInTypeFor(GetOptions().test_account_type), - embedded_test_server(), this, /*should_launch_browser=*/false, + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LogInTypeFor(GetOptions().test_account_type), + /*include_initial_user=*/true, AccountIdFor(GetOptions().test_account_type)); // Set up owner email of a device. We set up owner email only if a device is @@ -145,7 +146,8 @@ } void SetUpOnMainThread() override { - logged_in_user_mixin_->LogInUser(); + logged_in_user_mixin_->LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kNoBrowserLaunch}); FilesAppBrowserTest::SetUpOnMainThread(); }
diff --git a/chrome/browser/ash/file_manager/file_manager_browsertest_base.cc b/chrome/browser/ash/file_manager/file_manager_browsertest_base.cc index 7ecafe25..a52127f 100644 --- a/chrome/browser/ash/file_manager/file_manager_browsertest_base.cc +++ b/chrome/browser/ash/file_manager/file_manager_browsertest_base.cc
@@ -1008,12 +1008,12 @@ base::ImmediateCrash(); case kEnterprise: case kGoogler: - return ash::LoggedInUserMixin::LogInType::kRegular; + return ash::LoggedInUserMixin::LogInType::kManaged; case kChild: return ash::LoggedInUserMixin::LogInType::kChild; case kNonManaged: case kNonManagedNonOwner: - return ash::LoggedInUserMixin::LogInType::kRegular; + return ash::LoggedInUserMixin::LogInType::kConsumer; } } @@ -1024,14 +1024,11 @@ "LoggedInUserFilesAppBrowserTest"; // `base::ImmediateCrash` is necessary for https://crbug.com/1061742. base::ImmediateCrash(); - case kEnterprise: - return AccountId::FromUserEmailGaiaId( - FakeGaiaMixin::kEnterpriseUser1, - FakeGaiaMixin::kEnterpriseUser1GaiaId); case kGoogler: return AccountId::FromUserEmailGaiaId( "user@google.com", FakeGaiaMixin::kEnterpriseUser1GaiaId); case kChild: + case kEnterprise: case kNonManaged: case kNonManagedNonOwner: // Use the default account provided by `LoggedInUserMixin`.
diff --git a/chrome/browser/ash/file_manager/file_tasks_browsertest.cc b/chrome/browser/ash/file_manager/file_tasks_browsertest.cc index 21c97e3..590f8e9 100644 --- a/chrome/browser/ash/file_manager/file_tasks_browsertest.cc +++ b/chrome/browser/ash/file_manager/file_tasks_browsertest.cc
@@ -984,8 +984,8 @@ std::optional<AccountId> account_id = AccountIdFor(test_account_type); logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( - &mixin_host_, log_in_type, embedded_test_server(), this, - /*should_launch_browser=*/true, account_id); + &mixin_host_, /*test_base=*/this, embedded_test_server(), log_in_type, + /*include_initial_user=*/true, account_id); } // Launch Files app and wait for it to open.
diff --git a/chrome/browser/ash/login/app_mode/kiosk_launch_controller.cc b/chrome/browser/ash/login/app_mode/kiosk_launch_controller.cc index 246f3af..6897335 100644 --- a/chrome/browser/ash/login/app_mode/kiosk_launch_controller.cc +++ b/chrome/browser/ash/login/app_mode/kiosk_launch_controller.cc
@@ -301,6 +301,8 @@ CASE(kExtensionsLoadTimeout); CASE(kExtensionsPolicyInvalid); CASE(kUserNotAllowlisted); + CASE(kLacrosDataMigrationStarted); + CASE(kLacrosBackwardDataMigrationStarted); } NOTREACHED_NORETURN(); #undef CASE @@ -486,6 +488,7 @@ user.GetAccountId(), user.username_hash(), crosapi::browser_util::PolicyInitState::kAfterInit)) { LOG(WARNING) << "Restarting chrome to run profile migration."; + OnLaunchFailed(KioskAppLaunchError::Error::kLacrosDataMigrationStarted); return; } @@ -493,6 +496,8 @@ user.GetAccountId(), user.username_hash(), crosapi::browser_util::PolicyInitState::kAfterInit)) { LOG(WARNING) << "Restarting chrome to run backward profile migration."; + OnLaunchFailed( + KioskAppLaunchError::Error::kLacrosBackwardDataMigrationStarted); return; } @@ -607,8 +612,7 @@ void KioskLaunchController::OnTimerFire() { if (app_state_ == AppState::kLaunched) { - CloseSplashScreen(); - ReportSuccess(); + FinishLaunchWithSuccess(); } else if (app_state_ == AppState::kInstalled) { LaunchApp(); } @@ -673,7 +677,15 @@ // Do not save the error because saved errors would stop app from launching // on the next run. std::move(attempt_relaunch_).Run(); - ReportError(error); + FinishLaunchWithError(error); + return; + } + + if (error == KioskAppLaunchError::Error::kLacrosDataMigrationStarted || + error == + KioskAppLaunchError::Error::kLacrosBackwardDataMigrationStarted) { + // The Lacros migration code handles the chrome restart, so nothing to do. + FinishLaunchWithError(error); return; } @@ -686,9 +698,8 @@ // Saves the error and ends the session to go back to login screen. KioskAppLaunchError::Save(error); - CleanUp(); - ReportError(error); std::move(attempt_logout_).Run(); + FinishLaunchWithError(error); } void KioskLaunchController::FinishForcedExtensionsInstall( @@ -749,8 +760,7 @@ if (splash_wait_timer_.IsRunning()) { return; } - CloseSplashScreen(); - ReportSuccess(); + FinishLaunchWithSuccess(); } void KioskLaunchController::OnAppDataUpdated() { @@ -848,11 +858,14 @@ app_launcher_->LaunchApp(); } -void KioskLaunchController::ReportSuccess() { +void KioskLaunchController::FinishLaunchWithSuccess() { + CloseSplashScreen(); std::move(done_callback_).Run(std::nullopt); } -void KioskLaunchController::ReportError(KioskAppLaunchError::Error error) { +void KioskLaunchController::FinishLaunchWithError( + KioskAppLaunchError::Error error) { + CloseSplashScreen(); std::move(done_callback_).Run(error); }
diff --git a/chrome/browser/ash/login/app_mode/kiosk_launch_controller.h b/chrome/browser/ash/login/app_mode/kiosk_launch_controller.h index bf5a16d3..9d09edf 100644 --- a/chrome/browser/ash/login/app_mode/kiosk_launch_controller.h +++ b/chrome/browser/ash/login/app_mode/kiosk_launch_controller.h
@@ -7,13 +7,21 @@ #include <memory> #include <optional> +#include <string> #include "ash/public/cpp/login_accelerators.h" +#include "base/auto_reset.h" +#include "base/functional/callback.h" #include "base/functional/callback_forward.h" +#include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" #include "base/scoped_observation.h" #include "base/time/time.h" +#include "base/timer/timer.h" +#include "chrome/browser/ash/app_mode/cancellable_job.h" +#include "chrome/browser/ash/app_mode/kiosk_app_launch_error.h" #include "chrome/browser/ash/app_mode/kiosk_app_launcher.h" #include "chrome/browser/ash/app_mode/kiosk_app_types.h" #include "chrome/browser/ash/app_mode/kiosk_profile_loader.h" @@ -208,8 +216,8 @@ void CleanUp(); void LaunchApp(); - void ReportSuccess(); - void ReportError(KioskAppLaunchError::Error error); + void FinishLaunchWithSuccess(); + void FinishLaunchWithError(KioskAppLaunchError::Error error); bool auto_launch_ = false; // Whether current app is being auto-launched.
diff --git a/chrome/browser/ash/login/auth_factor_config_browsertest.cc b/chrome/browser/ash/login/auth_factor_config_browsertest.cc index 8c9ce20..c71c7b50 100644 --- a/chrome/browser/ash/login/auth_factor_config_browsertest.cc +++ b/chrome/browser/ash/login/auth_factor_config_browsertest.cc
@@ -46,8 +46,9 @@ } logged_in_user_mixin_ = std::make_unique<LoggedInUserMixin>( - &mixin_host_, LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this, /*should_launch_browser=*/true, + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kConsumer, + /*include_initial_user=*/true, /*account_id=*/std::nullopt, config); cryptohome_ = &logged_in_user_mixin_->GetCryptohomeMixin();
diff --git a/chrome/browser/ash/login/crash_restore_browsertest.cc b/chrome/browser/ash/login/crash_restore_browsertest.cc index d95742d..52aa38f 100644 --- a/chrome/browser/ash/login/crash_restore_browsertest.cc +++ b/chrome/browser/ash/login/crash_restore_browsertest.cc
@@ -283,14 +283,15 @@ MixinBasedInProcessBrowserTest::SetUpInProcessBrowserTestFixture(); } - LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), this, /*should_launch_browser=*/false}; + LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, + embedded_test_server(), + LoggedInUserMixin::LogInType::kChild}; }; IN_PROC_BROWSER_TEST_F(CrashRestoreChildUserTest, PRE_SessionRestore) { // Verify that child user can log in. - logged_in_user_mixin_.LogInUser(); + logged_in_user_mixin_.LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kNoBrowserLaunch}); } IN_PROC_BROWSER_TEST_F(CrashRestoreChildUserTest, SessionRestore) {
diff --git a/chrome/browser/ash/login/demo_mode/demo_session_browsertest.cc b/chrome/browser/ash/login/demo_mode/demo_session_browsertest.cc index 9107cdd..939520e 100644 --- a/chrome/browser/ash/login/demo_mode/demo_session_browsertest.cc +++ b/chrome/browser/ash/login/demo_mode/demo_session_browsertest.cc
@@ -271,7 +271,7 @@ public chromeos::FakePowerManagerClient::Observer { public: DemoSessionLoginTest() { - login_manager_mixin_.set_should_launch_browser(true); + login_manager_mixin_.SetShouldLaunchBrowser(true); BrowserList::AddObserver(this); }
diff --git a/chrome/browser/ash/login/existing_user_controller_browsertest.cc b/chrome/browser/ash/login/existing_user_controller_browsertest.cc index 97eb3232..4ee1989 100644 --- a/chrome/browser/ash/login/existing_user_controller_browsertest.cc +++ b/chrome/browser/ash/login/existing_user_controller_browsertest.cc
@@ -959,7 +959,8 @@ login_manager_mixin_.SkipPostLoginScreens(); auto context = LoginManagerMixin::CreateDefaultUserContext(test_user); - login_manager_mixin_.LoginAndWaitForActiveSession(context); + login_manager_mixin_.LoginAsNewRegularUser(context); + login_manager_mixin_.WaitForActiveSession(); } std::u16string ConstructManagedSessionUserWarning(std::string manager) {
diff --git a/chrome/browser/ash/login/login_ui_browsertest.cc b/chrome/browser/ash/login/login_ui_browsertest.cc index 7e36ec1..951cca9 100644 --- a/chrome/browser/ash/login/login_ui_browsertest.cc +++ b/chrome/browser/ash/login/login_ui_browsertest.cc
@@ -194,7 +194,8 @@ login_manager_mixin_.SkipPostLoginScreens(); auto context = LoginManagerMixin::CreateDefaultUserContext(test_user); - login_manager_mixin_.LoginAndWaitForActiveSession(context); + login_manager_mixin_.LoginAsNewRegularUser(context); + login_manager_mixin_.WaitForActiveSession(); ScreenLockerTester screen_locker_tester; screen_locker_tester.Lock(); @@ -336,7 +337,8 @@ login_manager_mixin_.SkipPostLoginScreens(); auto context = LoginManagerMixin::CreateDefaultUserContext(test_user); - login_manager_mixin_.LoginAndWaitForActiveSession(context); + login_manager_mixin_.LoginAsNewRegularUser(context); + login_manager_mixin_.WaitForActiveSession(); ScreenLockerTester screen_locker_tester; screen_locker_tester.Lock(); @@ -421,16 +423,17 @@ ~UserManagementDisclosureChildTest() override = default; protected: - LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), this, false /*should_launch_browser*/}; + LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, + embedded_test_server(), + LoggedInUserMixin::LogInType::kChild}; }; // Check if the user management disclosure is hidden on the lock screen after // having logged a child account into a session and having locked the screen. IN_PROC_BROWSER_TEST_F(UserManagementDisclosureChildTest, PRE_EnterpriseIconVisibleChildUser) { - logged_in_user_mixin_.LogInUser(); + logged_in_user_mixin_.LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kNoBrowserLaunch}); ScreenLockerTester screen_locker_tester; screen_locker_tester.Lock(); EXPECT_FALSE(LoginScreenTestApi::IsManagedIconShown(
diff --git a/chrome/browser/ash/login/oobe_interactive_ui_test.cc b/chrome/browser/ash/login/oobe_interactive_ui_test.cc index 08360b7..5e37853a 100644 --- a/chrome/browser/ash/login/oobe_interactive_ui_test.cc +++ b/chrome/browser/ash/login/oobe_interactive_ui_test.cc
@@ -1000,7 +1000,7 @@ observer_(std::make_unique<NativeWindowVisibilityObserver>()) { // Prevents Chrome from starting to quit right after login display is // finalized. - login_manager_.set_should_launch_browser(true); + login_manager_.SetShouldLaunchBrowser(true); } ~PublicSessionOobeTest() override = default; @@ -1119,7 +1119,7 @@ public ::testing::WithParamInterface< std::tuple<bool, bool, bool, ArcState>> { public: - EphemeralUserOobeTest() { login_manager_.set_should_launch_browser(true); } + EphemeralUserOobeTest() { login_manager_.SetShouldLaunchBrowser(true); } ~EphemeralUserOobeTest() override = default; // OobeBaseTest:
diff --git a/chrome/browser/ash/login/password_change_browsertest.cc b/chrome/browser/ash/login/password_change_browsertest.cc index f2606e39..4a8b6c1 100644 --- a/chrome/browser/ash/login/password_change_browsertest.cc +++ b/chrome/browser/ash/login/password_change_browsertest.cc
@@ -502,7 +502,7 @@ public: TokenAfterCrash() { login_mixin_.set_session_restore_enabled(); - login_mixin_.set_should_obtain_handles(true); + login_mixin_.SetShouldObtainHandle(true); login_mixin_.AppendRegularUsers(1); }
diff --git a/chrome/browser/ash/login/reporting/lock_unlock_reporter_browsertest.cc b/chrome/browser/ash/login/reporting/lock_unlock_reporter_browsertest.cc index 084fcf2..c613b7d 100644 --- a/chrome/browser/ash/login/reporting/lock_unlock_reporter_browsertest.cc +++ b/chrome/browser/ash/login/reporting/lock_unlock_reporter_browsertest.cc
@@ -82,7 +82,7 @@ } void SetUpOnMainThread() override { - login_manager_mixin_.set_should_launch_browser(true); + login_manager_mixin_.SetShouldLaunchBrowser(true); FakeSessionManagerClient::Get()->set_supports_browser_restart(true); policy::DevicePolicyCrosBrowserTest::SetUpOnMainThread(); }
diff --git a/chrome/browser/ash/login/reporting/login_logout_reporter_browsertest.cc b/chrome/browser/ash/login/reporting/login_logout_reporter_browsertest.cc index 0a70cc62..7169666f 100644 --- a/chrome/browser/ash/login/reporting/login_logout_reporter_browsertest.cc +++ b/chrome/browser/ash/login/reporting/login_logout_reporter_browsertest.cc
@@ -181,7 +181,7 @@ ~LoginLogoutReporterBrowserTest() override = default; void SetUpOnMainThread() override { - login_manager_.set_should_launch_browser(true); + login_manager_.SetShouldLaunchBrowser(true); FakeSessionManagerClient::Get()->set_supports_browser_restart(true); policy::DevicePolicyCrosBrowserTest::SetUpOnMainThread(); }
diff --git a/chrome/browser/ash/login/saml/saml_lockscreen_browsertest.cc b/chrome/browser/ash/login/saml/saml_lockscreen_browsertest.cc index 954b57c4..29b5ec40f 100644 --- a/chrome/browser/ash/login/saml/saml_lockscreen_browsertest.cc +++ b/chrome/browser/ash/login/saml/saml_lockscreen_browsertest.cc
@@ -182,9 +182,8 @@ } void LoginWithoutUpdatingPolicies() { - logged_in_user_mixin_.LogInUser(/*issue_any_scope_token=*/false, - /*wait_for_active_session=*/true, - /*request_policy_update=*/false); + logged_in_user_mixin_.LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kNoPolicyForUser}); PerformPostLoginSetup(); } @@ -213,15 +212,8 @@ private: CryptohomeMixin cryptohome_mixin_{&mixin_host_}; LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, - LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), - /*test_base=*/this, - true /*should_launch_browser*/, - AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kEnterpriseUser1, - FakeGaiaMixin::kEnterpriseUser1GaiaId), - /*auth_config=*/std::nullopt, - true /*include_initial_user*/}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kManaged}; FakeSamlIdpMixin fake_saml_idp_{&mixin_host_, fake_gaia_mixin()}; };
diff --git a/chrome/browser/ash/login/screens/locale_switch_screen.cc b/chrome/browser/ash/login/screens/locale_switch_screen.cc index b800412..f4f03f24 100644 --- a/chrome/browser/ash/login/screens/locale_switch_screen.cc +++ b/chrome/browser/ash/login/screens/locale_switch_screen.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ash/login/screens/locale_switch_screen.h" +#include "ash/constants/ash_features.h" #include "base/containers/contains.h" #include "base/time/time.h" #include "chrome/browser/ash/base/locale_util.h" @@ -17,6 +18,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/ui/webui/ash/login/locale_switch_screen_handler.h" +#include "chromeos/ash/components/osauth/public/auth_session_storage.h" #include "components/language/core/browser/pref_names.h" #include "components/language/core/common/locale_util.h" #include "components/prefs/pref_service.h" @@ -101,6 +103,13 @@ } void LocaleSwitchScreen::ShowImpl() { + if (ash::features::AreLocalPasswordsEnabledForConsumers()) { + if (context()->extra_factors_token) { + session_refresher_ = AuthSessionStorage::Get()->KeepAlive( + context()->extra_factors_token.value()); + } + } + user_manager::User* user = user_manager::UserManager::Get()->GetActiveUser(); DCHECK(user->is_profile_created()); Profile* profile = ProfileHelper::Get()->GetProfileByUser(user); @@ -150,6 +159,7 @@ } void LocaleSwitchScreen::HideImpl() { + session_refresher_.reset(); ResetState(); }
diff --git a/chrome/browser/ash/login/screens/locale_switch_screen.h b/chrome/browser/ash/login/screens/locale_switch_screen.h index 015df7e..9b4468e 100644 --- a/chrome/browser/ash/login/screens/locale_switch_screen.h +++ b/chrome/browser/ash/login/screens/locale_switch_screen.h
@@ -19,6 +19,7 @@ namespace ash { class LocaleSwitchView; +class ScopedSessionRefresher; // This screen waits for account information (locale and account capabilities) // to be fetched and handles OOBE locale switch for the post-login screens. @@ -83,6 +84,9 @@ signin::IdentityManager::Observer> identity_manager_observer_{this}; + // Keeps cryptohome authsession alive. + std::unique_ptr<ScopedSessionRefresher> session_refresher_; + base::OneShotTimer timeout_waiter_; bool refresh_token_loaded_ = false;
diff --git a/chrome/browser/ash/login/screens/management_transition_screen_browsertest.cc b/chrome/browser/ash/login/screens/management_transition_screen_browsertest.cc index f947cf3..fdacaff6 100644 --- a/chrome/browser/ash/login/screens/management_transition_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/management_transition_screen_browsertest.cc
@@ -50,15 +50,12 @@ struct TransitionScreenTestParams { TransitionScreenTestParams(LoggedInUserMixin::LogInType pre_test_user_type, - LoggedInUserMixin::LogInType test_user_type, - bool use_managed_account = false) + LoggedInUserMixin::LogInType test_user_type) : pre_test_user_type(pre_test_user_type), - test_user_type(test_user_type), - use_managed_account(use_managed_account) {} + test_user_type(test_user_type) {} LoggedInUserMixin::LogInType pre_test_user_type; LoggedInUserMixin::LogInType test_user_type; - bool use_managed_account; }; // Param returns the original user type. @@ -94,7 +91,7 @@ MixinBasedInProcessBrowserTest::SetUpOnMainThread(); // Allow ARC by policy for managed users. - if (use_managed_account()) { + if (GetTargetUserType() == LoggedInUserMixin::LogInType::kManaged) { logged_in_user_mixin() .GetUserPolicyMixin() ->RequestPolicyUpdate() @@ -103,14 +100,16 @@ ->set_value(true); } - // For this test class, the PRE tests just happen to always wait for active - // session immediately after logging in, while the main tests do some checks - // and then postpone WaitForActiveSession() until later. So wait for active - // session immediately if IsPreTest() and postpone the call to - // WaitForActiveSession() otherwise. - logged_in_user_mixin_.LogInUser( - false /*issue_any_scope_token*/, - content::IsPreTest() /*wait_for_active_session*/); + // For this test class, the PRE tests just set up necessary state, + // so they follow usual pattern and wait for user session to start. + // Main tests do some checks and then explicitly trigger + // WaitForActiveSession(). + base::flat_set<ash::LoggedInUserMixin::LoginDetails> details( + {ash::LoggedInUserMixin::LoginDetails::kNoBrowserLaunch}); + if (!content::IsPreTest()) { + details.insert(ash::LoggedInUserMixin::LoginDetails::kDontWaitForSession); + } + logged_in_user_mixin_.LogInUser(details); } LoggedInUserMixin::LogInType GetTargetUserType() const { @@ -122,18 +121,6 @@ return GetTargetUserType() == LoggedInUserMixin::LogInType::kChild; } - bool use_managed_account() { return GetParam().use_managed_account; } - - std::optional<AccountId> GetAccountId() { - if (use_managed_account()) { - return AccountId::FromUserEmailGaiaId( - FakeGaiaMixin::kEnterpriseUser1, - FakeGaiaMixin::kEnterpriseUser1GaiaId); - } - - return std::nullopt; - } - protected: LoggedInUserMixin& logged_in_user_mixin() { return logged_in_user_mixin_; } @@ -141,12 +128,9 @@ DeviceStateMixin device_state_{ &mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_PERMANENTLY_UNOWNED}; - LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, - GetTargetUserType(), + LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, embedded_test_server(), - this, - false /*should_launch_browser*/, - GetAccountId()}; + GetTargetUserType()}; base::test::ScopedFeatureList feature_list_; }; @@ -226,12 +210,11 @@ ManagementTransitionScreenTest, testing::Values( TransitionScreenTestParams(LoggedInUserMixin::LogInType::kChild, - LoggedInUserMixin::LogInType::kRegular), - TransitionScreenTestParams(LoggedInUserMixin::LogInType::kRegular, + LoggedInUserMixin::LogInType::kConsumer), + TransitionScreenTestParams(LoggedInUserMixin::LogInType::kConsumer, LoggedInUserMixin::LogInType::kChild), - TransitionScreenTestParams(LoggedInUserMixin::LogInType::kRegular, - LoggedInUserMixin::LogInType::kRegular, - true /* use_managed_account */))); + TransitionScreenTestParams(LoggedInUserMixin::LogInType::kManaged, + LoggedInUserMixin::LogInType::kManaged))); } // namespace } // namespace ash
diff --git a/chrome/browser/ash/login/screens/osauth/password_selection_screen.cc b/chrome/browser/ash/login/screens/osauth/password_selection_screen.cc index adf06cdd9..c920029 100644 --- a/chrome/browser/ash/login/screens/osauth/password_selection_screen.cc +++ b/chrome/browser/ash/login/screens/osauth/password_selection_screen.cc
@@ -7,7 +7,9 @@ #include <string> #include <utility> +#include "ash/constants/ash_features.h" #include "base/check.h" +#include "base/check_is_test.h" #include "base/functional/bind.h" #include "base/logging.h" #include "base/memory/weak_ptr.h" @@ -76,6 +78,7 @@ PasswordSelectionScreen::~PasswordSelectionScreen() = default; void PasswordSelectionScreen::ShowImpl() { + is_shown_ = true; if (!view_) { return; } @@ -87,6 +90,11 @@ weak_ptr_factory_.GetWeakPtr())); } +void PasswordSelectionScreen::HideImpl() { + BaseOSAuthSetupScreen::HideImpl(); + is_shown_ = false; +} + void PasswordSelectionScreen::OnUserAction(const base::Value::List& args) { const std::string& action_id = args[0].GetString(); if (action_id == kUserActionBack) { @@ -108,6 +116,13 @@ } bool PasswordSelectionScreen::MaybeSkip(WizardContext& wizard_context) { + if (wizard_context.skip_post_login_screens_for_tests && is_shown_) { + CHECK_IS_TEST(); + // WizardController::SkipPostLoginScreensForTesting() can be triggered + // after screen is shown. + exit_callback_.Run(Result::GAIA_PASSWORD_FALLBACK); + return true; + } return false; }
diff --git a/chrome/browser/ash/login/screens/osauth/password_selection_screen.h b/chrome/browser/ash/login/screens/osauth/password_selection_screen.h index b1521ba..d7ad6f3 100644 --- a/chrome/browser/ash/login/screens/osauth/password_selection_screen.h +++ b/chrome/browser/ash/login/screens/osauth/password_selection_screen.h
@@ -54,6 +54,7 @@ protected: // BaseScreen: void ShowImpl() override; + void HideImpl() override; void OnUserAction(const base::Value::List& args) override; bool MaybeSkip(WizardContext& context) override; @@ -67,6 +68,7 @@ // Values obtained from UserContext in `InspectContext` bool has_online_password_ = false; + bool is_shown_ = false; AuthFactorsConfiguration auth_factors_config_; base::WeakPtr<PasswordSelectionScreenView> view_ = nullptr;
diff --git a/chrome/browser/ash/login/screens/osauth/recovery_eligibility_screen.cc b/chrome/browser/ash/login/screens/osauth/recovery_eligibility_screen.cc index 3e016dd..1117242 100644 --- a/chrome/browser/ash/login/screens/osauth/recovery_eligibility_screen.cc +++ b/chrome/browser/ash/login/screens/osauth/recovery_eligibility_screen.cc
@@ -62,10 +62,6 @@ RecoveryEligibilityScreen::~RecoveryEligibilityScreen() = default; bool RecoveryEligibilityScreen::MaybeSkip(WizardContext& wizard_context) { - if (wizard_context.skip_post_login_screens_for_tests) { - exit_callback_.Run(Result::NOT_APPLICABLE); - return true; - } return false; }
diff --git a/chrome/browser/ash/login/screens/osauth/recovery_eligibility_screen_browsertest.cc b/chrome/browser/ash/login/screens/osauth/recovery_eligibility_screen_browsertest.cc index 5f73393..37fb3d5 100644 --- a/chrome/browser/ash/login/screens/osauth/recovery_eligibility_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/osauth/recovery_eligibility_screen_browsertest.cc
@@ -22,10 +22,12 @@ #include "chrome/browser/ash/login/test/oobe_base_test.h" #include "chrome/browser/ash/login/test/oobe_screen_exit_waiter.h" #include "chrome/browser/ash/login/test/oobe_screen_waiter.h" +#include "chrome/browser/ash/login/test/scoped_policy_update.h" #include "chrome/browser/ash/login/test/user_policy_mixin.h" #include "chrome/browser/ash/login/test/wizard_controller_screen_exit_waiter.h" #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ash/login/wizard_controller.h" +#include "chrome/browser/ash/policy/test_support/embedded_policy_test_server_mixin.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" @@ -34,6 +36,8 @@ #include "chrome/test/base/fake_gaia_mixin.h" #include "chromeos/ash/components/cryptohome/constants.h" #include "chromeos/ash/components/osauth/public/auth_session_storage.h" +#include "components/policy/core/common/cloud/test/policy_builder.h" +#include "components/policy/proto/cloud_policy.pb.h" #include "components/prefs/pref_service.h" #include "content/public/test/browser_test.h" #include "testing/gtest/include/gtest/gtest.h" @@ -47,6 +51,10 @@ ~RecoveryEligibilityScreenTest() override = default; void SetUpOnMainThread() override { + // Enable recovery factor support in FUDAC + FakeUserDataAuthClient::TestApi::Get() + ->set_supports_low_entropy_credentials(true); + original_callback_ = GetScreen()->get_exit_callback_for_testing(); GetScreen()->set_exit_callback_for_testing( base::BindRepeating(&RecoveryEligibilityScreenTest::HandleScreenExit, @@ -60,46 +68,17 @@ result_ = std::nullopt; } + virtual void LoginAsUserImpl(bool is_child) = 0; + void LoginAsUser(bool is_child) { // Login, and skip the post login screens. auto* context = LoginDisplayHost::default_host()->GetWizardContextForTesting(); context->skip_post_login_screens_for_tests = true; context->defer_oobe_flow_finished_for_tests = true; - if (is_child) { - // Child users require user policy. Set up an empty one so the user can - // get through login. - ASSERT_TRUE(user_policy_mixin_.RequestPolicyUpdate()); - login_manager_mixin_.LoginAsNewChildUser(); - } else { - login_manager_mixin_.LoginAsNewRegularUser(); - } + LoginAsUserImpl(is_child); WizardControllerExitWaiter(UserCreationView::kScreenId).Wait(); WaitForScreenExit(); - - std::unique_ptr<UserContext> user_context; - user_context = ash::AuthSessionStorage::Get()->BorrowForTests( - FROM_HERE, context->extra_factors_token.value()); - context->extra_factors_token = std::nullopt; - cryptohome_.MarkUserAsExisting(user_context->GetAccountId()); - ContinueScreenExit(); - // Wait until the OOBE flow finishes before we set new values on the wizard - // context. - OobeScreenExitWaiter(UserCreationView::kScreenId).Wait(); - - // Set the values on the wizard context: the `extra_factors_token` - // is available after the previous screens have run regularly, and it holds - // an authenticated auth session. - user_context->ResetAuthSessionIds(); - auto session_ids = cryptohome_.AddSession(user_context->GetAccountId(), - /*authenticated=*/true); - user_context->SetAuthSessionIds(session_ids.first, session_ids.second); - user_context->SetSessionLifetime(base::Time::Now() + - cryptohome::kAuthsessionInitialLifetime); - context->extra_factors_token = - ash::AuthSessionStorage::Get()->Store(std::move(user_context)); - context->skip_post_login_screens_for_tests = false; - result_ = std::nullopt; } RecoveryEligibilityScreen* GetScreen() { @@ -109,9 +88,9 @@ } void WaitForScreenExit() { - if (result_.has_value()) + if (result_.has_value()) { return; - + } base::RunLoop run_loop; screen_exit_callback_ = run_loop.QuitClosure(); run_loop.Run(); @@ -121,21 +100,12 @@ original_callback_.Run(result_.value()); } - void ShowScreen() { - LoginDisplayHost::default_host()->StartWizard( - RecoveryEligibilityView::kScreenId); - WaitForScreenExit(); - } - FakeGaiaMixin fake_gaia_{&mixin_host_}; - UserPolicyMixin user_policy_mixin_{ - &mixin_host_, - AccountId::FromUserEmailGaiaId(test::kTestEmail, test::kTestGaiaId)}; LoginManagerMixin login_manager_mixin_{&mixin_host_, {}, &fake_gaia_}; CryptohomeMixin cryptohome_{&mixin_host_}; std::optional<RecoveryEligibilityScreen::Result> result_; - private: + protected: void HandleScreenExit(RecoveryEligibilityScreen::Result result) { result_ = result; if (screen_exit_callback_) @@ -147,12 +117,55 @@ base::RepeatingClosure screen_exit_callback_; }; +class RecoveryEligibilityScreenConsumerTest + : public RecoveryEligibilityScreenTest { + public: + RecoveryEligibilityScreenConsumerTest() {} + ~RecoveryEligibilityScreenConsumerTest() override = default; + + void LoginAsUserImpl(bool is_child) override { + if (is_child) { + // Child users require user policy. Set up an empty one so the user can + // get through login. + ASSERT_TRUE(user_policy_mixin_.RequestPolicyUpdate()); + login_manager_mixin_.LoginAsNewChildUser(); + } else { + login_manager_mixin_.LoginAsNewRegularUser(); + } + } + + protected: + UserPolicyMixin user_policy_mixin_{ + &mixin_host_, + AccountId::FromUserEmailGaiaId(test::kTestEmail, test::kTestGaiaId)}; +}; + +class RecoveryEligibilityScreenEnterpriseTest + : public RecoveryEligibilityScreenTest { + public: + RecoveryEligibilityScreenEnterpriseTest() {} + ~RecoveryEligibilityScreenEnterpriseTest() override = default; + + void LoginAsUserImpl(bool is_child) override { + CHECK(!is_child); + ASSERT_TRUE(user_policy_mixin_.RequestPolicyUpdate()); + login_manager_mixin_.LoginAsNewEnterpriseUser(); + } + + protected: + EmbeddedPolicyTestServerMixin policy_server_{&mixin_host_}; + UserPolicyMixin user_policy_mixin_{ + &mixin_host_, + AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kEnterpriseUser1, + FakeGaiaMixin::kEnterpriseUser1GaiaId), + &policy_server_}; +}; + // The recovery fields on the context should be set correctly for unmanaged // users. -IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenTest, UnmanagedUser) { +IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenConsumerTest, RegularUser) { LoginAsUser(/*is_child=*/false); - ShowScreen(); EXPECT_TRUE(LoginDisplayHost::default_host() ->GetWizardContextForTesting() ->recovery_setup.ask_about_recovery_consent); @@ -166,15 +179,27 @@ EXPECT_EQ(result_.value(), RecoveryEligibilityScreen::Result::PROCEED); } +// The recovery fields on the context should be set correctly for child users. +IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenConsumerTest, ChildUser) { + LoginAsUser(/*is_child=*/true); + + EXPECT_TRUE(LoginDisplayHost::default_host() + ->GetWizardContextForTesting() + ->recovery_setup.ask_about_recovery_consent); + const bool opt_in = base::FeatureList::IsEnabled( + ash::features::kCryptohomeRecoveryByDefaultForConsumers); + EXPECT_EQ(opt_in, LoginDisplayHost::default_host() + ->GetWizardContextForTesting() + ->recovery_setup.recovery_factor_opted_in); + + ContinueScreenExit(); +} + // The recovery fields on the context should be set correctly for managed users. -IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenTest, +IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenEnterpriseTest, ManagedUserRecoveryDefault) { LoginAsUser(/*is_child=*/false); - ProfileManager::GetActiveUserProfile() - ->GetProfilePolicyConnector() - ->OverrideIsManagedForTesting(/*is_managed=*/true); - ShowScreen(); EXPECT_FALSE(LoginDisplayHost::default_host() ->GetWizardContextForTesting() ->recovery_setup.ask_about_recovery_consent); @@ -191,16 +216,15 @@ } // The recovery fields on the context should be set correctly for managed users. -IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenTest, +IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenEnterpriseTest, ManagedUserRecoveryEnabled) { - LoginAsUser(/*is_child=*/false); - ProfileManager::GetActiveUserProfile() - ->GetProfilePolicyConnector() - ->OverrideIsManagedForTesting(/*is_managed=*/true); - ProfileManager::GetActiveUserProfile()->GetPrefs()->SetBoolean( - ash::prefs::kRecoveryFactorBehavior, true); + user_policy_mixin_.RequestPolicyUpdate() + ->policy_payload() + ->mutable_recoveryfactorbehavior() + ->set_value(true); - ShowScreen(); + LoginAsUser(/*is_child=*/false); + EXPECT_FALSE(LoginDisplayHost::default_host() ->GetWizardContextForTesting() ->recovery_setup.ask_about_recovery_consent); @@ -213,16 +237,15 @@ } // The recovery fields on the context should be set correctly for managed users. -IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenTest, +IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenEnterpriseTest, ManagedUserRecoveryDisabled) { - LoginAsUser(/*is_child=*/false); - ProfileManager::GetActiveUserProfile() - ->GetProfilePolicyConnector() - ->OverrideIsManagedForTesting(/*is_managed=*/true); - ProfileManager::GetActiveUserProfile()->GetPrefs()->SetBoolean( - ash::prefs::kRecoveryFactorBehavior, false); + user_policy_mixin_.RequestPolicyUpdate() + ->policy_payload() + ->mutable_recoveryfactorbehavior() + ->set_value(false); - ShowScreen(); + LoginAsUser(/*is_child=*/false); + EXPECT_FALSE(LoginDisplayHost::default_host() ->GetWizardContextForTesting() ->recovery_setup.ask_about_recovery_consent); @@ -234,20 +257,4 @@ EXPECT_EQ(result_.value(), RecoveryEligibilityScreen::Result::PROCEED); } -// The recovery fields on the context should be set correctly for child users. -IN_PROC_BROWSER_TEST_F(RecoveryEligibilityScreenTest, ChildUser) { - LoginAsUser(/*is_child=*/true); - - ShowScreen(); - EXPECT_TRUE(LoginDisplayHost::default_host() - ->GetWizardContextForTesting() - ->recovery_setup.ask_about_recovery_consent); - const bool opt_in = base::FeatureList::IsEnabled( - ash::features::kCryptohomeRecoveryByDefaultForConsumers); - EXPECT_EQ(opt_in, LoginDisplayHost::default_host() - ->GetWizardContextForTesting() - ->recovery_setup.recovery_factor_opted_in); - - ContinueScreenExit(); -} } // namespace ash
diff --git a/chrome/browser/ash/login/screens/sync_consent_browsertest.cc b/chrome/browser/ash/login/screens/sync_consent_browsertest.cc index 8b42c7c..8aaf8ca 100644 --- a/chrome/browser/ash/login/screens/sync_consent_browsertest.cc +++ b/chrome/browser/ash/login/screens/sync_consent_browsertest.cc
@@ -370,6 +370,11 @@ } IN_PROC_BROWSER_TEST_F(SyncConsentTest, PRE_AbortedSetup) { + if (ash::features::AreLocalPasswordsEnabledForConsumers()) { + // With local passwords feature aborting at this stage would + // trigger user cleanup and remove all user information. + GTEST_SKIP(); + } LoginAndShowSyncConsentScreenWithCapability(); WaitForScreenShown(); test::OobeJS().CreateVisibilityWaiter(true, {kSyncConsent})->Wait(); @@ -377,6 +382,12 @@ } IN_PROC_BROWSER_TEST_F(SyncConsentTest, AbortedSetup) { + if (ash::features::AreLocalPasswordsEnabledForConsumers()) { + // With local passwords feature aborting at this stage would + // trigger user cleanup and remove all user information, + // so this test makes no sense. + GTEST_SKIP(); + } EXPECT_EQ(session_manager::SessionState::LOGIN_PRIMARY, session_manager::SessionManager::Get()->session_state()); Profile* profile = ProfileManager::GetPrimaryUserProfile(); @@ -776,6 +787,9 @@ } IN_PROC_BROWSER_TEST_F(SyncConsentMinorModeTest, PRE_AbortedSetup) { + if (ash::features::AreLocalPasswordsEnabledForConsumers()) { + GTEST_SKIP(); + } LoginAndShowSyncConsentScreenWithCapability(); WaitForScreenShown(); test::OobeJS().CreateVisibilityWaiter(true, {kSyncConsent})->Wait(); @@ -783,6 +797,9 @@ } IN_PROC_BROWSER_TEST_F(SyncConsentMinorModeTest, AbortedSetup) { + if (ash::features::AreLocalPasswordsEnabledForConsumers()) { + GTEST_SKIP(); + } EXPECT_EQ(session_manager::SessionState::LOGIN_PRIMARY, session_manager::SessionManager::Get()->session_state()); Profile* profile = ProfileManager::GetPrimaryUserProfile();
diff --git a/chrome/browser/ash/login/screens/user_selection_screen_browsertest.cc b/chrome/browser/ash/login/screens/user_selection_screen_browsertest.cc index 32d5cf4..5405b556 100644 --- a/chrome/browser/ash/login/screens/user_selection_screen_browsertest.cc +++ b/chrome/browser/ash/login/screens/user_selection_screen_browsertest.cc
@@ -269,8 +269,9 @@ LoginDisplayHost::default_host() ->GetWizardContext() ->defer_oobe_flow_finished_for_tests = true; - login_manager_mixin_.LoginWithDefaultContext( + UserContext user_context = LoginManagerMixin::CreateDefaultUserContext( LoginManagerMixin::TestUserInfo(account_id)); + login_manager_mixin_.LoginAsNewRegularUser(user_context); } void FinishLogin() { LoginDisplayHost::default_host()
diff --git a/chrome/browser/ash/login/session_login_browsertest.cc b/chrome/browser/ash/login/session_login_browsertest.cc index 425602ae..c531ccf1 100644 --- a/chrome/browser/ash/login/session_login_browsertest.cc +++ b/chrome/browser/ash/login/session_login_browsertest.cc
@@ -197,7 +197,9 @@ OobeScreenWaiter(UserCreationView::kScreenId).Wait(); LoginManagerMixin::TestUserInfo test_user(regular_user_); OobeScreenExitWaiter user_creation_exit_waiter(UserCreationView::kScreenId); - login_mixin_.LoginWithDefaultContext(test_user); + UserContext user_context = + LoginManagerMixin::CreateDefaultUserContext(test_user); + login_mixin_.LoginAsNewRegularUser(user_context); user_creation_exit_waiter.Wait(); login_mixin_.SkipPostLoginScreens(); login_mixin_.WaitForActiveSession();
diff --git a/chrome/browser/ash/login/test/logged_in_user_mixin.cc b/chrome/browser/ash/login/test/logged_in_user_mixin.cc index 278d0fbe..71a83a1 100644 --- a/chrome/browser/ash/login/test/logged_in_user_mixin.cc +++ b/chrome/browser/ash/login/test/logged_in_user_mixin.cc
@@ -4,9 +4,11 @@ #include "chrome/browser/ash/login/test/logged_in_user_mixin.h" +#include <initializer_list> #include <optional> #include "base/check.h" +#include "base/containers/flat_set.h" #include "chrome/browser/ash/login/test/cryptohome_mixin.h" #include "chrome/browser/ash/login/test/login_manager_mixin.h" #include "chrome/browser/ash/login/test/user_auth_config.h" @@ -28,11 +30,27 @@ switch (type) { case LoggedInUserMixin::LogInType::kChild: return user_manager::UserType::kChild; - case LoggedInUserMixin::LogInType::kRegular: + case LoggedInUserMixin::LogInType::kConsumer: + case LoggedInUserMixin::LogInType::kConsumerCustomDomain: + case LoggedInUserMixin::LogInType::kManaged: return user_manager::UserType::kRegular; } } +const AccountId AccountIdForType(LoggedInUserMixin::LogInType type) { + switch (type) { + case LoggedInUserMixin::LogInType::kChild: + case LoggedInUserMixin::LogInType::kConsumer: + return AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kFakeUserEmail, + FakeGaiaMixin::kFakeUserGaiaId); + case LoggedInUserMixin::LogInType::kConsumerCustomDomain: + case LoggedInUserMixin::LogInType::kManaged: + return AccountId::FromUserEmailGaiaId( + FakeGaiaMixin::kEnterpriseUser1, + FakeGaiaMixin::kEnterpriseUser1GaiaId); + } +} + std::vector<LoginManagerMixin::TestUserInfo> GetInitialUsers( const LoginManagerMixin::TestUserInfo& user, bool include_initial_user) { @@ -45,18 +63,15 @@ LoggedInUserMixin::LoggedInUserMixin( InProcessBrowserTestMixinHost* mixin_host, - LogInType type, - net::EmbeddedTestServer* embedded_test_server, InProcessBrowserTest* test_base, - bool should_launch_browser, - std::optional<AccountId> account_id, - std::optional<test::UserAuthConfig> auth_config, + net::EmbeddedTestServer* embedded_test_server, + LogInType type, bool include_initial_user, - bool use_embedded_policy_server) + std::optional<AccountId> account_id, + std::optional<test::UserAuthConfig> auth_config) : InProcessBrowserTestMixin(mixin_host), - user_(account_id.value_or( - AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kFakeUserEmail, - FakeGaiaMixin::kFakeUserGaiaId)), + login_type_(type), + user_(account_id.value_or(AccountIdForType(type)), auth_config.value_or( test::UserAuthConfig::Create(test::kDefaultAuthSetup)), ConvertUserType(type)), @@ -67,20 +82,14 @@ GetInitialUsers(user_, include_initial_user), &fake_gaia_, &cryptohome_), - embedded_policy_server_(mixin_host), - user_policy_( - mixin_host, - user_.account_id, - use_embedded_policy_server ? &embedded_policy_server_ : nullptr), + embedded_policy_server_(mixin_host, + {EmbeddedPolicyTestServerMixin::Capabilities:: + PER_USER_MANAGEMENT_STATUS}), + user_policy_(mixin_host, user_.account_id, &embedded_policy_server_), user_policy_helper_(user_.account_id.GetUserEmail(), &embedded_policy_server_), embedded_test_server_setup_(mixin_host, embedded_test_server), - test_base_(test_base) { - // By default, LoginManagerMixin will set up user session manager not to - // launch browser as part of user session setup - use this to override that - // behavior. - login_manager_.set_should_launch_browser(should_launch_browser); -} + test_base_(test_base) {} LoggedInUserMixin::~LoggedInUserMixin() = default; @@ -91,19 +100,29 @@ test_base_->host_resolver()->AddRule("*", "127.0.0.1"); } -void LoggedInUserMixin::LogInUser(bool issue_any_scope_token, - bool wait_for_active_session, - bool request_policy_update, - bool skip_post_login_screens) { - if (skip_post_login_screens) { - // Ensures logging in doesn't hang on the post login Gaia screens. - login_manager_.SkipPostLoginScreens(); +void LoggedInUserMixin::LogInUser( + std::initializer_list<LoggedInUserMixin::LoginDetails> login_details) { + LogInUser(base::flat_set<LoggedInUserMixin::LoginDetails>(login_details)); +} + +void LoggedInUserMixin::LogInUser( + const base::flat_set<LoggedInUserMixin::LoginDetails> const_login_details) { + base::flat_set<LoggedInUserMixin::LoginDetails> login_details( + const_login_details); + if (login_details.contains(LoginDetails::kUserOnboarding)) { + if (!login_details.contains(LoginDetails::kDontWaitForSession)) { + LOG(INFO) << "Implying kDontWaitForSession as test use kUserOnboarding"; + login_details.insert(LoginDetails::kDontWaitForSession); + } } else { - CHECK(!wait_for_active_session) - << "wait_for_active_session must be false if skip_post_login_screen is " - "false as there might not be an active session after a login."; + login_manager_.SkipPostLoginScreens(); } - login_manager_.set_should_wait_for_profile(wait_for_active_session); + login_manager_.SetShouldLaunchBrowser( + !login_details.contains(LoginDetails::kNoBrowserLaunch)); + + login_manager_.set_should_wait_for_profile( + !login_details.contains(LoginDetails::kDontWaitForSession)); + UserContext user_context = LoginManagerMixin::CreateDefaultUserContext(user_); user_context.SetRefreshToken(FakeGaiaMixin::kFakeRefreshToken); if (user_.user_type == user_manager::UserType::kChild) { @@ -112,15 +131,21 @@ fake_gaia_.SetupFakeGaiaForChildUser( user_.account_id.GetUserEmail(), user_.account_id.GetGaiaId(), - FakeGaiaMixin::kFakeRefreshToken, issue_any_scope_token); + FakeGaiaMixin::kFakeRefreshToken, + login_details.contains(LoginDetails::kUseAnyScopeToken)); } else { fake_gaia_.SetupFakeGaiaForLogin(user_.account_id.GetUserEmail(), user_.account_id.GetGaiaId(), FakeGaiaMixin::kFakeRefreshToken); } - if (request_policy_update) { - // Child users require user policy, set up an empty one so the user can get - // through login. + + if (!login_details.contains(LoginDetails::kNoPolicyForUser)) { + if (login_type_ == LogInType::kChild || + login_type_ == LogInType::kManaged) { + embedded_policy_server_.MarkUserAsManaged(user_.account_id); + } + // Managed users require user policy, set up an empty one so the user can + // get through login. GetUserPolicyMixin()->RequestPolicyUpdate(); } if (!include_initial_user_) { @@ -135,7 +160,7 @@ login_manager_.AttemptLoginUsingAuthenticator( user_context, std::make_unique<StubAuthenticatorBuilder>(user_context)); } - if (wait_for_active_session) { + if (!login_details.contains(LoginDetails::kDontWaitForSession)) { login_manager_.WaitForActiveSession(); // If should_launch_browser was set to true, then ensures // InProcessBrowserTest::browser() doesn't return nullptr.
diff --git a/chrome/browser/ash/login/test/logged_in_user_mixin.h b/chrome/browser/ash/login/test/logged_in_user_mixin.h index 7f5763d..847903c 100644 --- a/chrome/browser/ash/login/test/logged_in_user_mixin.h +++ b/chrome/browser/ash/login/test/logged_in_user_mixin.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_ASH_LOGIN_TEST_LOGGED_IN_USER_MIXIN_H_ #define CHROME_BROWSER_ASH_LOGIN_TEST_LOGGED_IN_USER_MIXIN_H_ +#include <initializer_list> #include <optional> #include "base/memory/raw_ptr.h" @@ -28,10 +29,9 @@ namespace ash { -// Compound mixin class for easily logging in as regular or child accounts for -// browser tests. Initiates other mixins required to log in users, sets up their -// user policies and gaia auth. -// To use: +// Compound mixin class for easily logging in as regular, managed or child +// accounts for browser tests. Initiates other mixins required to log in users, +// sets up their user policies and gaia auth. To use: // * Make your browser test class inherit from MixinBasedInProcessBrowserTest. // * Instantiate this class while passing in the inherited mixin_host_ member to // the constructor. @@ -57,41 +57,65 @@ */ class LoggedInUserMixin : public InProcessBrowserTestMixin { public: - enum class LogInType { kRegular, kChild }; + enum class LogInType { + // Regular consumer user, default account id at gmail.com. + kConsumer, + // Regular consumer user, default account id at custom domain, not managed. + kConsumerCustomDomain, + // Child consumer user, default account id at gmail.com, managed. + kChild, + // Enterprise managed user, default account id at custom domain, managed. + kManaged, + }; + + // Flags for fine-tuning login flow in some edge cases. + enum class LoginDetails { + // Prevents browser launch after successful login. + kNoBrowserLaunch, + // FakeGaiaMixin will issue a special all-access + // token associated with the test refresh token. Only matters for child + // login. + kUseAnyScopeToken, + // Without this LoginManagerMixin will wait for the session + // state to change to ACTIVE after logging in. Use if some errors + // are expected during login, or if user expected to go through + // onboarding after login. + kDontWaitForSession, + // This can be used by policy-related test to set up + // situations when policy can not be fetched for the user. + kNoPolicyForUser, + // By default mixin would skip onboarding in OOBE even for + // new users. This can be used to prevent that and + // let test interact with respective UIs. + // Implies `kDontWaitForSession`. + kUserOnboarding, + }; // `mixin_host` coordinates the other mixins. Since your browser test class // inherits from MixinBasedInProcessBrowserTest, there is an inherited + // `test_base`: just pass in a pointer to the browser test class. // mixin_host_ member that can be passed into this constructor. - // `type` specifies the desired user log in type, currently either regular or - // child. // `embedded_test_server`: your browser test class should already inherit from // BrowserTestBase. That means there is an inherited embedded_test_server() // that can be passed into this constructor. - // `test_base`: just pass in a pointer to the browser test class. - // `should_launch_browser` determines whether a browser instance is launched - // after successful login. - // `account_id` is the desired test account id for logging in. The default - // test account already works for the majority of test cases, unless an - // enterprise account is needed for setting up policy. - // `auth_config` defines the factors set up for the user. The default user will - // have the (gaia) password set to `ash::test:kGaiaPassword`. This parameter - // allows tests to define more complex configurations if needed. + // `type` specifies the desired user log in type, see `LogInType` above. // `include_initial_user` if true, then the user already exists on the login // screen. Otherwise, the user is newly added to the device and the OOBE Gaia // screen will show on start-up. - // `use_embedded_policy_server` determines if the - // EmbeddedPolicyTestServerMixin should be passed into the UserPolicyMixin. + // `account_id` is the desired test account id for logging in. The default + // test account already works for the majority of test cases, unless an + // enterprise account is needed for setting up policy. + // `auth_config` defines the factors set up for the user. The default user + // will have the (gaia) password set to `ash::test:kGaiaPassword`. This + // parameter allows tests to define more complex configurations if needed. LoggedInUserMixin( InProcessBrowserTestMixinHost* mixin_host, - LogInType type, - net::EmbeddedTestServer* embedded_test_server, InProcessBrowserTest* test_base, - bool should_launch_browser = true, - std::optional<AccountId> account_id = std::nullopt, - std::optional<test::UserAuthConfig> auth_config = std::nullopt, + net::EmbeddedTestServer* embedded_test_server, + LogInType type, bool include_initial_user = true, - // TODO(crbug/1112885): Remove this parameter. - bool use_embedded_policy_server = true); + std::optional<AccountId> account_id = std::nullopt, + std::optional<test::UserAuthConfig> auth_config = std::nullopt); LoggedInUserMixin(const LoggedInUserMixin&) = delete; LoggedInUserMixin& operator=(const LoggedInUserMixin&) = delete; ~LoggedInUserMixin() override; @@ -110,10 +134,8 @@ // screens. Default value is true (skip). Note that `wait_for_active_session` // must be false if this value is false as there won't be no active session // immediately after login. - void LogInUser(bool issue_any_scope_token = false, - bool wait_for_active_session = true, - bool request_policy_update = true, - bool skip_post_login_screens = true); + void LogInUser(std::initializer_list<LoginDetails> login_details = {}); + void LogInUser(base::flat_set<LoginDetails> login_details); LoginManagerMixin* GetLoginManagerMixin() { return &login_manager_; } @@ -134,6 +156,7 @@ FakeGaiaMixin* GetFakeGaiaMixin() { return &fake_gaia_; } private: + LogInType login_type_; LoginManagerMixin::TestUserInfo user_; bool include_initial_user_; FakeGaiaMixin fake_gaia_;
diff --git a/chrome/browser/ash/login/test/login_manager_mixin.cc b/chrome/browser/ash/login/test/login_manager_mixin.cc index 84381bc..5eb428b3 100644 --- a/chrome/browser/ash/login/test/login_manager_mixin.cc +++ b/chrome/browser/ash/login/test/login_manager_mixin.cc
@@ -206,6 +206,27 @@ should_launch_browser_); session_manager_test_api.SetShouldObtainTokenHandleInTests( should_obtain_handles_); + set_up_on_main_thread_ = true; +} + +void LoginManagerMixin::SetShouldLaunchBrowser(bool value) { + should_launch_browser_ = value; + if (set_up_on_main_thread_) { + test::UserSessionManagerTestApi session_manager_test_api( + UserSessionManager::GetInstance()); + session_manager_test_api.SetShouldLaunchBrowserInTests( + should_launch_browser_); + } +} + +void LoginManagerMixin::SetShouldObtainHandle(bool value) { + should_obtain_handles_ = value; + if (set_up_on_main_thread_) { + test::UserSessionManagerTestApi session_manager_test_api( + UserSessionManager::GetInstance()); + session_manager_test_api.SetShouldObtainTokenHandleInTests( + should_obtain_handles_); + } } void LoginManagerMixin::TearDownOnMainThread() { @@ -222,6 +243,19 @@ } } +void LoginManagerMixin::AttemptNewUserLoginUsingFakeDataAuthClient( + const UserContext& user_context) { + if (skip_post_login_screens_ && ash::WizardController::default_controller()) { + ash::WizardController::default_controller() + ->SkipPostLoginScreensForTesting(); + } + ExistingUserController::current_controller()->CompleteLogin(user_context); + if (skip_post_login_screens_ && ash::WizardController::default_controller()) { + ash::WizardController::default_controller() + ->SkipPostLoginScreensForTesting(); + } +} + void LoginManagerMixin::AttemptLoginUsingAuthenticator( const UserContext& user_context, std::unique_ptr<StubAuthenticatorBuilder> authenticator_builder) { @@ -271,8 +305,24 @@ } test::ProfilePreparedWaiter profile_prepared(user_context->GetAccountId()); - AttemptLoginUsingAuthenticator( - *user_context, std::make_unique<StubAuthenticatorBuilder>(*user_context)); + AttemptNewUserLoginUsingFakeDataAuthClient(*user_context); + if (wait_for_profile_) { + profile_prepared.Wait(); + } +} + +void LoginManagerMixin::LoginAsNewEnterpriseUser() { + LoginDisplayHost::default_host()->StartWizard(GaiaView::kScreenId); + test::WaitForOobeJSReady(); + + ASSERT_FALSE(session_manager::SessionManager::Get()->IsSessionStarted()); + UserContext user_context = CreateDefaultUserContext(TestUserInfo( + AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kEnterpriseUser1, + FakeGaiaMixin::kEnterpriseUser1GaiaId))); + user_context.SetRefreshToken(FakeGaiaMixin::kFakeRefreshToken); + + test::ProfilePreparedWaiter profile_prepared(user_context.GetAccountId()); + AttemptNewUserLoginUsingFakeDataAuthClient(user_context); if (wait_for_profile_) { profile_prepared.Wait(); } @@ -296,8 +346,7 @@ test_child_user_.account_id.GetGaiaId(), FakeGaiaMixin::kFakeRefreshToken, false /*issue_any_scope_token*/); test::ProfilePreparedWaiter profile_prepared(user_context.GetAccountId()); - AttemptLoginUsingAuthenticator( - user_context, std::make_unique<StubAuthenticatorBuilder>(user_context)); + AttemptNewUserLoginUsingFakeDataAuthClient(user_context); if (wait_for_profile_) { profile_prepared.Wait(); }
diff --git a/chrome/browser/ash/login/test/login_manager_mixin.h b/chrome/browser/ash/login/test/login_manager_mixin.h index 588bebe..71b097ec 100644 --- a/chrome/browser/ash/login/test/login_manager_mixin.h +++ b/chrome/browser/ash/login/test/login_manager_mixin.h
@@ -116,20 +116,21 @@ // Should be called before mixin SetUp() is called to take effect. void set_session_restore_enabled() { session_restore_enabled_ = true; } - // By default, LoginManagerMixin will set up user session manager not to - // launch browser as part of user session setup - use this to override that - // behavior. - void set_should_launch_browser(bool value) { should_launch_browser_ = value; } // By default, LoginManagerMixin will set wait for successful profile // initialization. If test expects some errors during profile initialization // this gives an option to bypass the wait. void set_should_wait_for_profile(bool value) { wait_for_profile_ = value; } - void set_should_obtain_handles(bool value) { should_obtain_handles_ = value; } - const UserList& users() const { return initial_users_; } + // By default, LoginManagerMixin will set up user session manager not to + // launch browser as part of user session setup - use this to override that + // behavior. + void SetShouldLaunchBrowser(bool value); + + void SetShouldObtainHandle(bool value); + // Sets the list of default policy switches to be added to command line on the // login screen. void SetDefaultLoginSwitches( @@ -151,10 +152,16 @@ std::unique_ptr<StubAuthenticatorBuilder> authenticator_builder); // Starts login attempt for a user, using actual authenticator backed by - // FakeUserDataAuthClient. - // Note that this will not wait for the login attempt to finish. + // FakeUserDataAuthClient. It is assumed that user already exists on the + // device. Note that this will not wait for the login attempt to finish. void AttemptLoginUsingFakeDataAuthClient(const UserContext& user_context); + // Starts login attempt for a user, assuming that user is a new user that have + // just completed GAIA authentication. + // Note that this will not wait for the login attempt to finish. + void AttemptNewUserLoginUsingFakeDataAuthClient( + const UserContext& user_context); + // Waits for the session state to change to ACTIVE. Returns immediately if the // session is already active. void WaitForActiveSession(); @@ -180,7 +187,11 @@ void LoginAsNewRegularUser( std::optional<UserContext> user_context = std::nullopt); - // Logs in as a child user with default user context.Should be used for + // Logs in as an enterprise user with default user context. Should be used + // for proceeding into the session from the login screen. + void LoginAsNewEnterpriseUser(); + + // Logs in as a child user with default user context. Should be used for // proceeding into the session from the login screen. void LoginAsNewChildUser(); @@ -196,6 +207,9 @@ bool session_restore_enabled_ = false; test::SessionFlagsManager session_flags_manager_; + // Whether `SetUpOnMainThread` was already called. + bool set_up_on_main_thread_ = false; + // Whether the user session manager should skip browser launch steps for // testing. bool should_launch_browser_ = false;
diff --git a/chrome/browser/ash/policy/core/user_cloud_policy_manager_ash_browsertest.cc b/chrome/browser/ash/policy/core/user_cloud_policy_manager_ash_browsertest.cc index f95b894..1d69231a 100644 --- a/chrome/browser/ash/policy/core/user_cloud_policy_manager_ash_browsertest.cc +++ b/chrome/browser/ash/policy/core/user_cloud_policy_manager_ash_browsertest.cc
@@ -7,8 +7,8 @@ #include <utility> #include <vector> -#include "ash/components/arc/arc_features.h" #include "ash/components/arc/arc_prefs.h" +#include "base/containers/flat_set.h" #include "base/test/scoped_feature_list.h" #include "base/values.h" #include "chrome/browser/ash/login/test/logged_in_user_mixin.h" @@ -19,9 +19,8 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/chrome_features.h" #include "chrome/test/base/mixin_based_in_process_browser_test.h" -#include "components/policy/policy_constants.h" +#include "components/policy/proto/policy_common_definitions.pb.h" #include "components/prefs/pref_service.h" #include "components/session_manager/core/session_manager.h" #include "components/signin/public/identity_manager/account_managed_status_finder.h" @@ -32,87 +31,144 @@ namespace policy { -class UserCloudPolicyManagerTest - : public MixinBasedInProcessBrowserTest, - public testing::WithParamInterface< - std::tuple<std::vector<base::test::FeatureRef>, - ash::LoggedInUserMixin::LogInType>> { +class UserCloudPolicyManagerTestBase : public MixinBasedInProcessBrowserTest { public: - UserCloudPolicyManagerTest(const UserCloudPolicyManagerTest&) = delete; - UserCloudPolicyManagerTest& operator=(const UserCloudPolicyManagerTest&) = + UserCloudPolicyManagerTestBase(const UserCloudPolicyManagerTestBase&) = delete; + UserCloudPolicyManagerTestBase& operator=( + const UserCloudPolicyManagerTestBase&) = delete; protected: - UserCloudPolicyManagerTest() { + UserCloudPolicyManagerTestBase(ash::LoggedInUserMixin::LogInType login_type, + bool user_existed_before) { + logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( + &mixin_host_, /*test_base=*/this, embedded_test_server(), login_type, + user_existed_before); + // Override default tests configuration that prevents effective testing of // whether start-up URL policy is properly applied: // * InProcessBrowserTest force about://blank start-up URL via command // line (which trumps policy values). set_open_about_blank_on_browser_launch(false); - - scoped_feature_list_.InitWithFeatures( - std::get<0>(GetParam()) /* enabled_features */, - std::vector<base::test::FeatureRef>() /* disabled_features */); } - ~UserCloudPolicyManagerTest() override = default; - - void TearDown() override { - signin::AccountManagedStatusFinder::SetNonEnterpriseDomainForTesting( - nullptr); - MixinBasedInProcessBrowserTest::TearDown(); - } + ~UserCloudPolicyManagerTestBase() override = default; // Sets up fake GAIA for specified user login, and requests login for the user // (using LoggedInUserMixin). void StartUserLogIn(bool wait_for_active_session) { - logged_in_user_mixin_.LogInUser(true /*issue_any_scope_token*/, - wait_for_active_session, - /*request_policy_update=*/false); - } + base::flat_set<ash::LoggedInUserMixin::LoginDetails> details{ + ash::LoggedInUserMixin::LoginDetails::kUseAnyScopeToken, + ash::LoggedInUserMixin::LoginDetails::kNoPolicyForUser}; - protected: - static const AccountId GetTestAccountId() { - if (std::get<1>(GetParam()) == ash::LoggedInUserMixin::LogInType::kChild) { - return AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kFakeUserEmail, - FakeGaiaMixin::kFakeUserGaiaId); - } else { - return AccountId::FromUserEmailGaiaId( - FakeGaiaMixin::kEnterpriseUser1, - FakeGaiaMixin::kEnterpriseUser1GaiaId); + if (!wait_for_active_session) { + details.insert(ash::LoggedInUserMixin::LoginDetails::kDontWaitForSession); } + logged_in_user_mixin_->LogInUser(details); } - ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, std::get<1>(GetParam()) /*type*/, embedded_test_server(), - this, true /*should_launch_browser*/, GetTestAccountId(), - /*auth_config=*/std::nullopt, - // Initializing the login manager with no user will cause GAIA screen to - // be shown on start-up. - false /*include_initial_user*/}; + user_manager::ProfileRequiresPolicy GetProfileRequiresPolicy() { + user_manager::KnownUser known_user(g_browser_process->local_state()); + return known_user.GetProfileRequiresPolicy( + logged_in_user_mixin_->GetAccountId()); + } - private: - base::test::ScopedFeatureList scoped_feature_list_; + void SetProfileRequiresPolicy(user_manager::ProfileRequiresPolicy value) { + user_manager::KnownUser known_user(g_browser_process->local_state()); + known_user.SetProfileRequiresPolicy(logged_in_user_mixin_->GetAccountId(), + value); + } + + std::unique_ptr<ash::LoggedInUserMixin> logged_in_user_mixin_; }; -IN_PROC_BROWSER_TEST_P(UserCloudPolicyManagerTest, StartSession) { - user_manager::KnownUser known_user(g_browser_process->local_state()); +// Test scenarios for enterprise-managed user signing in for the first time. +class UserCloudPolicyManagerNewManagedUserTest + : public UserCloudPolicyManagerTestBase { + protected: + UserCloudPolicyManagerNewManagedUserTest() + : UserCloudPolicyManagerTestBase( + ash::LoggedInUserMixin::LogInType::kManaged, + /*user_existed_before=*/false) {} +}; + +// Test scenarios for consumer user with custom domain signing in for the first +// time. +class UserCloudPolicyManagerNewConsumerUserTest + : public UserCloudPolicyManagerTestBase { + protected: + UserCloudPolicyManagerNewConsumerUserTest() + : UserCloudPolicyManagerTestBase( + ash::LoggedInUserMixin::LogInType::kConsumerCustomDomain, + /*user_existed_before=*/false) {} + + void SetUp() override { + UserCloudPolicyManagerTestBase::SetUp(); + // Recognize example.com as non-enterprise account. We don't use any + // available public domain such as gmail.com in order to prevent possible + // leak of verification keys/signatures. + signin::AccountManagedStatusFinder::SetNonEnterpriseDomainForTesting( + "example.com"); + } + + void TearDown() override { + signin::AccountManagedStatusFinder::SetNonEnterpriseDomainForTesting( + nullptr); + UserCloudPolicyManagerTestBase::TearDown(); + } +}; + +// Test scenarios for consumer user with custom domain who already signed in. +class UserCloudPolicyManagerExistingConsumerUserTest + : public UserCloudPolicyManagerTestBase { + protected: + UserCloudPolicyManagerExistingConsumerUserTest() + : UserCloudPolicyManagerTestBase( + ash::LoggedInUserMixin::LogInType::kConsumerCustomDomain, + /*user_existed_before=*/true) {} + + void SetUp() override { + UserCloudPolicyManagerTestBase::SetUp(); + // Recognize example.com as non-enterprise account. We don't use any + // available public domain such as gmail.com in order to prevent possible + // leak of verification keys/signatures. + signin::AccountManagedStatusFinder::SetNonEnterpriseDomainForTesting( + "example.com"); + } + + void TearDown() override { + signin::AccountManagedStatusFinder::SetNonEnterpriseDomainForTesting( + nullptr); + UserCloudPolicyManagerTestBase::TearDown(); + } +}; + +// Test scenarios for child user signing in for the first time. +class UserCloudPolicyManagerNewChildUserTest + : public UserCloudPolicyManagerTestBase { + protected: + UserCloudPolicyManagerNewChildUserTest() + : UserCloudPolicyManagerTestBase( + ash::LoggedInUserMixin::LogInType::kChild, + /*user_existed_before=*/false) {} +}; + +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerNewManagedUserTest, StartSession) { // User hasn't signed in yet, so shouldn't know if the user requires policy. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kUnknown, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); // Set up start-up URLs through a mandatory user policy. const char* const kStartupURLs[] = {"chrome://policy", "chrome://about"}; enterprise_management::StringList* startup_urls_proto = - logged_in_user_mixin_.GetUserPolicyMixin() + logged_in_user_mixin_->GetUserPolicyMixin() ->RequestPolicyUpdate() ->policy_payload() ->mutable_restoreonstartupurls() ->mutable_value(); for (auto* const url : kStartupURLs) startup_urls_proto->add_entries(url); - logged_in_user_mixin_.GetUserPolicyMixin() + logged_in_user_mixin_->GetUserPolicyMixin() ->RequestPolicyUpdate() ->policy_payload() ->mutable_restoreonstartup() @@ -137,8 +193,7 @@ // User should be marked as requiring policy. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kPolicyRequired, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); // It is expected that if ArcEnabled policy is not set then it is managed // by default and user is not able manually set it. @@ -147,82 +202,67 @@ arc::prefs::kArcEnabled)); } -IN_PROC_BROWSER_TEST_P(UserCloudPolicyManagerTest, ErrorLoadingPolicy) { +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerNewManagedUserTest, + ErrorLoadingPolicy) { StartUserLogIn(false /*wait_for_active_session*/); RunUntilBrowserProcessQuits(); // Session should not have been started. EXPECT_FALSE(session_manager::SessionManager::Get()->IsSessionStarted()); - user_manager::KnownUser known_user(g_browser_process->local_state()); // User should be marked as not knowing if policy is required yet. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kUnknown, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); } -IN_PROC_BROWSER_TEST_P(UserCloudPolicyManagerTest, +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerExistingConsumerUserTest, ErrorLoadingPolicyForUnmanagedUser) { - user_manager::KnownUser known_user(g_browser_process->local_state()); // User should be marked as not knowing if policy is required yet. // Mark user as not needing policy - errors loading policy should be // ignored (unlike previous ErrorLoadingPolicy test). - known_user.SetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId(), + SetProfileRequiresPolicy( user_manager::ProfileRequiresPolicy::kNoPolicyRequired); StartUserLogIn(true /*wait_for_active_session*/); // User should still be marked as not needing policy EXPECT_EQ(user_manager::ProfileRequiresPolicy::kNoPolicyRequired, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); } -IN_PROC_BROWSER_TEST_P(UserCloudPolicyManagerTest, +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerExistingConsumerUserTest, NoPolicyForNonEnterpriseUser) { // Recognize example.com as non-enterprise account. We don't use any // available public domain such as gmail.com in order to prevent possible // leak of verification keys/signatures. signin::AccountManagedStatusFinder::SetNonEnterpriseDomainForTesting( "example.com"); - EXPECT_EQ(signin::AccountManagedStatusFinder::IsEnterpriseUserBasedOnEmail( - logged_in_user_mixin_.GetAccountId().GetUserEmail()), + ASSERT_EQ(signin::AccountManagedStatusFinder::IsEnterpriseUserBasedOnEmail( + logged_in_user_mixin_->GetAccountId().GetUserEmail()), signin::AccountManagedStatusFinder::EmailEnterpriseStatus:: kKnownNonEnterprise); + user_manager::KnownUser known_user(g_browser_process->local_state()); // If a user signs in with a known non-enterprise account there should be no // policy. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kUnknown, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); StartUserLogIn(true /*wait_for_active_session*/); // User should be marked as not requiring policy. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kNoPolicyRequired, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); } -using UserCloudPolicyManagerChildTest = UserCloudPolicyManagerTest; - -IN_PROC_BROWSER_TEST_P(UserCloudPolicyManagerChildTest, PolicyForChildUser) { - signin::AccountManagedStatusFinder::SetNonEnterpriseDomainForTesting( - "example.com"); - EXPECT_EQ(signin::AccountManagedStatusFinder::IsEnterpriseUserBasedOnEmail( - logged_in_user_mixin_.GetAccountId().GetUserEmail()), - signin::AccountManagedStatusFinder::EmailEnterpriseStatus:: - kKnownNonEnterprise); - - user_manager::KnownUser known_user(g_browser_process->local_state()); +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerNewChildUserTest, + PolicyForChildUser) { // If a user signs in with a known non-enterprise account there should be no // policy in case user type is child. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kUnknown, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); - logged_in_user_mixin_.GetUserPolicyMixin() + logged_in_user_mixin_->GetUserPolicyMixin() ->RequestPolicyUpdate() ->policy_payload() ->Clear(); @@ -230,8 +270,7 @@ // User of CHILD type should be marked as requiring policy. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kPolicyRequired, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); // It is expected that if ArcEnabled policy is not set then it is not managed // by default and user is able manually set it. @@ -240,21 +279,12 @@ arc::prefs::kArcEnabled)); } -IN_PROC_BROWSER_TEST_P(UserCloudPolicyManagerChildTest, +IN_PROC_BROWSER_TEST_F(UserCloudPolicyManagerNewChildUserTest, PolicyForChildUserMissing) { - user_manager::KnownUser known_user(g_browser_process->local_state()); - signin::AccountManagedStatusFinder::SetNonEnterpriseDomainForTesting( - "example.com"); - EXPECT_EQ(signin::AccountManagedStatusFinder::IsEnterpriseUserBasedOnEmail( - logged_in_user_mixin_.GetAccountId().GetUserEmail()), - signin::AccountManagedStatusFinder::EmailEnterpriseStatus:: - kKnownNonEnterprise); - // If a user signs in with a known non-enterprise account there should be no // policy in case user type is child. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kUnknown, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); StartUserLogIn(false /*wait_for_active_session*/); RunUntilBrowserProcessQuits(); @@ -264,28 +294,6 @@ // User should be marked as not knowing if policy is required yet. EXPECT_EQ(user_manager::ProfileRequiresPolicy::kUnknown, - known_user.GetProfileRequiresPolicy( - logged_in_user_mixin_.GetAccountId())); + GetProfileRequiresPolicy()); } - -const std::vector<base::test::FeatureRef> feature_lists[] = { - {}, - {features::kDMServerOAuthForChildUser}}; - -// TODO(agawronska): Remove test instantiation with kDMServerOAuthForChildUser -// once it is enabled by default. -INSTANTIATE_TEST_SUITE_P( - /* no prefix */, - UserCloudPolicyManagerTest, - testing::Combine( - testing::ValuesIn(feature_lists), - testing::Values(ash::LoggedInUserMixin::LogInType::kRegular))); - -INSTANTIATE_TEST_SUITE_P( - /* no prefix */, - UserCloudPolicyManagerChildTest, - testing::Combine( - testing::ValuesIn(feature_lists), - testing::Values(ash::LoggedInUserMixin::LogInType::kChild))); - } // namespace policy
diff --git a/chrome/browser/ash/policy/login/login_policy_test_base.cc b/chrome/browser/ash/policy/login/login_policy_test_base.cc index 8e72aa7..45c3e1cb 100644 --- a/chrome/browser/ash/policy/login/login_policy_test_base.cc +++ b/chrome/browser/ash/policy/login/login_policy_test_base.cc
@@ -45,7 +45,7 @@ LoginPolicyTestBase::LoginPolicyTestBase() : account_id_(AccountId::FromUserEmailGaiaId(kAccountId, kAccountGaiaId)) { set_open_about_blank_on_browser_launch(false); - login_manager_.set_should_launch_browser(true); + login_manager_.SetShouldLaunchBrowser(true); } LoginPolicyTestBase::~LoginPolicyTestBase() = default;
diff --git a/chrome/browser/ash/policy/login/signin_profile_extensions_policy_test_base.cc b/chrome/browser/ash/policy/login/signin_profile_extensions_policy_test_base.cc index 692e257f..180d309 100644 --- a/chrome/browser/ash/policy/login/signin_profile_extensions_policy_test_base.cc +++ b/chrome/browser/ash/policy/login/signin_profile_extensions_policy_test_base.cc
@@ -31,11 +31,15 @@ } void SigninProfileExtensionsPolicyTestBase::SetUpOnMainThread() { - DevicePolicyCrosBrowserTest::SetUpOnMainThread(); - + // Mixins might configure and start test server extensions::policy_test_utils::SetUpEmbeddedTestServer( embedded_test_server()); - ASSERT_TRUE(embedded_test_server()->Start()); + + DevicePolicyCrosBrowserTest::SetUpOnMainThread(); + + if (!embedded_test_server()->Started()) { + ASSERT_TRUE(embedded_test_server()->Start()); + } } void SigninProfileExtensionsPolicyTestBase::AddExtensionForForceInstallation(
diff --git a/chrome/browser/ash/policy/reporting/os_updates/os_updates_reporter_browsertest.cc b/chrome/browser/ash/policy/reporting/os_updates/os_updates_reporter_browsertest.cc index c715b45..eab52ed 100644 --- a/chrome/browser/ash/policy/reporting/os_updates/os_updates_reporter_browsertest.cc +++ b/chrome/browser/ash/policy/reporting/os_updates/os_updates_reporter_browsertest.cc
@@ -78,7 +78,7 @@ } void SetUpOnMainThread() override { - login_manager_mixin_.set_should_launch_browser(true); + login_manager_mixin_.SetShouldLaunchBrowser(true); policy::DevicePolicyCrosBrowserTest::SetUpOnMainThread(); }
diff --git a/chrome/browser/ash/policy/reporting/user_added_removed/user_added_removed_reporter_browsertest.cc b/chrome/browser/ash/policy/reporting/user_added_removed/user_added_removed_reporter_browsertest.cc index 9b79a18..eee1bdbc 100644 --- a/chrome/browser/ash/policy/reporting/user_added_removed/user_added_removed_reporter_browsertest.cc +++ b/chrome/browser/ash/policy/reporting/user_added_removed/user_added_removed_reporter_browsertest.cc
@@ -142,7 +142,7 @@ } void SetUpOnMainThread() override { - login_manager_mixin_.set_should_launch_browser(true); + login_manager_mixin_.SetShouldLaunchBrowser(true); FakeSessionManagerClient::Get()->set_supports_browser_restart(true); policy::DevicePolicyCrosBrowserTest::SetUpOnMainThread(); }
diff --git a/chrome/browser/ash/power/renderer_freezer.cc b/chrome/browser/ash/power/renderer_freezer.cc index 4be36e8..3b1b125 100644 --- a/chrome/browser/ash/power/renderer_freezer.cc +++ b/chrome/browser/ash/power/renderer_freezer.cc
@@ -78,26 +78,21 @@ // iterate over all the extensions in the newly created process and take the // appropriate action based on whether we find an extension using GCM. content::BrowserContext* context = rph->GetBrowserContext(); - extensions::ExtensionRegistry* registry = - extensions::ExtensionRegistry::Get(context); - for (const std::string& extension_id : - extensions::ProcessMap::Get(context)->GetExtensionsInProcess(rph_id)) { - const extensions::Extension* extension = - registry->enabled_extensions().GetByID(extension_id); - if (!extension || !extension->permissions_data()->HasAPIPermission( - extensions::mojom::APIPermissionID::kGcm)) { - continue; + if (const extensions::Extension* extension = + extensions::ProcessMap::Get(context)->GetEnabledExtensionByProcessID( + rph_id)) { + if (extension->permissions_data()->HasAPIPermission( + extensions::mojom::APIPermissionID::kGcm)) { + // This renderer has an extension that is using GCM. Make sure it is not + // frozen during suspend. + delegate_->SetShouldFreezeRenderer(rph->GetProcess().Handle(), false); + gcm_extension_processes_.insert(rph_id); + + // Watch to see if the renderer process or the RenderProcessHost is + // destroyed. + rph->AddObserver(this); + return; } - - // This renderer has an extension that is using GCM. Make sure it is not - // frozen during suspend. - delegate_->SetShouldFreezeRenderer(rph->GetProcess().Handle(), false); - gcm_extension_processes_.insert(rph_id); - - // Watch to see if the renderer process or the RenderProcessHost is - // destroyed. - rph->AddObserver(this); - return; } // We didn't find an extension in this RenderProcessHost that is using GCM so
diff --git a/chrome/browser/ash/scalable_iph/customizable_test_env_browser_test_base.cc b/chrome/browser/ash/scalable_iph/customizable_test_env_browser_test_base.cc index 69dab3aee..57e85ef8 100644 --- a/chrome/browser/ash/scalable_iph/customizable_test_env_browser_test_base.cc +++ b/chrome/browser/ash/scalable_iph/customizable_test_env_browser_test_base.cc
@@ -101,22 +101,19 @@ break; case UserSessionType::kChild: logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( - &mixin_host_, ash::LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), this, /*should_launch_browser=*/false); + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kChild); break; case UserSessionType::kChildOwner: logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( - &mixin_host_, ash::LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), this, /*should_launch_browser=*/false); + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kChild); owner_user_email_ = logged_in_user_mixin_->GetAccountId().GetUserEmail(); break; case UserSessionType::kManaged: logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( - &mixin_host_, ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this, /*should_launch_browser=*/false, - AccountId::FromUserEmailGaiaId( - FakeGaiaMixin::kEnterpriseUser1, - FakeGaiaMixin::kEnterpriseUser1GaiaId)); + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kManaged); // If a device is not enrolled, simulate a case where a device is owned by // the managed account. This is a managed account on not-enrolled device @@ -130,24 +127,22 @@ break; case UserSessionType::kRegular: logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( - &mixin_host_, ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this); + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kConsumer); owner_user_email_ = logged_in_user_mixin_->GetAccountId().GetUserEmail(); break; case UserSessionType::kRegularNonOwner: logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( - &mixin_host_, ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this); - + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kConsumer); CHECK(kOwnerEmail != logged_in_user_mixin_->GetAccountId().GetUserEmail()); owner_user_email_ = kOwnerEmail; break; case UserSessionType::kRegularWithOobe: logged_in_user_mixin_ = std::make_unique<ash::LoggedInUserMixin>( - &mixin_host_, ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this, /*should_launch_browser=*/false, - /*account_id=*/std::nullopt, /*auth_config=*/std::nullopt, + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kConsumer, /*include_initial_user=*/false); break; } @@ -162,23 +157,34 @@ void CustomizableTestEnvBrowserTestBase::SetUpOnMainThread() { if (logged_in_user_mixin_) { + base::flat_set<LoggedInUserMixin::LoginDetails> login_details; + switch (test_environment_.user_session_type()) { + case UserSessionType::kChild: + case UserSessionType::kChildOwner: + case UserSessionType::kManaged: + login_details.insert(LoggedInUserMixin::LoginDetails::kNoBrowserLaunch); + break; + case UserSessionType::kRegularWithOobe: + login_details.insert(LoggedInUserMixin::LoginDetails::kNoBrowserLaunch); + login_details.insert(LoggedInUserMixin::LoginDetails::kUserOnboarding); + login_details.insert( + LoggedInUserMixin::LoginDetails::kDontWaitForSession); + break; + default: + break; + } if (test_environment_.user_session_type() == UserSessionType::kRegularWithOobe) { // For WithOobe session type, we don't wait an active session but a // profile creation. test::ProfilePreparedWaiter profile_prepared_waiter( logged_in_user_mixin_->GetAccountId()); - logged_in_user_mixin_->LogInUser(/*issue_any_scope_token=*/false, - /*wait_for_active_session=*/false, - /*request_policy_update=*/true, - /*skip_post_login_screens=*/false); + logged_in_user_mixin_->LogInUser(login_details); profile_prepared_waiter.Wait(); } else { - // `LoggedInUserMixin::LogInUser` waits an active session by default. - logged_in_user_mixin_->LogInUser(); + logged_in_user_mixin_->LogInUser(login_details); } } - MixinBasedInProcessBrowserTest::SetUpOnMainThread(); }
diff --git a/chrome/browser/certificate_manager_model_ash_browsertest.cc b/chrome/browser/certificate_manager_model_ash_browsertest.cc index c790135..bfbc396 100644 --- a/chrome/browser/certificate_manager_model_ash_browsertest.cc +++ b/chrome/browser/certificate_manager_model_ash_browsertest.cc
@@ -68,8 +68,8 @@ protected: ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kConsumer}; FakeObserver fake_observer_; base::test::ScopedFeatureList feature_list_;
diff --git a/chrome/browser/chrome_browser_application_mac.mm b/chrome/browser/chrome_browser_application_mac.mm index 25972e1..a053c1f 100644 --- a/chrome/browser/chrome_browser_application_mac.mm +++ b/chrome/browser/chrome_browser_application_mac.mm
@@ -151,10 +151,6 @@ if (self != [BrowserCrApplication class]) { return; } - // Turn all deallocated Objective-C objects into zombies, keeping - // the most recent 10,000 of them on the treadmill. - ObjcEvilDoers::ZombieEnable(true, 10000); - chrome::InstallObjcExceptionPreprocessor(); cocoa_l10n_util::ApplyForcedRTL();
diff --git a/chrome/browser/chrome_browser_field_trials.cc b/chrome/browser/chrome_browser_field_trials.cc index 62eb84d9e..6797fbb 100644 --- a/chrome/browser/chrome_browser_field_trials.cc +++ b/chrome/browser/chrome_browser_field_trials.cc
@@ -31,8 +31,6 @@ #include "chrome/browser/android/flags/chrome_cached_flags.h" #include "chrome/browser/flags/android/chrome_feature_list.h" #include "chrome/common/chrome_features.h" -#else -#include "chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.h" #endif #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -101,10 +99,6 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) ash::multidevice_setup::CreateFirstRunFieldTrial(feature_list); #endif -#if !BUILDFLAG(IS_ANDROID) - SearchEngineChoiceClientSideTrial::SetUpIfNeeded( - entropy_providers.default_entropy(), feature_list, local_state_); -#endif } } @@ -149,8 +143,6 @@ ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial( kBackgroundThreadPoolTrial, group_name); } -#else - SearchEngineChoiceClientSideTrial::RegisterSyntheticTrials(); #endif // BUILDFLAG(IS_ANDROID) #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index a2166e6..47cf3bb0 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -2876,11 +2876,11 @@ if (process_type != switches::kZygoteProcess) { // The switch value depends on the "HeapProfilerCentralControl" feature, and // the zygote starts before the FeatureList is available. - const auto* heap_profiler_controller = - heap_profiling::HeapProfilerController::GetInstance(); - if (heap_profiler_controller) { + if (const auto* heap_profiler_controller = + heap_profiling::HeapProfilerController::GetInstance()) { heap_profiler_controller->AppendCommandLineSwitchForChildProcess( - command_line, GetProfileParamsProcess(*command_line)); + command_line, GetProfileParamsProcess(*command_line), + child_process_id); } }
diff --git a/chrome/browser/chromeos/extensions/login_screen/login/login_apitest.cc b/chrome/browser/chromeos/extensions/login_screen/login/login_apitest.cc index d4560290..6eff28a 100644 --- a/chrome/browser/chromeos/extensions/login_screen/login/login_apitest.cc +++ b/chrome/browser/chromeos/extensions/login_screen/login/login_apitest.cc
@@ -471,13 +471,8 @@ // |embedded_test_server()|. net::EmbeddedTestServer test_server_; ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, - ash::LoggedInUserMixin::LogInType::kRegular, - &test_server_, - this, - /*should_launch_browser=*/true, - AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kEnterpriseUser1, - FakeGaiaMixin::kEnterpriseUser1GaiaId)}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kManaged}; }; IN_PROC_BROWSER_TEST_F(LoginApitestWithEnterpriseUser,
diff --git a/chrome/browser/commerce/price_tracking/android/javatests/src/org/chromium/chrome/browser/price_tracking/PriceTrackingButtonControllerUnitTest.java b/chrome/browser/commerce/price_tracking/android/javatests/src/org/chromium/chrome/browser/price_tracking/PriceTrackingButtonControllerUnitTest.java index 18efb8f7..3ad97b6 100644 --- a/chrome/browser/commerce/price_tracking/android/javatests/src/org/chromium/chrome/browser/price_tracking/PriceTrackingButtonControllerUnitTest.java +++ b/chrome/browser/commerce/price_tracking/android/javatests/src/org/chromium/chrome/browser/price_tracking/PriceTrackingButtonControllerUnitTest.java
@@ -46,7 +46,10 @@ /** Unit test for {@link PriceTrackingButtonController}. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) -@EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) +@EnableFeatures({ + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING, + ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2 +}) public class PriceTrackingButtonControllerUnitTest { @Rule public TestRule mFeaturesProcessor = new Features.JUnitProcessor();
diff --git a/chrome/browser/extensions/api/settings_private/settings_private_event_router_unittest.cc b/chrome/browser/extensions/api/settings_private/settings_private_event_router_unittest.cc index 6f847150..e75c657 100644 --- a/chrome/browser/extensions/api/settings_private/settings_private_event_router_unittest.cc +++ b/chrome/browser/extensions/api/settings_private/settings_private_event_router_unittest.cc
@@ -25,6 +25,9 @@ // A fake that pretends that all contexts are WebUI. class ProcessMapFake : public ProcessMap { public: + explicit ProcessMapFake(content::BrowserContext* browser_context) + : ProcessMap(browser_context) {} + mojom::ContextType GetMostLikelyContextType(const Extension* extension, int process_id, const GURL* url) const override { @@ -45,7 +48,7 @@ std::unique_ptr<KeyedService> BuildProcessMap( content::BrowserContext* profile) { - return std::make_unique<ProcessMapFake>(); + return std::make_unique<ProcessMapFake>(profile); } // Tracks event dispatches to a specific process.
diff --git a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc index a77b19b..377a3cf 100644 --- a/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc +++ b/chrome/browser/extensions/chrome_content_browser_client_extensions_part.cc
@@ -836,10 +836,8 @@ return; } - auto& process_map = CHECK_DEREF(ProcessMap::Get(process.GetBrowserContext())); - std::set<ExtensionId> extensions = - process_map.GetExtensionsInProcess(process.GetID()); - if (!extensions.empty()) { + if (auto* extension = ProcessMap::Get(process.GetBrowserContext()) + ->GetEnabledExtensionByProcessID(process.GetID())) { command_line->AppendSwitch(switches::kExtensionProcess); // Blink usually initializes the main-thread Isolate in background mode for @@ -848,29 +846,16 @@ // visibility, and benefit from being started in foreground mode. We can // safely start those processes in foreground mode, knowing that // RenderThreadImpl::OnRendererHidden will be called when appropriate. - const std::vector<std::string>& mimehandler_extensions = - MimeTypesHandler::GetMIMETypeAllowlist(); - for (const std::string& extension : mimehandler_extensions) { - if (extensions.contains(extension)) { - command_line->AppendSwitch(::switches::kInitIsolateAsForeground); - break; - } + if (base::Contains(MimeTypesHandler::GetMIMETypeAllowlist(), + extension->id())) { + command_line->AppendSwitch(::switches::kInitIsolateAsForeground); } + + // Direct Sockets API is enabled for Chrome Apps with "sockets" permission. if (base::FeatureList::IsEnabled(kDirectSocketsInChromeApps) && - extensions.size() == 1) { - // Chrome Apps never share their processes with other apps or extensions. - // With this precondition, it's sufficient to check that there's exactly - // one extension running in the current process, and that this extension - // is indeed a Chrome App with "sockets" permission to enable the Direct - // Sockets API. - auto* extension = ExtensionRegistry::Get(process.GetBrowserContext()) - ->enabled_extensions() - .GetByID(*extensions.begin()); - if (extension && extension->is_platform_app() && - SocketsManifestData::Get(extension)) { - command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures, - "DirectSockets"); - } + extension->is_platform_app() && SocketsManifestData::Get(extension)) { + command_line->AppendSwitchASCII(::switches::kEnableBlinkFeatures, + "DirectSockets"); } } }
diff --git a/chrome/browser/extensions/extension_service.cc b/chrome/browser/extensions/extension_service.cc index 09d1fad..c93f526 100644 --- a/chrome/browser/extensions/extension_service.cc +++ b/chrome/browser/extensions/extension_service.cc
@@ -2144,42 +2144,39 @@ return; ProcessMap* process_map = ProcessMap::Get(profile_); - if (process_map->Contains(host->GetID())) { - // An extension process was terminated, this might have resulted in an - // app or extension becoming idle. - std::set<std::string> extension_ids = - process_map->GetExtensionsInProcess(host->GetID()); - // In addition to the extensions listed in the process map, one of those - // extensions could be referencing a shared module which is waiting for - // idle to update. Check all imports of these extensions, too. - std::set<std::string> import_ids; - for (auto& extension_id : extension_ids) { - const Extension* extension = registry_->GetExtensionById( - extension_id, ExtensionRegistry::EVERYTHING); - if (!extension) - continue; + + // An extension process was terminated, this might have resulted in an + // app or extension becoming idle. + if (std::optional<std::string> extension_id = + process_map->GetExtensionIdForProcess(host->GetID())) { + // The extension running in this process might also be referencing a shared + // module which is waiting for idle to update. Check all imports of this + // extension too. + std::set<std::string> affected_ids; + affected_ids.insert(*extension_id); + + if (auto* extension = registry_->GetExtensionById( + *extension_id, ExtensionRegistry::EVERYTHING)) { const std::vector<SharedModuleInfo::ImportInfo>& imports = SharedModuleInfo::GetImports(extension); for (const auto& import_info : imports) { - import_ids.insert(import_info.extension_id); + affected_ids.insert(import_info.extension_id); } } - extension_ids.insert(import_ids.begin(), import_ids.end()); - for (auto& extension_id : extension_ids) { - if (delayed_installs_.Contains(extension_id)) { + for (const auto& id : affected_ids) { + if (delayed_installs_.Contains(id)) { base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( FROM_HERE, base::BindOnce( base::IgnoreResult( &ExtensionService::FinishDelayedInstallationIfReady), - AsExtensionServiceWeakPtr(), extension_id, - false /*install_immediately*/), + AsExtensionServiceWeakPtr(), id, false /*install_immediately*/), kUpdateIdleDelay); } } } - process_map->RemoveAllFromProcess(host->GetID()); + process_map->Remove(host->GetID()); } int ExtensionService::GetDisableReasonsOnInstalled(const Extension* extension) {
diff --git a/chrome/browser/feedback/android/family_info_feedback_source_unittest.cc b/chrome/browser/feedback/android/family_info_feedback_source_unittest.cc index 13aec54..2e83937 100644 --- a/chrome/browser/feedback/android/family_info_feedback_source_unittest.cc +++ b/chrome/browser/feedback/android/family_info_feedback_source_unittest.cc
@@ -28,6 +28,7 @@ #include "components/supervised_user/core/browser/supervised_user_service.h" #include "components/supervised_user/core/browser/supervised_user_url_filter.h" #include "components/supervised_user/core/browser/supervised_user_utils.h" +#include "components/supervised_user/core/common/supervised_user_constants.h" #include "content/public/test/browser_task_environment.h" #include "google_apis/gaia/google_service_auth_error.h" #include "testing/gtest/include/gtest/gtest.h" @@ -39,7 +40,6 @@ namespace { const char kTestEmail[] = "test@gmail.com"; -const char kFeedbackTagFamilyMemberRole[] = "Family_Member_Role"; const char kFeedbackTagParentalControlSitesChild[] = "Parental_Control_Sites_Child"; @@ -217,7 +217,7 @@ base::android::JavaParamRef<jobject>(env_, j_feedback_source_.obj()), base::android::ConvertUTF8ToJavaString( - env_, kFeedbackTagFamilyMemberRole)); + env_, supervised_user::kFamilyMemberRoleFeedbackTag)); return base::android::ConvertJavaStringToUTF8(env_, j_value); }
diff --git a/chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FamilyInfoFeedbackSource.java b/chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FamilyInfoFeedbackSource.java index 7c8e543..31f5ef56c 100644 --- a/chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FamilyInfoFeedbackSource.java +++ b/chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FamilyInfoFeedbackSource.java
@@ -19,7 +19,9 @@ /** Reports profile settings for users in a family group. */ @JNINamespace("chrome::android") public class FamilyInfoFeedbackSource implements AsyncFeedbackSource { + // LINT.IfChange private static final String FAMILY_MEMBER_ROLE = "Family_Member_Role"; + // LINT.ThenChange(//components/supervised_user/core/common/supervised_user_constants.h) private static final String PARENTAL_CONTROL_SITES_CHILD = "Parental_Control_Sites_Child"; private final Profile mProfile;
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 1bdb0523..a68604c 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -4450,6 +4450,11 @@ "expiry_milestone": 115 }, { + "name": "fetch-gaia-hash-on-sign-in", + "owners":["nwokedi@chromium.org"], + "expiry_milestone": 130 + }, + { "name": "file-handling-icons", "owners": [ "dmurph@chromium.org", "mgiuca@chromium.org", "cmp@chromium.org" ], "expiry_milestone": 110
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index 827e626..0c23700 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1966,6 +1966,11 @@ const char kContextualPageActionsDescription[] = "Enables contextual page action feature."; +const char kContextualPageActionsPriceTrackingName[] = + "Contextual page actions - price tracking"; +const char kContextualPageActionsPriceTrackingDescription[] = + "Enables price tracking as a contextual page action."; + const char kContextualPageActionsReaderModeName[] = "Contextual page actions - reader mode"; const char kContextualPageActionsReaderModeDescription[] = @@ -4120,6 +4125,12 @@ const char kFeedDynamicColorsDescription[] = "Allows feed to fully respect dynamic colors if supported by the client."; +const char kFetchGaiaHashOnSignInName[] = + "Enable Fetching Gaia credentials from SharedPreferences."; +const char kFetchGaiaHashOnSignInDescription[] = + "Enable retrieving email, salt, and hashed password from SharedPreferences " + "for password reuse detection when a user signs in."; + const char kFullscreenInsetsApiMigrationName[] = "Migrate to the new fullscreen insets APIs"; const char kFullscreenInsetsApiMigrationDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 853dcae9..0c72b4f 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -2440,6 +2440,9 @@ extern const char kFeedDiscoFeedEndpointName[]; extern const char kFeedDiscoFeedEndpointDescription[]; +extern const char kFetchGaiaHashOnSignInName[]; +extern const char kFetchGaiaHashOnSignInDescription[]; + extern const char kFullscreenInsetsApiMigrationName[]; extern const char kFullscreenInsetsApiMigrationDescription[];
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index b96b553..f2a69186 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -332,6 +332,7 @@ &safe_browsing::kSafeBrowsingNewGmsApiForBrowseUrlDatabaseCheck, &safe_browsing::kSafeBrowsingNewGmsApiForSubresourceFilterCheck, &segmentation_platform::features::kContextualPageActions, + &segmentation_platform::features::kContextualPageActionPriceTracking, &segmentation_platform::features::kContextualPageActionReaderMode, &segmentation_platform::features::kContextualPageActionShareModel, &segmentation_platform::features::
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java index 661cbb2..cbe1746 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java
@@ -247,6 +247,8 @@ public static final String COMMERCE_MERCHANT_VIEWER = "CommerceMerchantViewer"; public static final String COMMERCE_PRICE_TRACKING = "CommercePriceTracking"; public static final String CONTEXTUAL_PAGE_ACTIONS = "ContextualPageActions"; + public static final String CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING = + "ContextualPageActionPriceTracking"; public static final String CONTEXTUAL_PAGE_ACTION_READER_MODE = "ContextualPageActionReaderMode"; public static final String CONTEXTUAL_SEARCH_DISABLE_ONLINE_DETECTION =
diff --git a/chrome/browser/ip_protection/BUILD.gn b/chrome/browser/ip_protection/BUILD.gn index d2dd8fa3..f3179d3 100644 --- a/chrome/browser/ip_protection/BUILD.gn +++ b/chrome/browser/ip_protection/BUILD.gn
@@ -58,6 +58,7 @@ ":ip_protection", "//base/test:test_support", "//chrome/test:test_support", + "//components/ip_protection:ip_protection", "//components/prefs:test_support", "//components/privacy_sandbox:features", "//components/privacy_sandbox:privacy_sandbox_prefs",
diff --git a/chrome/browser/ip_protection/ip_protection_config_provider.cc b/chrome/browser/ip_protection/ip_protection_config_provider.cc index c3ea40df..fb90237 100644 --- a/chrome/browser/ip_protection/ip_protection_config_provider.cc +++ b/chrome/browser/ip_protection/ip_protection_config_provider.cc
@@ -16,6 +16,7 @@ #include "chrome/browser/ip_protection/ip_protection_switches.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/channel_info.h" +#include "components/ip_protection/ip_protection_config_provider_helper.h" #include "components/prefs/pref_service.h" #include "components/privacy_sandbox/privacy_sandbox_features.h" #include "components/privacy_sandbox/tracking_protection_prefs.h" @@ -35,17 +36,6 @@ #include "net/third_party/quiche/src/quiche/blind_sign_auth/proto/blind_sign_auth_options.pb.h" #include "net/third_party/quiche/src/quiche/blind_sign_auth/proto/spend_token_data.pb.h" -namespace { -// TODO(crbug.com/40216037): Once `google_apis::GetAPIKey()` handles this -// logic we can remove this helper. -std::string GetAPIKey() { - return chrome::GetChannel() == version_info::Channel::STABLE - ? google_apis::GetAPIKey() - : google_apis::GetNonStableAPIKey(); -} -constexpr char kChromeIpBlinding[] = "chromeipblinding"; -} // namespace - IpProtectionConfigProvider::IpProtectionConfigProvider( signin::IdentityManager* identity_manager, privacy_sandbox::TrackingProtectionSettings* tracking_protection_settings, @@ -75,7 +65,8 @@ if (!ip_protection_proxy_config_retriever_) { ip_protection_proxy_config_retriever_ = std::make_unique<IpProtectionProxyConfigRetriever>( - url_loader_factory_.get(), kChromeIpBlinding, GetAPIKey()); + url_loader_factory_.get(), + IpProtectionConfigProviderHelper::kChromeIpBlinding, GetAPIKey()); } if (!bsa_) { if (!blind_sign_auth_) { @@ -89,6 +80,12 @@ } } +std::string IpProtectionConfigProvider::GetAPIKey() { + return chrome::GetChannel() == version_info::Channel::STABLE + ? google_apis::GetAPIKey() + : google_apis::GetNonStableAPIKey(); +} + void IpProtectionConfigProvider::SetUpForTesting( std::unique_ptr<IpProtectionProxyConfigRetriever> ip_protection_proxy_config_retriever, @@ -304,64 +301,14 @@ return; } - // Shortcut to create a ProxyServer with SCHEME_HTTPS from a string in the - // proto. - auto add_server = [](std::vector<net::ProxyServer>& proxies, - std::string host) { - net::ProxyServer proxy_server = net::ProxySchemeHostAndPortToProxyServer( - net::ProxyServer::SCHEME_HTTPS, host); - if (!proxy_server.is_valid()) { - return false; - } - proxies.push_back(proxy_server); - return true; - }; - - std::vector<net::ProxyChain> proxy_list; - for (const auto& proxy_chain : response->proxy_chain()) { - std::vector<net::ProxyServer> proxies; - bool ok = true; - bool overridden = false; - if (const std::string a_override = - net::features::kIpPrivacyProxyAHostnameOverride.Get(); - a_override != "") { - overridden = true; - ok = ok && add_server(proxies, a_override); - } else { - ok = ok && add_server(proxies, proxy_chain.proxy_a()); - } - if (const std::string b_override = - net::features::kIpPrivacyProxyBHostnameOverride.Get(); - ok && b_override != "") { - overridden = true; - ok = ok && add_server(proxies, b_override); - } else { - ok = ok && add_server(proxies, proxy_chain.proxy_b()); - } - - // Create a new ProxyChain if the proxies were all valid. - if (ok) { - // If the `chain_id` is out of range or local features overrode the - // chain, use the proxy chain anyway, but with the default `chain_id`. - // This allows adding new IDs on the server side without breaking older - // browsers. - int chain_id = proxy_chain.chain_id(); - if (overridden || chain_id < 0 || - chain_id > net::ProxyChain::kMaxIpProtectionChainId) { - chain_id = net::ProxyChain::kDefaultIpProtectionChainId; - } - proxy_list.push_back( - net::ProxyChain::ForIpProtection(std::move(proxies), chain_id)); - } - } - - VLOG(2) << "IPATP::GetProxyList got proxy list of length " - << proxy_list.size(); + std::vector<net::ProxyChain> proxy_list = + IpProtectionConfigProviderHelper::GetProxyListFromProxyConfigResponse( + response.value()); std::move(callback).Run(std::move(proxy_list)); } void IpProtectionConfigProvider::FetchBlindSignedToken( - signin::AccessTokenInfo access_token_info, + std::optional<signin::AccessTokenInfo> access_token_info, uint32_t batch_size, network::mojom::IpProtectionProxyLayer proxy_layer, TryGetAuthTokensCallback callback) { @@ -371,7 +318,7 @@ ? quiche::ProxyLayer::kProxyA : quiche::ProxyLayer::kProxyB; bsa_->GetTokens( - access_token_info.token, batch_size, quiche_proxy_layer, + access_token_info.value().token, batch_size, quiche_proxy_layer, quiche::BlindSignAuthServiceType::kChromeIpBlinding, [weak_ptr = weak_ptr_factory_.GetWeakPtr(), bsa_get_tokens_start_time, callback = std::move(callback)]( @@ -425,7 +372,7 @@ std::vector<network::mojom::BlindSignedAuthTokenPtr> bsa_tokens; for (const quiche::BlindSignToken& token : tokens.value()) { network::mojom::BlindSignedAuthTokenPtr converted_token = - CreateBlindSignedAuthToken(token); + IpProtectionConfigProviderHelper::CreateBlindSignedAuthToken(token); if (converted_token->token.empty()) { TryGetAuthTokensComplete( std::nullopt, std::move(callback), @@ -444,27 +391,6 @@ IpProtectionTryGetAuthTokensResult::kSuccess); } -// static -network::mojom::BlindSignedAuthTokenPtr -IpProtectionConfigProvider::CreateBlindSignedAuthToken( - quiche::BlindSignToken bsa_token) { - base::Time expiration = - base::Time::FromTimeT(absl::ToTimeT(bsa_token.expiration)); - - // What the network service will receive as a "token" is the fully constructed - // authorization header value. - std::string token_header_value = ""; - privacy::ppn::PrivacyPassTokenData privacy_pass_token_data; - if (privacy_pass_token_data.ParseFromString(bsa_token.token)) { - token_header_value = - base::StrCat({"PrivateToken token=\"", privacy_pass_token_data.token(), - "\", extensions=\"", - privacy_pass_token_data.encoded_extensions(), "\""}); - } - return network::mojom::BlindSignedAuthToken::New( - std::move(token_header_value), expiration); -} - void IpProtectionConfigProvider::TryGetAuthTokensComplete( std::optional<std::vector<network::mojom::BlindSignedAuthTokenPtr>> bsa_tokens, @@ -520,19 +446,19 @@ case IpProtectionTryGetAuthTokensResult::kFailedBSA403: // Eligibility, whether determined locally or on the server, is unlikely // to change quickly. - backoff = kNotEligibleBackoff; + backoff = IpProtectionConfigProviderHelper::kNotEligibleBackoff; break; case IpProtectionTryGetAuthTokensResult::kFailedOAuthTokenTransient: case IpProtectionTryGetAuthTokensResult::kFailedBSAOther: // Transient failure to fetch an OAuth token, or some other error from // BSA that is probably transient. - backoff = kTransientBackoff; + backoff = IpProtectionConfigProviderHelper::kTransientBackoff; exponential = true; break; case IpProtectionTryGetAuthTokensResult::kFailedBSA400: case IpProtectionTryGetAuthTokensResult::kFailedBSA401: // Both 400 and 401 suggest a bug, so do not retry aggressively. - backoff = kBugBackoff; + backoff = IpProtectionConfigProviderHelper::kBugBackoff; exponential = true; break; case IpProtectionTryGetAuthTokensResult::kFailedOAuthTokenDeprecated:
diff --git a/chrome/browser/ip_protection/ip_protection_config_provider.h b/chrome/browser/ip_protection/ip_protection_config_provider.h index 91c93d1..c7a3f2e 100644 --- a/chrome/browser/ip_protection/ip_protection_config_provider.h +++ b/chrome/browser/ip_protection/ip_protection_config_provider.h
@@ -15,6 +15,7 @@ #include "base/time/time.h" #include "chrome/browser/ip_protection/ip_protection_config_http.h" #include "chrome/browser/ip_protection/ip_protection_config_provider_factory.h" +#include "components/ip_protection/ip_protection_config_provider_helper.h" #include "components/ip_protection/ip_protection_proxy_config_retriever.h" #include "components/privacy_sandbox/tracking_protection_settings.h" #include "components/privacy_sandbox/tracking_protection_settings_observer.h" @@ -37,43 +38,6 @@ struct BlindSignToken; } // namespace quiche -// The result of a fetch of tokens from the IP Protection auth token server. -// -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. Keep this in sync with -// IpProtectionTokenBatchRequestResult in enums.xml. -enum class IpProtectionTryGetAuthTokensResult { - // The request was successful and resulted in new tokens. - kSuccess = 0, - // No primary account is set. - kFailedNoAccount = 1, - // Chrome determined the primary account is not eligible. - kFailedNotEligible = 2, - // There was a failure fetching an OAuth token for the primary account. - // Deprecated in favor of `kFailedOAuthToken{Transient,Persistent}`. - kFailedOAuthTokenDeprecated = 3, - // There was a failure in BSA with the given status code. - kFailedBSA400 = 4, - kFailedBSA401 = 5, - kFailedBSA403 = 6, - - // Any other issue calling BSA. - kFailedBSAOther = 7, - - // There was a transient failure fetching an OAuth token for the primary - // account. - kFailedOAuthTokenTransient = 8, - // There was a persistent failure fetching an OAuth token for the primary - // account. - kFailedOAuthTokenPersistent = 9, - - // The attempt to request tokens failed because IP Protection was disabled by - // the user. - kFailedDisabledByUser = 10, - - kMaxValue = kFailedDisabledByUser, -}; - // Fetches IP protection tokens on demand for the network service. // // This class handles both requesting OAuth2 tokens for the signed-in user, and @@ -93,23 +57,19 @@ ~IpProtectionConfigProvider() override; - // Get a batch of blind-signed auth tokens. + // IpProtectionConfigGetter: // - // It is forbidden for two calls to this method to be outstanding at the same - // time. + // Get a batch of blind-signed auth tokens. It is forbidden for two calls to + // this method to be outstanding at the same time. void TryGetAuthTokens(uint32_t batch_size, network::mojom::IpProtectionProxyLayer proxy_layer, TryGetAuthTokensCallback callback) override; - // Get the list of IP Protection proxies. void GetProxyList(GetProxyListCallback callback) override; - // KeyedService: - void Shutdown() override; - - static IpProtectionConfigProvider* Get(Profile* profile); - static bool CanIpProtectionBeEnabled(); + + // Checks if IP Protection is disabled via user settings. bool IsIpProtectionEnabled(); // Add bidirectional pipes to a new network service. @@ -119,6 +79,11 @@ mojo::PendingRemote<network::mojom::IpProtectionProxyDelegate> pending_remote); + // KeyedService: + void Shutdown() override; + + static IpProtectionConfigProvider* Get(Profile* profile); + mojo::ReceiverSet<network::mojom::IpProtectionConfigGetter>& receivers_for_testing() { return receivers_; @@ -137,11 +102,6 @@ std::unique_ptr<IpProtectionConfigHttp> ip_protection_config_http, quiche::BlindSignAuthInterface* bsa); - // Base time deltas for calculating `try_again_after`. - static constexpr base::TimeDelta kNotEligibleBackoff = base::Days(1); - static constexpr base::TimeDelta kTransientBackoff = base::Seconds(5); - static constexpr base::TimeDelta kBugBackoff = base::Minutes(10); - private: friend class IpProtectionConfigProviderTest; FRIEND_TEST_ALL_PREFIXES(IpProtectionConfigProviderTest, CalculateBackoff); @@ -156,6 +116,46 @@ // loops in browser startup. void SetUp(); + // TODO(crbug.com/40216037): Once `google_apis::GetAPIKey()` handles this + // logic we can remove this helper. + std::string GetAPIKey(); + + // Wrapping `ip_protection_config_http_->GetProxyConfig()` method + // to enable OAuth Token inclusion in the GetProxyConfig API call to Phosphor. + void CallGetProxyConfig(GetProxyListCallback callback, + std::optional<std::string> oauth_token); + + void OnGetProxyConfigCompleted( + GetProxyListCallback callback, + base::expected<ip_protection::GetProxyConfigResponse, std::string> + response); + + // `FetchBlindSignedToken()` calls into the `quiche::BlindSignAuth` library to + // request a blind-signed auth token for use at the IP Protection proxies. + void FetchBlindSignedToken( + std::optional<signin::AccessTokenInfo> access_token_info, + uint32_t batch_size, + network::mojom::IpProtectionProxyLayer proxy_layer, + TryGetAuthTokensCallback callback); + + void OnFetchBlindSignedTokenCompleted( + base::TimeTicks bsa_get_tokens_start_time, + TryGetAuthTokensCallback callback, + absl::StatusOr<absl::Span<quiche::BlindSignToken>>); + + // Finish a call to `TryGetAuthTokens()` by recording the result and invoking + // its callback. + void TryGetAuthTokensComplete( + std::optional<std::vector<network::mojom::BlindSignedAuthTokenPtr>> + bsa_tokens, + TryGetAuthTokensCallback callback, + IpProtectionTryGetAuthTokensResult result); + + // Calculates the backoff time for the given result, based on + // `last_try_get_auth_tokens_..` fields, and updates those fields. + std::optional<base::TimeDelta> CalculateBackoff( + IpProtectionTryGetAuthTokensResult result); + // Creating a generic callback in order for `RequestOAuthToken()` to work for // `TryGetAuthTokens()` and `GetProxyList()`. using RequestOAuthTokenCallback = @@ -187,28 +187,6 @@ GoogleServiceAuthError error, signin::AccessTokenInfo access_token_info); - // Wrapping `ip_protection_config_http_->GetProxyConfig()` method - // to enable OAuth Token inclusion in the GetProxyConfig API call to Phosphor. - void CallGetProxyConfig(GetProxyListCallback callback, - std::optional<std::string> oauth_token); - void OnGetProxyConfigCompleted( - GetProxyListCallback callback, - base::expected<ip_protection::GetProxyConfigResponse, std::string> - response); - - // `FetchBlindSignedToken()` calls into the `quiche::BlindSignAuth` library to - // request a blind-signed auth token for use at the IP Protection proxies. - void FetchBlindSignedToken(signin::AccessTokenInfo access_token_info, - uint32_t batch_size, - network::mojom::IpProtectionProxyLayer proxy_layer, - TryGetAuthTokensCallback callback); - void OnFetchBlindSignedTokenCompleted( - base::TimeTicks bsa_get_tokens_start_time, - TryGetAuthTokensCallback callback, - absl::StatusOr<absl::Span<quiche::BlindSignToken>>); - static network::mojom::BlindSignedAuthTokenPtr CreateBlindSignedAuthToken( - quiche::BlindSignToken bsa_token); - void ClearOAuthTokenProblemBackoff(); // The object used to get an OAuth token. `identity_manager_` will be set to @@ -229,19 +207,6 @@ // corresponding dependency (if needed) registered in the factory class. raw_ptr<Profile> profile_; - // Finish a call to `TryGetAuthTokens()` by recording the result and invoking - // its callback. - void TryGetAuthTokensComplete( - std::optional<std::vector<network::mojom::BlindSignedAuthTokenPtr>> - bsa_tokens, - TryGetAuthTokensCallback callback, - IpProtectionTryGetAuthTokensResult result); - - // Calculates the backoff time for the given result, based on - // `last_try_get_auth_tokens_..` fields, and updates those fields. - std::optional<base::TimeDelta> CalculateBackoff( - IpProtectionTryGetAuthTokensResult result); - // Instruct the `IpProtectionConfigCache()`(s) in the Network Service to // ignore any previously sent `try_again_after` times. void InvalidateNetworkContextTryAgainAfterTime();
diff --git a/chrome/browser/ip_protection/ip_protection_config_provider_unittest.cc b/chrome/browser/ip_protection/ip_protection_config_provider_unittest.cc index 593155d..41354d9cd 100644 --- a/chrome/browser/ip_protection/ip_protection_config_provider_unittest.cc +++ b/chrome/browser/ip_protection/ip_protection_config_provider_unittest.cc
@@ -16,6 +16,7 @@ #include "base/time/time.h" #include "base/types/expected.h" #include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/ip_protection/ip_protection_config_provider_helper.h" #include "components/prefs/testing_pref_service.h" #include "components/privacy_sandbox/privacy_sandbox_features.h" #include "components/privacy_sandbox/privacy_sandbox_prefs.h" @@ -324,7 +325,7 @@ base::Time expiration) { quiche::BlindSignToken blind_sign_token = CreateMockBlindSignToken(token_value, expiration); - return IpProtectionConfigProvider::CreateBlindSignedAuthToken( + return IpProtectionConfigProviderHelper::CreateBlindSignedAuthToken( std::move(blind_sign_token)); } @@ -406,7 +407,7 @@ EXPECT_EQ(bsa_->proxy_layer_, quiche::ProxyLayer::kProxyA); EXPECT_EQ(bsa_->oauth_token_, "access_token"); ExpectTryGetAuthTokensResultFailed( - IpProtectionConfigProvider::kTransientBackoff); + IpProtectionConfigProviderHelper::kTransientBackoff); histogram_tester_.ExpectUniqueSample( kTryGetAuthTokensResultHistogram, IpProtectionTryGetAuthTokensResult::kFailedBSAOther, 1); @@ -426,7 +427,7 @@ EXPECT_EQ(bsa_->proxy_layer_, quiche::ProxyLayer::kProxyB); EXPECT_EQ(bsa_->oauth_token_, "access_token"); ExpectTryGetAuthTokensResultFailed( - IpProtectionConfigProvider::kTransientBackoff); + IpProtectionConfigProviderHelper::kTransientBackoff); histogram_tester_.ExpectUniqueSample( kTryGetAuthTokensResultHistogram, IpProtectionTryGetAuthTokensResult::kFailedBSAOther, 1); @@ -445,7 +446,8 @@ EXPECT_EQ(bsa_->num_tokens_, 1); EXPECT_EQ(bsa_->proxy_layer_, quiche::ProxyLayer::kProxyA); EXPECT_EQ(bsa_->oauth_token_, "access_token"); - ExpectTryGetAuthTokensResultFailed(IpProtectionConfigProvider::kBugBackoff); + ExpectTryGetAuthTokensResultFailed( + IpProtectionConfigProviderHelper::kBugBackoff); histogram_tester_.ExpectUniqueSample( kTryGetAuthTokensResultHistogram, IpProtectionTryGetAuthTokensResult::kFailedBSA400, 1); @@ -464,7 +466,8 @@ EXPECT_EQ(bsa_->num_tokens_, 1); EXPECT_EQ(bsa_->proxy_layer_, quiche::ProxyLayer::kProxyB); EXPECT_EQ(bsa_->oauth_token_, "access_token"); - ExpectTryGetAuthTokensResultFailed(IpProtectionConfigProvider::kBugBackoff); + ExpectTryGetAuthTokensResultFailed( + IpProtectionConfigProviderHelper::kBugBackoff); histogram_tester_.ExpectUniqueSample( kTryGetAuthTokensResultHistogram, IpProtectionTryGetAuthTokensResult::kFailedBSA401, 1); @@ -484,7 +487,7 @@ EXPECT_EQ(bsa_->proxy_layer_, quiche::ProxyLayer::kProxyA); EXPECT_EQ(bsa_->oauth_token_, "access_token"); ExpectTryGetAuthTokensResultFailed( - IpProtectionConfigProvider::kNotEligibleBackoff); + IpProtectionConfigProviderHelper::kNotEligibleBackoff); histogram_tester_.ExpectUniqueSample( kTryGetAuthTokensResultHistogram, IpProtectionTryGetAuthTokensResult::kFailedBSA403, 1); @@ -504,7 +507,7 @@ EXPECT_EQ(bsa_->proxy_layer_, quiche::ProxyLayer::kProxyB); EXPECT_EQ(bsa_->oauth_token_, "access_token"); ExpectTryGetAuthTokensResultFailed( - IpProtectionConfigProvider::kTransientBackoff); + IpProtectionConfigProviderHelper::kTransientBackoff); histogram_tester_.ExpectUniqueSample( kTryGetAuthTokensResultHistogram, IpProtectionTryGetAuthTokensResult::kFailedBSAOther, 1); @@ -545,7 +548,7 @@ EXPECT_FALSE(bsa_->get_tokens_called_); ExpectTryGetAuthTokensResultFailed( - IpProtectionConfigProvider::kTransientBackoff); + IpProtectionConfigProviderHelper::kTransientBackoff); histogram_tester_.ExpectUniqueSample( kTryGetAuthTokensResultHistogram, IpProtectionTryGetAuthTokensResult::kFailedOAuthTokenTransient, 1); @@ -680,12 +683,16 @@ }; check(kSuccess, std::nullopt, false); - check(kFailedNotEligible, getter_->kNotEligibleBackoff, false); - check(kFailedBSA400, getter_->kBugBackoff, true); - check(kFailedBSA401, getter_->kBugBackoff, true); - check(kFailedBSA403, getter_->kNotEligibleBackoff, false); - check(kFailedBSAOther, getter_->kTransientBackoff, true); - check(kFailedOAuthTokenTransient, getter_->kTransientBackoff, true); + check(kFailedNotEligible, + IpProtectionConfigProviderHelper::kNotEligibleBackoff, false); + check(kFailedBSA400, IpProtectionConfigProviderHelper::kBugBackoff, true); + check(kFailedBSA401, IpProtectionConfigProviderHelper::kBugBackoff, true); + check(kFailedBSA403, IpProtectionConfigProviderHelper::kNotEligibleBackoff, + false); + check(kFailedBSAOther, IpProtectionConfigProviderHelper::kTransientBackoff, + true); + check(kFailedOAuthTokenTransient, + IpProtectionConfigProviderHelper::kTransientBackoff, true); check(kFailedNoAccount, base::TimeDelta::Max(), false); // The account-related backoffs should not be changed except by account change @@ -694,7 +701,7 @@ AccountInfo account_info = identity_test_env_.MakePrimaryAccountAvailable( kTestEmail, signin::ConsentLevel::kSignin); // The backoff time should have been reset. - check(kFailedBSA400, getter_->kBugBackoff, true); + check(kFailedBSA400, IpProtectionConfigProviderHelper::kBugBackoff, true); check(kFailedOAuthTokenPersistent, base::TimeDelta::Max(), false); check(kFailedBSA400, base::TimeDelta::Max(), false); @@ -707,7 +714,7 @@ identity_test_env_.UpdatePersistentErrorOfRefreshTokenForAccount( account_info.account_id, GoogleServiceAuthError(GoogleServiceAuthError::State::NONE)); - check(kFailedBSA400, getter_->kBugBackoff, true); + check(kFailedBSA400, IpProtectionConfigProviderHelper::kBugBackoff, true); } TEST_F(IpProtectionConfigProviderTest, GetProxyListProxyChains) {
diff --git a/chrome/browser/memory/OWNERS b/chrome/browser/memory/OWNERS index be16e4e..2c86d29 100644 --- a/chrome/browser/memory/OWNERS +++ b/chrome/browser/memory/OWNERS
@@ -1,4 +1,4 @@ -chrisha@chromium.org +file://chrome/browser/resource_coordinator/OWNERS # OOM and memory kills logging per-file memory_kills_*=vovoy@chromium.org
diff --git a/chrome/browser/memory/chrome_browser_main_extra_parts_memory.cc b/chrome/browser/memory/chrome_browser_main_extra_parts_memory.cc index acd3c79..1c6f52b 100644 --- a/chrome/browser/memory/chrome_browser_main_extra_parts_memory.cc +++ b/chrome/browser/memory/chrome_browser_main_extra_parts_memory.cc
@@ -4,11 +4,21 @@ #include "chrome/browser/memory/chrome_browser_main_extra_parts_memory.h" +#include <utility> + +#include "base/functional/bind.h" +#include "base/functional/callback.h" #include "base/memory/memory_pressure_monitor.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/memory/enterprise_memory_limit_pref_observer.h" +#include "components/heap_profiling/in_process/browser_process_snapshot_controller.h" +#include "components/heap_profiling/in_process/mojom/snapshot_controller.mojom.h" +#include "content/public/browser/browser_child_process_host.h" +#include "content/public/browser/child_process_host.h" +#include "content/public/browser/render_process_host.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "base/logging.h" @@ -16,11 +26,42 @@ #include "chromeos/ash/components/memory/pressure/system_memory_pressure_evaluator.h" #endif +namespace { + +// A shim to connect HeapProfilerController, which can't depend on content/, to +// ChildProcessHost. +void BindHeapSnapshotControllerToProcessHost( + int child_process_id, + mojo::PendingReceiver<heap_profiling::mojom::SnapshotController> receiver) { + // `child_process_id` could refer to a BrowserChildProcessHost or + // RenderProcessHost. + if (auto* browser_child_process_host = + content::BrowserChildProcessHost::FromID(child_process_id)) { + browser_child_process_host->GetHost()->BindReceiver(std::move(receiver)); + } else if (auto* render_process_host = + content::RenderProcessHost::FromID(child_process_id)) { + render_process_host->BindReceiver(std::move(receiver)); + } +} + +} // namespace + ChromeBrowserMainExtraPartsMemory::ChromeBrowserMainExtraPartsMemory() = default; ChromeBrowserMainExtraPartsMemory::~ChromeBrowserMainExtraPartsMemory() = default; +void ChromeBrowserMainExtraPartsMemory::PostCreateThreads() { + // BrowserProcessSnapshotController may be null if heap profiling isn't + // enabled in this session, or if the kHeapProfilerCentralControl feature is + // disabled. + if (auto* snapshot_controller = + heap_profiling::BrowserProcessSnapshotController::GetInstance()) { + snapshot_controller->SetBindRemoteForChildProcessCallback( + base::BindRepeating(&BindHeapSnapshotControllerToProcessHost)); + } +} + void ChromeBrowserMainExtraPartsMemory::PostBrowserStart() { // The MemoryPressureMonitor might not be available in some tests. if (base::MemoryPressureMonitor::Get()) {
diff --git a/chrome/browser/memory/chrome_browser_main_extra_parts_memory.h b/chrome/browser/memory/chrome_browser_main_extra_parts_memory.h index 2639e50..d973ac7 100644 --- a/chrome/browser/memory/chrome_browser_main_extra_parts_memory.h +++ b/chrome/browser/memory/chrome_browser_main_extra_parts_memory.h
@@ -36,6 +36,7 @@ private: // ChromeBrowserMainExtraParts overrides. + void PostCreateThreads() override; void PostBrowserStart() override; void PostMainMessageLoopRun() override;
diff --git a/chrome/browser/memory_details.cc b/chrome/browser/memory_details.cc index 58fe3bd8..362542c 100644 --- a/chrome/browser/memory_details.cc +++ b/chrome/browser/memory_details.cc
@@ -308,13 +308,12 @@ int rph_id = render_process_host->GetID(); process_is_for_extensions = process_map->Contains(rph_id); - // For our purposes, don't count processes containing only hosted - // apps as extension processes. See also: crbug.com/102533. - for (auto& extension_id : process_map->GetExtensionsInProcess(rph_id)) { - const Extension* extension = extension_set->GetByID(extension_id); - if (extension && !extension->is_hosted_app()) { + // For our purposes, don't count processes running hosted apps as + // extension processes. See also: crbug.com/102533. + if (const Extension* extension = + process_map->GetEnabledExtensionByProcessID(rph_id)) { + if (!extension->is_hosted_app()) { process.renderer_type = ProcessMemoryInformation::RENDERER_EXTENSION; - break; } } }
diff --git a/chrome/browser/metrics/chrome_metrics_service_accessor.h b/chrome/browser/metrics/chrome_metrics_service_accessor.h index ffe4c32..7a6f95b 100644 --- a/chrome/browser/metrics/chrome_metrics_service_accessor.h +++ b/chrome/browser/metrics/chrome_metrics_service_accessor.h
@@ -106,10 +106,6 @@ class ExperimentManagerImpl; } -namespace SearchEngineChoiceClientSideTrial { -void RegisterSyntheticTrials(); -} - namespace readaloud { class SyntheticTrial; } @@ -174,7 +170,6 @@ friend class WebUITabStripFieldTrial; friend class feed::FeedServiceDelegateImpl; friend class FirstRunService; - friend void SearchEngineChoiceClientSideTrial::RegisterSyntheticTrials(); friend class browser_sync::DeviceInfoSyncClientImpl; friend class feed::WebFeedSubscriptionCoordinator; friend class HttpsFirstModeService;
diff --git a/chrome/browser/metrics/chromeos_family_link_user_metrics_provider_browsertest.cc b/chrome/browser/metrics/chromeos_family_link_user_metrics_provider_browsertest.cc index ba53d2e..c2b4ab6 100644 --- a/chrome/browser/metrics/chromeos_family_link_user_metrics_provider_browsertest.cc +++ b/chrome/browser/metrics/chromeos_family_link_user_metrics_provider_browsertest.cc
@@ -26,7 +26,7 @@ ChromeOSFamilyLinkUserMetricsProvider::LogSegment log_segment) { switch (log_segment) { case ChromeOSFamilyLinkUserMetricsProvider::LogSegment::kOther: - return ash::LoggedInUserMixin::LogInType::kRegular; + return ash::LoggedInUserMixin::LogInType::kConsumer; case ChromeOSFamilyLinkUserMetricsProvider::LogSegment::kUnderConsentAge: case ChromeOSFamilyLinkUserMetricsProvider::LogSegment::kOverConsentAge: return ash::LoggedInUserMixin::LogInType::kChild; @@ -76,9 +76,9 @@ public testing::WithParamInterface< ChromeOSFamilyLinkUserMetricsProvider::LogSegment> { protected: - ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, GetLogInType(GetParam()), embedded_test_server(), - /*test_base=*/this}; + ash::LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, + embedded_test_server(), + GetLogInType(GetParam())}; }; IN_PROC_BROWSER_TEST_P(ChromeOSFamilyLinkUserMetricsProviderTest, @@ -103,7 +103,8 @@ logged_in_user_mixin_.GetFakeGaiaMixin()->set_initialize_child_id_token( log_segment == ChromeOSFamilyLinkUserMetricsProvider::LogSegment::kUnderConsentAge); - logged_in_user_mixin_.LogInUser(/*issue_any_scope_token=*/true); + logged_in_user_mixin_.LogInUser( + {ash::LoggedInUserMixin::LoginDetails::kUseAnyScopeToken}); run_loop.Run();
diff --git a/chrome/browser/metrics/chromeos_metrics_provider_browsertest.cc b/chrome/browser/metrics/chromeos_metrics_provider_browsertest.cc index ecf5f13..b14312c 100644 --- a/chrome/browser/metrics/chromeos_metrics_provider_browsertest.cc +++ b/chrome/browser/metrics/chromeos_metrics_provider_browsertest.cc
@@ -32,7 +32,7 @@ if (user_type == user_manager::UserType::kChild) { return ash::LoggedInUserMixin::LogInType::kChild; } - return ash::LoggedInUserMixin::LogInType::kRegular; + return ash::LoggedInUserMixin::LogInType::kConsumer; } void ProvideHistograms() { @@ -55,8 +55,9 @@ : public MixinBasedInProcessBrowserTest, public testing::WithParamInterface<user_manager::UserType> { protected: - ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, GetLogInType(GetParam()), embedded_test_server(), this}; + ash::LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, + embedded_test_server(), + GetLogInType(GetParam())}; }; IN_PROC_BROWSER_TEST_P(ChromeOSMetricsProviderTest, PrimaryUserType) {
diff --git a/chrome/browser/metrics/family_user_metrics_provider_browsertest.cc b/chrome/browser/metrics/family_user_metrics_provider_browsertest.cc index fdd095d..f77bd16 100644 --- a/chrome/browser/metrics/family_user_metrics_provider_browsertest.cc +++ b/chrome/browser/metrics/family_user_metrics_provider_browsertest.cc
@@ -13,6 +13,7 @@ #include "chrome/browser/ash/login/test/logged_in_user_mixin.h" #include "chrome/browser/ash/login/test/scoped_policy_update.h" #include "chrome/browser/ash/login/test/user_policy_mixin.h" +#include "chrome/browser/ash/policy/test_support/embedded_policy_test_server_mixin.h" #include "chrome/browser/ash/settings/scoped_testing_cros_settings.h" #include "chrome/browser/ash/settings/stub_cros_settings_provider.h" #include "chrome/browser/browser_process.h" @@ -43,31 +44,13 @@ case FamilyUserMetricsProvider::FamilyUserLogSegment::kSupervisedStudent: return ash::LoggedInUserMixin::LogInType::kChild; case FamilyUserMetricsProvider::FamilyUserLogSegment::kStudentAtHome: + return ash::LoggedInUserMixin::LogInType::kManaged; case FamilyUserMetricsProvider::FamilyUserLogSegment::kRegularUser: case FamilyUserMetricsProvider::FamilyUserLogSegment::kOther: - return ash::LoggedInUserMixin::LogInType::kRegular; + return ash::LoggedInUserMixin::LogInType::kConsumer; } } -// Returns the account id for the primary test account for logging in. -std::optional<AccountId> GetPrimaryAccountId( - FamilyUserMetricsProvider::FamilyUserLogSegment log_segment) { - if (log_segment == - FamilyUserMetricsProvider::FamilyUserLogSegment::kStudentAtHome) { - // To distinguish K-12 EDU users from Enterprise users in ChromeOS, we use a - // PolicyData field. Fetching policy is skipped for obviously consumer - // users, who have an @gmail.com e-mail, for example (see comments in - // fake_gaia_mixin.h). Since we need policies for this test, we must use an - // e-mail address that has an enterprise domain. Of all the user categories, - // kStudentAtHome is the only one with an enterprise managed primary - // account. - return AccountId::FromUserEmailGaiaId( - FakeGaiaMixin::kEnterpriseUser1, FakeGaiaMixin::kEnterpriseUser1GaiaId); - } - // Use the default FakeGaiaMixin::kFakeUserEmail consumer test account id. - return std::nullopt; -} - void ProvideHistograms() { // The purpose of the below call is to avoid a DCHECK failure in an unrelated // metrics provider, in |FieldTrialsProvider::ProvideCurrentSessionData()|. @@ -94,10 +77,8 @@ if (GetFamilyUserLogSegment() == FamilyUserMetricsProvider::FamilyUserLogSegment::kStudentAtHome) { - logged_in_user_mixin_.GetUserPolicyMixin() - ->RequestPolicyUpdate() - ->policy_data() - ->set_metrics_log_segment(enterprise_management::PolicyData::K12); + logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin() + ->SetMetricsLogSegment(enterprise_management::PolicyData::K12); } } @@ -108,16 +89,8 @@ } ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, GetPrimaryLogInType(GetFamilyUserLogSegment()), - embedded_test_server(), this, - /*should_launch_browser=*/true, - GetPrimaryAccountId(GetFamilyUserLogSegment()), - /*auth_config=*/std::nullopt, - /*include_initial_user=*/true, - // Don't use EmbeddedPolicyTestServer because it does not support - // customizing PolicyData. - // TODO(crbug/1112885): Use EmbeddedPolicyTestServer when this is fixed. - /*use_embedded_policy_server=*/false}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + GetPrimaryLogInType(GetFamilyUserLogSegment())}; }; IN_PROC_BROWSER_TEST_P(FamilyUserMetricsProviderTest, UserCategory) { @@ -237,8 +210,8 @@ ash::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kConsumer}; ash::ScopedTestingCrosSettings scoped_testing_cros_settings_; };
diff --git a/chrome/browser/metrics/power/process_monitor.cc b/chrome/browser/metrics/power/process_monitor.cc index f170abc..db8a85e5 100644 --- a/chrome/browser/metrics/power/process_monitor.cc +++ b/chrome/browser/metrics/power/process_monitor.cc
@@ -111,25 +111,12 @@ return MonitoredProcessType::kRenderer; } - extensions::ProcessMap* extension_process_map = - extensions::ProcessMap::Get(browser_context); - DCHECK(extension_process_map); - std::set<std::string> extension_ids = - extension_process_map->GetExtensionsInProcess(host->GetID()); - - // We only collect more granular metrics when there's only one extension - // running in a given renderer, to reduce noise. - if (extension_ids.size() != 1) - return MonitoredProcessType::kRenderer; - - extensions::ExtensionRegistry* extension_registry = - extensions::ExtensionRegistry::Get(browser_context); - const extensions::Extension* extension = - extension_registry->enabled_extensions().GetByID(*extension_ids.begin()); - - if (!extension) - return MonitoredProcessType::kRenderer; + extensions::ProcessMap::Get(browser_context) + ->GetEnabledExtensionByProcessID(host->GetID()); + if (!extension) { + return kRenderer; + } return extensions::BackgroundInfo::HasPersistentBackgroundPage(extension) ? MonitoredProcessType::kExtensionPersistent
diff --git a/chrome/browser/metrics/process_memory_metrics_emitter.cc b/chrome/browser/metrics/process_memory_metrics_emitter.cc index 6c251080..f28f7e8 100644 --- a/chrome/browser/metrics/process_memory_metrics_emitter.cc +++ b/chrome/browser/metrics/process_memory_metrics_emitter.cc
@@ -1273,48 +1273,38 @@ int ProcessMemoryMetricsEmitter::GetNumberOfExtensions(base::ProcessId pid) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - int number_of_extensions = 0; #if BUILDFLAG(ENABLE_EXTENSIONS) // Retrieve the renderer process host for the given pid. - int rph_id = -1; - bool found = false; + + content::RenderProcessHost* rph = nullptr; for (auto iter = content::RenderProcessHost::AllHostsIterator(); !iter.IsAtEnd(); iter.Advance()) { if (!iter.GetCurrentValue()->GetProcess().IsValid()) continue; if (iter.GetCurrentValue()->GetProcess().Pid() == pid) { - found = true; - rph_id = iter.GetCurrentValue()->GetID(); + rph = iter.GetCurrentValue(); break; } } - if (!found) + if (!rph) { return 0; - - // Count the number of extensions associated with that renderer process host - // in all profiles. - for (Profile* profile : - g_browser_process->profile_manager()->GetLoadedProfiles()) { - extensions::ProcessMap* process_map = extensions::ProcessMap::Get(profile); - extensions::ExtensionRegistry* registry = - extensions::ExtensionRegistry::Get(profile); - if (!process_map || !registry) - continue; - - std::set<std::string> extension_ids = - process_map->GetExtensionsInProcess(rph_id); - for (const std::string& extension_id : extension_ids) { - // Only count non hosted apps extensions. - const extensions::Extension* extension = - registry->enabled_extensions().GetByID(extension_id); - if (extension && !extension->is_hosted_app()) - number_of_extensions++; - } } + + // Count the number of extensions associated with this `rph`'s profile. + extensions::ProcessMap* process_map = + extensions::ProcessMap::Get(rph->GetBrowserContext()); + if (!process_map) { + return 0; + } + + const extensions::Extension* extension = + process_map->GetEnabledExtensionByProcessID(rph->GetID()); + // Only include this extension if it's not a hosted app. + return (extension && !extension->is_hosted_app()) ? 1 : 0; +#else + return 0; #endif - return number_of_extensions; } std::optional<base::TimeDelta> ProcessMemoryMetricsEmitter::GetProcessUptime(
diff --git a/chrome/browser/metrics/structured/metadata_processor_ash_browsertest.cc b/chrome/browser/metrics/structured/metadata_processor_ash_browsertest.cc index 5bb4e73..5f8be3a 100644 --- a/chrome/browser/metrics/structured/metadata_processor_ash_browsertest.cc +++ b/chrome/browser/metrics/structured/metadata_processor_ash_browsertest.cc
@@ -104,11 +104,6 @@ return std::nullopt; } -std::optional<AccountId> GetPrimaryAccountId() { - return AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kEnterpriseUser1, - FakeGaiaMixin::kEnterpriseUser1GaiaId); -} - } // namespace namespace metrics::structured { @@ -216,9 +211,10 @@ void UploadDeviceLocalAccountPolicy() { BuildDeviceLocalAccountPolicy(); - policy_test_server_mixin_.UpdateExternalPolicy( - policy::dm_protocol::kChromePublicAccountPolicyType, kAccountId1, - device_local_account_policy_.payload().SerializeAsString()); + logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin() + ->UpdateExternalPolicy( + policy::dm_protocol::kChromePublicAccountPolicyType, kAccountId1, + device_local_account_policy_.payload().SerializeAsString()); } void UploadAndInstallDeviceLocalAccountPolicy() { @@ -254,7 +250,8 @@ em::ChromeDeviceSettingsProto& proto(device_policy()->payload()); policy::DeviceLocalAccountTestHelper::AddPublicSession(&proto, username); RefreshDevicePolicy(); - policy_test_server_mixin_.UpdateDevicePolicy(proto); + logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin() + ->UpdateDevicePolicy(proto); } void WaitForDisplayName(const std::string& user_id, @@ -275,10 +272,8 @@ std::optional<em::PolicyData::MetricsLogSegment> log_segment = GetParam().GetMetricsLogSegment(); if (log_segment) { - logged_in_user_mixin_.GetUserPolicyMixin() - ->RequestPolicyUpdate() - ->policy_data() - ->set_metrics_log_segment(log_segment.value()); + logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin() + ->SetMetricsLogSegment(log_segment.value()); } logged_in_user_mixin_.LogInUser(); } @@ -371,16 +366,9 @@ private: ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this, - /*should_launch_browser=*/true, GetPrimaryAccountId(), - /*auth_config=*/std::nullopt, /*include_initial_user=*/true, - // Don't use EmbeddedPolicyTestServer because it does not support - // customizing PolicyData. - // TODO(crbug/1112885): Use EmbeddedPolicyTestServer when this is fixed. - /*use_embedded_policy_server=*/false}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kManaged}; policy::UserPolicyBuilder device_local_account_policy_; - ash::EmbeddedPolicyTestServerMixin policy_test_server_mixin_{&mixin_host_}; const AccountId account_id_1_ = AccountId::FromUserEmail(policy::GenerateDeviceLocalAccountUserId(
diff --git a/chrome/browser/metrics/usertype_by_devicetype_metrics_provider_browsertest.cc b/chrome/browser/metrics/usertype_by_devicetype_metrics_provider_browsertest.cc index 3553c06..f2ff50c8 100644 --- a/chrome/browser/metrics/usertype_by_devicetype_metrics_provider_browsertest.cc +++ b/chrome/browser/metrics/usertype_by_devicetype_metrics_provider_browsertest.cc
@@ -86,11 +86,6 @@ return std::nullopt; } -std::optional<AccountId> GetPrimaryAccountId() { - return AccountId::FromUserEmailGaiaId(FakeGaiaMixin::kEnterpriseUser1, - FakeGaiaMixin::kEnterpriseUser1GaiaId); -} - void ProvideHistograms() { // The purpose of the below call is to avoid a DCHECK failure in an unrelated // metrics provider, in |FieldTrialsProvider::ProvideCurrentSessionData()|. @@ -261,9 +256,10 @@ void UploadDeviceLocalAccountPolicy() { BuildDeviceLocalAccountPolicy(); - policy_test_server_mixin_.UpdateExternalPolicy( - policy::dm_protocol::kChromePublicAccountPolicyType, kAccountId1, - device_local_account_policy_.payload().SerializeAsString()); + logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin() + ->UpdateExternalPolicy( + policy::dm_protocol::kChromePublicAccountPolicyType, kAccountId1, + device_local_account_policy_.payload().SerializeAsString()); } void UploadAndInstallDeviceLocalAccountPolicy() { @@ -290,7 +286,8 @@ em::ChromeDeviceSettingsProto& proto(device_policy()->payload()); policy::DeviceLocalAccountTestHelper::AddPublicSession(&proto, username); RefreshDevicePolicy(); - policy_test_server_mixin_.UpdateDevicePolicy(proto); + logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin() + ->UpdateDevicePolicy(proto); } void WaitForDisplayName(const std::string& user_id, @@ -311,10 +308,8 @@ std::optional<em::PolicyData::MetricsLogSegment> log_segment = GetParam().GetMetricsLogSegment(); if (log_segment) { - logged_in_user_mixin_.GetUserPolicyMixin() - ->RequestPolicyUpdate() - ->policy_data() - ->set_metrics_log_segment(log_segment.value()); + logged_in_user_mixin_.GetEmbeddedPolicyTestServerMixin() + ->SetMetricsLogSegment(log_segment.value()); } logged_in_user_mixin_.LogInUser(); } @@ -394,16 +389,9 @@ private: ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this, - /*should_launch_browser=*/true, GetPrimaryAccountId(), - /*auth_config=*/std::nullopt, /*include_initial_user=*/true, - // Don't use EmbeddedPolicyTestServer because it does not support - // customizing PolicyData. - // TODO(crbug/1112885): Use EmbeddedPolicyTestServer when this is fixed. - /*use_embedded_policy_server=*/false}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kManaged}; policy::UserPolicyBuilder device_local_account_policy_; - ash::EmbeddedPolicyTestServerMixin policy_test_server_mixin_{&mixin_host_}; const AccountId account_id_1_ = AccountId::FromUserEmail(GenerateDeviceLocalAccountUserId(
diff --git a/chrome/browser/password_manager/android/save_update_password_message_delegate.cc b/chrome/browser/password_manager/android/save_update_password_message_delegate.cc index 4998e15..56422ef 100644 --- a/chrome/browser/password_manager/android/save_update_password_message_delegate.cc +++ b/chrome/browser/password_manager/android/save_update_password_message_delegate.cc
@@ -41,6 +41,7 @@ namespace { +using password_manager::PasswordForm; using password_manager::UsesSplitStoresAndUPMForLocal; // Duration of message before timeout; 20 seconds. @@ -514,31 +515,24 @@ return false; } + // Pre-UPM the profile storage was used in fact as the account store (when + // sync is on). So this is the cut-off for the users who are not using UPM + // (this evaluates to using account store when the user is syncing and using + // profile store when they are not syncing). Profile* profile = Profile::FromBrowserContext(web_contents_->GetBrowserContext()); if (!UsesSplitStoresAndUPMForLocal(profile->GetPrefs())) { return account_email_.has_value(); } - // Saving new credential to the account store. - auto different_username = [&username](const auto& form) { - return (form->username_value != username); - }; - // TODO(crbug.com/40675711): Fix the update logic to use all best matches, - // rather than current_forms which is best_matches without PSL-matched - // credentials. - if (base::ranges::all_of(passwords_state_.GetCurrentForms(), - different_username)) { - return true; - } - - // If it's an update in the account store return true, else (meaning - // that the updated username is only in the profile store) return false. - auto same_username_in_account_store = [&username](const auto& form) { - return (form->username_value == username) && form->IsUsingAccountStore(); - }; - return base::ranges::any_of(passwords_state_.GetCurrentForms(), - same_username_in_account_store); + // Copy the pending password form here and assign the new username. + password_manager::PasswordForm updated_credentials = + passwords_state_.form_manager()->GetPendingCredentials(); + updated_credentials.username_value = username; + return (passwords_state_.form_manager()->GetPasswordStoreForSaving( + updated_credentials) & + PasswordForm::Store::kAccountStore) == + PasswordForm::Store::kAccountStore; } void SaveUpdatePasswordMessageDelegate::ClearState() {
diff --git a/chrome/browser/password_manager/android/save_update_password_message_delegate_unittest.cc b/chrome/browser/password_manager/android/save_update_password_message_delegate_unittest.cc index a20c738..95dd8ee 100644 --- a/chrome/browser/password_manager/android/save_update_password_message_delegate_unittest.cc +++ b/chrome/browser/password_manager/android/save_update_password_message_delegate_unittest.cc
@@ -3,7 +3,9 @@ // found in the LICENSE file. #include "chrome/browser/password_manager/android/save_update_password_message_delegate.h" + #include <jni.h> + #include <algorithm> #include <memory> @@ -310,6 +312,11 @@ ON_CALL(*form_manager, Save()) .WillByDefault(testing::Invoke( this, &SaveUpdatePasswordMessageDelegateTest::RecordPasswordSaved)); + ON_CALL(*form_manager, GetPasswordStoreForSaving(_)) + .WillByDefault([](const PasswordForm& form) -> PasswordForm::Store { + return form.IsUsingAccountStore() ? PasswordForm::Store::kAccountStore + : PasswordForm::Store::kProfileStore; + }); return form_manager; } @@ -1448,7 +1455,7 @@ // set correctly for update password message. TEST_F(SaveUpdatePasswordMessageDelegateTest, MessagePropertyValues_UpdatePassword) { - SetPendingCredentials(kUsername, kPassword); + SetPendingCredentials(kUsername, kPassword, /*is_account_store=*/false); auto form_manager = CreateFormManager(GURL(kDefaultUrl), empty_best_matches()); const bool is_signed_in = false; @@ -1475,7 +1482,7 @@ // password. TEST_F(SaveUpdatePasswordMessageDelegateTest, SignedInDescription_SavePassword) { - SetPendingCredentials(kUsername, kPassword); + SetPendingCredentials(kUsername, kPassword, /*is_account_store=*/true); auto form_manager = CreateFormManager(GURL(kDefaultUrl), empty_best_matches()); const bool is_signed_in = true; @@ -1494,7 +1501,7 @@ // non-displayable email saves a password. TEST_F(SaveUpdatePasswordMessageDelegateTest, SignedInDescription_SavePasswordNonDisplayableEmail) { - SetPendingCredentials(kUsername, kPassword); + SetPendingCredentials(kUsername, kPassword, /*is_account_store=*/true); auto form_manager = CreateFormManager(GURL(kDefaultUrl), empty_best_matches()); const bool is_signed_in = true; @@ -1520,7 +1527,7 @@ // password. TEST_F(SaveUpdatePasswordMessageDelegateTest, SignedInDescription_UpdatePassword) { - SetPendingCredentials(kUsername, kPassword); + SetPendingCredentials(kUsername, kPassword, /*is_account_store=*/true); auto form_manager = CreateFormManager(GURL(kDefaultUrl), empty_best_matches()); const bool is_signed_in = true; @@ -1586,38 +1593,11 @@ DismissMessage(messages::DismissReason::UNKNOWN); } -// Tests that the description is set correctly when the signed in user updated -// the password, which is stored in both local and account stores. -TEST_F(SaveUpdatePasswordMessageDelegateTest, - SignedInDescription_UpdatePasswordInBothStores) { - // Enables using split storages (local and account). - EnableUseUPMLocalAndSeparateStores(); - - SetPendingCredentials(kUsername, kPassword); - PasswordForm password_form = CreatePasswordForm(kUsername, kPassword); - password_form.in_store = - password_manager::PasswordForm::Store::kProfileStore | - password_manager::PasswordForm::Store::kAccountStore; - std::vector<PasswordForm> single_form_best_matches = {password_form}; - auto form_manager = - CreateFormManager(GURL(kDefaultUrl), single_form_best_matches); - const bool is_update = true; - EnqueueMessage(std::move(form_manager), /*user_signed_in=*/true, - /*update_password=*/is_update); - - // Should display signed out message for updating the password in the local - // store (even when the user is signed in). - EXPECT_EQ(GetExpectedUPMMessageDescription(is_update, true, kAccountEmail16), - GetMessageWrapper()->GetDescription()); - - DismissMessage(messages::DismissReason::UNKNOWN); -} - // Tests that the description is set correctly when the signed-in user with a // non-displayable email updates a password. TEST_F(SaveUpdatePasswordMessageDelegateTest, SignedInDescription_UpdatePasswordNonDisplayableEmail) { - SetPendingCredentials(kUsername, kPassword); + SetPendingCredentials(kUsername, kPassword, /*is_account_store=*/true); auto form_manager = CreateFormManager(GURL(kDefaultUrl), empty_best_matches()); const bool is_signed_in = true; @@ -1637,53 +1617,3 @@ GetMessageWrapper()->GetDescription()); DismissMessage(messages::DismissReason::UNKNOWN); } - -// Tests that SaveUpdatePasswordMessageDelegate::IsUsingAccountStorage returns -// correct value for the updated credential. -TEST_F(SaveUpdatePasswordMessageDelegateTest, - IsUsingProfileStore_UpdatingExistingValue) { - EnableUseUPMLocalAndSeparateStores(); - SetPendingCredentials(kUsername, kPassword); - PasswordForm password_form1 = CreatePasswordForm(kUsername, kPassword, true); - PasswordForm password_form2 = - CreatePasswordForm(kUsername2, kPassword, false); - std::vector<PasswordForm> single_form_best_matches = {password_form1, - password_form2}; - auto form_manager = - CreateFormManager(GURL(kDefaultUrl), single_form_best_matches); - - EnqueueMessage(std::move(form_manager), /*user_signed_in=*/true, - /*update_password=*/true); - - EXPECT_TRUE(get_password_edit_dialog_bridge_delegate()->IsUsingAccountStorage( - kUsername)); - EXPECT_FALSE( - get_password_edit_dialog_bridge_delegate()->IsUsingAccountStorage( - kUsername2)); - - DismissMessage(messages::DismissReason::UNKNOWN); -} - -// Tests that SaveUpdatePasswordMessageDelegate::IsUsingAccountStorage returns -// correct value for the saved credential. -TEST_F(SaveUpdatePasswordMessageDelegateTest, - IsUsingProfileStore_SavingNewCredentialFromUpdateDialog) { - EnableUseUPMLocalAndSeparateStores(); - SetPendingCredentials(kUsername, kPassword); - PasswordForm password_form1 = CreatePasswordForm(kUsername, kPassword, false); - std::vector<PasswordForm> single_form_best_matches = { - CreatePasswordForm(kUsername, kPassword, false)}; - auto form_manager = - CreateFormManager(GURL(kDefaultUrl), single_form_best_matches); - - EnqueueMessage(std::move(form_manager), /*user_signed_in=*/true, - /*update_password=*/true); - - EXPECT_FALSE( - get_password_edit_dialog_bridge_delegate()->IsUsingAccountStorage( - kUsername)); - EXPECT_TRUE(get_password_edit_dialog_bridge_delegate()->IsUsingAccountStorage( - kUsername2)); - - DismissMessage(messages::DismissReason::UNKNOWN); -}
diff --git a/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc b/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc index b0f264e..8766c37 100644 --- a/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc +++ b/chrome/browser/performance_manager/chrome_browser_main_extra_parts_performance_manager.cc
@@ -279,7 +279,7 @@ g_browser_process->local_state())); if (base::FeatureList::IsEnabled( - performance_manager::features::kPerformanceCPUIntervention)) { + performance_manager::features::kPerformanceIntervention)) { performance_detection_manager_ = base::WrapUnique( new performance_manager::user_tuning::PerformanceDetectionManager()); }
diff --git a/chrome/browser/performance_manager/user_tuning/performance_detection_manager_browsertest.cc b/chrome/browser/performance_manager/user_tuning/performance_detection_manager_browsertest.cc index fa28d2b..00cf2bc7 100644 --- a/chrome/browser/performance_manager/user_tuning/performance_detection_manager_browsertest.cc +++ b/chrome/browser/performance_manager/user_tuning/performance_detection_manager_browsertest.cc
@@ -34,7 +34,7 @@ void SetUp() override { feature_list_.InitAndEnableFeature( - performance_manager::features::kPerformanceCPUIntervention); + performance_manager::features::kPerformanceIntervention); InProcessBrowserTest::SetUp(); }
diff --git a/chrome/browser/policy/test/promotional_tabs_enabled_policy_browsertest.cc b/chrome/browser/policy/test/promotional_tabs_enabled_policy_browsertest.cc index 734d1c8..8be8e47 100644 --- a/chrome/browser/policy/test/promotional_tabs_enabled_policy_browsertest.cc +++ b/chrome/browser/policy/test/promotional_tabs_enabled_policy_browsertest.cc
@@ -117,17 +117,11 @@ const PromotionalTabsEnabledPolicyWelcomeTest&) = delete; protected: - PromotionalTabsEnabledPolicyWelcomeTest() { - scoped_feature_list_.InitAndEnableFeature(kForYouFre); - } - ~PromotionalTabsEnabledPolicyWelcomeTest() override = default; + PromotionalTabsEnabledPolicyWelcomeTest() = default; void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(switches::kForceFirstRun); } - - private: - base::test::ScopedFeatureList scoped_feature_list_; }; IN_PROC_BROWSER_TEST_P(PromotionalTabsEnabledPolicyWelcomeTest, RunTest) {
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 392ffc2..2dacf8a 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -284,7 +284,6 @@ #include "chrome/browser/new_tab_page/promos/promo_service.h" #include "chrome/browser/policy/developer_tools_policy_handler.h" #include "chrome/browser/search/background/ntp_custom_background_service.h" -#include "chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.h" #include "chrome/browser/search_engine_choice/search_engine_choice_dialog_service.h" #include "chrome/browser/serial/serial_policy_allowed_ports.h" #include "chrome/browser/signin/signin_promo.h" @@ -1058,6 +1057,12 @@ constexpr char kGlanceablesEnabled[] = "ash.glanceables_enabled"; #endif // BUILDFLAG(IS_CHROMEOS_ASH) +#if !BUILDFLAG(IS_ANDROID) +// Deprecated 05/2024 +inline constexpr char kSearchEnginesStudyGroup[] = + "search_engines.client_side_study_group"; +#endif + // Register local state used only for migration (clearing or moving to a new // key). void RegisterLocalStatePrefsForMigration(PrefRegistrySimple* registry) { @@ -1182,6 +1187,11 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) registry->RegisterDictionaryPref(kLastUploadedEuiccStatusPrefLegacy); #endif // BUILDFLAG(IS_CHROMEOS_ASH) + +#if !BUILDFLAG(IS_ANDROID) + // Deprecated 05/2024. + registry->RegisterStringPref(kSearchEnginesStudyGroup, std::string()); +#endif } // Register prefs used only for migration (clearing or moving to a new key). @@ -1642,7 +1652,6 @@ metrics::TabStatsTracker::RegisterPrefs(registry); performance_manager::user_tuning::prefs::RegisterLocalStatePrefs(registry); RegisterBrowserPrefs(registry); - SearchEngineChoiceClientSideTrial::RegisterLocalStatePrefs(registry); speech::SodaInstaller::RegisterLocalStatePrefs(registry); StartupBrowserCreator::RegisterLocalStatePrefs(registry); task_manager::TaskManagerInterface::RegisterPrefs(registry); @@ -2428,6 +2437,11 @@ local_state->ClearPref(kLastUploadedEuiccStatusPrefLegacy); #endif // BUILDFLAG(IS_CHROMEOS_ASH) +#if !BUILDFLAG(IS_ANDROID) + // Added 05/2024. + local_state->ClearPref(kSearchEnginesStudyGroup); +#endif + // Please don't delete the following line. It is used by PRESUBMIT.py. // END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu.cc b/chrome/browser/renderer_context_menu/render_view_context_menu.cc index dc50a60..8296236 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu.cc
@@ -4259,7 +4259,7 @@ LensOverlayController* const controller = LensOverlayController::GetController(source_web_contents_); if (controller && controller->Enabled()) { - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kContentAreaContextMenuPage); return; } }
diff --git a/chrome/browser/resources/history/app.ts b/chrome/browser/resources/history/app.ts index 2cac89d..316f98b9 100644 --- a/chrome/browser/resources/history/app.ts +++ b/chrome/browser/resources/history/app.ts
@@ -280,6 +280,8 @@ private queryState_: QueryState; private selectedPage_: string; private selectedTab_: number; + private lastRecordedSelectedPageHistogramValue_: HistoryPageViewHistogram = + HistoryPageViewHistogram.END; private showHistoryClusters_: boolean; private tabsIcons_: string[]; private tabsNames_: string[]; @@ -695,6 +697,12 @@ break; } + // Avoid double-recording the same page consecutively. + if (histogramValue === this.lastRecordedSelectedPageHistogramValue_) { + return; + } + this.lastRecordedSelectedPageHistogramValue_ = histogramValue; + this.browserService_!.recordHistogram( 'History.HistoryPageView', histogramValue, HistoryPageViewHistogram.END);
diff --git a/chrome/browser/resources/settings/about_page/about_page.html b/chrome/browser/resources/settings/about_page/about_page.html index f748652..d8d70fe 100644 --- a/chrome/browser/resources/settings/about_page/about_page.html +++ b/chrome/browser/resources/settings/about_page/about_page.html
@@ -146,7 +146,7 @@ <get-most-chrome-section></get-most-chrome-section> <settings-section page-title="Get Help"> - <cr-link-row class="hr" id="help" on-click="onHelpClick_" + <cr-link-row id="help" on-click="onHelpClick_" label="$i18n{aboutGetHelpUsingChrome}" external></cr-link-row> <cr-link-row class="hr" id="reportIssue" on-click="onReportIssueClick_"
diff --git a/chrome/browser/resources/settings/about_page/get_most_chrome_section.html b/chrome/browser/resources/settings/about_page/get_most_chrome_section.html index 8e022ea..405deeab 100644 --- a/chrome/browser/resources/settings/about_page/get_most_chrome_section.html +++ b/chrome/browser/resources/settings/about_page/get_most_chrome_section.html
@@ -1,4 +1,8 @@ <style include="cr-shared-style"> + .get-most-chrome { + display: flex; + } + .get-most-chrome-item { display: flex; flex: 1; @@ -10,20 +14,24 @@ </style> <settings-section page-title="$i18n{getTheMostOutOfChrome}"> - <cr-link-row class="hr" id="getTheMostOutOfChrome" + <cr-link-row id="getTheMostOutOfChrome" on-click="onGetTheMostOutOfChromeClick_" - role-description="$i18n{getTheMostOutOfChromePageButton}"> - <template is="dom-repeat" items="[[entries_]]"> - <div class="get-most-chrome-item"> - <picture> - <source - srcset="chrome://settings/images/[[item.iconDark]]" - media="(prefers-color-scheme: dark)"> - <img id="banner" alt="" - src="chrome://settings/images/[[item.iconLight]]"> - </picture> - <div>[[item.label]]</div> - </div> - </template> + using-slotted-label + button-aria-description="$i18n{getTheMostOutOfChrome}" + role-description="$i18n{subpageArrowRoleDescription}"> + <div slot="label" class="get-most-chrome"> + <template is="dom-repeat" items="[[entries_]]"> + <div class="get-most-chrome-item"> + <picture> + <source + srcset="chrome://settings/images/[[item.iconDark]]" + media="(prefers-color-scheme: dark)"> + <img id="banner" alt="" + src="chrome://settings/images/[[item.iconLight]]"> + </picture> + <div>[[item.label]]</div> + </div> + </template> + </div> </cr-link-row> </settings-section>
diff --git a/chrome/browser/resources/settings/people_page/sync_account_control.html b/chrome/browser/resources/settings/people_page/sync_account_control.html index 63a13dc..1523394 100644 --- a/chrome/browser/resources/settings/people_page/sync_account_control.html +++ b/chrome/browser/resources/settings/people_page/sync_account_control.html
@@ -218,12 +218,13 @@ <div id="signin-paused-buttons" hidden="[[!shouldShowSigninPausedButtons_( syncStatus.signinPaused)]]"> - <cr-button class="cr-button-gap" on-click="onSigninClick_"> - $i18n{signinPaused} - </cr-button> <cr-button class="cr-button-gap" on-click="onSignoutClick_"> $i18n{peopleSignOut} </cr-button> + <cr-button class="action-button cr-button-gap" + on-click="onSigninClick_"> + $i18n{verifyAccount} + </cr-button> </div> </div>
diff --git a/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.cc b/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.cc deleted file mode 100644 index feaa677..0000000 --- a/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.cc +++ /dev/null
@@ -1,200 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.h" - -#include "base/check_deref.h" -#include "base/check_is_test.h" -#include "base/feature_list.h" -#include "base/metrics/field_trial.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/metrics/chrome_metrics_service_accessor.h" -#include "chrome/common/channel_info.h" -#include "components/prefs/pref_registry_simple.h" -#include "components/prefs/pref_service.h" -#include "components/search_engines/search_engines_pref_names.h" -#include "components/search_engines/search_engines_switches.h" -#include "components/signin/public/base/signin_switches.h" -#include "components/version_info/channel.h" - -namespace SearchEngineChoiceClientSideTrial { -namespace { - -std::optional<version_info::Channel> g_channel_for_testing; - -// Should match the trial name from Finch. -const char kTrialName[] = "WaffleStudy"; - -// Group names for the trial. -const char kEnabledGroup[] = "ClientSideEnabledForTaggedProfiles"; -const char kDisabledGroup[] = "ClientSideDisabled"; -const char kDefaultGroup[] = "Default"; - -// Probabilities for all field trial groups add up to kTotalGroupWeight. -constexpr base::FieldTrial::Probability kTotalGroupWeight = 1000; - -constexpr int kNonStableEnabledWeight = 0; -constexpr int kNonStableDisabledWeight = 0; -constexpr int kNonStableDefaultWeight = 1000; -static_assert(kTotalGroupWeight == kNonStableEnabledWeight + - kNonStableDisabledWeight + - kNonStableDefaultWeight); - -constexpr int kStableEnabledWeight = 0; -constexpr int kStableDisabledWeight = 0; -constexpr int kStableDefaultWeight = 1000; -static_assert(kTotalGroupWeight == kStableEnabledWeight + - kStableDisabledWeight + - kStableDefaultWeight); - -std::string PickTrialGroupWithoutActivation(base::FieldTrial& trial, - version_info::Channel channel) { - int enabled_weight; - int disabled_weight; - int default_weight; - switch (channel) { - case version_info::Channel::UNKNOWN: - case version_info::Channel::CANARY: - case version_info::Channel::DEV: - case version_info::Channel::BETA: - enabled_weight = kNonStableEnabledWeight; - disabled_weight = kNonStableDisabledWeight; - default_weight = kNonStableDefaultWeight; - break; - case version_info::Channel::STABLE: - enabled_weight = kStableEnabledWeight; - disabled_weight = kStableDisabledWeight; - default_weight = kStableDefaultWeight; - break; - } - DCHECK_EQ(kTotalGroupWeight, - enabled_weight + disabled_weight + default_weight); - - trial.AppendGroup(kEnabledGroup, enabled_weight); - trial.AppendGroup(kDisabledGroup, disabled_weight); - trial.AppendGroup(kDefaultGroup, default_weight); - - return trial.GetGroupNameWithoutActivation(); -} - -void SetUp(const base::FieldTrial::EntropyProvider& entropy_provider, - base::FeatureList& feature_list, - PrefService& local_state, - version_info::Channel channel) { - // Set up the trial and determine the group for the current client. - scoped_refptr<base::FieldTrial> trial = - base::FieldTrialList::FactoryGetFieldTrial( - kTrialName, kTotalGroupWeight, kDefaultGroup, entropy_provider); - - std::string group_name; - if (local_state.HasPrefPath(prefs::kSearchEnginesStudyGroup)) { - DVLOG(1) << "Continuing field trial setup with already set group " - << group_name; - group_name = local_state.GetString(prefs::kSearchEnginesStudyGroup); - } else { - group_name = PickTrialGroupWithoutActivation(*trial, channel); - DVLOG(1) << "Setting field trial with selected group " << group_name; - local_state.SetString(prefs::kSearchEnginesStudyGroup, group_name); - } - - // Set up the state of the features based on the obtained group. - base::FeatureList::OverrideState feature_state = - group_name == kDefaultGroup - ? base::FeatureList::OVERRIDE_USE_DEFAULT - : (group_name == kEnabledGroup - ? base::FeatureList::OVERRIDE_ENABLE_FEATURE - : base::FeatureList::OVERRIDE_DISABLE_FEATURE); - - if (feature_state == base::FeatureList::OVERRIDE_ENABLE_FEATURE) { - base::AssociateFieldTrialParams( - kTrialName, group_name, - {{switches::kSearchEngineChoiceTriggerForTaggedProfilesOnly.name, - "true"}}); - } - - feature_list.RegisterFieldTrialOverride( - switches::kSearchEngineChoiceTrigger.name, feature_state, trial.get()); - - // Activate only after the overrides are completed. - trial->Activate(); - - // Can't call `RegisterSyntheticFieldTrial` here, it requires - // `g_browser_process` to be available, we are too early for this. -} - -} // namespace - -void RegisterLocalStatePrefs(PrefRegistrySimple* registry) { - registry->RegisterStringPref(prefs::kSearchEnginesStudyGroup, ""); -} - -void SetUpIfNeeded(const base::FieldTrial::EntropyProvider& entropy_provider, - base::FeatureList* feature_list, - PrefService* local_state) { -#if !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_MAC) - // Platform not in scope for this client-side trial. - return; -#else - // Make sure that Finch, fieldtrial_testing_config and command line flags take - // precedence over features defined here. In particular, not detecting - // fieldtrial_testing_config triggers a DCHECK. - if (base::FieldTrialList::Find(kTrialName) || - feature_list->HasAssociatedFieldTrialByFeatureName( - switches::kSearchEngineChoiceTrigger.name)) { - DVLOG(1) << "Not setting up client-side trial for WaffleStudy, trial " - "already registered"; - return; - } - - // Skip setup if an associated feature is overriden, typically via the - // commandline or setup during tests. - if (feature_list->IsFeatureOverridden( - switches::kSearchEngineChoiceTrigger.name)) { - LOG(WARNING) << "Not setting up client-side trial for WaffleStudy, feature " - "already overridden."; - return; - } - - // Proceed with actually setting up the field trial. - SetUp(entropy_provider, CHECK_DEREF(feature_list), CHECK_DEREF(local_state), - g_channel_for_testing.value_or(chrome::GetChannel())); -#endif -} - -void SetUpForTesting(const base::FieldTrial::EntropyProvider& entropy_provider, - base::FeatureList& feature_list, - PrefService& local_state, - version_info::Channel channel) { - CHECK_IS_TEST(); - SetUp(entropy_provider, feature_list, local_state, channel); -} - -void RegisterSyntheticTrials() { - CHECK(g_browser_process); - auto enrolled_study_group = g_browser_process->local_state()->GetString( - prefs::kSearchEnginesStudyGroup); - if (enrolled_study_group.empty()) { - // The user was not enrolled or exited the study at some point. - return; - } - - if (enrolled_study_group == kDefaultGroup) { - // No need to register for the default group. - return; - } - - DVLOG(1) << "Registering synthetic field trial for group " - << enrolled_study_group; - ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial( - kSyntheticTrialName, enrolled_study_group, - variations::SyntheticTrialAnnotationMode::kCurrentLog); -} - -ScopedChannelOverride CreateScopedChannelOverrideForTesting( - version_info::Channel channel) { - CHECK_IS_TEST(); - return ScopedChannelOverride(&g_channel_for_testing, channel); -} - -} // namespace SearchEngineChoiceClientSideTrial
diff --git a/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.h b/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.h deleted file mode 100644 index d924e3f7..0000000 --- a/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_SEARCH_ENGINE_CHOICE_SEARCH_ENGINE_CHOICE_CLIENT_SIDE_TRIAL_H_ -#define CHROME_BROWSER_SEARCH_ENGINE_CHOICE_SEARCH_ENGINE_CHOICE_CLIENT_SIDE_TRIAL_H_ - -#include "base/metrics/field_trial.h" - -namespace base { -class FeatureList; -} - -namespace version_info { -enum class Channel; -} - -class PrefService; -class PrefRegistrySimple; - -namespace SearchEngineChoiceClientSideTrial { - -inline constexpr char kSyntheticTrialName[] = "WaffleSynthetic"; - -void RegisterLocalStatePrefs(PrefRegistrySimple* registry); - -// Enrolls the client in a trial and overrides the SearchEngineChoice related -// features according the the selected group. -// Note: Does not perform the synthetic trial registration, it has to be done -// at a later time by calling `RegisterSyntheticTrials()`, as that requires -// `g_browser_process` to be fully initialized, which is typically not the -// case when this method is called. -void SetUpIfNeeded(const base::FieldTrial::EntropyProvider& entropy_provider, - base::FeatureList* feature_list, - PrefService* local_state); - -// Registers a synthetic trial name and group to annotate UMA records based on -// the client-side trial. -// Requires `g_browser_process` to be fully initialized. -void RegisterSyntheticTrials(); - -// Overrides the client channel value used when choosing in which group to -// assign this client. -using ScopedChannelOverride = - base::AutoReset<std::optional<version_info::Channel>>; -ScopedChannelOverride CreateScopedChannelOverrideForTesting( - version_info::Channel channel); - -} // namespace SearchEngineChoiceClientSideTrial - -#endif // CHROME_BROWSER_SEARCH_ENGINE_CHOICE_SEARCH_ENGINE_CHOICE_CLIENT_SIDE_TRIAL_H_
diff --git a/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial_unittest.cc b/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial_unittest.cc deleted file mode 100644 index 4dc4e5b8..0000000 --- a/chrome/browser/search_engine_choice/search_engine_choice_client_side_trial_unittest.cc +++ /dev/null
@@ -1,230 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/search_engine_choice/search_engine_choice_client_side_trial.h" - -#include "base/feature_list.h" -#include "base/files/file_path.h" -#include "base/run_loop.h" -#include "base/scoped_observation.h" -#include "base/strings/stringprintf.h" -#include "base/test/mock_entropy_provider.h" -#include "base/test/scoped_feature_list.h" -#include "base/test/task_environment.h" -#include "chrome/browser/first_run/first_run.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/test/base/scoped_metrics_service_for_synthetic_trials.h" -#include "chrome/test/base/scoped_testing_local_state.h" -#include "chrome/test/base/testing_browser_process.h" -#include "chrome/test/base/testing_profile_manager.h" -#include "components/metrics/metrics_service.h" -#include "components/metrics/metrics_service_client.h" -#include "components/metrics/metrics_state_manager.h" -#include "components/metrics/test/test_enabled_state_provider.h" -#include "components/metrics/test/test_metrics_service_client.h" -#include "components/prefs/pref_service.h" -#include "components/prefs/testing_pref_service.h" -#include "components/search_engines/search_engines_pref_names.h" -#include "components/search_engines/search_engines_switches.h" -#include "components/signin/public/base/signin_switches.h" -#include "components/variations/active_field_trials.h" -#include "components/variations/synthetic_trial_registry.h" -#include "components/variations/synthetic_trials.h" -#include "components/variations/synthetic_trials_active_group_id_provider.h" -#include "components/variations/variations_crash_keys.h" -#include "components/version_info/channel.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -struct SearchEngineChoiceFieldTrialTestParams { - double entropy_value = 0.0; - version_info::Channel channel = version_info::Channel::UNKNOWN; - - bool expect_study_enabled = false; - bool expect_feature_enabled = false; -}; - -} // namespace - -class SearchEngineChoiceClientSideTrialTest - : public testing::Test, - public testing::WithParamInterface< - SearchEngineChoiceFieldTrialTestParams> { - public: - base::test::ScopedFeatureList& scoped_feature_list() { - return scoped_feature_list_; - } - - TestingPrefServiceSimple* local_state() { return testing_local_state_.Get(); } - - private: - base::test::ScopedFeatureList scoped_feature_list_; - - base::test::TaskEnvironment task_environment_; - - ScopedTestingLocalState testing_local_state_{ - TestingBrowserProcess::GetGlobal()}; - - // Needed for synthetic trial checks to work. - ScopedMetricsServiceForSyntheticTrials testing_metrics_service_{ - TestingBrowserProcess::GetGlobal()}; -}; - -TEST_P(SearchEngineChoiceClientSideTrialTest, SetUpIfNeeded) { - { - auto scoped_channel_override = SearchEngineChoiceClientSideTrial:: - CreateScopedChannelOverrideForTesting(GetParam().channel); - base::MockEntropyProvider low_entropy_provider{GetParam().entropy_value}; - auto feature_list = std::make_unique<base::FeatureList>(); - - SearchEngineChoiceClientSideTrial::SetUpIfNeeded( - low_entropy_provider, feature_list.get(), local_state()); - - // Substitute the existing feature list with the one with field trial - // configurations we are testing, so we can check the assertions. - scoped_feature_list().InitWithFeatureList(std::move(feature_list)); - } - - EXPECT_EQ(GetParam().expect_feature_enabled, - base::FeatureList::IsEnabled(switches::kSearchEngineChoiceTrigger)); - - // Using explicit checks per branch here because the value of this property - // depends not only on the study state set in the test, but also on the - // hardcoded default value, which might be subject to cherry picks on branch. - if (GetParam().expect_feature_enabled) { - // Client-side study config explicitly sets it to true. - EXPECT_TRUE( - switches::kSearchEngineChoiceTriggerForTaggedProfilesOnly.Get()); - } else { - // Default value of the flag, independent from the feature state. - EXPECT_TRUE( - switches::kSearchEngineChoiceTriggerForTaggedProfilesOnly.Get()); - } - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) - EXPECT_TRUE(base::FieldTrialList::IsTrialActive("WaffleStudy")); - - std::string expected_group_name = - GetParam().expect_study_enabled - ? GetParam().expect_feature_enabled - ? "ClientSideEnabledForTaggedProfiles" - : "ClientSideDisabled" - : "Default"; - - EXPECT_EQ(local_state()->GetString(prefs::kSearchEnginesStudyGroup), - expected_group_name); -#else - // No group is assigned on other platforms and nothing is added to prefs. - EXPECT_TRUE( - local_state()->GetString(prefs::kSearchEnginesStudyGroup).empty()); -#endif -} - -// The test below only checks field trials for specific platforms, so the list -// is allowed to be empty. -GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST( - SearchEngineChoiceClientSideTrialTest); - -INSTANTIATE_TEST_SUITE_P( - , - SearchEngineChoiceClientSideTrialTest, - testing::Values( - // `entropy_value` makes the group be assigned according to the - // specified weight of each group and the order in which they are - // declared. So for a split at 33% enabled, 33% disabled, 33% default - // a .4 entropy value should select the "disabled" group. -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) - // Today, the feature is enabled by default, never enroll clients. - SearchEngineChoiceFieldTrialTestParams{ - .entropy_value = 0.01, - .channel = version_info::Channel::BETA, - .expect_study_enabled = false, - .expect_feature_enabled = false}, - SearchEngineChoiceFieldTrialTestParams{ - .entropy_value = 0.01, - .channel = version_info::Channel::STABLE, - .expect_study_enabled = false, - .expect_feature_enabled = false} -#elif BUILDFLAG(IS_CHROMEOS) - // Did not have a client-side field trial, so it's not bundled with the - // group above, but it's being enabled on a different schedule than the - // group below. - SearchEngineChoiceFieldTrialTestParams{ - .entropy_value = 0.01, - .channel = version_info::Channel::BETA, - .expect_study_enabled = false, - .expect_feature_enabled = false}, - SearchEngineChoiceFieldTrialTestParams{ - .entropy_value = 0.01, - .channel = version_info::Channel::STABLE, - .expect_study_enabled = false, - .expect_feature_enabled = false} -#elif BUILDFLAG(IS_WIN) - SearchEngineChoiceFieldTrialTestParams{ - .entropy_value = 0.01, - .channel = version_info::Channel::BETA, - // On other platforms we never enroll clients. - .expect_study_enabled = false, - .expect_feature_enabled = false}, - SearchEngineChoiceFieldTrialTestParams{ - .entropy_value = 0.01, - .channel = version_info::Channel::STABLE, - // On other platforms we never enroll clients. - .expect_study_enabled = false, - .expect_feature_enabled = false} -#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC) - ), - - [](const ::testing::TestParamInfo<SearchEngineChoiceFieldTrialTestParams>& - params) { - return base::StringPrintf( - "%02.0fpctEntropy%s", params.param.entropy_value * 100, - version_info::GetChannelString(params.param.channel).data()); - }); - -TEST_F(SearchEngineChoiceClientSideTrialTest, - SetUpIfNeeded_SkipsIfFeatureOverridden) { - { - base::MockEntropyProvider low_entropy_provider{0.01}; - auto feature_list = std::make_unique<base::FeatureList>(); - feature_list->RegisterExtraFeatureOverrides( - {{std::cref(switches::kSearchEngineChoiceTrigger), - base::FeatureList::OVERRIDE_ENABLE_FEATURE}}); - - SearchEngineChoiceClientSideTrial::SetUpIfNeeded( - low_entropy_provider, feature_list.get(), local_state()); - - // Substitute the existing feature list with the one with field trial - // configurations we are testing, so we can check the assertions. - scoped_feature_list().InitWithFeatureList(std::move(feature_list)); - } - - EXPECT_FALSE(base::FieldTrialList::IsTrialActive("WaffleStudy")); - EXPECT_FALSE(local_state()->HasPrefPath(prefs::kSearchEnginesStudyGroup)); -} - -TEST_F(SearchEngineChoiceClientSideTrialTest, - RegisterSyntheticTrials_ReadsPref) { - const char kStudyTestGroupName1[] = "group_name_1"; - EXPECT_FALSE(local_state()->HasPrefPath(prefs::kSearchEnginesStudyGroup)); - EXPECT_FALSE(variations::HasSyntheticTrial( - SearchEngineChoiceClientSideTrial::kSyntheticTrialName)); - - // `RegisterSyntheticTrials()` no-ops without some specific pref. - SearchEngineChoiceClientSideTrial::RegisterSyntheticTrials(); - EXPECT_FALSE(local_state()->HasPrefPath(prefs::kSearchEnginesStudyGroup)); - EXPECT_FALSE(variations::HasSyntheticTrial( - SearchEngineChoiceClientSideTrial::kSyntheticTrialName)); - - // With the pref, it will log it as synthetic trial group. - local_state()->SetString(prefs::kSearchEnginesStudyGroup, - kStudyTestGroupName1); - SearchEngineChoiceClientSideTrial::RegisterSyntheticTrials(); - EXPECT_TRUE(variations::HasSyntheticTrial( - SearchEngineChoiceClientSideTrial::kSyntheticTrialName)); - EXPECT_TRUE(variations::IsInSyntheticTrialGroup( - SearchEngineChoiceClientSideTrial::kSyntheticTrialName, - kStudyTestGroupName1)); -}
diff --git a/chrome/browser/segmentation_platform/segmentation_platform_config.cc b/chrome/browser/segmentation_platform/segmentation_platform_config.cc index 561fd1a0..3b26fb5 100644 --- a/chrome/browser/segmentation_platform/segmentation_platform_config.cc +++ b/chrome/browser/segmentation_platform/segmentation_platform_config.cc
@@ -97,7 +97,16 @@ #if BUILDFLAG(IS_ANDROID) bool IsEnabledContextualPageActions() { - return base::FeatureList::IsEnabled(features::kContextualPageActions); + if (!base::FeatureList::IsEnabled(features::kContextualPageActions)) + return false; + + bool is_price_tracking_enabled = base::FeatureList::IsEnabled( + features::kContextualPageActionPriceTracking); + + bool is_reader_mode_enabled = + base::FeatureList::IsEnabled(features::kContextualPageActionReaderMode); + + return is_price_tracking_enabled || is_reader_mode_enabled; } std::unique_ptr<Config> GetConfigForContextualPageActions(
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller.cc b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller.cc index 0aaffd7..60f2800 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller.cc +++ b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller.cc
@@ -17,6 +17,7 @@ session_id_(bound_session_params.session_id()), session_creation_time_(bound_session_credentials::TimestampToTime( bound_session_params.creation_time())), + refresh_url_(bound_session_params.refresh_url()), delegate_(delegate) { CHECK(!url_.is_empty()); CHECK(!bound_session_params.credentials().empty()); @@ -39,7 +40,7 @@ void BoundSessionCookieController::Initialize() {} -base::Time BoundSessionCookieController::min_cookie_expiration_time() { +base::Time BoundSessionCookieController::min_cookie_expiration_time() const { CHECK(!bound_cookies_info_.empty()); return base::ranges::min_element(bound_cookies_info_, {}, [](const auto& bound_cookie_info) { @@ -49,7 +50,7 @@ } chrome::mojom::BoundSessionThrottlerParamsPtr -BoundSessionCookieController::bound_session_throttler_params() { +BoundSessionCookieController::bound_session_throttler_params() const { return chrome::mojom::BoundSessionThrottlerParams::New( url().host(), url().path(), min_cookie_expiration_time()); }
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller.h b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller.h index 9b64d73c..2a7fa1c 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller.h +++ b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller.h
@@ -63,15 +63,17 @@ const GURL& url() const { return url_; } const std::string& session_id() const { return session_id_; } base::Time session_creation_time() const { return session_creation_time_; } - base::Time min_cookie_expiration_time(); - chrome::mojom::BoundSessionThrottlerParamsPtr - bound_session_throttler_params(); + const GURL& refresh_url() const { return refresh_url_; } + base::Time min_cookie_expiration_time() const; + chrome::mojom::BoundSessionThrottlerParamsPtr bound_session_throttler_params() + const; base::flat_set<std::string> bound_cookie_names() const; protected: const GURL url_; const std::string session_id_; const base::Time session_creation_time_; + const GURL refresh_url_; // Map from cookie name to cookie expiration time, it is expected to have two // elements the 1P and 3P cookies. // Cookie expiration time is reduced by threshold to guarantee cookie will be
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.cc b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.cc index 361650a3..1531bcb 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.cc +++ b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl.cc
@@ -233,19 +233,15 @@ std::unique_ptr<BoundSessionRefreshCookieFetcher> BoundSessionCookieControllerImpl::CreateRefreshCookieFetcher() const { - base::flat_set<std::string> cookie_names; - for (const auto& [cookie_name, _] : bound_cookies_info_) { - cookie_names.insert(cookie_name); - } - return refresh_cookie_fetcher_factory_for_testing_.is_null() ? std::make_unique<BoundSessionRefreshCookieFetcherImpl>( storage_partition_->GetURLLoaderFactoryForBrowserProcess(), - *session_binding_helper_, url_, std::move(cookie_names), - is_off_the_record_profile_, debug_info_) + *session_binding_helper_, refresh_url_, url_, + bound_cookie_names(), is_off_the_record_profile_, + debug_info_) : refresh_cookie_fetcher_factory_for_testing_.Run( storage_partition_->GetCookieManagerForBrowserProcess(), - url_, std::move(cookie_names)); + url_, bound_cookie_names()); } bool BoundSessionCookieControllerImpl::AreAllCookiesFresh() {
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl_unittest.cc b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl_unittest.cc index 8eea0c83..7076c6a 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl_unittest.cc +++ b/chrome/browser/signin/bound_session_credentials/bound_session_cookie_controller_impl_unittest.cc
@@ -38,6 +38,7 @@ #include "net/cookies/canonical_cookie.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "services/network/test/test_network_connection_tracker.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using bound_session_credentials::RotationDebugInfo; @@ -48,6 +49,7 @@ namespace { constexpr char k1PSIDTSCookieName[] = "__Secure-1PSIDTS"; constexpr char k3PSIDTSCookieName[] = "__Secure-3PSIDTS"; +constexpr char kSessionId[] = "test_session_id"; const base::TimeDelta kCookieExpirationThreshold = base::Seconds(15); const base::TimeDelta kCookieRefreshInterval = base::Minutes(2); @@ -107,7 +109,7 @@ network::mojom::ConnectionType::CONNECTION_WIFI); if (build_controller) { - BuildBoundSessionCookieController(); + BuildBoundSessionCookieController(CreateDefaultBoundSessionParams()); } } @@ -262,18 +264,9 @@ // This shouldn't be called more than once per test. The second controller // won't be able to register itself properly with `cookie_manager_`. - void BuildBoundSessionCookieController() { - std::vector<uint8_t> wrapped_key = GetWrappedKey(key_id_); - bound_session_credentials::BoundSessionParams bound_session_params; - bound_session_params.set_site("https://google.com"); - bound_session_params.set_session_id("test_session_id"); - bound_session_params.set_wrapped_key( - std::string(wrapped_key.begin(), wrapped_key.end())); - *bound_session_params.add_credentials() = - CreateCookieCredential(k1PSIDTSCookieName); - *bound_session_params.add_credentials() = - CreateCookieCredential(k3PSIDTSCookieName); - + void BuildBoundSessionCookieController( + const bound_session_credentials::BoundSessionParams& + bound_session_params) { bound_session_cookie_controller_ = std::make_unique<BoundSessionCookieControllerImpl>( unexportable_key_service_, &storage_partition_, @@ -307,6 +300,21 @@ task_environment_.RunUntilIdle(); } + bound_session_credentials::BoundSessionParams + CreateDefaultBoundSessionParams() { + std::vector<uint8_t> wrapped_key = GetWrappedKey(key_id_); + bound_session_credentials::BoundSessionParams bound_session_params; + bound_session_params.set_site("https://google.com"); + bound_session_params.set_session_id(kSessionId); + bound_session_params.set_wrapped_key( + std::string(wrapped_key.begin(), wrapped_key.end())); + *bound_session_params.add_credentials() = + CreateCookieCredential(k1PSIDTSCookieName); + *bound_session_params.add_credentials() = + CreateCookieCredential(k3PSIDTSCookieName); + return bound_session_params; + } + base::HistogramTester* histogram_tester() { return &histogram_tester_; } private: @@ -867,7 +875,7 @@ TEST_F(BoundSessionCookieControllerImplNoDefaultControllerTest, ScheduleCookieRefreshIfComingOnlineStartingOffline) { SetUpNetworkConnection(true, network::mojom::ConnectionType::CONNECTION_NONE); - BuildBoundSessionCookieController(); + BuildBoundSessionCookieController(CreateDefaultBoundSessionParams()); // Set up a situation where cookies are stale and there is no ongoing refresh. // `kServerTransientError` is used to complete the refresh request without @@ -884,6 +892,32 @@ EXPECT_FALSE(preemptive_cookie_refresh_timer()->IsRunning()); } +TEST_F(BoundSessionCookieControllerImplNoDefaultControllerTest, + SessionParameters) { + constexpr char kRefreshUrl[] = "https://accounts.google.com/refresh"; + constexpr base::Time kInitTime = + base::Time::FromMillisecondsSinceUnixEpoch(12345); + + bound_session_credentials::BoundSessionParams params = + CreateDefaultBoundSessionParams(); + params.set_refresh_url(kRefreshUrl); + *params.mutable_creation_time() = + bound_session_credentials::TimeToTimestamp(kInitTime); + BuildBoundSessionCookieController(params); + const BoundSessionCookieControllerImpl* const controller = + bound_session_cookie_controller(); + EXPECT_EQ(controller->url(), GURL("https://google.com")); + EXPECT_EQ(controller->session_id(), kSessionId); + EXPECT_EQ(controller->session_creation_time(), kInitTime); + EXPECT_EQ(controller->refresh_url(), GURL(kRefreshUrl)); + EXPECT_THAT( + controller->bound_cookie_names(), + testing::UnorderedElementsAre(k1PSIDTSCookieName, k3PSIDTSCookieName)); + auto throttler_params = controller->bound_session_throttler_params(); + EXPECT_EQ(throttler_params->domain, "google.com"); + EXPECT_EQ(throttler_params->path, "/"); +} + TEST_F(BoundSessionCookieControllerImplTest, NotNullCookieExpirationTimeIsReducedByThreshold) { EXPECT_TRUE(CompletePendingRefreshRequestIfAny());
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl.cc b/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl.cc index 0007164..2f5eab0 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl.cc +++ b/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl.cc
@@ -65,16 +65,20 @@ BoundSessionRefreshCookieFetcherImpl::BoundSessionRefreshCookieFetcherImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, SessionBindingHelper& session_binding_helper, + const GURL& refresh_url, const GURL& cookie_url, base::flat_set<std::string> cookie_names, bool is_off_the_record_profile, bound_session_credentials::RotationDebugInfo debug_info) : url_loader_factory_(std::move(url_loader_factory)), session_binding_helper_(session_binding_helper), + refresh_url_(refresh_url), expected_cookie_domain_(cookie_url), expected_cookie_names_(std::move(cookie_names)), is_off_the_record_profile_(is_off_the_record_profile), - debug_info_(std::move(debug_info)) {} + debug_info_(std::move(debug_info)) { + CHECK(refresh_url.is_empty() || refresh_url.is_valid()); +} BoundSessionRefreshCookieFetcherImpl::~BoundSessionRefreshCookieFetcherImpl() = default; @@ -147,7 +151,9 @@ })"); auto request = std::make_unique<network::ResourceRequest>(); - request->url = GaiaUrls::GetInstance()->rotate_bound_cookies_url(); + request->url = !refresh_url_.is_empty() + ? refresh_url_ + : GaiaUrls::GetInstance()->rotate_bound_cookies_url(); request->method = "GET"; if (sec_session_challenge_response) {
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl.h b/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl.h index 7381220..5653c5e 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl.h +++ b/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl.h
@@ -33,6 +33,7 @@ BoundSessionRefreshCookieFetcherImpl( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, SessionBindingHelper& session_binding_helper, + const GURL& refresh_url, const GURL& cookie_url, base::flat_set<std::string> cookie_names, bool is_off_the_record_profile, @@ -87,6 +88,11 @@ const scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_; const raw_ref<SessionBindingHelper> session_binding_helper_; + // Temporarily, this URL might be empty, meaning that the hardcoded URL must + // be used instead. + // TODO(b/325441004): require URL to be valid after migrating the storage. + const GURL refresh_url_; + // Used to check whether the refresh request has set the required cookie. // Otherwise, the request is considered a failure. const GURL expected_cookie_domain_;
diff --git a/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl_unittest.cc b/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl_unittest.cc index 983475c3..94e21a80 100644 --- a/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl_unittest.cc +++ b/chrome/browser/signin/bound_session_credentials/bound_session_refresh_cookie_fetcher_impl_unittest.cc
@@ -111,7 +111,7 @@ *unexportable_key_service_.GetWrappedKey(binding_key_id_), kSessionId); fetcher_ = std::make_unique<BoundSessionRefreshCookieFetcherImpl>( test_url_loader_factory_.GetSafeWeakWrapper(), *session_binding_helper_, - kGairaUrl, + /*refresh_url=*/GURL(), kGaiaUrl, base::flat_set<std::string>{k1PSIDTSCookieName, k3PSIDTSCookieName}, /*is_off_the_record_profile=*/false, bound_session_credentials::RotationDebugInfo()); @@ -119,7 +119,7 @@ } protected: - const GURL kGairaUrl = GURL("https://google.com/"); + const GURL kGaiaUrl = GURL("https://google.com/"); const std::string k1PSIDTSCookieName = "__Secure-1PSIDTS"; const std::string k3PSIDTSCookieName = "__Secure-3PSIDTS"; @@ -134,7 +134,7 @@ continue; } cookies_.emplace_back( - BoundSessionTestCookieManager::CreateCookie(kGairaUrl, cookie_name)); + BoundSessionTestCookieManager::CreateCookie(kGaiaUrl, cookie_name)); } } @@ -170,7 +170,7 @@ network::mojom::CookieAccessDetails::Type access_type) { std::vector<network::mojom::CookieAccessDetailsPtr> cookie_access_details; cookie_access_details.emplace_back(network::mojom::CookieAccessDetails::New( - access_type, kGairaUrl, url::Origin(), net::SiteForCookies(), + access_type, kGaiaUrl, url::Origin(), net::SiteForCookies(), CreateReportedCookies(cookies_), std::nullopt, /*count=*/1, /*is_ad_tagged=*/false, net::CookieSettingOverrides())); fetcher_->OnCookiesAccessed(std::move(cookie_access_details)); @@ -249,6 +249,32 @@ /*expect_assertion_was_generated_count=*/0); } +TEST_F(BoundSessionRefreshCookieFetcherImplTest, SuccessNonEmptyRefreshUrl) { + const GURL refresh_url("https://security.google.com/CheckBinding"); + fetcher_ = std::make_unique<BoundSessionRefreshCookieFetcherImpl>( + test_url_loader_factory_.GetSafeWeakWrapper(), *session_binding_helper_, + refresh_url, kGaiaUrl, + base::flat_set<std::string>{k1PSIDTSCookieName, k3PSIDTSCookieName}, + /*is_off_the_record_profile=*/false, + bound_session_credentials::RotationDebugInfo()); + RefreshTestFuture future; + fetcher_->Start(future.GetCallback()); + + EXPECT_EQ(test_url_loader_factory_.total_requests(), 1u); + network::TestURLLoaderFactory::PendingRequest* pending_request = + test_url_loader_factory_.GetPendingRequest(0); + EXPECT_EQ(pending_request->request.url, refresh_url); + + SimulateOnCookiesAccessed(network::mojom::CookieAccessDetails::Type::kChange); + test_url_loader_factory_.SimulateResponseForPendingRequest( + pending_request->request.url.spec(), ""); + + EXPECT_TRUE(future.IsReady()); + EXPECT_EQ(future.Get(), Result::kSuccess); + VerifyMetricsRecorded(Result::kSuccess, + /*expect_assertion_was_generated_count=*/0); +} + TEST_F(BoundSessionRefreshCookieFetcherImplTest, SuccessCookiesReportedDelayed) { RefreshTestFuture future; @@ -509,7 +535,7 @@ unexportable_key_service_, wrapped_key, kSessionId); fetcher_ = std::make_unique<BoundSessionRefreshCookieFetcherImpl>( test_url_loader_factory_.GetSafeWeakWrapper(), *session_binding_helper_, - kGairaUrl, + /*refresh_url=*/GURL(), kGaiaUrl, base::flat_set<std::string>{k1PSIDTSCookieName, k3PSIDTSCookieName}, /*is_off_the_record_profile_=*/false, bound_session_credentials::RotationDebugInfo()); @@ -575,7 +601,7 @@ fetcher_ = std::make_unique<BoundSessionRefreshCookieFetcherImpl>( test_url_loader_factory_.GetSafeWeakWrapper(), *session_binding_helper_, - kGairaUrl, + /*refresh_url=*/GURL(), kGaiaUrl, base::flat_set<std::string>{k1PSIDTSCookieName, k3PSIDTSCookieName}, /*is_off_the_record_profile_=*/false, info); RefreshTestFuture future;
diff --git a/chrome/browser/signin/dice_response_handler.cc b/chrome/browser/signin/dice_response_handler.cc index bd982d1..b8f297c 100644 --- a/chrome/browser/signin/dice_response_handler.cc +++ b/chrome/browser/signin/dice_response_handler.cc
@@ -550,13 +550,28 @@ identity_manager_->PickAccountIdForAccount(gaia_id, email); bool is_new_account = !identity_manager_->HasAccountWithRefreshToken(account_id); + // If this is a reauth, do not update the access point. - identity_manager_->GetAccountsMutator()->AddOrUpdateAccount( - gaia_id, email, refresh_token, is_under_advanced_protection, + signin_metrics::AccessPoint access_point = is_new_account ? token_fetcher->delegate()->GetAccessPoint() - : signin_metrics::AccessPoint::ACCESS_POINT_UNKNOWN, - signin_metrics::SourceForRefreshTokenOperation:: - kDiceResponseHandler_Signin + : signin_metrics::AccessPoint::ACCESS_POINT_UNKNOWN; + // Specifically set the token operation source in case the error was updated + // through a sign in from a password sign in promo, as this will indicate + // whether to move the password to account storage or not. + // TODO(crbug.com/339157240): Change the way this is implemented to not use + // SourceForRefreshTokenOperation as an indicator of the reauthentication + // source. + signin_metrics::SourceForRefreshTokenOperation token_operation_source = + token_fetcher->delegate()->GetAccessPoint() == + signin_metrics::AccessPoint::ACCESS_POINT_PASSWORD_BUBBLE + ? signin_metrics::SourceForRefreshTokenOperation:: + kDiceResponseHandler_PasswordPromoSignin + : signin_metrics::SourceForRefreshTokenOperation:: + kDiceResponseHandler_Signin; + + identity_manager_->GetAccountsMutator()->AddOrUpdateAccount( + gaia_id, email, refresh_token, is_under_advanced_protection, access_point, + token_operation_source #if BUILDFLAG(ENABLE_BOUND_SESSION_CREDENTIALS) , wrapped_binding_key
diff --git a/chrome/browser/supervised_user/supervised_user_test_util.cc b/chrome/browser/supervised_user/supervised_user_test_util.cc index cc79833c..cc761cb 100644 --- a/chrome/browser/supervised_user/supervised_user_test_util.cc +++ b/chrome/browser/supervised_user/supervised_user_test_util.cc
@@ -34,10 +34,6 @@ void SetSupervisedUserExtensionsMayRequestPermissionsPref(Profile* profile, bool enabled) { - // TODO(crbug/1024646): kSupervisedUserExtensionsMayRequestPermissions is - // currently set indirectly by setting geolocation requests. Update Kids - // Management server to set a new bit for extension permissions and update - // this setter function. supervised_user::SupervisedUserSettingsService* settings_service = SupervisedUserSettingsServiceFactory::GetInstance()->GetForKey( profile->GetProfileKey());
diff --git a/chrome/browser/supervised_user/url_filter_interactive_uitest.cc b/chrome/browser/supervised_user/url_filter_interactive_uitest.cc index adf62be1..e1c8aee 100644 --- a/chrome/browser/supervised_user/url_filter_interactive_uitest.cc +++ b/chrome/browser/supervised_user/url_filter_interactive_uitest.cc
@@ -131,7 +131,8 @@ } }; -IN_PROC_BROWSER_TEST_P(UrlFilterUiTest, ParentBlocksPage) { +// TODO(https://crbug.com/328036610): fails on win-live-tests-tester-rel +IN_PROC_BROWSER_TEST_P(UrlFilterUiTest, DISABLED_ParentBlocksPage) { DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kChildElementId); DEFINE_LOCAL_STATE_IDENTIFIER_VALUE(BrowserState::Observer, kSetSafeSitesStateObserverId); @@ -167,7 +168,8 @@ // Sanity test, if it fails it means that resetting the test state is not // functioning properly. -IN_PROC_BROWSER_TEST_P(UrlFilterUiTest, ClearFamilyLinkSettings) { +// TODO(https://crbug.com/328036610): fails on win-live-tests-tester-rel +IN_PROC_BROWSER_TEST_P(UrlFilterUiTest, DISABLED_ClearFamilyLinkSettings) { DEFINE_LOCAL_STATE_IDENTIFIER_VALUE(BrowserState::Observer, kObserverId); TurnOnSyncFor(head_of_household()); @@ -178,7 +180,9 @@ BrowserState::Reset())); } -IN_PROC_BROWSER_TEST_P(UrlFilterUiTest, ParentAllowsPageBlockedBySafeSites) { +// TODO(https://crbug.com/328036610): fails on win-live-tests-tester-rel +IN_PROC_BROWSER_TEST_P(UrlFilterUiTest, + DISABLED_ParentAllowsPageBlockedBySafeSites) { DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kChildElementId); DEFINE_LOCAL_STATE_IDENTIFIER_VALUE(BrowserState::Observer, kDefineStateObserverId);
diff --git a/chrome/browser/support_tool/policy_data_collector_browsertest.cc b/chrome/browser/support_tool/policy_data_collector_browsertest.cc index 52aae532..bb226184 100644 --- a/chrome/browser/support_tool/policy_data_collector_browsertest.cc +++ b/chrome/browser/support_tool/policy_data_collector_browsertest.cc
@@ -193,13 +193,8 @@ &mixin_host_, ash::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, - ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), - this, - /*should_launch_browser=*/true, - AccountId::FromUserEmailGaiaId(policy::PolicyBuilder::kFakeUsername, - policy::PolicyBuilder::kFakeGaiaId)}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kManaged}; // Use a temporary directory to store data collector output. base::ScopedTempDir temp_dir_; };
diff --git a/chrome/browser/support_tool/signin_data_collector_browsertest.cc b/chrome/browser/support_tool/signin_data_collector_browsertest.cc index fc773b2..9ed505a1 100644 --- a/chrome/browser/support_tool/signin_data_collector_browsertest.cc +++ b/chrome/browser/support_tool/signin_data_collector_browsertest.cc
@@ -88,13 +88,8 @@ protected: ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, - ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), - this, - true, - AccountId::FromUserEmailGaiaId(policy::PolicyBuilder::kFakeUsername, - "0123456789")}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kManaged}; base::ScopedTempDir temp_dir_; scoped_refptr<base::SequencedTaskRunner> task_runner_for_redaction_tool_;
diff --git a/chrome/browser/tab_resumption/BUILD.gn b/chrome/browser/tab_resumption/BUILD.gn index 027cec0..7b6dd2c 100644 --- a/chrome/browser/tab_resumption/BUILD.gn +++ b/chrome/browser/tab_resumption/BUILD.gn
@@ -97,6 +97,7 @@ "junit/src/org/chromium/chrome/browser/tab_resumption/MixedTabResumptionDataProviderTest.java", "junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleEnablementUnitTest.java", "junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMediatorUnitTest.java", + "junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMetricsUtilsUnitTest.java", "junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleSuggestionsUnitTest.java", "junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleUtilsUnitTest.java", "junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleViewUnitTest.java",
diff --git a/chrome/browser/tab_resumption/java/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMetricsUtils.java b/chrome/browser/tab_resumption/java/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMetricsUtils.java index e1e04a1..56da186 100644 --- a/chrome/browser/tab_resumption/java/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMetricsUtils.java +++ b/chrome/browser/tab_resumption/java/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMetricsUtils.java
@@ -81,6 +81,9 @@ "MagicStack.Clank.TabResumption.ModuleShowConfig"; static final String HISTOGRAM_STABILITY_DELAY = "MagicStack.Clank.TabResumption.StabilityDelay"; + static final String HISTOGRAM_IS_SALIENT_IMAGE_AVAILABLE = + "MagicStack.Clank.TabResumption.IsSalientImageAvailable"; + /** Maps specification of a clicked tile to a ClickInfo for logging. */ static @ClickInfo int computeClickInfo(@ModuleShowConfig int moduleShowConfig, int tileIndex) { switch (moduleShowConfig) { @@ -154,4 +157,9 @@ // moot. This timeout is well below the max bucket of 10 seconds. RecordHistogram.recordTimesHistogram(HISTOGRAM_STABILITY_DELAY, stabilityDelay); } + + /** Records whether a salient image fetch attempt was successful. */ + static void recordSalientImageAvailability(boolean isAvailable) { + RecordHistogram.recordBooleanHistogram(HISTOGRAM_IS_SALIENT_IMAGE_AVAILABLE, isAvailable); + } }
diff --git a/chrome/browser/tab_resumption/java/src/org/chromium/chrome/browser/tab_resumption/TabResumptionTileContainerView.java b/chrome/browser/tab_resumption/java/src/org/chromium/chrome/browser/tab_resumption/TabResumptionTileContainerView.java index 40f3fdf..549f4c9 100644 --- a/chrome/browser/tab_resumption/java/src/org/chromium/chrome/browser/tab_resumption/TabResumptionTileContainerView.java +++ b/chrome/browser/tab_resumption/java/src/org/chromium/chrome/browser/tab_resumption/TabResumptionTileContainerView.java
@@ -220,14 +220,16 @@ boolean useSalientImage) { UrlImageCallback callback = (Bitmap bitmap) -> { - onImageAvailable(bitmap, tileView, /* isSalientImage= */ false); + onImageAvailable( + bitmap, tileView, useSalientImage, /* isSalientImage= */ false); }; if (useSalientImage) { urlImageProvider.fetchSalientImageWithFallback( entry.url, isSingle, (bitmap) -> { - onImageAvailable(bitmap, tileView, /* isSalientImage= */ true); + onImageAvailable( + bitmap, tileView, useSalientImage, /* isSalientImage= */ true); }, callback); } else { @@ -240,16 +242,23 @@ * * @param bitmap The image bitmap returned. * @param tileView The tile view to show the image. + * @param useSalientImage Whether a salient image is requested. * @param isSalientImage Whether the returned image is a salient image. */ private void onImageAvailable( - Bitmap bitmap, TabResumptionTileView tileView, boolean isSalientImage) { + Bitmap bitmap, + TabResumptionTileView tileView, + boolean useSalientImage, + boolean isSalientImage) { Resources res = getContext().getResources(); Drawable urlDrawable = new BitmapDrawable(res, bitmap); tileView.setImageDrawable(urlDrawable); if (isSalientImage) { tileView.updateForSalientImage(); } + if (useSalientImage) { + TabResumptionModuleMetricsUtils.recordSalientImageAvailability(isSalientImage); + } } /** Binds the click handler with an associated URL. */
diff --git a/chrome/browser/tab_resumption/junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMetricsUtilsUnitTest.java b/chrome/browser/tab_resumption/junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMetricsUtilsUnitTest.java new file mode 100644 index 0000000..a3e1f6a --- /dev/null +++ b/chrome/browser/tab_resumption/junit/src/org/chromium/chrome/browser/tab_resumption/TabResumptionModuleMetricsUtilsUnitTest.java
@@ -0,0 +1,35 @@ +// Copyright 2024 The Chromium Authors +// 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.tab_resumption; + +import androidx.test.filters.SmallTest; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.annotation.Config; + +import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.base.test.util.HistogramWatcher; + +/** Unit tests for {@link TabResumptionModuleMetricsUtils}. */ +@RunWith(BaseRobolectricTestRunner.class) +@Config(manifest = Config.NONE) +public class TabResumptionModuleMetricsUtilsUnitTest { + @Test + @SmallTest + public void testRecordSalientImageAvailability() { + String histogramName = "MagicStack.Clank.TabResumption.IsSalientImageAvailable"; + + var histogramWatcher = + HistogramWatcher.newBuilder().expectBooleanRecord(histogramName, true).build(); + TabResumptionModuleMetricsUtils.recordSalientImageAvailability(true); + histogramWatcher.assertExpected(); + + histogramWatcher = + HistogramWatcher.newBuilder().expectBooleanRecord(histogramName, false).build(); + TabResumptionModuleMetricsUtils.recordSalientImageAvailability(false); + histogramWatcher.assertExpected(); + } +}
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 25ada358..8e615e50 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -4424,7 +4424,6 @@ "signin/chrome_signout_confirmation_prompt.h", "signin/dice_web_signin_interceptor_delegate.cc", "signin/dice_web_signin_interceptor_delegate.h", - "startup/first_run_service_dice_statics.cc", "views/profiles/dice_web_signin_interception_bubble_view.cc", "views/profiles/dice_web_signin_interception_bubble_view.h", "views/profiles/first_run_flow_controller_dice.cc",
diff --git a/chrome/browser/ui/android/signin/java/src/org/chromium/chrome/browser/ui/signin/SyncPromoController.java b/chrome/browser/ui/android/signin/java/src/org/chromium/chrome/browser/ui/signin/SyncPromoController.java index 17b050b..2cddfb4 100644 --- a/chrome/browser/ui/android/signin/java/src/org/chromium/chrome/browser/ui/signin/SyncPromoController.java +++ b/chrome/browser/ui/android/signin/java/src/org/chromium/chrome/browser/ui/signin/SyncPromoController.java
@@ -114,6 +114,8 @@ private static final int NTP_SYNC_PROMO_INCREASE_SHOW_COUNT_AFTER_MINUTE = 30; private static final String SYNC_ANDROID_NTP_PROMO_MAX_IMPRESSIONS = "SyncAndroidNTPPromoMaxImpressions"; + private static final Set<Integer> HISTORY_SYNC_DEDICATED_ACCESS_POINTS = + Set.of(SigninAccessPoint.RECENT_TABS); @VisibleForTesting static final String GMAIL_DOMAIN = "gmail.com"; /** Strings used for promo shown count histograms. */ @@ -203,10 +205,6 @@ } private static boolean canShowSettingsPromo() { - if (ChromeFeatureList.isEnabled( - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS)) { - return false; - } SharedPreferencesManager preferencesManager = ChromeSharedPreferences.getInstance(); boolean isPromoDismissed = preferencesManager.readBoolean( @@ -263,14 +261,8 @@ mImpressionUserActionName = "Signin_Impression_FromBookmarkManager"; mSyncPromoDismissedPreferenceTracker = ChromePreferenceKeys.SIGNIN_PROMO_BOOKMARKS_DECLINED; - if (ChromeFeatureList.isEnabled( - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS)) { - mTitleStringId = R.string.signin_promo_title_bookmarks; - mDescriptionStringId = R.string.signin_promo_description_bookmarks; - } else { - mTitleStringId = R.string.sync_promo_title_bookmarks; - mDescriptionStringId = R.string.sync_promo_description_bookmarks; - } + mTitleStringId = R.string.sync_promo_title_bookmarks; + mDescriptionStringId = R.string.sync_promo_description_bookmarks; mHistoryOptInMode = SigninAndHistoryOptInCoordinator.HistoryOptInMode.NONE; // TODO(b/332704829): Move delegate creation outside of this constructor. mDelegate = @@ -425,17 +417,6 @@ } private boolean canShowBookmarkPromo() { - if (ChromeFeatureList.isEnabled( - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS)) { - assert SyncFeatureMap.isEnabled( - SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE); - if (IdentityServicesProvider.get() - .getIdentityManager(mProfile) - .hasPrimaryAccount(ConsentLevel.SIGNIN)) { - return false; - } - } - SyncService syncService = SyncServiceFactory.getForProfile(mProfile); if (SyncFeatureMap.isEnabled(SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE) && syncService @@ -616,18 +597,8 @@ view.getTitle().setText(mTitleStringId); view.getDescription().setText(mDescriptionStringId); - IdentityManager identityManager = - IdentityServicesProvider.get().getIdentityManager(mProfile); - SigninManager signinManager = IdentityServicesProvider.get().getSigninManager(mProfile); - List<CoreAccountInfo> accounts = - AccountManagerFacadeProvider.getInstance().getCoreAccountInfos().getResult(); - PrefService prefService = UserPrefs.get(mProfile); - boolean shouldLaunchSigninFlow = - shouldLaunchSigninFlow( - mAccessPoint, identityManager, signinManager, accounts, prefService); view.getPrimaryButton().setText(mDelegate.getTextForPrimaryButton(context, null)); - view.getPrimaryButton() - .setOnClickListener(v -> signinWithNewAccount(context, shouldLaunchSigninFlow)); + view.getPrimaryButton().setOnClickListener(v -> signinWithNewAccount(context)); view.getSecondaryButton().setVisibility(View.GONE); } @@ -647,17 +618,20 @@ List<CoreAccountInfo> accounts = AccountManagerFacadeProvider.getInstance().getCoreAccountInfos().getResult(); PrefService prefService = UserPrefs.get(mProfile); - boolean shouldLaunchSigninFlow = - shouldLaunchSigninFlow( + boolean launchBookmarksSigninFlow = + shouldLaunchBookmarksSigninFlow( mAccessPoint, identityManager, signinManager, accounts, prefService); - if (!ChromeFeatureList.isEnabled(ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS) - && shouldLaunchSigninFlow - && mAccessPoint == SigninAccessPoint.BOOKMARK_MANAGER) { + if (launchBookmarksSigninFlow) { view.getDescription().setText(R.string.signin_promo_description_bookmarks); } // The bookmarks manager has different conditions for displaying the new flow. view.getPrimaryButton() - .setOnClickListener(v -> signinWithDefaultAccount(context, shouldLaunchSigninFlow)); + .setOnClickListener( + v -> + signinWithDefaultAccount( + context, + launchBookmarksSigninFlow + || shouldLaunchDedicatedSigninAndHistorySyncFlow())); view.getPrimaryButton().setText(mDelegate.getTextForPrimaryButton(context, mProfileData)); if (identityManager.hasPrimaryAccount(ConsentLevel.SIGNIN)) { view.getSecondaryButton().setVisibility(View.GONE); @@ -671,34 +645,37 @@ view.getSecondaryButton().setText(R.string.signin_promo_choose_another_account); view.getSecondaryButton() .setOnClickListener( - v -> signinWithNotDefaultAccount(context, shouldLaunchSigninFlow)); + v -> + signinWithNotDefaultAccount( + context, + launchBookmarksSigninFlow + || shouldLaunchDedicatedSigninAndHistorySyncFlow())); view.getSecondaryButton().setVisibility(View.VISIBLE); } } - private void signinWithNewAccount(Context context, boolean launchSigninFlow) { + private void signinWithNewAccount(Context context) { recordShowCountHistogram(UserAction.CONTINUED); - if (launchSigninFlow) { - if (mAccessPoint == SigninAccessPoint.RECENT_TABS) { - mSigninAndHistoryOptInActivityLauncher.launchActivityForHistorySyncDedicatedFlow( - context, - mProfile, - mBottomSheetStrings, - SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, - SigninAndHistoryOptInCoordinator.WithAccountSigninMode - .DEFAULT_ACCOUNT_BOTTOM_SHEET, - mAccessPoint); - } else { - mSigninAndHistoryOptInActivityLauncher.launchActivityIfAllowed( - context, - mProfile, - mBottomSheetStrings, - SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, - SigninAndHistoryOptInCoordinator.WithAccountSigninMode - .DEFAULT_ACCOUNT_BOTTOM_SHEET, - mHistoryOptInMode, - mAccessPoint); - } + if (shouldLaunchDedicatedSigninAndHistorySyncFlow()) { + mSigninAndHistoryOptInActivityLauncher.launchActivityForHistorySyncDedicatedFlow( + context, + mProfile, + mBottomSheetStrings, + SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, + SigninAndHistoryOptInCoordinator.WithAccountSigninMode + .DEFAULT_ACCOUNT_BOTTOM_SHEET, + mAccessPoint); + } else if (ChromeFeatureList.isEnabled( + ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS)) { + mSigninAndHistoryOptInActivityLauncher.launchActivityIfAllowed( + context, + mProfile, + mBottomSheetStrings, + SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, + SigninAndHistoryOptInCoordinator.WithAccountSigninMode + .DEFAULT_ACCOUNT_BOTTOM_SHEET, + mHistoryOptInMode, + mAccessPoint); } else { mSyncConsentActivityLauncher.launchActivityForPromoAddAccountFlow( context, mAccessPoint); @@ -707,27 +684,25 @@ private void signinWithDefaultAccount(Context context, boolean launchSigninFlow) { recordShowCountHistogram(UserAction.CONTINUED); - if (launchSigninFlow) { - if (mAccessPoint == SigninAccessPoint.RECENT_TABS) { - mSigninAndHistoryOptInActivityLauncher.launchActivityForHistorySyncDedicatedFlow( - context, - mProfile, - mBottomSheetStrings, - SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, - SigninAndHistoryOptInCoordinator.WithAccountSigninMode - .DEFAULT_ACCOUNT_BOTTOM_SHEET, - mAccessPoint); - } else { - mSigninAndHistoryOptInActivityLauncher.launchActivityIfAllowed( - context, - mProfile, - mBottomSheetStrings, - SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, - SigninAndHistoryOptInCoordinator.WithAccountSigninMode - .DEFAULT_ACCOUNT_BOTTOM_SHEET, - mHistoryOptInMode, - mAccessPoint); - } + if (shouldLaunchDedicatedSigninAndHistorySyncFlow()) { + mSigninAndHistoryOptInActivityLauncher.launchActivityForHistorySyncDedicatedFlow( + context, + mProfile, + mBottomSheetStrings, + SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, + SigninAndHistoryOptInCoordinator.WithAccountSigninMode + .DEFAULT_ACCOUNT_BOTTOM_SHEET, + mAccessPoint); + } else if (launchSigninFlow) { + mSigninAndHistoryOptInActivityLauncher.launchActivityIfAllowed( + context, + mProfile, + mBottomSheetStrings, + SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, + SigninAndHistoryOptInCoordinator.WithAccountSigninMode + .DEFAULT_ACCOUNT_BOTTOM_SHEET, + mHistoryOptInMode, + mAccessPoint); } else { mSyncConsentActivityLauncher.launchActivityForPromoDefaultFlow( context, mAccessPoint, mProfileData.getAccountEmail()); @@ -736,27 +711,25 @@ private void signinWithNotDefaultAccount(Context context, boolean launchSigninFlow) { recordShowCountHistogram(UserAction.CONTINUED); - if (launchSigninFlow) { - if (mAccessPoint == SigninAccessPoint.RECENT_TABS) { - mSigninAndHistoryOptInActivityLauncher.launchActivityForHistorySyncDedicatedFlow( - context, - mProfile, - mBottomSheetStrings, - SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, - SigninAndHistoryOptInCoordinator.WithAccountSigninMode - .CHOOSE_ACCOUNT_BOTTOM_SHEET, - mAccessPoint); - } else { - mSigninAndHistoryOptInActivityLauncher.launchActivityIfAllowed( - context, - mProfile, - mBottomSheetStrings, - SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, - SigninAndHistoryOptInCoordinator.WithAccountSigninMode - .CHOOSE_ACCOUNT_BOTTOM_SHEET, - mHistoryOptInMode, - mAccessPoint); - } + if (shouldLaunchDedicatedSigninAndHistorySyncFlow()) { + mSigninAndHistoryOptInActivityLauncher.launchActivityForHistorySyncDedicatedFlow( + context, + mProfile, + mBottomSheetStrings, + SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, + SigninAndHistoryOptInCoordinator.WithAccountSigninMode + .CHOOSE_ACCOUNT_BOTTOM_SHEET, + mAccessPoint); + } else if (launchSigninFlow) { + mSigninAndHistoryOptInActivityLauncher.launchActivityIfAllowed( + context, + mProfile, + mBottomSheetStrings, + SigninAndHistoryOptInCoordinator.NoAccountSigninMode.ADD_ACCOUNT, + SigninAndHistoryOptInCoordinator.WithAccountSigninMode + .CHOOSE_ACCOUNT_BOTTOM_SHEET, + mHistoryOptInMode, + mAccessPoint); } else { mSyncConsentActivityLauncher.launchActivityForPromoChooseAccountFlow( context, mAccessPoint, mProfileData.getAccountEmail()); @@ -801,6 +774,12 @@ RecordUserAction.record(mImpressionUserActionName); } + private boolean shouldLaunchDedicatedSigninAndHistorySyncFlow() { + return ChromeFeatureList.isEnabled( + ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS) + && HISTORY_SYNC_DEDICATED_ACCESS_POINTS.contains(mAccessPoint); + } + public static void setPrefSigninPromoDeclinedBookmarksForTests(boolean isDeclined) { ChromeSharedPreferences.getInstance() .writeBoolean(ChromePreferenceKeys.SIGNIN_PROMO_BOOKMARKS_DECLINED, isDeclined); @@ -811,19 +790,12 @@ } @VisibleForTesting - static boolean shouldLaunchSigninFlow( + static boolean shouldLaunchBookmarksSigninFlow( @SigninAccessPoint int accessPoint, IdentityManager identityManager, SigninManager signinManager, @Nullable List<CoreAccountInfo> accounts, PrefService prefService) { - if (ChromeFeatureList.isEnabled( - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS)) { - assert SyncFeatureMap.isEnabled( - SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE); - return true; - } - if (!SyncFeatureMap.isEnabled(SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE)) { return false; }
diff --git a/chrome/browser/ui/android/signin/junit/src/org/chromium/chrome/browser/ui/signin/SyncPromoControllerTest.java b/chrome/browser/ui/android/signin/junit/src/org/chromium/chrome/browser/ui/signin/SyncPromoControllerTest.java index 111fb06..0dfd5d9 100644 --- a/chrome/browser/ui/android/signin/junit/src/org/chromium/chrome/browser/ui/signin/SyncPromoControllerTest.java +++ b/chrome/browser/ui/android/signin/junit/src/org/chromium/chrome/browser/ui/signin/SyncPromoControllerTest.java
@@ -57,7 +57,6 @@ @DisableFeatures({ ChromeFeatureList.FORCE_DISABLE_EXTENDED_SYNC_PROMOS, ChromeFeatureList.SYNC_ANDROID_LIMIT_NTP_PROMO_IMPRESSIONS, - ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS, }) @EnableFeatures(SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE) public class SyncPromoControllerTest { @@ -496,31 +495,15 @@ } @Test - @EnableFeatures(ChromeFeatureList.REPLACE_SYNC_PROMOS_WITH_SIGN_IN_PROMOS) - public void shouldLaunchBookmarksSigninFlowReturnsTrue_UnoFeatureEnabled() { + @EnableFeatures(SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE) + public void shouldLaunchBookmarksSigninFlowReturnsTrue() { doReturn(false).when(mIdentityManager).hasPrimaryAccount(ConsentLevel.SIGNIN); doReturn(SyncPromoController.GMAIL_DOMAIN) .when(mSigninManager) .extractDomainName(anyString()); Assert.assertTrue( - SyncPromoController.shouldLaunchSigninFlow( - SigninAccessPoint.BOOKMARK_MANAGER, - mIdentityManager, - mSigninManager, - List.of(mAccountManagerTestRule.addAccount("test@gmail.com")), - mPrefService)); - } - - @Test - public void shouldLaunchBookmarksSigninFlowReturnsTrue_AccountStorageFeatureEnabled() { - doReturn(false).when(mIdentityManager).hasPrimaryAccount(ConsentLevel.SIGNIN); - doReturn(SyncPromoController.GMAIL_DOMAIN) - .when(mSigninManager) - .extractDomainName(anyString()); - - Assert.assertTrue( - SyncPromoController.shouldLaunchSigninFlow( + SyncPromoController.shouldLaunchBookmarksSigninFlow( SigninAccessPoint.BOOKMARK_MANAGER, mIdentityManager, mSigninManager, @@ -530,14 +513,14 @@ @Test @DisableFeatures(SyncFeatureMap.ENABLE_BOOKMARK_FOLDERS_FOR_ACCOUNT_STORAGE) - public void shouldLaunchBookmarksSigninFlowReturnsFalse_AccountStorageFeatureDisabled() { + public void shouldLaunchBookmarksSigninFlowReturnsFalse_FeatureDisabled() { doReturn(false).when(mIdentityManager).hasPrimaryAccount(ConsentLevel.SIGNIN); doReturn(SyncPromoController.GMAIL_DOMAIN) .when(mSigninManager) .extractDomainName(anyString()); Assert.assertFalse( - SyncPromoController.shouldLaunchSigninFlow( + SyncPromoController.shouldLaunchBookmarksSigninFlow( SigninAccessPoint.BOOKMARK_MANAGER, mIdentityManager, mSigninManager, @@ -554,7 +537,7 @@ .extractDomainName(anyString()); Assert.assertFalse( - SyncPromoController.shouldLaunchSigninFlow( + SyncPromoController.shouldLaunchBookmarksSigninFlow( SigninAccessPoint.NTP_FEED_TOP_PROMO, mIdentityManager, mSigninManager, @@ -571,7 +554,7 @@ .extractDomainName(anyString()); Assert.assertFalse( - SyncPromoController.shouldLaunchSigninFlow( + SyncPromoController.shouldLaunchBookmarksSigninFlow( SigninAccessPoint.BOOKMARK_MANAGER, mIdentityManager, mSigninManager, @@ -589,7 +572,7 @@ .extractDomainName(anyString()); Assert.assertFalse( - SyncPromoController.shouldLaunchSigninFlow( + SyncPromoController.shouldLaunchBookmarksSigninFlow( SigninAccessPoint.BOOKMARK_MANAGER, mIdentityManager, mSigninManager, @@ -604,7 +587,7 @@ doReturn("nongmail.com").when(mSigninManager).extractDomainName(anyString()); Assert.assertFalse( - SyncPromoController.shouldLaunchSigninFlow( + SyncPromoController.shouldLaunchBookmarksSigninFlow( SigninAccessPoint.BOOKMARK_MANAGER, mIdentityManager, mSigninManager, @@ -621,7 +604,7 @@ .extractDomainName(anyString()); Assert.assertFalse( - SyncPromoController.shouldLaunchSigninFlow( + SyncPromoController.shouldLaunchBookmarksSigninFlow( SigninAccessPoint.BOOKMARK_MANAGER, mIdentityManager, mSigninManager, @@ -638,7 +621,7 @@ .extractDomainName(anyString()); Assert.assertFalse( - SyncPromoController.shouldLaunchSigninFlow( + SyncPromoController.shouldLaunchBookmarksSigninFlow( SigninAccessPoint.BOOKMARK_MANAGER, mIdentityManager, mSigninManager,
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index 3f007c8..a3606953 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -218,8 +218,8 @@ </message> <!-- TODO(b/326574743): Revisit string and mark it as translateable.--> - <message name="IDS_PREFS_CONTROL_YOUR_DATA" desc='Title of "Control your data and accounts" section of preferences. [CHAR_LIMIT=32]' translateable="false"> - Control your data & accounts + <message name="IDS_ACCOUNT_ADVANCED_HEADER" desc="Heading of a section with settings related to the user's Google Account and data. [CHAR_LIMIT=32]" translateable="false"> + Control your data & account </message> <!-- Notification channels --> @@ -3414,9 +3414,6 @@ <message name="IDS_SYNC_PROMO_DESCRIPTION_BOOKMARKS" desc="This string is the body of a card that appears when the user opens Chrome's bookmarks; the user may be signed in to Chrome, but isn't syncing their Chrome data. The headline above this string is 'Get all your bookmarks'. There's no character limit but try to keep the translation under 120 characters." meaning="This message means that the user can get the bookmarks from their computer on their phone, and their phone's bookmarks on their computer. We want users to read this card and tap the 'Continue' button and turn on sync. The tone should be inviting."> Sync to get your bookmarks from your other devices </message> - <message name="IDS_SIGNIN_PROMO_TITLE_BOOKMARKS" desc="This string is the headline of a card that appears when the user opens Chrome's bookmarks; the user may be signed in to Chrome, but isn't syncing their Chrome data. The line below this string is 'Sync to get your bookmarks from your other devices'. [CHAR_LIMIT=70]" meaning="This headline means that the user can get the bookmarks from their computer on their phone, and their phone's bookmarks on their computer. We want users to read this card and tap the 'Continue' button and sign-in. The tone should be inviting."> - Get all your bookmarks - </message> <message name="IDS_SIGNIN_PROMO_DESCRIPTION_BOOKMARKS" desc="This string is the body of a card that appears when the user opens Chrome's bookmarks; the user is signed out of Chrome. The headline above this string is 'Get all your bookmarks'. There's no character limit but try to keep the translation under 120 characters." meaning="This message means that the user can get the bookmarks from their computer on their phone, and their phone's bookmarks on their computer. We want users to read this card and tap the 'Continue' button and sign-in. The tone should be inviting."> Sign in to get your bookmarks and more from your other devices </message>
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SIGNIN_PROMO_TITLE_BOOKMARKS.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SIGNIN_PROMO_TITLE_BOOKMARKS.png.sha1 deleted file mode 100644 index 27ee5e68..0000000 --- a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SIGNIN_PROMO_TITLE_BOOKMARKS.png.sha1 +++ /dev/null
@@ -1 +0,0 @@ -e4f91839c0b7464682a8c46ad9de547c1d488e17 \ No newline at end of file
diff --git a/chrome/browser/ui/android/toolbar/adaptive_toolbar_enums.h b/chrome/browser/ui/android/toolbar/adaptive_toolbar_enums.h index c7ea874..4ba2c42 100644 --- a/chrome/browser/ui/android/toolbar/adaptive_toolbar_enums.h +++ b/chrome/browser/ui/android/toolbar/adaptive_toolbar_enums.h
@@ -35,9 +35,7 @@ kAddToBookmarks = 9, // ReadAloud action. kReadAloud = 10, - // Value for testing. - kTestButton = 11, - kMaxValue = kTestButton, + kMaxValue = kReadAloud, }; #endif // CHROME_BROWSER_UI_ANDROID_TOOLBAR_ADAPTIVE_TOOLBAR_ENUMS_H_
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/BaseButtonDataProviderTest.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/BaseButtonDataProviderTest.java index 951aaf0..06a502a 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/BaseButtonDataProviderTest.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/BaseButtonDataProviderTest.java
@@ -42,7 +42,10 @@ /** Unit test for {@link BaseButtonDataProvider}. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE) -@EnableFeatures({ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2}) +@EnableFeatures({ + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING, + ChromeFeatureList.ADAPTIVE_BUTTON_IN_TOP_TOOLBAR_CUSTOMIZATION_V2 +}) public class BaseButtonDataProviderTest { private class TestButtonDataProvider extends BaseButtonDataProvider { public TestButtonDataProvider(
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarFeatures.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarFeatures.java index a7a235e..e90d6d7 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarFeatures.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/adaptive/AdaptiveToolbarFeatures.java
@@ -59,10 +59,6 @@ /** Default action chip delay for reader mode. */ public static final int DEFAULT_READER_MODE_ACTION_CHIP_DELAY_MS = 3000; - @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) - public static final String CONTEXTUAL_PAGE_ACTION_TEST_FEATURE_NAME = - "CONTEXTUAL_PAGE_ACTION_TEST_FEATURE_NAME"; - @AdaptiveToolbarButtonVariant private static Integer sButtonVariant; /** For testing only. */ @@ -73,17 +69,11 @@ private static Boolean sShowUiOnlyAfterReadyForTesting; private static HashMap<Integer, Boolean> sActionChipOverridesForTesting; private static HashMap<Integer, Boolean> sAlternativeColorOverridesForTesting; - private static HashMap<Integer, Boolean> sIsDynamicActionOverridesForTesting; /** * @return Whether the button variant is a dynamic action. */ public static boolean isDynamicAction(@AdaptiveToolbarButtonVariant int variant) { - if (sIsDynamicActionOverridesForTesting != null - && sIsDynamicActionOverridesForTesting.containsKey(variant)) { - return Boolean.TRUE.equals(sIsDynamicActionOverridesForTesting.get(variant)); - } - switch (variant) { case AdaptiveToolbarButtonVariant.UNKNOWN: case AdaptiveToolbarButtonVariant.NONE: @@ -102,10 +92,10 @@ private static String getFeatureNameForButtonVariant( @AdaptiveToolbarButtonVariant int variant) { switch (variant) { + case AdaptiveToolbarButtonVariant.PRICE_TRACKING: + return ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING; case AdaptiveToolbarButtonVariant.READER_MODE: return ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_READER_MODE; - case AdaptiveToolbarButtonVariant.TEST_BUTTON: - return CONTEXTUAL_PAGE_ACTION_TEST_FEATURE_NAME; default: throw new IllegalArgumentException( "Provided button variant not assigned to feature"); @@ -214,8 +204,9 @@ } public static boolean isPriceTrackingPageActionEnabled() { - // Price tracking is now default enabled, only depending on the global CPA flag. - return ChromeFeatureList.isEnabled(ChromeFeatureList.CONTEXTUAL_PAGE_ACTIONS); + return ChromeFeatureList.isEnabled(ChromeFeatureList.CONTEXTUAL_PAGE_ACTIONS) + && ChromeFeatureList.isEnabled( + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING); } public static boolean isReaderModePageActionEnabled() { @@ -358,15 +349,6 @@ ResettersForTesting.register(() -> sAlternativeColorOverridesForTesting = null); } - public static void setIsDynamicActionForTesting( - @AdaptiveToolbarButtonVariant int buttonVariant, Boolean isDynamicAction) { - if (sIsDynamicActionOverridesForTesting == null) { - sIsDynamicActionOverridesForTesting = new HashMap<>(); - } - sIsDynamicActionOverridesForTesting.put(buttonVariant, isDynamicAction); - ResettersForTesting.register(() -> sIsDynamicActionOverridesForTesting = null); - } - public static void clearParsedParamsForTesting() { sButtonVariant = null; sDefaultSegmentForTesting = null;
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/optional_button/OptionalButtonCoordinatorTest.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/optional_button/OptionalButtonCoordinatorTest.java index 42ca7308..62e55df 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/optional_button/OptionalButtonCoordinatorTest.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/optional_button/OptionalButtonCoordinatorTest.java
@@ -40,11 +40,11 @@ import org.chromium.base.FeatureList; import org.chromium.base.FeatureList.TestValues; import org.chromium.base.test.BaseRobolectricTestRunner; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.toolbar.ButtonData; import org.chromium.chrome.browser.toolbar.ButtonData.ButtonSpec; import org.chromium.chrome.browser.toolbar.ButtonDataImpl; import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarButtonVariant; -import org.chromium.chrome.browser.toolbar.adaptive.AdaptiveToolbarFeatures; import org.chromium.chrome.browser.toolbar.optional_button.OptionalButtonCoordinator.TransitionType; import org.chromium.chrome.browser.user_education.IPHCommandBuilder; import org.chromium.chrome.browser.user_education.UserEducationHelper; @@ -301,13 +301,9 @@ @Test public void testUpdateButton_actionChipResourceIdGetsRemovedWhenNotInVariant() { - AdaptiveToolbarFeatures.setIsDynamicActionForTesting( - AdaptiveToolbarButtonVariant.TEST_BUTTON, true); TestValues testValues = new TestValues(); testValues.addFieldTrialParamOverride( - AdaptiveToolbarFeatures.CONTEXTUAL_PAGE_ACTION_TEST_FEATURE_NAME, - "action_chip", - "false"); + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING, "action_chip", "false"); FeatureList.setTestValues(testValues); Drawable iconDrawable = mock(Drawable.class); @@ -326,7 +322,7 @@ /* supportsTinting= */ true, mockIphCommandBuilder, /* isEnabled= */ isEnabled, - AdaptiveToolbarButtonVariant.TEST_BUTTON, + AdaptiveToolbarButtonVariant.PRICE_TRACKING, /* tooltipTextResId= */ Resources.ID_NULL, /* showHoverHighlight= */ false); @@ -339,13 +335,9 @@ @Test public void testUpdateButton_actionChipResourceIdGetsRemovedByFeatureEngagement() { - AdaptiveToolbarFeatures.setIsDynamicActionForTesting( - AdaptiveToolbarButtonVariant.TEST_BUTTON, true); TestValues testValues = new TestValues(); testValues.addFieldTrialParamOverride( - AdaptiveToolbarFeatures.CONTEXTUAL_PAGE_ACTION_TEST_FEATURE_NAME, - "action_chip", - "true"); + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING, "action_chip", "true"); FeatureList.setTestValues(testValues); doReturn(true).when(mMockTracker).isInitialized(); @@ -369,7 +361,7 @@ /* supportsTinting= */ true, mockIphCommandBuilder, /* isEnabled= */ isEnabled, - AdaptiveToolbarButtonVariant.TEST_BUTTON, + AdaptiveToolbarButtonVariant.PRICE_TRACKING, /* tooltipTextResId= */ Resources.ID_NULL, /* showHoverHighlight= */ false); @@ -382,13 +374,9 @@ @Test public void testUpdateButton_actionChipResourceIdGetsKeptByFeatureEngagement() { - AdaptiveToolbarFeatures.setIsDynamicActionForTesting( - AdaptiveToolbarButtonVariant.TEST_BUTTON, true); TestValues testValues = new TestValues(); testValues.addFieldTrialParamOverride( - AdaptiveToolbarFeatures.CONTEXTUAL_PAGE_ACTION_TEST_FEATURE_NAME, - "action_chip", - "true"); + ChromeFeatureList.CONTEXTUAL_PAGE_ACTION_PRICE_TRACKING, "action_chip", "true"); FeatureList.setTestValues(testValues); doReturn(true).when(mMockTracker).isInitialized(); @@ -412,7 +400,7 @@ /* supportsTinting= */ true, mockIphCommandBuilder, /* isEnabled= */ isEnabled, - AdaptiveToolbarButtonVariant.TEST_BUTTON, + AdaptiveToolbarButtonVariant.PRICE_TRACKING, /* tooltipTextResId= */ Resources.ID_NULL, /* showHoverHighlight= */ false);
diff --git a/chrome/browser/ui/ash/assistant/assistant_test_mixin.cc b/chrome/browser/ui/ash/assistant/assistant_test_mixin.cc index ad9ba545..823a9a3 100644 --- a/chrome/browser/ui/ash/assistant/assistant_test_mixin.cc +++ b/chrome/browser/ui/ash/assistant/assistant_test_mixin.cc
@@ -312,7 +312,7 @@ test_base_(test_base), user_context_(LoginManagerMixin::CreateDefaultUserContext(user)) { // Tell LoginManagerMixin to launch the browser when the user is logged in. - login_manager_.set_should_launch_browser(true); + login_manager_.SetShouldLaunchBrowser(true); } ~LoggedInUserMixin() override = default;
diff --git a/chrome/browser/ui/ash/container_app/container_app_interactive_uitest.cc b/chrome/browser/ui/ash/container_app/container_app_interactive_uitest.cc index bff0586..270c3b68 100644 --- a/chrome/browser/ui/ash/container_app/container_app_interactive_uitest.cc +++ b/chrome/browser/ui/ash/container_app/container_app_interactive_uitest.cc
@@ -95,23 +95,6 @@ inline char kGmailAppElementName[] = "GmailApp"; inline char kShowAppInfoMenuItemElementName[] = "ShowAppInfoMenuItem"; -// Users ----------------------------------------------------------------------- - -inline char kManagedUserEmail[] = "managed@example.com"; -inline char kManagedUserGaiaId[] = "<MANAGED_USER_GAIA_ID>"; -inline char kUnmanagedUserEmail[] = "unmanaged@gmail.com"; -inline char kUnmanagedUserGaiaId[] = "<UNMANAGED_USER_GAIA_ID>"; - -// Helpers --------------------------------------------------------------------- - -// Returns an `AccountId` for either a `managed` or an unmanaged user. -AccountId GetAccountId(bool managed) { - return managed ? AccountId::FromUserEmailGaiaId(kManagedUserEmail, - kManagedUserGaiaId) - : AccountId::FromUserEmailGaiaId(kUnmanagedUserEmail, - kUnmanagedUserGaiaId); -} - // Returns all `descendants` of the specified `parent` matching the given class. template <typename ViewClass> void FindDescendantsOfClass(views::View* parent, @@ -225,10 +208,10 @@ class ContainerAppInteractiveUiTestBase : public InteractiveBrowserTestT<MixinBasedInProcessBrowserTest> { public: - ContainerAppInteractiveUiTestBase(const AccountId& account_id, - user_manager::UserType user_type, - bool should_ignore_feature_key) - : user_session_mixin_(CreateUserSessionMixin(account_id, user_type)) { + ContainerAppInteractiveUiTestBase( + std::optional<ash::LoggedInUserMixin::LogInType> login_type, + bool should_ignore_feature_key) + : user_session_mixin_(CreateUserSessionMixin(login_type)) { // Conditionally ignore the container app preinstallation key. if (should_ignore_feature_key) { ignore_container_app_preinstall_key_ = std::make_unique< @@ -353,25 +336,18 @@ private: // Creates the appropriate guest or logged-in user session mixin based on - // the specified `account_id` and `user_type`. + // the presence of `login_type`. absl::variant<ash::GuestSessionMixin, ash::LoggedInUserMixin> - CreateUserSessionMixin(const AccountId& account_id, - user_manager::UserType user_type) { - if (user_type == user_manager::UserType::kGuest) { + CreateUserSessionMixin( + std::optional<ash::LoggedInUserMixin::LogInType> login_type) { + if (!login_type) { return absl::variant<ash::GuestSessionMixin, ash::LoggedInUserMixin>( absl::in_place_type_t<ash::GuestSessionMixin>(), &mixin_host_); } - CHECK(user_type == user_manager::UserType::kChild || - user_type == user_manager::UserType::kRegular); - return absl::variant<ash::GuestSessionMixin, ash::LoggedInUserMixin>( absl::in_place_type_t<ash::LoggedInUserMixin>(), &mixin_host_, - user_type == user_manager::UserType::kChild - ? ash::LoggedInUserMixin::LogInType::kChild - : ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this, /*should_launch_browser=*/true, - account_id); + /*test_base=*/this, embedded_test_server(), login_type.value()); } // Returns whether the user should be logged in as part of test setup. @@ -398,14 +374,15 @@ // whether the logged-in user is new or existing. Tests include a PRE_ session, // where user state is initialized, followed by a subsequent session containing // test logic. Chrome is restarted between sessions. + class ContainerAppInteractiveUiTest : public ContainerAppInteractiveUiTestBase, public WithParamInterface</*existing_user=*/bool> { public: ContainerAppInteractiveUiTest() - : ContainerAppInteractiveUiTestBase(GetAccountId(/*managed=*/false), - user_manager::UserType::kRegular, - /*should_ignore_feature_key=*/true) { + : ContainerAppInteractiveUiTestBase( + ash::LoggedInUserMixin::LogInType::kConsumer, + /*should_ignore_feature_key=*/true) { // Disable the container app during the PRE_ session so that the subsequent // session containing test logic is when the app preinstallation occurs. if (IsPreSession()) { @@ -899,8 +876,7 @@ static constexpr char kIncorrectKey[] = "<INCORRECT_KEY>"; ContainerAppInteractiveUiIneligibilityTest() - : ContainerAppInteractiveUiTestBase(GetAccountId(), - GetUserType(), + : ContainerAppInteractiveUiTestBase(GetLoginType(), ShouldIgnoreFeatureKey()) { std::vector<base::test::FeatureRefAndParams> enabled; std::vector<base::test::FeatureRef> disabled; @@ -947,7 +923,7 @@ // preinstallation of the container app, circumvent timeouts by disabling // other default web apps. std::unique_ptr<web_app::ScopedTestingPreinstalledAppData> app_data; - if (GetUserType() == user_manager::UserType::kChild) { + if (GetLoginType() == ash::LoggedInUserMixin::LogInType::kChild) { app_data = std::make_unique<web_app::ScopedTestingPreinstalledAppData>(); app_data->apps.emplace_back( web_app::GetConfigForContainer(/*device_info=*/std::nullopt)); @@ -956,21 +932,17 @@ ContainerAppInteractiveUiTestBase::SetUpOnMainThread(); } - // Returns the `AccountId` for the user given test parameterization. - AccountId GetAccountId() const { - return ::GetAccountId(/*managed=*/GetParam() == - IneligibilityReason::kUserManaged); - } - - // Returns the type for the user given test parameterization. - user_manager::UserType GetUserType() const { + // Returns the login type for the user given test parameterization. + std::optional<ash::LoggedInUserMixin::LogInType> GetLoginType() const { switch (GetParam()) { case IneligibilityReason::kUserTypeChild: - return user_manager::UserType::kChild; + return ash::LoggedInUserMixin::LogInType::kChild; case IneligibilityReason::kUserTypeGuest: - return user_manager::UserType::kGuest; + return std::nullopt; + case IneligibilityReason::kUserManaged: + return ash::LoggedInUserMixin::LogInType::kManaged; default: - return user_manager::UserType::kRegular; + return ash::LoggedInUserMixin::LogInType::kConsumer; } }
diff --git a/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc b/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc index 8027acf..7ae28295 100644 --- a/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc +++ b/chrome/browser/ui/ash/projector/projector_client_impl_browsertest.cc
@@ -63,16 +63,6 @@ return apps::AppServiceProxyFactory::GetForProfile(profile); } -// Returns the account id for logging in. -std::optional<AccountId> GetPrimaryAccountId(bool is_managed) { - if (is_managed) { - return AccountId::FromUserEmailGaiaId( - FakeGaiaMixin::kEnterpriseUser1, FakeGaiaMixin::kEnterpriseUser1GaiaId); - } - // Use the default FakeGaiaMixin::kFakeUserEmail consumer test account id. - return std::nullopt; -} - } // namespace // A class helps to verify enable/disable Drive could invoke @@ -342,8 +332,6 @@ bool is_child() const { return GetParam(); } - bool is_managed() const { return !is_child(); } - ProjectorClient* client() { return ProjectorClient::Get(); } std::string GetPolicy() { @@ -380,13 +368,9 @@ DeviceStateMixin device_state_{ &mixin_host_, DeviceStateMixin::State::OOBE_COMPLETED_CONSUMER_OWNED}; LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, + &mixin_host_, /*test_base=*/this, embedded_test_server(), is_child() ? LoggedInUserMixin::LogInType::kChild - : LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), - this, - /*should_launch_browser=*/true, - GetPrimaryAccountId(is_managed())}; + : LoggedInUserMixin::LogInType::kManaged}; }; IN_PROC_BROWSER_TEST_P(ProjectorClientManagedTest,
diff --git a/chrome/browser/ui/ash/system_tray_tray_cast_browsertest_media_router_chromeos.cc b/chrome/browser/ui/ash/system_tray_tray_cast_browsertest_media_router_chromeos.cc index 3dbb55d..711823bc 100644 --- a/chrome/browser/ui/ash/system_tray_tray_cast_browsertest_media_router_chromeos.cc +++ b/chrome/browser/ui/ash/system_tray_tray_cast_browsertest_media_router_chromeos.cc
@@ -249,7 +249,7 @@ SystemTrayTrayCastAccessCodeChromeOSTest() { // Use consumer emails to avoid having to fake a policy fetch. login_mixin_.AppendRegularUsers(2); - login_mixin_.set_should_launch_browser(true); + login_mixin_.SetShouldLaunchBrowser(true); account_id1_ = login_mixin_.users()[0].account_id; account_id2_ = login_mixin_.users()[1].account_id; }
diff --git a/chrome/browser/ui/autofill/autofill_signin_promo_tab_helper.cc b/chrome/browser/ui/autofill/autofill_signin_promo_tab_helper.cc index 6a2dbb7..a763ece 100644 --- a/chrome/browser/ui/autofill/autofill_signin_promo_tab_helper.cc +++ b/chrome/browser/ui/autofill/autofill_signin_promo_tab_helper.cc
@@ -10,6 +10,7 @@ #include "chrome/browser/password_manager/chrome_password_manager_client.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/identity_manager_factory.h" +#include "chrome/browser/signin/signin_ui_util.h" #include "chrome/browser/ui/browser.h" #include "components/signin/public/base/consent_level.h" @@ -59,10 +60,21 @@ const password_manager::PasswordForm& password_form, signin_metrics::AccessPoint access_point, base::TimeDelta time_limit) { + signin::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile( + Profile::FromBrowserContext(web_contents_->GetBrowserContext())); if (!state_->identity_manager_observation_.IsObserving()) { - state_->identity_manager_observation_.Observe( - IdentityManagerFactory::GetForProfile( - Profile::FromBrowserContext(web_contents_->GetBrowserContext()))); + state_->identity_manager_observation_.Observe(identity_manager); + } + + // If there is already an account in error state, then we need to reauth. This + // variable will help us determine whether we should reset the helper in + // `OnErrorStateOfRefreshTokenUpdatedForAccount` or not. + if (identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSignin) && + identity_manager->HasAccountWithRefreshTokenInPersistentErrorState( + identity_manager->GetPrimaryAccountId( + signin::ConsentLevel::kSignin))) { + state_->needs_reauth_ = true; } state_->password_form_ = password_form; state_->access_point_ = access_point; @@ -75,8 +87,80 @@ return state_->is_initialized_; } +void AutofillSigninPromoTabHelper::OnErrorStateOfRefreshTokenUpdatedForAccount( + const CoreAccountInfo& account_info, + const GoogleServiceAuthError& error, + signin_metrics::SourceForRefreshTokenOperation token_operation_source) { + // Do nothing if there was not already an account with a refresh token error + // before. The password move will be initiated by `OnPrimaryAccountChanged`. + if (!state_->needs_reauth_) { + return; + } + + // Do not move the data anymore if the time limit since the initialization of + // the move has been exceeded. This can happen for example if the user clicks + // "Sign in" in the promo which opens a sign in tab and initializes this + // helper, but the user does not complete the sign in. As they may forget that + // this sign in tab would move the password, we do nothing instead. + if (base::Time::Now() - state_->initialization_time_ > state_->time_limit_) { + Reset(); + return; + } + + // Return if there is no password to move. + if (!state_->password_form_.HasNonEmptyPasswordValue()) { + Reset(); + return; + } + + // Do nothing if there is still an error. + if (error != GoogleServiceAuthError::AuthErrorNone()) { + Reset(); + return; + } + + // Do nothing if the error was not resolved for the primary account. + signin::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile( + Profile::FromBrowserContext(web_contents_->GetBrowserContext())); + if (identity_manager->GetPrimaryAccountId(signin::ConsentLevel::kSignin) != + account_info.account_id) { + Reset(); + return; + } + + // We only want to move the data if the sign in event has the correct + // operation source, so if it was performed from the tab that was opened after + // clicking the sign in promo. + if (token_operation_source != signin_metrics::SourceForRefreshTokenOperation:: + kDiceResponseHandler_PasswordPromoSignin) { + Reset(); + return; + } + + // Initiate password move if requirements are met. + state_->move_helper_ = + std::make_unique<password_manager::MovePasswordToAccountStoreHelper>( + state_->password_form_, + ChromePasswordManagerClient::FromWebContents(web_contents_), + password_manager::metrics_util::MoveToAccountStoreTrigger:: + kUserOptedInAfterSavingLocally, + // `base::Unretained(this)` is fine to use, because `this` owns the + // `MovePasswordToAccountStoreHelper`. + base::BindOnce(&AutofillSigninPromoTabHelper::Reset, + base::Unretained(this))); +} + void AutofillSigninPromoTabHelper::OnPrimaryAccountChanged( const signin::PrimaryAccountChangeEvent& event_details) { + // The user changed their primary account while we were expecting them to + // reauthenticate. Abandon password move to avoid saving password to a wrong + // account. + if (state_->needs_reauth_) { + Reset(); + return; + } + // Do not move the data anymore if the time limit since the initialization of // the move has been exceeded. This can happen for example if the user clicks // "Sign in" in the promo which opens a sign in tab and initializes this
diff --git a/chrome/browser/ui/autofill/autofill_signin_promo_tab_helper.h b/chrome/browser/ui/autofill/autofill_signin_promo_tab_helper.h index 3938d16..78fbdd4 100644 --- a/chrome/browser/ui/autofill/autofill_signin_promo_tab_helper.h +++ b/chrome/browser/ui/autofill/autofill_signin_promo_tab_helper.h
@@ -47,6 +47,11 @@ // Overrides signin::IdentityManager::Observer functions. void OnPrimaryAccountChanged( const signin::PrimaryAccountChangeEvent& event_details) override; + void OnErrorStateOfRefreshTokenUpdatedForAccount( + const CoreAccountInfo& account_info, + const GoogleServiceAuthError& error, + signin_metrics::SourceForRefreshTokenOperation token_operation_source) + override; void OnIdentityManagerShutdown( signin::IdentityManager* identity_manager) override; @@ -71,6 +76,7 @@ base::Time initialization_time_; base::TimeDelta time_limit_; bool is_initialized_ = false; + bool needs_reauth_ = false; }; std::unique_ptr<ResetableState> state_;
diff --git a/chrome/browser/ui/browser_commands.cc b/chrome/browser/ui/browser_commands.cc index e04b276..79f81a69e 100644 --- a/chrome/browser/ui/browser_commands.cc +++ b/chrome/browser/ui/browser_commands.cc
@@ -2234,7 +2234,7 @@ LensOverlayController* const controller = LensOverlayController::GetController(web_contents); if (controller && controller->Enabled()) { - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); } }
diff --git a/chrome/browser/ui/lens/lens_overlay_controller.cc b/chrome/browser/ui/lens/lens_overlay_controller.cc index 1dedff1..a156c58 100644 --- a/chrome/browser/ui/lens/lens_overlay_controller.cc +++ b/chrome/browser/ui/lens/lens_overlay_controller.cc
@@ -200,7 +200,7 @@ return lens::features::IsLensOverlayEnabled(); } -void LensOverlayController::ShowUI() { +void LensOverlayController::ShowUI(InvocationSource invocation_source) { // If UI is already showing or in the process of showing, do nothing. if (state_ != State::kOff) { return; @@ -261,6 +261,8 @@ base::BindOnce(&LensOverlayController::DidCaptureScreenshot, weak_factory_.GetWeakPtr(), ++screenshot_attempt_id_))); + + base::UmaHistogramEnumeration("Lens.Overlay.Invoked", invocation_source); } void LensOverlayController::CloseUI() {
diff --git a/chrome/browser/ui/lens/lens_overlay_controller.h b/chrome/browser/ui/lens/lens_overlay_controller.h index 8493445..864535aa 100644 --- a/chrome/browser/ui/lens/lens_overlay_controller.h +++ b/chrome/browser/ui/lens/lens_overlay_controller.h
@@ -58,6 +58,39 @@ public lens::mojom::LensPageHandler, public lens::mojom::LensSidePanelPageHandler { public: + // Designates the source of any lens overlay invocation (in other words, any + // call to `ShowUI()`). + // + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + // + // LINT.IfChange(InvocationSource) + enum InvocationSource { + // The Chrome app ("3-dot") menu entry. + kAppMenu = 0, + + // The content area context menu entry that is available when the user + // right-clicks on any area of the page that doesn't contain text, links or + // media. + kContentAreaContextMenuPage = 1, + + // The content area context menu entry that is available when the user + // right-clicks on an image. + kContentAreaContextMenuImage = 2, + + // The pinned toolbar action button. + kToolbar = 3, + + // The find in page (Ctrl/Cmd-f) dialog button. + kFindInPage = 4, + + // The button in the omnibox (address bar). + kOmnibox = 5, + + kMaxValue = kOmnibox + }; + // LINT.ThenChange(//tools/metrics/histograms/metadata/others/enums.xml:LensOverlayInvocationSource) + LensOverlayController(tabs::TabInterface* tab, variations::VariationsClient* variations_client, signin::IdentityManager* identity_manager, @@ -92,8 +125,10 @@ bool Enabled(); // This is entry point for showing the overlay UI. This has no effect if state - // is not kOff. This has no effect if the tab is not in the foreground. - void ShowUI(); + // is not kOff. This has no effect if the tab is not in the foreground. If the + // overlay is successfully invoked, then the value of `invocation_source` will + // be recorded in the relevant metrics. + void ShowUI(InvocationSource invocation_source); // Closes the overlay UI and sets state to kOff. This method should be // idempotent. This synchronously destroys any associated WebUIs, so should
diff --git a/chrome/browser/ui/lens/lens_overlay_controller_browsertest.cc b/chrome/browser/ui/lens/lens_overlay_controller_browsertest.cc index 56430662..4856c5db 100644 --- a/chrome/browser/ui/lens/lens_overlay_controller_browsertest.cc +++ b/chrome/browser/ui/lens/lens_overlay_controller_browsertest.cc
@@ -8,6 +8,7 @@ #include "chrome/browser/ui/lens/lens_overlay_controller.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/run_until.h" #include "chrome/browser/lens/core/mojom/geometry.mojom.h" #include "chrome/browser/lens/core/mojom/lens.mojom.h" @@ -349,7 +350,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); @@ -376,7 +377,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); @@ -398,7 +399,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); @@ -434,7 +435,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); @@ -474,7 +475,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); @@ -524,7 +525,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); // We need to flush the mojo receiver calls to make sure the screenshot was @@ -593,7 +594,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); ASSERT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -642,7 +643,7 @@ // Showing UI should eventually result in overlay state. When the overlay is // bound, it should start the query flow which returns a response for the // full image callback. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); ASSERT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -682,7 +683,7 @@ // Showing UI should eventually result in overlay state. When the overlay is // bound, it should start the query flow which returns a response for the // interaction data callback. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); ASSERT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -715,7 +716,7 @@ browser()->tab_strip_model()->active_index(); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); ASSERT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -765,7 +766,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); ASSERT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -819,7 +820,7 @@ EXPECT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); EXPECT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); EXPECT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -879,7 +880,7 @@ EXPECT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); EXPECT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); EXPECT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -932,7 +933,7 @@ EXPECT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); EXPECT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); EXPECT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -987,7 +988,7 @@ EXPECT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); EXPECT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); EXPECT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -1043,7 +1044,7 @@ // Showing UI should eventually result in overlay state. When the overlay is // bound, it should start the query flow which returns a response for the // interaction data callback. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); ASSERT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -1084,7 +1085,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); EXPECT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); EXPECT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -1162,7 +1163,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); EXPECT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; })); EXPECT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); @@ -1241,4 +1242,95 @@ loaded_search_query->selected_text_); } +IN_PROC_BROWSER_TEST_F(LensOverlayControllerBrowserTest, + RecordInvocationHistogram) { + base::HistogramTester histogram_tester; + WaitForPaint(); + + // State should start in off. + auto* controller = browser() + ->tab_strip_model() + ->GetActiveTab() + ->tab_features() + ->lens_overlay_controller(); + ASSERT_EQ(controller->state(), State::kOff); + + // Showing UI should eventually result in overlay state. When the overlay is + // bound, it should start the query flow which returns a response for the + // interaction data callback. + controller->ShowUI(LensOverlayController::kAppMenu); + ASSERT_TRUE(base::test::RunUntil( + [&]() { return controller->state() == State::kOverlay; })); + ASSERT_TRUE(content::WaitForLoadStop(GetOverlayWebContents())); + + // Showing the UI should have recorded an entry in the appropriate bucket and + // the total count of invocations should be 1. + histogram_tester.ExpectBucketCount("Lens.Overlay.Invoked", + LensOverlayController::kAppMenu, + /*expected_count=*/1); + histogram_tester.ExpectTotalCount("Lens.Overlay.Invoked", + /*expected_count=*/1); + + // Attenmpting to invoke the overlay again without closing it first should not + // record any new entries. + controller->ShowUI(LensOverlayController::kAppMenu); + histogram_tester.ExpectBucketCount("Lens.Overlay.Invoked", + LensOverlayController::kAppMenu, + /*expected_count=*/1); + histogram_tester.ExpectTotalCount("Lens.Overlay.Invoked", + /*expected_count=*/1); + + // Closing the UI and then reopening it via any entry point should record a + // new entry in the appropriate bucket. + controller->CloseUI(); + controller->ShowUI(LensOverlayController::kAppMenu); + histogram_tester.ExpectBucketCount("Lens.Overlay.Invoked", + LensOverlayController::kAppMenu, + /*expected_count=*/2); + histogram_tester.ExpectTotalCount("Lens.Overlay.Invoked", + /*expected_count=*/2); + + controller->CloseUI(); + controller->ShowUI(LensOverlayController::kContentAreaContextMenuPage); + histogram_tester.ExpectBucketCount( + "Lens.Overlay.Invoked", + LensOverlayController::kContentAreaContextMenuPage, + /*expected_count=*/1); + histogram_tester.ExpectTotalCount("Lens.Overlay.Invoked", + /*expected_count=*/3); + + controller->CloseUI(); + controller->ShowUI(LensOverlayController::kContentAreaContextMenuImage); + histogram_tester.ExpectBucketCount( + "Lens.Overlay.Invoked", + LensOverlayController::kContentAreaContextMenuImage, + /*expected_count=*/1); + histogram_tester.ExpectTotalCount("Lens.Overlay.Invoked", + /*expected_count=*/4); + + controller->CloseUI(); + controller->ShowUI(LensOverlayController::kToolbar); + histogram_tester.ExpectBucketCount("Lens.Overlay.Invoked", + LensOverlayController::kToolbar, + /*expected_count=*/1); + histogram_tester.ExpectTotalCount("Lens.Overlay.Invoked", + /*expected_count=*/5); + + controller->CloseUI(); + controller->ShowUI(LensOverlayController::kFindInPage); + histogram_tester.ExpectBucketCount("Lens.Overlay.Invoked", + LensOverlayController::kFindInPage, + /*expected_count=*/1); + histogram_tester.ExpectTotalCount("Lens.Overlay.Invoked", + /*expected_count=*/6); + + controller->CloseUI(); + controller->ShowUI(LensOverlayController::kOmnibox); + histogram_tester.ExpectBucketCount("Lens.Overlay.Invoked", + LensOverlayController::kOmnibox, + /*expected_count=*/1); + histogram_tester.ExpectTotalCount("Lens.Overlay.Invoked", + /*expected_count=*/7); +} + } // namespace
diff --git a/chrome/browser/ui/lens/lens_overlay_side_panel_coordinator.cc b/chrome/browser/ui/lens/lens_overlay_side_panel_coordinator.cc index 34131045..a61343b 100644 --- a/chrome/browser/ui/lens/lens_overlay_side_panel_coordinator.cc +++ b/chrome/browser/ui/lens/lens_overlay_side_panel_coordinator.cc
@@ -92,7 +92,7 @@ if (controller->IsOverlayShowing()) { controller->CloseUI(); } else { - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kToolbar); } }, browser);
diff --git a/chrome/browser/ui/passwords/manage_passwords_test.cc b/chrome/browser/ui/passwords/manage_passwords_test.cc index 7e36082..ca6d9a1 100644 --- a/chrome/browser/ui/passwords/manage_passwords_test.cc +++ b/chrome/browser/ui/passwords/manage_passwords_test.cc
@@ -248,14 +248,6 @@ } } -void ManagePasswordsTest::SetupSaveToAccountStore() { - ON_CALL(*client_.GetPasswordFeatureManager(), IsOptedInForAccountStorage()) - .WillByDefault(testing::Return(true)); - ON_CALL(*client_.GetPasswordFeatureManager(), GetDefaultPasswordStore()) - .WillByDefault(testing::Return( - password_manager::PasswordForm::Store::kAccountStore)); -} - std::unique_ptr<base::HistogramSamples> ManagePasswordsTest::GetSamples( const char* histogram) { // Ensure that everything has been properly recorded before pulling samples.
diff --git a/chrome/browser/ui/passwords/manage_passwords_test.h b/chrome/browser/ui/passwords/manage_passwords_test.h index 98f51e6..bdbe870 100644 --- a/chrome/browser/ui/passwords/manage_passwords_test.h +++ b/chrome/browser/ui/passwords/manage_passwords_test.h
@@ -76,9 +76,6 @@ // Put the controller, icon, and bubble into a moving-password state. void SetupMovingPasswords(); - // Put the client into a state which induces password save to account store. - void SetupSaveToAccountStore(); - // Always configures a signed-in user, and when |is_enabled| is true, it also // configures the Sync service to sync passwords. |is_account_storage_enabled| // enables account storage for the user.
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc index a14190d6..ad3a597f 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller.cc
@@ -934,16 +934,13 @@ profile, account, signin_metrics::AccessPoint::ACCESS_POINT_PASSWORD_BUBBLE); - // Do nothing if the password is already using account store, it will be - // uploaded automatically after successful reauthentication. - if (pending_password.IsUsingAccountStore()) { - return; - } - // If the sign in was already successful, move the password directly. // Otherwise, wait for a sign in event and move the password upon success. - if (IdentityManagerFactory::GetForProfile(profile)->HasPrimaryAccount( - signin::ConsentLevel::kSignin)) { + signin::IdentityManager* identity_manager = + IdentityManagerFactory::GetForProfile(profile); + if (identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSignin) && + !identity_manager->HasAccountWithRefreshTokenInPersistentErrorState( + account.account_id)) { MoveJustSavedPasswordAfterAccountStoreOptIn( pending_password, password_manager::PasswordManagerClient::ReauthSucceeded(true));
diff --git a/chrome/browser/ui/side_panel/side_panel_enums.h b/chrome/browser/ui/side_panel/side_panel_enums.h index c1ee60d04..68a5c7a 100644 --- a/chrome/browser/ui/side_panel/side_panel_enums.h +++ b/chrome/browser/ui/side_panel/side_panel_enums.h
@@ -40,6 +40,11 @@ // is causing the side panel to remain open or after the side panel has been // closed. kReadyToHide = 1, + // Content is ready to show, will influence side panel visibility, and show + // immediately without any animations. + kShowImmediately = 2, + // Side panel content should be hidden immediately with no animations. + kHideImmediately = 3, }; #endif // CHROME_BROWSER_UI_SIDE_PANEL_SIDE_PANEL_ENUMS_H_
diff --git a/chrome/browser/ui/startup/first_run_service.cc b/chrome/browser/ui/startup/first_run_service.cc index ace544ea..9526df4 100644 --- a/chrome/browser/ui/startup/first_run_service.cc +++ b/chrome/browser/ui/startup/first_run_service.cc
@@ -470,19 +470,6 @@ return nullptr; } -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - if (base::FeatureList::IsEnabled(kForYouFreSyntheticTrialRegistration)) { - // We use this point to register for the study as it can give us a good - // counterfactual, before checking the state of the feature itself. The - // service is created on demand so we are in a code path that will require - // the FRE to be shown. - // Besides being suppressed by enterprise policy, if the FRE doesn't run, it - // would be related to handling some corner cases, and should not impact our - // metrics too much. - FirstRunService::JoinFirstRunCohort(); - } -#endif - std::unique_ptr<FirstRunService> instance = std::make_unique<FirstRunService>( *profile, *IdentityManagerFactory::GetForProfile(profile)); base::UmaHistogramBoolean("ProfilePicker.FirstRun.ServiceCreated", true);
diff --git a/chrome/browser/ui/startup/first_run_service.h b/chrome/browser/ui/startup/first_run_service.h index 52dd732..da5efc6 100644 --- a/chrome/browser/ui/startup/first_run_service.h +++ b/chrome/browser/ui/startup/first_run_service.h
@@ -9,7 +9,6 @@ #include "base/functional/callback_forward.h" #include "base/gtest_prod_util.h" -#include "base/metrics/field_trial.h" #include "base/no_destructor.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -23,10 +22,6 @@ class SilentSyncEnabler; class ProfileNameResolver; -namespace base { -class FeatureList; -} - namespace version_info { enum class Channel; } @@ -79,25 +74,6 @@ static void RegisterLocalStatePrefs(PrefRegistrySimple* registry); -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - // Creates a field trial to control the ForYouFre and - // ForYouFreSyntheticTrialRegistration features. The trial is client - // controlled because ForYouFre controls the First Run Experience (FRE), which - // shows up before a variations seed is available. - // - // No persistence happens here, instead it happens if/when the attempt to show - // the FRE happens, and the client joins an experiment cohort through - // `JoinFirstRunCohort()`. - static void SetUpClientSideFieldTrialIfNeeded( - const base::FieldTrial::EntropyProvider& entropy_provider, - base::FeatureList* feature_list); - - // Ensures that the user's experiment group is appropriately reported - // to track the effect of the first run experience over time. Should be called - // once per browser process startup. - static void EnsureStickToFirstRunCohort(); -#endif - FirstRunService(Profile& profile, signin::IdentityManager& identity_manager); ~FirstRunService() override; @@ -130,36 +106,9 @@ private: friend class FirstRunServiceFactory; - FRIEND_TEST_ALL_PREFIXES(FirstRunFieldTrialCreatorTest, SetUpFromClientSide); - FRIEND_TEST_ALL_PREFIXES(FirstRunCohortSetupTest, JoinFirstRunCohort); FRIEND_TEST_ALL_PREFIXES(FirstRunServiceTest, ShouldPopulateProfileNameFromPrimaryAccount); -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - // Internal interface for `SetUpClientSideFieldTrialIfNeeded()`, exposed to - // allow for channel-independent testing. - static void SetUpClientSideFieldTrial( - const base::FieldTrial::EntropyProvider& entropy_provider, - base::FeatureList* feature_list, - version_info::Channel channel); - - // Enrolls this client with a synthetic field trial based on the Finch params. - // Should be called when the FRE is launched, then the client needs to - // register again on each process startup by calling - // `RegisterSyntheticFieldTrial()`. - static void JoinFirstRunCohort(); - - // Reports to the launch study for the First Run rollout. - // Notes: - // - This is declared here so it can have access to some private functions - // that need to be friended to be used. - // - The function is Dice-only as on Lacros (where this build flag is not set) - // the ForYouFre feature rollout will not go through this study process. The - // feature only guards an internal refactoring that does not have a - // user-visible effect. If will only have a killswitch. - static void RegisterSyntheticFieldTrial(const std::string& group_name); -#endif - // Asynchronously attempts to complete the first run silently. // By the time `callback` is run (if non-null), either: // - the first run has been marked finished because it can't be run for this
diff --git a/chrome/browser/ui/startup/first_run_service_dice_statics.cc b/chrome/browser/ui/startup/first_run_service_dice_statics.cc deleted file mode 100644 index 4a3c96d..0000000 --- a/chrome/browser/ui/startup/first_run_service_dice_statics.cc +++ /dev/null
@@ -1,200 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <memory> -#include <utility> - -#include "base/feature_list.h" -#include "base/logging.h" -#include "base/metrics/field_trial.h" -#include "base/metrics/field_trial_params.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/first_run/first_run.h" -#include "chrome/browser/metrics/chrome_metrics_service_accessor.h" -#include "chrome/browser/ui/startup/first_run_service.h" -#include "chrome/common/channel_info.h" -#include "chrome/common/pref_names.h" -#include "components/prefs/pref_service.h" -#include "components/signin/public/base/signin_switches.h" -#include "components/variations/variations_associated_data.h" -#include "components/version_info/channel.h" - -#if !BUILDFLAG(ENABLE_DICE_SUPPORT) -#error "Unsupported platform" -#endif - -namespace { -// The field trial name. -const char kTrialName[] = "ForYouFreStudy"; - -// Group names for the trial. -const char kEnabledGroup[] = "ClientSideEnabled-2"; -const char kDisabledGroup[] = "ClientSideDisabled-2"; -const char kDefaultGroup[] = "Default"; - -// Probabilities for all field trial groups add up to kTotalProbability. -const base::FieldTrial::Probability kTotalProbability = 100; - -std::string PickTrialGroupWithoutActivation(base::FieldTrial& trial, - version_info::Channel channel) { - int enabled_percent; - int disabled_percent; - int default_percent; - switch (channel) { - case version_info::Channel::UNKNOWN: - case version_info::Channel::CANARY: - case version_info::Channel::DEV: - case version_info::Channel::BETA: - enabled_percent = 50; - disabled_percent = 50; - default_percent = 0; - break; - case version_info::Channel::STABLE: - enabled_percent = 1; - disabled_percent = 1; - default_percent = 98; - break; - } - DCHECK_EQ(kTotalProbability, - enabled_percent + disabled_percent + default_percent); - - trial.AppendGroup(kEnabledGroup, enabled_percent); - trial.AppendGroup(kDisabledGroup, disabled_percent); - trial.AppendGroup(kDefaultGroup, default_percent); - - return trial.GetGroupNameWithoutActivation(); -} - -} // namespace - -// static -void FirstRunService::SetUpClientSideFieldTrialIfNeeded( - const base::FieldTrial::EntropyProvider& entropy_provider, - base::FeatureList* feature_list) { - if (!first_run::IsChromeFirstRun()) { - // We should not check these features outside of the first run. - DVLOG(1) << "Not setting up client-side trial for the FRE, this is not the " - "first run."; - return; - } - - // Make sure that Finch, fieldtrial_testing_config and command line flags take - // precedence over features defined here. In particular, not detecting - // fieldtrial_testing_config triggers a DCHECK. - - if (base::FieldTrialList::Find(kTrialName)) { - DVLOG(1) << "Not setting up client-side trial for the FRE, trial " - "already registered"; - return; - } - - bool is_behaviour_feature_associated = - feature_list->HasAssociatedFieldTrialByFeatureName(kForYouFre.name); - bool is_measurement_feature_associated = - feature_list->HasAssociatedFieldTrialByFeatureName(kForYouFre.name); - if (is_behaviour_feature_associated || is_measurement_feature_associated) { - LOG(WARNING) << "Not setting up client-side trial for the FRE, feature(s) " - "already overridden:" - << (is_behaviour_feature_associated ? " ForYouFre" : "") - << (is_measurement_feature_associated - ? " ForYouFreSyntheticTrialRegistration" - : ""); - return; - } - - // Proceed with actually setting up the field trial. - SetUpClientSideFieldTrial(entropy_provider, feature_list, - chrome::GetChannel()); -} - -// static -void FirstRunService::SetUpClientSideFieldTrial( - const base::FieldTrial::EntropyProvider& entropy_provider, - base::FeatureList* feature_list, - version_info::Channel channel) { - // Set up the trial and determine the group for the current client. - scoped_refptr<base::FieldTrial> trial = - base::FieldTrialList::FactoryGetFieldTrial( - kTrialName, kTotalProbability, kDefaultGroup, entropy_provider); - std::string group_name = PickTrialGroupWithoutActivation(*trial, channel); - - // Set up the state of the features based on the obtained group. - base::FeatureList::OverrideState behaviour_feature_state = - group_name == kEnabledGroup ? base::FeatureList::OVERRIDE_ENABLE_FEATURE - : base::FeatureList::OVERRIDE_DISABLE_FEATURE; - base::FeatureList::OverrideState measurement_feature_state = - group_name != kDefaultGroup ? base::FeatureList::OVERRIDE_ENABLE_FEATURE - : base::FeatureList::OVERRIDE_DISABLE_FEATURE; - - if (measurement_feature_state == base::FeatureList::OVERRIDE_ENABLE_FEATURE) { - base::AssociateFieldTrialParams(kTrialName, group_name, - {{kForYouFreStudyGroup.name, group_name}}); - } - - feature_list->RegisterFieldTrialOverride( - kForYouFre.name, behaviour_feature_state, trial.get()); - feature_list->RegisterFieldTrialOverride( - kForYouFreSyntheticTrialRegistration.name, measurement_feature_state, - trial.get()); - - // Activate only after the overrides are completed. - trial->Activate(); -} - -// static -void FirstRunService::EnsureStickToFirstRunCohort() { - PrefService* local_state = g_browser_process->local_state(); - if (!local_state) { - return; // Can be null in unit tests; - } - - if (!local_state->GetBoolean(prefs::kFirstRunFinished)) { - // This user did not see the FRE. Their first run either happened before the - // feature was enabled, or it's happening right now. In the former case we - // don't enroll them, and in the latter, they will be enrolled right before - // starting the FRE. - return; - } - - auto enrolled_study_group = - local_state->GetString(prefs::kFirstRunStudyGroup); - if (enrolled_study_group.empty()) { - // The user was not enrolled or exited the study at some point. - return; - } - - RegisterSyntheticFieldTrial(enrolled_study_group); -} - -// static -void FirstRunService::JoinFirstRunCohort() { - PrefService* local_state = g_browser_process->local_state(); - if (!local_state) { - return; // Can be null in unit tests; - } - - // The First Run experience depends on experiment groups (see params - // associated with the `kForYouFre` feature). To measure the long terms impact - // of this one-shot experience, we save an associated group name to prefs so - // we can report it as a synthetic trial for understanding the effects for - // each specific configuration, disambiguating it from other clients who had - // a different experience (or did not see the FRE for some reason). - std::string active_study_group = kForYouFreStudyGroup.Get(); - if (active_study_group.empty()) { - return; // No active study, no need to sign up. - } - - local_state->SetString(prefs::kFirstRunStudyGroup, active_study_group); - RegisterSyntheticFieldTrial(active_study_group); -} - -// static -void FirstRunService::RegisterSyntheticFieldTrial( - const std::string& group_name) { - DCHECK(!group_name.empty()); - - ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial( - FirstRunService::kSyntheticTrialName, group_name, - variations::SyntheticTrialAnnotationMode::kCurrentLog); -}
diff --git a/chrome/browser/ui/startup/first_run_service_unittest.cc b/chrome/browser/ui/startup/first_run_service_unittest.cc index ad7216f..7a2810f 100644 --- a/chrome/browser/ui/startup/first_run_service_unittest.cc +++ b/chrome/browser/ui/startup/first_run_service_unittest.cc
@@ -7,25 +7,17 @@ #include "base/files/file_path.h" #include "base/run_loop.h" #include "base/scoped_observation.h" -#include "base/strings/stringprintf.h" -#include "base/test/mock_entropy_provider.h" -#include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "base/test/test_future.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/ui/startup/first_run_test_util.h" #include "chrome/common/pref_names.h" -#include "chrome/test/base/scoped_metrics_service_for_synthetic_trials.h" #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" -#include "components/prefs/pref_service.h" #include "components/signin/public/base/consent_level.h" -#include "components/signin/public/base/signin_switches.h" #include "components/signin/public/identity_manager/identity_test_environment.h" -#include "components/variations/active_field_trials.h" -#include "components/version_info/channel.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" @@ -35,14 +27,6 @@ namespace { -struct FirstRunFieldTrialTestParams { - double entropy_value; - version_info::Channel channel; - - bool expect_study_enabled; - bool expect_feature_enabled; -}; - class ProfileNameChangeFuture : public base::test::TestFuture<std::u16string>, public ProfileAttributesStorage::Observer { public: @@ -107,8 +91,6 @@ // Regression test for crbug.com/1450709. TEST_F(FirstRunServiceTest, ShouldPopulateProfileNameFromPrimaryAccount) { - base::test::ScopedFeatureList feature_list{kForYouFre}; - signin::IdentityTestEnvironment identity_test_env; TestingProfileManager testing_profile_manager{ TestingBrowserProcess::GetGlobal()}; @@ -152,167 +134,3 @@ EXPECT_TRUE(profile_name_future.IsReady()); EXPECT_EQ(u"Primary", profile_name_future.Get()); } - -class FirstRunFieldTrialCreatorTest - : public testing::Test, - public testing::WithParamInterface<FirstRunFieldTrialTestParams> { - public: - base::test::ScopedFeatureList& scoped_feature_list() { - return scoped_feature_list_; - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - -TEST_P(FirstRunFieldTrialCreatorTest, SetUpFromClientSide) { - { - base::MockEntropyProvider low_entropy_provider{GetParam().entropy_value}; - auto feature_list = std::make_unique<base::FeatureList>(); - - FirstRunService::SetUpClientSideFieldTrial( - low_entropy_provider, feature_list.get(), GetParam().channel); - - // Substitute the existing feature list with the one with field trial - // configurations we are testing, so we can check the assertions. - scoped_feature_list().InitWithFeatureList(std::move(feature_list)); - } - - EXPECT_TRUE(base::FieldTrialList::IsTrialActive("ForYouFreStudy")); - - EXPECT_EQ(GetParam().expect_study_enabled, - base::FeatureList::IsEnabled(kForYouFreSyntheticTrialRegistration)); - - EXPECT_EQ(GetParam().expect_study_enabled - ? (GetParam().expect_feature_enabled ? "ClientSideEnabled-2" - : "ClientSideDisabled-2") - : "", - kForYouFreStudyGroup.Get()); -} - -INSTANTIATE_TEST_SUITE_P( - , - FirstRunFieldTrialCreatorTest, - testing::Values( - FirstRunFieldTrialTestParams{.entropy_value = 0.6, - .channel = version_info::Channel::BETA, - .expect_study_enabled = true, - .expect_feature_enabled = false}, - FirstRunFieldTrialTestParams{.entropy_value = 0.01, - .channel = version_info::Channel::BETA, - .expect_study_enabled = true, - .expect_feature_enabled = true}, - FirstRunFieldTrialTestParams{.entropy_value = 0.99, - .channel = version_info::Channel::STABLE, - .expect_study_enabled = false, - .expect_feature_enabled = false}, - FirstRunFieldTrialTestParams{.entropy_value = 0.016, - .channel = version_info::Channel::STABLE, - .expect_study_enabled = true, - .expect_feature_enabled = false}, - FirstRunFieldTrialTestParams{.entropy_value = 0.009, - .channel = version_info::Channel::STABLE, - .expect_study_enabled = true, - .expect_feature_enabled = true}), - - [](const ::testing::TestParamInfo<FirstRunFieldTrialTestParams>& params) { - return base::StringPrintf( - "%02.0fpctEntropy%s", params.param.entropy_value * 100, - version_info::GetChannelString(params.param.channel).data()); - }); - -// Tests to verify the logic for synthetic trial registration that we use to -// assign a given client in a cohort for our long term tracking metrics. -class FirstRunCohortSetupTest : public testing::Test { - public: - static constexpr char kStudyTestGroupName1[] = "test_group_1"; - static constexpr char kStudyTestGroupName2[] = "test_group_2"; - - private: - base::test::TaskEnvironment task_environment_; - ScopedTestingLocalState testing_local_state_{ - TestingBrowserProcess::GetGlobal()}; - ScopedMetricsServiceForSyntheticTrials testing_metrics_service_{ - TestingBrowserProcess::GetGlobal()}; -}; - -// `JoinFirstRunCohort` is run when the FRE is finished, if a group name is -// provided through the feature flags, should result in registering the -// synthetic trial with that group name and store it for subsequent startups. -TEST_F(FirstRunCohortSetupTest, JoinFirstRunCohort) { - PrefService* local_state = g_browser_process->local_state(); - EXPECT_FALSE(local_state->HasPrefPath(prefs::kFirstRunStudyGroup)); - EXPECT_FALSE( - variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName)); - - // No group name available through the features, should no-op. - FirstRunService::JoinFirstRunCohort(); - EXPECT_FALSE(local_state->HasPrefPath(prefs::kFirstRunStudyGroup)); - EXPECT_FALSE( - variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName)); - - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitWithFeaturesAndParameters( - /*enabled_features=*/ - { - {kForYouFreSyntheticTrialRegistration, - {{"group_name", kStudyTestGroupName1}}}, - {kForYouFre, {}}, - }, - /*disabled_features=*/{}); - - // A group name is available, the trial should get registered. - FirstRunService::JoinFirstRunCohort(); - EXPECT_EQ(kStudyTestGroupName1, - local_state->GetString(prefs::kFirstRunStudyGroup)); - EXPECT_TRUE( - variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName)); - EXPECT_TRUE(variations::IsInSyntheticTrialGroup( - FirstRunService::kSyntheticTrialName, kStudyTestGroupName1)); -} - -// `EnsureStickToFirstRunCohort` is run on startup, and should result in -// registering the synthetic trial if the client saw the FRE and we recorded a -// group name to assign to it. -TEST_F(FirstRunCohortSetupTest, EnsureStickToFirstRunCohort) { - PrefService* local_state = g_browser_process->local_state(); - EXPECT_FALSE(local_state->HasPrefPath(prefs::kFirstRunStudyGroup)); - EXPECT_FALSE( - variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName)); - - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitWithFeaturesAndParameters( - /*enabled_features=*/ - { - {kForYouFreSyntheticTrialRegistration, - {{"group_name", kStudyTestGroupName1}}}, - {kForYouFre, {}}, - }, - /*disabled_features=*/{}); - - // `EnsureStickToFirstRunCohort()` no-ops without some specific prefs. - FirstRunService::EnsureStickToFirstRunCohort(); - EXPECT_FALSE(local_state->HasPrefPath(prefs::kFirstRunStudyGroup)); - EXPECT_FALSE( - variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName)); - - // Setting the group name pref: the first, but not sufficient requirement. - // We also set it to a different name from the feature flag to verify which - // one is used. - local_state->SetString(prefs::kFirstRunStudyGroup, kStudyTestGroupName2); - FirstRunService::EnsureStickToFirstRunCohort(); - EXPECT_FALSE( - variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName)); - - // Marking the FRE finished: the second and final requirement. - local_state->SetBoolean(prefs::kFirstRunFinished, true); - FirstRunService::EnsureStickToFirstRunCohort(); - EXPECT_TRUE( - variations::HasSyntheticTrial(FirstRunService::kSyntheticTrialName)); - - // The registered group is read from the prefs, not from the feature param. - EXPECT_TRUE(variations::IsInSyntheticTrialGroup( - FirstRunService::kSyntheticTrialName, kStudyTestGroupName2)); - EXPECT_FALSE(variations::IsInSyntheticTrialGroup( - FirstRunService::kSyntheticTrialName, kStudyTestGroupName1)); -}
diff --git a/chrome/browser/ui/startup/first_run_test_util.h b/chrome/browser/ui/startup/first_run_test_util.h index f4291b6..beb3bb5 100644 --- a/chrome/browser/ui/startup/first_run_test_util.h +++ b/chrome/browser/ui/startup/first_run_test_util.h
@@ -9,8 +9,6 @@ #include "build/build_config.h" #include "chrome/browser/ui/profiles/profile_customization_util.h" #include "chrome/test/base/in_process_browser_test.h" -#include "components/signin/public/base/signin_buildflags.h" -#include "components/signin/public/base/signin_switches.h" class Profile; class FirstRunService; @@ -56,11 +54,6 @@ bool IsProfileNameDefault() const; private: -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - // Only Dice guards the FRE behind a feature flag. - base::test::ScopedFeatureList scoped_feature_list_{kForYouFre}; -#endif - ProfileNameResolver::ScopedInfoFetchTimeoutOverride profile_name_fetch_timeout_override_ = ProfileNameResolver::CreateScopedInfoFetchTimeoutOverrideForTesting(
diff --git a/chrome/browser/ui/views/autofill/popup/popup_search_bar_view.cc b/chrome/browser/ui/views/autofill/popup/popup_search_bar_view.cc index 52c28d0..59a85f4 100644 --- a/chrome/browser/ui/views/autofill/popup/popup_search_bar_view.cc +++ b/chrome/browser/ui/views/autofill/popup/popup_search_bar_view.cc
@@ -14,6 +14,7 @@ #include "ui/base/interaction/element_identifier.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/events/types/event_type.h" +#include "ui/gfx/geometry/point.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/textfield/textfield.h" @@ -21,14 +22,9 @@ namespace autofill { -PopupSearchBarView::PopupSearchBarView( - const std::u16string& placeholder, - OnInputChangedCallback on_input_changed_callback, - base::RepeatingClosure on_focus_lost_callback, - Delegate& delegate) - : on_input_changed_callback_(std::move(on_input_changed_callback)), - on_focus_lost_callback_(std::move(on_focus_lost_callback)), - delegate_(delegate) { +PopupSearchBarView::PopupSearchBarView(const std::u16string& placeholder, + Delegate& delegate) + : delegate_(delegate) { ChromeLayoutProvider* layout_provider = ChromeLayoutProvider::Get(); SetLayoutManager(std::make_unique<views::FlexLayout>()) @@ -70,6 +66,8 @@ // LayoutManager). clear_ = AddChildView( views::Builder<views::ImageButton>() + .SetCallback(base::BindRepeating(&PopupSearchBarView::OnClearPressed, + base::Unretained(this))) .SetImageModel(views::Button::STATE_NORMAL, ui::ImageModel::FromVectorIcon( vector_icons::kCloseChromeRefreshIcon)) @@ -89,7 +87,7 @@ void PopupSearchBarView::OnDidChangeFocus(views::View* focused_before, views::View* focused_now) { if (focused_now != input_ && focused_now != clear_) { - on_focus_lost_callback_.Run(); + delegate_->SearchBarOnFocusLost(); } } @@ -109,12 +107,24 @@ input_->SetText(text); } +gfx::Point PopupSearchBarView::GetClearButtonScreenCenterPointForTesting() + const { + return clear_->GetBoundsInScreen().CenterPoint(); +} + PopupSearchBarView::~PopupSearchBarView() = default; void PopupSearchBarView::OnInputChanged() { input_change_notification_timer_.Start( FROM_HERE, kInputChangeCallbackDelay, - base::BindOnce(on_input_changed_callback_, input_->GetText())); + // `delegate_` is expected to outlive `this`, the timer will either be + // triggered when it is alive or canceled. + base::BindOnce(&Delegate::SearchBarOnInputChanged, + base::Unretained(delegate_), input_->GetText())); +} + +void PopupSearchBarView::OnClearPressed() { + input_->SetText(u""); } BEGIN_METADATA(PopupSearchBarView)
diff --git a/chrome/browser/ui/views/autofill/popup/popup_search_bar_view.h b/chrome/browser/ui/views/autofill/popup/popup_search_bar_view.h index cfebaa4..db93ae3 100644 --- a/chrome/browser/ui/views/autofill/popup/popup_search_bar_view.h +++ b/chrome/browser/ui/views/autofill/popup/popup_search_bar_view.h
@@ -11,6 +11,7 @@ #include "base/memory/raw_ref.h" #include "base/timer/timer.h" #include "ui/base/interaction/element_identifier.h" +#include "ui/gfx/geometry/point.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" @@ -37,6 +38,13 @@ class Delegate { public: + // Called when text in the textfield changes. Calls are throttled with + // a delay of kInputChangeCallbackDelay to avoid excessive triggering. + virtual void SearchBarOnInputChanged(const std::u16string& text) = 0; + + // Called when the controls (textfield and clear button) lose focus. + virtual void SearchBarOnFocusLost() = 0; + // Keyboard events from the textfield are passed to this method first. // The delegate returns `true` if the event was handled, this suppresses // the default behaviour in the textfield. As an example, the LEFT/RIGHT @@ -54,10 +62,7 @@ static constexpr base::TimeDelta kInputChangeCallbackDelay = base::Milliseconds(250); - PopupSearchBarView(const std::u16string& placeholder, - OnInputChangedCallback on_input_changed_callback, - base::RepeatingClosure on_focus_lost_callback, - Delegate& delegate); + PopupSearchBarView(const std::u16string& placeholder, Delegate& delegate); PopupSearchBarView(const PopupSearchBarView&) = delete; PopupSearchBarView& operator=(const PopupSearchBarView&) = delete; ~PopupSearchBarView() override; @@ -78,16 +83,14 @@ void Focus(); void SetInputTextForTesting(const std::u16string& text); + gfx::Point GetClearButtonScreenCenterPointForTesting() const; // TODO(b/325246516): Add methods to support communication with its hosting // poopup view. private: void OnInputChanged(); - - // TODO(b/325246516): Move these callbacks to Delegate. - OnInputChangedCallback on_input_changed_callback_; - base::RepeatingClosure on_focus_lost_callback_; + void OnClearPressed(); const raw_ref<Delegate> delegate_;
diff --git a/chrome/browser/ui/views/autofill/popup/popup_search_bar_view_unittest.cc b/chrome/browser/ui/views/autofill/popup/popup_search_bar_view_unittest.cc index a5397fbd..e081568 100644 --- a/chrome/browser/ui/views/autofill/popup/popup_search_bar_view_unittest.cc +++ b/chrome/browser/ui/views/autofill/popup/popup_search_bar_view_unittest.cc
@@ -30,6 +30,11 @@ public: MockDelegate() = default; ~MockDelegate() override = default; + MOCK_METHOD(void, + SearchBarOnInputChanged, + (const std::u16string& text), + (override)); + MOCK_METHOD(void, SearchBarOnFocusLost, (), (override)); MOCK_METHOD(bool, SearchBarHandleKeyPressed, (const ui::KeyEvent& event), @@ -66,10 +71,8 @@ }; TEST_F(PopupSearchBarViewTest, SetsFocusOnTextfield) { - PopupSearchBarView* view = - widget().SetContentsView(std::make_unique<PopupSearchBarView>( - u"placeholder", /*on_input_changed_callback=*/base::DoNothing(), - /*on_focus_lost_callback=*/base::DoNothing(), delegate())); + PopupSearchBarView* view = widget().SetContentsView( + std::make_unique<PopupSearchBarView>(u"placeholder", delegate())); widget().Show(); view->Focus(); @@ -80,30 +83,24 @@ } TEST_F(PopupSearchBarViewTest, OnFocusLostCalled) { - base::MockRepeatingClosure mock_on_focus_lost_callback; - PopupSearchBarView* view = - widget().SetContentsView(std::make_unique<PopupSearchBarView>( - u"placeholder", /*on_input_changed_callback=*/base::DoNothing(), - mock_on_focus_lost_callback.Get(), delegate())); + PopupSearchBarView* view = widget().SetContentsView( + std::make_unique<PopupSearchBarView>(u"placeholder", delegate())); widget().Show(); view->Focus(); ASSERT_NE(widget().GetFocusManager()->GetFocusedView(), nullptr); - EXPECT_CALL(mock_on_focus_lost_callback, Run); + EXPECT_CALL(delegate(), SearchBarOnFocusLost); widget().GetFocusManager()->SetFocusedView(nullptr); } TEST_F(PopupSearchBarViewTest, OnInputChangedIsCalledAfterDelay) { - base::MockRepeatingCallback<void(const std::u16string&)> input_callback; - auto view = std::make_unique<PopupSearchBarView>( - u"placeholder", input_callback.Get(), - /*on_focus_lost_callback=*/base::DoNothing(), delegate()); + auto view = std::make_unique<PopupSearchBarView>(u"placeholder", delegate()); MockFunction<void()> check; { InSequence s; EXPECT_CALL(check, Call); - EXPECT_CALL(input_callback, Run(Eq(u"input text"))); + EXPECT_CALL(delegate(), SearchBarOnInputChanged(Eq(u"input text"))); } view->SetInputTextForTesting(u"input text"); @@ -115,16 +112,13 @@ } TEST_F(PopupSearchBarViewTest, OnInputChangedCallbackIsThrottled) { - base::MockRepeatingCallback<void(const std::u16string&)> input_callback; - auto view = std::make_unique<PopupSearchBarView>( - u"placeholder", input_callback.Get(), - /*on_focus_lost_callback=*/base::DoNothing(), delegate()); + auto view = std::make_unique<PopupSearchBarView>(u"placeholder", delegate()); MockFunction<void()> check; { InSequence s; EXPECT_CALL(check, Call); - EXPECT_CALL(input_callback, Run(std::u16string(u"input text 2"))); + EXPECT_CALL(delegate(), SearchBarOnInputChanged(Eq(u"input text 2"))); } view->SetInputTextForTesting(u"input text"); @@ -139,11 +133,8 @@ // TODO(b/338934966): Enable when key events suppressing in tests is fixed. #if !BUILDFLAG(IS_WIN) TEST_F(PopupSearchBarViewTest, KeyPressedFromTextfieldPassedToDelegateFirst) { - base::MockRepeatingCallback<void(const std::u16string&)> input_callback; - PopupSearchBarView* view = - widget().SetContentsView(std::make_unique<PopupSearchBarView>( - u"placeholder", input_callback.Get(), - /*on_focus_lost_callback=*/base::DoNothing(), delegate())); + PopupSearchBarView* view = widget().SetContentsView( + std::make_unique<PopupSearchBarView>(u"placeholder", delegate())); widget().Show(); view->Focus(); @@ -153,7 +144,7 @@ return event.key_code() == ui::VKEY_A ? true : false; }); // As "a" is suppressed, only "bc" is expected. - EXPECT_CALL(input_callback, Run(std::u16string(u"bc"))); + EXPECT_CALL(delegate(), SearchBarOnInputChanged(Eq(u"bc"))); generator().PressAndReleaseKey(ui::VKEY_A); generator().PressAndReleaseKey(ui::VKEY_B); @@ -163,4 +154,30 @@ PopupSearchBarView::kInputChangeCallbackDelay); } #endif // !BUILDFLAG(IS_WIN) + +TEST_F(PopupSearchBarViewTest, ClearButton) { + PopupSearchBarView* view = widget().SetContentsView( + std::make_unique<PopupSearchBarView>(u"placeholder", delegate())); + widget().Show(); + view->Focus(); + + MockFunction<void()> check; + { + InSequence s; + EXPECT_CALL(delegate(), SearchBarOnInputChanged(Eq(u"abc"))); + EXPECT_CALL(check, Call); + EXPECT_CALL(delegate(), SearchBarOnInputChanged(Eq(u""))); + } + + view->SetInputTextForTesting(u"abc"); + task_environment()->FastForwardBy( + PopupSearchBarView::kInputChangeCallbackDelay); + + check.Call(); + + generator().MoveMouseTo(view->GetClearButtonScreenCenterPointForTesting()); + generator().ClickLeftButton(); + task_environment()->FastForwardBy( + PopupSearchBarView::kInputChangeCallbackDelay); +} } // namespace autofill
diff --git a/chrome/browser/ui/views/autofill/popup/popup_view_views.cc b/chrome/browser/ui/views/autofill/popup/popup_view_views.cc index 786f3e5..1a4f16f3 100644 --- a/chrome/browser/ui/views/autofill/popup/popup_view_views.cc +++ b/chrome/browser/ui/views/autofill/popup/popup_view_views.cc
@@ -696,6 +696,25 @@ feature_engagement::kIPHAutofillCreditCardBenefitFeature); } +void PopupViewViews::SearchBarOnInputChanged(const std::u16string& query) { + if (controller_) { + controller_->SetFilter( + query.empty() + ? std::nullopt + : std::optional(AutofillPopupController::SuggestionFilter(query))); + } +} + +void PopupViewViews::SearchBarOnFocusLost() { + // Deactivate to ensure `HasFocus()` won't return `true`. + if (GetWidget()) { + GetWidget()->Deactivate(); + } + if (controller_) { + controller_->Hide(SuggestionHidingReason::kFocusChanged); + } +} + bool PopupViewViews::SearchBarHandleKeyPressed(const ui::KeyEvent& event) { if (!controller_) { return false; @@ -782,12 +801,7 @@ if (search_bar_config.enabled) { search_bar_ = AddChildView(std::make_unique<PopupSearchBarView>( - search_bar_config.placeholder, - base::BindRepeating(&PopupViewViews::OnSearchBarInputChanged, - base::Unretained(this)), - base::BindRepeating(&PopupViewViews::OnSearchBarFocusLost, - base::Unretained(this)), - *this)); + search_bar_config.placeholder, *this)); search_bar_->SetProperty(views::kMarginsKey, gfx::Insets::VH(GetContentsVerticalPadding(), 0)); AddChildView(std::make_unique<PopupSeparatorView>(/*vertical_padding=*/0)); @@ -1188,15 +1202,6 @@ return !suggestion.is_acceptable && !suggestion.apply_deactivated_style; } -void PopupViewViews::OnSearchBarInputChanged(const std::u16string& query) { - if (controller_) { - controller_->SetFilter( - query.empty() - ? std::nullopt - : std::optional(AutofillPopupController::SuggestionFilter(query))); - } -} - bool PopupViewViews::SelectParentPopupContentCell() { if (!row_with_open_sub_popup_) { return false; @@ -1213,16 +1218,6 @@ return true; } -void PopupViewViews::OnSearchBarFocusLost() { - // Deactivate to ensure `HasFocus()` won't return `true`. - if (GetWidget()) { - GetWidget()->Deactivate(); - } - if (controller_) { - controller_->Hide(SuggestionHidingReason::kFocusChanged); - } -} - base::WeakPtr<AutofillPopupView> PopupViewViews::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); }
diff --git a/chrome/browser/ui/views/autofill/popup/popup_view_views.h b/chrome/browser/ui/views/autofill/popup/popup_view_views.h index 7e473bd..04ae88d 100644 --- a/chrome/browser/ui/views/autofill/popup/popup_view_views.h +++ b/chrome/browser/ui/views/autofill/popup/popup_view_views.h
@@ -127,6 +127,8 @@ void OnWidgetVisibilityChanged(views::Widget* widget, bool visible) override; // PopupSearchBarView::Delegate: + void SearchBarOnInputChanged(const std::u16string& text) override; + void SearchBarOnFocusLost() override; bool SearchBarHandleKeyPressed(const ui::KeyEvent& event) override; private: @@ -237,13 +239,6 @@ // fallback suggestion. bool CanOpenSubPopupSuggestion(const Suggestion& suggestion); - // Callback passed to the search bar (if enabled). Hides the popup. - void OnSearchBarFocusLost(); - - // Callback passed to the search bar (if enabled). Updates the controller - // filter with the `query` argument. - void OnSearchBarInputChanged(const std::u16string& query); - // Attempts to select the content cell of the row with the currently open // sub-popup. This closes the sub-popup and has the effect of going one menu // level up. Returns whether this was successful.
diff --git a/chrome/browser/ui/views/performance_controls/performance_intervention_interactive_ui_test.cc b/chrome/browser/ui/views/performance_controls/performance_intervention_interactive_ui_test.cc index 6559a0be..6ec6b62 100644 --- a/chrome/browser/ui/views/performance_controls/performance_intervention_interactive_ui_test.cc +++ b/chrome/browser/ui/views/performance_controls/performance_intervention_interactive_ui_test.cc
@@ -19,7 +19,7 @@ public: void SetUp() override { feature_list_.InitAndEnableFeature( - performance_manager::features::kPerformanceCPUIntervention); + performance_manager::features::kPerformanceIntervention); InteractiveBrowserTest::SetUp(); }
diff --git a/chrome/browser/ui/views/profiles/first_run_intro_browsertest.cc b/chrome/browser/ui/views/profiles/first_run_intro_browsertest.cc index af558d4..e4ff0f9 100644 --- a/chrome/browser/ui/views/profiles/first_run_intro_browsertest.cc +++ b/chrome/browser/ui/views/profiles/first_run_intro_browsertest.cc
@@ -43,19 +43,15 @@ // Permutations of supported parameters. const FirstRunTestParam kTestParams[] = { {.pixel_test_param = {.test_suffix = "DarkThemeFixedSize", - .use_dark_theme = true, - .use_fre_style = true}, + .use_dark_theme = true}, .use_fixed_size = true}, - {.pixel_test_param = {.test_suffix = "LightTheme", .use_fre_style = true}}, - {.pixel_test_param = {.test_suffix = "LongerStringsFixedSize", - .use_fre_style = true}, + {.pixel_test_param = {.test_suffix = "LightTheme"}}, + {.pixel_test_param = {.test_suffix = "LongerStringsFixedSize"}, .use_fixed_size = true, .use_longer_strings = true}, {.pixel_test_param = {.test_suffix = "RightToLeftLanguage", - .use_right_to_left_language = true, - .use_fre_style = true}}, + .use_right_to_left_language = true}}, {.pixel_test_param = {.test_suffix = "CR2023", - .use_fre_style = true, .use_chrome_refresh_2023_style = true}}, };
diff --git a/chrome/browser/ui/views/profiles/profiles_pixel_test_utils.cc b/chrome/browser/ui/views/profiles/profiles_pixel_test_utils.cc index 00a5f5c..5e5ee6ab 100644 --- a/chrome/browser/ui/views/profiles/profiles_pixel_test_utils.cc +++ b/chrome/browser/ui/views/profiles/profiles_pixel_test_utils.cc
@@ -119,11 +119,6 @@ enabled_features.push_back(features::kChromeRefresh2023); enabled_features.push_back(features::kChromeWebuiRefresh2023); } -#if BUILDFLAG(ENABLE_DICE_SUPPORT) - if (params.use_fre_style) { - enabled_features.push_back(kForYouFre); - } -#endif feature_list.InitWithFeatures(enabled_features, disabled_features); }
diff --git a/chrome/browser/ui/views/profiles/profiles_pixel_test_utils.h b/chrome/browser/ui/views/profiles/profiles_pixel_test_utils.h index c67e293..db71aaf 100644 --- a/chrome/browser/ui/views/profiles/profiles_pixel_test_utils.h +++ b/chrome/browser/ui/views/profiles/profiles_pixel_test_utils.h
@@ -35,7 +35,6 @@ bool use_dark_theme = false; bool use_right_to_left_language = false; bool use_small_window = false; - bool use_fre_style = false; bool use_chrome_refresh_2023_style = false; };
diff --git a/chrome/browser/ui/views/promos/autofill_bubble_signin_promo_interactive_uitest.cc b/chrome/browser/ui/views/promos/autofill_bubble_signin_promo_interactive_uitest.cc index 96e5763..62bd751 100644 --- a/chrome/browser/ui/views/promos/autofill_bubble_signin_promo_interactive_uitest.cc +++ b/chrome/browser/ui/views/promos/autofill_bubble_signin_promo_interactive_uitest.cc
@@ -22,10 +22,12 @@ #include "components/signin/public/base/consent_level.h" #include "components/signin/public/base/signin_pref_names.h" #include "components/signin/public/base/signin_switches.h" +#include "components/signin/public/identity_manager/accounts_mutator.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync/base/features.h" #include "content/public/test/browser_test.h" +#include "google_apis/gaia/gaia_auth_consumer.h" namespace { constexpr char kButton[] = "SignInButton"; @@ -58,10 +60,8 @@ } // Trigger the password save by simulating an "Accept" in the password bubble, - // and wait for it to appear in the store. If |store| is kAccountStore, it - // will wait for a password to appear in the account store, if not, in the - // profile store. - void SavePassword(password_manager::PasswordForm::Store store); + // and wait for it to appear in the profile store. + void SavePassword(); // Perform a sign in with the password bubble access point and wait for an // event in the account store. @@ -92,12 +92,9 @@ scoped_refptr<password_manager::TestPasswordStore> account_password_store_; }; -void AutofillBubbleSignInPromoInteractiveUITest::SavePassword( - password_manager::PasswordForm::Store store) { - auto store_waiter = - store == password_manager::PasswordForm::Store::kAccountStore - ? password_manager::PasswordStoreWaiter(account_password_store_.get()) - : password_manager::PasswordStoreWaiter(local_password_store_.get()); +void AutofillBubbleSignInPromoInteractiveUITest::SavePassword() { + password_manager::PasswordStoreWaiter store_waiter( + local_password_store_.get()); PasswordBubbleViewBase* bubble = PasswordBubbleViewBase::manage_password_bubble(); @@ -138,7 +135,7 @@ local_password_store_.get(), account_password_store_.get())); // Save the password and check that it was properly saved to profile store. - SavePassword(password_manager::PasswordForm::Store::kProfileStore); + SavePassword(); EXPECT_EQ(1u, local_password_store_->stored_passwords().size()); EXPECT_EQ(0u, account_password_store_->stored_passwords().size()); @@ -202,7 +199,7 @@ local_password_store_.get(), account_password_store_.get())); // Save the password and check that it was properly saved to profile store. - SavePassword(password_manager::PasswordForm::Store::kProfileStore); + SavePassword(); EXPECT_EQ(1u, local_password_store_->stored_passwords().size()); EXPECT_EQ(0u, account_password_store_->stored_passwords().size()); @@ -255,18 +252,14 @@ identity_manager(), info.account_id, GoogleServiceAuthError( GoogleServiceAuthError::State::USER_NOT_SIGNED_UP)); - // Set up password and password stores. GetController()->OnPasswordSubmitted(CreateFormManager( local_password_store_.get(), account_password_store_.get())); - // Simulate the use of account store. - SetupSaveToAccountStore(); - - // Save the password and check that it was properly saved to account store. - SavePassword(password_manager::PasswordForm::Store::kAccountStore); - EXPECT_EQ(0u, local_password_store_->stored_passwords().size()); - EXPECT_EQ(1u, account_password_store_->stored_passwords().size()); + // Save the password and check that it was properly saved to profile store. + SavePassword(); + EXPECT_EQ(1u, local_password_store_->stored_passwords().size()); + EXPECT_EQ(0u, account_password_store_->stored_passwords().size()); // Wait for the bubble to be replaced with the sign in promo and click // the sign in button. @@ -287,21 +280,30 @@ // Check that clicking the sign in button navigated to a sign in page. EXPECT_TRUE(IsSignInURL()); - // Check that there is no helper attached to the sign in tab, because the - // password does not need to be moved. - EXPECT_FALSE(autofill::AutofillSigninPromoTabHelper::GetForWebContents( - *browser()->tab_strip_model()->GetActiveWebContents()) - ->IsInitializedForTesting()); + // Check that there is a helper attached to the sign in tab, because the + // password still needs to be moved. + EXPECT_TRUE(autofill::AutofillSigninPromoTabHelper::GetForWebContents( + *browser()->tab_strip_model()->GetActiveWebContents()) + ->IsInitializedForTesting()); + EXPECT_FALSE(IsSignedIn()); // Set a new refresh token for the primary account, which verifies the - // user's identity and signs them back in. The password will stay in the + // user's identity and signs them back in. The password will be moved to // account store. - signin::SetRefreshTokenForPrimaryAccount(identity_manager()); + auto account_store_waiter = + password_manager::PasswordStoreWaiter(account_password_store_.get()); + identity_manager()->GetAccountsMutator()->AddOrUpdateAccount( + info.gaia, info.email, "dummy_refresh_token", + /*is_under_advanced_protection=*/false, + signin_metrics::AccessPoint::ACCESS_POINT_PASSWORD_BUBBLE, + signin_metrics::SourceForRefreshTokenOperation:: + kDiceResponseHandler_PasswordPromoSignin); + account_store_waiter.WaitOrReturn(); // Check that the sign in was successful. EXPECT_TRUE(IsSignedIn()); - // Check that password is still account store. + // Check that password was moved to account store. EXPECT_EQ(0u, local_password_store_->stored_passwords().size()); EXPECT_EQ(1u, account_password_store_->stored_passwords().size());
diff --git a/chrome/browser/ui/views/side_panel/side_panel.cc b/chrome/browser/ui/views/side_panel/side_panel.cc index c90238f..3ef1d7de 100644 --- a/chrome/browser/ui/views/side_panel/side_panel.cc +++ b/chrome/browser/ui/views/side_panel/side_panel.cc
@@ -458,25 +458,31 @@ void SidePanel::UpdateVisibility() { bool should_be_open = false; + bool animate_transition = true; std::vector<views::View*> views_to_hide; // TODO(pbos): Iterate content instead. Requires moving the owned pointer out // of owned contents before resetting it. for (views::View* view : children()) { - if (view == border_view_ || view == resize_area_ || view == header_view_) { + if (view == border_view_ || view == resize_area_ || view == header_view_ || + !view->GetVisible()) { continue; } - if (view->GetVisible() && - static_cast<SidePanelContentState>( - view->GetProperty(kSidePanelContentStateKey)) == - SidePanelContentState::kReadyToHide) { - views_to_hide.push_back(view); - } - if (view->GetVisible() && - static_cast<SidePanelContentState>( - view->GetProperty(kSidePanelContentStateKey)) == - SidePanelContentState::kReadyToShow) { - should_be_open = true; + SidePanelContentState current_state = static_cast<SidePanelContentState>( + view->GetProperty(kSidePanelContentStateKey)); + switch (current_state) { + case SidePanelContentState::kHideImmediately: + animate_transition = false; + [[fallthrough]]; + case SidePanelContentState::kReadyToHide: + views_to_hide.push_back(view); + break; + case SidePanelContentState::kShowImmediately: + animate_transition = false; + [[fallthrough]]; + case SidePanelContentState::kReadyToShow: + should_be_open = true; + break; } } // Make sure the border visibility matches the side panel. Also dynamically @@ -504,7 +510,7 @@ border_view_->DestroyLayer(); } } - if (ShouldShowAnimation()) { + if (ShouldShowAnimation() && animate_transition) { if (should_be_open) { // If the side panel should remain open but there are views to hide, hide // them immediately.
diff --git a/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc b/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc index b5abe1d..8e7e9774 100644 --- a/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc +++ b/chrome/browser/ui/views/side_panel/side_panel_coordinator.cc
@@ -395,21 +395,7 @@ } void SidePanelCoordinator::Close() { - if (!IsSidePanelShowing() || - browser_view_->unified_side_panel()->IsClosing()) { - return; - } - - if (current_entry_ && - browser_view_->toolbar()->pinned_toolbar_actions_container()) { - NotifyPinnedContainerOfActiveStateChange(current_entry_->key(), false); - } - if (views::View* content_container = GetContentContainerView()) { - content_container->SetProperty( - kSidePanelContentStateKey, - static_cast<std::underlying_type_t<SidePanelContentState>>( - SidePanelContentState::kReadyToHide)); - } + Close(/*supress_animations=*/false); } void SidePanelCoordinator::Toggle() { @@ -591,7 +577,8 @@ void SidePanelCoordinator::Show( SidePanelEntry* entry, - std::optional<SidePanelUtil::SidePanelOpenTrigger> open_trigger) { + std::optional<SidePanelUtil::SidePanelOpenTrigger> open_trigger, + bool supress_animations) { // Side panel is not supported for non-normal browsers. if (!browser_view_->browser()->is_type_normal()) { return; @@ -667,7 +654,26 @@ content_wrapper->RequestEntry( entry, base::BindOnce(&SidePanelCoordinator::PopulateSidePanel, - base::Unretained(this))); + base::Unretained(this), supress_animations)); +} + +void SidePanelCoordinator::Close(bool supress_animations) { + if (!IsSidePanelShowing() || + browser_view_->unified_side_panel()->IsClosing()) { + return; + } + + if (current_entry_ && + browser_view_->toolbar()->pinned_toolbar_actions_container()) { + NotifyPinnedContainerOfActiveStateChange(current_entry_->key(), false); + } + if (views::View* content_container = GetContentContainerView()) { + content_container->SetProperty( + kSidePanelContentStateKey, + static_cast<std::underlying_type_t<SidePanelContentState>>( + supress_animations ? SidePanelContentState::kHideImmediately + : SidePanelContentState::kReadyToHide)); + } } views::View* SidePanelCoordinator::GetContentContainerView() const { @@ -746,6 +752,7 @@ } void SidePanelCoordinator::PopulateSidePanel( + bool supress_animations, SidePanelEntry* entry, std::optional<std::unique_ptr<views::View>> content_view) { if (!header_combobox_) { @@ -775,7 +782,8 @@ content_container->SetProperty( kSidePanelContentStateKey, static_cast<std::underlying_type_t<SidePanelContentState>>( - SidePanelContentState::kReadyToShow)); + supress_animations ? SidePanelContentState::kShowImmediately + : SidePanelContentState::kReadyToShow)); if (current_entry_ && content_wrapper->children().size()) { auto current_entry_view = @@ -939,7 +947,7 @@ auto* header_close_button = header->AddChildView(CreateControlButton( header.get(), - base::BindRepeating(&SidePanelCoordinator::Close, base::Unretained(this)), + base::BindRepeating(&SidePanelUI::Close, base::Unretained(this)), views::kIcCloseIcon, l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE), kSidePanelCloseButtonElementId, ChromeLayoutProvider::Get()->GetDistanceMetric( @@ -1219,7 +1227,8 @@ // Attempt to find a suitable entry to be shown after the tab switch and if // one is found, show it. if (auto* new_active_entry = GetNewActiveEntryOnTabChanged()) { - Show(new_active_entry, SidePanelUtil::SidePanelOpenTrigger::kTabChanged); + Show(new_active_entry, SidePanelUtil::SidePanelOpenTrigger::kTabChanged, + /*supress_animations=*/true); if (combobox_model_) { SetSelectedEntryInCombobox(new_active_entry->key()); } @@ -1238,12 +1247,13 @@ auto* active_entry = old_contextual_registry->active_entry().value(); active_entry->CacheView(std::move(current_entry_view)); } - Close(); + Close(/*supress_animations=*/true); } } else if (new_contextual_registry && new_contextual_registry->active_entry().has_value()) { Show(new_contextual_registry->active_entry().value(), - SidePanelUtil::SidePanelOpenTrigger::kTabChanged); + SidePanelUtil::SidePanelOpenTrigger::kTabChanged, + /*supress_animations=*/true); } }
diff --git a/chrome/browser/ui/views/side_panel/side_panel_coordinator.h b/chrome/browser/ui/views/side_panel/side_panel_coordinator.h index 2cd4c4b..3e64a62 100644 --- a/chrome/browser/ui/views/side_panel/side_panel_coordinator.h +++ b/chrome/browser/ui/views/side_panel/side_panel_coordinator.h
@@ -140,7 +140,9 @@ // entry instead of letting GetEntryForKey() decide for us. void Show(SidePanelEntry* entry, std::optional<SidePanelUtil::SidePanelOpenTrigger> open_trigger = - std::nullopt); + std::nullopt, + bool supress_animations = false); + void Close(bool supress_animations); void OnClosed(); views::View* GetContentContainerView() const; @@ -170,6 +172,7 @@ // `content_view` if provided, otherwise get the content_view from the // provided SidePanelEntry. void PopulateSidePanel( + bool supress_animations, SidePanelEntry* entry, std::optional<std::unique_ptr<views::View>> content_view);
diff --git a/chrome/browser/ui/views/toolbar/toolbar_view.cc b/chrome/browser/ui/views/toolbar/toolbar_view.cc index 55d3439..e02fe5d5 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_view.cc
@@ -442,7 +442,7 @@ } if (base::FeatureList::IsEnabled( - performance_manager::features::kPerformanceCPUIntervention)) { + performance_manager::features::kPerformanceIntervention)) { performance_intervention_button_ = container_view_->AddChildView( std::make_unique<PerformanceInterventionButton>()); }
diff --git a/chrome/browser/ui/webui/ash/edu_coexistence/edu_coexistence_login_handler_browsertest.cc b/chrome/browser/ui/webui/ash/edu_coexistence/edu_coexistence_login_handler_browsertest.cc index 2922fd3..021fd83 100644 --- a/chrome/browser/ui/webui/ash/edu_coexistence/edu_coexistence_login_handler_browsertest.cc +++ b/chrome/browser/ui/webui/ash/edu_coexistence/edu_coexistence_login_handler_browsertest.cc
@@ -105,9 +105,9 @@ content::TestWebUI* web_ui() { return &web_ui_; } private: - LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, - LoggedInUserMixin::LogInType::kChild, - embedded_test_server(), this}; + LoggedInUserMixin logged_in_user_mixin_{&mixin_host_, /*test_base=*/this, + embedded_test_server(), + LoggedInUserMixin::LogInType::kChild}; base::HistogramTester histograms_;
diff --git a/chrome/browser/ui/webui/ash/parent_access/parent_access_browsertest_base.cc b/chrome/browser/ui/webui/ash/parent_access/parent_access_browsertest_base.cc index ec13397..f12f169 100644 --- a/chrome/browser/ui/webui/ash/parent_access/parent_access_browsertest_base.cc +++ b/chrome/browser/ui/webui/ash/parent_access/parent_access_browsertest_base.cc
@@ -21,7 +21,7 @@ void ParentAccessBrowserTestBase::SetUp() { logged_in_user_mixin_ = std::make_unique<LoggedInUserMixin>( - &mixin_host_, GetLogInType(), embedded_test_server(), this); + &mixin_host_, /*test_base=*/this, embedded_test_server(), GetLogInType()); // Setup() must be called after the mixin is instantiated because it is what // actually causes the tests to be run. MixinBasedInProcessBrowserTest::SetUp(); @@ -67,7 +67,7 @@ // ParentAccessBrowserTestBase methods LoggedInUserMixin::LogInType ParentAccessRegularUserBrowserTestBase::GetLogInType() { - return LoggedInUserMixin::LogInType::kRegular; + return LoggedInUserMixin::LogInType::kConsumer; } // ParentAccessChildUserBrowserTestBase
diff --git a/chrome/browser/ui/webui/ash/settings/test_support/os_settings_lock_screen_browser_test_base.cc b/chrome/browser/ui/webui/ash/settings/test_support/os_settings_lock_screen_browser_test_base.cc index 4e97224..0e1db84 100644 --- a/chrome/browser/ui/webui/ash/settings/test_support/os_settings_lock_screen_browser_test_base.cc +++ b/chrome/browser/ui/webui/ash/settings/test_support/os_settings_lock_screen_browser_test_base.cc
@@ -32,8 +32,9 @@ } logged_in_user_mixin_ = std::make_unique<LoggedInUserMixin>( - &mixin_host_, LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), this, /*should_launch_browser=*/true, + &mixin_host_, /*test_base=*/this, embedded_test_server(), + LoggedInUserMixin::LogInType::kConsumer, + /*include_initial_user=*/true, /*account_id=*/std::nullopt, config); cryptohome_ = &logged_in_user_mixin_->GetCryptohomeMixin(); cryptohome_->set_enable_auth_check(true);
diff --git a/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc b/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc index 53da1c369..d5c79075b 100644 --- a/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc +++ b/chrome/browser/ui/webui/chrome_url_data_manager_browsertest.cc
@@ -204,8 +204,6 @@ enabled_features.push_back(ash::features::kDriveFsMirroring); enabled_features.push_back(ash::features::kShimlessRMAOsUpdate); enabled_features.push_back(chromeos::features::kUploadOfficeToCloud); -#else - enabled_features.push_back(kForYouFre); #endif feature_list_.InitWithFeatures(enabled_features, {}); }
diff --git a/chrome/browser/ui/webui/policy/policy_ui_browsertest.cc b/chrome/browser/ui/webui/policy/policy_ui_browsertest.cc index 99fd95d..c21aa01 100644 --- a/chrome/browser/ui/webui/policy/policy_ui_browsertest.cc +++ b/chrome/browser/ui/webui/policy/policy_ui_browsertest.cc
@@ -305,13 +305,8 @@ &mixin_host_, ash::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; ash::LoggedInUserMixin logged_in_user_mixin_{ - &mixin_host_, - ash::LoggedInUserMixin::LogInType::kRegular, - embedded_test_server(), - this, - /*should_launch_browser=*/true, - AccountId::FromUserEmailGaiaId(policy::PolicyBuilder::kFakeUsername, - policy::PolicyBuilder::kFakeGaiaId)}; + &mixin_host_, /*test_base=*/this, embedded_test_server(), + ash::LoggedInUserMixin::LogInType::kManaged}; }; bool PolicyUIStatusTest::ReadStatusFor(
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 3419fb3..f48a629 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -563,8 +563,6 @@ void AddGetTheMostOutOfChromeStrings(content::WebUIDataSource* html_source) { static constexpr webui::LocalizedString kLocalizedStrings[] = { {"getTheMostOutOfChrome", IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME}, - {"getTheMostOutOfChromePageButton", - IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME_PAGE_BUTTON}, {"getTheMostOutOfChromeBetterForYou", IDS_SETTINGS_GET_THE_MOST_OUT_OF_CHROME_BETTER_FOR_YOU}, {"getTheMostOutOfChromeYourDataInChrome", @@ -1431,10 +1429,7 @@ #if !BUILDFLAG(IS_CHROMEOS_LACROS) {"syncAdvancedPageTitle", IDS_SETTINGS_NEW_SYNC_ADVANCED_PAGE_TITLE}, #endif - // TODO(crbug.com/330680561): Use a settings specific string or combine - // all the string usages of "Verify it's you" in a single translatable - // string. - {"signinPaused", IDS_AVATAR_BUTTON_SIGNIN_PAUSED}, + {"verifyAccount", IDS_PROFILES_VERIFY_ACCOUNT_BUTTON}, }; html_source->AddLocalizedStrings(kLocalizedStrings);
diff --git a/chrome/browser/ui/webui/side_panel/performance_controls/performance_side_panel_ui.cc b/chrome/browser/ui/webui/side_panel/performance_controls/performance_side_panel_ui.cc index a5240d77..cc69d04 100644 --- a/chrome/browser/ui/webui/side_panel/performance_controls/performance_side_panel_ui.cc +++ b/chrome/browser/ui/webui/side_panel/performance_controls/performance_side_panel_ui.cc
@@ -48,14 +48,8 @@ source->AddResourcePaths(base::make_span(kSidePanelSharedResources, kSidePanelSharedResourcesSize)); - source->AddBoolean( - "isPerformanceCPUInterventionEnabled", - base::FeatureList::IsEnabled( - performance_manager::features::kPerformanceCPUIntervention)); - source->AddBoolean( - "isPerformanceMemoryInterventionEnabled", - base::FeatureList::IsEnabled( - performance_manager::features::kPerformanceMemoryIntervention)); + source->AddBoolean("isPerformanceCPUInterventionEnabled", false); + source->AddBoolean("isPerformanceMemoryInterventionEnabled", false); url::Component query(0, static_cast<int>(url.query_piece().length())); url::Component key, value;
diff --git a/chrome/build/android-arm32.pgo.txt b/chrome/build/android-arm32.pgo.txt index c854e7a..bce9ba9 100644 --- a/chrome/build/android-arm32.pgo.txt +++ b/chrome/build/android-arm32.pgo.txt
@@ -1 +1 @@ -chrome-android32-main-1715061348-eeadc61172488720ca7b9d7802f1f2f43c31e157-974d107e4e5cbade7c0f7ede9127ab07641e8cef.profdata +chrome-android32-main-1715082852-e9e1450495829fb107ed5b75caae033176938cdc-49ee37fcc316a7797ae7fd0e599576fdb8b9c5e1.profdata
diff --git a/chrome/build/android-arm64.pgo.txt b/chrome/build/android-arm64.pgo.txt index 2f8f8a6..c2d6044 100644 --- a/chrome/build/android-arm64.pgo.txt +++ b/chrome/build/android-arm64.pgo.txt
@@ -1 +1 @@ -chrome-android64-main-1715039966-4faceb4c71a66fa21c64d27628adfa7cd68bda7b-a9dc5f3d1de565d109b15b763b0f606dc240c1e0.profdata +chrome-android64-main-1715090204-f51dc649c4742c39391deb97cee7911422cdb81b-45579a61c795e48c94e153917f27aafd0a2b3125.profdata
diff --git a/chrome/build/lacros64.pgo.txt b/chrome/build/lacros64.pgo.txt index f14de06..286ab0d 100644 --- a/chrome/build/lacros64.pgo.txt +++ b/chrome/build/lacros64.pgo.txt
@@ -1 +1 @@ -chrome-chromeos-amd64-generic-main-1715039966-e871306a02ea161d968074b654841d763f29c301-a9dc5f3d1de565d109b15b763b0f606dc240c1e0.profdata +chrome-chromeos-amd64-generic-main-1715082852-108f667640867729e871512d4938adbfbaa34b53-49ee37fcc316a7797ae7fd0e599576fdb8b9c5e1.profdata
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index c586e56..031018f 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1715061348-7f667676f930b42fe03b47b4ea07949eb0ad71a2-974d107e4e5cbade7c0f7ede9127ab07641e8cef.profdata +chrome-linux-main-1715082852-ff170f32eab7eb5979ed7e223bc9183b49dfffc7-49ee37fcc316a7797ae7fd0e599576fdb8b9c5e1.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 18618e3..acae075 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1715068359-eef3d259db683f900b6a48bd3b41d8d3e540b019-f28d59839051eb5e07ad77e54761edb9cc9371fa.profdata +chrome-mac-arm-main-1715090204-a8f2a91ea8527f08b109b90492dd26e8d7ac6bfb-45579a61c795e48c94e153917f27aafd0a2b3125.profdata
diff --git a/chrome/build/win-arm64.pgo.txt b/chrome/build/win-arm64.pgo.txt index 24644cc..e9608ec 100644 --- a/chrome/build/win-arm64.pgo.txt +++ b/chrome/build/win-arm64.pgo.txt
@@ -1 +1 @@ -chrome-win-arm64-main-1715061348-9e525c44c9dcc7821f0a168eb3d51676ed9aba7d-974d107e4e5cbade7c0f7ede9127ab07641e8cef.profdata +chrome-win-arm64-main-1715082852-57977b35713e7db3709bc63d9bfd8054015d1f3c-49ee37fcc316a7797ae7fd0e599576fdb8b9c5e1.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index df98b42..465eef3 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1715050601-53367db54d1bdf7cb3dbf9d10d124cb91250fdf1-ad615e4ff6bc7bc246331d104b5d17a7cb58a087.profdata +chrome-win32-main-1715072136-332a9bbbdefc3724e54b1aba19835872477ed003-c25f67a53e00700c65b77f63ed5c055bd8116676.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index ffaa1c30..5356e74 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1715050601-f3d8f477d141180c95b89d7f60af8542bfb0fadc-ad615e4ff6bc7bc246331d104b5d17a7cb58a087.profdata +chrome-win64-main-1715082852-de2c97d7691e00aafae2bdfb1ac1a4769512186c-49ee37fcc316a7797ae7fd0e599576fdb8b9c5e1.profdata
diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index 6757c9a..2d7c5d71 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn
@@ -262,6 +262,8 @@ "//build:chromeos_buildflags", "//components/crash/core/app", "//components/google/core/common", + "//components/heap_profiling/in_process", + "//components/heap_profiling/in_process:mojom", "//components/live_caption:constants", "//components/metrics:call_stack_profile_builder", "//components/no_state_prefetch/common",
diff --git a/chrome/common/DEPS b/chrome/common/DEPS index 3862c29..848135d 100644 --- a/chrome/common/DEPS +++ b/chrome/common/DEPS
@@ -26,6 +26,7 @@ "+components/flags_ui/flags_ui_switches.h", "+components/gcm_driver", "+components/google/core/common", + "+components/heap_profiling/in_process", "+components/live_caption/pref_names.h", "+components/metrics/client_info.h", "+components/metrics/metadata_recorder.h",
diff --git a/chrome/common/chrome_content_client.cc b/chrome/common/chrome_content_client.cc index ae3a91e..16622c4f 100644 --- a/chrome/common/chrome_content_client.cc +++ b/chrome/common/chrome_content_client.cc
@@ -11,6 +11,7 @@ #include <string_view> #include <utility> +#include "base/check.h" #include "base/containers/flat_set.h" #include "base/files/file_util.h" #include "base/functional/bind.h" @@ -40,6 +41,9 @@ #include "components/crash/core/common/crash_key.h" #include "components/dom_distiller/core/url_constants.h" #include "components/embedder_support/origin_trials/origin_trial_policy_impl.h" +#include "components/heap_profiling/in_process/child_process_snapshot_controller.h" +#include "components/heap_profiling/in_process/heap_profiler_controller.h" +#include "components/heap_profiling/in_process/mojom/snapshot_controller.mojom.h" #include "components/services/heap_profiling/public/cpp/profiling_client.h" #include "components/strings/grit/components_strings.h" #include "content/public/common/cdm_info.h" @@ -372,6 +376,9 @@ void ChromeContentClient::ExposeInterfacesToBrowser( scoped_refptr<base::SequencedTaskRunner> io_task_runner, mojo::BinderMap* binders) { + // Sets up the client side of the multi-process heap profiler service. + // TODO(crbug.com/40915258): Hook up chrome://memory-internals to the + // in-process heap profiler, and delete this service. binders->Add<heap_profiling::mojom::ProfilingClient>( base::BindRepeating( [](mojo::PendingReceiver<heap_profiling::mojom::ProfilingClient> @@ -381,4 +388,16 @@ profiling_client->BindToInterface(std::move(receiver)); }), io_task_runner); + + // Sets up the simplified in-process heap profiler, if it's enabled. + const auto* heap_profiler_controller = + heap_profiling::HeapProfilerController::GetInstance(); + if (heap_profiler_controller && heap_profiler_controller->IsEnabled()) { + binders->Add<heap_profiling::mojom::SnapshotController>( + base::BindRepeating(&heap_profiling::ChildProcessSnapshotController:: + CreateSelfOwnedReceiver), + // ChildProcessSnapshotController calls into HeapProfilerController, + // which can only be accessed on this sequence. + base::SequencedTaskRunner::GetCurrentDefault()); + } }
diff --git a/chrome/renderer/autofill/form_autocomplete_browsertest.cc b/chrome/renderer/autofill/form_autocomplete_browsertest.cc index 8b03191c..767789e2 100644 --- a/chrome/renderer/autofill/form_autocomplete_browsertest.cc +++ b/chrome/renderer/autofill/form_autocomplete_browsertest.cc
@@ -737,21 +737,21 @@ // Parameterized test for submission detection. The parameter dictates whether // the tests run with `kAutofillReplaceFormElementObserver` enabled or not. -class FormAutocompleteSubmissionTest - : public FormAutocompleteTest, - public testing::WithParamInterface<bool> { +class FormAutocompleteSubmissionTest : public FormAutocompleteTest, + public testing::WithParamInterface<int> { public: FormAutocompleteSubmissionTest() { - if (GetParam()) { - scoped_feature_list_.InitWithFeatures( - /*enabled_features=*/ - {features::kAutofillReplaceCachedWebElementsByRendererIds, - features::kAutofillReplaceFormElementObserver}, - /*disabled_features=*/{}); - } else { - scoped_feature_list_.InitAndDisableFeature( - features::kAutofillReplaceFormElementObserver); - } + EXPECT_LE(GetParam(), 3); + std::vector<base::test::FeatureRef> features = { + features::kAutofillUnifyAndFixFormTracking, + features::kAutofillReplaceCachedWebElementsByRendererIds, + features::kAutofillReplaceFormElementObserver}; + + std::vector<base::test::FeatureRef> enabled_features( + features.begin(), features.begin() + GetParam()); + std::vector<base::test::FeatureRef> disabled_features( + features.begin() + GetParam(), features.end()); + scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); } private: @@ -760,7 +760,7 @@ INSTANTIATE_TEST_SUITE_P(AutofillSubmissionTest, FormAutocompleteSubmissionTest, - ::testing::Bool()); + ::testing::Values(0, 1, 2, 3)); // Tests that submitting a form generates FormSubmitted message with the form // fields. @@ -768,8 +768,9 @@ // Load a form. LoadHTML( "<html><form id='myForm' action='about:blank'>" - "<input name='fname' value='Rick'/>" + "<input name='fname' id='fname'/>" "<input name='lname' value='Deckard'/></form></html>"); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Submit the form. ExecuteJavaScriptForTests("document.getElementById('myForm').submit();"); @@ -785,9 +786,10 @@ TEST_P(FormAutocompleteSubmissionTest, SubmitEventPrevented) { // Load a form. LoadHTML( - "<html><form id='myForm'><input name='fname' value='Rick'/>" + "<html><form id='myForm'><input name='fname' id='fname'/>" "<input name='lname' value='Deckard'/><input type=submit></form>" "</html>"); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Submit the form. ExecuteJavaScriptForTests( @@ -809,13 +811,7 @@ "<html><form id='myForm' action='http://example.com/blade.php'>" "<input name='fname' id='fname' value='Bob'/>" "<input name='lname' value='Deckard'/><input type=submit></form></html>"); - - // Simulate user input so that the form is "remembered". - WebDocument document = GetMainFrame()->GetDocument(); - WebElement element = document.GetElementById(WebString::FromUTF8("fname")); - ASSERT_FALSE(element.IsNull()); - WebInputElement fname_element = element.To<WebInputElement>(); - SimulateUserInputChangeForElement(&fname_element, std::string("Rick")); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Simulate removing the form just before the ajax request completes. ExecuteJavaScriptForTests( @@ -844,13 +840,7 @@ "<form id='myForm2' action='http://example.com/runner.php'>" "<input name='fname' id='fname2' value='Bob'/>" "<input name='lname' value='Deckard'/><input type=submit></form></html>"); - - // Simulate user input so that the form is "remembered". - WebDocument document = GetMainFrame()->GetDocument(); - WebElement element = document.GetElementById(WebString::FromUTF8("fname")); - ASSERT_FALSE(element.IsNull()); - WebInputElement fname_element = element.To<WebInputElement>(); - SimulateUserInputChangeForElement(&fname_element, std::string("Rick")); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Simulate removing the form just before the ajax request completes. ExecuteJavaScriptForTests( @@ -886,13 +876,7 @@ "<form id='myForm2'>" "<input name='fname' id='fname2' value='John'/>" "<input name='lname' value='Doe'/><input type=submit></form></html>"); - - // Simulate user input so that the form is "remembered". - WebDocument document = GetMainFrame()->GetDocument(); - WebElement element = document.GetElementById(WebString::FromUTF8("fname")); - ASSERT_FALSE(element.IsNull()); - WebInputElement fname_element = element.To<WebInputElement>(); - SimulateUserInputChangeForElement(&fname_element, std::string("Rick")); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Simulate removing the form just before the ajax request completes. ExecuteJavaScriptForTests( @@ -916,13 +900,7 @@ "<html><form id='myForm'>" "<input name='fname' id='fname' value='Bob'/>" "<input name='lname' value='Deckard'/><input type=submit></form></html>"); - - // Simulate user input so that the form is "remembered". - WebDocument document = GetMainFrame()->GetDocument(); - WebElement element = document.GetElementById(WebString::FromUTF8("fname")); - ASSERT_FALSE(element.IsNull()); - WebInputElement fname_element = element.To<WebInputElement>(); - SimulateUserInputChangeForElement(&fname_element, std::string("Rick")); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Simulate removing the form just before the ajax request completes. ExecuteJavaScriptForTests( @@ -948,11 +926,7 @@ "<input name='lname' value='Deckard'/><input type=submit></form></html>"); // Simulate user input so that the form is "remembered". - WebDocument document = GetMainFrame()->GetDocument(); - WebElement element = document.GetElementById(WebString::FromUTF8("fname")); - ASSERT_FALSE(element.IsNull()); - WebInputElement fname_element = element.To<WebInputElement>(); - SimulateUserInputChangeForElement(&fname_element, std::string("Rick")); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Simulate an Ajax request completing. static_cast<blink::WebAutofillClient*>(autofill_agent_)->AjaxSucceeded(); @@ -996,8 +970,6 @@ "<html><form id='myForm' action='http://example.com/blade.php'>" "<input name='fname' id='fname'/>" "<input name='lname'/></form></html>"); - - // Simulate filling a form using Autofill. SimulateFillForm(autofill_agent_, GetMainFrame()); // Simulate user input since ajax request doesn't fire submission message @@ -1027,8 +999,6 @@ "<html><form id='myForm' action='http://example.com/blade.php'>" "<input name='fname' id='fname' value='Rick'/>" "<input name='lname' value='Deckard'/></form></html>"); - - // Simulate filling a form using Autofill. SimulateFillForm(autofill_agent_, GetMainFrame()); // Form still visible. @@ -1051,13 +1021,7 @@ "<input type='text' name='fname' id='fname'/>" "<input type='text' name='lname' value='Puckett'/>" "<input type='number' name='number' value='34'/>"); - - // Simulate user input. - WebDocument document = GetMainFrame()->GetDocument(); - WebElement element = document.GetElementById(WebString::FromUTF8("fname")); - ASSERT_FALSE(element.IsNull()); - WebInputElement fname_element = element.To<WebInputElement>(); - SimulateUserInputChangeForElement(&fname_element, std::string("Kirby")); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Kirby")); // Remove element from view. ExecuteJavaScriptForTests( @@ -1080,9 +1044,10 @@ // Load a form. LoadHTML( "<html><form id='myForm' autocomplete='off' action='about:blank'>" - "<input name='fname' value='Rick'/>" + "<input name='fname' id='fname'/>" "<input name='lname' value='Deckard'/>" "</form></html>"); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Submit the form. ExecuteJavaScriptForTests("document.getElementById('myForm').submit();"); @@ -1098,9 +1063,10 @@ // Load a form. LoadHTML( "<html><form id='myForm' action='about:blank'>" - "<input name='fname' value='Rick'/>" + "<input name='fname' id='fname'/>" "<input name='lname' value='Deckard' autocomplete='off'/>" "</form></html>"); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); // Submit the form. ExecuteJavaScriptForTests("document.getElementById('myForm').submit();"); @@ -1117,8 +1083,9 @@ TEST_P(FormAutocompleteSubmissionTest, DynamicAutoCompleteOffFormSubmit) { LoadHTML( "<html><form id='myForm' action='about:blank'>" - "<input name='fname' value='Rick'/>" + "<input name='fname' id='fname'/>" "<input name='lname' value='Deckard'/></form></html>"); + SimulateUserInput(WebString::FromUTF8("fname"), std::string("Rick")); WebElement element = GetMainFrame()->GetDocument().GetElementById(blink::WebString("myForm")); @@ -1147,10 +1114,7 @@ "<html>" "<input type='text' id='address_field' name='address' autocomplete='on'>" "</html>"); - SimulateUserInput(WebString::FromUTF8("address_field"), std::string("City")); - - // Simulate an Ajax request completing. static_cast<blink::WebAutofillClient*>(autofill_agent_)->AjaxSucceeded(); // Hide elements to simulate successful form submission. @@ -1171,7 +1135,6 @@ "<html>" "<input type='text' id='address_field' name='address' autocomplete='on'>" "</html>"); - SimulateUserInput(WebString::FromUTF8("address_field"), std::string("City")); // Hide elements to simulate successful form submission. @@ -1196,7 +1159,6 @@ "<html>" "<input type='text' id='address_field' name='address' autocomplete='on'>" "</html>"); - SimulateUserInput(WebString::FromUTF8("address_field"), std::string("City")); // Hide elements to simulate successful form submission.
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index adeaca3..249f1e45 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -6619,7 +6619,6 @@ "../browser/picture_in_picture/auto_pip_setting_view_unittest.cc", "../browser/picture_in_picture/picture_in_picture_occlusion_tracker_unittest.cc", "../browser/policy/messaging_layer/util/reporting_server_connector_unittest.cc", - "../browser/search_engine_choice/search_engine_choice_client_side_trial_unittest.cc", "../browser/search_engine_choice/search_engine_choice_dialog_service_unittest.cc", "../browser/segmentation_platform/client_util/local_tab_handler_unittest.cc", "../browser/ssl/generated_https_first_mode_pref_unittest.cc",
diff --git a/chrome/test/base/fake_gaia_mixin.cc b/chrome/test/base/fake_gaia_mixin.cc index 13bca94..82cf740 100644 --- a/chrome/test/base/fake_gaia_mixin.cc +++ b/chrome/test/base/fake_gaia_mixin.cc
@@ -31,8 +31,10 @@ const char FakeGaiaMixin::kFakeSIDCookie[] = "fake-SID-cookie"; const char FakeGaiaMixin::kFakeLSIDCookie[] = "fake-LSID-cookie"; -const char FakeGaiaMixin::kEnterpriseUser1[] = "user-1@example.com"; +// LINT.IfChange +const char FakeGaiaMixin::kEnterpriseUser1[] = "username@example.com"; const char FakeGaiaMixin::kEnterpriseUser1GaiaId[] = "0000111111"; +// LINT.ThenChange(/components/policy/core/common/cloud/test/policy_builder.cc) const char FakeGaiaMixin::kEnterpriseUser2[] = "user-2@example.com"; const char FakeGaiaMixin::kEnterpriseUser2GaiaId[] = "0000222222";
diff --git a/chrome/test/chromedriver/capabilities.cc b/chrome/test/chromedriver/capabilities.cc index 103bd88b..27d8baf3 100644 --- a/chrome/test/chromedriver/capabilities.cc +++ b/chrome/test/chromedriver/capabilities.cc
@@ -1118,7 +1118,7 @@ parser_map["strictFileInteractability"] = base::BindRepeating(&ParseBoolean, &strict_file_interactability); parser_map["webSocketUrl"] = - base::BindRepeating(&ParseBoolean, &web_socket_url); + base::BindRepeating(&ParseBoolean, &webSocketUrl); if (!w3c_compliant) { // TODO(https://crbug.com/chromedriver/2596): "unexpectedAlertBehaviour" is // legacy name of "unhandledPromptBehavior", remove when we stop supporting
diff --git a/chrome/test/chromedriver/capabilities.h b/chrome/test/chromedriver/capabilities.h index 6f52221..12e4f92 100644 --- a/chrome/test/chromedriver/capabilities.h +++ b/chrome/test/chromedriver/capabilities.h
@@ -193,7 +193,7 @@ std::set<WebViewInfo::Type> window_types; - bool web_socket_url = false; + bool webSocketUrl = false; }; bool GetChromeOptionsDictionary(const base::Value::Dict& params,
diff --git a/chrome/test/chromedriver/chrome/chrome_android_impl.cc b/chrome/test/chromedriver/chrome/chrome_android_impl.cc index 7426e6e..38b63bd 100644 --- a/chrome/test/chromedriver/chrome/chrome_android_impl.cc +++ b/chrome/test/chromedriver/chrome/chrome_android_impl.cc
@@ -22,15 +22,13 @@ devtools_event_listeners, std::optional<MobileDevice> mobile_device, std::string page_load_strategy, - std::unique_ptr<Device> device, - bool autoaccept_beforeunload) + std::unique_ptr<Device> device) : ChromeImpl(std::move(browser_info), std::move(window_types), std::move(websocket_client), std::move(devtools_event_listeners), std::move(mobile_device), - page_load_strategy, - autoaccept_beforeunload), + page_load_strategy), device_(std::move(device)) {} ChromeAndroidImpl::~ChromeAndroidImpl() = default;
diff --git a/chrome/test/chromedriver/chrome/chrome_android_impl.h b/chrome/test/chromedriver/chrome/chrome_android_impl.h index b4562a4..28e469ef 100644 --- a/chrome/test/chromedriver/chrome/chrome_android_impl.h +++ b/chrome/test/chromedriver/chrome/chrome_android_impl.h
@@ -23,8 +23,7 @@ devtools_event_listeners, std::optional<MobileDevice> mobile_device, std::string page_load_strategy, - std::unique_ptr<Device> device, - bool autoaccept_beforeunload); + std::unique_ptr<Device> device); ~ChromeAndroidImpl() override; // Overridden from Chrome:
diff --git a/chrome/test/chromedriver/chrome/chrome_desktop_impl.cc b/chrome/test/chromedriver/chrome/chrome_desktop_impl.cc index 09f6ca7d..95136e2 100644 --- a/chrome/test/chromedriver/chrome/chrome_desktop_impl.cc +++ b/chrome/test/chromedriver/chrome/chrome_desktop_impl.cc
@@ -85,15 +85,13 @@ const base::CommandLine& command, base::ScopedTempDir* user_data_dir, base::ScopedTempDir* extension_dir, - bool network_emulation_enabled, - bool autoaccept_beforeunload) + bool network_emulation_enabled) : ChromeImpl(std::move(browser_info), std::move(window_types), std::move(websocket_client), std::move(devtools_event_listeners), std::move(mobile_device), - page_load_strategy, - autoaccept_beforeunload), + page_load_strategy), process_(std::move(process)), command_(command), network_connection_enabled_(network_emulation_enabled), @@ -167,9 +165,9 @@ if (status.IsError()) return status; std::unique_ptr<WebViewImpl> web_view_tmp = - WebViewImpl::CreateTopLevelWebView( - id, w3c_compliant, &browser_info_, std::move(client), mobile_device, - page_load_strategy(), autoaccept_beforeunload_); + WebViewImpl::CreateTopLevelWebView(id, w3c_compliant, &browser_info_, + std::move(client), mobile_device, + page_load_strategy()); status = web_view_tmp->AttachTo(devtools_websocket_client_.get()); if (status.IsError()) { return status;
diff --git a/chrome/test/chromedriver/chrome/chrome_desktop_impl.h b/chrome/test/chromedriver/chrome/chrome_desktop_impl.h index d549b82e..84061d6 100644 --- a/chrome/test/chromedriver/chrome/chrome_desktop_impl.h +++ b/chrome/test/chromedriver/chrome/chrome_desktop_impl.h
@@ -35,8 +35,7 @@ const base::CommandLine& command, base::ScopedTempDir* user_data_dir, base::ScopedTempDir* extension_dir, - bool network_emulation_enabled, - bool autoaccept_beforeunload); + bool network_emulation_enabled); ~ChromeDesktopImpl() override; // Waits for a page with the given URL to appear and finish loading.
diff --git a/chrome/test/chromedriver/chrome/chrome_impl.cc b/chrome/test/chromedriver/chrome/chrome_impl.cc index edf2737e8..8d4c303 100644 --- a/chrome/test/chromedriver/chrome/chrome_impl.cc +++ b/chrome/test/chromedriver/chrome/chrome_impl.cc
@@ -183,7 +183,7 @@ } else { web_views_.push_back(WebViewImpl::CreateTopLevelWebView( view.id, w3c_compliant, &browser_info_, std::move(client), - mobile_device_, page_load_strategy_, autoaccept_beforeunload_)); + mobile_device_, page_load_strategy_)); } status = web_views_.back()->AttachTo(devtools_websocket_client_.get()); if (status.IsError()) { @@ -689,13 +689,11 @@ std::vector<std::unique_ptr<DevToolsEventListener>> devtools_event_listeners, std::optional<MobileDevice> mobile_device, - std::string page_load_strategy, - bool autoaccept_beforeunload) + std::string page_load_strategy) : mobile_device_(std::move(mobile_device)), browser_info_(std::move(browser_info)), window_types_(std::move(window_types)), devtools_websocket_client_(std::move(websocket_client)), - autoaccept_beforeunload_(autoaccept_beforeunload), devtools_event_listeners_(std::move(devtools_event_listeners)), page_load_strategy_(page_load_strategy) { window_types_.insert(WebViewInfo::kPage);
diff --git a/chrome/test/chromedriver/chrome/chrome_impl.h b/chrome/test/chromedriver/chrome/chrome_impl.h index b806a07..37a7bd7f 100644 --- a/chrome/test/chromedriver/chrome/chrome_impl.h +++ b/chrome/test/chromedriver/chrome/chrome_impl.h
@@ -96,8 +96,7 @@ std::vector<std::unique_ptr<DevToolsEventListener>> devtools_event_listeners, std::optional<MobileDevice> mobile_device, - std::string page_load_strategy, - bool autoaccept_beforeunload); + std::string page_load_strategy); virtual Status QuitImpl() = 0; Status CloseTarget(const std::string& id); @@ -119,7 +118,6 @@ BrowserInfo browser_info_; std::set<WebViewInfo::Type> window_types_; std::unique_ptr<DevToolsClient> devtools_websocket_client_; - bool autoaccept_beforeunload_ = false; private: static Status PermissionNameToChromePermissions(
diff --git a/chrome/test/chromedriver/chrome/chrome_remote_impl.cc b/chrome/test/chromedriver/chrome/chrome_remote_impl.cc index b3e4342..ec6ce22 100644 --- a/chrome/test/chromedriver/chrome/chrome_remote_impl.cc +++ b/chrome/test/chromedriver/chrome/chrome_remote_impl.cc
@@ -18,15 +18,13 @@ std::vector<std::unique_ptr<DevToolsEventListener>> devtools_event_listeners, std::optional<MobileDevice> mobile_device, - std::string page_load_strategy, - bool autoaccept_beforeunload) + std::string page_load_strategy) : ChromeImpl(std::move(browser_info), std::move(window_types), std::move(websocket_client), std::move(devtools_event_listeners), std::move(mobile_device), - page_load_strategy, - autoaccept_beforeunload) {} + page_load_strategy) {} ChromeRemoteImpl::~ChromeRemoteImpl() = default;
diff --git a/chrome/test/chromedriver/chrome/chrome_remote_impl.h b/chrome/test/chromedriver/chrome/chrome_remote_impl.h index 4a56a355..4c21c80 100644 --- a/chrome/test/chromedriver/chrome/chrome_remote_impl.h +++ b/chrome/test/chromedriver/chrome/chrome_remote_impl.h
@@ -21,8 +21,7 @@ std::vector<std::unique_ptr<DevToolsEventListener>> devtools_event_listeners, std::optional<MobileDevice> mobile_device, - std::string page_load_strategy, - bool autoaccept_beforeunload); + std::string page_load_strategy); ~ChromeRemoteImpl() override; // Overridden from Chrome.
diff --git a/chrome/test/chromedriver/chrome/devtools_client_impl.cc b/chrome/test/chromedriver/chrome/devtools_client_impl.cc index fcc8707..18c04c2 100644 --- a/chrome/test/chromedriver/chrome/devtools_client_impl.cc +++ b/chrome/test/chromedriver/chrome/devtools_client_impl.cc
@@ -47,9 +47,6 @@ const char kNoNodeForBackendNodeIdError[] = "No node found for given backend id"; const char kNoNodeWithGivenIdFoundError[] = "No node with given id found"; -const char kExecutionContextWasDestroyed[] = "Execution context was destroyed."; -const char kInspectedTargetNavigatedOrClosed[] = - "Inspected target navigated or closed"; static constexpr int kSessionNotFoundInspectorCode = -32001; static constexpr int kCdpMethodNotFoundCode = -32601; @@ -1064,8 +1061,7 @@ crashed_ = true; return Status(kTabCrashed); } - if ((owner_ && owner_->GetJavaScriptDialogManager()->IsDialogOpen()) || - (!owner_ && event.method == "Page.javascriptDialogOpening")) { + if (event.method == "Page.javascriptDialogOpening") { // A command may have opened the dialog, which will block the response. // To find out which one (if any), do a round trip with a simple command // to the renderer and afterwards see if any of the commands still haven't @@ -1392,11 +1388,6 @@ // The error message that arises during DOM.resolveNode code. // This means that the node with given BackendNodeId is not found. return Status{kNoSuchElement, error_message}; - } else if (error_message == kExecutionContextWasDestroyed || - error_message == kInspectedTargetNavigatedOrClosed) { - // The error messages that arise if navigation was started by the - // asynchronous script before the script execution was finished.. - return Status{kNavigationDetectedByRemoteEnd, error_message}; } std::optional<int> error_code = error_dict->FindInt("code"); if (error_code == kInvalidParamsInspectorCode) {
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc b/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc index 8a77e13..600cd61 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc
@@ -7,9 +7,8 @@ #include "chrome/test/chromedriver/chrome/devtools_client.h" #include "chrome/test/chromedriver/chrome/status.h" -JavaScriptDialogManager::JavaScriptDialogManager(DevToolsClient* client, - bool autoaccept_beforeunload) - : client_(client), autoaccept_beforeunload_(autoaccept_beforeunload) { +JavaScriptDialogManager::JavaScriptDialogManager(DevToolsClient* client) + : client_(client) { client_->AddListener(this); } @@ -96,10 +95,6 @@ "dialog event missing or invalid 'defaultPrompt'"); } prompt_text_ = *prompt_text; - - if (*type == "beforeunload" && autoaccept_beforeunload_) { - return HandleDialog(true, nullptr); - } } else if (method == "Page.javascriptDialogClosed") { // Inspector only sends this event when all dialogs have been closed. // Clear the unhandled queue in case the user closed a dialog manually.
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager.h b/chrome/test/chromedriver/chrome/javascript_dialog_manager.h index a0fcfba..416d1cd 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager.h +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager.h
@@ -18,8 +18,7 @@ // Tracks the opening and closing of JavaScript dialogs (e.g., alerts). class JavaScriptDialogManager : public DevToolsEventListener { public: - explicit JavaScriptDialogManager(DevToolsClient* client, - bool autoaccept_beforeunload); + explicit JavaScriptDialogManager(DevToolsClient* client); JavaScriptDialogManager(const JavaScriptDialogManager&) = delete; JavaScriptDialogManager& operator=(const JavaScriptDialogManager&) = delete; @@ -50,8 +49,6 @@ std::list<std::string> dialog_type_queue_; std::string prompt_text_; - - bool autoaccept_beforeunload_ = false; }; #endif // CHROME_TEST_CHROMEDRIVER_CHROME_JAVASCRIPT_DIALOG_MANAGER_H_
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc b/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc index 1c374de..29385f6 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc
@@ -17,7 +17,7 @@ TEST(JavaScriptDialogManager, NoDialog) { StubDevToolsClient client; - JavaScriptDialogManager manager(&client, true); + JavaScriptDialogManager manager(&client); std::string message("HI"); ASSERT_EQ(kNoSuchAlert, manager.GetDialogMessage(&message).code()); ASSERT_FALSE(manager.IsDialogOpen()); @@ -27,7 +27,7 @@ TEST(JavaScriptDialogManager, HandleDialogPassesParams) { RecorderDevToolsClient client; - JavaScriptDialogManager manager(&client, true); + JavaScriptDialogManager manager(&client); base::Value::Dict params; params.Set("message", "hi"); params.Set("type", "prompt"); @@ -45,7 +45,7 @@ TEST(JavaScriptDialogManager, HandleDialogNullPrompt) { RecorderDevToolsClient client; - JavaScriptDialogManager manager(&client, true); + JavaScriptDialogManager manager(&client); base::Value::Dict params; params.Set("message", "hi"); params.Set("type", "prompt"); @@ -60,7 +60,7 @@ TEST(JavaScriptDialogManager, ReconnectClearsStateAndSendsEnable) { RecorderDevToolsClient client; - JavaScriptDialogManager manager(&client, true); + JavaScriptDialogManager manager(&client); base::Value::Dict params; params.Set("message", "hi"); params.Set("type", "alert"); @@ -122,7 +122,7 @@ TEST(JavaScriptDialogManager, OneDialog) { FakeDevToolsClient client; - JavaScriptDialogManager manager(&client, true); + JavaScriptDialogManager manager(&client); base::Value::Dict params; params.Set("message", "hi"); params.Set("type", "alert"); @@ -150,7 +150,7 @@ TEST(JavaScriptDialogManager, TwoDialogs) { FakeDevToolsClient client; - JavaScriptDialogManager manager(&client, true); + JavaScriptDialogManager manager(&client); base::Value::Dict params; params.Set("message", "1"); params.Set("type", "confirm"); @@ -189,7 +189,7 @@ TEST(JavaScriptDialogManager, OneDialogManualClose) { StubDevToolsClient client; BrowserInfo browser_info; - JavaScriptDialogManager manager(&client, true); + JavaScriptDialogManager manager(&client); base::Value::Dict params; params.Set("message", "hi"); params.Set("type", "alert"); @@ -215,50 +215,3 @@ ASSERT_EQ(kNoSuchAlert, manager.GetDialogMessage(&message).code()); ASSERT_EQ(kNoSuchAlert, manager.HandleDialog(false, nullptr).code()); } - -TEST(JavaScriptDialogManager, BeforeunloadIsAutoAccepted) { - FakeDevToolsClient client; - JavaScriptDialogManager manager(&client, true); - base::Value::Dict params; - params.Set("message", "hi"); - params.Set("type", "beforeunload"); - params.Set("defaultPrompt", ""); - ASSERT_FALSE(manager.IsDialogOpen()); - std::string message; - ASSERT_EQ(kNoSuchAlert, manager.GetDialogMessage(&message).code()); - - client.set_closing_count(1); - ASSERT_EQ( - kOk, - manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); - - ASSERT_FALSE(manager.IsDialogOpen()); - ASSERT_EQ(kNoSuchAlert, manager.GetDialogMessage(&message).code()); - ASSERT_EQ(kNoSuchAlert, manager.HandleDialog(false, nullptr).code()); -} - -TEST(JavaScriptDialogManager, AlertAndBeforeunloadAreAutoAccepted) { - FakeDevToolsClient client; - JavaScriptDialogManager manager(&client, true); - base::Value::Dict params; - params.Set("message", "1"); - params.Set("type", "alert"); - params.Set("defaultPrompt", ""); - ASSERT_EQ( - kOk, - manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); - params.Set("message", "2"); - params.Set("type", "beforeunload"); - // If a beforeunload dialog is detected all the previous dialogs are - // auto-accepted because a navigation has started after after their - // appearance. - client.set_closing_count(1); - ASSERT_EQ( - kOk, - manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); - - ASSERT_FALSE(manager.IsDialogOpen()); - std::string message; - ASSERT_EQ(kNoSuchAlert, manager.GetDialogMessage(&message).code()); - ASSERT_EQ(kNoSuchAlert, manager.HandleDialog(false, nullptr).code()); -}
diff --git a/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc b/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc index 2f7965f9..7b5377e 100644 --- a/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc +++ b/chrome/test/chromedriver/chrome/navigation_tracker_unittest.cc
@@ -131,8 +131,8 @@ DevToolsClient* client_ptr = client_uptr.get(); WebViewImpl web_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); - JavaScriptDialogManager dialog_manager(client_ptr, true); + PageLoadStrategy::kNormal); + JavaScriptDialogManager dialog_manager(client_ptr); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); base::Value::Dict params; @@ -159,8 +159,8 @@ DevToolsClient* client_ptr = client_uptr.get(); WebViewImpl web_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); - JavaScriptDialogManager dialog_manager(client_ptr, true); + PageLoadStrategy::kNormal); + JavaScriptDialogManager dialog_manager(client_ptr); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); base::Value::Dict params; @@ -188,8 +188,8 @@ DevToolsClient* client_ptr = client_uptr.get(); WebViewImpl web_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); - JavaScriptDialogManager dialog_manager(client_ptr, true); + PageLoadStrategy::kNormal); + JavaScriptDialogManager dialog_manager(client_ptr); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); base::Value::Dict params; @@ -241,8 +241,8 @@ DevToolsClient* client_ptr = client_uptr.get(); WebViewImpl web_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); - JavaScriptDialogManager dialog_manager(client_ptr, true); + PageLoadStrategy::kNormal); + JavaScriptDialogManager dialog_manager(client_ptr); NavigationTracker tracker(client_ptr, NavigationTracker::kNotLoading, &web_view, &dialog_manager); @@ -263,7 +263,7 @@ std::make_unique<DeterminingLoadStateDevToolsClient>( false, false, std::string(), &dict); DevToolsClient* client_ptr = client_uptr.get(); - JavaScriptDialogManager dialog_manager(client_ptr, true); + JavaScriptDialogManager dialog_manager(client_ptr); EvaluateScriptWebView web_view(kOk); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); @@ -314,7 +314,7 @@ std::make_unique<DeterminingLoadStateDevToolsClient>( false, false, std::string(), &dict); DevToolsClient* client_ptr = client_uptr.get(); - JavaScriptDialogManager dialog_manager(client_ptr, true); + JavaScriptDialogManager dialog_manager(client_ptr); EvaluateScriptWebView web_view(kOk); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); @@ -353,7 +353,7 @@ std::make_unique<DeterminingLoadStateDevToolsClient>( false, false, std::string(), &dict); DevToolsClient* client_ptr = client_uptr.get(); - JavaScriptDialogManager dialog_manager(client_ptr, true); + JavaScriptDialogManager dialog_manager(client_ptr); EvaluateScriptWebView web_view(kOk); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); @@ -423,8 +423,8 @@ DevToolsClient* client_ptr = client_uptr.get(); WebViewImpl web_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); - JavaScriptDialogManager dialog_manager(client_ptr, true); + PageLoadStrategy::kNormal); + JavaScriptDialogManager dialog_manager(client_ptr); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); bool is_pending; @@ -441,8 +441,8 @@ DevToolsClient* client_ptr = client_uptr.get(); WebViewImpl web_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); - JavaScriptDialogManager dialog_manager(client_ptr, true); + PageLoadStrategy::kNormal); + JavaScriptDialogManager dialog_manager(client_ptr); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); ASSERT_NO_FATAL_FAILURE(AssertPendingState(&tracker, true)); @@ -454,7 +454,7 @@ std::make_unique<DeterminingLoadStateDevToolsClient>( false, true, std::string(), &dict); DevToolsClient* client_ptr = client_uptr.get(); - JavaScriptDialogManager dialog_manager(client_ptr, true); + JavaScriptDialogManager dialog_manager(client_ptr); EvaluateScriptWebView web_view(kOk); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); @@ -470,8 +470,8 @@ DevToolsClient* client_ptr = client_uptr.get(); WebViewImpl web_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); - JavaScriptDialogManager dialog_manager(client_ptr, true); + PageLoadStrategy::kNormal); + JavaScriptDialogManager dialog_manager(client_ptr); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); base::Value::Dict params; @@ -487,7 +487,7 @@ std::make_unique<DeterminingLoadStateDevToolsClient>( false, true, std::string(), &dict); DevToolsClient* client_ptr = client_uptr.get(); - JavaScriptDialogManager dialog_manager(client_ptr, true); + JavaScriptDialogManager dialog_manager(client_ptr); EvaluateScriptWebView web_view(kOk); NavigationTracker tracker(client_ptr, NavigationTracker::kNotLoading, &web_view, &dialog_manager); @@ -509,7 +509,7 @@ std::make_unique<DeterminingLoadStateDevToolsClient>( false, true, std::string(), &dict); DevToolsClient* client_ptr = client_uptr.get(); - JavaScriptDialogManager dialog_manager(client_ptr, true); + JavaScriptDialogManager dialog_manager(client_ptr); EvaluateScriptWebView web_view(kOk); NavigationTracker tracker(client_ptr, NavigationTracker::kNotLoading, &web_view, &dialog_manager); @@ -532,7 +532,7 @@ std::make_unique<DeterminingLoadStateDevToolsClient>( false, true, std::string(), &dict); DevToolsClient* client_ptr = client_uptr.get(); - JavaScriptDialogManager dialog_manager(client_ptr, true); + JavaScriptDialogManager dialog_manager(client_ptr); EvaluateScriptWebView web_view(kOk); NavigationTracker tracker(client_ptr, NavigationTracker::kNotLoading, &web_view, &dialog_manager); @@ -573,8 +573,8 @@ DevToolsClient* client_ptr = client_uptr.get(); WebViewImpl web_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); - JavaScriptDialogManager dialog_manager(client_ptr, true); + PageLoadStrategy::kNormal); + JavaScriptDialogManager dialog_manager(client_ptr); NavigationTracker tracker(client_ptr, &web_view, &dialog_manager); bool is_pending;
diff --git a/chrome/test/chromedriver/chrome/status.cc b/chrome/test/chromedriver/chrome/status.cc index 67556a9..3ef992b 100644 --- a/chrome/test/chromedriver/chrome/status.cc +++ b/chrome/test/chromedriver/chrome/status.cc
@@ -76,8 +76,6 @@ return "no such shadow root"; case kDetachedShadowRoot: return "detached shadow root"; - case kNavigationDetectedByRemoteEnd: - return "navigation detected by remote end"; default: return "<unknown>"; }
diff --git a/chrome/test/chromedriver/chrome/status.h b/chrome/test/chromedriver/chrome/status.h index 65e4157..f881b7a 100644 --- a/chrome/test/chromedriver/chrome/status.h +++ b/chrome/test/chromedriver/chrome/status.h
@@ -44,7 +44,6 @@ kTabCrashed, kTargetDetached, kUnexpectedAlertOpen_Keep, - kNavigationDetectedByRemoteEnd, }; // Represents a WebDriver status, which may be an error or ok.
diff --git a/chrome/test/chromedriver/chrome/web_view_impl.cc b/chrome/test/chromedriver/chrome/web_view_impl.cc index d46ea59..3343f4c 100644 --- a/chrome/test/chromedriver/chrome/web_view_impl.cc +++ b/chrome/test/chromedriver/chrome/web_view_impl.cc
@@ -373,11 +373,10 @@ const BrowserInfo* browser_info, std::unique_ptr<DevToolsClient> client, std::optional<MobileDevice> mobile_device, - std::string page_load_strategy, - bool autoaccept_beforeunload) { + std::string page_load_strategy) { return std::make_unique<WebViewImpl>( id, w3c_compliant, nullptr, browser_info, std::move(client), - std::move(mobile_device), page_load_strategy, autoaccept_beforeunload); + std::move(mobile_device), page_load_strategy); } WebViewImpl::WebViewImpl(const std::string& id, @@ -408,8 +407,7 @@ const BrowserInfo* browser_info, std::unique_ptr<DevToolsClient> client, std::optional<MobileDevice> mobile_device, - std::string page_load_strategy, - bool autoaccept_beforeunload) + std::string page_load_strategy) : id_(id), w3c_compliant_(w3c_compliant), browser_info_(browser_info), @@ -418,8 +416,7 @@ parent_(parent), client_(std::move(client)), frame_tracker_(new FrameTracker(client_.get(), this)), - dialog_manager_( - new JavaScriptDialogManager(client_.get(), autoaccept_beforeunload)), + dialog_manager_(new JavaScriptDialogManager(client_.get())), mobile_emulation_override_manager_( new MobileEmulationOverrideManager(client_.get(), std::move(mobile_device), @@ -429,8 +426,7 @@ network_conditions_override_manager_( new NetworkConditionsOverrideManager(client_.get())), heap_snapshot_taker_(new HeapSnapshotTaker(client_.get())), - is_service_worker_(false), - autoaccept_beforeunload_(autoaccept_beforeunload) { + is_service_worker_(false) { // Downloading in headless mode requires the setting of // Browser.setDownloadBehavior. This is handled by the // DownloadDirectoryOverrideManager, which is only instantiated @@ -485,7 +481,7 @@ std::make_unique<DevToolsClientImpl>(session_id, session_id); std::unique_ptr<WebViewImpl> child = std::make_unique<WebViewImpl>( target_id, w3c_compliant_, this, browser_info_, std::move(child_client), - std::nullopt, "", autoaccept_beforeunload_); + std::nullopt, ""); const WebViewImpl* root_view = this; while (root_view->parent_ != nullptr) { root_view = root_view->parent_; @@ -1382,8 +1378,7 @@ Status status{kOk}; while (keep_waiting) { status = client_->HandleEventsUntil(not_pending_navigation, timeout); - keep_waiting = status.code() == kNoSuchExecutionContext || - status.code() == kNavigationDetectedByRemoteEnd; + keep_waiting = status.code() == kNoSuchExecutionContext; } if (status.code() == kTimeout && stop_load_on_timeout) { VLOG(0) << "Timed out. Stopping navigation..."; @@ -1399,8 +1394,7 @@ new_status = client_->HandleEventsUntil( not_pending_navigation, Timeout(base::Seconds(kWaitForNavigationStopSeconds))); - keep_waiting = new_status.code() == kNoSuchExecutionContext || - new_status.code() == kNavigationDetectedByRemoteEnd; + keep_waiting = new_status.code() == kNoSuchExecutionContext; } navigation_tracker_->set_timed_out(false); if (new_status.IsError()) @@ -1739,33 +1733,61 @@ async_args.Append(true); std::unique_ptr<base::Value> tmp; Timeout local_timeout(timeout); - std::unique_ptr<base::Value> query_value; Status status = CallFunctionWithTimeout(frame, kExecuteAsyncScriptScript, - async_args, timeout, &query_value); - if (status.IsError()) { + async_args, timeout, &tmp); + if (status.IsError()) return status; - } - base::Value::Dict* result_info = query_value->GetIfDict(); - if (!result_info) { - return Status(kUnknownError, "async result info is not a dictionary"); + const char kDocUnloadError[] = "document unloaded while waiting for result"; + std::string kQueryResult = base::StringPrintf( + "function() {" + " var info = document.$chrome_asyncScriptInfo;" + " if (!info)" + " return {status: %d, value: '%s'};" + " var result = info.result;" + " if (!result)" + " return {status: 0};" + " delete info.result;" + " return result;" + "}", + kJavaScriptError, + kDocUnloadError); + const base::TimeDelta kOneHundredMs = base::Milliseconds(100); + + while (true) { + base::Value::List no_args; + std::unique_ptr<base::Value> query_value; + status = CallFunction(frame, kQueryResult, no_args, &query_value); + if (status.IsError()) { + if (status.code() == kNoSuchFrame) + return Status(kJavaScriptError, kDocUnloadError); + return status; + } + + base::Value::Dict* result_info = query_value->GetIfDict(); + if (!result_info) + return Status(kUnknownError, "async result info is not a dictionary"); + std::optional<int> status_code = result_info->FindInt("status"); + if (!status_code) + return Status(kUnknownError, "async result info has no int 'status'"); + if (*status_code != kOk) { + const std::string* message = result_info->FindString("value"); + return Status(static_cast<StatusCode>(*status_code), + message ? *message : ""); + } + + if (base::Value* value = result_info->Find("value")) { + *result = base::Value::ToUniquePtrValue(value->Clone()); + return Status(kOk); + } + + // Since async-scripts return immediately, need to time period here instead. + if (local_timeout.IsExpired()) + return Status(kTimeout); + + base::PlatformThread::Sleep( + std::min(kOneHundredMs, local_timeout.GetRemainingTime())); } - std::optional<int> status_code = result_info->FindInt("status"); - if (!status_code) { - return Status(kUnknownError, "async result info has no int 'status'"); - } - if (*status_code != kOk) { - const std::string* message = result_info->FindString("value"); - return Status(static_cast<StatusCode>(*status_code), - message ? *message : ""); - } - base::Value* value = result_info->Find("value"); - if (!value) { - return Status{kJavaScriptError, - "no value field in Reuntime.callFunctionOn result"}; - } - *result = base::Value::ToUniquePtrValue(value->Clone()); - return Status(kOk); } void WebViewImpl::SetFrame(const std::string& new_frame_id) {
diff --git a/chrome/test/chromedriver/chrome/web_view_impl.h b/chrome/test/chromedriver/chrome/web_view_impl.h index 9b53ae0..c705bb80 100644 --- a/chrome/test/chromedriver/chrome/web_view_impl.h +++ b/chrome/test/chromedriver/chrome/web_view_impl.h
@@ -43,16 +43,14 @@ const BrowserInfo* browser_info, std::unique_ptr<DevToolsClient> client, std::optional<MobileDevice> mobile_device, - std::string page_load_strategy, - bool autoaccept_beforeunload); + std::string page_load_strategy); WebViewImpl(const std::string& id, const bool w3c_compliant, const WebViewImpl* parent, const BrowserInfo* browser_info, std::unique_ptr<DevToolsClient> client, std::optional<MobileDevice> mobile_device, - std::string page_load_strategy, - bool autoaccept_beforeunload); + std::string page_load_strategy); ~WebViewImpl() override; std::unique_ptr<WebViewImpl> CreateChild(const std::string& session_id, const std::string& target_id) const; @@ -272,7 +270,6 @@ std::unique_ptr<CastTracker> cast_tracker_; std::unique_ptr<FedCmTracker> fedcm_tracker_; bool is_service_worker_; - bool autoaccept_beforeunload_ = false; }; // Responsible for locking a WebViewImpl and its associated data structure to
diff --git a/chrome/test/chromedriver/chrome/web_view_impl_unittest.cc b/chrome/test/chromedriver/chrome/web_view_impl_unittest.cc index 5fcbfd2..0d91820 100644 --- a/chrome/test/chromedriver/chrome/web_view_impl_unittest.cc +++ b/chrome/test/chromedriver/chrome/web_view_impl_unittest.cc
@@ -467,7 +467,7 @@ BrowserInfo browser_info; WebViewImpl level1(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kEager, true); + PageLoadStrategy::kEager); EXPECT_TRUE(socket_holder.ConnectSocket()); EXPECT_TRUE(StatusOk(client_ptr->SetSocket(socket_holder.Wrapper()))); std::string sessionid = "2"; @@ -493,7 +493,7 @@ BrowserInfo browser_info; WebViewImpl parent_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kEager, true); + PageLoadStrategy::kEager); EXPECT_TRUE(socket_holder.ConnectSocket()); EXPECT_TRUE(StatusOk(client_ptr->SetSocket(socket_holder.Wrapper()))); ASSERT_FALSE(parent_view.IsNonBlocking()); @@ -515,7 +515,7 @@ BrowserInfo browser_info; WebViewImpl parent_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNone, true); + PageLoadStrategy::kNone); EXPECT_TRUE(socket_holder.ConnectSocket()); EXPECT_TRUE(StatusOk(client_ptr->SetSocket(socket_holder.Wrapper()))); std::string sessionid = "2"; @@ -535,7 +535,7 @@ BrowserInfo browser_info; WebViewImpl parent_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNone, true); + PageLoadStrategy::kNone); EXPECT_TRUE(socket_holder.ConnectSocket()); EXPECT_TRUE(StatusOk(client_ptr->SetSocket(socket_holder.Wrapper()))); std::string sessionid = "2"; @@ -558,7 +558,7 @@ BrowserInfo browser_info; WebViewImpl parent_view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kNormal, true); + PageLoadStrategy::kNormal); EXPECT_TRUE(socket_holder.ConnectSocket()); EXPECT_TRUE(StatusOk(client_ptr->SetSocket(socket_holder.Wrapper()))); std::string sessionid = "2"; @@ -578,7 +578,7 @@ BrowserInfo browser_info; WebViewImpl view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kEager, true); + PageLoadStrategy::kEager); std::string samesite = "Strict"; base::Value::Dict dict; dict.Set("success", true); @@ -595,7 +595,7 @@ BrowserInfo browser_info; WebViewImpl view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kEager, true); + PageLoadStrategy::kEager); { // Good 1 base::Value::Dict node_ref; @@ -647,7 +647,7 @@ BrowserInfo browser_info; WebViewImpl view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kEager, true); + PageLoadStrategy::kEager); { // Good 1 base::Value::Dict node_ref; @@ -696,7 +696,7 @@ BrowserInfo browser_info; WebViewImpl view(client_ptr->GetId(), false, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kEager, true); + PageLoadStrategy::kEager); { base::Value::Dict node_ref; node_ref.Set(kElementKey, ElementReference("root", "root_loader", 25)); @@ -723,7 +723,7 @@ std::make_unique<FakeDevToolsClient>("root"); client_uptr->SetResult(GenerateResponse(4321)); WebViewImpl view("root", true, nullptr, &browser_info, std::move(client_uptr), - std::nullopt, PageLoadStrategy::kEager, true); + std::nullopt, PageLoadStrategy::kEager); view.GetFrameTracker()->SetContextIdForFrame("root", "irrelevant"); view.GetFrameTracker()->SetContextIdForFrame("good", "irrelevant"); { @@ -761,7 +761,7 @@ std::make_unique<FakeDevToolsClient>("good"); client_uptr->SetResult(GenerateResponse(4321)); WebViewImpl view("good", true, nullptr, &browser_info, std::move(client_uptr), - std::nullopt, PageLoadStrategy::kEager, true); + std::nullopt, PageLoadStrategy::kEager); view.GetFrameTracker()->SetContextIdForFrame("root", "irrelevant"); view.GetFrameTracker()->SetContextIdForFrame("good", "irrelevant"); { @@ -799,7 +799,7 @@ std::make_unique<FakeDevToolsClient>("root"); FakeDevToolsClient* client_ptr = client_uptr.get(); WebViewImpl view("root", true, nullptr, &browser_info, std::move(client_uptr), - std::nullopt, PageLoadStrategy::kEager, true); + std::nullopt, PageLoadStrategy::kEager); view.GetFrameTracker()->SetContextIdForFrame("root", "irrelevant"); view.GetFrameTracker()->SetContextIdForFrame("good", "irrelevant"); view.GetFrameTracker()->SetContextIdForFrame("bad", "irrelevant"); @@ -891,7 +891,7 @@ BrowserInfo browser_info; WebViewImpl view(client_ptr->GetId(), true, nullptr, &browser_info, std::move(client_uptr), std::nullopt, - PageLoadStrategy::kEager, true); + PageLoadStrategy::kEager); FedCmTracker* tracker = nullptr; Status status = view.GetFedCmTracker(&tracker); EXPECT_TRUE(StatusOk(status)); @@ -907,7 +907,7 @@ client_ptr = client_uptr.get(); view = std::make_unique<WebViewImpl>( "root", IsW3C(), nullptr, &browser_info, std::move(client_uptr), - std::nullopt, PageLoadStrategy::kEager, true); + std::nullopt, PageLoadStrategy::kEager); view->GetFrameTracker()->SetContextIdForFrame("root", "irrelevant"); view->GetFrameTracker()->SetContextIdForFrame("good", "irrelevant"); view->GetFrameTracker()->SetContextIdForFrame("bad", "irrelevant"); @@ -1104,7 +1104,7 @@ BrowserInfo browser_info; WebViewImpl view("root", true, nullptr, &browser_info, std::move(client_uptr), - std::nullopt, PageLoadStrategy::kEager, true); + std::nullopt, PageLoadStrategy::kEager); view.GetFrameTracker()->SetContextIdForFrame("root", "irrelevant"); std::unique_ptr<base::Value> result; @@ -1145,7 +1145,7 @@ BrowserInfo browser_info; WebViewImpl view("root", true, nullptr, &browser_info, std::move(client_uptr), - std::nullopt, PageLoadStrategy::kEager, true); + std::nullopt, PageLoadStrategy::kEager); view.GetFrameTracker()->SetContextIdForFrame("root", "irrelevant"); std::unique_ptr<base::Value> result; @@ -1183,7 +1183,7 @@ BrowserInfo browser_info; WebViewImpl view("root", true, nullptr, &browser_info, std::move(client_uptr), - std::nullopt, PageLoadStrategy::kEager, true); + std::nullopt, PageLoadStrategy::kEager); view.GetFrameTracker()->SetContextIdForFrame("root", "irrelevant"); std::unique_ptr<base::Value> result;
diff --git a/chrome/test/chromedriver/chrome_launcher.cc b/chrome/test/chromedriver/chrome_launcher.cc index 7ee02f56..a559362 100644 --- a/chrome/test/chromedriver/chrome_launcher.cc +++ b/chrome/test/chromedriver/chrome_launcher.cc
@@ -253,7 +253,7 @@ // disable throttling all together. // TODO(crbug.com/chromedriver/4762): Remove after the Mapper is moved away // from the tab. - if (capabilities.web_socket_url) { + if (capabilities.webSocketUrl) { switches.SetSwitch("disable-background-timer-throttling"); } @@ -447,8 +447,7 @@ chrome = std::make_unique<ChromeRemoteImpl>( browser_info, capabilities.window_types, std::move(devtools_websocket_client), std::move(devtools_event_listeners), - capabilities.mobile_device, capabilities.page_load_strategy, - !capabilities.web_socket_url); + capabilities.mobile_device, capabilities.page_load_strategy); return Status(kOk); } @@ -760,18 +759,20 @@ std::move(devtools_event_listeners), capabilities.mobile_device, capabilities.page_load_strategy, std::move(process), command, &user_data_dir_temp_dir, &extension_dir, - capabilities.network_emulation_enabled, !capabilities.web_socket_url); + capabilities.network_emulation_enabled); if (!capabilities.extension_load_timeout.is_zero()) { - for (const std::string& url : extension_bg_pages) { - VLOG(0) << "Waiting for extension bg page load: " << url; + for (size_t i = 0; i < extension_bg_pages.size(); ++i) { + VLOG(0) << "Waiting for extension bg page load: " + << extension_bg_pages[i]; std::unique_ptr<WebView> web_view; status = chrome_desktop->WaitForPageToLoad( - url, capabilities.extension_load_timeout, &web_view, w3c_compliant); + extension_bg_pages[i], capabilities.extension_load_timeout, &web_view, + w3c_compliant); if (status.IsError()) { - return Status( - kSessionNotCreated, - "failed to wait for extension background page to load: " + url, - status); + return Status(kSessionNotCreated, + "failed to wait for extension background page to load: " + + extension_bg_pages[i], + status); } } } @@ -846,7 +847,7 @@ browser_info, capabilities.window_types, std::move(devtools_websocket_client), std::move(devtools_event_listeners), capabilities.mobile_device, capabilities.page_load_strategy, - std::move(device), !capabilities.web_socket_url); + std::move(device)); return Status(kOk); } @@ -906,19 +907,21 @@ std::move(devtools_event_listeners), capabilities.mobile_device, capabilities.page_load_strategy, std::move(dummy_process), command, &user_data_dir_temp_dir, &extension_dir, - capabilities.network_emulation_enabled, !capabilities.web_socket_url); + capabilities.network_emulation_enabled); if (!capabilities.extension_load_timeout.is_zero()) { - for (const std::string& url : extension_bg_pages) { - VLOG(0) << "Waiting for extension bg page load: " << url; + for (size_t i = 0; i < extension_bg_pages.size(); ++i) { + VLOG(0) << "Waiting for extension bg page load: " + << extension_bg_pages[i]; std::unique_ptr<WebView> web_view; status = chrome_impl->WaitForPageToLoad( - url, capabilities.extension_load_timeout, &web_view, w3c_compliant); + extension_bg_pages[i], capabilities.extension_load_timeout, &web_view, + w3c_compliant); if (status.IsError()) { - return Status( - kSessionNotCreated, - "failed to wait for extension background page to load: " + url, - status); + return Status(kSessionNotCreated, + "failed to wait for extension background page to load: " + + extension_bg_pages[i], + status); } } }
diff --git a/chrome/test/chromedriver/js/execute_async_script.js b/chrome/test/chromedriver/js/execute_async_script.js index a210c48..a0735e6b 100644 --- a/chrome/test/chromedriver/js/execute_async_script.js +++ b/chrome/test/chromedriver/js/execute_async_script.js
@@ -14,6 +14,23 @@ }; /** + * Dictionary key for asynchronous script info. + * @const + */ +var ASYNC_INFO_KEY = '$chrome_asyncScriptInfo'; + +/** +* Return the information of asynchronous script execution. +* +* @return {Object<?>} Information of asynchronous script execution. +*/ +function getAsyncScriptInfo() { + if (!(ASYNC_INFO_KEY in document)) + document[ASYNC_INFO_KEY] = {'id': 0}; + return document[ASYNC_INFO_KEY]; +} + +/** * Execute the given script and save its asynchronous result. * * If script1 finishes after script2 is executed, then script1's result will be @@ -29,46 +46,61 @@ * exception occurs during the script, and an additional error callback will * be supplied to the script. */ -async function executeAsyncScript(script, args, isUserSupplied) { +function executeAsyncScript(script, args, isUserSupplied) { + let resolveHandle; + let rejectHandle; const Promise = window.cdc_adoQpoasnfa76pfcZLmcfl_Promise || window.Promise; + var promise = new Promise((resolve, reject) => { + resolveHandle = resolve; + rejectHandle = reject; + }); + const info = getAsyncScriptInfo(); + info.id++; + delete info.result; + const id = info.id; + function isThenable(value) { return typeof value === 'object' && typeof value.then === 'function'; } - function reportValue(value) { - return {status: StatusCode.OK, value: value}; + function report(status, value) { + if (id != info.id) + return; + info.id++; + // Undefined value is skipped when the object is converted to JSON. + // Replace it with null so we don't lose the value. + if (value === undefined) + value = null; + info.result = {status: status, value: value}; } - function reportError(error) { + function reportValue(value) { + report(StatusCode.OK, value); + } + function reportScriptError(error) { var code = isUserSupplied ? StatusCode.JAVASCRIPT_ERROR : (error.code || StatusCode.UNKNOWN_ERROR); var message = error.message; if (error.stack) { message += "\nJavaScript stack:\n" + error.stack; } - return {status: code, value: message}; + report(code, message); } - var promise = new Promise((resolve, reject) => { - args.push(resolve); - if (!isUserSupplied) { - args.push(reject); + promise.then(reportValue).catch(reportScriptError); + args.push(resolveHandle); + if (!isUserSupplied) + args.push(rejectHandle); + try { + const scriptResult = new Function(script).apply(null, args); + // The return value is only considered if it is a promise. + if (isThenable(scriptResult)) { + const resolvedPromise = Promise.resolve(scriptResult); + resolvedPromise.then((value) => { + // Must be thenable if user-supplied. + if (!isUserSupplied || isThenable(value)) + resolveHandle(value); + }) + .catch(rejectHandle); } - try { - let scriptResult = new Function(script).apply(null, args); - if (isThenable(scriptResult)) { - const resolvedPromise = Promise.resolve(scriptResult); - resolvedPromise.then((value) => { - // Must be thenable if user-supplied. - if (!isUserSupplied || isThenable(value)) - resolve(value); - }) - .catch(reject); - } - } catch (error) { - reject(error); - } - }); - return await promise.then((result) => { - return reportValue(result); - }).catch((error) => { - return reportError(error); - }); + } catch (error) { + rejectHandle(error); + } }
diff --git a/chrome/test/chromedriver/js/execute_async_script_test.html b/chrome/test/chromedriver/js/execute_async_script_test.html index 30aa597..1c4ff5d 100644 --- a/chrome/test/chromedriver/js/execute_async_script_test.html +++ b/chrome/test/chromedriver/js/execute_async_script_test.html
@@ -4,73 +4,117 @@ <script src='execute_async_script.js'></script> <script> +function resetAsyncScriptInfo() { + delete document[ASYNC_INFO_KEY]; +} + +function waitForResultToPopulate(callback) { + const info = getAsyncScriptInfo(); + setTimeout(() => { + if (info.result) + callback(info); + else + waitForResultToPopulate(callback); + }, 10); +} + function testUserScriptThrows(runner) { - executeAsyncScript('f(123);', [], true).then((result)=>{ - assertEquals(StatusCode.JAVASCRIPT_ERROR, result.status); + resetAsyncScriptInfo(); + executeAsyncScript('f(123);', [], true); + waitForResultToPopulate((info) => { + assertEquals(StatusCode.JAVASCRIPT_ERROR, info.result.status); runner.continueTesting(); - }); - runner.waitForAsync("StatusCode.JAVASCRIPT_ERROR"); + }); + runner.waitForAsync(); } function testScriptThrows(runner) { - executeAsyncScript('f(123);', [], false).then((result)=>{ - assertEquals(StatusCode.UNKNOWN_ERROR, result.status); + resetAsyncScriptInfo(); + executeAsyncScript('f(123);', [], false); + waitForResultToPopulate((info) => { + assertEquals(StatusCode.UNKNOWN_ERROR, info.result.status); runner.continueTesting(); - }); - runner.waitForAsync("StatusCode.UNKNOWN_ERROR"); + }); + runner.waitForAsync(); } function testUserScriptWithArgs(runner) { - let injectedArgs = null; + resetAsyncScriptInfo(); + + var injectedArgs = null; function captureArguments(args) { injectedArgs = args; } // Pass function captureArguments as the first argument. It is used to capture // the injected arguments to the following script. - const script = + var script = 'var args = arguments; args[0](args); args[args.length - 1](args[1]);'; - const script_args = [captureArguments, 1]; - executeAsyncScript(script, script_args, true) - .then((result)=>{ - assertEquals(3, injectedArgs.length); - assertEquals(captureArguments, injectedArgs[0]); - assertEquals(1, injectedArgs[1]); + var script_args = [captureArguments, 1]; + executeAsyncScript(script, script_args, true); + waitForResultToPopulate((info) => { + assertEquals(3, injectedArgs.length); + assertEquals(captureArguments, injectedArgs[0]); + assertEquals(1, injectedArgs[1]); - assertEquals(0, result.status); - assertEquals(1, result.value); - runner.continueTesting(); - }); - runner.waitForAsync("arguments are captured"); + assertEquals(0, info.result.status); + assertEquals(1, info.result.value); + assertEquals(2, info.id); + runner.continueTesting(); + }); + runner.waitForAsync(); } function testNonUserScriptCallback(runner) { - executeAsyncScript('arguments[1](arguments[0])', [33], false) - .then((result)=>{ - assertEquals(0, result.status); - assertEquals(33, result.value); - runner.continueTesting(); - }); - runner.waitForAsync('user script callback'); + resetAsyncScriptInfo(); + executeAsyncScript('arguments[1](arguments[0])', [33], false); + waitForResultToPopulate((info) => { + assertEquals(0, info.result.status); + assertEquals(33, info.result.value); + runner.continueTesting(); + }); + runner.waitForAsync(); } function testNonUserScriptCustomError(runner) { - executeAsyncScript('arguments[2](new Error("ERR"))', [33], false) - .then((result)=>{ - assertEquals(StatusCode.UNKNOWN_ERROR, result.status); - assertEquals(0, result.value.indexOf('ERR')); - runner.continueTesting(); - }); - runner.waitForAsync("custom error"); + resetAsyncScriptInfo(); + executeAsyncScript('arguments[2](new Error("ERR"))', [33], false); + waitForResultToPopulate((info) => { + assertEquals(StatusCode.UNKNOWN_ERROR, info.result.status); + assertEquals(0, info.result.value.indexOf('ERR')); + runner.continueTesting(); + }); + runner.waitForAsync(); } function testNonUserScriptCustomErrorCode(runner) { + resetAsyncScriptInfo(); executeAsyncScript('var e = new Error("ERR"); e.code = 111; arguments[1](e)', - [], false).then((result)=>{ - assertEquals(111, result.status); - assertEquals(0, result.value.indexOf('ERR')); - runner.continueTesting(); + [], false); + waitForResultToPopulate((info) => { + assertEquals(111, info.result.status); + assertEquals(0, info.result.value.indexOf('ERR')); + runner.continueTesting(); }); - runner.waitForAsync("custom error with custom error code"); + runner.waitForAsync(); +} + +function testFirstScriptFinishAfterSecondScriptExecute(runner) { + resetAsyncScriptInfo(); + + executeAsyncScript( + 'var f = arguments[0]; setTimeout(function(){ f(1); }, 100000);', []); + var info = getAsyncScriptInfo(); + assert(!info.hasOwnProperty('result')); + assertEquals(1, info.id); + + executeAsyncScript('var fn = arguments[0]; fn(2);', []); + waitForResultToPopulate((info) => { + assertEquals(0, info.result.status); + assertEquals(2, info.result.value); + assertEquals(3, info.id); + runner.continueTesting(); + }); + runner.waitForAsync(); } </script>
diff --git a/chrome/test/chromedriver/log_replay/chrome_replay_impl.cc b/chrome/test/chromedriver/log_replay/chrome_replay_impl.cc index ed2676cf..722bf4c 100644 --- a/chrome/test/chromedriver/log_replay/chrome_replay_impl.cc +++ b/chrome/test/chromedriver/log_replay/chrome_replay_impl.cc
@@ -20,8 +20,7 @@ const base::CommandLine& command, base::ScopedTempDir* user_data_dir, base::ScopedTempDir* extension_dir, - bool network_emulation_enabled, - bool autoaccept_beforeunload) + bool network_emulation_enabled) : ChromeDesktopImpl(std::move(browser_info), std::move(window_types), std::move(websocket_client), @@ -32,8 +31,7 @@ command, user_data_dir, extension_dir, - network_emulation_enabled, - autoaccept_beforeunload) {} + network_emulation_enabled) {} ChromeReplayImpl::~ChromeReplayImpl() = default;
diff --git a/chrome/test/chromedriver/log_replay/chrome_replay_impl.h b/chrome/test/chromedriver/log_replay/chrome_replay_impl.h index 2848163..43d743b 100644 --- a/chrome/test/chromedriver/log_replay/chrome_replay_impl.h +++ b/chrome/test/chromedriver/log_replay/chrome_replay_impl.h
@@ -28,8 +28,7 @@ const base::CommandLine& command, base::ScopedTempDir* user_data_dir, base::ScopedTempDir* extension_dir, - bool network_emulation_enabled, - bool autoaccept_beforeunload); + bool network_emulation_enabled); ~ChromeReplayImpl() override; // A no-op: all this does in DesktopChromeImpl is kill the Chrome process.
diff --git a/chrome/test/chromedriver/navigation_tracker_integrationtest.cc b/chrome/test/chromedriver/navigation_tracker_integrationtest.cc index ca50ea1..ad6b94c4 100644 --- a/chrome/test/chromedriver/navigation_tracker_integrationtest.cc +++ b/chrome/test/chromedriver/navigation_tracker_integrationtest.cc
@@ -173,7 +173,7 @@ ASSERT_TRUE(StatusOk(status)); WebViewImpl web_view(view_info->id, true, nullptr, &browser_info_, std::move(client), std::nullopt, - PageLoadStrategy::kNormal, true); + PageLoadStrategy::kNormal); web_view.AttachTo(browser_client_.get()); http_server_.SetDataForPath("test.html", "<span>DONE!</span>");
diff --git a/chrome/test/chromedriver/server/http_handler.cc b/chrome/test/chromedriver/server/http_handler.cc index d6f13e17..8fd52ea 100644 --- a/chrome/test/chromedriver/server/http_handler.cc +++ b/chrome/test/chromedriver/server/http_handler.cc
@@ -1528,9 +1528,7 @@ default: DCHECK(false); // Examples of unexpected codes: - // * kChromeNotReachable: kSessionNotCreated must be returned instead; - // * kNavigationDetectedByRemoteEnd: kUnknownError must be returned - // instead. + // * kChromeNotReachable - kSessionNotCreated must be returned instead response = std::make_unique<net::HttpServerResponseInfo>( net::HTTP_INTERNAL_SERVER_ERROR); break;
diff --git a/chrome/test/chromedriver/session.h b/chrome/test/chromedriver/session.h index d337d457..c38f01f 100644 --- a/chrome/test/chromedriver/session.h +++ b/chrome/test/chromedriver/session.h
@@ -114,7 +114,7 @@ const std::string id; bool w3c_compliant; - bool web_socket_url = false; + bool webSocketUrl = false; bool quit; bool detach; bool awaiting_bidi_response = false;
diff --git a/chrome/test/chromedriver/session_commands.cc b/chrome/test/chromedriver/session_commands.cc index 7b38fa1b..4b36413f 100644 --- a/chrome/test/chromedriver/session_commands.cc +++ b/chrome/test/chromedriver/session_commands.cc
@@ -259,7 +259,7 @@ caps.Set("hasTouchScreen", session->chrome->HasTouchScreen()); } - if (session->web_socket_url) { + if (session->webSocketUrl) { caps.Set("webSocketUrl", "ws://" + session->host + "/session/" + session->id); } @@ -300,7 +300,7 @@ // |session| will own the |CommandListener|s. session->command_listeners.swap(command_listeners); - if (session->web_socket_url) { + if (session->webSocketUrl) { // Suffixes used with the client channels. std::string client_suffixes[] = {Session::kChannelSuffix, Session::kNoChannelSuffix, @@ -350,7 +350,7 @@ *value = std::make_unique<base::Value>(session->capabilities->Clone()); } - if (session->web_socket_url) { + if (session->webSocketUrl) { WebView* web_view = nullptr; status = session->GetTargetWindow(&web_view); if (status.IsError()) @@ -457,7 +457,7 @@ session->script_timeout = capabilities->script_timeout; session->strict_file_interactability = capabilities->strict_file_interactability; - session->web_socket_url = capabilities->web_socket_url; + session->webSocketUrl = capabilities->webSocketUrl; Log::Level driver_level = Log::kWarning; if (capabilities->logging_prefs.count(WebDriverLog::kDriverType)) driver_level = capabilities->logging_prefs[WebDriverLog::kDriverType]; @@ -776,7 +776,7 @@ if (status.IsError()) return status; bool is_last_web_view = web_view_ids.size() == 1u; - if (session->web_socket_url) { + if (session->webSocketUrl) { is_last_web_view = web_view_ids.size() <= 2u; } web_view_ids.clear(); @@ -850,7 +850,7 @@ if (status.IsError()) return status; - if (session->web_socket_url) { + if (session->webSocketUrl) { auto it = base::ranges::find(web_view_ids, session->bidi_mapper_web_view_id); if (it != web_view_ids.end()) {
diff --git a/chrome/test/chromedriver/test/run_py_tests.py b/chrome/test/chromedriver/test/run_py_tests.py index 7dea4d3..75d61c4c 100755 --- a/chrome/test/chromedriver/test/run_py_tests.py +++ b/chrome/test/chromedriver/test/run_py_tests.py
@@ -222,7 +222,15 @@ 'ChromeDriverSecureContextTest.testGetVirtualSensorInformation', 'ChromeDriverSecureContextTest.testUpdateVirtualSensor', # Flaky on Mac: https://crbug.com/1503101 - 'BidiTest.*' + 'BidiTest.*', + # Failing on macOS 14 due to https://crbug.com/40233722 + 'ChromeDriverSecureContextTest.testAddVirtualAuthenticator', + 'ChromeDriverSecureContextTest.testAddVirtualAuthenticatorDefaultBackupSettings', + 'ChromeDriverSecureContextTest.testAddVirtualAuthenticatorDefaultParams', + 'ChromeDriverSecureContextTest.testGetCredentials', + 'ChromeDriverSecureContextTest.testRemoveAllCredentials', + 'ChromeDriverSecureContextTest.testRemoveCredential', + 'ChromeDriverSecureContextTest.testSetUserVerified' ] _BROWSER_AND_PLATFORM_SPECIFIC_FILTER['chrome-headless-shell']['win'] = [ # https://bugs.chromium.org/p/chromium/issues/detail?id=1196363 @@ -1169,24 +1177,6 @@ with self.assertRaises(chromedriver.DetachedShadowRoot): self._driver.ExecuteScript("return true;", shadow) - def testExecuteAsyncScriptWithResolve(self): - self.assertEqual( - 10, - self._driver.ExecuteAsyncScript( - 'arguments[0](10)')) - self.assertEqual( - 'one', - self._driver.ExecuteAsyncScript( - 'arguments[0]("one")')) - self.assertEqual( - 0.123, - self._driver.ExecuteAsyncScript( - 'arguments[0](0.123)')) - self.assertEqual( - [1, 2.2, 'three'], - self._driver.ExecuteAsyncScript( - 'arguments[0]([1, 2.2, "three"])')) - def testExecuteAsyncScript(self): self._driver.SetTimeouts({'script': 3000}) self.assertRaises( @@ -2470,32 +2460,8 @@ self._driver.ExecuteScript('window.onbeforeunload=function(){return true}') self._driver.FindElement('tag name', 'body').Click() self._driver.GoBack() - self.assertFalse(self._driver.IsAlertOpen()) - - def testAlertHandlingOnNavigation(self): - self._driver.Load(self.GetHttpUrlForFile('/chromedriver/page_test.html')) - self._driver.ExecuteScript('window.onbeforeunload=function(){return true}') - self._driver.FindElement('tag name', 'body').Click() - self._driver.ExecuteAsyncScript(''' - const [url, resolve] = arguments; - window.location.href = url; - resolve(url); - ''', self.GetHttpUrlForFile('/chromedriver/empty.html')) - self.assertFalse(self._driver.IsAlertOpen()) - - def testAlertHandlingOnNavigationNoResolve(self): - self._driver.Load(self.GetHttpUrlForFile('/chromedriver/page_test.html')) - self._driver.ExecuteScript('window.onbeforeunload=function(){return true}') - self._driver.FindElement('tag name', 'body').Click() - self._driver.SetTimeouts({'script': 100}) - - # The following script never calls resolve. Therefore it times out. - with self.assertRaises(chromedriver.ScriptTimeout): - self._driver.ExecuteAsyncScript(''' - const [url, resolve] = arguments; - window.location.href = url; - ''', self.GetHttpUrlForFile('/chromedriver/empty.html')) - + self.assertTrue(self._driver.IsAlertOpen()) + self._driver.HandleAlert(True) self.assertFalse(self._driver.IsAlertOpen()) def testRefresh(self): @@ -2527,7 +2493,10 @@ self._driver.ExecuteScript('window.onbeforeunload=function(){return true}') self._driver.FindElement('tag name', 'body').Click() self._driver.Refresh() - self.assertFalse(self._driver.IsAlertOpen()) + self.assertTrue(self._driver.IsAlertOpen()) + self.assertRaises(chromedriver.UnsupportedOperation, + self._driver.HandleAlert, + True, 'textToOnBeforeUnload') def testAlertOnNewWindow(self): self._driver.Load(self.GetHttpUrlForFile('/chromedriver/empty.html')) @@ -5680,16 +5649,6 @@ self._CheckPageLoadTimeout(self._driver.GoForward) self.assertEqual(self._initial_url, self._driver.GetCurrentUrl()) - def testHistoryNavigationAndLoadWithPageLoadTimeout(self): - # Allow the page to load for the first time. - self._handler.send_response_event.set() - self._LoadHangingUrl() - self.assertTrue(self._handler.request_received_event.wait(1)) - - self._driver.GoBack() - self._CheckPageLoadTimeout(self._LoadHangingUrl) - self.assertEqual(self._initial_url, self._driver.GetCurrentUrl()) - def testRefreshWithPageLoadTimeout(self): # Allow the page to load for the first time. self._handler.send_response_event.set()
diff --git a/chrome/test/chromedriver/window_commands.cc b/chrome/test/chromedriver/window_commands.cc index 3160862..ea5802062 100644 --- a/chrome/test/chromedriver/window_commands.cc +++ b/chrome/test/chromedriver/window_commands.cc
@@ -816,15 +816,9 @@ Status status = web_view->CallUserSyncScript(session->GetCurrentFrameId(), script, *args, session->script_timeout, value); - switch (status.code()) { - case kTimeout: - // Navigation has happened during script execution. Further wait would lead - // to timeout. - case kNavigationDetectedByRemoteEnd: - return Status(kScriptTimeout); - default: - return status; - } + if (status.code() == kTimeout) + return Status(kScriptTimeout); + return status; } Status ExecuteExecuteAsyncScript(Session* session, @@ -848,15 +842,9 @@ Status status = web_view->CallUserAsyncFunction( session->GetCurrentFrameId(), "async function(){" + script + "}", *args, session->script_timeout, value); - switch (status.code()) { - case kTimeout: - // Navigation has happened during script execution. Further wait would lead - // to timeout. - case kNavigationDetectedByRemoteEnd: - return Status(kScriptTimeout); - default: - return status; - } + if (status.code() == kTimeout) + return Status(kScriptTimeout); + return status; } Status ExecuteNewWindow(Session* session,
diff --git a/chrome/test/data/webui/chromeos/diagnostics/BUILD.gn b/chrome/test/data/webui/chromeos/diagnostics/BUILD.gn index 5a61a74..53160f3 100644 --- a/chrome/test/data/webui/chromeos/diagnostics/BUILD.gn +++ b/chrome/test/data/webui/chromeos/diagnostics/BUILD.gn
@@ -43,7 +43,7 @@ "network_info_test.ts", "network_list_test.js", "network_troubleshooting_test.js", - "overview_card_test.js", + "overview_card_test.ts", "percent_bar_chart_test.ts", "realtime_cpu_chart_test.js", "routine_group_test.ts",
diff --git a/chrome/test/data/webui/chromeos/diagnostics/overview_card_test.js b/chrome/test/data/webui/chromeos/diagnostics/overview_card_test.js deleted file mode 100644 index 809fe4a..0000000 --- a/chrome/test/data/webui/chromeos/diagnostics/overview_card_test.js +++ /dev/null
@@ -1,98 +0,0 @@ -// Copyright 2020 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'chrome://diagnostics/overview_card.js'; -import 'chrome://webui-test/chromeos/mojo_webui_test_support.js'; - -import {fakeSystemInfo, fakeSystemInfoWithoutBoardName, fakeSystemInfoWithTBD} from 'chrome://diagnostics/fake_data.js'; -import {FakeSystemDataProvider} from 'chrome://diagnostics/fake_system_data_provider.js'; -import {getSystemDataProvider, setSystemDataProviderForTesting} from 'chrome://diagnostics/mojo_interface_provider.js'; -import {OverviewCardElement} from 'chrome://diagnostics/overview_card.js'; -import {SystemInfo} from 'chrome://diagnostics/system_data_provider.mojom-webui.js'; -import {loadTimeData} from 'chrome://resources/ash/common/load_time_data.m.js'; -import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; -import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; - -import {isVisible} from '../test_util.js'; - -import * as dx_utils from './diagnostics_test_utils.js'; - -suite('overviewCardTestSuite', function() { - /** @type {?OverviewCardElement} */ - let overviewElement = null; - - /** @type {?FakeSystemDataProvider} */ - let provider = null; - - suiteSetup(() => { - provider = new FakeSystemDataProvider(); - setSystemDataProviderForTesting(provider); - }); - - setup(() => { - document.body.innerHTML = window.trustedTypes.emptyHTML; - }); - - teardown(() => { - overviewElement.remove(); - overviewElement = null; - provider.reset(); - }); - - /** @param {!SystemInfo} fakeSystemInfo */ - function initializeOverviewCard(fakeSystemInfo) { - assertFalse(!!overviewElement); - - // Initialize the fake data. - provider.setFakeSystemInfo(fakeSystemInfo); - - // Add the overview card to the DOM. - overviewElement = /** @type {!OverviewCardElement} */ ( - document.createElement('overview-card')); - assertTrue(!!overviewElement); - document.body.appendChild(overviewElement); - - return flushTasks(); - } - - test('OverviewCardPopulated', () => { - return initializeOverviewCard(fakeSystemInfo).then(() => { - dx_utils.assertElementContainsText( - overviewElement.shadowRoot.querySelector('#marketingName'), - fakeSystemInfo.marketingName); - dx_utils.assertElementContainsText( - overviewElement.shadowRoot.querySelector('#deviceInfo'), - fakeSystemInfo.boardName); - dx_utils.assertElementContainsText( - overviewElement.shadowRoot.querySelector('#deviceInfo'), - fakeSystemInfo.versionInfo.milestoneVersion); - }); - }); - - test('TBDMarketingNameHidden', () => { - return initializeOverviewCard(fakeSystemInfoWithTBD).then(() => { - assertFalse(isVisible( - /** @type {!HTMLElement} */ ( - overviewElement.shadowRoot.querySelector('#marketingName')))); - - // Device info should not be surrounded by parentheses when the marketing - // name is hidden. - const deviceInfoText = - overviewElement.shadowRoot.querySelector('#deviceInfo').textContent; - assertTrue(deviceInfoText[0] !== '('); - assertTrue(deviceInfoText[deviceInfoText.length - 1] !== ')'); - }); - }); - - test('BoardNameMissing', () => { - return initializeOverviewCard(fakeSystemInfoWithoutBoardName).then(() => { - const versionInfo = loadTimeData.getStringF( - 'versionInfo', - fakeSystemInfoWithoutBoardName.versionInfo.fullVersionString); - assertEquals( - overviewElement.shadowRoot.querySelector('#deviceInfo').textContent, - versionInfo[0].toUpperCase() + versionInfo.slice(1)); - }); - }); -});
diff --git a/chrome/test/data/webui/chromeos/diagnostics/overview_card_test.ts b/chrome/test/data/webui/chromeos/diagnostics/overview_card_test.ts new file mode 100644 index 0000000..57c4143 --- /dev/null +++ b/chrome/test/data/webui/chromeos/diagnostics/overview_card_test.ts
@@ -0,0 +1,96 @@ +// Copyright 2020 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'chrome://diagnostics/overview_card.js'; +import 'chrome://webui-test/chromeos/mojo_webui_test_support.js'; + +import {fakeSystemInfo, fakeSystemInfoWithoutBoardName, fakeSystemInfoWithTBD} from 'chrome://diagnostics/fake_data.js'; +import {FakeSystemDataProvider} from 'chrome://diagnostics/fake_system_data_provider.js'; +import {setSystemDataProviderForTesting} from 'chrome://diagnostics/mojo_interface_provider.js'; +import {OverviewCardElement} from 'chrome://diagnostics/overview_card.js'; +import {SystemInfo} from 'chrome://diagnostics/system_data_provider.mojom-webui.js'; +import {loadTimeData} from 'chrome://resources/ash/common/load_time_data.m.js'; +import {strictQuery} from 'chrome://resources/ash/common/typescript_utils/strict_query.js'; +import {assert} from 'chrome://resources/js/assert.js'; +import {assertEquals, assertFalse, assertNotEquals} from 'chrome://webui-test/chromeos/chai_assert.js'; +import {flushTasks} from 'chrome://webui-test/polymer_test_util.js'; +import {isVisible} from 'chrome://webui-test/test_util.js'; + +import * as dx_utils from './diagnostics_test_utils.js'; + +suite('overviewCardTestSuite', function() { + let overviewElement: OverviewCardElement|null = null; + + const provider = new FakeSystemDataProvider(); + + suiteSetup(() => { + setSystemDataProviderForTesting(provider); + }); + + setup(() => { + document.body.innerHTML = window.trustedTypes!.emptyHTML; + }); + + teardown(() => { + overviewElement?.remove(); + overviewElement = null; + provider.reset(); + }); + + function initializeOverviewCard(fakeSystemInfo: SystemInfo): Promise<void> { + assertFalse(!!overviewElement); + + // Initialize the fake data. + provider.setFakeSystemInfo(fakeSystemInfo); + + // Add the overview card to the DOM. + overviewElement = document.createElement(OverviewCardElement.is); + assert(overviewElement); + document.body.appendChild(overviewElement); + + return flushTasks(); + } + + test('OverviewCardPopulated', async () => { + await initializeOverviewCard(fakeSystemInfo); + assert(overviewElement); + dx_utils.assertElementContainsText( + strictQuery( + '#marketingName', overviewElement.shadowRoot, HTMLSpanElement), + fakeSystemInfo.marketingName); + dx_utils.assertElementContainsText( + strictQuery('#deviceInfo', overviewElement.shadowRoot, HTMLSpanElement), + fakeSystemInfo.boardName); + dx_utils.assertElementContainsText( + strictQuery('#deviceInfo', overviewElement.shadowRoot, HTMLSpanElement), + fakeSystemInfo.versionInfo.milestoneVersion); + }); + + test('TBDMarketingNameHidden', async () => { + await initializeOverviewCard(fakeSystemInfoWithTBD); + assert(overviewElement); + assertFalse(isVisible(strictQuery( + '#marketingName', overviewElement.shadowRoot, HTMLSpanElement))); + // Device info should not be surrounded by parentheses when the marketing + // name is hidden. + const deviceInfoText = + strictQuery('#deviceInfo', overviewElement.shadowRoot, HTMLSpanElement) + .textContent; + assert(deviceInfoText); + assertNotEquals('(', deviceInfoText[0]); + assertNotEquals(')', deviceInfoText[deviceInfoText.length - 1]); + }); + + test('BoardNameMissing', async () => { + await initializeOverviewCard(fakeSystemInfoWithoutBoardName); + assert(overviewElement); + const versionInfo = loadTimeData.getStringF( + 'versionInfo', + fakeSystemInfoWithoutBoardName!.versionInfo!.fullVersionString); + assertEquals( + versionInfo[0]!.toUpperCase() + versionInfo!.slice(1), + strictQuery('#deviceInfo', overviewElement.shadowRoot, HTMLSpanElement) + .textContent); + }); +});
diff --git a/chrome/test/data/webui/intro/intro_browsertest.cc b/chrome/test/data/webui/intro/intro_browsertest.cc index 5513899..5c28e71 100644 --- a/chrome/test/data/webui/intro/intro_browsertest.cc +++ b/chrome/test/data/webui/intro/intro_browsertest.cc
@@ -2,35 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "base/test/scoped_feature_list.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/web_ui_mocha_browser_test.h" #include "components/signin/public/base/signin_buildflags.h" -#include "components/signin/public/base/signin_switches.h" #include "content/public/test/browser_test.h" class IntroBrowserTest : public WebUIMochaBrowserTest { protected: IntroBrowserTest() { set_test_loader_host(chrome::kChromeUIIntroHost); } - - private: - base::test::ScopedFeatureList scoped_feature_list_{kForYouFre}; }; -using IntroTest = IntroBrowserTest; - #if BUILDFLAG(ENABLE_DICE_SUPPORT) -IN_PROC_BROWSER_TEST_F(IntroTest, SignInPromo) { +IN_PROC_BROWSER_TEST_F(IntroBrowserTest, SignInPromo) { RunTest("intro/sign_in_promo_test.js", "mocha.run()"); } -IN_PROC_BROWSER_TEST_F(IntroTest, DiceApp) { +IN_PROC_BROWSER_TEST_F(IntroBrowserTest, DiceApp) { RunTest("intro/dice_app_test.js", "mocha.run()"); } #endif // BUILDFLAG(ENABLE_DICE_SUPPORT) #if BUILDFLAG(IS_CHROMEOS_LACROS) -IN_PROC_BROWSER_TEST_F(IntroTest, LacrosApp) { +IN_PROC_BROWSER_TEST_F(IntroBrowserTest, LacrosApp) { RunTest("intro/lacros_app_test.js", "mocha.run()"); } #endif // BUILDFLAG(IS_CHROMEOS_LACROS)
diff --git a/chrome/test/data/webui/lens/lens_webui_browsertest.cc b/chrome/test/data/webui/lens/lens_webui_browsertest.cc index 9ecb436..165ab7d2 100644 --- a/chrome/test/data/webui/lens/lens_webui_browsertest.cc +++ b/chrome/test/data/webui/lens/lens_webui_browsertest.cc
@@ -59,7 +59,7 @@ ASSERT_EQ(controller->state(), State::kOff); // Showing UI should eventually result in overlay state. - controller->ShowUI(); + controller->ShowUI(LensOverlayController::kAppMenu); ASSERT_TRUE(base::test::RunUntil( [&]() { return controller->state() == State::kOverlay; }));
diff --git a/chrome/updater/constants.h b/chrome/updater/constants.h index 0253f05..3c76c43bc 100644 --- a/chrome/updater/constants.h +++ b/chrome/updater/constants.h
@@ -431,6 +431,9 @@ // service. inline constexpr int kErrorEulaRequired = 46; +// The current operating system is not supported. +inline constexpr int kErrorUnsupportedOperatingSystem = 47; + inline constexpr int kErrorTagParsing = 50; // Metainstaller errors.
diff --git a/chrome/updater/setup_mac.mm b/chrome/updater/setup_mac.mm index d4c0482..5f589ef 100644 --- a/chrome/updater/setup_mac.mm +++ b/chrome/updater/setup_mac.mm
@@ -4,8 +4,12 @@ #include "chrome/updater/setup.h" +#include <AvailabilityMacros.h> + #include "base/functional/bind.h" #include "base/functional/callback.h" +#include "base/mac/mac_util.h" +#include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/updater/constants.h" @@ -16,6 +20,12 @@ void InstallCandidate(UpdaterScope scope, base::OnceCallback<void(int)> callback) { + if (base::mac::MacOSVersion() < MAC_OS_X_VERSION_MIN_REQUIRED) { + base::SequencedTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, + base::BindOnce(std::move(callback), kErrorUnsupportedOperatingSystem)); + return; + } base::ThreadPool::PostTaskAndReplyWithResult(FROM_HERE, {base::MayBlock()}, base::BindOnce(&Setup, scope), std::move(callback));
diff --git a/chrome/updater/setup_win.cc b/chrome/updater/setup_win.cc index e7f2b198..51027d3 100644 --- a/chrome/updater/setup_win.cc +++ b/chrome/updater/setup_win.cc
@@ -6,8 +6,11 @@ #include "base/functional/bind.h" #include "base/functional/callback.h" +#include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" +#include "base/win/windows_version.h" +#include "chrome/updater/constants.h" #include "chrome/updater/updater_scope.h" #include "chrome/updater/win/setup/setup.h" @@ -15,6 +18,12 @@ void InstallCandidate(UpdaterScope scope, base::OnceCallback<void(int)> callback) { + if (base::win::GetVersion() < base::win::Version::WIN10) { + base::SequencedTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, + base::BindOnce(std::move(callback), kErrorUnsupportedOperatingSystem)); + return; + } base::ThreadPool::PostTaskAndReplyWithResult(FROM_HERE, {base::MayBlock()}, base::BindOnce(&Setup, scope), std::move(callback));
diff --git a/chromeos/ash/components/audio/audio_device_metrics_handler.cc b/chromeos/ash/components/audio/audio_device_metrics_handler.cc index bd9648d..f3d64ca8 100644 --- a/chromeos/ash/components/audio/audio_device_metrics_handler.cc +++ b/chromeos/ash/components/audio/audio_device_metrics_handler.cc
@@ -79,11 +79,13 @@ input_devices_bits); // Record the before and after encoded device sets. + uint32_t before_and_after_input_device_set_bits = + EncodeBeforeAndAfterAudioDeviceSets(previous_input_devices, + input_devices); base::UmaHistogramSparse( is_switched ? kSystemSwitchInputBeforeAndAfterAudioDeviceSet : kSystemNotSwitchInputBeforeAndAfterAudioDeviceSet, - EncodeBeforeAndAfterAudioDeviceSets(previous_input_devices, - input_devices)); + before_and_after_input_device_set_bits); // Record chrome restarts related metrics. RecordAudioSelectionMetricsSeparatedByChromeRestarts( @@ -98,6 +100,8 @@ input_not_switched_by_system_at_ = is_switched ? std::nullopt : std::make_optional(base::TimeTicks::Now()); is_system_decision_at_chrome_restarts_ = is_chrome_restarts_; + before_and_after_input_device_set_bits_ = + before_and_after_input_device_set_bits; } else { // Do not record if there is only one audio device. Same as above. if (!has_alternative_device) { @@ -146,11 +150,13 @@ output_devices_bits); // Record the before and after encoded device sets. + uint32_t before_and_after_output_device_set_bits = + EncodeBeforeAndAfterAudioDeviceSets(previous_output_devices, + output_devices); base::UmaHistogramSparse( is_switched ? kSystemSwitchOutputBeforeAndAfterAudioDeviceSet : kSystemNotSwitchOutputBeforeAndAfterAudioDeviceSet, - EncodeBeforeAndAfterAudioDeviceSets(previous_output_devices, - output_devices)); + before_and_after_output_device_set_bits); // Record chrome restarts related metrics. RecordAudioSelectionMetricsSeparatedByChromeRestarts( @@ -165,6 +171,8 @@ output_not_switched_by_system_at_ = is_switched ? std::nullopt : std::make_optional(base::TimeTicks::Now()); is_system_decision_at_chrome_restarts_ = is_chrome_restarts_; + before_and_after_output_device_set_bits_ = + before_and_after_output_device_set_bits; } } @@ -225,12 +233,18 @@ time_delta_since_system_decision); // Record user override metrics separated by chrome restarts. - RecordUserOverrideMetricsSeparatedByChromeRestarts( is_input, /*is_switched=*/true, /*is_chrome_restarts=*/is_system_decision_at_chrome_restarts, time_delta_since_system_decision); + // Record the before and after encoded device sets. + base::UmaHistogramSparse( + is_input ? kUserOverrideSystemSwitchInputBeforeAndAfterAudioDeviceSet + : kUserOverrideSystemSwitchOutputBeforeAndAfterAudioDeviceSet, + is_input ? before_and_after_input_device_set_bits_ + : before_and_after_output_device_set_bits_); + // Reset the system_switch timestamp since user has activated an audio // device now. User activating again is not considered overriding system // decision, thus not recorded. @@ -253,12 +267,19 @@ time_delta_since_system_decision); // Record user override metrics separated by chrome restarts. - RecordUserOverrideMetricsSeparatedByChromeRestarts( is_input, /*is_switched=*/false, /*is_chrome_restarts=*/is_system_decision_at_chrome_restarts, time_delta_since_system_decision); + // Record the before and after encoded device sets. + base::UmaHistogramSparse( + is_input + ? kUserOverrideSystemNotSwitchInputBeforeAndAfterAudioDeviceSet + : kUserOverrideSystemNotSwitchOutputBeforeAndAfterAudioDeviceSet, + is_input ? before_and_after_input_device_set_bits_ + : before_and_after_output_device_set_bits_); + // Reset the system_not_switch timestamp since user has activated an audio // device now. not_switched_by_system_at = std::nullopt;
diff --git a/chromeos/ash/components/audio/audio_device_metrics_handler.h b/chromeos/ash/components/audio/audio_device_metrics_handler.h index 66645f2c..e4e868f 100644 --- a/chromeos/ash/components/audio/audio_device_metrics_handler.h +++ b/chromeos/ash/components/audio/audio_device_metrics_handler.h
@@ -106,6 +106,25 @@ "ChromeOS.AudioSelection.Output.SystemNotSwitchAudio." "BeforeAndAfterAudioDeviceSet"; + // A series of histogram metrics to record the before and after condition + // of audio device types when users override the system selection decision. + static constexpr char + kUserOverrideSystemSwitchInputBeforeAndAfterAudioDeviceSet[] = + "ChromeOS.AudioSelection.Input.UserOverrideSystemSwitchAudio." + "BeforeAndAfterAudioDeviceSet"; + static constexpr char + kUserOverrideSystemNotSwitchInputBeforeAndAfterAudioDeviceSet[] = + "ChromeOS.AudioSelection.Input.UserOverrideSystemNotSwitchAudio." + "BeforeAndAfterAudioDeviceSet"; + static constexpr char + kUserOverrideSystemSwitchOutputBeforeAndAfterAudioDeviceSet[] = + "ChromeOS.AudioSelection.Output.UserOverrideSystemSwitchAudio." + "BeforeAndAfterAudioDeviceSet"; + static constexpr char + kUserOverrideSystemNotSwitchOutputBeforeAndAfterAudioDeviceSet[] = + "ChromeOS.AudioSelection.Output.UserOverrideSystemNotSwitchAudio." + "BeforeAndAfterAudioDeviceSet"; + // A series of histogram metrics to record system selection decision after // audio device has changed. static constexpr char kSystemSwitchInputAudioChromeRestarts[] = @@ -428,6 +447,12 @@ std::optional<base::TimeTicks> output_not_switched_by_system_at_ = std::nullopt; + // The device set bits calculated by EncodeBeforeAndAfterAudioDeviceSets + // function to record the audio devices types when users override the system + // decision. + uint32_t before_and_after_input_device_set_bits_ = 0; + uint32_t before_and_after_output_device_set_bits_ = 0; + // The timestamp when devices have changed, including devices added/removed // and devices changed. Used for recording the time elaspsed between two // consecutive devices change event.
diff --git a/chromeos/ash/components/audio/audio_device_selection_unittest.cc b/chromeos/ash/components/audio/audio_device_selection_unittest.cc index c3a80ee..e22a7926 100644 --- a/chromeos/ash/components/audio/audio_device_selection_unittest.cc +++ b/chromeos/ash/components/audio/audio_device_selection_unittest.cc
@@ -634,6 +634,15 @@ // device. Select(input_internal); + histogram_tester().ExpectBucketCount( + AudioDeviceMetricsHandler:: + kUserOverrideSystemSwitchInputBeforeAndAfterAudioDeviceSet, + EncodeBeforeAndAfterAudioDeviceSets( + /*device_set_before=*/{AudioDevice(input_internal)}, + /*device_set_after=*/{AudioDevice(input_internal), + AudioDevice(input_USB)}), + /*bucket_count=*/1); + ExpectUserOverrideSystemDecisionHistogramCount( histogram_tester(), ++expected_user_override_system_switch_input_count, expected_user_override_system_not_switch_input_count, @@ -657,6 +666,15 @@ FastForwardBy(base::Minutes(kTimeDeltaInMinuteA)); Select(output_internal); + histogram_tester().ExpectBucketCount( + AudioDeviceMetricsHandler:: + kUserOverrideSystemSwitchOutputBeforeAndAfterAudioDeviceSet, + EncodeBeforeAndAfterAudioDeviceSets( + /*device_set_before=*/{AudioDevice(output_internal)}, + /*device_set_after=*/{AudioDevice(output_internal), + AudioDevice(output_USB)}), + /*bucket_count=*/1); + ExpectUserOverrideSystemDecisionHistogramCount( histogram_tester(), expected_user_override_system_switch_input_count, expected_user_override_system_not_switch_input_count, @@ -679,6 +697,15 @@ // there is no system switch or not switch decision in between. Select(output_USB); + histogram_tester().ExpectBucketCount( + AudioDeviceMetricsHandler:: + kUserOverrideSystemSwitchOutputBeforeAndAfterAudioDeviceSet, + EncodeBeforeAndAfterAudioDeviceSets( + /*device_set_before=*/{AudioDevice(output_internal)}, + /*device_set_after=*/{AudioDevice(output_internal), + AudioDevice(output_USB)}), + /*bucket_count=*/1); + ExpectUserOverrideSystemDecisionHistogramCount( histogram_tester(), expected_user_override_system_switch_input_count, expected_user_override_system_not_switch_input_count, @@ -760,6 +787,17 @@ FastForwardBy(base::Minutes(kTimeDeltaInMinuteB)); Select(input_USB); + histogram_tester().ExpectBucketCount( + AudioDeviceMetricsHandler:: + kUserOverrideSystemNotSwitchInputBeforeAndAfterAudioDeviceSet, + EncodeBeforeAndAfterAudioDeviceSets( + /*device_set_before=*/{AudioDevice(input_internal), + AudioDevice(input_USB)}, + /*device_set_after=*/{AudioDevice(input_internal), + AudioDevice(input_USB), + AudioDevice(input_bluetooth_nb)}), + /*bucket_count=*/1); + ExpectUserOverrideSystemDecisionHistogramCount( histogram_tester(), expected_user_override_system_switch_input_count, ++expected_user_override_system_not_switch_input_count, @@ -842,6 +880,17 @@ FastForwardBy(base::Minutes(kTimeDeltaInMinuteC)); Select(input_bluetooth_nb); + histogram_tester().ExpectBucketCount( + AudioDeviceMetricsHandler:: + kUserOverrideSystemSwitchInputBeforeAndAfterAudioDeviceSet, + EncodeBeforeAndAfterAudioDeviceSets( + /*device_set_before=*/{AudioDevice(input_internal), + AudioDevice(input_bluetooth_nb), + AudioDevice(input_USB)}, + /*device_set_after=*/{AudioDevice(input_internal), + AudioDevice(input_bluetooth_nb)}), + /*bucket_count=*/1); + ExpectUserOverrideSystemDecisionHistogramCount( histogram_tester(), ++expected_user_override_system_switch_input_count, expected_user_override_system_not_switch_input_count, @@ -990,6 +1039,15 @@ // Mock user switching to internal mic. Select(input_internal); + histogram_tester().ExpectBucketCount( + AudioDeviceMetricsHandler:: + kUserOverrideSystemSwitchInputBeforeAndAfterAudioDeviceSet, + EncodeBeforeAndAfterAudioDeviceSets( + /*device_set_before=*/{}, + /*device_set_after=*/{AudioDevice(input_internal), + AudioDevice(input_USB)}), + /*bucket_count=*/1); + ExpectUserOverrideSystemDecisionHistogramCount( histogram_tester(), ++expected_user_override_system_switch_input_count, expected_user_override_system_not_switch_input_count,
diff --git a/chromeos/ash/components/audio/cras_audio_handler.cc b/chromeos/ash/components/audio/cras_audio_handler.cc index aada3ac..4848920 100644 --- a/chromeos/ash/components/audio/cras_audio_handler.cc +++ b/chromeos/ash/components/audio/cras_audio_handler.cc
@@ -3039,6 +3039,8 @@ const AudioDevice* active_device = GetDeviceFromId(active_node_id); if (!active_device) { VLOG(1) << "SyncDevicePrefSetMap: No active device found."; + // Early return since no active_device is available to sync. + return; } std::map<std::string, std::string>& device_pref_set_map =
diff --git a/chromeos/ash/components/audio/cras_audio_handler_unittest.cc b/chromeos/ash/components/audio/cras_audio_handler_unittest.cc index ab2456c..efdd4bd3 100644 --- a/chromeos/ash/components/audio/cras_audio_handler_unittest.cc +++ b/chromeos/ash/components/audio/cras_audio_handler_unittest.cc
@@ -723,6 +723,17 @@ return message_center->NotificationCount(); } + // Helper function to call SyncDevicePrefSetMap. + void SyncDevicePrefSetMap(bool is_input) { + cras_audio_handler_->SyncDevicePrefSetMap(is_input); + } + + // Retrieves input_device_pref_set_map_ or output_device_pref_set_map_. + std::map<std::string, std::string>& GetDevicePrefSetMap(bool is_input) { + return is_input ? cras_audio_handler_->input_device_pref_set_map_ + : cras_audio_handler_->output_device_pref_set_map_; + } + protected: FakeCrasAudioClient* fake_cras_audio_client() { return FakeCrasAudioClient::Get(); @@ -7162,4 +7173,21 @@ EXPECT_EQ(1u, audio_devices.size()); } +// Tests calling SyncDevicePrefSetMap with no active device will early return +// and no crashes. +TEST_P(CrasAudioHandlerTest, SyncDevicePrefSetMap) { + SetUpCrasAudioHandler({}); + std::map<std::string, std::string>& input_device_pref_set_map = + GetDevicePrefSetMap(/*is_input=*/true); + std::map<std::string, std::string>& output_device_pref_set_map = + GetDevicePrefSetMap(/*is_input=*/false); + EXPECT_TRUE(input_device_pref_set_map.empty()); + EXPECT_TRUE(output_device_pref_set_map.empty()); + + SyncDevicePrefSetMap(/*is_input=*/true); + SyncDevicePrefSetMap(/*is_input=*/false); + EXPECT_TRUE(input_device_pref_set_map.empty()); + EXPECT_TRUE(output_device_pref_set_map.empty()); +} + } // namespace ash
diff --git a/clank b/clank index 620d29e..e8ea8ba 160000 --- a/clank +++ b/clank
@@ -1 +1 @@ -Subproject commit 620d29ecf663bd64f394abe63a9dfcd074ccf82e +Subproject commit e8ea8ba6aa94a95f24d12e785f2602153c069d94
diff --git a/components/attribution_reporting/privacy_math.h b/components/attribution_reporting/privacy_math.h index cca670e..46fb38f1 100644 --- a/components/attribution_reporting/privacy_math.h +++ b/components/attribution_reporting/privacy_math.h
@@ -22,9 +22,6 @@ class MaxEventLevelReports; class TriggerSpecs; -// TODO(apaseltiner): Use `uint8_t` as the type of both fields here, as the -// trigger data *index* is guaranteed to be < 32 and the window index is -// guaranteed to be < 5. struct FakeEventLevelReport { uint32_t trigger_data; int window_index;
diff --git a/components/autofill/content/renderer/autofill_agent.cc b/components/autofill/content/renderer/autofill_agent.cc index 81dfaaae..7c0a27f 100644 --- a/components/autofill/content/renderer/autofill_agent.cc +++ b/components/autofill/content/renderer/autofill_agent.cc
@@ -1789,7 +1789,9 @@ // submission from it (and the relevant use cases will most probably be // handled by other sources), therefore we only consider detached // subframes. - if (!unsafe_render_frame()->GetWebFrame()->IsOutermostMainFrame() && + if ((!unsafe_render_frame()->GetWebFrame()->IsOutermostMainFrame() || + base::FeatureList::IsEnabled( + features::kAutofillUnifyAndFixFormTracking)) && provisionally_saved_form()) { // Should not access the frame because it is now detached. Instead, use // `provisionally_saved_form()`.
diff --git a/components/autofill/content/renderer/autofill_agent_browsertest.cc b/components/autofill/content/renderer/autofill_agent_browsertest.cc index 1a34489..44eb3b0d 100644 --- a/components/autofill/content/renderer/autofill_agent_browsertest.cc +++ b/components/autofill/content/renderer/autofill_agent_browsertest.cc
@@ -731,29 +731,34 @@ } class AutofillAgentSubmissionTest : public AutofillAgentTest, - public testing::WithParamInterface<bool> { + public testing::WithParamInterface<int> { public: AutofillAgentSubmissionTest() { - if (improved_submission_detection()) { - scoped_feature_list.InitWithFeatures( - {features::kAutofillReplaceCachedWebElementsByRendererIds, - features::kAutofillReplaceFormElementObserver}, - /*disabled_features=*/{}); - } else { - scoped_feature_list.InitAndDisableFeature( - features::kAutofillReplaceFormElementObserver); - } + EXPECT_LE(GetParam(), 3); + std::vector<base::test::FeatureRef> features = { + features::kAutofillUnifyAndFixFormTracking, + features::kAutofillReplaceCachedWebElementsByRendererIds, + features::kAutofillReplaceFormElementObserver}; + + std::vector<base::test::FeatureRef> enabled_features( + features.begin(), features.begin() + GetParam()); + std::vector<base::test::FeatureRef> disabled_features( + features.begin() + GetParam(), features.end()); + scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); } - bool improved_submission_detection() { return GetParam(); } + bool improved_submission_detection() { + return base::FeatureList::IsEnabled( + features::kAutofillReplaceFormElementObserver); + } private: - base::test::ScopedFeatureList scoped_feature_list; + base::test::ScopedFeatureList scoped_feature_list_; }; INSTANTIATE_TEST_SUITE_P(AutofillSubmissionTest, AutofillAgentSubmissionTest, - ::testing::Bool()); + ::testing::Values(0, 1, 2, 3)); // Test that AutofillAgent::JavaScriptChangedValue updates the // last interacted saved state.
diff --git a/components/autofill/content/renderer/form_tracker.cc b/components/autofill/content/renderer/form_tracker.cc index bfd69eb..83e1d91 100644 --- a/components/autofill/content/renderer/form_tracker.cc +++ b/components/autofill/content/renderer/form_tracker.cc
@@ -326,8 +326,11 @@ void FormTracker::WillDetach(blink::DetachReason detach_reason) { DCHECK_CALLED_ON_VALID_SEQUENCE(form_tracker_sequence_checker_); + if (!unsafe_render_frame()) { + return; + } if (detach_reason == blink::DetachReason::kFrameDeletion && - (provisionally_saved_form() || + (!unsafe_render_frame()->GetWebFrame()->IsOutermostMainFrame() || !base::FeatureList::IsEnabled( features::kAutofillUnifyAndFixFormTracking))) { // Exclude cases where the previous RenderFrame gets deleted only to be @@ -336,6 +339,12 @@ // (<iframe> element etc) gets detached. FireInferredFormSubmission(SubmissionSource::FRAME_DETACHED); } + if (base::FeatureList::IsEnabled( + features::kAutofillUnifyAndFixFormTracking)) { + // TODO(b/40281981): Figure out if this is still needed, and document + // the reason, otherwise remove. + ResetLastInteractedElements(); + } } void FormTracker::WillSendSubmitEvent(const WebFormElement& form) { @@ -374,7 +383,10 @@ void FormTracker::OnFrameDetached() { DCHECK_CALLED_ON_VALID_SEQUENCE(form_tracker_sequence_checker_); - ResetLastInteractedElements(); + if (!base::FeatureList::IsEnabled( + features::kAutofillUnifyAndFixFormTracking)) { + ResetLastInteractedElements(); + } } void FormTracker::FireFormSubmitted(const blink::WebFormElement& form) {
diff --git a/components/autofill/content/renderer/form_tracker_browsertest.cc b/components/autofill/content/renderer/form_tracker_browsertest.cc index b36eeaf..b7bafb9e 100644 --- a/components/autofill/content/renderer/form_tracker_browsertest.cc +++ b/components/autofill/content/renderer/form_tracker_browsertest.cc
@@ -30,19 +30,20 @@ }; class FormTrackerTest : public test::AutofillRendererTest, - public testing::WithParamInterface<bool> { + public testing::WithParamInterface<int> { public: FormTrackerTest() { - if (GetParam()) { - scoped_feature_list_.InitWithFeatures( - /*enabled_features=*/ - {features::kAutofillReplaceCachedWebElementsByRendererIds, - features::kAutofillReplaceFormElementObserver}, - /*disabled_features=*/{}); - } else { - scoped_feature_list_.InitAndDisableFeature( - features::kAutofillReplaceFormElementObserver); - } + EXPECT_LE(GetParam(), 3); + std::vector<base::test::FeatureRef> features = { + features::kAutofillUnifyAndFixFormTracking, + features::kAutofillReplaceCachedWebElementsByRendererIds, + features::kAutofillReplaceFormElementObserver}; + + std::vector<base::test::FeatureRef> enabled_features( + features.begin(), features.begin() + GetParam()); + std::vector<base::test::FeatureRef> disabled_features( + features.begin() + GetParam(), features.end()); + scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); } blink::WebFormControlElement GetFormControlById(const std::string& id) { return GetMainFrame() @@ -57,7 +58,7 @@ INSTANTIATE_TEST_SUITE_P(AutofillSubmissionTest, FormTrackerTest, - ::testing::Bool()); + ::testing::Values(0, 1, 2, 3)); // Check that submission is detected on a page with no <form> when in sequence: // 1) User types into a field.
diff --git a/components/autofill/core/browser/browser_autofill_manager.cc b/components/autofill/core/browser/browser_autofill_manager.cc index 8214fd19..bc25b74 100644 --- a/components/autofill/core/browser/browser_autofill_manager.cc +++ b/components/autofill/core/browser/browser_autofill_manager.cc
@@ -1782,7 +1782,6 @@ base::FeatureList::IsEnabled( features::kAutofillFixCachingOnJavaScriptChanges)) { field.set_is_autofilled(false); - field.set_previously_autofilled(true); } // We are interested in reporting the events where JavaScript resets an // autofilled value immediately after filling. For a reset, the value
diff --git a/components/autofill/core/browser/metrics/suggestions_list_metrics.cc b/components/autofill/core/browser/metrics/suggestions_list_metrics.cc index 0178fb6b..e5a21f27 100644 --- a/components/autofill/core/browser/metrics/suggestions_list_metrics.cc +++ b/components/autofill/core/browser/metrics/suggestions_list_metrics.cc
@@ -37,9 +37,6 @@ FillingProduct filling_product) { switch (filling_product) { case FillingProduct::kAddress: - // TODO(b/324029575): Remove when the metric below gets to Stable. - base::UmaHistogramCounts100("Autofill.AddressSuggestionsCount", - num_suggestions); base::UmaHistogramCounts100("Autofill.SuggestionsCount.Address", num_suggestions); break;
diff --git a/components/autofill/core/browser/metrics/suggestions_list_metrics_unittest.cc b/components/autofill/core/browser/metrics/suggestions_list_metrics_unittest.cc index 88f26b0..c42d9db 100644 --- a/components/autofill/core/browser/metrics/suggestions_list_metrics_unittest.cc +++ b/components/autofill/core/browser/metrics/suggestions_list_metrics_unittest.cc
@@ -47,8 +47,6 @@ { base::HistogramTester histogram_tester; autofill_manager().OnAskForValuesToFillTest(form, form.fields.front()); - histogram_tester.ExpectUniqueSample("Autofill.AddressSuggestionsCount", 2, - 1); histogram_tester.ExpectUniqueSample("Autofill.SuggestionsCount.Address", 2, 1); }
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 88662f7..be8fbf9 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -686,7 +686,7 @@ base::FEATURE_DISABLED_BY_DEFAULT); const base::FeatureParam<int> kAutofillEnableCacheForRegexMatchingCacheSizeParam{ - &kAutofillEnableCacheForRegexMatching, "cache_size", 300}; + &kAutofillEnableCacheForRegexMatching, "cache_size", 1000}; // When enabled, various deduplication related metrics are logged on startup // and on import.
diff --git a/components/certificate_transparency/data/log_list.json b/components/certificate_transparency/data/log_list.json index edcd461..a41bfa7 100644 --- a/components/certificate_transparency/data/log_list.json +++ b/components/certificate_transparency/data/log_list.json
@@ -1,6 +1,6 @@ { - "version": "34.8", - "log_list_timestamp": "2024-05-06T12:54:57Z", + "version": "34.9", + "log_list_timestamp": "2024-05-07T12:55:54Z", "operators": [ { "name": "Google",
diff --git a/components/commerce/core/commerce_info_cache.h b/components/commerce/core/commerce_info_cache.h index ad13c4c..757dd1b1 100644 --- a/components/commerce/core/commerce_info_cache.h +++ b/components/commerce/core/commerce_info_cache.h
@@ -45,6 +45,10 @@ // The product info associated with the URL or nullptr if not available. std::unique_ptr<ProductInfo> product_info; + // A flag indicating whether we should check for product info on-demand. + // This will be used to prevent repeated attempts. + bool run_product_info_on_demand{true}; + // The price insights info associated with the URL or nullptr if not // available. std::unique_ptr<PriceInsightsInfo> price_insights_info;
diff --git a/components/commerce/core/compare/cluster_manager.cc b/components/commerce/core/compare/cluster_manager.cc index 0931bd3..e4d7cec 100644 --- a/components/commerce/core/compare/cluster_manager.cc +++ b/components/commerce/core/compare/cluster_manager.cc
@@ -173,11 +173,12 @@ OnProductSpecificationsSetAdded(product_specifications_set); } -void ClusterManager::OnProductSpecificationsSetRemoved(const base::Uuid& uuid) { +void ClusterManager::OnProductSpecificationsSetRemoved( + const ProductSpecificationsSet& set) { // TODO(qinmin): Check if we still want to keep candidate product from // the removed product group in `candidate_product_map_` if tab is still // open. - product_group_map_.erase(uuid); + product_group_map_.erase(set.uuid()); } void ClusterManager::WebWrapperDestroyed(const GURL& url) {
diff --git a/components/commerce/core/compare/cluster_manager.h b/components/commerce/core/compare/cluster_manager.h index 25cee3d..4b48640 100644 --- a/components/commerce/core/compare/cluster_manager.h +++ b/components/commerce/core/compare/cluster_manager.h
@@ -43,7 +43,8 @@ void OnProductSpecificationsSetUpdate( const ProductSpecificationsSet& before, const ProductSpecificationsSet& product_specifications_set) override; - void OnProductSpecificationsSetRemoved(const base::Uuid& uuid) override; + void OnProductSpecificationsSetRemoved( + const ProductSpecificationsSet& set) override; // A notification that a WebWrapper with `url` has been destroyed. This // signals that the web page backing the provided WebWrapper is about to be
diff --git a/components/commerce/core/compare/cluster_manager_unittest.cc b/components/commerce/core/compare/cluster_manager_unittest.cc index a92fa03..65bbef8 100644 --- a/components/commerce/core/compare/cluster_manager_unittest.cc +++ b/components/commerce/core/compare/cluster_manager_unittest.cc
@@ -99,16 +99,16 @@ } } - base::Uuid AddProductSpecificationSet() { + ProductSpecificationsSet AddProductSpecificationSet() { ProductSpecificationsSet product_specifications_set = CreateProductSpecificationsSet(kProduct1Url); cluster_manager_->OnProductSpecificationsSetAdded( product_specifications_set); - return product_specifications_set.uuid(); + return product_specifications_set; } - void RemoveProductSpecificationSet(const base::Uuid& uuid) { - cluster_manager_->OnProductSpecificationsSetRemoved(uuid); + void RemoveProductSpecificationSet(const ProductSpecificationsSet& set) { + cluster_manager_->OnProductSpecificationsSetRemoved(set); } std::vector<GURL> FindSimilarCandidateProductsForProductGroup( @@ -353,7 +353,7 @@ } TEST_F(ClusterManagerTest, FindSimilarCandidateProductsForProductGroup) { - base::Uuid uuid = AddProductSpecificationSet(); + base::Uuid uuid = AddProductSpecificationSet().uuid(); ProductGroup* product_group = (*GetProductGroupMap())[uuid].get(); ASSERT_EQ(1u, product_group->member_products.size()); @@ -388,7 +388,7 @@ cluster_manager_->DidNavigatePrimaryMainFrame(foo3); base::RunLoop().RunUntilIdle(); - base::Uuid uuid = AddProductSpecificationSet(); + base::Uuid uuid = AddProductSpecificationSet().uuid(); ProductGroup* product_group = (*GetProductGroupMap())[uuid].get(); ASSERT_EQ(1u, product_group->member_products.size()); @@ -457,7 +457,7 @@ ->set_category_default_label(kCategoryChair); product_infos_[GURL(kProduct1Url)] = product_info; - base::Uuid uuid = AddProductSpecificationSet(); + base::Uuid uuid = AddProductSpecificationSet().uuid(); ProductGroup* product_group = (*GetProductGroupMap())[uuid].get(); ASSERT_EQ(1u, product_group->member_products.size()); GURL foo1(kTestUrl1); @@ -509,7 +509,7 @@ } TEST_F(ClusterManagerTest, RemoveProductGroup) { - base::Uuid uuid = AddProductSpecificationSet(); + ProductSpecificationsSet product_specs = AddProductSpecificationSet(); GURL foo1(kTestUrl1); GURL foo2(kTestUrl2); GURL foo3(kTestUrl3); @@ -521,13 +521,13 @@ base::RunLoop().RunUntilIdle(); ASSERT_EQ(3u, GetCandidateProductMap()->size()); - RemoveProductSpecificationSet(uuid); - ASSERT_FALSE((*GetProductGroupMap())[uuid]); + RemoveProductSpecificationSet(product_specs); + ASSERT_FALSE((*GetProductGroupMap())[product_specs.uuid()]); ASSERT_EQ(3u, GetCandidateProductMap()->size()); } TEST_F(ClusterManagerTest, GetProductGroupForCandidateProduct) { - base::Uuid uuid = AddProductSpecificationSet(); + base::Uuid uuid = AddProductSpecificationSet().uuid(); ProductGroup* product_group = (*GetProductGroupMap())[uuid].get(); ASSERT_EQ(1u, product_group->member_products.size()); base::RunLoop().RunUntilIdle(); @@ -587,7 +587,7 @@ } TEST_F(ClusterManagerTest, AddCandidateProductAlreadyInProductGroups) { - base::Uuid uuid = AddProductSpecificationSet(); + base::Uuid uuid = AddProductSpecificationSet().uuid(); ProductGroup* product_group = (*GetProductGroupMap())[uuid].get(); ASSERT_EQ(1u, product_group->member_products.size()); GURL foo1(kProduct1Url);
diff --git a/components/commerce/core/product_specifications/product_specifications_service_unittest.cc b/components/commerce/core/product_specifications/product_specifications_service_unittest.cc index 228980b..c657039 100644 --- a/components/commerce/core/product_specifications/product_specifications_service_unittest.cc +++ b/components/commerce/core/product_specifications/product_specifications_service_unittest.cc
@@ -100,10 +100,6 @@ return arg.uuid() == uuid; } -MATCHER_P(IsUuid, uuid, "") { - return arg.AsLowercaseString() == uuid; -} - MATCHER_P2(HasProductSpecsNameUrl, name, urls, "") { return arg.name() == name && arg.urls() == urls; } @@ -174,7 +170,7 @@ MOCK_METHOD(void, OnProductSpecificationsSetRemoved, - (const base::Uuid& uuid), + (const ProductSpecificationsSet& set), (override)); }; @@ -269,8 +265,9 @@ TEST_F(ProductSpecificationsServiceTest, TestRemoveProductSpecifications) { AddTestSpecifics(bridge()); - EXPECT_CALL(*observer(), OnProductSpecificationsSetRemoved( - IsUuid(kCompareSpecifics[0].uuid()))) + EXPECT_CALL(*observer(), + OnProductSpecificationsSetRemoved(IsSetWithUuid( + base::Uuid::ParseLowercase(kCompareSpecifics[0].uuid())))) .Times(1); service()->DeleteProductSpecificationsSet(kCompareSpecifics[0].uuid()); } @@ -410,8 +407,8 @@ for (const auto& specifics : kCompareSpecifics) { remove_changes.push_back( syncer::EntityChange::CreateDelete(specifics.uuid())); - EXPECT_CALL(*observer(), - OnProductSpecificationsSetRemoved(IsUuid(specifics.uuid()))) + EXPECT_CALL(*observer(), OnProductSpecificationsSetRemoved(IsSetWithUuid( + base::Uuid::ParseLowercase(specifics.uuid())))) .Times(1); } bridge()->ApplyIncrementalSyncChanges(
diff --git a/components/commerce/core/product_specifications/product_specifications_set.h b/components/commerce/core/product_specifications/product_specifications_set.h index 8524df07..3154fcf2 100644 --- a/components/commerce/core/product_specifications/product_specifications_set.h +++ b/components/commerce/core/product_specifications/product_specifications_set.h
@@ -32,14 +32,11 @@ const ProductSpecificationsSet& before, const ProductSpecificationsSet& after) {} - virtual void OnProductSpecificationsSetRemoved(const base::Uuid& uuid) {} + virtual void OnProductSpecificationsSetRemoved( + const ProductSpecificationsSet& product_specifications_set) {} private: friend commerce::ProductSpecificationsSyncBridge; - - void OnProductSpecificationsSetRemoved(const std::string& uuid) { - OnProductSpecificationsSetRemoved(base::Uuid::ParseLowercase(uuid)); - } }; ProductSpecificationsSet(const std::string& uuid,
diff --git a/components/commerce/core/product_specifications/product_specifications_sync_bridge.cc b/components/commerce/core/product_specifications/product_specifications_sync_bridge.cc index bb564ed..659c4e3c 100644 --- a/components/commerce/core/product_specifications/product_specifications_sync_bridge.cc +++ b/components/commerce/core/product_specifications/product_specifications_sync_bridge.cc
@@ -89,9 +89,15 @@ break; } case syncer::EntityChange::ACTION_DELETE: + auto it = entries_.find(change->storage_key()); + if (it == entries_.end()) { + break; + } + ProductSpecificationsSet deleted_set = + ProductSpecificationsSet::FromProto(it->second); entries_.erase(change->storage_key()); batch->DeleteData(change->storage_key()); - OnSpecificsRemoved(change->storage_key()); + OnSpecificsRemoved(deleted_set); break; } } @@ -202,6 +208,13 @@ return; } + auto it = entries_.find(uuid); + if (it == entries_.end()) { + return; + } + ProductSpecificationsSet deleted_set = + ProductSpecificationsSet::FromProto(it->second); + std::unique_ptr<syncer::ModelTypeStore::WriteBatch> batch = store_->CreateWriteBatch(); @@ -212,7 +225,7 @@ batch->DeleteData(uuid); Commit(std::move(batch)); - OnSpecificsRemoved(uuid); + OnSpecificsRemoved(deleted_set); } void ProductSpecificationsSyncBridge::OnStoreCreated( @@ -304,9 +317,9 @@ } void ProductSpecificationsSyncBridge::OnSpecificsRemoved( - const std::string& uuid) { + const ProductSpecificationsSet& removed_set) { for (auto& observer : observers_) { - observer.OnProductSpecificationsSetRemoved(uuid); + observer.OnProductSpecificationsSetRemoved(removed_set); } }
diff --git a/components/commerce/core/product_specifications/product_specifications_sync_bridge.h b/components/commerce/core/product_specifications/product_specifications_sync_bridge.h index a4031b1..2b112ac 100644 --- a/components/commerce/core/product_specifications/product_specifications_sync_bridge.h +++ b/components/commerce/core/product_specifications/product_specifications_sync_bridge.h
@@ -87,7 +87,7 @@ void OnSpecificsAdded(const sync_pb::CompareSpecifics& compare_specifics); void OnSpecificsUpdated(const sync_pb::CompareSpecifics& before, const sync_pb::CompareSpecifics& compare_specifics); - void OnSpecificsRemoved(const std::string& uuid); + void OnSpecificsRemoved(const ProductSpecificationsSet& removed_set); CompareSpecificsEntries entries_;
diff --git a/components/commerce/core/shopping_service.cc b/components/commerce/core/shopping_service.cc index 5ec22536..b36271f 100644 --- a/components/commerce/core/shopping_service.cc +++ b/components/commerce/core/shopping_service.cc
@@ -887,16 +887,27 @@ ProductInfoCallback callback, optimization_guide::OptimizationGuideDecision decision, const optimization_guide::OptimizationMetadata& metadata) { + CommerceInfoCache::CacheEntry* entry = + commerce_info_cache_.GetEntryForUrl(url); + // If optimization guide returns negative, return a negative signal with an // empty data object. if (decision != optimization_guide::OptimizationGuideDecision::kTrue) { + if (entry && + decision == optimization_guide::OptimizationGuideDecision::kFalse) { + entry->run_product_info_on_demand = false; + } + // Receiving a negative signal could simply mean that opt guide no longer // has the information available, it doesn't mean the backend doesn't know. // We may be allowed to fetch information on-demand if we're referencing // the URL in the cache. Only do this for explicit requests from a feature // rather than populating as a result of navigation (signified by the lack // of a web wrapper). - if (commerce_info_cache_.IsUrlReferenced(url) && !web) { + if (commerce_info_cache_.IsUrlReferenced(url) && !web && entry && + entry->run_product_info_on_demand) { + entry->run_product_info_on_demand = false; + // We're wrapping this in a repeating callback but it should only ever be // called once. This is necessary because the on-demand api requires a // repeating callback but we primarily use once callbacks in the shopping @@ -931,6 +942,11 @@ return; } + // If we got a positive result, we don't need to run on-demand. + if (entry) { + entry->run_product_info_on_demand = false; + } + std::unique_ptr<ProductInfo> info = OptGuideResultToProductInfo(metadata); std::optional<ProductInfo> optional_info;
diff --git a/components/commerce/core/shopping_service_test_base.cc b/components/commerce/core/shopping_service_test_base.cc index 2a7bdb5e..a2ff962 100644 --- a/components/commerce/core/shopping_service_test_base.cc +++ b/components/commerce/core/shopping_service_test_base.cc
@@ -48,11 +48,34 @@ const uint64_t kInvalidDiscountId = 0; -MockOptGuideDecider::MockOptGuideDecider() = default; -MockOptGuideDecider::~MockOptGuideDecider() = default; +MockOptGuideDecider::MockOptGuideDecider() { + ON_CALL(*this, CanApplyOptimizationOnDemand) + .WillByDefault( + [&](const std::vector<GURL>& urls, + const base::flat_set<OptimizationType>& optimization_types, + RequestContext request_context, + OnDemandOptimizationGuideDecisionRepeatingCallback callback, + std::optional<RequestContextMetadata> request_context_metadata) { + if (optimization_types.contains(OptimizationType::PRICE_TRACKING)) { + for (const GURL& url : urls) { + if (on_demand_shopping_responses_.find(url.spec()) == + on_demand_shopping_responses_.end()) { + continue; + } -void MockOptGuideDecider::RegisterOptimizationTypes( - const std::vector<OptimizationType>& optimization_types) {} + base::flat_map<OptimizationType, + OptimizationGuideDecisionWithMetadata> + decision_map; + decision_map[OptimizationType::PRICE_TRACKING] = + on_demand_shopping_responses_[url.spec()]; + base::SequencedTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, + base::BindOnce(callback, url, std::move(decision_map))); + } + } + }); +} +MockOptGuideDecider::~MockOptGuideDecider() = default; void MockOptGuideDecider::CanApplyOptimization( const GURL& url, @@ -102,29 +125,6 @@ return OptimizationGuideDecision::kUnknown; } -void MockOptGuideDecider::CanApplyOptimizationOnDemand( - const std::vector<GURL>& urls, - const base::flat_set<OptimizationType>& optimization_types, - RequestContext request_context, - OnDemandOptimizationGuideDecisionRepeatingCallback callback, - std::optional<RequestContextMetadata> request_context_metadata) { - if (optimization_types.contains(OptimizationType::PRICE_TRACKING)) { - for (const GURL& url : urls) { - if (on_demand_shopping_responses_.find(url.spec()) == - on_demand_shopping_responses_.end()) { - continue; - } - - base::flat_map<OptimizationType, OptimizationGuideDecisionWithMetadata> - decision_map; - decision_map[OptimizationType::PRICE_TRACKING] = - on_demand_shopping_responses_[url.spec()]; - base::SequencedTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(callback, url, std::move(decision_map))); - } - } -} - void MockOptGuideDecider::AddOnDemandShoppingResponse( const GURL& url, const OptimizationGuideDecision decision, @@ -539,4 +539,8 @@ return shopping_service_->commerce_info_cache_; } +MockOptGuideDecider* ShoppingServiceTestBase::GetMockOptGuideDecider() { + return opt_guide_.get(); +} + } // namespace commerce
diff --git a/components/commerce/core/shopping_service_test_base.h b/components/commerce/core/shopping_service_test_base.h index 94b9119..e9a36beb 100644 --- a/components/commerce/core/shopping_service_test_base.h +++ b/components/commerce/core/shopping_service_test_base.h
@@ -23,6 +23,7 @@ #include "components/optimization_guide/core/optimization_metadata.h" #include "components/optimization_guide/proto/hints.pb.h" #include "services/data_decoder/public/cpp/test_support/in_process_data_decoder.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using optimization_guide::OnDemandOptimizationGuideDecisionRepeatingCallback; @@ -65,8 +66,18 @@ MockOptGuideDecider operator=(const MockOptGuideDecider&) = delete; ~MockOptGuideDecider() override; - void RegisterOptimizationTypes( - const std::vector<OptimizationType>& optimization_types) override; + MOCK_METHOD(void, + RegisterOptimizationTypes, + (const std::vector<OptimizationType>& optimization_types), + (override)); + MOCK_METHOD(void, + CanApplyOptimizationOnDemand, + (const std::vector<GURL>& urls, + const base::flat_set<OptimizationType>& optimization_types, + RequestContext request_context, + OnDemandOptimizationGuideDecisionRepeatingCallback callback, + std::optional<RequestContextMetadata> request_context_metadata), + (override)); void CanApplyOptimization( const GURL& url, @@ -78,14 +89,6 @@ OptimizationType optimization_type, OptimizationMetadata* optimization_metadata) override; - void CanApplyOptimizationOnDemand( - const std::vector<GURL>& urls, - const base::flat_set<OptimizationType>& optimization_types, - RequestContext request_context, - OnDemandOptimizationGuideDecisionRepeatingCallback callback, - std::optional<RequestContextMetadata> request_context_metadata = - std::nullopt) override; - void AddOnDemandShoppingResponse(const GURL& url, const OptimizationGuideDecision decision, const OptimizationMetadata& data); @@ -239,6 +242,8 @@ // Gets a handle to the cache. CommerceInfoCache& GetCache(); + MockOptGuideDecider* GetMockOptGuideDecider(); + protected: base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME};
diff --git a/components/commerce/core/shopping_service_unittest.cc b/components/commerce/core/shopping_service_unittest.cc index 41068ac..850dc882 100644 --- a/components/commerce/core/shopping_service_unittest.cc +++ b/components/commerce/core/shopping_service_unittest.cc
@@ -711,6 +711,114 @@ ASSERT_EQ(0, GetProductInfoCacheOpenURLCount(GURL(kProductUrl))); } +// The on-demand api should not be triggered in the case where we have an +// explicit negative signal from the page. +TEST_P(ShoppingServiceTest, TestProductInfoWithFallback_NoOnDemandCalls) { + MockWebWrapper web(GURL(kProductUrl), false); + + // Assume the page has already loaded for the navigation. This is usually the + // case for single-page webapps. + web.SetIsFirstLoadForNavigationFinished(true); + + opt_guide_->SetResponse(GURL(kProductUrl), OptimizationType::PRICE_TRACKING, + OptimizationGuideDecision::kFalse, + OptimizationMetadata()); + + // The on-demand api should only ever be called once in this test. + EXPECT_CALL(*GetMockOptGuideDecider(), CanApplyOptimizationOnDemand).Times(0); + + DidNavigatePrimaryMainFrame(&web); + // If the page was already loaded, assume the js has time to run now. + SimulateProductInfoLocalExtractionTaskFinished(); + + // By this point there should be something in the cache. + ASSERT_EQ(1, GetProductInfoCacheOpenURLCount(GURL(kProductUrl))); + + // We should be able to access the cached data. + CommerceInfoCache::CacheEntry* entry = + GetCache().GetEntryForUrl(GURL(kProductUrl)); + ASSERT_FALSE(entry == nullptr); + ASSERT_FALSE(entry->run_product_info_on_demand); + + // Querying for the info multiple times should not trigger the on-demand api. + base::RunLoop run_loop; + shopping_service_->GetProductInfoForUrl( + GURL(kProductUrl), base::BindOnce( + [](base::RunLoop* run_loop, const GURL& url, + const std::optional<const ProductInfo>& info) { + ASSERT_EQ(kProductUrl, url.spec()); + ASSERT_FALSE(info.has_value()); + run_loop->Quit(); + }, + &run_loop)); + run_loop.Run(); + + // Close the "tab" and make sure the cache is empty. + WebWrapperDestroyed(&web); + ASSERT_EQ(0, GetProductInfoCacheOpenURLCount(GURL(kProductUrl))); +} + +// If there's a reference to the url in the cache and opt guide doesn't know +// about the url, we should be allowed to call the on-demand api. +TEST_P(ShoppingServiceTest, + TestProductInfoWithFallback_CallsOnDemandOnce_RefInCache) { + // The on-demand api should not be called if there isn't a page open and + // there isn't a reference in the cache. + EXPECT_CALL(*GetMockOptGuideDecider(), CanApplyOptimizationOnDemand).Times(0); + + opt_guide_->SetResponse(GURL(kProductUrl), OptimizationType::PRICE_TRACKING, + OptimizationGuideDecision::kUnknown, + OptimizationMetadata()); + + base::RunLoop run_loop; + shopping_service_->GetProductInfoForUrl( + GURL(kProductUrl), base::BindOnce( + [](base::RunLoop* run_loop, const GURL& url, + const std::optional<const ProductInfo>& info) { + ASSERT_EQ(kProductUrl, url.spec()); + ASSERT_FALSE(info.has_value()); + run_loop->Quit(); + }, + &run_loop)); + run_loop.Run(); + + // We shouldn't have a cache entry. + ASSERT_TRUE(GetCache().GetEntryForUrl(GURL(kProductUrl)) == nullptr); + + // Add a ref to the url - this could be a page loading or another feature. + GetCache().AddRef(GURL(kProductUrl)); + + CommerceInfoCache::CacheEntry* entry = + GetCache().GetEntryForUrl(GURL(kProductUrl)); + ASSERT_FALSE(entry == nullptr); + ASSERT_TRUE(entry->run_product_info_on_demand); + + // We should now be allowed to call the on-demand api when product info is + // requested. + EXPECT_CALL(*GetMockOptGuideDecider(), CanApplyOptimizationOnDemand).Times(1); + + OptimizationMetadata meta = opt_guide_->BuildPriceTrackingResponse( + kTitle, "", kOfferId, kClusterId, kCountryCode); + opt_guide_->AddOnDemandShoppingResponse( + GURL(kProductUrl), OptimizationGuideDecision::kTrue, meta); + + // By this point there should be something in the cache. + ASSERT_EQ(1, GetProductInfoCacheOpenURLCount(GURL(kProductUrl))); + + // Querying for the info multiple times should not trigger the on-demand api. + base::RunLoop run_loop2; + shopping_service_->GetProductInfoForUrl( + GURL(kProductUrl), base::BindOnce( + [](base::RunLoop* run_loop, const GURL& url, + const std::optional<const ProductInfo>& info) { + ASSERT_EQ(kProductUrl, url.spec()); + ASSERT_TRUE(info.has_value()); + run_loop->Quit(); + }, + &run_loop2)); + run_loop2.Run(); +} + // Test that merchant info is processed correctly. TEST_P(ShoppingServiceTest, TestMerchantInfoResponse) { // Ensure a feature that uses merchant info is enabled.
diff --git a/components/commerce/core/webui/shopping_service_handler.cc b/components/commerce/core/webui/shopping_service_handler.cc index bfc2ba1..19fe65c6 100644 --- a/components/commerce/core/webui/shopping_service_handler.cc +++ b/components/commerce/core/webui/shopping_service_handler.cc
@@ -752,8 +752,8 @@ } void ShoppingServiceHandler::OnProductSpecificationsSetRemoved( - const base::Uuid& uuid) { - remote_page_->OnProductSpecificationsSetRemoved(uuid); + const ProductSpecificationsSet& set) { + remote_page_->OnProductSpecificationsSetRemoved(set.uuid()); } } // namespace commerce
diff --git a/components/commerce/core/webui/shopping_service_handler.h b/components/commerce/core/webui/shopping_service_handler.h index cca2a8d4..b2aa1416 100644 --- a/components/commerce/core/webui/shopping_service_handler.h +++ b/components/commerce/core/webui/shopping_service_handler.h
@@ -143,7 +143,8 @@ const ProductSpecificationsSet& before, const ProductSpecificationsSet& set) override; - void OnProductSpecificationsSetRemoved(const base::Uuid& uuid) override; + void OnProductSpecificationsSetRemoved( + const ProductSpecificationsSet& set) override; static std::vector<shopping_service::mojom::BookmarkProductInfoPtr> BookmarkListToMojoList(
diff --git a/components/heap_profiling/in_process/BUILD.gn b/components/heap_profiling/in_process/BUILD.gn index 7ff759a..c68c5712 100644 --- a/components/heap_profiling/in_process/BUILD.gn +++ b/components/heap_profiling/in_process/BUILD.gn
@@ -3,12 +3,22 @@ # found in the LICENSE file. import("//base/allocator/allocator.gni") +import("//mojo/public/tools/bindings/mojom.gni") + +mojom("mojom") { + sources = [ "mojom/snapshot_controller.mojom" ] + deps = [ "//mojo/public/mojom/base" ] +} source_set("in_process") { # HeapProfilerController's dependencies are not compiled on iOS unless # use_allocator_shim is true. if (!is_ios || use_allocator_shim) { sources = [ + "browser_process_snapshot_controller.cc", + "browser_process_snapshot_controller.h", + "child_process_snapshot_controller.cc", + "child_process_snapshot_controller.h", "heap_profiler_controller.cc", "heap_profiler_controller.h", "heap_profiler_parameters.cc", @@ -18,12 +28,14 @@ ] deps = [ + ":mojom", "//base", "//components/metrics", "//components/metrics:child_call_stack_profile_builder", "//components/services/heap_profiling/public/cpp:cpp", "//components/variations", "//components/version_info", + "//mojo/public/cpp/bindings", ] } } @@ -40,6 +52,7 @@ ] deps = [ ":in_process", + ":mojom", "//base/test:test_support", "//components/metrics", "//components/metrics:child_call_stack_profile_builder",
diff --git a/components/heap_profiling/in_process/DEPS b/components/heap_profiling/in_process/DEPS index 052f773..bb01966 100644 --- a/components/heap_profiling/in_process/DEPS +++ b/components/heap_profiling/in_process/DEPS
@@ -4,12 +4,12 @@ "+components/services/heap_profiling/public", "+components/variations/variations_switches.h", "+components/version_info", + "+mojo/public/cpp/bindings", ] specific_include_rules = { "heap_profiler_controller_unittest\.cc": [ "+components/metrics/public/mojom/call_stack_profile_collector.mojom.h", - "+mojo/public/cpp/bindings", "+third_party/metrics_proto/execution_context.pb.h", "+third_party/metrics_proto/sampled_profile.pb.h", ],
diff --git a/components/heap_profiling/in_process/browser_process_snapshot_controller.cc b/components/heap_profiling/in_process/browser_process_snapshot_controller.cc new file mode 100644 index 0000000..bdad1806 --- /dev/null +++ b/components/heap_profiling/in_process/browser_process_snapshot_controller.cc
@@ -0,0 +1,80 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/heap_profiling/in_process/browser_process_snapshot_controller.h" + +#include <utility> + +#include "base/functional/bind.h" +#include "base/functional/callback.h" +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "base/sequence_checker.h" +#include "base/task/sequenced_task_runner.h" +#include "components/heap_profiling/in_process/heap_profiler_controller.h" +#include "components/heap_profiling/in_process/mojom/snapshot_controller.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/remote_set.h" + +namespace heap_profiling { + +// static +BrowserProcessSnapshotController* +BrowserProcessSnapshotController::GetInstance() { + const auto* controller = HeapProfilerController::GetInstance(); + return controller ? controller->GetBrowserProcessSnapshotController() + : nullptr; +} + +BrowserProcessSnapshotController::BrowserProcessSnapshotController( + scoped_refptr<base::SequencedTaskRunner> snapshot_task_runner) + : snapshot_task_runner_(std::move(snapshot_task_runner)) { + // Label this as the main sequence. + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_checker_); + DETACH_FROM_SEQUENCE(snapshot_sequence_checker_); +} + +BrowserProcessSnapshotController::~BrowserProcessSnapshotController() { + DCHECK_CALLED_ON_VALID_SEQUENCE(snapshot_sequence_checker_); +} + +base::WeakPtr<BrowserProcessSnapshotController> +BrowserProcessSnapshotController::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + +void BrowserProcessSnapshotController::SetBindRemoteForChildProcessCallback( + BindRemoteCallback callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_checker_); + bind_remote_callback_ = std::move(callback); +} + +void BrowserProcessSnapshotController::BindRemoteForChildProcess( + int child_process_id) { + DCHECK_CALLED_ON_VALID_SEQUENCE(main_sequence_checker_); + mojo::PendingRemote<mojom::SnapshotController> remote; + bind_remote_callback_.Run(child_process_id, + remote.InitWithNewPipeAndPassReceiver()); + snapshot_task_runner_->PostTask( + FROM_HERE, + base::BindOnce( + &BrowserProcessSnapshotController::StoreRemoteOnSnapshotSequence, + GetWeakPtr(), std::move(remote))); +} + +void BrowserProcessSnapshotController::TakeSnapshotsOnSnapshotSequence() { + DCHECK_CALLED_ON_VALID_SEQUENCE(snapshot_sequence_checker_); + for (const auto& remote : remotes_) { + remote->TakeSnapshot(); + } +} + +void BrowserProcessSnapshotController::StoreRemoteOnSnapshotSequence( + mojo::PendingRemote<mojom::SnapshotController> remote) { + DCHECK_CALLED_ON_VALID_SEQUENCE(snapshot_sequence_checker_); + remotes_.Add(std::move(remote), snapshot_task_runner_); +} + +} // namespace heap_profiling
diff --git a/components/heap_profiling/in_process/browser_process_snapshot_controller.h b/components/heap_profiling/in_process/browser_process_snapshot_controller.h new file mode 100644 index 0000000..c332f82d --- /dev/null +++ b/components/heap_profiling/in_process/browser_process_snapshot_controller.h
@@ -0,0 +1,99 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_HEAP_PROFILING_IN_PROCESS_BROWSER_PROCESS_SNAPSHOT_CONTROLLER_H_ +#define COMPONENTS_HEAP_PROFILING_IN_PROCESS_BROWSER_PROCESS_SNAPSHOT_CONTROLLER_H_ + +#include "base/functional/callback_forward.h" +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "base/sequence_checker.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/remote_set.h" + +namespace base { +class SequencedTaskRunner; +} + +namespace heap_profiling { + +namespace mojom { +class SnapshotController; +} + +// Sends notifications to ChildProcessSnapshotController endpoints in child +// processes to trigger snapshots on demand from the HeapProfilerController in +// the current browser process. +// +// Unless otherwise noted all methods must be called on the main thread. +class BrowserProcessSnapshotController { + public: + // Returns the BrowserProcessSnapshotController for this process or nullptr if + // none exists. + static BrowserProcessSnapshotController* GetInstance(); + + // Outside of tests, BrowserProcessSnapshotController is created and owned by + // the HeapProfilerController. `snapshot_task_runner` will be used to take + // heap snapshots off of the main thread. + explicit BrowserProcessSnapshotController( + scoped_refptr<base::SequencedTaskRunner> snapshot_task_runner); + + // The destructor must be called on `snapshot_task_runner` so that + // WeakPtr's are invalidated on the correct sequence. + ~BrowserProcessSnapshotController(); + + BrowserProcessSnapshotController(const BrowserProcessSnapshotController&) = + delete; + BrowserProcessSnapshotController& operator=( + const BrowserProcessSnapshotController&) = delete; + + // Returns a pointer that must be dereferenced on `snapshot_task_runner`. + // This can be called from any thread. + base::WeakPtr<BrowserProcessSnapshotController> GetWeakPtr(); + + // Sets a callback that registers a remote endpoint to send commands to a + // child process. `callback` will be invoked from BindRemoteForChildProcess() + // with a `child_process_id` and a `pending_receiver`. The callback should + // bind the `pending_receiver` to a mojo::Receiver in the child process with + // ID `child_process_id`. The BrowserProcessSnapshotController will hold the + // mojo::Remote end of the connection. + using BindRemoteCallback = base::RepeatingCallback<void( + int /*child_process_id*/, + mojo::PendingReceiver<mojom::SnapshotController> /*pending_receiver*/)>; + void SetBindRemoteForChildProcessCallback(BindRemoteCallback callback); + + // Binds a remote endpoint to communicate with `child_process_id`. + void BindRemoteForChildProcess(int child_process_id); + + // Triggers a snapshot in all known child processes. This must be called on + // `snapshot_task_runner`. + void TakeSnapshotsOnSnapshotSequence(); + + private: + // Saves `remote` in `remotes_`. Must be called on `snapshot_task_runner`. + void StoreRemoteOnSnapshotSequence( + mojo::PendingRemote<mojom::SnapshotController> remote); + + SEQUENCE_CHECKER(main_sequence_checker_); + SEQUENCE_CHECKER(snapshot_sequence_checker_); + + // A task runner to trigger snapshots off of the main thread. + scoped_refptr<base::SequencedTaskRunner> snapshot_task_runner_; + + // Callback used to bind a mojo remote to a child process. + BindRemoteCallback bind_remote_callback_ + GUARDED_BY_CONTEXT(main_sequence_checker_); + + // A set of remotes for controlling child processes. Must be accessed on + // `snapshot_task_runner_`. + mojo::RemoteSet<mojom::SnapshotController> remotes_ + GUARDED_BY_CONTEXT(snapshot_sequence_checker_); + + base::WeakPtrFactory<BrowserProcessSnapshotController> weak_factory_{this}; +}; + +} // namespace heap_profiling + +#endif // COMPONENTS_HEAP_PROFILING_IN_PROCESS_BROWSER_PROCESS_SNAPSHOT_CONTROLLER_H_
diff --git a/components/heap_profiling/in_process/child_process_snapshot_controller.cc b/components/heap_profiling/in_process/child_process_snapshot_controller.cc new file mode 100644 index 0000000..00d87c1 --- /dev/null +++ b/components/heap_profiling/in_process/child_process_snapshot_controller.cc
@@ -0,0 +1,34 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/heap_profiling/in_process/child_process_snapshot_controller.h" + +#include <memory> +#include <utility> + +#include "base/memory/ptr_util.h" +#include "base/types/pass_key.h" +#include "components/heap_profiling/in_process/heap_profiler_controller.h" +#include "components/heap_profiling/in_process/mojom/snapshot_controller.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "mojo/public/cpp/bindings/self_owned_receiver.h" + +namespace heap_profiling { + +// static +void ChildProcessSnapshotController::CreateSelfOwnedReceiver( + mojo::PendingReceiver<mojom::SnapshotController> receiver) { + mojo::MakeSelfOwnedReceiver( + base::WrapUnique(new ChildProcessSnapshotController()), + std::move(receiver)); +} + +void ChildProcessSnapshotController::TakeSnapshot() { + if (auto* controller = HeapProfilerController::GetInstance()) { + controller->TakeSnapshotInChildProcess( + base::PassKey<ChildProcessSnapshotController>()); + } +} + +} // namespace heap_profiling
diff --git a/components/heap_profiling/in_process/child_process_snapshot_controller.h b/components/heap_profiling/in_process/child_process_snapshot_controller.h new file mode 100644 index 0000000..bd1e538 --- /dev/null +++ b/components/heap_profiling/in_process/child_process_snapshot_controller.h
@@ -0,0 +1,38 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_HEAP_PROFILING_IN_PROCESS_CHILD_PROCESS_SNAPSHOT_CONTROLLER_H_ +#define COMPONENTS_HEAP_PROFILING_IN_PROCESS_CHILD_PROCESS_SNAPSHOT_CONTROLLER_H_ + +#include "components/heap_profiling/in_process/mojom/snapshot_controller.mojom.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" + +namespace heap_profiling { + +// Triggers heap snapshots in the HeapProfilerController of the current child +// process in response to notifications from the HeapProfilerController in the +// browser process. +class ChildProcessSnapshotController final : public mojom::SnapshotController { + public: + // Creates a ChildProcessSnapshotController and binds it to `receiver`. + static void CreateSelfOwnedReceiver( + mojo::PendingReceiver<mojom::SnapshotController> receiver); + + ~ChildProcessSnapshotController() final = default; + + ChildProcessSnapshotController(const ChildProcessSnapshotController&) = + delete; + ChildProcessSnapshotController& operator=( + const ChildProcessSnapshotController&) = delete; + + // SnapshotController: + void TakeSnapshot() final; + + private: + ChildProcessSnapshotController() = default; +}; + +} // namespace heap_profiling + +#endif // COMPONENTS_HEAP_PROFILING_IN_PROCESS_CHILD_PROCESS_SNAPSHOT_CONTROLLER_H_
diff --git a/components/heap_profiling/in_process/heap_profiler_controller.cc b/components/heap_profiling/in_process/heap_profiler_controller.cc index abad719..0abe36d 100644 --- a/components/heap_profiling/in_process/heap_profiler_controller.cc +++ b/components/heap_profiling/in_process/heap_profiler_controller.cc
@@ -6,6 +6,8 @@ #include <cmath> #include <limits> +#include <memory> +#include <optional> #include <string> #include <utility> #include <vector> @@ -18,6 +20,7 @@ #include "base/functional/callback.h" #include "base/functional/callback_helpers.h" #include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" #include "base/metrics/histogram_functions.h" #include "base/notreached.h" #include "base/numerics/clamped_math.h" @@ -32,6 +35,8 @@ #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" +#include "base/types/pass_key.h" +#include "components/heap_profiling/in_process/browser_process_snapshot_controller.h" #include "components/heap_profiling/in_process/heap_profiler_parameters.h" #include "components/heap_profiling/in_process/switches.h" #include "components/metrics/call_stacks/call_stack_profile_builder.h" @@ -162,19 +167,29 @@ } // namespace HeapProfilerController::SnapshotParams::SnapshotParams( - base::TimeDelta mean_interval, + std::optional<base::TimeDelta> mean_interval, bool use_random_interval, scoped_refptr<StoppedFlag> stopped, ProcessType process_type, base::TimeTicks profiler_creation_time, base::OnceClosure on_first_snapshot_callback) - : mean_interval(mean_interval), + : mean_interval(std::move(mean_interval)), use_random_interval(use_random_interval), stopped(std::move(stopped)), process_type(process_type), profiler_creation_time(profiler_creation_time), on_first_snapshot_callback(std::move(on_first_snapshot_callback)) {} +HeapProfilerController::SnapshotParams::SnapshotParams( + scoped_refptr<StoppedFlag> stopped, + ProcessType process_type, + base::TimeTicks profiler_creation_time, + base::OnceClosure on_first_snapshot_callback) + : stopped(std::move(stopped)), + process_type(process_type), + profiler_creation_time(profiler_creation_time), + on_first_snapshot_callback(std::move(on_first_snapshot_callback)) {} + HeapProfilerController::SnapshotParams::~SnapshotParams() = default; HeapProfilerController::SnapshotParams::SnapshotParams(SnapshotParams&& other) = @@ -205,6 +220,13 @@ // key to debug reentry into the profiler. // TODO(crbug.com/40062835): Remove this after diagnosing reentry crashes. base::allocator::dispatcher::ReentryGuard::RecordTLSSlotToCrashKey(); + + if (profiling_enabled_ && process_type_ == ProcessType::kBrowser && + base::FeatureList::IsEnabled(kHeapProfilerCentralControl)) { + browser_process_snapshot_controller_ = + std::make_unique<BrowserProcessSnapshotController>( + snapshot_task_runner_); + } } HeapProfilerController::~HeapProfilerController() { @@ -212,6 +234,13 @@ stopped_->data.Set(); CHECK_EQ(g_instance, this); g_instance = nullptr; + + // BrowserProcessSnapshotController must be deleted on the sequence that its + // WeakPtr's are bound to. + if (browser_process_snapshot_controller_) { + snapshot_task_runner_->DeleteSoon( + FROM_HERE, std::move(browser_process_snapshot_controller_)); + } } bool HeapProfilerController::StartIfEnabled() { @@ -237,11 +266,25 @@ profiler_params.sampling_rate_bytes); } base::SamplingHeapProfiler::Get()->Start(); + + if (process_type_ != ProcessType::kBrowser && + base::FeatureList::IsEnabled(kHeapProfilerCentralControl)) { + // ChildProcessSnapshotController will trigger snapshots. + return true; + } + DCHECK(profiler_params.collection_interval.is_positive()); SnapshotParams params( profiler_params.collection_interval, /*use_random_interval=*/!suppress_randomness_for_testing_, stopped_, process_type_, creation_time_, std::move(on_first_snapshot_callback_)); + if (base::FeatureList::IsEnabled(kHeapProfilerCentralControl)) { + params.trigger_child_process_snapshot_closure = base::BindRepeating( + &BrowserProcessSnapshotController::TakeSnapshotsOnSnapshotSequence, + browser_process_snapshot_controller_->GetWeakPtr()); + } else { + params.trigger_child_process_snapshot_closure = base::DoNothing(); + } snapshot_task_runner_->PostTask( FROM_HERE, base::BindOnce(&HeapProfilerController::ScheduleNextSnapshot, std::move(params))); @@ -261,18 +304,64 @@ void HeapProfilerController::AppendCommandLineSwitchForChildProcess( base::CommandLine* command_line, - metrics::CallStackProfileParams::Process child_process_type) const { + metrics::CallStackProfileParams::Process child_process_type, + int child_process_id) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CHECK_EQ(process_type_, ProcessType::kBrowser); - CHECK_NE(child_process_type, ProcessType::kBrowser); if (!base::FeatureList::IsEnabled(kHeapProfilerCentralControl)) { return; } - // Only enable subprocess profiling when the browser process is being - // profiled. - if (profiling_enabled_ && + // If profiling is disabled in the browser process, pass a null + // BrowserProcessSnapshotController to disable it in the child process too. + BrowserProcessSnapshotController* snapshot_controller = nullptr; + if (profiling_enabled_) { + CHECK(browser_process_snapshot_controller_); + snapshot_controller = browser_process_snapshot_controller_.get(); + } + AppendCommandLineSwitchInternal(command_line, child_process_type, + child_process_id, snapshot_controller); +} + +BrowserProcessSnapshotController* +HeapProfilerController::GetBrowserProcessSnapshotController() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return browser_process_snapshot_controller_.get(); +} + +void HeapProfilerController::TakeSnapshotInChildProcess( + base::PassKey<ChildProcessSnapshotController>) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + CHECK_NE(process_type_, ProcessType::kBrowser); + CHECK(base::FeatureList::IsEnabled(kHeapProfilerCentralControl)); + snapshot_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&TakeSnapshot, + SnapshotParams(stopped_, process_type_, creation_time_, + std::move(on_first_snapshot_callback_)))); +} + +// static +void HeapProfilerController::AppendCommandLineSwitchForTesting( + base::CommandLine* command_line, + metrics::CallStackProfileParams::Process child_process_type, + int child_process_id, + BrowserProcessSnapshotController* snapshot_controller) { + AppendCommandLineSwitchInternal(command_line, child_process_type, + child_process_id, snapshot_controller); +} + +// static +void HeapProfilerController::AppendCommandLineSwitchInternal( + base::CommandLine* command_line, + metrics::CallStackProfileParams::Process child_process_type, + int child_process_id, + BrowserProcessSnapshotController* snapshot_controller) { + CHECK_NE(child_process_type, ProcessType::kBrowser); + CHECK(base::FeatureList::IsEnabled(kHeapProfilerCentralControl)); + if (snapshot_controller && GetHeapProfilerParametersForProcess(child_process_type).is_supported) { command_line->AppendSwitch(switches::kSubprocessHeapProfiling); + snapshot_controller->BindRemoteForChildProcess(child_process_id); return; } // Record that HeapProfilerController had a chance to update the child's @@ -284,9 +373,11 @@ // static void HeapProfilerController::ScheduleNextSnapshot(SnapshotParams params) { + // Should only be called for repeating snapshots. + CHECK(params.mean_interval.has_value()); base::TimeDelta interval = params.use_random_interval - ? RandomInterval(params.mean_interval) - : params.mean_interval; + ? RandomInterval(params.mean_interval.value()) + : params.mean_interval.value(); base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask( FROM_HERE, base::BindOnce(&HeapProfilerController::TakeSnapshot, std::move(params)), @@ -304,9 +395,16 @@ RetrieveAndSendSnapshot( params.process_type, base::TimeTicks::Now() - params.profiler_creation_time); - // Callback should be left as null for next snapshot. - CHECK(params.on_first_snapshot_callback.is_null()); - ScheduleNextSnapshot(std::move(params)); + if (params.process_type == ProcessType::kBrowser) { + // Also trigger snapshots in child processes. + params.trigger_child_process_snapshot_closure.Run(); + } + + if (params.mean_interval.has_value()) { + // Callback should be left as null for next snapshot. + CHECK(params.on_first_snapshot_callback.is_null()); + ScheduleNextSnapshot(std::move(params)); + } } // static
diff --git a/components/heap_profiling/in_process/heap_profiler_controller.h b/components/heap_profiling/in_process/heap_profiler_controller.h index aa8c0d4..a471b92 100644 --- a/components/heap_profiling/in_process/heap_profiler_controller.h +++ b/components/heap_profiling/in_process/heap_profiler_controller.h
@@ -5,6 +5,9 @@ #ifndef COMPONENTS_HEAP_PROFILING_IN_PROCESS_HEAP_PROFILER_CONTROLLER_H_ #define COMPONENTS_HEAP_PROFILING_IN_PROCESS_HEAP_PROFILER_CONTROLLER_H_ +#include <memory> +#include <optional> + #include "base/feature_list.h" #include "base/functional/callback.h" #include "base/memory/ref_counted.h" @@ -13,6 +16,7 @@ #include "base/synchronization/atomic_flag.h" #include "base/task/sequenced_task_runner.h" #include "base/time/time.h" +#include "base/types/pass_key.h" #include "components/metrics/call_stacks/call_stack_profile_params.h" #include "components/version_info/channel.h" @@ -31,6 +35,9 @@ // from the browser process. BASE_DECLARE_FEATURE(kHeapProfilerCentralControl); +class BrowserProcessSnapshotController; +class ChildProcessSnapshotController; + // HeapProfilerController controls collection of sampled heap allocation // snapshots for the current process. class HeapProfilerController { @@ -76,7 +83,26 @@ // `child_process_type` to `command_line`. void AppendCommandLineSwitchForChildProcess( base::CommandLine* command_line, - metrics::CallStackProfileParams::Process child_process_type) const; + metrics::CallStackProfileParams::Process child_process_type, + int child_process_id) const; + + // Returns the BrowserProcessSnapshotController or nullptr if none exists (if + // heap profiling is disabled or kHeapProfilerCentralControl is disabled). + BrowserProcessSnapshotController* GetBrowserProcessSnapshotController() const; + + // Triggers an immediate snapshot in a child process. In the browser process, + // snapshots are scheduled internally by the HeapProfilerController. + void TakeSnapshotInChildProcess( + base::PassKey<ChildProcessSnapshotController>); + + // Allows unit tests to call AppendCommandLineSwitchForChildProcess without + // creating a HeapProfilerController. `snapshot_controller` should be null if + // profiling is disabled in the browser process. + static void AppendCommandLineSwitchForTesting( + base::CommandLine* command_line, + metrics::CallStackProfileParams::Process child_process_type, + int child_process_id, + BrowserProcessSnapshotController* snapshot_controller); private: using ProcessType = metrics::CallStackProfileParams::Process; @@ -86,12 +112,20 @@ // move-only so that it can be safely passed between threads to the static // snapshot functions. struct SnapshotParams { - SnapshotParams(base::TimeDelta mean_interval, + // Creates params for a repeating snapshot. + SnapshotParams(std::optional<base::TimeDelta> mean_interval, bool use_random_interval, scoped_refptr<StoppedFlag> stopped, ProcessType process_type, base::TimeTicks profiler_creation_time, base::OnceClosure on_first_snapshot_callback); + + // Creates params for a single snapshot. + SnapshotParams(scoped_refptr<StoppedFlag> stopped, + ProcessType process_type, + base::TimeTicks profiler_creation_time, + base::OnceClosure on_first_snapshot_callback); + ~SnapshotParams(); // Move-only. @@ -100,8 +134,9 @@ SnapshotParams(SnapshotParams&& other); SnapshotParams& operator=(SnapshotParams&& other); - // Mean interval until the next snapshot. - base::TimeDelta mean_interval; + // Mean interval until the next snapshot or nullopt if the params are used + // only for a single snapshot. + std::optional<base::TimeDelta> mean_interval; // If true, generate a random time centered around `mean_interval`. // Otherwise use `mean_interval` exactly. @@ -119,8 +154,20 @@ // A callback to invoke for the first snapshot. Will be null for the // following snapshots. For testing. base::OnceClosure on_first_snapshot_callback; + + // A callback to trigger snapshots in all known child processes. Only used + // in the browser process when kHeapProfilerCentralControl is enabled. + base::RepeatingClosure trigger_child_process_snapshot_closure; }; + // Shared implementation of AppendCommandLineSwitchForChildProcess and + // AppendCommandLineSwitchForTesting. + static void AppendCommandLineSwitchInternal( + base::CommandLine* command_line, + ProcessType child_process_type, + int child_process_id, + BrowserProcessSnapshotController* snapshot_controller); + // Schedules the next call to TakeSnapshot. static void ScheduleNextSnapshot(SnapshotParams params); @@ -155,6 +202,13 @@ scoped_refptr<base::SequencedTaskRunner> snapshot_task_runner_ GUARDED_BY_CONTEXT(sequence_checker_); + // A controller that notifies the HeapProfilerController in child processes to + // take a snapshot at the same time as this HeapProfilerController. Created + // only in the browser process when kHeapProfilerCentralControl is enabled. + std::unique_ptr<BrowserProcessSnapshotController> + browser_process_snapshot_controller_ + GUARDED_BY_CONTEXT(sequence_checker_); + // If true, the sampling interval and time between samples won't have any // random variance added so that tests are repeatable. bool suppress_randomness_for_testing_ GUARDED_BY_CONTEXT(sequence_checker_) =
diff --git a/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc b/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc index c8663e5..be59fd37 100644 --- a/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc +++ b/components/heap_profiling/in_process/heap_profiler_controller_unittest.cc
@@ -13,30 +13,41 @@ #include "base/allocator/dispatcher/notification_data.h" #include "base/allocator/dispatcher/subsystem.h" #include "base/barrier_closure.h" +#include "base/command_line.h" #include "base/containers/contains.h" #include "base/containers/enum_set.h" #include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/functional/callback_helpers.h" #include "base/json/json_writer.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/field_trial_params.h" #include "base/notreached.h" #include "base/sampling_heap_profiler/poisson_allocation_sampler.h" #include "base/sampling_heap_profiler/sampling_heap_profiler.h" +#include "base/task/sequenced_task_runner.h" #include "base/test/bind.h" #include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_command_line.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" +#include "base/test/test_timeouts.h" #include "base/time/time.h" #include "base/values.h" #include "build/build_config.h" +#include "components/heap_profiling/in_process/browser_process_snapshot_controller.h" +#include "components/heap_profiling/in_process/child_process_snapshot_controller.h" #include "components/heap_profiling/in_process/heap_profiler_parameters.h" +#include "components/heap_profiling/in_process/mojom/snapshot_controller.mojom.h" +#include "components/heap_profiling/in_process/switches.h" #include "components/metrics/call_stacks/call_stack_profile_builder.h" #include "components/metrics/call_stacks/call_stack_profile_params.h" #include "components/metrics/public/mojom/call_stack_profile_collector.mojom.h" #include "components/version_info/channel.h" #include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/metrics_proto/execution_context.pb.h" #include "third_party/metrics_proto/sampled_profile.pb.h" @@ -113,8 +124,13 @@ // will also run the given `profile_collector_callback`. If not, // collector_callback() returns a callback that's expected not to run, and the // given `profile_collector_callback` is ignored. + // + // If `use_other_process_callback` is true, the test will also fake a snapshot + // in another process, so other_process_callback() will return a callback to + // invoke for this. ScopedCallbacks(bool expect_take_snapshot, bool expect_sampled_profile, + bool use_other_process_callback, ProfileCollectorCallback profile_collector_callback, base::OnceClosure quit_closure) { size_t num_callbacks = 0; @@ -124,6 +140,11 @@ if (expect_sampled_profile) { num_callbacks += 1; } + if (use_other_process_callback) { + // The test should invoke other_process_snapshot_callback() to simulate a + // snapshot in another process. + num_callbacks += 1; + } barrier_closure_ = base::BarrierClosure(num_callbacks, std::move(quit_closure)); @@ -142,6 +163,12 @@ FAIL() << "ProfileCollectorCallback called unexpectedly."; }); } + if (use_other_process_callback) { + other_process_callback_ = barrier_closure_; + } else { + other_process_callback_ = base::BindOnce( + [] { FAIL() << "Other process callback invoked unexpectedly."; }); + } } ~ScopedCallbacks() = default; @@ -160,10 +187,20 @@ return std::move(collector_callback_); } + base::OnceClosure other_process_callback() { + return std::move(other_process_callback_); + } + private: base::RepeatingClosure barrier_closure_; base::OnceClosure first_snapshot_callback_; ProfileCollectorCallback collector_callback_; + base::OnceClosure other_process_callback_; +}; + +class MockSnapshotController : public mojom::SnapshotController { + public: + MOCK_METHOD(void, TakeSnapshot, (), (override)); }; // Configurations of the HeapProfiler* features to test. @@ -182,6 +219,8 @@ ChannelParams nonstable; // Whether HeapProfilerIncludeZero is enabled. bool include_zero_feature_enabled = true; + // Whether HeapProfilerCentralControl is enabled. + bool central_control_feature_enabled = false; base::FieldTrialParams ToFieldTrialParams() const; @@ -254,6 +293,10 @@ enabled_features.push_back( FeatureRefAndParams(kHeapProfilerIncludeZero, {})); } + if (central_control_feature_enabled) { + enabled_features.push_back( + FeatureRefAndParams(kHeapProfilerCentralControl, {})); + } return enabled_features; } @@ -265,6 +308,9 @@ if (!include_zero_feature_enabled) { disabled_features.push_back(FeatureRef(kHeapProfilerIncludeZero)); } + if (!central_control_feature_enabled) { + disabled_features.push_back(FeatureRef(kHeapProfilerCentralControl)); + } return disabled_features; } @@ -283,7 +329,8 @@ os << "nonstable/browser:" << params.stable.expect_browser_sample << ","; os << "nonstable/child:" << params.stable.expect_child_sample; os << "},"; - os << "include_zero:" << params.include_zero_feature_enabled; + os << "include_zero:" << params.include_zero_feature_enabled << ","; + os << "central_control:" << params.central_control_feature_enabled; os << "}"; return os; } @@ -406,10 +453,13 @@ std::move(remote)); } - ScopedCallbacks CreateScopedCallbacks(bool expect_take_snapshot, - bool expect_sampled_profile) { + ScopedCallbacks CreateScopedCallbacks( + bool expect_take_snapshot, + bool expect_sampled_profile, + bool use_other_process_callback = false) { return ScopedCallbacks( expect_take_snapshot, expect_sampled_profile, + use_other_process_callback, base::BindRepeating(&HeapProfilerControllerTest::RecordSampleReceived, base::Unretained(this)), task_environment_.QuitClosure()); @@ -620,16 +670,38 @@ { .supported_processes = {ProcessType::kBrowser}, .stable = {.expect_browser_sample = true, .expect_child_sample = false}, + .central_control_feature_enabled = false, + }, + { + .supported_processes = {ProcessType::kBrowser}, + .stable = {.expect_browser_sample = true, .expect_child_sample = false}, + .central_control_feature_enabled = true, }, // Enabled in child process only. { .supported_processes = {ProcessType::kUtility}, .stable = {.expect_browser_sample = false, .expect_child_sample = true}, + .central_control_feature_enabled = false, + }, + { + // Central control only samples child processes when the browser process + // is sampled, so no samples are expected even though sampling is + // supported in the child process. + .supported_processes = {ProcessType::kUtility}, + .stable = {.expect_browser_sample = false, + .expect_child_sample = false}, + .central_control_feature_enabled = true, }, // Enabled in parent and child processes. { .supported_processes = {ProcessType::kBrowser, ProcessType::kUtility}, .stable = {.expect_browser_sample = true, .expect_child_sample = true}, + .central_control_feature_enabled = false, + }, + { + .supported_processes = {ProcessType::kBrowser, ProcessType::kUtility}, + .stable = {.expect_browser_sample = true, .expect_child_sample = true}, + .central_control_feature_enabled = true, }, }; @@ -644,7 +716,17 @@ base::Contains(GetParam().supported_processes, ProcessType::kBrowser); ScopedCallbacks callbacks = CreateScopedCallbacks( /*expect_take_snapshot=*/profiling_enabled, - GetParam().stable.expect_browser_sample); + GetParam().stable.expect_browser_sample, + /*use_other_process_callback=*/ + GetParam().central_control_feature_enabled && + GetParam().stable.expect_child_sample); + + // Mock the child end of the SnapshotController mojo pipe. (Only used when + // central control is enabled.) + MockSnapshotController mock_child_snapshot_controller; + mojo::Receiver<mojom::SnapshotController> mock_receiver( + &mock_child_snapshot_controller); + StartHeapProfiling(version_info::Channel::STABLE, ProcessType::kBrowser, profiling_enabled, callbacks.first_snapshot_callback(), callbacks.collector_callback()); @@ -652,6 +734,45 @@ "HeapProfiling.InProcess.Enabled.Browser", profiling_enabled, 1); histogram_tester_.ExpectUniqueSample("HeapProfiling.InProcess.Enabled", profiling_enabled, 1); + + constexpr int kTestChildProcessId = 1; + if (profiling_enabled && GetParam().central_control_feature_enabled) { + ASSERT_TRUE(controller_->GetBrowserProcessSnapshotController()); + + // This callback should be invoked from + // AppendCommandLineSwitchForChildProcess to bind the child end of the mojo + // pipe. + controller_->GetBrowserProcessSnapshotController() + ->SetBindRemoteForChildProcessCallback(base::BindLambdaForTesting( + [&](int child_process_id, + mojo::PendingReceiver<mojom::SnapshotController> receiver) { + EXPECT_EQ(child_process_id, kTestChildProcessId); + mock_receiver.Bind(std::move(receiver)); + })); + } else { + EXPECT_FALSE(controller_->GetBrowserProcessSnapshotController()); + } + + if (GetParam().central_control_feature_enabled) { + // Simulate a child process launch. If profiling is enabled in both browser + // and child processes, this will bind the browser end of the mojo pipe to + // the BrowserProcessSnapshotController and use the above callback to bind + // the child end to `mock_child_snapshot_controller`. + base::CommandLine child_command_line(base::CommandLine::NO_PROGRAM); + controller_->AppendCommandLineSwitchForChildProcess( + &child_command_line, ProcessType::kUtility, kTestChildProcessId); + + if (GetParam().stable.expect_child_sample) { + EXPECT_CALL(mock_child_snapshot_controller, TakeSnapshot()).WillOnce([&] { + // Record that BrowserProcessSnapshotController triggered a fake + // snapshot in the child process. + callbacks.other_process_callback().Run(); + }); + } else { + EXPECT_CALL(mock_child_snapshot_controller, TakeSnapshot()).Times(0); + } + } + AddOneSampleAndWait(); EXPECT_EQ(sample_received_, GetParam().stable.expect_browser_sample); } @@ -659,9 +780,58 @@ TEST_P(HeapProfilerControllerProcessTest, ChildProcess) { const bool profiling_enabled = base::Contains(GetParam().supported_processes, ProcessType::kUtility); + // If HeapProfilingCentralControl is enabled, TakeSnapshot() is only called in + // the child process when the browser process triggers it. Otherwise it's + // always called when profiling is enabled for the process. ScopedCallbacks callbacks = CreateScopedCallbacks( - /*expect_take_snapshot=*/profiling_enabled, - GetParam().stable.expect_child_sample); + /*expect_take_snapshot=*/GetParam().central_control_feature_enabled + ? GetParam().stable.expect_child_sample + : profiling_enabled, + /*expect_sampled_profile=*/GetParam().stable.expect_child_sample, + /*use_other_process_callback=*/ + GetParam().central_control_feature_enabled); + + // Simulate the browser side of child process launching. + base::test::ScopedCommandLine scoped_command_line; + if (GetParam().central_control_feature_enabled) { + constexpr int kTestChildProcessId = 1; + + // Create a snapshot controller to hold the browser end of the mojo pipe. + auto snapshot_task_runner = base::SequencedTaskRunner::GetCurrentDefault(); + auto fake_browser_snapshot_controller = + std::make_unique<BrowserProcessSnapshotController>( + snapshot_task_runner); + + // This callback should be invoked from AppendCommandLineSwitchForTesting to + // bind the child end of the mojo pipe. + fake_browser_snapshot_controller->SetBindRemoteForChildProcessCallback( + base::BindLambdaForTesting( + [&](int child_process_id, + mojo::PendingReceiver<mojom::SnapshotController> receiver) { + EXPECT_EQ(child_process_id, kTestChildProcessId); + ChildProcessSnapshotController::CreateSelfOwnedReceiver( + std::move(receiver)); + })); + + HeapProfilerController::AppendCommandLineSwitchForTesting( + scoped_command_line.GetProcessCommandLine(), ProcessType::kUtility, + kTestChildProcessId, fake_browser_snapshot_controller.get()); + + // Simulate the browser process taking a sample after a delay. If profiling + // isn't enabled in the browser process, just quit waiting after the delay. + base::OnceClosure browser_snapshot_callback = base::DoNothing(); + if (base::Contains(GetParam().supported_processes, ProcessType::kBrowser)) { + browser_snapshot_callback = base::BindOnce( + &BrowserProcessSnapshotController::TakeSnapshotsOnSnapshotSequence, + std::move(fake_browser_snapshot_controller)); + } + snapshot_task_runner->PostDelayedTask( + FROM_HERE, + std::move(browser_snapshot_callback) + .Then(callbacks.other_process_callback()), + TestTimeouts::action_timeout()); + } + StartHeapProfiling(version_info::Channel::STABLE, ProcessType::kUtility, profiling_enabled, callbacks.first_snapshot_callback(), callbacks.collector_callback()); @@ -669,6 +839,12 @@ "HeapProfiling.InProcess.Enabled.Utility", profiling_enabled, 1); histogram_tester_.ExpectUniqueSample("HeapProfiling.InProcess.Enabled", profiling_enabled, 1); + + // The child process HeapProfilerController should never have a + // BrowserProcessSnapshotController. (`fake_browser_snapshot_controller` + // simulates the browser side of the connection.) + EXPECT_EQ(controller_->GetBrowserProcessSnapshotController(), nullptr); + AddOneSampleAndWait(); EXPECT_EQ(sample_received_, GetParam().stable.expect_child_sample); }
diff --git a/components/heap_profiling/in_process/mojom/OWNERS b/components/heap_profiling/in_process/mojom/OWNERS new file mode 100644 index 0000000..61b5e28 --- /dev/null +++ b/components/heap_profiling/in_process/mojom/OWNERS
@@ -0,0 +1,2 @@ +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS \ No newline at end of file
diff --git a/components/heap_profiling/in_process/mojom/snapshot_controller.mojom b/components/heap_profiling/in_process/mojom/snapshot_controller.mojom new file mode 100644 index 0000000..7cb4005 --- /dev/null +++ b/components/heap_profiling/in_process/mojom/snapshot_controller.mojom
@@ -0,0 +1,14 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +module heap_profiling.mojom; + +// Lets HeapProfilerController in the browser process schedule heap snapshots in +// child processes. +interface SnapshotController { + // Triggers a heap snapshot. The snapshot data will be passed back to the + // browser process using metrics::ChildCallStackProfileCollector, for + // inclusion in the next metrics upload via CallStackProfileMetricsProvider. + TakeSnapshot(); +};
diff --git a/components/ip_protection/BUILD.gn b/components/ip_protection/BUILD.gn index d610e514..83ed623 100644 --- a/components/ip_protection/BUILD.gn +++ b/components/ip_protection/BUILD.gn
@@ -7,6 +7,8 @@ source_set("ip_protection") { sources = [ + "ip_protection_config_provider_helper.cc", + "ip_protection_config_provider_helper.h", "ip_protection_proxy_config_retriever.cc", "ip_protection_proxy_config_retriever.h", ] @@ -15,6 +17,11 @@ "//base", "//build:branding_buildflags", "//google_apis:google_apis", + "//mojo/public/cpp/bindings:bindings", + "//net:net", + "//net/third_party/quiche:blind_sign_auth", + "//services/network/public/cpp:cpp", + "//services/network/public/mojom:mojom", ] }
diff --git a/components/ip_protection/ip_protection_config_provider_helper.cc b/components/ip_protection/ip_protection_config_provider_helper.cc new file mode 100644 index 0000000..a1a2bbb7 --- /dev/null +++ b/components/ip_protection/ip_protection_config_provider_helper.cc
@@ -0,0 +1,93 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/ip_protection/ip_protection_config_provider_helper.h" + +#include "net/base/proxy_chain.h" +#include "net/base/proxy_server.h" +#include "net/base/proxy_string_util.h" +#include "net/third_party/quiche/src/quiche/blind_sign_auth/blind_sign_auth.h" +#include "net/third_party/quiche/src/quiche/blind_sign_auth/proto/blind_sign_auth_options.pb.h" + +// static +std::vector<net::ProxyChain> +IpProtectionConfigProviderHelper::GetProxyListFromProxyConfigResponse( + ip_protection::GetProxyConfigResponse response) { + // Shortcut to create a ProxyServer with SCHEME_HTTPS from a string in the + // proto. + auto add_server = [](std::vector<net::ProxyServer>& proxies, + std::string host) { + net::ProxyServer proxy_server = net::ProxySchemeHostAndPortToProxyServer( + net::ProxyServer::SCHEME_HTTPS, host); + if (!proxy_server.is_valid()) { + return false; + } + proxies.push_back(proxy_server); + return true; + }; + + std::vector<net::ProxyChain> proxy_list; + for (const auto& proxy_chain : response.proxy_chain()) { + std::vector<net::ProxyServer> proxies; + bool ok = true; + bool overridden = false; + if (const std::string a_override = + net::features::kIpPrivacyProxyAHostnameOverride.Get(); + a_override != "") { + overridden = true; + ok = ok && add_server(proxies, a_override); + } else { + ok = ok && add_server(proxies, proxy_chain.proxy_a()); + } + if (const std::string b_override = + net::features::kIpPrivacyProxyBHostnameOverride.Get(); + ok && b_override != "") { + overridden = true; + ok = ok && add_server(proxies, b_override); + } else { + ok = ok && add_server(proxies, proxy_chain.proxy_b()); + } + + // Create a new ProxyChain if the proxies were all valid. + if (ok) { + // If the `chain_id` is out of range or local features overrode the + // chain, use the proxy chain anyway, but with the default `chain_id`. + // This allows adding new IDs on the server side without breaking older + // browsers. + int chain_id = proxy_chain.chain_id(); + if (overridden || chain_id < 0 || + chain_id > net::ProxyChain::kMaxIpProtectionChainId) { + chain_id = net::ProxyChain::kDefaultIpProtectionChainId; + } + proxy_list.push_back( + net::ProxyChain::ForIpProtection(std::move(proxies), chain_id)); + } + } + + VLOG(2) << "IPATP::GetProxyList got proxy list of length " + << proxy_list.size(); + + return proxy_list; +} + +// static +network::mojom::BlindSignedAuthTokenPtr +IpProtectionConfigProviderHelper::CreateBlindSignedAuthToken( + quiche::BlindSignToken bsa_token) { + base::Time expiration = + base::Time::FromTimeT(absl::ToTimeT(bsa_token.expiration)); + + // What the network service will receive as a "token" is the fully constructed + // authorization header value. + std::string token_header_value = ""; + privacy::ppn::PrivacyPassTokenData privacy_pass_token_data; + if (privacy_pass_token_data.ParseFromString(bsa_token.token)) { + token_header_value = + base::StrCat({"PrivateToken token=\"", privacy_pass_token_data.token(), + "\", extensions=\"", + privacy_pass_token_data.encoded_extensions(), "\""}); + } + return network::mojom::BlindSignedAuthToken::New( + std::move(token_header_value), expiration); +}
diff --git a/components/ip_protection/ip_protection_config_provider_helper.h b/components/ip_protection/ip_protection_config_provider_helper.h new file mode 100644 index 0000000..ab87880 --- /dev/null +++ b/components/ip_protection/ip_protection_config_provider_helper.h
@@ -0,0 +1,91 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_IP_PROTECTION_IP_PROTECTION_CONFIG_PROVIDER_HELPER_H_ +#define COMPONENTS_IP_PROTECTION_IP_PROTECTION_CONFIG_PROVIDER_HELPER_H_ + +#include <memory> +#include <optional> +#include <string> + +#include "base/functional/callback.h" +#include "base/time/time.h" +#include "components/ip_protection/get_proxy_config.pb.h" +#include "services/network/public/mojom/network_context.mojom.h" + +namespace quiche { +class BlindSignAuth; +struct BlindSignToken; +} // namespace quiche + +// The result of a fetch of tokens from the IP Protection auth token server. +// +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. Keep this in sync with +// IpProtectionTokenBatchRequestResult in enums.xml. +enum class IpProtectionTryGetAuthTokensResult { + // The request was successful and resulted in new tokens. + kSuccess = 0, + // No primary account is set. + kFailedNoAccount = 1, + // Chrome determined the primary account is not eligible. + kFailedNotEligible = 2, + // There was a failure fetching an OAuth token for the primary account. + // Deprecated in favor of `kFailedOAuthToken{Transient,Persistent}`. + kFailedOAuthTokenDeprecated = 3, + // There was a failure in BSA with the given status code. + kFailedBSA400 = 4, + kFailedBSA401 = 5, + kFailedBSA403 = 6, + + // Any other issue calling BSA. + kFailedBSAOther = 7, + + // There was a transient failure fetching an OAuth token for the primary + // account. + kFailedOAuthTokenTransient = 8, + // There was a persistent failure fetching an OAuth token for the primary + // account. + kFailedOAuthTokenPersistent = 9, + + // The attempt to request tokens failed because IP Protection was disabled by + // the user. + kFailedDisabledByUser = 10, + + kMaxValue = kFailedDisabledByUser, +}; + +// Contains static variables and methods for IpProtectionConfigProviders. +// +// It is the implementation's job to actually get the IP protection tokens on +// demand for the network service. This interface defines methods and variables +// commonly used for config providers that implement it. Derived classes must +// contain instances of `IpProtectionProxyConfigRetriever`, +// `quiche::BlindSignAuth`, and some implementation of +// `quiche::BlindSignMessageInterface`. +class IpProtectionConfigProviderHelper { + public: + virtual ~IpProtectionConfigProviderHelper() = default; + + // Creates a list of ProxyChains from GetProxyConfigResponse. + static std::vector<net::ProxyChain> GetProxyListFromProxyConfigResponse( + ip_protection::GetProxyConfigResponse response); + + // Creates a blind-signed auth token by converting token fetched using the + // `quiche::BlindSignAuth` library to a + // `network::mojom::BlindSignedAuthToken`. + static network::mojom::BlindSignedAuthTokenPtr CreateBlindSignedAuthToken( + quiche::BlindSignToken bsa_token); + + // Service types used for GetProxyConfigRequest. + static constexpr char kChromeIpBlinding[] = "chromeipblinding"; + static constexpr char kWebViewIpBlinding[] = "webviewipblinding"; + + // Base time deltas for calculating `try_again_after`. + static constexpr base::TimeDelta kNotEligibleBackoff = base::Days(1); + static constexpr base::TimeDelta kTransientBackoff = base::Seconds(5); + static constexpr base::TimeDelta kBugBackoff = base::Minutes(10); +}; + +#endif // COMPONENTS_IP_PROTECTION_IP_PROTECTION_CONFIG_PROVIDER_HELPER_H_
diff --git a/components/omnibox/browser/history_url_provider.cc b/components/omnibox/browser/history_url_provider.cc index a809feba..17c5356 100644 --- a/components/omnibox/browser/history_url_provider.cc +++ b/components/omnibox/browser/history_url_provider.cc
@@ -438,9 +438,16 @@ // Do some fixup on the user input before matching against it, so we provide // good results for local file paths, input with spaces, etc. - const FixupReturn fixup_return(FixupUserInput(autocomplete_input)); + FixupReturn fixup_return(FixupUserInput(autocomplete_input)); if (!fixup_return.first) return; + // Inputs like '@hist' shouldn't match 'history.com' because users are more + // likely to be looking for a starer pack scope than a URL. However, + // URLs containing '@' before the host, such as '@history.com', area valid + // URLs and still needs to run autocompletion. + if (autocomplete_input.text().starts_with('@')) + fixup_return.second = u"@" + fixup_return.second; + url::Parsed parts; url_formatter::SegmentURL(fixup_return.second, &parts); AutocompleteInput fixed_up_input(autocomplete_input);
diff --git a/components/omnibox/browser/history_url_provider_unittest.cc b/components/omnibox/browser/history_url_provider_unittest.cc index 52fc380..b904bea 100644 --- a/components/omnibox/browser/history_url_provider_unittest.cc +++ b/components/omnibox/browser/history_url_provider_unittest.cc
@@ -1466,15 +1466,19 @@ ASSERT_GT(matches_.size(), 0u); EXPECT_EQ(matches_[0].destination_url, GURL("http://www.google.com/")); - // Test result for "@history" and "@history google" while NOT in keyword mode, - // we should get a result for history.com and not for google since we're - // searching for the whole input text including "@history". - matches_ = test(u"@history"); - ASSERT_GT(matches_.size(), 0u); - EXPECT_EQ(matches_[0].destination_url, GURL("https://history.com/")); - + // Test result for "@history", "@history.c", and "@history google" while NOT + // in keyword mode, we should not get results for history.com or google since + // we're searching for the whole input text including "@". + EXPECT_TRUE(test(u"@history").empty()); + EXPECT_TRUE(test(u"@history.c").empty()); EXPECT_TRUE(test(u"@history google").empty()); + // Test results for "@history.co"; we should see a URL what you type + // suggestion because that's a valid URL. + matches_ = test(u"@history.co"); + ASSERT_GT(matches_.size(), 0u); + EXPECT_EQ(matches_[0].destination_url, GURL("http://history.co/")); + // Turn on keyword mode, test result again, we should get back the result for // google.com since we're searching only for the user text after the keyword. matches_ = test(u"@history google", true);
diff --git a/components/page_load_metrics/browser/BUILD.gn b/components/page_load_metrics/browser/BUILD.gn index 955b77c..e2776f22 100644 --- a/components/page_load_metrics/browser/BUILD.gn +++ b/components/page_load_metrics/browser/BUILD.gn
@@ -6,6 +6,8 @@ source_set("browser") { sources = [ + "features.cc", + "features.h", "layout_shift_normalization.cc", "layout_shift_normalization.h", "metrics_lifecycle_observer.cc", @@ -79,6 +81,7 @@ "responsiveness_metrics_normalization.h", ] deps = [ + "//base", "//build:chromeos_buildflags", "//components/keyed_service/content:content", "//components/keyed_service/core:core",
diff --git a/components/page_load_metrics/browser/features.cc b/components/page_load_metrics/browser/features.cc new file mode 100644 index 0000000..7e01565 --- /dev/null +++ b/components/page_load_metrics/browser/features.cc
@@ -0,0 +1,15 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/page_load_metrics/browser/features.h" + +#include "base/feature_list.h" + +namespace page_load_metrics::features { +// Whether to send continuous events - kTouchMove, kGestureScrollUpdate, +// kGesturePinchUpdate, to page load tracker observers. +BASE_FEATURE(kSendContinuousInputEventsToObservers, + "SendContinuousInputEventsToObservers", + base::FEATURE_DISABLED_BY_DEFAULT); +} // namespace page_load_metrics::features
diff --git a/components/page_load_metrics/browser/features.h b/components/page_load_metrics/browser/features.h new file mode 100644 index 0000000..aa700070 --- /dev/null +++ b/components/page_load_metrics/browser/features.h
@@ -0,0 +1,14 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_PAGE_LOAD_METRICS_BROWSER_FEATURES_H_ +#define COMPONENTS_PAGE_LOAD_METRICS_BROWSER_FEATURES_H_ + +#include "base/feature_list.h" + +namespace page_load_metrics::features { +BASE_DECLARE_FEATURE(kSendContinuousInputEventsToObservers); +} // namespace page_load_metrics::features + +#endif // COMPONENTS_PAGE_LOAD_METRICS_BROWSER_FEATURES_H_
diff --git a/components/page_load_metrics/browser/page_load_tracker.cc b/components/page_load_metrics/browser/page_load_tracker.cc index b005845..a173a5f 100644 --- a/components/page_load_metrics/browser/page_load_tracker.cc +++ b/components/page_load_metrics/browser/page_load_tracker.cc
@@ -11,12 +11,14 @@ #include <utility> #include "base/check_op.h" +#include "base/feature_list.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/notreached.h" #include "base/strings/stringprintf.h" #include "base/time/default_tick_clock.h" #include "base/trace_event/trace_event.h" +#include "components/page_load_metrics/browser/features.h" #include "components/page_load_metrics/browser/page_load_metrics_embedder_interface.h" #include "components/page_load_metrics/browser/page_load_metrics_forward_observer.h" #include "components/page_load_metrics/browser/page_load_metrics_memory_tracker.h" @@ -33,6 +35,7 @@ #include "page_load_metrics_observer_delegate.h" #include "services/metrics/public/cpp/ukm_recorder.h" #include "services/metrics/public/cpp/ukm_source_id.h" +#include "third_party/blink/public/mojom/input/input_event.mojom-shared.h" namespace page_load_metrics { @@ -752,6 +755,20 @@ } void PageLoadTracker::OnInputEvent(const blink::WebInputEvent& event) { + static const bool do_not_send_continuous_events = + !base::FeatureList::IsEnabled( + features::kSendContinuousInputEventsToObservers); + using Type = blink::mojom::EventType; + const bool is_continuous_event = + (event.GetType() == Type::kTouchMove || + event.GetType() == Type::kGestureScrollUpdate || + event.GetType() == Type::kGesturePinchUpdate); + if (do_not_send_continuous_events && is_continuous_event) { + return; + } + + // TODO(b/328601354): Confirm continuous input events are not required for + // page load tracker observers and rename the API to reflect the same. for (const auto& observer : observers_) { observer->OnUserInput(event, metrics_update_dispatcher_.timing()); }
diff --git a/components/password_manager/core/browser/mock_password_form_manager_for_ui.h b/components/password_manager/core/browser/mock_password_form_manager_for_ui.h index cc508847..da46544 100644 --- a/components/password_manager/core/browser/mock_password_form_manager_for_ui.h +++ b/components/password_manager/core/browser/mock_password_form_manager_for_ui.h
@@ -68,6 +68,10 @@ MOCK_METHOD(void, OnPasswordsRevealed, (), (override)); MOCK_METHOD(void, MoveCredentialsToAccountStore, (), (override)); MOCK_METHOD(void, BlockMovingCredentialsToAccountStore, (), (override)); + MOCK_METHOD(PasswordForm::Store, + GetPasswordStoreForSaving, + (const PasswordForm& password_form), + (const override)); }; } // namespace password_manager
diff --git a/components/password_manager/core/browser/password_form_manager.cc b/components/password_manager/core/browser/password_form_manager.cc index 91e7b71..3086463 100644 --- a/components/password_manager/core/browser/password_form_manager.cc +++ b/components/password_manager/core/browser/password_form_manager.cc
@@ -619,6 +619,11 @@ GaiaIdHash::FromGaiaId(gaia_id)); } +PasswordForm::Store PasswordFormManager::GetPasswordStoreForSaving( + const PasswordForm& password_form) const { + return password_save_manager_->GetPasswordStoreForSaving(password_form); +} + bool PasswordFormManager::IsNewLogin() const { return password_save_manager_->IsNewLogin(); }
diff --git a/components/password_manager/core/browser/password_form_manager.h b/components/password_manager/core/browser/password_form_manager.h index 117c6fb..94465c0f 100644 --- a/components/password_manager/core/browser/password_form_manager.h +++ b/components/password_manager/core/browser/password_form_manager.h
@@ -188,6 +188,8 @@ void OnPasswordsRevealed() override; void MoveCredentialsToAccountStore() override; void BlockMovingCredentialsToAccountStore() override; + PasswordForm::Store GetPasswordStoreForSaving( + const PasswordForm& password_form) const override; bool IsNewLogin() const; FormFetcher* GetFormFetcher();
diff --git a/components/password_manager/core/browser/password_form_manager_for_ui.h b/components/password_manager/core/browser/password_form_manager_for_ui.h index 15fa1b8..bb7eadd 100644 --- a/components/password_manager/core/browser/password_form_manager_for_ui.h +++ b/components/password_manager/core/browser/password_form_manager_for_ui.h
@@ -115,6 +115,13 @@ // GetPendingCredentials() to the account store of the currently signed in // user. virtual void BlockMovingCredentialsToAccountStore() = 0; + + // Returns the password store type into which the form is going to be saved or + // updated. It might be that the credential is updated in both stores; in this + // case the result will be the enum value with both bits set (the account and + // the profile store bits). + virtual PasswordForm::Store GetPasswordStoreForSaving( + const PasswordForm& password_form) const = 0; }; } // namespace password_manager
diff --git a/components/password_manager/core/browser/password_generation_manager.cc b/components/password_manager/core/browser/password_generation_manager.cc index 8c6b0367..0c1d356 100644 --- a/components/password_manager/core/browser/password_generation_manager.cc +++ b/components/password_manager/core/browser/password_generation_manager.cc
@@ -43,6 +43,7 @@ matches, const std::vector<raw_ptr<const PasswordForm, VectorExperimental>>& federated, + PasswordForm::Store store_for_saving, base::RepeatingCallback<void(bool, const PasswordForm&)> bubble_interaction); ~PasswordDataForUI() override = default; @@ -74,12 +75,15 @@ void OnPasswordsRevealed() override; void MoveCredentialsToAccountStore() override; void BlockMovingCredentialsToAccountStore() override; + PasswordForm::Store GetPasswordStoreForSaving( + const PasswordForm& password_form) const override; private: PasswordForm pending_form_; std::vector<PasswordForm> matches_; const std::vector<PasswordForm> federated_matches_; const std::vector<PasswordForm> non_federated_matches_; + PasswordForm::Store store_for_saving_; // Observer that waits for bubble interaction. // The first parameter is true iff the bubble was accepted. @@ -93,10 +97,12 @@ const std::vector<raw_ptr<const PasswordForm, VectorExperimental>>& matches, const std::vector<raw_ptr<const PasswordForm, VectorExperimental>>& federated, + PasswordForm::Store store_for_saving, base::RepeatingCallback<void(bool, const PasswordForm&)> bubble_interaction) : pending_form_(std::move(pending_form)), federated_matches_(DeepCopyVector(federated)), non_federated_matches_(DeepCopyVector(matches)), + store_for_saving_(store_for_saving), bubble_interaction_cb_(std::move(bubble_interaction)) { for (const PasswordForm& form : non_federated_matches_) matches_.push_back(form); @@ -197,6 +203,11 @@ void PasswordDataForUI::BlockMovingCredentialsToAccountStore() {} +PasswordForm::Store PasswordDataForUI::GetPasswordStoreForSaving( + const PasswordForm& password_form) const { + return store_for_saving_; +} + // Returns a form from |matches| that causes a name conflict with |generated|. const PasswordForm* FindUsernameConflict( const PasswordForm& generated, @@ -338,6 +349,7 @@ non_federated_matches, const std::vector<raw_ptr<const PasswordForm, VectorExperimental>>& federated_matches, + PasswordForm::Store store_for_saving, base::WeakPtr<PasswordManagerDriver> driver) { // Clear the username value if there are already saved credentials with // the same username in order to prevent overwriting. @@ -348,6 +360,7 @@ if (conflict) { auto bubble_launcher = std::make_unique<PasswordDataForUI>( std::move(generated), non_federated_matches, federated_matches, + store_for_saving, base::BindRepeating(&PasswordGenerationManager::OnPresaveBubbleResult, weak_factory_.GetWeakPtr(), std::move(driver))); client_->PromptUserToSaveOrUpdatePassword(std::move(bubble_launcher),
diff --git a/components/password_manager/core/browser/password_generation_manager.h b/components/password_manager/core/browser/password_generation_manager.h index c333170..262f47c6 100644 --- a/components/password_manager/core/browser/password_generation_manager.h +++ b/components/password_manager/core/browser/password_generation_manager.h
@@ -58,7 +58,8 @@ // synchronously passed to |driver|. Otherwise, the UI on the client is // invoked to ask for overwrite permission. There is one corner case that is // still not covered. The user had the current password saved with empty - // username. + // username. |store_for_saving| indicates into which store the generated + // password will be pre-saved. // - The change password form has no username. // - The user generates a password and sees the bubble with an empty username. // - The user clicks 'Update'. @@ -69,6 +70,7 @@ non_federated_matches, const std::vector<raw_ptr<const PasswordForm, VectorExperimental>>& federated_matches, + PasswordForm::Store store_for_saving, base::WeakPtr<PasswordManagerDriver> driver); // Called when generated password is accepted or changed by user.
diff --git a/components/password_manager/core/browser/password_generation_manager_unittest.cc b/components/password_manager/core/browser/password_generation_manager_unittest.cc index 49f1d90..46cd18a0 100644 --- a/components/password_manager/core/browser/password_generation_manager_unittest.cc +++ b/components/password_manager/core/browser/password_generation_manager_unittest.cc
@@ -176,7 +176,8 @@ .WillOnce(testing::Return(true)); manager().GeneratedPasswordAccepted( std::move(generated), fetcher.GetNonFederatedMatches(), - fetcher.GetFederatedMatches(), std::move(driver)); + fetcher.GetFederatedMatches(), PasswordForm::Store::kAccountStore, + std::move(driver)); return client_.MoveForm(); } @@ -199,7 +200,8 @@ EXPECT_CALL(driver, GeneratedPasswordAccepted(generated.password_value)); manager().GeneratedPasswordAccepted( std::move(generated), fetcher.GetNonFederatedMatches(), - fetcher.GetFederatedMatches(), driver.AsWeakPtr()); + fetcher.GetFederatedMatches(), PasswordForm::Store::kAccountStore, + driver.AsWeakPtr()); EXPECT_FALSE(manager().HasGeneratedPassword()); } @@ -217,7 +219,8 @@ EXPECT_CALL(driver, GeneratedPasswordAccepted(generated.password_value)); manager().GeneratedPasswordAccepted( std::move(generated), fetcher.GetNonFederatedMatches(), - fetcher.GetFederatedMatches(), driver.AsWeakPtr()); + fetcher.GetFederatedMatches(), PasswordForm::Store::kAccountStore, + driver.AsWeakPtr()); EXPECT_FALSE(manager().HasGeneratedPassword()); } @@ -273,6 +276,9 @@ std::unique_ptr<PasswordFormManagerForUI> ui_form = SetUpOverwritingUI(driver.AsWeakPtr()); ASSERT_TRUE(ui_form); + EXPECT_EQ( + PasswordForm::Store::kAccountStore, + ui_form->GetPasswordStoreForSaving(ui_form->GetPendingCredentials())); EXPECT_CALL(driver, GeneratedPasswordAccepted(CreateGenerated().password_value)); ui_form->Save();
diff --git a/components/password_manager/core/browser/password_save_manager.h b/components/password_manager/core/browser/password_save_manager.h index 01a7729..9ba1b271 100644 --- a/components/password_manager/core/browser/password_save_manager.h +++ b/components/password_manager/core/browser/password_save_manager.h
@@ -123,7 +123,7 @@ // case the result will be the enum value with both bits set (the account and // the profile store bits). virtual PasswordForm::Store GetPasswordStoreForSaving( - const PasswordForm& parsed_submitted_form) const = 0; + const PasswordForm& password_form) const = 0; virtual std::unique_ptr<PasswordSaveManager> Clone() = 0; };
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 3e65801c0..aba4ac8 100644 --- a/components/password_manager/core/browser/password_save_manager_impl.cc +++ b/components/password_manager/core/browser/password_save_manager_impl.cc
@@ -487,6 +487,9 @@ std::move(parsed_form), GetRelevantMatchesForGeneration(form_fetcher_->GetNonFederatedMatches()), GetRelevantMatchesForGeneration(form_fetcher_->GetFederatedMatches()), + ShouldStoreGeneratedPasswordsInAccountStore() + ? PasswordForm::Store::kAccountStore + : PasswordForm::Store::kProfileStore, driver); } @@ -993,9 +996,9 @@ } PasswordForm::Store PasswordSaveManagerImpl::GetPasswordStoreForSaving( - const PasswordForm& parsed_submitted_form) const { + const PasswordForm& password_form) const { PendingCredentialsStates states = ComputePendingCredentialsStates( - parsed_submitted_form, form_fetcher_->GetAllRelevantMatches(), + password_form, form_fetcher_->GetAllRelevantMatches(), username_updated_in_bubble_, generation_manager_.get()); return GetPasswordStoreForSavingImpl(states); }
diff --git a/components/password_manager/core/browser/password_save_manager_impl.h b/components/password_manager/core/browser/password_save_manager_impl.h index d29eba3..0c95dcb0 100644 --- a/components/password_manager/core/browser/password_save_manager_impl.h +++ b/components/password_manager/core/browser/password_save_manager_impl.h
@@ -107,7 +107,7 @@ void UsernameUpdatedInBubble() override; PasswordForm::Store GetPasswordStoreForSaving( - const PasswordForm& parsed_submitted_form) const override; + const PasswordForm& password_form) const override; std::unique_ptr<PasswordSaveManager> Clone() override;
diff --git a/components/performance_manager/features.cc b/components/performance_manager/features.cc index 2bd701e..4be6b28 100644 --- a/components/performance_manager/features.cc +++ b/components/performance_manager/features.cc
@@ -77,38 +77,33 @@ "PerformanceControlsSidePanel", base::FEATURE_DISABLED_BY_DEFAULT); -BASE_FEATURE(kPerformanceCPUIntervention, - "PerformanceCPUIntervention", +BASE_FEATURE(kPerformanceIntervention, + "PerformanceIntervention", base::FEATURE_DISABLED_BY_DEFAULT); const base::FeatureParam<base::TimeDelta> kCPUTimeOverThreshold{ - &kPerformanceCPUIntervention, "cpu_time_over_threshold", base::Seconds(60)}; + &kPerformanceIntervention, "cpu_time_over_threshold", base::Seconds(60)}; const base::FeatureParam<base::TimeDelta> kCPUSampleFrequency{ - &kPerformanceCPUIntervention, "cpu_sample_frequency", base::Seconds(15)}; + &kPerformanceIntervention, "cpu_sample_frequency", base::Seconds(15)}; const base::FeatureParam<int> kCPUDegradedHealthPercentageThreshold{ - &kPerformanceCPUIntervention, "cpu_degraded_percent_threshold", 50}; + &kPerformanceIntervention, "cpu_degraded_percent_threshold", 50}; const base::FeatureParam<int> kCPUUnhealthyPercentageThreshold{ - &kPerformanceCPUIntervention, "cpu_unhealthy_percent_threshold", 75}; + &kPerformanceIntervention, "cpu_unhealthy_percent_threshold", 75}; const base::FeatureParam<int> kCPUMaxActionableTabs{ - &kPerformanceCPUIntervention, "cpu_max_actionable_tabs", 4}; + &kPerformanceIntervention, "cpu_max_actionable_tabs", 4}; const base::FeatureParam<int> kMinimumActionableTabCPUPercentage{ - &kPerformanceCPUIntervention, "minimum_actionable_tab_cpu", 10}; - -BASE_FEATURE(kPerformanceMemoryIntervention, - "PerformanceMemoryIntervention", - base::FEATURE_DISABLED_BY_DEFAULT); + &kPerformanceIntervention, "minimum_actionable_tab_cpu", 10}; const base::FeatureParam<base::TimeDelta> kMemoryTimeOverThreshold{ - &kPerformanceMemoryIntervention, "memory_time_over_threshold", - base::Seconds(60)}; + &kPerformanceIntervention, "memory_time_over_threshold", base::Seconds(60)}; const base::FeatureParam<int> kMemoryFreePercentThreshold{ - &kPerformanceMemoryIntervention, "memory_free_percent_threshold", 10}; + &kPerformanceIntervention, "memory_free_percent_threshold", 10}; const base::FeatureParam<int> kMemoryFreeBytesThreshold{ - &kPerformanceMemoryIntervention, "memory_free_bytes_threshold", + &kPerformanceIntervention, "memory_free_bytes_threshold", 1024 * 1024 * 1024}; #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/components/performance_manager/public/features.h b/components/performance_manager/public/features.h index a63a9780..366dc61 100644 --- a/components/performance_manager/public/features.h +++ b/components/performance_manager/public/features.h
@@ -89,8 +89,8 @@ // configuring performance settings. BASE_DECLARE_FEATURE(kPerformanceControlsSidePanel); -// This enables the CPU performance interventions within the side panel. -BASE_DECLARE_FEATURE(kPerformanceCPUIntervention); +// This enables the performance detection backend and interventions UI. +BASE_DECLARE_FEATURE(kPerformanceIntervention); #if BUILDFLAG(IS_WIN) // Prefetch the main browser DLL when a new node is added to the PM graph @@ -117,9 +117,6 @@ // Minimum percentage to improve CPU health for a tab to be actionable extern const base::FeatureParam<int> kMinimumActionableTabCPUPercentage; -// This enables the Memory performance interventions within the side panel. -BASE_DECLARE_FEATURE(kPerformanceMemoryIntervention); - // This represents the duration that Memory must be over the threshold before // a notification is triggered. extern const base::FeatureParam<base::TimeDelta> kMemoryTimeOverThreshold;
diff --git a/components/permissions/pref_names.cc b/components/permissions/pref_names.cc index 22463348..eea910f9 100644 --- a/components/permissions/pref_names.cc +++ b/components/permissions/pref_names.cc
@@ -53,10 +53,10 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { PermissionActionsHistory::RegisterProfilePrefs(registry); -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) +#if !BUILDFLAG(IS_IOS) registry->RegisterBooleanPref(prefs::kUnusedSitePermissionsRevocationEnabled, true); -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) +#endif // !BUILDFLAG(IS_IOS) } } // namespace permissions
diff --git a/components/plus_addresses/BUILD.gn b/components/plus_addresses/BUILD.gn index c1e02f15..53b5efce 100644 --- a/components/plus_addresses/BUILD.gn +++ b/components/plus_addresses/BUILD.gn
@@ -96,6 +96,7 @@ source_set("unit_tests") { testonly = true sources = [ + "affiliations/plus_address_affiliation_match_helper_unittest.cc", "affiliations/plus_address_affiliation_source_adapter_unittest.cc", "plus_address_http_client_impl_unittest.cc", "plus_address_jit_allocator_unittest.cc",
diff --git a/components/plus_addresses/affiliations/plus_address_affiliation_match_helper.cc b/components/plus_addresses/affiliations/plus_address_affiliation_match_helper.cc index f5ad64f..1d249482 100644 --- a/components/plus_addresses/affiliations/plus_address_affiliation_match_helper.cc +++ b/components/plus_addresses/affiliations/plus_address_affiliation_match_helper.cc
@@ -4,12 +4,20 @@ #include "components/plus_addresses/affiliations/plus_address_affiliation_match_helper.h" +#include <string> +#include <vector> + +#include "base/barrier_callback.h" #include "components/affiliations/core/browser/affiliation_service.h" +#include "components/affiliations/core/browser/affiliation_utils.h" #include "components/plus_addresses/features.h" #include "components/plus_addresses/plus_address_service.h" #include "components/plus_addresses/plus_address_types.h" namespace plus_addresses { +namespace { +using affiliations::FacetURI; +} // namespace PlusAddressAffiliationMatchHelper::PlusAddressAffiliationMatchHelper( PlusAddressService* plus_address_service, @@ -29,7 +37,64 @@ return; } + FacetURI facet = absl::get<FacetURI>(plus_profile.facet); + // TODO(b/324553908): Include other sources (e.g. credential sharing, grouped + // affiliations). + const int kCallsNumber = 1; + auto barrier_callback = base::BarrierCallback<std::vector<PlusProfile>>( + kCallsNumber, + base::BindOnce(&PlusAddressAffiliationMatchHelper::MergeResults, + weak_factory_.GetWeakPtr(), std::move(result_callback))); + + GetPSLExtensions(base::BindOnce( + &PlusAddressAffiliationMatchHelper::ProcessExactAndPSLMatches, + weak_factory_.GetWeakPtr(), barrier_callback, facet)); +} + +void PlusAddressAffiliationMatchHelper::GetPSLExtensions( + PSLExtensionCallback callback) { + if (psl_extensions_.has_value()) { + std::move(callback).Run(psl_extensions_.value()); + return; + } + + psl_extensions_callbacks_.push_back(std::move(callback)); + if (psl_extensions_callbacks_.size() > 1) { + // If there is more than one request in the queue, wait until the + // OnPSLExtensionsReceived is triggered. + return; + } + + affiliation_service_->GetPSLExtensions(base::BindOnce( + &PlusAddressAffiliationMatchHelper::OnPSLExtensionsReceived, + weak_factory_.GetWeakPtr())); +} + +void PlusAddressAffiliationMatchHelper::OnPSLExtensionsReceived( + std::vector<std::string> psl_extensions) { + psl_extensions_ = base::flat_set<std::string>( + std::make_move_iterator(psl_extensions.begin()), + std::make_move_iterator(psl_extensions.end())); + + for (auto& callback : std::exchange(psl_extensions_callbacks_, {})) { + std::move(callback).Run(psl_extensions_.value()); + } +} + +void PlusAddressAffiliationMatchHelper::ProcessExactAndPSLMatches( + base::RepeatingCallback<void(std::vector<PlusProfile>)> + matches_received_callback, + const FacetURI& facet, + const base::flat_set<std::string>& psl_extensions) { // TODO(b/324553908): Complete. + std::move(matches_received_callback).Run({}); +} + +void PlusAddressAffiliationMatchHelper::MergeResults( + AffiliatedPlusProfilesCallback result_callback, + std::vector<std::vector<PlusProfile>> results) { + // TODO(b/324553908): Complete. + std::move(result_callback).Run({}); } } // namespace plus_addresses
diff --git a/components/plus_addresses/affiliations/plus_address_affiliation_match_helper.h b/components/plus_addresses/affiliations/plus_address_affiliation_match_helper.h index ee99cb8..765db81 100644 --- a/components/plus_addresses/affiliations/plus_address_affiliation_match_helper.h +++ b/components/plus_addresses/affiliations/plus_address_affiliation_match_helper.h
@@ -5,14 +5,17 @@ #ifndef COMPONENTS_PLUS_ADDRESSES_AFFILIATIONS_PLUS_ADDRESS_AFFILIATION_MATCH_HELPER_H_ #define COMPONENTS_PLUS_ADDRESSES_AFFILIATIONS_PLUS_ADDRESS_AFFILIATION_MATCH_HELPER_H_ +#include <string> #include <vector> +#include "base/containers/flat_set.h" #include "base/functional/callback_forward.h" #include "base/memory/raw_ref.h" #include "components/plus_addresses/plus_address_types.h" namespace affiliations { class AffiliationService; +class FacetURI; } namespace plus_addresses { @@ -29,6 +32,9 @@ // Callback to return the list of affiliated plus profiles. using AffiliatedPlusProfilesCallback = base::OnceCallback<void(std::vector<PlusProfile>)>; + // Callback to return that set of PSL extensions. + using PSLExtensionCallback = + base::OnceCallback<void(const base::flat_set<std::string>&)>; // The `plus_address_service` and `affiliation_service` must outlive `this`. // Both arguments must be non-NULL. @@ -44,13 +50,37 @@ // Returns the complete list of plus profiles, including the specified // `plus_profile`, that belong to the same affiliation group based on their // facet value. + // TODO(b/324553908): Update to query by facet. void GetAffiliatedPlusProfiles( const PlusProfile& plus_profile, AffiliatedPlusProfilesCallback result_callback); + // Requests and caches the list of PSL extensions. + void GetPSLExtensions(PSLExtensionCallback callback); + private: + void OnPSLExtensionsReceived(std::vector<std::string> psl_extensions); + + // Queries the plus address cache for entries with facets that satisfy either + // exact or PSL matching against the provided `facet`. + void ProcessExactAndPSLMatches( + base::RepeatingCallback<void(std::vector<PlusProfile>)> + matches_received_callback, + const affiliations::FacetURI& facet, + const base::flat_set<std::string>& psl_extensions); + + // Merges results from various affiliation types, prioritizes them, eliminates + // duplicates, and delivers a ranked list of affiliated plus profiles. + void MergeResults(AffiliatedPlusProfilesCallback result_callback, + std::vector<std::vector<PlusProfile>> results); + + std::optional<base::flat_set<std::string>> psl_extensions_; + std::vector<PSLExtensionCallback> psl_extensions_callbacks_; + const raw_ref<PlusAddressService> plus_address_service_; const raw_ref<affiliations::AffiliationService> affiliation_service_; + + base::WeakPtrFactory<PlusAddressAffiliationMatchHelper> weak_factory_{this}; }; } // namespace plus_addresses
diff --git a/components/plus_addresses/affiliations/plus_address_affiliation_match_helper_unittest.cc b/components/plus_addresses/affiliations/plus_address_affiliation_match_helper_unittest.cc new file mode 100644 index 0000000..9b08c74 --- /dev/null +++ b/components/plus_addresses/affiliations/plus_address_affiliation_match_helper_unittest.cc
@@ -0,0 +1,107 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/plus_addresses/affiliations/plus_address_affiliation_match_helper.h" + +#include "base/test/gmock_callback_support.h" +#include "base/test/gmock_move_support.h" +#include "base/test/mock_callback.h" +#include "components/affiliations/core/browser/affiliation_service.h" +#include "components/affiliations/core/browser/affiliation_utils.h" +#include "components/affiliations/core/browser/mock_affiliation_service.h" +#include "components/plus_addresses/mock_plus_address_http_client.h" +#include "components/plus_addresses/plus_address_service.h" +#include "components/plus_addresses/plus_address_types.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace plus_addresses { +namespace { +using ::affiliations::FacetURI; +using ::affiliations::MockAffiliationService; +using ::base::test::RunOnceCallback; +using ::testing::UnorderedElementsAreArray; +} // namespace + +class PlusAddressAffiliationMatchHelperTest : public testing::Test { + public: + PlusAddressAffiliationMatchHelperTest() { + plus_address_service_ = std::make_unique<PlusAddressService>( + /*identity_manager=*/nullptr, + /*pref_service=*/nullptr, + std::make_unique<testing::NiceMock<MockPlusAddressHttpClient>>(), + /*webdata_service=*/nullptr); + + match_helper_ = std::make_unique<PlusAddressAffiliationMatchHelper>( + plus_address_service(), mock_affiliation_service()); + } + + MockAffiliationService* mock_affiliation_service() { + return &mock_affiliation_service_; + } + + PlusAddressService* plus_address_service() { + return plus_address_service_.get(); + } + + PlusAddressAffiliationMatchHelper* match_helper() { + return match_helper_.get(); + } + + private: + testing::StrictMock<MockAffiliationService> mock_affiliation_service_; + std::unique_ptr<PlusAddressService> plus_address_service_; + std::unique_ptr<PlusAddressAffiliationMatchHelper> match_helper_; +}; + +// Verifies that PSL extensions are cached within the match helper and a single +// affiliation service call is issued. +TEST_F(PlusAddressAffiliationMatchHelperTest, GetPSLExtensionsCachesResult) { + std::vector<std::string> pls_extensions = {"a.com", "b.com"}; + EXPECT_CALL(*mock_affiliation_service(), GetPSLExtensions) + .WillOnce(RunOnceCallback<0>(pls_extensions)); + + base::MockCallback<PlusAddressAffiliationMatchHelper::PSLExtensionCallback> + callback; + EXPECT_CALL(callback, Run(UnorderedElementsAreArray(pls_extensions))); + + match_helper()->GetPSLExtensions(callback.Get()); + + // Now affiliation service isn't called. + EXPECT_CALL(*mock_affiliation_service(), GetPSLExtensions).Times(0); + EXPECT_CALL(callback, Run(UnorderedElementsAreArray(pls_extensions))); + match_helper()->GetPSLExtensions(callback.Get()); +} + +// Verifies that the match helper correctly handles simultaneous fetch requests +// for PSL extensions. +TEST_F(PlusAddressAffiliationMatchHelperTest, + GetPSLExtensionsHandlesSimultaneousCalls) { + std::vector<std::string> pls_extensions = {"a.com", "b.com"}; + base::OnceCallback<void(std::vector<std::string>)> first_callback; + + base::MockCallback<PlusAddressAffiliationMatchHelper::PSLExtensionCallback> + callback1; + base::MockCallback<PlusAddressAffiliationMatchHelper::PSLExtensionCallback> + callback2; + { + testing::InSequence in_sequence; + EXPECT_CALL(*mock_affiliation_service(), GetPSLExtensions) + // Store the callback and wait until all the GetPSLExtensions calls are + // made. + .WillOnce(MoveArg<0>(&first_callback)); + + EXPECT_CALL(callback1, Run(UnorderedElementsAreArray(pls_extensions))); + EXPECT_CALL(callback2, Run(UnorderedElementsAreArray(pls_extensions))); + } + + match_helper()->GetPSLExtensions(callback1.Get()); + match_helper()->GetPSLExtensions(callback2.Get()); + + // After all `GetPSLExtensions` are made, resolve the affiliation service + // callback and make sure all the calls are resolved. + std::move(first_callback).Run(pls_extensions); +} + +} // namespace plus_addresses
diff --git a/components/policy/core/common/cloud/test/policy_builder.cc b/components/policy/core/common/cloud/test/policy_builder.cc index 28a44f3..24862caa 100644 --- a/components/policy/core/common/cloud/test/policy_builder.cc +++ b/components/policy/core/common/cloud/test/policy_builder.cc
@@ -267,15 +267,18 @@ } // namespace // Constants used as dummy data for filling the PolicyData protobuf. +// LINT.IfChange +const char PolicyBuilder::kFakeGaiaId[] = "0000111111"; +const char PolicyBuilder::kFakeUsername[] = "username@example.com"; +// LINT.ThenChange(/chrome/test/base/fake_gaia_mixin.cc) + const char PolicyBuilder::kFakeDeviceId[] = "device-id"; const char PolicyBuilder::kFakeDomain[] = "example.com"; -const char PolicyBuilder::kFakeGaiaId[] = "gaia-id"; const char PolicyBuilder::kFakeMachineName[] = "machine-name"; const char PolicyBuilder::kFakePolicyType[] = "policy type"; const int PolicyBuilder::kFakePublicKeyVersion = 17; const int64_t PolicyBuilder::kFakeTimestamp = 365LL * 24 * 60 * 60 * 1000; const char PolicyBuilder::kFakeToken[] = "token"; -const char PolicyBuilder::kFakeUsername[] = "username@example.com"; const char PolicyBuilder::kFakeServiceAccountIdentity[] = "robot4test@g.com"; PolicyBuilder::PolicyBuilder() {
diff --git a/components/policy/core/common/cloud/user_info_fetcher.cc b/components/policy/core/common/cloud/user_info_fetcher.cc index 4f7fe49..bcd328a2 100644 --- a/components/policy/core/common/cloud/user_info_fetcher.cc +++ b/components/policy/core/common/cloud/user_info_fetcher.cc
@@ -6,6 +6,7 @@ #include "base/functional/bind.h" #include "base/json/json_reader.h" +#include "base/metrics/histogram_functions.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "components/policy/core/common/policy_logger.h" @@ -43,6 +44,14 @@ return url; } +void RecordFetchStatus(policy::EnterpriseUserInfoFetchStatus status) { + base::UmaHistogramEnumeration("Enterprise.UserInfoFetch.Status", status); +} + +void RecordHttpErrorCode(int code) { + base::UmaHistogramSparse("Enterprise.UserInfoFetch.HttpErrorCode", code); +} + } // namespace namespace policy { @@ -106,11 +115,13 @@ GoogleServiceAuthError error = GoogleServiceAuthError::AuthErrorNone(); if (url_loader->NetError() != net::OK) { + RecordFetchStatus(EnterpriseUserInfoFetchStatus::kFailedWithNetworkError); if (url_loader->ResponseInfo() && url_loader->ResponseInfo()->headers) { int response_code = url_loader->ResponseInfo()->headers->response_code(); DLOG_POLICY(WARNING, POLICY_AUTH) << "UserInfo request failed with HTTP code: " << response_code; error = GoogleServiceAuthError(GoogleServiceAuthError::CONNECTION_FAILED); + RecordHttpErrorCode(response_code); } else { DLOG_POLICY(WARNING, POLICY_AUTH) << "UserInfo request failed"; error = @@ -130,9 +141,15 @@ std::optional<base::Value> parsed_value = base::JSONReader::Read(*unparsed_data); if (parsed_value && parsed_value->is_dict()) { + RecordFetchStatus(EnterpriseUserInfoFetchStatus::kSuccess); delegate_->OnGetUserInfoSuccess(parsed_value->GetDict()); } else { - NOTREACHED() << "Could not parse userinfo response from server"; + EnterpriseUserInfoFetchStatus status = + parsed_value ? EnterpriseUserInfoFetchStatus::kResponseIsNotDict + : EnterpriseUserInfoFetchStatus::kCantParseJsonInResponse; + RecordFetchStatus(status); + DLOG_POLICY(WARNING, POLICY_AUTH) + << "Could not parse userinfo response from server: " << *unparsed_data; delegate_->OnGetUserInfoFailure(GoogleServiceAuthError( GoogleServiceAuthError::CONNECTION_FAILED)); }
diff --git a/components/policy/core/common/cloud/user_info_fetcher.h b/components/policy/core/common/cloud/user_info_fetcher.h index ddf20446..76c6a1d 100644 --- a/components/policy/core/common/cloud/user_info_fetcher.h +++ b/components/policy/core/common/cloud/user_info_fetcher.h
@@ -22,6 +22,14 @@ namespace policy { +enum class EnterpriseUserInfoFetchStatus { + kSuccess, + kFailedWithNetworkError, + kCantParseJsonInResponse, + kResponseIsNotDict, + kMaxValue = kResponseIsNotDict +}; + // Class that makes a UserInfo request, parses the response, and notifies // a provided Delegate when the request is complete. class POLICY_EXPORT UserInfoFetcher {
diff --git a/components/policy/core/common/cloud/user_info_fetcher_unittest.cc b/components/policy/core/common/cloud/user_info_fetcher_unittest.cc index ea4106e..b3dd1da 100644 --- a/components/policy/core/common/cloud/user_info_fetcher_unittest.cc +++ b/components/policy/core/common/cloud/user_info_fetcher_unittest.cc
@@ -4,6 +4,7 @@ #include "components/policy/core/common/cloud/user_info_fetcher.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/task_environment.h" #include "base/values.h" #include "google_apis/gaia/google_service_auth_error.h" @@ -54,6 +55,8 @@ }; TEST_F(UserInfoFetcherTest, FailedFetch) { + base::HistogramTester histogram_tester; + MockUserInfoFetcherDelegate delegate; UserInfoFetcher fetcher( &delegate, @@ -66,6 +69,12 @@ EXPECT_TRUE(loader_factory_.SimulateResponseForPendingRequest( kUserInfoUrl, std::string(), net::HTTP_INTERNAL_SERVER_ERROR)); task_env_.RunUntilIdle(); + + histogram_tester.ExpectUniqueSample( + "Enterprise.UserInfoFetch.Status", + EnterpriseUserInfoFetchStatus::kFailedWithNetworkError, 1); + histogram_tester.ExpectUniqueSample("Enterprise.UserInfoFetch.HttpErrorCode", + 500, 1); } TEST_F(UserInfoFetcherTest, SuccessfulFetch) { @@ -90,6 +99,48 @@ kUserInfoUrl, kUserInfoResponse)); } +TEST_F(UserInfoFetcherTest, FetchResponseNotParsableToJSON) { + base::HistogramTester histogram_tester; + + MockUserInfoFetcherDelegate delegate; + UserInfoFetcher fetcher( + &delegate, + base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( + &loader_factory_)); + fetcher.Start("access_token"); + + // Fake a successful fetch - should result in the data being parsed and + // the values passed off to the success callback. + EXPECT_CALL(delegate, OnGetUserInfoFailure(GoogleServiceAuthError( + GoogleServiceAuthError::CONNECTION_FAILED))); + EXPECT_TRUE(loader_factory_.SimulateResponseForPendingRequest( + kUserInfoUrl, "<content>not json</content>")); + histogram_tester.ExpectUniqueSample( + "Enterprise.UserInfoFetch.Status", + EnterpriseUserInfoFetchStatus::kCantParseJsonInResponse, 1); +} + +TEST_F(UserInfoFetcherTest, FetchResponseNotDict) { + base::HistogramTester histogram_tester; + + MockUserInfoFetcherDelegate delegate; + UserInfoFetcher fetcher( + &delegate, + base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( + &loader_factory_)); + fetcher.Start("access_token"); + + // Fake a successful fetch - should result in the data being parsed and + // the values passed off to the success callback. + EXPECT_CALL(delegate, OnGetUserInfoFailure(GoogleServiceAuthError( + GoogleServiceAuthError::CONNECTION_FAILED))); + EXPECT_TRUE(loader_factory_.SimulateResponseForPendingRequest(kUserInfoUrl, + "[1, 2, 3]")); + histogram_tester.ExpectUniqueSample( + "Enterprise.UserInfoFetch.Status", + EnterpriseUserInfoFetchStatus::kResponseIsNotDict, 1); +} + } // namespace } // namespace policy
diff --git a/components/policy/resources/templates/policy_definitions/Kiosk/DeviceWeeklyScheduledSuspend.yaml b/components/policy/resources/templates/policy_definitions/Kiosk/DeviceWeeklyScheduledSuspend.yaml index e4dffe5..ebdaf9e 100644 --- a/components/policy/resources/templates/policy_definitions/Kiosk/DeviceWeeklyScheduledSuspend.yaml +++ b/components/policy/resources/templates/policy_definitions/Kiosk/DeviceWeeklyScheduledSuspend.yaml
@@ -6,6 +6,7 @@ <ph name="PRODUCT_OS_NAME">$2<ex>Google ChromeOS</ex></ph> devices will use the system timezone to apply these intervals. + Important Note: The schedules set by this policy may not occur as expected if they conflict with other power management settings, such as <ph name="POWER_MANAGEMENT_IDLE_SETTINGS_POLICY_NAME">PowerManagementIdleSettings</ph>. Ensure these settings are configured to allow the scheduled suspend intervals to take effect. device_only: true example_value: - start:
diff --git a/components/saved_tab_groups/saved_tab_group_sync_bridge.cc b/components/saved_tab_groups/saved_tab_group_sync_bridge.cc index ec1ebde9..6bb3e1c 100644 --- a/components/saved_tab_groups/saved_tab_group_sync_bridge.cc +++ b/components/saved_tab_groups/saved_tab_group_sync_bridge.cc
@@ -23,6 +23,7 @@ #include "components/saved_tab_groups/saved_tab_group.h" #include "components/saved_tab_groups/saved_tab_group_model.h" #include "components/saved_tab_groups/saved_tab_group_tab.h" +#include "components/sync/base/deletion_origin.h" #include "components/sync/base/model_type.h" #include "components/sync/model/entity_change.h" #include "components/sync/model/metadata_batch.h" @@ -340,6 +341,7 @@ return; change_processor()->Delete(guid.AsLowercaseString(), + syncer::DeletionOrigin::Unspecified(), write_batch->GetMetadataChangeList()); }
diff --git a/components/search_engines/search_engines_switches.cc b/components/search_engines/search_engines_switches.cc index 3c3b368..771fbf85 100644 --- a/components/search_engines/search_engines_switches.cc +++ b/components/search_engines/search_engines_switches.cc
@@ -83,4 +83,14 @@ /*default_value=*/10}; #endif +#if BUILDFLAG(IS_ANDROID) +BASE_FEATURE(kSearchEngineChoice, + "SearchEngineChoice", + base::FEATURE_DISABLED_BY_DEFAULT); + +BASE_FEATURE(kSearchEnginePromoDialogRewrite, + "SearchEnginePromoDialogRewrite", + base::FEATURE_DISABLED_BY_DEFAULT); +#endif + } // namespace switches
diff --git a/components/search_engines/search_engines_switches.h b/components/search_engines/search_engines_switches.h index 8f7a0360..d1f67252c 100644 --- a/components/search_engines/search_engines_switches.h +++ b/components/search_engines/search_engines_switches.h
@@ -82,6 +82,16 @@ extern const base::FeatureParam<int> kSearchEngineChoiceMaximumSkipCount; #endif +#if BUILDFLAG(IS_ANDROID) +// Enables the search engine choice feature for existing users. +// TODO(b/316859558): Not used for shipping purposes, remove this feature. +COMPONENT_EXPORT(SEARCH_ENGINES_SWITCHES) +BASE_DECLARE_FEATURE(kSearchEngineChoice); + +// Rewrites DefaultSearchEnginePromoDialog into MVC pattern. +COMPONENT_EXPORT(SEARCH_ENGINES_SWITCHES) +BASE_DECLARE_FEATURE(kSearchEnginePromoDialogRewrite); +#endif } // namespace switches #endif // COMPONENTS_SEARCH_ENGINES_SEARCH_ENGINES_SWITCHES_H_
diff --git a/components/segmentation_platform/public/features.cc b/components/segmentation_platform/public/features.cc index fb41e5c..2d76a43 100644 --- a/components/segmentation_platform/public/features.cc +++ b/components/segmentation_platform/public/features.cc
@@ -69,6 +69,10 @@ "ContextualPageActions", base::FEATURE_ENABLED_BY_DEFAULT); +BASE_FEATURE(kContextualPageActionPriceTracking, + "ContextualPageActionPriceTracking", + base::FEATURE_ENABLED_BY_DEFAULT); + BASE_FEATURE(kContextualPageActionReaderMode, "ContextualPageActionReaderMode", base::FEATURE_ENABLED_BY_DEFAULT);
diff --git a/components/segmentation_platform/public/features.h b/components/segmentation_platform/public/features.h index d0f958a..8447a81c 100644 --- a/components/segmentation_platform/public/features.h +++ b/components/segmentation_platform/public/features.h
@@ -47,6 +47,9 @@ // Feature flag for device switcher segment. BASE_DECLARE_FEATURE(kSegmentationPlatformDeviceSwitcher); +// Feature flag for enabling price tracking action feature. +BASE_DECLARE_FEATURE(kContextualPageActionPriceTracking); + // Feature flag for enabling reader mode action feature. BASE_DECLARE_FEATURE(kContextualPageActionReaderMode);
diff --git a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.cc b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.cc index e649643..ac71813 100644 --- a/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.cc +++ b/components/signin/internal/identity_manager/profile_oauth2_token_service_delegate.cc
@@ -70,6 +70,10 @@ case SourceForRefreshTokenOperation:: kAccountReconcilor_RevokeTokensNotInCookies: return "AccountReconcilor::RevokeTokensNotInCookies"; + case SourceForRefreshTokenOperation:: + kDiceResponseHandler_PasswordPromoSignin: + return "DiceResponseHandler::Signin from sign in promo after password " + "save"; } }
diff --git a/components/signin/public/base/signin_metrics.h b/components/signin/public/base/signin_metrics.h index 3eda371..f11fbbb8 100644 --- a/components/signin/public/base/signin_metrics.h +++ b/components/signin/public/base/signin_metrics.h
@@ -450,8 +450,9 @@ kLogoutTabHelper_PrimaryPageChanged = 19, kForceSigninReauthWithDifferentAccount = 20, kAccountReconcilor_RevokeTokensNotInCookies = 21, + kDiceResponseHandler_PasswordPromoSignin = 22, - kMaxValue = kAccountReconcilor_RevokeTokensNotInCookies, + kMaxValue = kDiceResponseHandler_PasswordPromoSignin, }; // Different types of reporting. This is used as a histogram suffix.
diff --git a/components/signin/public/base/signin_switches.cc b/components/signin/public/base/signin_switches.cc index 38183150..d3ccb6a 100644 --- a/components/signin/public/base/signin_switches.cc +++ b/components/signin/public/base/signin_switches.cc
@@ -5,7 +5,6 @@ #include "components/signin/public/base/signin_switches.h" #include "base/feature_list.h" -#include "base/metrics/field_trial_params.h" #include "components/prefs/pref_service.h" #include "components/signin/public/base/signin_pref_names.h" @@ -114,18 +113,6 @@ base::FEATURE_DISABLED_BY_DEFAULT); #endif -#if BUILDFLAG(IS_ANDROID) -// Enables the search engine choice feature for existing users. -// TODO(b/316859558): Not used for shipping purposes, remove this feature. -BASE_FEATURE(kSearchEngineChoice, - "SearchEngineChoice", - base::FEATURE_DISABLED_BY_DEFAULT); -// Rewrites DefaultSearchEnginePromoDialog into MVC pattern. -BASE_FEATURE(kSearchEnginePromoDialogRewrite, - "SearchEnginePromoDialogRewrite", - base::FEATURE_DISABLED_BY_DEFAULT); -#endif - BASE_FEATURE(kExplicitBrowserSigninUIOnDesktop, "ExplicitBrowserSigninUIOnDesktop", base::FEATURE_DISABLED_BY_DEFAULT); @@ -196,29 +183,6 @@ } // namespace switches -#if !BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) -// Enables the new style, "For You" First Run Experience -BASE_FEATURE(kForYouFre, "ForYouFre", base::FEATURE_ENABLED_BY_DEFAULT); - -#if BUILDFLAG(ENABLE_DICE_SUPPORT) -// Feature that indicates that we should put the client in a study group -// (provided through `kForYouFreStudyGroup`) to be able to look at metrics in -// the long term. Does not affect the client's behavior by itself, instead this -// is done through the `kForYouFre` feature. -BASE_FEATURE(kForYouFreSyntheticTrialRegistration, - "ForYouFreSyntheticTrialRegistration", - base::FEATURE_DISABLED_BY_DEFAULT); - -// String that refers to the study group in which this install was enrolled. -// Used to implement the sticky experiment tracking. If the value is an empty -// string, we don't register the client. -const base::FeatureParam<std::string> kForYouFreStudyGroup{ - &kForYouFreSyntheticTrialRegistration, /*name=*/"group_name", - /*default_value=*/""}; -#endif // BUILDFLAG(ENABLE_DICE_SUPPORT) -#endif // !BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_ANDROID) && - // !BUILDFLAG(IS_IOS) - #if BUILDFLAG(IS_CHROMEOS_ASH) // Enables the generation of pseudo-stable per-user per-device device // identifiers. This identifier can be reset by the user by powerwashing the
diff --git a/components/signin/public/base/signin_switches.h b/components/signin/public/base/signin_switches.h index a7de1e1..96f012e 100644 --- a/components/signin/public/base/signin_switches.h +++ b/components/signin/public/base/signin_switches.h
@@ -98,13 +98,6 @@ BASE_DECLARE_FEATURE(kRestoreSignedInAccountAndSettingsFromBackup); #endif -#if BUILDFLAG(IS_ANDROID) -COMPONENT_EXPORT(SIGNIN_SWITCHES) -BASE_DECLARE_FEATURE(kSearchEngineChoice); -COMPONENT_EXPORT(SIGNIN_SWITCHES) -BASE_DECLARE_FEATURE(kSearchEnginePromoDialogRewrite); -#endif - // Used for the launch of the UNO model on Desktop Phase 0. COMPONENT_EXPORT(SIGNIN_SWITCHES) BASE_DECLARE_FEATURE(kExplicitBrowserSigninUIOnDesktop); @@ -157,20 +150,6 @@ // TODO(crbug.com/337879458): Move switches below into the switches namespace. -#if !BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS) -COMPONENT_EXPORT(SIGNIN_SWITCHES) -BASE_DECLARE_FEATURE(kForYouFre); - -#if BUILDFLAG(ENABLE_DICE_SUPPORT) -COMPONENT_EXPORT(SIGNIN_SWITCHES) -BASE_DECLARE_FEATURE(kForYouFreSyntheticTrialRegistration); - -COMPONENT_EXPORT(SIGNIN_SWITCHES) -extern const base::FeatureParam<std::string> kForYouFreStudyGroup; -#endif // BUILDFLAG(ENABLE_DICE_SUPPORT) -#endif // !BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_ANDROID) && - // !BUILDFLAG(IS_IOS) - #if BUILDFLAG(IS_CHROMEOS_ASH) COMPONENT_EXPORT(SIGNIN_SWITCHES) BASE_DECLARE_FEATURE(kStableDeviceId);
diff --git a/components/supervised_user/core/browser/supervised_user_pref_store.cc b/components/supervised_user/core/browser/supervised_user_pref_store.cc index 180babd..2e32bb6 100644 --- a/components/supervised_user/core/browser/supervised_user_pref_store.cc +++ b/components/supervised_user/core/browser/supervised_user_pref_store.cc
@@ -163,10 +163,6 @@ #if BUILDFLAG(ENABLE_EXTENSIONS) { - // TODO(crbug/1024646): Update Kids Management server to set a new bit for - // extension permissions. Until then, rely on other side effects of the - // "Permissions for sites, apps and extensions" setting, like geolocation - // being disallowed. bool permissions_disallowed = settings.FindBool(supervised_user::kGeolocationDisabled) .value_or(false);
diff --git a/components/supervised_user/core/common/supervised_user_constants.cc b/components/supervised_user/core/common/supervised_user_constants.cc index 7e92343..8a41ba8 100644 --- a/components/supervised_user/core/common/supervised_user_constants.cc +++ b/components/supervised_user/core/common/supervised_user_constants.cc
@@ -119,6 +119,7 @@ const char kManagedByParentUiMoreInfoUrl[] = "https://familylink.google.com/setting/resource/94"; +// LINT.IfChange const char kFamilyMemberRoleFeedbackTag[] = "Family_Member_Role"; - +// LINT.ThenChange(//chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FamilyInfoFeedbackSource.java) } // namespace supervised_user
diff --git a/components/viz/common/BUILD.gn b/components/viz/common/BUILD.gn index aed6b11..cb62bc1 100644 --- a/components/viz/common/BUILD.gn +++ b/components/viz/common/BUILD.gn
@@ -7,6 +7,7 @@ import("//components/viz/viz.gni") import("//gpu/vulkan/features.gni") import("//skia/features.gni") +import("//testing/libfuzzer/fuzzer_test.gni") import("//testing/test.gni") import("//third_party/inspector_protocol/inspector_protocol.gni") @@ -160,8 +161,12 @@ "gpu/raster_context_provider.cc", "gpu/raster_context_provider.h", "hit_test/aggregated_hit_test_region.h", + "hit_test/hit_test_data_provider.h", + "hit_test/hit_test_query.cc", + "hit_test/hit_test_query.h", "hit_test/hit_test_region_list.cc", "hit_test/hit_test_region_list.h", + "hit_test/hit_test_region_observer.h", "performance_hint_utils.cc", "performance_hint_utils.h", "quads/aggregated_render_pass.cc", @@ -343,6 +348,7 @@ "frame_sinks/copy_output_util_unittest.cc", "frame_sinks/delay_based_time_source_unittest.cc", "gpu/context_cache_controller_unittest.cc", + "hit_test/hit_test_query_unittest.cc", "quads/compositor_frame_metadata_unittest.cc", "quads/compositor_frame_transition_directive_unittest.cc", "quads/compositor_render_pass_unittest.cc", @@ -404,3 +410,16 @@ "//testing/perf", ] } + +fuzzer_test("hit_test_query_fuzzer") { + sources = [ "hit_test/hit_test_query_fuzzer.cc" ] + + libfuzzer_options = [ "max_len=4096" ] + + deps = [ + ":common", + "//base/test:test_support", + "//components/viz/test:test_support", + "//ui/gfx:test_support", + ] +}
diff --git a/components/viz/common/features.cc b/components/viz/common/features.cc index ec9dd05c..21d2403 100644 --- a/components/viz/common/features.cc +++ b/components/viz/common/features.cc
@@ -386,7 +386,7 @@ // inserting a separate color conversion pass during surface aggregation. BASE_FEATURE(kColorConversionInRenderer, "ColorConversionInRenderer", - base::FEATURE_ENABLED_BY_DEFAULT); + base::FEATURE_DISABLED_BY_DEFAULT); bool IsDelegatedCompositingEnabled() { return base::FeatureList::IsEnabled(kDelegatedCompositing);
diff --git a/components/viz/common/hit_test/DEPS b/components/viz/common/hit_test/DEPS index 16764a92..e24a504 100644 --- a/components/viz/common/hit_test/DEPS +++ b/components/viz/common/hit_test/DEPS
@@ -1,3 +1,4 @@ include_rules = [ "+mojo/public/cpp/bindings", + "+services/viz/public/mojom", ]
diff --git a/components/viz/common/hit_test/hit_test_data_provider.h b/components/viz/common/hit_test/hit_test_data_provider.h new file mode 100644 index 0000000..ede2a06 --- /dev/null +++ b/components/viz/common/hit_test/hit_test_data_provider.h
@@ -0,0 +1,32 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_DATA_PROVIDER_H_ +#define COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_DATA_PROVIDER_H_ + +#include "base/containers/flat_map.h" +#include "components/viz/common/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_region_observer.h" +#include "components/viz/common/surfaces/frame_sink_id.h" + +namespace viz { +using DisplayHitTestQueryMap = + base::flat_map<FrameSinkId, std::unique_ptr<HitTestQuery>>; + +// This interface will be implemented by both HostFrameSinkManager and +// FrameSinkManagerImpl allowing RenderWidgetHostInputEventRouter to find target +// view synchronously. +class VIZ_COMMON_EXPORT HitTestDataProvider { + public: + virtual ~HitTestDataProvider() = default; + // Add/Remove an observer to receive notifications of when the host receives + // new hit test data. + virtual void AddHitTestRegionObserver(HitTestRegionObserver* observer) = 0; + virtual void RemoveHitTestRegionObserver(HitTestRegionObserver* observer) = 0; + virtual const DisplayHitTestQueryMap& GetDisplayHitTestQuery() const = 0; +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_DATA_PROVIDER_H_
diff --git a/components/viz/host/hit_test/hit_test_query.cc b/components/viz/common/hit_test/hit_test_query.cc similarity index 99% rename from components/viz/host/hit_test/hit_test_query.cc rename to components/viz/common/hit_test/hit_test_query.cc index be77a1a..6144947 100644 --- a/components/viz/host/hit_test/hit_test_query.cc +++ b/components/viz/common/hit_test/hit_test_query.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 "components/viz/host/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_query.h" #include <sstream> #include <string>
diff --git a/components/viz/host/hit_test/hit_test_query.h b/components/viz/common/hit_test/hit_test_query.h similarity index 95% rename from components/viz/host/hit_test/hit_test_query.h rename to components/viz/common/hit_test/hit_test_query.h index 64437a4..830e6b13d 100644 --- a/components/viz/host/hit_test/hit_test_query.h +++ b/components/viz/common/hit_test/hit_test_query.h
@@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_VIZ_HOST_HIT_TEST_HIT_TEST_QUERY_H_ -#define COMPONENTS_VIZ_HOST_HIT_TEST_HIT_TEST_QUERY_H_ +#ifndef COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_QUERY_H_ +#define COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_QUERY_H_ #include <string> #include <vector> #include "base/functional/callback.h" #include "components/viz/common/hit_test/aggregated_hit_test_region.h" -#include "components/viz/host/viz_host_export.h" +#include "components/viz/common/viz_common_export.h" #include "ui/gfx/geometry/point_f.h" namespace viz { @@ -33,7 +33,7 @@ // Finds the target for a given location based on the AggregatedHitTestRegion // list aggregated by HitTestAggregator. // TODO(crbug.com/41460939): Handle 3d space cases correctly. -class VIZ_HOST_EXPORT HitTestQuery { +class VIZ_COMMON_EXPORT HitTestQuery { public: HitTestQuery(); @@ -159,4 +159,4 @@ } // namespace viz -#endif // COMPONENTS_VIZ_HOST_HIT_TEST_HIT_TEST_QUERY_H_ +#endif // COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_QUERY_H_
diff --git a/components/viz/host/hit_test/hit_test_query_fuzzer.cc b/components/viz/common/hit_test/hit_test_query_fuzzer.cc similarity index 98% rename from components/viz/host/hit_test/hit_test_query_fuzzer.cc rename to components/viz/common/hit_test/hit_test_query_fuzzer.cc index f4a8a01..0c80992 100644 --- a/components/viz/host/hit_test/hit_test_query_fuzzer.cc +++ b/components/viz/common/hit_test/hit_test_query_fuzzer.cc
@@ -11,7 +11,7 @@ #include <vector> #include "base/command_line.h" -#include "components/viz/host/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_query.h" #include "ui/gfx/geometry/test/fuzzer_util.h" namespace {
diff --git a/components/viz/host/hit_test/hit_test_query_unittest.cc b/components/viz/common/hit_test/hit_test_query_unittest.cc similarity index 99% rename from components/viz/host/hit_test/hit_test_query_unittest.cc rename to components/viz/common/hit_test/hit_test_query_unittest.cc index d290f073..6e23c9c 100644 --- a/components/viz/host/hit_test/hit_test_query_unittest.cc +++ b/components/viz/common/hit_test/hit_test_query_unittest.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 "components/viz/host/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_query.h" #include <cstdint>
diff --git a/components/viz/host/hit_test/hit_test_region_observer.h b/components/viz/common/hit_test/hit_test_region_observer.h similarity index 81% rename from components/viz/host/hit_test/hit_test_region_observer.h rename to components/viz/common/hit_test/hit_test_region_observer.h index c65eaea8..e8ed593c 100644 --- a/components/viz/host/hit_test/hit_test_region_observer.h +++ b/components/viz/common/hit_test/hit_test_region_observer.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_VIZ_HOST_HIT_TEST_HIT_TEST_REGION_OBSERVER_H_ -#define COMPONENTS_VIZ_HOST_HIT_TEST_HIT_TEST_REGION_OBSERVER_H_ +#ifndef COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_REGION_OBSERVER_H_ +#define COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_REGION_OBSERVER_H_ #include <vector> @@ -31,4 +31,4 @@ } // namespace viz -#endif // COMPONENTS_VIZ_HOST_HIT_TEST_HIT_TEST_REGION_OBSERVER_H_ +#endif // COMPONENTS_VIZ_COMMON_HIT_TEST_HIT_TEST_REGION_OBSERVER_H_
diff --git a/components/viz/common/resources/transferable_resource.h b/components/viz/common/resources/transferable_resource.h index d67826b..9f88d02 100644 --- a/components/viz/common/resources/transferable_resource.h +++ b/components/viz/common/resources/transferable_resource.h
@@ -146,6 +146,13 @@ } const gpu::Mailbox& mailbox() const { return mailbox_; } + // Returns the SharedBitmapId that this instance (which must have been created + // via MakeSoftwareSharedBitmap()) is storing. + // TODO(crbug.com/337538024): Decouple SharedBitmapId from Mailbox. + const SharedBitmapId& shared_bitmap_id() const { + CHECK(is_software && !IsSoftwareSharedImage()); + return mailbox_; + } const gpu::SyncToken& sync_token() const { return sync_token_; } gpu::SyncToken& mutable_sync_token() { return sync_token_; } uint32_t texture_target() const { return texture_target_; } @@ -251,7 +258,7 @@ // `texture_target` is that texture's type. // See here for OpenGL texture types: // https://www.opengl.org/wiki/Texture#Texture_Objects - uint32_t texture_target_; + uint32_t texture_target_ = 0; }; } // namespace viz
diff --git a/components/viz/host/BUILD.gn b/components/viz/host/BUILD.gn index bcc47b9..fcfdcaa 100644 --- a/components/viz/host/BUILD.gn +++ b/components/viz/host/BUILD.gn
@@ -4,7 +4,6 @@ import("//build/config/ui.gni") import("//components/viz/viz.gni") -import("//testing/libfuzzer/fuzzer_test.gni") viz_component("host") { defines = [ "VIZ_HOST_IMPLEMENTATION" ] @@ -19,9 +18,6 @@ "gpu_client_delegate.h", "gpu_host_impl.cc", "gpu_host_impl.h", - "hit_test/hit_test_query.cc", - "hit_test/hit_test_query.h", - "hit_test/hit_test_region_observer.h", "host_display_client.cc", "host_display_client.h", "host_frame_sink_client.h", @@ -75,7 +71,6 @@ testonly = true sources = [ - "hit_test/hit_test_query_unittest.cc", "host_frame_sink_manager_unittest.cc", "host_gpu_memory_buffer_manager_unittest.cc", ] @@ -100,16 +95,3 @@ deps += [ "//ui/ozone" ] } } - -fuzzer_test("hit_test_query_fuzzer") { - sources = [ "hit_test/hit_test_query_fuzzer.cc" ] - - libfuzzer_options = [ "max_len=4096" ] - - deps = [ - ":host", - "//base/test:test_support", - "//components/viz/test:test_support", - "//ui/gfx:test_support", - ] -}
diff --git a/components/viz/host/hit_test/DEPS b/components/viz/host/hit_test/DEPS deleted file mode 100644 index 28690bc5..0000000 --- a/components/viz/host/hit_test/DEPS +++ /dev/null
@@ -1,11 +0,0 @@ -# Please consult components/viz/README.md about allowable dependencies. - -include_rules = [ - "+services/viz/public/mojom", -] - -specific_include_rules = { - "hit_test_query_fuzzer.cc": [ - "+mojo/core/embedder", - ] -}
diff --git a/components/viz/host/hit_test/OWNERS b/components/viz/host/hit_test/OWNERS deleted file mode 100644 index e85219c1..0000000 --- a/components/viz/host/hit_test/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -file://components/viz/common/hit_test/OWNERS
diff --git a/components/viz/host/host_frame_sink_manager.cc b/components/viz/host/host_frame_sink_manager.cc index 5b8b72f3..f437063 100644 --- a/components/viz/host/host_frame_sink_manager.cc +++ b/components/viz/host/host_frame_sink_manager.cc
@@ -340,6 +340,11 @@ observers_.RemoveObserver(observer); } +const DisplayHitTestQueryMap& HostFrameSinkManager::GetDisplayHitTestQuery() + const { + return display_hit_test_query_; +} + void HostFrameSinkManager::OnConnectionLost() { connection_was_lost_ = true;
diff --git a/components/viz/host/host_frame_sink_manager.h b/components/viz/host/host_frame_sink_manager.h index 6c43dc2..790ef5a7 100644 --- a/components/viz/host/host_frame_sink_manager.h +++ b/components/viz/host/host_frame_sink_manager.h
@@ -19,11 +19,12 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/time/time.h" +#include "components/viz/common/hit_test/hit_test_data_provider.h" +#include "components/viz/common/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_region_observer.h" #include "components/viz/common/surfaces/frame_sink_bundle_id.h" #include "components/viz/common/surfaces/frame_sink_id.h" #include "components/viz/host/client_frame_sink_video_capturer.h" -#include "components/viz/host/hit_test/hit_test_query.h" -#include "components/viz/host/hit_test/hit_test_region_observer.h" #include "components/viz/host/host_frame_sink_client.h" #include "components/viz/host/viz_host_export.h" #include "mojo/public/cpp/bindings/pending_receiver.h" @@ -47,11 +48,9 @@ // UI thread. Manages frame sinks and is intended to replace all usage of // FrameSinkManagerImpl. class VIZ_HOST_EXPORT HostFrameSinkManager - : public mojom::FrameSinkManagerClient { + : public mojom::FrameSinkManagerClient, + public HitTestDataProvider { public: - using DisplayHitTestQueryMap = - base::flat_map<FrameSinkId, std::unique_ptr<HitTestQuery>>; - HostFrameSinkManager(); HostFrameSinkManager(const HostFrameSinkManager&) = delete; @@ -59,10 +58,6 @@ ~HostFrameSinkManager() override; - const DisplayHitTestQueryMap& display_hit_test_query() const { - return display_hit_test_query_; - } - // Sets a local FrameSinkManagerImpl instance and connects directly to it. void SetLocalManager(mojom::FrameSinkManager* frame_sink_manager); @@ -232,10 +227,10 @@ void StartThrottlingAllFrameSinks(base::TimeDelta interval); void StopThrottlingAllFrameSinks(); - // Add/Remove an observer to receive notifications of when the host receives - // new hit test data. - void AddHitTestRegionObserver(HitTestRegionObserver* observer); - void RemoveHitTestRegionObserver(HitTestRegionObserver* observer); + // HitTestDataProvider implementation. + void AddHitTestRegionObserver(HitTestRegionObserver* observer) override; + void RemoveHitTestRegionObserver(HitTestRegionObserver* observer) override; + const DisplayHitTestQueryMap& GetDisplayHitTestQuery() const override; void SetHitTestAsyncQueriedDebugRegions( const FrameSinkId& root_frame_sink_id,
diff --git a/components/viz/service/display/display_resource_provider_software.cc b/components/viz/service/display/display_resource_provider_software.cc index fa200e2..fb75a8ac 100644 --- a/components/viz/service/display/display_resource_provider_software.cc +++ b/components/viz/service/display/display_resource_provider_software.cc
@@ -73,7 +73,8 @@ } } else { if (!resource->shared_bitmap) { - const SharedBitmapId& shared_bitmap_id = resource->transferable.mailbox(); + const SharedBitmapId& shared_bitmap_id = + resource->transferable.shared_bitmap_id(); std::unique_ptr<SharedBitmap> bitmap = shared_bitmap_manager_->GetSharedBitmapFromId( resource->transferable.size, resource->transferable.format,
diff --git a/components/viz/service/display/frame_rate_decider_unittest.cc b/components/viz/service/display/frame_rate_decider_unittest.cc index 7b269e9..9beb21de6 100644 --- a/components/viz/service/display/frame_rate_decider_unittest.cc +++ b/components/viz/service/display/frame_rate_decider_unittest.cc
@@ -82,8 +82,8 @@ SurfaceId surface_id(frame_sink_id, local_surface_id); SurfaceInfo surface_info(surface_id, frame_.device_scale_factor(), frame_.size_in_pixels()); - auto* surface = - surface_manager_->CreateSurface(surface_client(), surface_info); + auto* surface = surface_manager_->CreateSurface(surface_client(), + surface_info, SurfaceId()); { FrameRateDecider::ScopedAggregate scope(frame_rate_decider_.get());
diff --git a/components/viz/service/display/surface_aggregator_unittest.cc b/components/viz/service/display/surface_aggregator_unittest.cc index daf3fe8a..22cda1d 100644 --- a/components/viz/service/display/surface_aggregator_unittest.cc +++ b/components/viz/service/display/surface_aggregator_unittest.cc
@@ -10,6 +10,7 @@ #include <algorithm> #include <map> #include <set> +#include <string> #include <utility> #include <vector> @@ -17,6 +18,7 @@ #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" +#include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/test/scoped_feature_list.h" #include "base/time/time.h" @@ -50,6 +52,7 @@ #include "components/viz/test/draw_quad_matchers.h" #include "components/viz/test/fake_compositor_frame_sink_client.h" #include "components/viz/test/fake_surface_observer.h" +#include "components/viz/test/stub_surface_client.h" #include "components/viz/test/test_surface_id_allocator.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -11249,4 +11252,239 @@ EXPECT_EQ(2u, aggregated_frame.render_pass_list.size()); } +namespace { + +// Blocks until `OnScreenshotCaptured()` is called. +class OnScreenshotCapturedWaiter : public mojom::FrameSinkManagerClient { + public: + OnScreenshotCapturedWaiter() = default; + ~OnScreenshotCapturedWaiter() override = default; + OnScreenshotCapturedWaiter(const OnScreenshotCapturedWaiter&) = delete; + OnScreenshotCapturedWaiter& operator=(const OnScreenshotCapturedWaiter&) = + delete; + + // mojom::FrameSinkManagerClient: + void OnFirstSurfaceActivation(const SurfaceInfo&) override {} + void OnFrameTokenChanged(const FrameSinkId&, + uint32_t, + base::TimeTicks) override {} + void OnAggregatedHitTestRegionListUpdated( + const FrameSinkId& frame_sink_id, + const std::vector<AggregatedHitTestRegion>& hit_test_data) override {} +#if BUILDFLAG(IS_ANDROID) + void VerifyThreadIdsDoNotBelongToHost( + const std::vector<int32_t>& thread_ids, + VerifyThreadIdsDoNotBelongToHostCallback callback) override {} +#endif + void OnScreenshotCaptured( + const blink::SameDocNavigationScreenshotDestinationToken& + destination_token, + std::unique_ptr<CopyOutputResult> copy_output_result) override { + observed_token_ = destination_token; + run_loop_.Quit(); + } + + void Wait() { run_loop_.Run(); } + + const blink::SameDocNavigationScreenshotDestinationToken& observed_token() { + return observed_token_; + } + + private: + blink::SameDocNavigationScreenshotDestinationToken observed_token_; + base::RunLoop run_loop_; +}; + +class SurfaceAggregatorCopyRequestAgainstPreviousSurfaceTest + : public SurfaceAggregatorValidSurfaceTest, + public ::testing::WithParamInterface<bool> { + public: + SurfaceAggregatorCopyRequestAgainstPreviousSurfaceTest() = default; + ~SurfaceAggregatorCopyRequestAgainstPreviousSurfaceTest() override = default; + + bool DestroyFrameSinkBeforeResult() { return GetParam(); } +}; + +std::string DescribeParam(const ::testing::TestParamInfo<bool>& info) { + if (info.param) { + return "CompositorFrameSinkSupportDestroyedBeforeResult"; + } else { + return "CopyResultSent"; + } +} + +} // namespace + +TEST_P(SurfaceAggregatorCopyRequestAgainstPreviousSurfaceTest, + CopyAgainstPreviousSurface) { + OnScreenshotCapturedWaiter waiter; + manager_.SetLocalClient(&waiter); + + TestSurfaceIdAllocator child_allocator(child_sink_->frame_sink_id()); + SurfaceId prev_sid = child_allocator.Get(); + child_allocator.Increment(); + SurfaceId current_sid = child_allocator.Get(); + + TestSurfaceIdAllocator root_allocator(root_sink_->frame_sink_id()); + SurfaceId root_sid = root_allocator.Get(); + + // Submit one frame against the previous child surface. + { + SCOPED_TRACE("previous surface"); + CompositorFrame new_frame = MakeEmptyCompositorFrame(); + std::vector<Quad> quads = { + Quad::SolidColorQuad(SkColors::kGreen, gfx::Rect(5, 5))}; + std::vector<Pass> passes = { + Pass(quads, CompositorRenderPassId{1}, gfx::Size(100, 100))}; + AddPasses(&new_frame.render_pass_list, passes, + &new_frame.metadata.referenced_surfaces); + child_sink_->SubmitCompositorFrame(prev_sid.local_surface_id(), + std::move(new_frame)); + } + + // Submit a frame against the root surface. + { + SCOPED_TRACE("root surface -> previous surface"); + CompositorFrame new_frame = MakeEmptyCompositorFrame(); + // The previous surface is reachable from the root surface. + new_frame.metadata.referenced_surfaces = {SurfaceRange(prev_sid)}; + std::vector<Quad> quads = { + Quad::SolidColorQuad(SkColors::kBlue, gfx::Rect(5, 5))}; + std::vector<Pass> passes = { + Pass(quads, CompositorRenderPassId{2}, gfx::Size(100, 100))}; + AddPasses(&new_frame.render_pass_list, passes, + &new_frame.metadata.referenced_surfaces); + root_sink_->SubmitCompositorFrame(root_sid.local_surface_id(), + std::move(new_frame)); + } + + // Activate the previous surface, and removes previous surface's temporary + // reference. + std::ignore = AggregateFrame(root_sid); + + // A new frame against the root surface and aggregate. This removes the + // reference from root to the previous surface, but make the new surface + // reachable. + { + SCOPED_TRACE("root surface -> current surface"); + CompositorFrame new_frame = MakeEmptyCompositorFrame(); + new_frame.metadata.referenced_surfaces = {SurfaceRange(current_sid)}; + std::vector<Quad> quads = { + Quad::SolidColorQuad(SkColors::kBlue, gfx::Rect(5, 5))}; + std::vector<Pass> passes = { + Pass(quads, CompositorRenderPassId{3}, gfx::Size(100, 100))}; + AddPasses(&new_frame.render_pass_list, passes, + &new_frame.metadata.referenced_surfaces); + root_sink_->SubmitCompositorFrame(root_sid.local_surface_id(), + std::move(new_frame)); + } + + // Another frame against the current child surface, with the CopyOutputRequest + // destination. + const auto expected_token = base::UnguessableToken::Create(); + { + SCOPED_TRACE("current surface with a COR"); + CompositorFrame new_frame = MakeEmptyCompositorFrame(); + new_frame.metadata.screenshot_destination = + blink::SameDocNavigationScreenshotDestinationToken(expected_token); + std::vector<Quad> quads = { + Quad::SolidColorQuad(SkColors::kRed, gfx::Rect(5, 5))}; + std::vector<Pass> passes = { + Pass(quads, CompositorRenderPassId{4}, gfx::Size(100, 100))}; + AddPasses(&new_frame.render_pass_list, passes, + &new_frame.metadata.referenced_surfaces); + child_sink_->SubmitCompositorFrame(current_sid.local_surface_id(), + std::move(new_frame)); + } + + // Check that the current child surface has `pending_copy_surface_id_` set. + ASSERT_EQ(manager_.surface_manager() + ->GetSurfaceForId(current_sid) + ->pending_copy_surface_id_for_testing(), + prev_sid); + + // Check the references. + ASSERT_THAT( + manager_.surface_manager()->GetSurfacesReferencedByParent(current_sid), + ::testing::UnorderedElementsAre(prev_sid)); + ASSERT_THAT( + manager_.surface_manager()->GetSurfacesThatReferenceChildForTesting( + prev_sid), + ::testing::UnorderedElementsAre(current_sid)); + + // Check that the CopyOutputRequest is taken during aggregation. + auto result = AggregateFrame(root_sid); + ASSERT_TRUE(result.has_copy_requests); + ASSERT_EQ(result.render_pass_list.size(), 2U); + ASSERT_EQ(result.render_pass_list[0]->copy_requests.size(), 1U); + + if (DestroyFrameSinkBeforeResult()) { + child_sink_.reset(); + + // The destruction of the frame sink doesn't remove the reference. + ASSERT_EQ(manager_.surface_manager() + ->GetSurfaceForId(current_sid) + ->pending_copy_surface_id_for_testing(), + prev_sid); + ASSERT_THAT( + manager_.surface_manager()->GetSurfacesReferencedByParent(current_sid), + ::testing::UnorderedElementsAre(prev_sid)); + ASSERT_THAT( + manager_.surface_manager()->GetSurfacesThatReferenceChildForTesting( + prev_sid), + ::testing::UnorderedElementsAre(current_sid)); + + // The destruction of `current_sid` removes the reference. + { + SCOPED_TRACE("deref current surface from root"); + CompositorFrame new_frame = MakeEmptyCompositorFrame(); + std::vector<Quad> quads = { + Quad::SolidColorQuad(SkColors::kBlue, gfx::Rect(5, 5))}; + std::vector<Pass> passes = { + Pass(quads, CompositorRenderPassId{3}, gfx::Size(100, 100))}; + AddPasses(&new_frame.render_pass_list, passes, + &new_frame.metadata.referenced_surfaces); + root_sink_->SubmitCompositorFrame(root_sid.local_surface_id(), + std::move(new_frame)); + } + manager_.surface_manager()->GarbageCollectSurfaces(); + + ASSERT_FALSE(manager_.surface_manager()->GetSurfaceForId(current_sid)); + ASSERT_FALSE(manager_.surface_manager()->GetSurfaceForId(prev_sid)); + ASSERT_TRUE(manager_.surface_manager() + ->GetSurfacesReferencedByParent(current_sid) + .empty()); + ASSERT_TRUE(manager_.surface_manager() + ->GetSurfacesThatReferenceChildForTesting(prev_sid) + .empty()); + } else { + auto empty_result = std::make_unique<CopyOutputResult>( + CopyOutputResult::Format::RGBA, + CopyOutputResult::Destination::kSystemMemory, gfx::Rect(), + /*needs_lock_for_bitmap=*/false); + result.render_pass_list[0]->copy_requests[0]->SendResult( + std::move(empty_result)); + { + SCOPED_TRACE("Waiting for OnScreenshotCaptured()"); + waiter.Wait(); + } + ASSERT_EQ(waiter.observed_token().value(), expected_token); + ASSERT_FALSE(manager_.surface_manager() + ->GetSurfaceForId(current_sid) + ->pending_copy_surface_id_for_testing() + .is_valid()); + ASSERT_TRUE(manager_.surface_manager() + ->GetSurfacesReferencedByParent(current_sid) + .empty()); + ASSERT_TRUE(manager_.surface_manager() + ->GetSurfacesThatReferenceChildForTesting(prev_sid) + .empty()); + } +} + +INSTANTIATE_TEST_SUITE_P(All, + SurfaceAggregatorCopyRequestAgainstPreviousSurfaceTest, + ::testing::Bool(), + &DescribeParam); + } // namespace viz
diff --git a/components/viz/service/frame_sinks/compositor_frame_sink_support.cc b/components/viz/service/frame_sinks/compositor_frame_sink_support.cc index 847fe4d..3d4e344 100644 --- a/components/viz/service/frame_sinks/compositor_frame_sink_support.cc +++ b/components/viz/service/frame_sinks/compositor_frame_sink_support.cc
@@ -96,14 +96,19 @@ void RemoveSurfaceReferenceAndDispatchCopyOutputRequestCallback( base::WeakPtr<FrameSinkManagerImpl> frame_sink_manager, - SurfaceId copied_surface, + const SurfaceId& holds_ref_surface_id, const blink::SameDocNavigationScreenshotDestinationToken& destination_token, std::unique_ptr<CopyOutputResult> result) { if (!frame_sink_manager) { return; } - frame_sink_manager->surface_manager()->RemoveTemporaryReferenceAfterCopy( - copied_surface); + if (auto* surface_holds_ref = + frame_sink_manager->surface_manager()->GetSurfaceForId( + holds_ref_surface_id)) { + surface_holds_ref->ResetPendingCopySurfaceId(); + } + // Send the IPC to the browser process even if `result` is empty. The empty + // result will be handled on the browser side. frame_sink_manager->OnScreenshotCaptured(destination_token, std::move(result)); } @@ -888,18 +893,30 @@ return SubmitResult::ACCEPTED; } + const bool has_copy_request_against_prev_surface = + frame.metadata.screenshot_destination.has_value() && prev_surface; + current_surface = surface_manager_->CreateSurface( - weak_factory_.GetWeakPtr(), surface_info); + weak_factory_.GetWeakPtr(), surface_info, + has_copy_request_against_prev_surface ? last_created_surface_id_ + : SurfaceId()); // The previous surface needs to be valid to generate a screenshot. - if (frame.metadata.screenshot_destination.has_value() && prev_surface) { - surface_manager_->AddTemporaryReference(last_created_surface_id_); + // + // NOTE: In order for the previous surface to be copied, it needs to be + // reachable and kept alive. This is achieved by adding a reference from the + // current surface to the previous surface. Normally this reference is + // removed when the copy is finished in Viz. However we could run into an + // edge case where the frame sink is destroyed before the copy is finished. + // If that happens, we will rely on the GC of the current surface to remove + // the reference. + if (has_copy_request_against_prev_surface) { auto copy_request = std::make_unique<CopyOutputRequest>( CopyOutputRequest::ResultFormat::RGBA, CopyOutputRequest::ResultDestination::kSystemMemory, base::BindOnce( &RemoveSurfaceReferenceAndDispatchCopyOutputRequestCallback, - frame_sink_manager_->GetWeakPtr(), last_created_surface_id_, + frame_sink_manager_->GetWeakPtr(), surface_info.id(), frame.metadata.screenshot_destination.value())); copy_request->set_result_task_runner( base::SequencedTaskRunner::GetCurrentDefault());
diff --git a/components/viz/service/frame_sinks/frame_sink_bundle_impl.cc b/components/viz/service/frame_sinks/frame_sink_bundle_impl.cc index a43e274..3d4c5e5 100644 --- a/components/viz/service/frame_sinks/frame_sink_bundle_impl.cc +++ b/components/viz/service/frame_sinks/frame_sink_bundle_impl.cc
@@ -339,7 +339,7 @@ void FrameSinkBundleImpl::DidAllocateSharedBitmap( uint32_t sink_id, base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id) { + const SharedBitmapId& id) { if (auto* sink = GetFrameSink(sink_id)) { sink->DidAllocateSharedBitmap(std::move(region), id); }
diff --git a/components/viz/service/frame_sinks/frame_sink_bundle_impl.h b/components/viz/service/frame_sinks/frame_sink_bundle_impl.h index f4d0070..3f0fe6d6 100644 --- a/components/viz/service/frame_sinks/frame_sink_bundle_impl.h +++ b/components/viz/service/frame_sinks/frame_sink_bundle_impl.h
@@ -71,7 +71,7 @@ std::vector<mojom::BundledFrameSubmissionPtr> submissions) override; void DidAllocateSharedBitmap(uint32_t sink_id, base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id) override; + const SharedBitmapId& id) override; #if BUILDFLAG(IS_ANDROID) void SetThreadIds(uint32_t sink_id, const std::vector<int32_t>& thread_ids) override;
diff --git a/components/viz/service/surfaces/surface.cc b/components/viz/service/surfaces/surface.cc index b455c746a..8cd3f80 100644 --- a/components/viz/service/surfaces/surface.cc +++ b/components/viz/service/surfaces/surface.cc
@@ -88,10 +88,12 @@ SurfaceManager* surface_manager, SurfaceAllocationGroup* allocation_group, base::WeakPtr<SurfaceClient> surface_client, + const SurfaceId& pending_copy_surface_id, size_t max_uncommitted_frames) : surface_info_(surface_info), surface_manager_(surface_manager), surface_client_(std::move(surface_client)), + pending_copy_surface_id_(pending_copy_surface_id), allocation_group_(allocation_group), max_uncommitted_frames_(max_uncommitted_frames) { TRACE_EVENT_ASYNC_BEGIN1(TRACE_DISABLED_BY_DEFAULT("viz.surface_lifetime"), @@ -479,6 +481,12 @@ return std::nullopt; } +void Surface::ResetPendingCopySurfaceId() { + CHECK(pending_copy_surface_id_.is_valid()); + pending_copy_surface_id_ = SurfaceId(); + RecomputeActiveReferencedSurfaces(); +} + void Surface::UpdateReferencedAllocationGroups( std::vector<SurfaceAllocationGroup*> new_referenced_allocation_groups) { base::flat_set<raw_ptr<SurfaceAllocationGroup, CtnExperimental>> new_set( @@ -502,7 +510,6 @@ // Extract the latest in flight surface from the ranges in the frame then // notify SurfaceManager of the new references. active_referenced_surfaces_.clear(); - last_surface_id_for_range_.clear(); std::vector<SurfaceAllocationGroup*> new_referenced_allocation_groups; for (const SurfaceRange& surface_range : active_frame_data_->frame.metadata.referenced_surfaces) { @@ -511,9 +518,6 @@ surface_manager_->GetLatestInFlightSurface(surface_range); if (surface) { active_referenced_surfaces_.insert(surface->surface_id()); - last_surface_id_for_range_.push_back(surface->surface_id()); - } else { - last_surface_id_for_range_.emplace_back(); } // The allocation group for the end of the SurfaceRange should always be // referenced. @@ -540,6 +544,13 @@ } } } + + // Makes sure `pending_copy_surface_id_` is reachable from `this` during + // aggregation. + if (pending_copy_surface_id_.is_valid()) { + active_referenced_surfaces_.insert(pending_copy_surface_id_); + } + UpdateReferencedAllocationGroups(std::move(new_referenced_allocation_groups)); UpdateSurfaceReferences(); }
diff --git a/components/viz/service/surfaces/surface.h b/components/viz/service/surfaces/surface.h index 67821e6..4db8f01 100644 --- a/components/viz/service/surfaces/surface.h +++ b/components/viz/service/surfaces/surface.h
@@ -120,10 +120,13 @@ using CommitPredicate = base::FunctionRef<bool(const SurfaceId&, const BeginFrameId&)>; + // `pending_copy_surface_id`, when valid, becomes an + // `active_referenced_surfaces_` of `this`. Surface(const SurfaceInfo& surface_info, SurfaceManager* surface_manager, SurfaceAllocationGroup* allocation_group, base::WeakPtr<SurfaceClient> surface_client, + const SurfaceId& pending_copy_surface_id, size_t max_uncommitted_frames); Surface(const Surface&) = delete; @@ -323,6 +326,14 @@ std::optional<uint64_t> GetUncommitedFrameIndexNewerThan( uint64_t frame_index); + // Called when `pending_copy_surface_id_` no longer needs to be referenced + // from `this`. `activation_dependencies_` will also recomputed. + void ResetPendingCopySurfaceId(); + + const SurfaceId& pending_copy_surface_id_for_testing() const { + return pending_copy_surface_id_; + } + private: struct FrameData { FrameData(CompositorFrame&& frame, uint64_t frame_index); @@ -410,12 +421,6 @@ // avoid recompution. base::flat_set<SurfaceId> active_referenced_surfaces_; - // Keeps track of the referenced surface for each SurfaceRange. i.e the i-th - // element is the referenced SurfaceId in the i-th SurfaceRange. If a - // SurfaceRange doesn't contain any active surfaces then the corresponding - // entry in this vector is an unvalid SurfaceId. - std::vector<SurfaceId> last_surface_id_for_range_; - // Allocation groups that this surface references by its active frame. base::flat_set<raw_ptr<SurfaceAllocationGroup, CtnExperimental>> referenced_allocation_groups_; @@ -435,6 +440,12 @@ bool is_latency_info_taken_ = false; + // Indicates there is a pending `CopyOutputRequest` against + // `pending_copy_surface_id_`. When valid, it keeps `pending_copy_surface_id_` + // reachable from `this`, and keeps `pending_copy_surface_id_` alive during + // the aggregation. + SurfaceId pending_copy_surface_id_; + const raw_ptr<SurfaceAllocationGroup> allocation_group_; const size_t max_uncommitted_frames_;
diff --git a/components/viz/service/surfaces/surface_manager.cc b/components/viz/service/surfaces/surface_manager.cc index 1140031e..50b87281 100644 --- a/components/viz/service/surfaces/surface_manager.cc +++ b/components/viz/service/surfaces/surface_manager.cc
@@ -112,7 +112,8 @@ Surface* SurfaceManager::CreateSurface( base::WeakPtr<SurfaceClient> surface_client, - const SurfaceInfo& surface_info) { + const SurfaceInfo& surface_info, + const SurfaceId& pending_copy_surface_id) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(surface_info.is_valid()); DCHECK(surface_client); @@ -129,9 +130,9 @@ if (!allocation_group) return nullptr; - std::unique_ptr<Surface> surface = - std::make_unique<Surface>(surface_info, this, allocation_group, - surface_client, max_uncommitted_frames_); + std::unique_ptr<Surface> surface = std::make_unique<Surface>( + surface_info, this, allocation_group, surface_client, + pending_copy_surface_id, max_uncommitted_frames_); surface->SetDependencyDeadline( std::make_unique<SurfaceDependencyDeadline>(tick_clock_)); surface_map_[surface_info.id()] = std::move(surface); @@ -311,7 +312,9 @@ const SurfaceId& parent_id = reference.parent_id(); const SurfaceId& child_id = reference.child_id(); - if (parent_id.frame_sink_id() == child_id.frame_sink_id()) { + if (parent_id.frame_sink_id() == child_id.frame_sink_id() && + !parent_id.IsNewerThan(child_id)) { + // Only newer surfaces from the same client can keep an older surface alive. DLOG(ERROR) << "Cannot add self reference from " << parent_id << " to " << child_id; return; @@ -607,11 +610,6 @@ RemoveTemporaryReferenceImpl(surface_id, RemovedReason::DROPPED); } -void SurfaceManager::RemoveTemporaryReferenceAfterCopy( - const SurfaceId& surface_id) { - RemoveTemporaryReferenceImpl(surface_id, RemovedReason::COPIED); -} - SurfaceAllocationGroup* SurfaceManager::GetOrCreateAllocationGroupForSurfaceId( const SurfaceId& surface_id) { std::unique_ptr<SurfaceAllocationGroup>& allocation_group =
diff --git a/components/viz/service/surfaces/surface_manager.h b/components/viz/service/surfaces/surface_manager.h index 19ef7b4c..ffe4eef9 100644 --- a/components/viz/service/surfaces/surface_manager.h +++ b/components/viz/service/surfaces/surface_manager.h
@@ -88,7 +88,8 @@ // dependencies are satisfied, and it is not reachable from the root surface. // A temporary reference will be added to the new Surface. Surface* CreateSurface(base::WeakPtr<SurfaceClient> surface_client, - const SurfaceInfo& surface_info); + const SurfaceInfo& surface_info, + const SurfaceId& pending_copy_surface_id); // Marks |surface_id| for destruction. The surface will get destroyed when // it's not reachable from the root or any other surface that is not marked @@ -188,13 +189,6 @@ // next display frame. We will notify SurfaceObservers accordingly. void SurfaceWillBeDrawn(Surface* surface); - // Adds a temporary reference to |surface_id|. The reference will not have an - // owner initially. - void AddTemporaryReference(const SurfaceId& surface_id); - - // Removes the temporary reference after the `surface_id` is copied. - void RemoveTemporaryReferenceAfterCopy(const SurfaceId& surface_id); - // Removes temporary reference to |surface_id| and older surfaces. void DropTemporaryReference(const SurfaceId& surface_id); @@ -274,6 +268,10 @@ // Returns whether |surface_id| has a temporary reference or not. bool HasTemporaryReference(const SurfaceId& surface_id) const; + // Adds a temporary reference to |surface_id|. The reference will not have an + // owner initially. + void AddTemporaryReference(const SurfaceId& surface_id); + // Removes temporary reference to |surface_id| and older surfaces. The // |reason| for removing will be recorded with UMA. void RemoveTemporaryReferenceImpl(const SurfaceId& surface_id,
diff --git a/components/viz/service/surfaces/surface_unittest.cc b/components/viz/service/surfaces/surface_unittest.cc index 4fd0c52..67fa429 100644 --- a/components/viz/service/surfaces/surface_unittest.cc +++ b/components/viz/service/surfaces/surface_unittest.cc
@@ -301,6 +301,51 @@ testing::ElementsAre(child_surface_id2)); } +TEST_F(SurfaceTest, PendingCopySurfaceIncludedInActiveReferencedSurfaces) { + SurfaceManager* surface_manager = frame_sink_manager_.surface_manager(); + + gfx::Rect rect(5, 5); + + auto support = std::make_unique<CompositorFrameSinkSupport>( + nullptr, &frame_sink_manager_, kArbitraryFrameSinkId, + /*is_root=*/false); + + TestSurfaceIdAllocator allocator(kArbitraryFrameSinkId); + SurfaceId prev_id = allocator.Get(); + allocator.Increment(); + SurfaceId curr_id = allocator.Get(); + + { + CompositorFrame frame = + MakeCompositorFrame(RenderPassBuilder(CompositorRenderPassId{1}, rect) + .AddSolidColorQuad(rect, SkColors::kBlue) + .AddSolidColorQuad(rect, SkColors::kBlue) + .Build()); + support->SubmitCompositorFrame(prev_id.local_surface_id(), + std::move(frame)); + } + { + CompositorFrame frame = + MakeCompositorFrame(RenderPassBuilder(CompositorRenderPassId{2}, rect) + .AddSolidColorQuad(rect, SkColors::kBlue) + .AddSolidColorQuad(rect, SkColors::kBlue) + .Build()); + frame.metadata.screenshot_destination = + blink::SameDocNavigationScreenshotDestinationToken( + base::UnguessableToken::Create()); + support->SubmitCompositorFrame(curr_id.local_surface_id(), + std::move(frame)); + } + + auto* curr_surface = surface_manager->GetSurfaceForId(curr_id); + ASSERT_TRUE(curr_surface); + ASSERT_THAT(curr_surface->active_referenced_surfaces(), + ::testing::UnorderedElementsAre(prev_id)); + + curr_surface->ResetPendingCopySurfaceId(); + ASSERT_TRUE(curr_surface->active_referenced_surfaces().empty()); +} + // Parameterized by whether we should enable kDrawImmediatelyWhenInteractive. class ImmediateActivationSurfaceTest : public SurfaceTest,
diff --git a/components/viz/service/transitions/transferable_resource_tracker.cc b/components/viz/service/transitions/transferable_resource_tracker.cc index 8da9f13..ba0720b68 100644 --- a/components/viz/service/transitions/transferable_resource_tracker.cc +++ b/components/viz/service/transitions/transferable_resource_tracker.cc
@@ -89,7 +89,7 @@ release_callback = base::BindOnce( [](SharedBitmapManager* manager, const TransferableResource& resource, const gpu::SyncToken& sync_token) { - const SharedBitmapId& id = resource.mailbox(); + const SharedBitmapId& id = resource.shared_bitmap_id(); manager->ChildDeletedSharedBitmap(id); }, shared_bitmap_manager_);
diff --git a/components/viz/service/transitions/transferable_resource_tracker_unittest.cc b/components/viz/service/transitions/transferable_resource_tracker_unittest.cc index fc92b2e..af8a9276 100644 --- a/components/viz/service/transitions/transferable_resource_tracker_unittest.cc +++ b/components/viz/service/transitions/transferable_resource_tracker_unittest.cc
@@ -39,7 +39,7 @@ // Returns if there is a SharedBitmap in SharedBitmapManager for |resource|. bool HasBitmapResource(const TransferableResource& resource) { DCHECK(resource.is_software); - SharedBitmapId id = resource.mailbox(); + SharedBitmapId id = resource.shared_bitmap_id(); return !!shared_bitmap_manager_.GetSharedBitmapFromId( gfx::Size(1, 1), SinglePlaneFormat::kRGBA_8888, id); }
diff --git a/components/viz/test/host_frame_sink_manager_test_api.cc b/components/viz/test/host_frame_sink_manager_test_api.cc index bb8215a8..0254c1b 100644 --- a/components/viz/test/host_frame_sink_manager_test_api.cc +++ b/components/viz/test/host_frame_sink_manager_test_api.cc
@@ -11,7 +11,7 @@ : host_frame_sink_manager_(host_frame_sink_manager) {} void HostFrameSinkManagerTestApi::SetDisplayHitTestQuery( - HostFrameSinkManager::DisplayHitTestQueryMap map) { + DisplayHitTestQueryMap map) { host_frame_sink_manager_->display_hit_test_query_.clear(); host_frame_sink_manager_->display_hit_test_query_ = std::move(map); }
diff --git a/components/viz/test/host_frame_sink_manager_test_api.h b/components/viz/test/host_frame_sink_manager_test_api.h index 073b3ae..8f0dbef 100644 --- a/components/viz/test/host_frame_sink_manager_test_api.h +++ b/components/viz/test/host_frame_sink_manager_test_api.h
@@ -31,7 +31,7 @@ // Clears out the currently set hit test queries, and overrides it with |map|. // The HostFrameSinkManager will take ownership of |map|. There should only be // one HitTestQuery per root FrameSinkId. - void SetDisplayHitTestQuery(HostFrameSinkManager::DisplayHitTestQueryMap map); + void SetDisplayHitTestQuery(DisplayHitTestQueryMap map); private: // Not owned.
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 77d0340..cee9eeb 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -1160,6 +1160,8 @@ "interest_group/interest_group_permissions_checker.h", "interest_group/interest_group_priority_util.cc", "interest_group/interest_group_priority_util.h", + "interest_group/interest_group_real_time_report_util.cc", + "interest_group/interest_group_real_time_report_util.h", "interest_group/interest_group_storage.cc", "interest_group/interest_group_storage.h", "interest_group/interest_group_update.cc",
diff --git a/content/browser/attribution_reporting/attribution_internals_browsertest.cc b/content/browser/attribution_reporting/attribution_internals_browsertest.cc index b0e0df50..c43f9eb 100644 --- a/content/browser/attribution_reporting/attribution_internals_browsertest.cc +++ b/content/browser/attribution_reporting/attribution_internals_browsertest.cc
@@ -359,8 +359,6 @@ .Build(), StorableSource::Result::kExcessiveReportingOrigins); - // TODO(crbug.com/40285244): Bypass locale dependency to validate event report - // windows column value. static constexpr char kScript[] = R"( // TODO(apaseltiner): This is necessary because innerText returns different // results based on whether the text is visible. Switch to textContent to
diff --git a/content/browser/attribution_reporting/attribution_manager_impl.cc b/content/browser/attribution_reporting/attribution_manager_impl.cc index 3169087..51527ad 100644 --- a/content/browser/attribution_reporting/attribution_manager_impl.cc +++ b/content/browser/attribution_reporting/attribution_manager_impl.cc
@@ -133,9 +133,6 @@ // While the class does not make large changes to the underlying database, it // is responsible for notifying the `AttributionStorage` when the browser comes // back online, which mutates report times for some scheduled reports. -// -// TODO(apaseltiner): Consider making this class an observer to allow it to -// manage when to schedule things. class AttributionReportScheduler : public ReportSchedulerTimer::Delegate { public: AttributionReportScheduler(
diff --git a/content/browser/attribution_reporting/attribution_storage_sql.cc b/content/browser/attribution_reporting/attribution_storage_sql.cc index 55a7f97..9fa000e 100644 --- a/content/browser/attribution_reporting/attribution_storage_sql.cc +++ b/content/browser/attribution_reporting/attribution_storage_sql.cc
@@ -1429,8 +1429,6 @@ trigger_spec.event_report_windows(), source.source_time(), attribution_info.time); - // TODO(apaseltiner): Consider informing the manager if the trigger - // data was out of range for DevTools issue reporting. report = AttributionReport( attribution_info, AttributionReport::Id(kUnsetRecordId), report_time, /*initial_report_time=*/report_time, delegate_->NewReportID(), @@ -1928,8 +1926,6 @@ // crrev.com/c/2150071/4/content/browser/conversions/conversion_storage_sql.cc#342 // // TODO(crbug.com/40212333): Look into optimizing origin filter callback. - // TODO(apaseltiner): Consider wrapping `filter` such that it deletes - // opaque/untrustworthy origins. std::vector<StoredSource::Id> source_ids_to_delete;
diff --git a/content/browser/attribution_reporting/interop/parser.cc b/content/browser/attribution_reporting/interop/parser.cc index 222e43fb..d377d55 100644 --- a/content/browser/attribution_reporting/interop/parser.cc +++ b/content/browser/attribution_reporting/interop/parser.cc
@@ -273,8 +273,6 @@ /*allow_empty=*/false); } - // TODO(linnan): Parse null reports rate if it's supported in interop tests. - if (has_error_) { return base::unexpected(error_stream_.str()); }
diff --git a/content/browser/interest_group/interest_group_real_time_report_util.cc b/content/browser/interest_group/interest_group_real_time_report_util.cc new file mode 100644 index 0000000..61fc44c --- /dev/null +++ b/content/browser/interest_group/interest_group_real_time_report_util.cc
@@ -0,0 +1,91 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/interest_group/interest_group_real_time_report_util.h" + +#include <cmath> +#include <cstddef> +#include <cstdint> +#include <map> +#include <optional> + +#include "base/check_op.h" +#include "base/notreached.h" +#include "base/rand_util.h" +#include "content/services/auction_worklet/public/mojom/real_time_reporting.mojom.h" +#include "third_party/blink/public/common/features.h" +#include "url/origin.h" + +namespace content { + +std::vector<uint8_t> Rappor(std::optional<int32_t> maybe_bucket, + double epsilon, + int num_buckets) { + std::vector<uint8_t> histogram(num_buckets, 0); + if (maybe_bucket.has_value()) { + // Browser side that collects contributions should guarantee this. + CHECK_GE(*maybe_bucket, 0); + CHECK_LT(*maybe_bucket, num_buckets); + histogram[*maybe_bucket] = 1; + } + + double f = 2.0 / (1 + std::exp(epsilon / 2.0)); + for (size_t i = 0; i < static_cast<size_t>(num_buckets); i++) { + if (base::RandDouble() < f / 2.0) { + histogram[i] = 1 - histogram[i]; + } + } + return histogram; +} + +std::optional<int32_t> SampleContributions( + const std::vector<auction_worklet::mojom::RealTimeReportingContributionPtr>& + contributions) { + if (contributions.empty()) { + return std::nullopt; + } + double priority_weight_sum = 0.0; + for (const auto& contribution : contributions) { + // Browser side that collects contributions should guarantee this. + CHECK(contribution->priority_weight > 0); + priority_weight_sum += contribution->priority_weight; + } + // `random` is always smaller than `priority_weight_sum`, since RandDouble() + // produces output in the range [0, 1). + double random = base::RandDouble() * priority_weight_sum; + priority_weight_sum = 0.0; + for (const auto& contribution : contributions) { + priority_weight_sum += contribution->priority_weight; + if (priority_weight_sum >= random) { + return contribution->bucket; + } + } + + // If `contributions` is not empty, one should have be chosen and returned. + NOTREACHED_NORETURN(); +} + +std::map<url::Origin, std::vector<uint8_t>> +CalculateRealTimeReportingHistograms( + std::map< + url::Origin, + std::vector<auction_worklet::mojom::RealTimeReportingContributionPtr>> + contributions) { + std::map<url::Origin, std::vector<uint8_t>> histograms; + for (const auto& [origin, single_origin_contributions] : contributions) { + std::optional<int32_t> maybe_bucket = + SampleContributions(single_origin_contributions); + // If an origin did not make any contributions, it will contribute an + // array of zeros by default, which will still require the input going + // through the noising mechanism to satisfy the privacy requirements. + histograms.emplace( + origin, + Rappor(maybe_bucket, + blink::features::kFledgeRealTimeReportingEpsilon.Get(), + blink::features::kFledgeRealTimeReportingNumBuckets.Get())); + } + return histograms; +} + +} // namespace content
diff --git a/content/browser/interest_group/interest_group_real_time_report_util.h b/content/browser/interest_group/interest_group_real_time_report_util.h new file mode 100644 index 0000000..59db8797 --- /dev/null +++ b/content/browser/interest_group/interest_group_real_time_report_util.h
@@ -0,0 +1,46 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CONTENT_BROWSER_INTEREST_GROUP_INTEREST_GROUP_REAL_TIME_REPORT_UTIL_H_ +#define CONTENT_BROWSER_INTEREST_GROUP_INTEREST_GROUP_REAL_TIME_REPORT_UTIL_H_ + +#include <map> +#include <optional> +#include <vector> + +#include "content/common/content_export.h" +#include "content/services/auction_worklet/public/mojom/real_time_reporting.mojom-forward.h" +#include "url/origin.h" + +namespace content { + +// Basic RAPPOR noises each coordinate of the bit vector (of size `num_buckets`) +// independently, and it is parameterized by epsilon, a measure of privacy loss. +// See the explainer for more details: +// https://github.com/WICG/turtledove/blob/main/PA_real_time_monitoring.md#histogram-contributions-and-the-rappor-noise-algorithm +// CONTENT_EXPORT for testing. +CONTENT_EXPORT std::vector<uint8_t> Rappor(std::optional<int32_t> maybe_bucket, + double epsilon, + int num_buckets); + +// Randomly select one contribution from `contributions` and return its index if +// `contributions` is not empty, otherwise return nullopt. The select is based +// on each contribution's priority weight. +// CONTENT_EXPORT for testing. +CONTENT_EXPORT std::optional<int32_t> SampleContributions( + const std::vector<auction_worklet::mojom::RealTimeReportingContributionPtr>& + contributions); + +// Randomly select one contribution per origin, based on each contribution's +// priority weight, and convert it to a histogram using Rappor. +CONTENT_EXPORT std::map<url::Origin, std::vector<uint8_t>> +CalculateRealTimeReportingHistograms( + std::map< + url::Origin, + std::vector<auction_worklet::mojom::RealTimeReportingContributionPtr>> + contributions); + +} // namespace content + +#endif // CONTENT_BROWSER_INTEREST_GROUP_INTEREST_GROUP_REAL_TIME_REPORT_UTIL_H_
diff --git a/content/browser/interest_group/interest_group_real_time_report_util_unittest.cc b/content/browser/interest_group/interest_group_real_time_report_util_unittest.cc new file mode 100644 index 0000000..2bd7341 --- /dev/null +++ b/content/browser/interest_group/interest_group_real_time_report_util_unittest.cc
@@ -0,0 +1,220 @@ +// Copyright 2024 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/interest_group/interest_group_real_time_report_util.h" + +#include <stdint.h> + +#include <algorithm> +#include <cstddef> +#include <limits> +#include <optional> +#include <string> +#include <utility> +#include <vector> + +#include "content/services/auction_worklet/public/mojom/real_time_reporting.mojom.h" +#include "testing/gmock/include/gmock/gmock-matchers.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" +#include "url/gurl.h" +#include "url/origin.h" + +namespace content { + +class InterestGroupRealTimeReportUtilTest : public testing::Test { + public: + using RealTimeReportingContributions = + std::vector<auction_worklet::mojom::RealTimeReportingContributionPtr>; + + InterestGroupRealTimeReportUtilTest() = default; + + ~InterestGroupRealTimeReportUtilTest() override = default; +}; + +// The proposed epsilon value of 1 yielding a flipping probability of ~0.378. +// Running the flipping a lot of times should get a flipping probability close +// to that. +TEST_F(InterestGroupRealTimeReportUtilTest, RapporFlippingProbability) { + const size_t kIterations = 100; + int kNumBuckets = 1024; + int total_flipped = 0; + + for (size_t i = 0; i < kIterations; i++) { + // Use std::nullopt as the bucket, so that the histogram before flipping + // would be all 0s, and the sum of histogram after calling Rappor will be + // the number of flipped bits. + std::vector<uint8_t> histogram = + Rappor(/*maybe_bucket=*/std::nullopt, /*epsilon=*/1.0, + /*num_buckets=*/kNumBuckets); + for (size_t j = 0; j < static_cast<size_t>(kNumBuckets); j++) { + total_flipped += histogram[j]; + } + } + + EXPECT_GT(total_flipped, 0.35 * kNumBuckets * kIterations); + EXPECT_LT(total_flipped, 0.4 * kNumBuckets * kIterations); +} + +// 0 and 1 in histogram are both flipped (and not flipped) randomly. +TEST_F(InterestGroupRealTimeReportUtilTest, RapporFlippingIsNonDeterministic) { + // Two buckets, with the bucket being 1, so that before flipping, the + // histogram is [0, 1]. + int kNumBuckets = 2; + int32_t bucket = 1; + base::flat_set<std::vector<uint8_t>> seen; + while (seen.size() < 4) { + std::vector<uint8_t> histogram = + Rappor(bucket, /*epsilon=*/1.0, kNumBuckets); + ASSERT_THAT(histogram, testing::AnyOf(testing::ElementsAreArray({0, 0}), + testing::ElementsAreArray({0, 1}), + testing::ElementsAreArray({1, 0}), + testing::ElementsAreArray({1, 1}))); + seen.insert(histogram); + } +} + +TEST_F(InterestGroupRealTimeReportUtilTest, SampleContributionsNoContribution) { + EXPECT_EQ(std::nullopt, SampleContributions(/*contributions=*/{})); +} + +TEST_F(InterestGroupRealTimeReportUtilTest, + SampleContributionsOneContribution) { + auction_worklet::mojom::RealTimeReportingContribution histogram( + /*bucket=*/100, /*priority_weight=*/0.5, + /*latency_threshold=*/std::nullopt); + RealTimeReportingContributions contributions; + contributions.push_back(histogram.Clone()); + + EXPECT_EQ(100, SampleContributions(contributions)); +} + +// All contributions should get a chance to be selected if we run the sampling +// a lot of times. +TEST_F(InterestGroupRealTimeReportUtilTest, + SampleContributionsMultipleContributions) { + auction_worklet::mojom::RealTimeReportingContribution contribution( + /*bucket=*/1, /*priority_weight=*/0.95, + /*latency_threshold=*/std::nullopt); + auction_worklet::mojom::RealTimeReportingContribution contribution2( + /*bucket=*/100, /*priority_weight=*/1, + /*latency_threshold=*/std::nullopt); + auction_worklet::mojom::RealTimeReportingContribution latency_contribution( + /*bucket=*/200, /*priority_weight=*/1.05, + /*latency_threshold=*/0); + auction_worklet::mojom::RealTimeReportingContribution latency_contribution2( + /*bucket=*/201, /*priority_weight=*/1, + /*latency_threshold=*/100); + + RealTimeReportingContributions contributions; + contributions.push_back(contribution.Clone()); + contributions.push_back(contribution2.Clone()); + contributions.push_back(latency_contribution.Clone()); + contributions.push_back(latency_contribution2.Clone()); + + base::flat_set<int32_t> seen; + while (seen.size() < 4) { + std::optional<int32_t> bucket = SampleContributions(contributions); + ASSERT_TRUE(bucket.has_value()); + ASSERT_THAT(*bucket, testing::AnyOf(1, 100, 200, 201)); + seen.insert(*bucket); + } +} + +// If all contributions have the same priority_weight, they should get roughly +// the same probability of being selected. +TEST_F(InterestGroupRealTimeReportUtilTest, + SampleContributionsEqualPriorityWeight) { + auction_worklet::mojom::RealTimeReportingContribution contribution1( + /*bucket=*/1, /*priority_weight=*/1, + /*latency_threshold=*/std::nullopt); + auction_worklet::mojom::RealTimeReportingContribution contribution2( + /*bucket=*/100, /*priority_weight=*/1, + /*latency_threshold=*/std::nullopt); + + RealTimeReportingContributions contributions; + contributions.push_back(contribution1.Clone()); + contributions.push_back(contribution2.Clone()); + + const size_t kIterations = 10000; + int contribution1_selected_times = 0; + for (size_t i = 0; i < kIterations; i++) { + std::optional<int32_t> bucket = SampleContributions(contributions); + ASSERT_TRUE(bucket.has_value()); + contribution1_selected_times += *bucket == 1; + } + + EXPECT_GT(contribution1_selected_times, 0.45 * kIterations); + EXPECT_LT(contribution1_selected_times, 0.55 * kIterations); +} + +// If one contribution has extremely larger priority_weight, it should be +// selected with much higher probability. +TEST_F(InterestGroupRealTimeReportUtilTest, + SampleContributionsMuchLargerPriorityWeight) { + auction_worklet::mojom::RealTimeReportingContribution + contribution_large_priority( + /*bucket=*/100, + /*priority_weight=*/std::numeric_limits<double>::max(), + /*latency_threshold=*/std::nullopt); + auction_worklet::mojom::RealTimeReportingContribution + contribution_small_priority( + /*bucket=*/1, /*priority_weight=*/0.1, + /*latency_threshold=*/std::nullopt); + + RealTimeReportingContributions contributions; + contributions.push_back(contribution_large_priority.Clone()); + contributions.push_back(contribution_small_priority.Clone()); + + const size_t kIterations = 10000; + int large_priority_selected_times = 0; + for (size_t i = 0; i < kIterations; i++) { + std::optional<int32_t> bucket = SampleContributions(contributions); + ASSERT_TRUE(bucket.has_value()); + large_priority_selected_times += *bucket == 100; + } + + EXPECT_GT(large_priority_selected_times, 0.99 * kIterations); +} + +TEST_F(InterestGroupRealTimeReportUtilTest, + CalculateRealTimeReportingHistograms) { + const url::Origin origin_a = url::Origin::Create(GURL("https://a.test/")); + const url::Origin origin_b = url::Origin::Create(GURL("https://b.test/")); + auction_worklet::mojom::RealTimeReportingContribution contribution1( + /*bucket=*/1, /*priority_weight=*/1, + /*latency_threshold=*/std::nullopt); + auction_worklet::mojom::RealTimeReportingContribution contribution2( + /*bucket=*/100, /*priority_weight=*/1, + /*latency_threshold=*/std::nullopt); + + std::map<url::Origin, RealTimeReportingContributions> contributions_map; + RealTimeReportingContributions empty_contributions = {}; + // `origin_a` has no contributions, but will still get a histogram after + // calling CalculateRealTimeReportingHistograms(). + contributions_map[origin_a] = std::move(empty_contributions); + + RealTimeReportingContributions contributions; + contributions.push_back(contribution1.Clone()); + contributions.push_back(contribution2.Clone()); + // `origin_b` has two contributions, but will still get one histogram after + // calling CalculateRealTimeReportingHistograms(). + contributions_map[origin_b] = std::move(contributions); + + std::map<url::Origin, std::vector<uint8_t>> histograms_map = + CalculateRealTimeReportingHistograms(std::move(contributions_map)); + for (const url::Origin& origin : {origin_a, origin_b}) { + auto it = histograms_map.find(origin); + CHECK(it != histograms_map.end()); + // A histogram is a vector of length kFledgeRealTimeReportingNumBuckets, + // and each element is either 0 or 1. + EXPECT_EQ(static_cast<unsigned>( + blink::features::kFledgeRealTimeReportingNumBuckets.Get()), + it->second.size()); + EXPECT_TRUE(base::ranges::all_of( + it->second, [](uint8_t bit) { return bit == 0 || bit == 1; })); + } +} + +} // namespace content
diff --git a/content/browser/loader/navigation_url_loader_impl.cc b/content/browser/loader/navigation_url_loader_impl.cc index 57543f7b..eef19518 100644 --- a/content/browser/loader/navigation_url_loader_impl.cc +++ b/content/browser/loader/navigation_url_loader_impl.cc
@@ -1318,7 +1318,7 @@ new_interceptors; new_interceptors.push_back(std::move(interceptor)); new_interceptors.swap(interceptors_); - // Reset the state of ServiceWorkerContainerHost. + // Reset the state of ServiceWorkerClient. // Currently we don't support Service Worker in Signed Exchange // pages. The page will not be controlled by service workers. And // Service Worker related APIs will fail with NoDocumentURL error. @@ -1326,13 +1326,13 @@ // Service Worker integration. Properly populate all params below, and // storage key in particular, when we want to support it. if (service_worker_handle_) { - base::WeakPtr<ServiceWorkerContainerHost> container_host = - service_worker_handle_->container_host(); - if (container_host) { - container_host->SetControllerRegistration( + base::WeakPtr<ServiceWorkerClient> service_worker_client = + service_worker_handle_->service_worker_client(); + if (service_worker_client) { + service_worker_client->SetControllerRegistration( nullptr, /*notify_controllerchange=*/false); - container_host->UpdateUrls(GURL(), std::nullopt, - blink::StorageKey()); + service_worker_client->UpdateUrls(GURL(), std::nullopt, + blink::StorageKey()); } } } @@ -1734,8 +1734,8 @@ // There might be other cases where the controller is lost here, but probably // it's fine to reset ServiceWorker subresource interception as well, as the // controller is anyway lost. - if (!subresource_loader_params_.container_host || - !subresource_loader_params_.container_host->controller()) { + if (!subresource_loader_params_.service_worker_client || + !subresource_loader_params_.service_worker_client->controller()) { subresource_loader_params_.controller_service_worker_info = nullptr; subresource_loader_params_.controller_service_worker_object_host = nullptr; }
diff --git a/content/browser/navigation_subresource_loader_params.h b/content/browser/navigation_subresource_loader_params.h index 97eaf69..e76cb2c5 100644 --- a/content/browser/navigation_subresource_loader_params.h +++ b/content/browser/navigation_subresource_loader_params.h
@@ -13,7 +13,7 @@ namespace content { -class ServiceWorkerContainerHost; +class ServiceWorkerClient; class ServiceWorkerObjectHost; // For NetworkService glues: @@ -42,7 +42,7 @@ // For `NavigationURLLoaderImpl` only, to detect the controller lost and // cancel ServiceWorker subresource interception. See the comment in // `NavigationURLLoaderImpl::NotifyResponseStarted()` for details. - base::WeakPtr<ServiceWorkerContainerHost> container_host; + base::WeakPtr<ServiceWorkerClient> service_worker_client; // When signed exchanges were prefetched in the previous page and were stored // to the PrefetchedSignedExchangeCache, and the main resource for the
diff --git a/content/browser/renderer_host/delegated_frame_host.h b/content/browser/renderer_host/delegated_frame_host.h index 222abc3..6711a09 100644 --- a/content/browser/renderer_host/delegated_frame_host.h +++ b/content/browser/renderer_host/delegated_frame_host.h
@@ -18,7 +18,7 @@ #include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/frame_sinks/begin_frame_source.h" #include "components/viz/common/frame_timing_details_map.h" -#include "components/viz/host/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_query.h" #include "components/viz/host/host_frame_sink_client.h" #include "components/viz/host/host_frame_sink_manager.h" #include "content/browser/renderer_host/dip_util.h"
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index df5d941c..28175c7 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -6133,8 +6133,9 @@ std::move(subresource_loader_params_), std::move(subresource_overrides_), std::move(service_worker_container_info), document_token_, devtools_navigation_token_); - if (service_worker_handle_ && service_worker_handle_->container_host()) { - service_worker_handle_->container_host()->SetContainerReady(); + if (service_worker_handle_ && + service_worker_handle_->service_worker_client()) { + service_worker_handle_->service_worker_client()->SetContainerReady(); } UpdateNavigationHandleTimingsOnCommitSent();
diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc index 7b0b6c4..3313f6fc 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc
@@ -2134,9 +2134,11 @@ return; } - for (auto& entry : service_worker_container_hosts_) { - if (base::WeakPtr<ServiceWorkerContainerHost> host = entry.second) - host->OnEnterBackForwardCache(); + for (auto& entry : service_worker_clients_) { + if (base::WeakPtr<ServiceWorkerClient> service_worker_client = + entry.second) { + service_worker_client->OnEnterBackForwardCache(); + } } DedicatedWorkerHostsForDocument::GetOrCreateForCurrentDocument(this) @@ -2178,9 +2180,11 @@ return; } - for (auto& entry : service_worker_container_hosts_) { - if (base::WeakPtr<ServiceWorkerContainerHost> host = entry.second) - host->OnRestoreFromBackForwardCache(); + for (auto& entry : service_worker_clients_) { + if (base::WeakPtr<ServiceWorkerClient> service_worker_client = + entry.second) { + service_worker_client->OnRestoreFromBackForwardCache(); + } } DedicatedWorkerHostsForDocument::GetOrCreateForCurrentDocument(this) @@ -14762,30 +14766,30 @@ void RenderFrameHostImpl::AddServiceWorkerContainerHost( const std::string& uuid, - base::WeakPtr<content::ServiceWorkerContainerHost> host) { + base::WeakPtr<content::ServiceWorkerClient> service_worker_client) { if (IsInBackForwardCache()) { // RenderFrameHost entered BackForwardCache before adding - // ServiceWorkerContainerHost. In this case, evict the entry from the cache. + // ServiceWorkerClient. In this case, evict the entry from the cache. EvictFromBackForwardCacheWithReason( BackForwardCacheMetrics::NotRestoredReason:: kEnteredBackForwardCacheBeforeServiceWorkerHostAdded); } - DCHECK(!base::Contains(service_worker_container_hosts_, uuid)); - last_committed_service_worker_host_ = host; - service_worker_container_hosts_[uuid] = std::move(host); + DCHECK(!base::Contains(service_worker_clients_, uuid)); + last_committed_service_worker_client_ = service_worker_client; + service_worker_clients_[uuid] = std::move(service_worker_client); } void RenderFrameHostImpl::RemoveServiceWorkerContainerHost( const std::string& uuid) { - DCHECK(!service_worker_container_hosts_.empty()); - DCHECK(base::Contains(service_worker_container_hosts_, uuid)); - service_worker_container_hosts_.erase(uuid); + DCHECK(!service_worker_clients_.empty()); + DCHECK(base::Contains(service_worker_clients_, uuid)); + service_worker_clients_.erase(uuid); } -base::WeakPtr<ServiceWorkerContainerHost> +base::WeakPtr<ServiceWorkerClient> RenderFrameHostImpl::GetLastCommittedServiceWorkerHost() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - return last_committed_service_worker_host_; + return last_committed_service_worker_client_; } bool RenderFrameHostImpl::MaybeInterceptCommitCallback(
diff --git a/content/browser/renderer_host/render_frame_host_impl.h b/content/browser/renderer_host/render_frame_host_impl.h index 2729908..75434a0 100644 --- a/content/browser/renderer_host/render_frame_host_impl.h +++ b/content/browser/renderer_host/render_frame_host_impl.h
@@ -288,7 +288,7 @@ class RenderProcessHost; class RenderViewHostImpl; class RenderWidgetHostView; -class ServiceWorkerContainerHost; +class ServiceWorkerClient; class SiteInfo; class SpeechSynthesisImpl; class TimeoutMonitor; @@ -1786,10 +1786,10 @@ void AddServiceWorkerContainerHost( const std::string& uuid, - base::WeakPtr<ServiceWorkerContainerHost> host); + base::WeakPtr<ServiceWorkerClient> service_worker_client); void RemoveServiceWorkerContainerHost(const std::string& uuid); - // Returns the last committed ServiceWorkerContainerHost of this frame. - base::WeakPtr<ServiceWorkerContainerHost> GetLastCommittedServiceWorkerHost(); + // Returns the last committed ServiceWorkerClient of this frame. + base::WeakPtr<ServiceWorkerClient> GetLastCommittedServiceWorkerHost(); // Called to taint |this| so the pages which have requested MediaStream // (audio/video/etc capture stream) access would not enter BackForwardCache. @@ -4872,16 +4872,17 @@ // Salt for generating frame-specific media device IDs. std::string media_device_id_salt_base_; - // Keep the list of ServiceWorkerContainerHosts so that they can observe when + // Keep the list of ServiceWorkerClients so that they can observe when // the frame goes in/out of BackForwardCache. // TODO(yuzus): Make this a single pointer. A frame should only have a single - // container host, but probably during a navigation the old container host is - // still alive when the new container host is created and added to this - // vector, and the old container host is destroyed shortly after navigation. - std::map<std::string, base::WeakPtr<ServiceWorkerContainerHost>> - service_worker_container_hosts_; - // Keeps the track of the latest ServiceWorkerContainerHost. - base::WeakPtr<ServiceWorkerContainerHost> last_committed_service_worker_host_; + // service worker client, but probably during a navigation the old service + // worker client is still alive when the new service worker client is created + // and added to this vector, and the old service worker client is destroyed + // shortly after navigation. + std::map<std::string, base::WeakPtr<ServiceWorkerClient>> + service_worker_clients_; + // Keeps the track of the latest ServiceWorkerClient. + base::WeakPtr<ServiceWorkerClient> last_committed_service_worker_client_; // The fenced frames owned by this document, ordered with newer fenced frames // being appended to the end.
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.cc b/content/browser/renderer_host/render_widget_host_input_event_router.cc index 543a24c8..5802387 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router.cc
@@ -15,10 +15,9 @@ #include "base/metrics/histogram_macros.h" #include "base/trace_event/trace_event.h" #include "components/viz/common/features.h" +#include "components/viz/common/hit_test/hit_test_data_provider.h" #include "components/viz/common/hit_test/hit_test_region_list.h" #include "components/viz/common/quads/surface_draw_quad.h" -#include "components/viz/host/host_frame_sink_manager.h" -#include "content/browser/compositor/surface_utils.h" #include "content/browser/renderer_host/cursor_manager.h" #include "content/browser/renderer_host/input/touch_emulator.h" #include "content/common/input/render_input_router.h" @@ -55,13 +54,11 @@ namespace content { // Helper method also used from hit_test_debug_key_event_observer.cc -viz::HitTestQuery* GetHitTestQuery( - viz::HostFrameSinkManager* host_frame_sink_manager, - const viz::FrameSinkId& frame_sink_id) { +viz::HitTestQuery* GetHitTestQuery(viz::HitTestDataProvider* provider, + const viz::FrameSinkId& frame_sink_id) { if (!frame_sink_id.is_valid()) return nullptr; - const auto& display_hit_test_query_map = - host_frame_sink_manager->display_hit_test_query(); + const auto& display_hit_test_query_map = provider->GetDisplayHitTestQuery(); const auto iter = display_hit_test_query_map.find(frame_sink_id); if (iter == display_hit_test_query_map.end()) return nullptr; @@ -322,6 +319,16 @@ return owner_map_.size(); } +RenderWidgetHostViewInput* +RenderWidgetHostInputEventRouter::GetLastMouseMoveTargetForTest() { + return last_mouse_move_target_.get(); +} + +RenderWidgetHostViewInput* +RenderWidgetHostInputEventRouter::GetLastMouseMoveRootViewForTest() { + return last_mouse_move_root_view_.get(); +} + void RenderWidgetHostInputEventRouter::OnRenderWidgetHostViewInputDestroyed( RenderWidgetHostViewInput* view) { // RenderWidgetHostViewInput::RemoveObserver() should only ever be called @@ -418,22 +425,21 @@ entry.second->RemoveObserver(this); } owner_map_.clear(); - viz::HostFrameSinkManager* manager = GetHostFrameSinkManager(); - if (manager) - manager->RemoveHitTestRegionObserver(this); + hit_test_provider_->RemoveHitTestRegionObserver(this); } -RenderWidgetHostInputEventRouter::RenderWidgetHostInputEventRouter() +RenderWidgetHostInputEventRouter::RenderWidgetHostInputEventRouter( + viz::HitTestDataProvider* provider) : last_mouse_move_target_(nullptr), last_mouse_move_root_view_(nullptr), last_emulated_event_root_view_(nullptr), last_device_scale_factor_(1.f), active_touches_(0), + hit_test_provider_(provider), event_targeter_(std::make_unique<RenderWidgetTargeter>(this)), touch_event_ack_queue_(new TouchEventAckQueue(this)) { - viz::HostFrameSinkManager* manager = GetHostFrameSinkManager(); - DCHECK(manager); - manager->AddHitTestRegionObserver(this); + DCHECK(hit_test_provider_); + hit_test_provider_->AddHitTestRegionObserver(this); } RenderWidgetHostInputEventRouter::~RenderWidgetHostInputEventRouter() { @@ -547,8 +553,8 @@ viz::FrameSinkId frame_sink_id; bool query_renderer = false; - viz::HitTestQuery* query = GetHitTestQuery(GetHostFrameSinkManager(), - root_view->GetRootFrameSinkId()); + viz::HitTestQuery* query = + GetHitTestQuery(hit_test_provider_, root_view->GetRootFrameSinkId()); if (!query) { *transformed_point = point; return {root_view, false, *transformed_point, false}; @@ -986,34 +992,31 @@ // as long as they are the only embeddable RWHVs. while (cur_view->GetParentViewInput()) { cur_view = cur_view->GetParentViewInput(); - // cur_view can possibly be nullptr for guestviews that are not currently - // connected to the webcontents tree. - if (!cur_view) { - last_mouse_move_target_ = target; - last_mouse_move_root_view_ = root_view; - return; - } entered_views.push_back(cur_view); } - - // On Windows, it appears to be possible that render widget targeting could - // produce a target that is outside of the specified root. For now, we'll - // just give up in such a case. See https://crbug.com/851958. - if (cur_view != root_view) + // There are two cases where cur_view != root_view : + // 1. On Windows, render widget targeting could produce a target that is + // outside of the specified root. See https://crbug.com/851958. In this case, + // we'll just give up. + // 2. cur_view's GetParentViewInput() can possibly be nullptr for + // guestviews (Chrome App or WebUI) that are not currently connected to + // the webcontents tree. It is fine to return early since this would be + // attempted again on next mouse event and once guestview is connected, the + // ancestors will be notified and state would be updated. + if (cur_view != root_view) { return; + } cur_view = last_mouse_move_target_; if (cur_view) { exited_views.push_back(cur_view); while (cur_view->GetParentViewInput()) { cur_view = cur_view->GetParentViewInput(); - if (!cur_view) { - last_mouse_move_target_ = target; - last_mouse_move_root_view_ = root_view; - return; - } exited_views.push_back(cur_view); } + if (cur_view != root_view) { + return; + } DCHECK_EQ(cur_view, root_view); }
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router.h b/content/browser/renderer_host/render_widget_host_input_event_router.h index 6af9c641..b04f7bb 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router.h +++ b/content/browser/renderer_host/render_widget_host_input_event_router.h
@@ -15,9 +15,9 @@ #include "base/memory/raw_ptr.h" #include "base/memory/raw_ptr_exclusion.h" #include "base/memory/weak_ptr.h" +#include "components/viz/common/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_region_observer.h" #include "components/viz/common/surfaces/surface_id.h" -#include "components/viz/host/hit_test/hit_test_query.h" -#include "components/viz/host/hit_test/hit_test_region_observer.h" #include "content/browser/renderer_host/input/touch_emulator_client.h" #include "content/browser/renderer_host/render_widget_targeter.h" #include "content/common/content_export.h" @@ -48,7 +48,7 @@ } namespace viz { -class HostFrameSinkManager; +class HitTestDataProvider; } namespace content { @@ -59,9 +59,8 @@ class TouchEventAckQueue; // Helper method also used from hit_test_debug_key_event_observer.cc -viz::HitTestQuery* GetHitTestQuery( - viz::HostFrameSinkManager* host_frame_sink_manager, - const viz::FrameSinkId& frame_sink_id); +viz::HitTestQuery* GetHitTestQuery(viz::HitTestDataProvider* provider, + const viz::FrameSinkId& frame_sink_id); // Class owned by WebContentsImpl for the purpose of directing input events // to the correct RenderWidgetHost on pages with multiple RenderWidgetHosts. @@ -75,7 +74,7 @@ public TouchEmulatorClient, public viz::HitTestRegionObserver { public: - RenderWidgetHostInputEventRouter(); + explicit RenderWidgetHostInputEventRouter(viz::HitTestDataProvider* provider); RenderWidgetHostInputEventRouter(const RenderWidgetHostInputEventRouter&) = delete; @@ -197,6 +196,9 @@ void SetAutoScrollInProgress(bool is_autoscroll_in_progress); + RenderWidgetHostViewInput* GetLastMouseMoveTargetForTest(); + RenderWidgetHostViewInput* GetLastMouseMoveRootViewForTest(); + private: FRIEND_TEST_ALL_PREFIXES( BrowserSideFlingBrowserTest, @@ -453,6 +455,9 @@ }; TouchscreenPinchState touchscreen_pinch_state_; + // This is expected to outlive RenderWidgetHostInputEventRouter object. + const raw_ptr<viz::HitTestDataProvider> hit_test_provider_ = nullptr; + std::unique_ptr<RenderWidgetTargeter> event_targeter_; bool events_being_flushed_ = false;
diff --git a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc index f936ba0..64c5e208 100644 --- a/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_input_event_router_unittest.cc
@@ -3,13 +3,14 @@ // found in the LICENSE file. #include "content/browser/renderer_host/render_widget_host_input_event_router.h" + #include <memory> #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/test/task_environment.h" #include "build/build_config.h" -#include "components/viz/host/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_query.h" #include "components/viz/host/host_frame_sink_manager.h" #include "components/viz/test/host_frame_sink_manager_test_api.h" #include "content/browser/compositor/surface_utils.h" @@ -144,7 +145,7 @@ bool query_renderer) { DCHECK(GetHostFrameSinkManager()); - viz::HostFrameSinkManager::DisplayHitTestQueryMap hit_test_map; + viz::DisplayHitTestQueryMap hit_test_map; hit_test_map[GetFrameSinkId()] = std::make_unique<StubHitTestQuery>(result_view, query_renderer); @@ -195,12 +196,13 @@ RenderWidgetHostInputEventRouterTest() = default; RenderWidgetHostInputEventRouter* rwhier() { - return delegate_.GetInputEventRouter(); + return delegate_->GetInputEventRouter(); } // testing::Test: void SetUp() override { browser_context_ = std::make_unique<TestBrowserContext>(); + delegate_ = std::make_unique<MockRenderWidgetHostDelegate>(); // ImageTransportFactory doesn't exist on Android. This is needed to create // a RenderWidgetHostViewChildFrame in the test. @@ -209,7 +211,7 @@ std::make_unique<TestImageTransportFactory>()); #endif - delegate_.CreateInputEventRouter(); + delegate_->CreateInputEventRouter(); process_host_root_ = std::make_unique<MockRenderProcessHost>(browser_context_.get()); @@ -218,7 +220,7 @@ browser_context_.get(), process_host_root_.get())); auto routing_id = process_host_root_->GetNextRoutingID(); widget_host_root_ = RenderWidgetHostImpl::Create( - /*frame_tree=*/nullptr, &delegate_, + /*frame_tree=*/nullptr, delegate_.get(), RenderWidgetHostImpl::DefaultFrameSinkId(*site_instance_group_root_, routing_id), site_instance_group_root_->GetSafeRef(), routing_id, @@ -281,7 +283,7 @@ site_instance_group_root_.get(), child.process_host.get())); auto routing_id = child.process_host->GetNextRoutingID(); child.widget_host = RenderWidgetHostImpl::Create( - /*frame_tree=*/nullptr, &delegate_, + /*frame_tree=*/nullptr, delegate_.get(), RenderWidgetHostImpl::DefaultFrameSinkId(*child.site_instance_group, routing_id), child.site_instance_group->GetSafeRef(), routing_id, @@ -305,6 +307,8 @@ process_host_root_->Cleanup(); site_instance_group_root_.reset(); process_host_root_.reset(); + delegate_.reset(); + base::RunLoop().RunUntilIdle(); #if !BUILDFLAG(IS_ANDROID) @@ -332,7 +336,7 @@ BrowserTaskEnvironment task_environment_; - MockRenderWidgetHostDelegate delegate_; + std::unique_ptr<MockRenderWidgetHostDelegate> delegate_; std::unique_ptr<BrowserContext> browser_context_; std::unique_ptr<MockRenderProcessHost> process_host_root_; @@ -971,6 +975,64 @@ EXPECT_NE(view_root_.get(), bubbling_gesture_scroll_target()); } +// Ensure that when the RenderWidgetHostChildFrameView handling mouse events is +// rooted by GuestView which is not connected to WebContents, we return early +// and when it's connected, we do update mouse move related states in RWHIER. +TEST_F(RenderWidgetHostInputEventRouterTest, + DoNotSendMouseLeaveEventsForDisconnectedGuestView) { + ChildViewState child = MakeChildView(view_root_.get()); + + // We start the touch in the area for |child.view|. + view_root_->SetHittestResult(child.view.get(), false); + + blink::WebTouchEvent touch_event( + blink::WebInputEvent::Type::kTouchStart, + blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); + touch_event.touches_length = 1; + touch_event.touches[0].state = blink::WebTouchPoint::State::kStatePressed; + touch_event.unique_touch_event_id = 1; + + rwhier()->RouteTouchEvent(view_root_.get(), &touch_event, + ui::LatencyInfo(ui::SourceEventType::TOUCH)); + EXPECT_EQ(child.view.get(), touch_target()); + + // Need to send a new mouse event after ending the previous touch. + blink::WebMouseEvent mouse_event( + blink::WebInputEvent::Type::kMouseLeave, + blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); + mouse_event.SetPositionInWidget(gfx::PointF(20, 21)); + + { // Simulates GuestView not yet attached to WebContents. + ChildViewState guest_view = MakeChildView(nullptr); + ChildViewState child1 = MakeChildView(guest_view.view.get()); + ChildViewState child2 = MakeChildView(child1.view.get()); + + // We start the input event in the area for |child1.view|. + view_root_->SetHittestResult(child1.view.get(), false); + + rwhier()->RouteMouseEvent(view_root_.get(), &mouse_event, + ui::LatencyInfo(ui::SourceEventType::MOUSE)); + + DCHECK_EQ(rwhier()->GetLastMouseMoveTargetForTest(), nullptr); + DCHECK_EQ(rwhier()->GetLastMouseMoveRootViewForTest(), nullptr); + } + { // Simulates GuestView attached to WebContents. + ChildViewState guest_view = MakeChildView(view_root_.get()); + ChildViewState child1 = MakeChildView(guest_view.view.get()); + ChildViewState child2 = MakeChildView(child1.view.get()); + + // We start the input event in the area for |child2.view|. + view_root_->SetHittestResult(child1.view.get(), false); + rwhier()->RouteMouseEvent(view_root_.get(), &mouse_event, + ui::LatencyInfo(ui::SourceEventType::MOUSE)); + + DCHECK_EQ(rwhier()->GetLastMouseMoveTargetForTest(), child1.view.get()); + DCHECK_EQ(rwhier()->GetLastMouseMoveRootViewForTest(), view_root_.get()); + } +} + // Calling ShowContextMenuAtPoint without other events will happen when desktop // devtools connect to a browser instance running on a mobile. It should not // crash.
diff --git a/content/browser/renderer_host/render_widget_host_view_base.cc b/content/browser/renderer_host/render_widget_host_view_base.cc index 63c09cf..62322ba 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.cc +++ b/content/browser/renderer_host/render_widget_host_view_base.cc
@@ -970,7 +970,7 @@ if (!root_frame_sink_id.is_valid()) return false; const auto& display_hit_test_query_map = - GetHostFrameSinkManager()->display_hit_test_query(); + GetHostFrameSinkManager()->GetDisplayHitTestQuery(); const auto iter = display_hit_test_query_map.find(root_frame_sink_id); if (iter == display_hit_test_query_map.end()) return false; @@ -1026,7 +1026,7 @@ return false; const auto& display_hit_test_query_map = - GetHostFrameSinkManager()->display_hit_test_query(); + GetHostFrameSinkManager()->GetDisplayHitTestQuery(); const auto iter = display_hit_test_query_map.find(root_frame_sink_id); if (iter == display_hit_test_query_map.end()) return false;
diff --git a/content/browser/renderer_host/render_widget_host_view_base.h b/content/browser/renderer_host/render_widget_host_view_base.h index e0b35461..36ed537 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.h +++ b/content/browser/renderer_host/render_widget_host_view_base.h
@@ -21,9 +21,9 @@ #include "base/process/kill.h" #include "base/time/time.h" #include "build/build_config.h" +#include "components/viz/common/hit_test/hit_test_query.h" #include "components/viz/common/surfaces/scoped_surface_id_allocator.h" #include "components/viz/common/surfaces/surface_id.h" -#include "components/viz/host/hit_test/hit_test_query.h" #include "content/browser/renderer_host/display_feature.h" #include "content/common/content_export.h" #include "content/common/input/event_with_latency_info.h"
diff --git a/content/browser/service_worker/service_worker_client_utils.cc b/content/browser/service_worker/service_worker_client_utils.cc index d7c4242cf..26406ce 100644 --- a/content/browser/service_worker/service_worker_client_utils.cc +++ b/content/browser/service_worker/service_worker_client_utils.cc
@@ -177,45 +177,50 @@ } void AddWindowClient( - const ServiceWorkerContainerHost* container_host, + const ServiceWorkerClient& service_worker_client, std::vector< std::tuple<GlobalRenderFrameHostId, base::TimeTicks, std::string>>* client_info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!container_host->IsContainerForWindowClient()) { + if (!service_worker_client.IsContainerForWindowClient()) { return; } - if (!container_host->is_execution_ready()) + if (!service_worker_client.is_execution_ready()) { return; - client_info->push_back(std::make_tuple(container_host->GetRenderFrameHostId(), - container_host->create_time(), - container_host->client_uuid())); + } + client_info->push_back( + std::make_tuple(service_worker_client.GetRenderFrameHostId(), + service_worker_client.create_time(), + service_worker_client.client_uuid())); } void AddNonWindowClient( - const ServiceWorkerContainerHost* container_host, + const ServiceWorkerClient& service_worker_client, blink::mojom::ServiceWorkerClientType client_type, std::vector<blink::mojom::ServiceWorkerClientInfoPtr>* out_clients) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - blink::mojom::ServiceWorkerClientType host_client_type = - container_host->GetClientType(); - if (host_client_type == blink::mojom::ServiceWorkerClientType::kWindow) + if (service_worker_client.GetClientType() == + blink::mojom::ServiceWorkerClientType::kWindow) { return; + } if (client_type != blink::mojom::ServiceWorkerClientType::kAll && - client_type != host_client_type) + client_type != service_worker_client.GetClientType()) { return; - if (!container_host->is_execution_ready()) + } + if (!service_worker_client.is_execution_ready()) { return; + } // TODO(dtapuska): Need to get frozen state for dedicated workers from // DedicatedWorkerHost. crbug.com/968417 auto client_info = blink::mojom::ServiceWorkerClientInfo::New( - container_host->url(), blink::mojom::RequestContextFrameType::kNone, - container_host->client_uuid(), host_client_type, + service_worker_client.url(), blink::mojom::RequestContextFrameType::kNone, + service_worker_client.client_uuid(), + service_worker_client.GetClientType(), /*page_hidden=*/true, /*is_focused=*/false, blink::mojom::ServiceWorkerClientLifecycleState::kActive, - base::TimeTicks(), container_host->create_time()); + base::TimeTicks(), service_worker_client.create_time()); out_clients->push_back(std::move(client_info)); } @@ -263,13 +268,12 @@ controller->key(), false /* include_reserved_clients */, false /* include_back_forward_cached_clients */); !it.IsAtEnd(); ++it) { - AddNonWindowClient(&*it, options->client_type, &clients); + AddNonWindowClient(*it, options->client_type, &clients); } } } else { for (const auto& controllee : controller->controllee_map()) { - AddNonWindowClient(controllee.second.get(), options->client_type, - &clients); + AddNonWindowClient(*controllee.second, options->client_type, &clients); } } DidGetClients(std::move(callback), std::move(clients)); @@ -309,12 +313,12 @@ controller->key(), false /* include_reserved_clients */, false /* include_back_forward_cached_clients */); !it.IsAtEnd(); ++it) { - AddWindowClient(&*it, &clients_info); + AddWindowClient(*it, &clients_info); } } } else { for (const auto& controllee : controller->controllee_map()) { - AddWindowClient(controllee.second.get(), &clients_info); + AddWindowClient(*controllee.second, &clients_info); } } @@ -328,7 +332,7 @@ blink::mojom::ServiceWorkerClientInfoPtr info = GetWindowClientInfo(std::get<0>(it), std::get<1>(it), std::get<2>(it)); - // If the request to the container_host returned a null + // If the request to the service_worker_client returned a null // ServiceWorkerClientInfo, that means that it wasn't possible to associate // it with a valid RenderFrameHost. It might be because the frame was killed // or navigated in between. @@ -364,9 +368,9 @@ return; } - ServiceWorkerContainerHost* container_host = + ServiceWorkerClient* service_worker_client = context->GetContainerHostByClientID(client_uuid); - if (!container_host || !container_host->is_execution_ready()) { + if (!service_worker_client || !service_worker_client->is_execution_ready()) { // The page was destroyed before it became execution ready. Tell the // renderer the page opened but it doesn't have access to it. std::move(callback).Run(blink::ServiceWorkerStatusCode::kOk, @@ -378,23 +382,25 @@ // may be cross-origin CHECK_EQ( service_worker_security_utils::GetCorrectStorageKeyForWebSecurityState( - container_host->key(), script_url), + service_worker_client->key(), script_url), key); - blink::mojom::ServiceWorkerClientInfoPtr info = GetWindowClientInfo( - container_host->GetRenderFrameHostId(), container_host->create_time(), - container_host->client_uuid()); + blink::mojom::ServiceWorkerClientInfoPtr info = + GetWindowClientInfo(service_worker_client->GetRenderFrameHostId(), + service_worker_client->create_time(), + service_worker_client->client_uuid()); std::move(callback).Run(blink::ServiceWorkerStatusCode::kOk, std::move(info)); } } // namespace -void FocusWindowClient(ServiceWorkerContainerHost* container_host, +void FocusWindowClient(ServiceWorkerClient* service_worker_client, ClientCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(container_host->IsContainerForWindowClient()); + DCHECK(service_worker_client->IsContainerForWindowClient()); - GlobalRenderFrameHostId rfh_id = container_host->GetRenderFrameHostId(); + GlobalRenderFrameHostId rfh_id = + service_worker_client->GetRenderFrameHostId(); auto* render_frame_host = RenderFrameHostImpl::FromID(rfh_id); WebContentsImpl* web_contents = static_cast<WebContentsImpl*>( WebContents::FromRenderFrameHost(render_frame_host)); @@ -426,8 +432,9 @@ // Move the web contents to the foreground. web_contents->Activate(); - blink::mojom::ServiceWorkerClientInfoPtr info = GetWindowClientInfo( - rfh_id, container_host->create_time(), container_host->client_uuid()); + blink::mojom::ServiceWorkerClientInfoPtr info = + GetWindowClientInfo(rfh_id, service_worker_client->create_time(), + service_worker_client->client_uuid()); std::move(callback).Run(std::move(info)); } @@ -546,17 +553,16 @@ std::move(callback))); } -void GetClient(ServiceWorkerContainerHost* container_host, +void GetClient(ServiceWorkerClient* service_worker_client, ClientCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(container_host->IsContainerForClient()); - blink::mojom::ServiceWorkerClientType host_client_type = - container_host->GetClientType(); - if (host_client_type == blink::mojom::ServiceWorkerClientType::kWindow) { - blink::mojom::ServiceWorkerClientInfoPtr info = GetWindowClientInfo( - container_host->GetRenderFrameHostId(), container_host->create_time(), - container_host->client_uuid()); + if (service_worker_client->GetClientType() == + blink::mojom::ServiceWorkerClientType::kWindow) { + blink::mojom::ServiceWorkerClientInfoPtr info = + GetWindowClientInfo(service_worker_client->GetRenderFrameHostId(), + service_worker_client->create_time(), + service_worker_client->client_uuid()); base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), std::move(info))); return; @@ -565,12 +571,14 @@ // TODO(dtapuska): Need to get frozen state for dedicated workers from // DedicatedWorkerHost. crbug.com/968417 auto client_info = blink::mojom::ServiceWorkerClientInfo::New( - container_host->url(), blink::mojom::RequestContextFrameType::kNone, - container_host->client_uuid(), host_client_type, + service_worker_client->url(), + blink::mojom::RequestContextFrameType::kNone, + service_worker_client->client_uuid(), + service_worker_client->GetClientType(), /*page_hidden=*/true, /*is_focused=*/false, blink::mojom::ServiceWorkerClientLifecycleState::kActive, - base::TimeTicks(), container_host->create_time()); + base::TimeTicks(), service_worker_client->create_time()); base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), std::move(client_info))); } @@ -645,8 +653,8 @@ return; } - // If here, it means that no container_host was found, in which case, the - // renderer should still be informed that the window was opened. + // If here, it means that no service_worker_client was found, in which case, + // the renderer should still be informed that the window was opened. std::move(callback).Run(blink::ServiceWorkerStatusCode::kOk, nullptr /* client_info */); }
diff --git a/content/browser/service_worker/service_worker_client_utils.h b/content/browser/service_worker/service_worker_client_utils.h index a6321eaa..c35292b 100644 --- a/content/browser/service_worker/service_worker_client_utils.h +++ b/content/browser/service_worker/service_worker_client_utils.h
@@ -20,7 +20,7 @@ namespace content { struct GlobalRenderFrameHostId; -class ServiceWorkerContainerHost; +class ServiceWorkerClient; class ServiceWorkerContextCore; class ServiceWorkerVersion; @@ -42,9 +42,9 @@ PAYMENT_HANDLER_WINDOW, }; -// Focuses the window client associated with |container_host|. |callback| is -// called with the client information on completion. -void FocusWindowClient(ServiceWorkerContainerHost* container_host, +// Focuses the window client associated with |service_worker_client|. |callback| +// is called with the client information on completion. +void FocusWindowClient(ServiceWorkerClient* service_worker_client, ClientCallback callback); // Opens a new window and navigates it to `url`. `callback` is called with the @@ -71,9 +71,9 @@ const base::WeakPtr<ServiceWorkerContextCore>& context, NavigationCallback callback); -// Gets the client specified by |container_host|. |callback| is called with the -// client information on completion. -void GetClient(ServiceWorkerContainerHost* container_host, +// Gets the client specified by |service_worker_client|. |callback| is called +// with the client information on completion. +void GetClient(ServiceWorkerClient* service_worker_client, ClientCallback callback); // Collects clients matched with |options|. |callback| is called with the client @@ -82,15 +82,14 @@ blink::mojom::ServiceWorkerClientQueryOptionsPtr options, blink::mojom::ServiceWorkerHost::GetClientsCallback callback); -// Called after a navigation. Uses `rfh_id` to find the -// ServiceWorkerContainerHost where the navigation occurred and calls -// `callback` with its info once -// ServiceWorkerContainerHost::is_execution_ready() is true. May call -// the callback with OK status but nullptr if the host is already -// destroyed, or call the callback with an error status on error. +// Called after a navigation. Uses `rfh_id` to find the ServiceWorkerClient +// where the navigation occurred and calls `callback` with its info once +// ServiceWorkerClient::is_execution_ready() is true. May call the callback with +// OK status but nullptr if the service worker client is already destroyed, or +// call the callback with an error status on error. // // `key` is only used for a CHECK_EQ check to ensure we don't accidentally -// get a cross-origin ServiceWorkerContainerHost when "--disable-web-security" +// get a cross-origin ServiceWorkerClient when "--disable-web-security" // is inactive. But for scenarios where "--disable-web-security" is // specified/active `script_url` will ensure the correct key (as inferred from // the script_url during registration) is used.
diff --git a/content/browser/service_worker/service_worker_container_host.cc b/content/browser/service_worker/service_worker_container_host.cc index 4e77faa..66f3edd 100644 --- a/content/browser/service_worker/service_worker_container_host.cc +++ b/content/browser/service_worker/service_worker_container_host.cc
@@ -42,7 +42,7 @@ namespace { void RunCallbacks( - std::vector<ServiceWorkerContainerHost::ExecutionReadyCallback> callbacks) { + std::vector<ServiceWorkerClient::ExecutionReadyCallback> callbacks) { for (auto& callback : callbacks) { std::move(callback).Run(); } @@ -101,7 +101,7 @@ // from the renderer. // // This class is move-only. -class ServiceWorkerContainerHost::PendingUpdateVersion { +class ServiceWorkerClient::PendingUpdateVersion { public: explicit PendingUpdateVersion(scoped_refptr<ServiceWorkerVersion> version) : version_(std::move(version)) { @@ -144,7 +144,7 @@ // // See: // https://w3c.github.io/ServiceWorker/#dom-routercondition-runningstatus -class ServiceWorkerContainerHost::ServiceWorkerRunningStatusObserver final +class ServiceWorkerClient::ServiceWorkerRunningStatusObserver final : public ServiceWorkerVersion::Observer { public: void OnRunningStateChanged(ServiceWorkerVersion* version) override { @@ -165,19 +165,7 @@ mojo::RemoteSet<blink::mojom::ServiceWorkerRunningStatusCallback> callbacks_; }; -ServiceWorkerContainerHost::ServiceWorkerContainerHost( - base::WeakPtr<ServiceWorkerContextCore> context, - bool is_parent_frame_secure, - mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> - container_remote, - int process_id_for_worker_client) - : context_(std::move(context)), - create_time_(base::TimeTicks::Now()), - is_parent_frame_secure_(is_parent_frame_secure), - container_(std::move(container_remote)), - process_id_for_worker_client_(process_id_for_worker_client) { - DCHECK(context_); -} +ServiceWorkerContainerHost::ServiceWorkerContainerHost() = default; ServiceWorkerContainerHostForServiceWorker:: ServiceWorkerContainerHostForServiceWorker( @@ -185,70 +173,57 @@ ServiceWorkerHost* service_worker_host, const GURL& url, const blink::StorageKey& storage_key) - : ServiceWorkerContainerHost( - std::move(context), - /*is_parent_frame_secure=*/true, - /*container_remote=*/{}, - /*process_id_for_worker_client=*/ChildProcessHost::kInvalidUniqueID), - service_worker_host_(service_worker_host) { - url_ = url; - key_ = storage_key; - top_frame_origin_ = url::Origin::Create(key_.top_level_site().GetURL()); + : service_worker_host_(service_worker_host), + context_(std::move(context)), + url_(url), + key_(storage_key), + top_frame_origin_(url::Origin::Create(key_.top_level_site().GetURL())) { + DCHECK(context_); CHECK(!url_.has_ref()); service_worker_security_utils::CheckOnUpdateUrls(url_, key_); } -ServiceWorkerContainerHostForClient::ServiceWorkerContainerHostForClient( +ServiceWorkerClient::ServiceWorkerClient( base::WeakPtr<ServiceWorkerContextCore> context, bool is_parent_frame_secure, - mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> - container_remote, int frame_tree_node_id) - : ServiceWorkerContainerHost( - std::move(context), - is_parent_frame_secure, - std::move(container_remote), - /*process_id_for_worker_client=*/ChildProcessHost::kInvalidUniqueID) { - client_uuid_ = base::Uuid::GenerateRandomV4().AsLowercaseString(); - client_info_ = ServiceWorkerClientInfo(); - ongoing_navigation_frame_tree_node_id_ = frame_tree_node_id; - - DCHECK(IsContainerForWindowClient()); - DCHECK(container_.is_bound()); + : context_(std::move(context)), + create_time_(base::TimeTicks::Now()), + client_uuid_(base::Uuid::GenerateRandomV4().AsLowercaseString()), + is_parent_frame_secure_(is_parent_frame_secure), + client_info_(ServiceWorkerClientInfo()), + process_id_for_worker_client_(ChildProcessHost::kInvalidUniqueID), + ongoing_navigation_frame_tree_node_id_(frame_tree_node_id) { + DCHECK(context_); } -ServiceWorkerContainerHostForClient::ServiceWorkerContainerHostForClient( +ServiceWorkerClient::ServiceWorkerClient( base::WeakPtr<ServiceWorkerContextCore> context, int process_id, - mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> - container_remote, ServiceWorkerClientInfo client_info) - : ServiceWorkerContainerHost(std::move(context), - /*is_parent_frame_secure=*/true, - std::move(container_remote), - process_id) { + : context_(std::move(context)), + create_time_(base::TimeTicks::Now()), + client_uuid_(base::Uuid::GenerateRandomV4().AsLowercaseString()), + is_parent_frame_secure_(true), + client_info_(client_info), + process_id_for_worker_client_(process_id) { + DCHECK(context_); DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - client_uuid_ = base::Uuid::GenerateRandomV4().AsLowercaseString(); - client_info_ = client_info; - - DCHECK(IsContainerForWorkerClient()); DCHECK_NE(process_id_for_worker_client_, ChildProcessHost::kInvalidUniqueID); - DCHECK(container_.is_bound()); } -ServiceWorkerContainerHost::~ServiceWorkerContainerHost() { +ServiceWorkerClient::~ServiceWorkerClient() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (IsContainerForWindowClient()) { auto* rfh = RenderFrameHostImpl::FromID(GetRenderFrameHostId()); - if (rfh) + if (rfh) { rfh->RemoveServiceWorkerContainerHost(client_uuid()); + } } if (controller_) { - DCHECK(IsContainerForClient()); controller_->Uncontrol(client_uuid()); if (running_status_observer_) { @@ -263,17 +238,45 @@ controller_registration_.reset(); // Ensure callbacks awaiting execution ready are notified. - if (IsContainerForClient()) - RunExecutionReadyCallbacks(); + RunExecutionReadyCallbacks(); RemoveAllMatchingRegistrations(); } +ServiceWorkerContainerHost::~ServiceWorkerContainerHost() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); +} ServiceWorkerContainerHostForClient::~ServiceWorkerContainerHostForClient() = default; ServiceWorkerContainerHostForServiceWorker:: ~ServiceWorkerContainerHostForServiceWorker() = default; +ServiceWorkerContainerHostForClient::ServiceWorkerContainerHostForClient( + base::WeakPtr<ServiceWorkerClient> service_worker_client, + mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> + container_remote) + : service_worker_client_(std::move(service_worker_client)), + container_(std::move(container_remote)) { + CHECK(service_worker_client_); + DCHECK(container_.is_bound()); +} + +void ServiceWorkerContainerHostForClient::Create( + base::WeakPtr<ServiceWorkerClient> service_worker_client, + mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> + container_remote) { + service_worker_client->set_container_host( + std::make_unique<ServiceWorkerContainerHostForClient>( + service_worker_client, std::move(container_remote))); +} + +void ServiceWorkerClient::set_container_host( + std::unique_ptr<ServiceWorkerContainerHostForClient> container_host) { + CHECK(!container_host_); + CHECK(container_host); + container_host_ = std::move(container_host); +} + void ServiceWorkerContainerHostForClient::Register( const GURL& script_url, blink::mojom::ServiceWorkerRegistrationOptionsPtr options, @@ -292,14 +295,14 @@ return; } - if (!IsContainerForWindowClient()) { + if (!service_worker_client().IsContainerForWindowClient()) { mojo::ReportBadMessage(ServiceWorkerConsts::kBadMessageFromNonWindow); std::move(callback).Run(blink::mojom::ServiceWorkerErrorType::kUnknown, std::string(), nullptr); return; } - std::vector<GURL> urls = {url_, options->scope, script_url}; + std::vector<GURL> urls = {url(), options->scope, script_url}; if (!service_worker_security_utils::AllOriginsMatchAndCanAccessServiceWorkers( urls)) { mojo::ReportBadMessage(ServiceWorkerConsts::kBadMessageImproperOrigins); @@ -312,7 +315,7 @@ } if (!service_worker_security_utils:: - OriginCanRegisterServiceWorkerFromJavascript(url_)) { + OriginCanRegisterServiceWorkerFromJavascript(url())) { mojo::ReportBadMessage(ServiceWorkerConsts::kBadMessageImproperOrigins); // ReportBadMessage() will terminate the renderer process, but Mojo // complains if the callback is not run. Just run it with nonsense @@ -347,7 +350,8 @@ // process yet. This must be after commit so it should be populated, while // it's possible the RenderFrameHost has already been destroyed due to IPC // ordering. - GlobalRenderFrameHostId global_frame_id = GetRenderFrameHostId(); + GlobalRenderFrameHostId global_frame_id = + service_worker_client().GetRenderFrameHostId(); DCHECK_NE(global_frame_id.child_id, ChildProcessHost::kInvalidUniqueID); DCHECK_NE(global_frame_id.frame_routing_id, MSG_ROUTING_NONE); @@ -355,16 +359,17 @@ // is active, we need to make sure we get the correct key. const blink::StorageKey key = service_worker_security_utils::GetCorrectStorageKeyForWebSecurityState( - key_, options->scope); + service_worker_client().key(), options->scope); - context_->RegisterServiceWorker( + context()->RegisterServiceWorker( script_url, key, *options, std::move(outside_fetch_client_settings_object), base::BindOnce(&ServiceWorkerContainerHostForClient::RegistrationComplete, base::AsWeakPtr(this), GURL(script_url), GURL(options->scope), std::move(wrapped_callback), trace_id, mojo::GetBadMessageCallback()), - global_frame_id, policy_container_policies_.value()); + global_frame_id, + service_worker_client().policy_container_policies().value()); } void ServiceWorkerContainerHostForClient::GetRegistration( @@ -373,7 +378,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!CanServeContainerHostMethods( - &callback, url_, GURL(), + &callback, url(), GURL(), ServiceWorkerConsts::kServiceWorkerGetRegistrationErrorPrefix, nullptr)) { return; @@ -400,9 +405,9 @@ // make sure we get the correct key. const blink::StorageKey key = service_worker_security_utils::GetCorrectStorageKeyForWebSecurityState( - key_, client_url); + service_worker_client().key(), client_url); - context_->registry()->FindRegistrationForClientUrl( + context()->registry()->FindRegistrationForClientUrl( ServiceWorkerRegistry::Purpose::kNotForNavigation, client_url, key, base::BindOnce( &ServiceWorkerContainerHostForClient::GetRegistrationComplete, @@ -414,7 +419,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!CanServeContainerHostMethods( - &callback, url_, GURL(), + &callback, url(), GURL(), ServiceWorkerConsts::kServiceWorkerGetRegistrationsErrorPrefix, std::nullopt)) { return; @@ -435,10 +440,11 @@ "ServiceWorker", "ServiceWorkerContainerHost::GetRegistrations", TRACE_ID_WITH_SCOPE("ServiceWorkerContainerHost::GetRegistrations", trace_id)); - context_->registry()->GetRegistrationsForStorageKey( - key_, base::BindOnce( - &ServiceWorkerContainerHostForClient::GetRegistrationsComplete, - base::AsWeakPtr(this), std::move(callback), trace_id)); + context()->registry()->GetRegistrationsForStorageKey( + service_worker_client().key(), + base::BindOnce( + &ServiceWorkerContainerHostForClient::GetRegistrationsComplete, + base::AsWeakPtr(this), std::move(callback), trace_id)); } void ServiceWorkerContainerHostForClient::GetRegistrationForReady( @@ -468,15 +474,21 @@ blink::mojom::ControllerServiceWorkerPurpose purpose) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + service_worker_client().EnsureControllerServiceWorker(std::move(receiver), + purpose); +} + +void ServiceWorkerClient::EnsureControllerServiceWorker( + mojo::PendingReceiver<blink::mojom::ControllerServiceWorker> receiver, + blink::mojom::ControllerServiceWorkerPurpose purpose) { // TODO(kinuko): Log the reasons we drop the request. if (!context_ || !controller_) return; controller_->RunAfterStartWorker( PurposeToEventType(purpose), - base::BindOnce( - &ServiceWorkerContainerHostForClient::StartControllerComplete, - base::AsWeakPtr(this), std::move(receiver))); + base::BindOnce(&ServiceWorkerClient::StartControllerComplete, + base::AsWeakPtr(this), std::move(receiver))); } void ServiceWorkerContainerHost::CloneContainerHost( @@ -487,8 +499,10 @@ void ServiceWorkerContainerHostForClient::HintToUpdateServiceWorker() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(IsContainerForClient()); + service_worker_client().HintToUpdateServiceWorker(); +} +void ServiceWorkerClient::HintToUpdateServiceWorker() { // The destructors notify the ServiceWorkerVersions to update. versions_to_update_.clear(); } @@ -497,6 +511,13 @@ const std::vector<base::FilePath>& file_paths, EnsureFileAccessCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + service_worker_client().EnsureFileAccess(file_paths, std::move(callback)); +} + +void ServiceWorkerClient::EnsureFileAccess( + const std::vector<base::FilePath>& file_paths, + blink::mojom::ServiceWorkerContainerHost::EnsureFileAccessCallback + callback) { ServiceWorkerVersion* version = controller_registration_ ? controller_registration_->active_version() : nullptr; @@ -526,10 +547,13 @@ void ServiceWorkerContainerHostForClient::OnExecutionReady() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + service_worker_client().OnExecutionReady(); +} + +void ServiceWorkerClient::OnExecutionReady() { // Since `OnExecutionReady()` is a part of `ServiceWorkerContainerHost`, // this method is called only if `is_container_ready_` is true. CHECK(is_container_ready_); - CHECK(IsContainerForClient()); if (is_execution_ready()) { mojo::ReportBadMessage("SWPH_OER_ALREADY_READY"); @@ -612,7 +636,16 @@ mojo::ReportBadMessage("SWPH_OER_NOT_CLIENT"); } -void ServiceWorkerContainerHost::OnVersionAttributesChanged( +void ServiceWorkerClient::OnVersionAttributesChanged( + ServiceWorkerRegistration* registration, + blink::mojom::ChangedServiceWorkerObjectsMaskPtr changed_mask) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + container_host().OnVersionAttributesChanged(registration, + std::move(changed_mask)); +} + +void ServiceWorkerContainerHostForClient::OnVersionAttributesChanged( ServiceWorkerRegistration* registration, blink::mojom::ChangedServiceWorkerObjectsMaskPtr changed_mask) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -621,25 +654,26 @@ if (changed_mask->active && registration->active_version()) { // Wait until the state change so we don't send the get for ready // registration complete message before set version attributes message. - registration->active_version()->RegisterStatusChangeCallback(base::BindOnce( - &ServiceWorkerContainerHost::ReturnRegistrationForReadyIfNeeded, - base::AsWeakPtr(this))); + registration->active_version()->RegisterStatusChangeCallback( + base::BindOnce(&ServiceWorkerContainerHostForClient:: + ReturnRegistrationForReadyIfNeeded, + base::AsWeakPtr(this))); } } -void ServiceWorkerContainerHost::OnRegistrationFailed( +void ServiceWorkerClient::OnRegistrationFailed( ServiceWorkerRegistration* registration) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); RemoveMatchingRegistration(registration); } -void ServiceWorkerContainerHost::OnRegistrationFinishedUninstalling( +void ServiceWorkerClient::OnRegistrationFinishedUninstalling( ServiceWorkerRegistration* registration) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); RemoveMatchingRegistration(registration); } -void ServiceWorkerContainerHost::OnSkippedWaiting( +void ServiceWorkerClient::OnSkippedWaiting( ServiceWorkerRegistration* registration) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (controller_registration_ != registration) @@ -667,7 +701,7 @@ UpdateController(true /* notify_controllerchange */); } -void ServiceWorkerContainerHost::AddMatchingRegistration( +void ServiceWorkerClient::AddMatchingRegistration( ServiceWorkerRegistration* registration) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(blink::ServiceWorkerScopeMatches(registration->scope(), @@ -680,10 +714,11 @@ return; registration->AddListener(this); matching_registrations_[key] = registration; - ReturnRegistrationForReadyIfNeeded(); + + container_host().ReturnRegistrationForReadyIfNeeded(); } -void ServiceWorkerContainerHost::RemoveMatchingRegistration( +void ServiceWorkerClient::RemoveMatchingRegistration( ServiceWorkerRegistration* registration) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_NE(controller_registration_, registration); @@ -696,8 +731,7 @@ matching_registrations_.erase(key); } -ServiceWorkerRegistration* ServiceWorkerContainerHost::MatchRegistration() - const { +ServiceWorkerRegistration* ServiceWorkerClient::MatchRegistration() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); for (const auto& registration : base::Reversed(matching_registrations_)) { if (registration.second->is_uninstalled()) @@ -709,7 +743,7 @@ return nullptr; } -void ServiceWorkerContainerHost::AddServiceWorkerToUpdate( +void ServiceWorkerClient::AddServiceWorkerToUpdate( scoped_refptr<ServiceWorkerVersion> version) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -720,28 +754,34 @@ versions_to_update_.emplace(std::move(version)); } -void ServiceWorkerContainerHost::PostMessageToClient( +void ServiceWorkerClient::PostMessageToClient( ServiceWorkerVersion* version, blink::TransferableMessage message) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); base::WeakPtr<ServiceWorkerObjectHost> object_host = - version_object_manager().GetOrCreateHost(version); + container_host().version_object_manager().GetOrCreateHost(version); if (!is_container_ready_) { if (buffered_messages_.size() < kMaxBufferedMessageSize) { buffered_messages_.emplace_back(object_host, std::move(message)); } return; } + + container_host().PostMessageToClient(std::move(object_host), + std::move(message)); +} + +void ServiceWorkerContainerHostForClient::PostMessageToClient( + base::WeakPtr<ServiceWorkerObjectHost> object_host, + blink::TransferableMessage message) { blink::mojom::ServiceWorkerObjectInfoPtr info; if (object_host) info = object_host->CreateCompleteObjectInfoToSend(); container_->PostMessageToClient(std::move(info), std::move(message)); } -void ServiceWorkerContainerHost::CountFeature( - blink::mojom::WebFeature feature) { +void ServiceWorkerClient::CountFeature(blink::mojom::WebFeature feature) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); SCOPED_CRASH_KEY_NUMBER("SWCH_CF", "feature", static_cast<int32_t>(feature)); SCOPED_CRASH_KEY_NUMBER("SWCH_CF", "client_type", @@ -749,10 +789,6 @@ constexpr char kDropOutMetrics[] = "ServiceWorker.CountFeature.DropOut"; - // CountFeature is a message about the client's controller. It should be sent - // only for clients. - DCHECK(IsContainerForClient()); - // `container_` can be used only if ServiceWorkerContainerInfoForClient has // been passed to the renderer process. Otherwise, the method call will crash // inside the mojo library (See crbug.com/40918057). @@ -771,6 +807,13 @@ return; } + container_host().CountFeature(feature); +} + +void ServiceWorkerContainerHostForClient::CountFeature( + blink::mojom::WebFeature feature) { + constexpr char kDropOutMetrics[] = "ServiceWorker.CountFeature.DropOut"; + // `container_` shouldn't be disconnected during the lifetime of `this` but // there seems a situation where `container_` is disconnected or unbound. // TODO(crbug.com/1136843, crbug.com/40918057): Figure out the cause and @@ -787,7 +830,7 @@ } blink::mojom::ControllerServiceWorkerInfoPtr -ServiceWorkerContainerHost::CreateControllerServiceWorkerInfo() { +ServiceWorkerClient::CreateControllerServiceWorkerInfo() { CHECK(controller()); auto controller_info = blink::mojom::ControllerServiceWorkerInfo::New(); @@ -841,10 +884,9 @@ return controller_info; } -void ServiceWorkerContainerHost::SendSetControllerServiceWorker( +void ServiceWorkerClient::SendSetControllerServiceWorker( bool notify_controllerchange) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); CHECK(is_container_ready_); if (!controller_ || !context_) { @@ -863,8 +905,8 @@ // renderer side, setController as no-controller. auto controller_info = blink::mojom::ControllerServiceWorkerInfo::New(); controller_info->client_id = client_uuid(); - container_->SetController(std::move(controller_info), - notify_controllerchange); + container_host().SendSetController(std::move(controller_info), + notify_controllerchange); return; } @@ -875,7 +917,8 @@ // Set the info for the JavaScript ServiceWorkerContainer#controller object. if (base::WeakPtr<ServiceWorkerObjectHost> object_host = - version_object_manager().GetOrCreateHost(controller())) { + container_host().version_object_manager().GetOrCreateHost( + controller())) { controller_info->object_info = object_host->CreateCompleteObjectInfoToSend(); } @@ -883,21 +926,28 @@ // TODO(crbug.com/331279951): Remove these crash keys after investigation. SCOPED_CRASH_KEY_NUMBER("SWCH_SC", "client_type", static_cast<int32_t>(GetClientType())); + SCOPED_CRASH_KEY_BOOL("SWCH_SC", "is_execution_ready", is_execution_ready()); + SCOPED_CRASH_KEY_BOOL("SWCH_SC", "is_container_ready", is_container_ready_); + + container_host().SendSetController(std::move(controller_info), + notify_controllerchange); +} + +void ServiceWorkerContainerHostForClient::SendSetController( + blink::mojom::ControllerServiceWorkerInfoPtr controller_info, + bool notify_controllerchange) { + // TODO(crbug.com/331279951): Remove these crash keys after investigation. SCOPED_CRASH_KEY_BOOL("SWCH_SC", "is_bound", container_.is_bound()); SCOPED_CRASH_KEY_BOOL("SWCH_SC", "is_connected", container_.is_bound() && container_.is_connected()); SCOPED_CRASH_KEY_BOOL("SWCH_SC", "notify_controllerchange", notify_controllerchange); - SCOPED_CRASH_KEY_BOOL("SWCH_SC", "IsContainerForClient", - IsContainerForClient()); - SCOPED_CRASH_KEY_BOOL("SWCH_SC", "is_execution_ready", is_execution_ready()); - SCOPED_CRASH_KEY_BOOL("SWCH_SC", "is_container_ready", is_container_ready_); container_->SetController(std::move(controller_info), notify_controllerchange); } -void ServiceWorkerContainerHost::NotifyControllerLost() { +void ServiceWorkerClient::NotifyControllerLost() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (IsBackForwardCacheEnabled() && IsInBackForwardCache()) { // The controller was unregistered, which usually does not happen while it @@ -911,10 +961,9 @@ SetControllerRegistration(nullptr, true /* notify_controllerchange */); } -void ServiceWorkerContainerHost::ClaimedByRegistration( +void ServiceWorkerClient::ClaimedByRegistration( scoped_refptr<ServiceWorkerRegistration> registration) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); DCHECK(registration->active_version()); DCHECK(is_execution_ready()); @@ -1039,13 +1088,8 @@ service_worker_object_hosts_.erase(version_id); } -bool ServiceWorkerContainerHost::IsContainerForClient() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return client_info_ != std::nullopt; -} - -blink::mojom::ServiceWorkerClientType -ServiceWorkerContainerHost::GetClientType() const { +blink::mojom::ServiceWorkerClientType ServiceWorkerClient::GetClientType() + const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(client_info_); return absl::visit( @@ -1062,13 +1106,13 @@ *client_info_); } -bool ServiceWorkerContainerHost::IsContainerForWindowClient() const { +bool ServiceWorkerClient::IsContainerForWindowClient() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return client_info_ && absl::holds_alternative<GlobalRenderFrameHostId>(*client_info_); } -bool ServiceWorkerContainerHost::IsContainerForWorkerClient() const { +bool ServiceWorkerClient::IsContainerForWorkerClient() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); using blink::mojom::ServiceWorkerClientType; if (!client_info_) @@ -1078,15 +1122,13 @@ absl::holds_alternative<blink::SharedWorkerToken>(*client_info_); } -ServiceWorkerClientInfo ServiceWorkerContainerHost::GetServiceWorkerClientInfo() +ServiceWorkerClientInfo ServiceWorkerClient::GetServiceWorkerClientInfo() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); - return *client_info_; } -void ServiceWorkerContainerHost::OnBeginNavigationCommit( +void ServiceWorkerClient::OnBeginNavigationCommit( const GlobalRenderFrameHostId& rfh_id, const PolicyContainerPolicies& policy_container_policies, mojo::PendingRemote<network::mojom::CrossOriginEmbedderPolicyReporter> @@ -1131,7 +1173,7 @@ TransitionToClientPhase(ClientPhase::kResponseCommitted); } -void ServiceWorkerContainerHost::OnEndNavigationCommit() { +void ServiceWorkerClient::OnEndNavigationCommit() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsContainerForWindowClient()); @@ -1144,7 +1186,7 @@ } } -void ServiceWorkerContainerHost::CompleteWebWorkerPreparation( +void ServiceWorkerClient::CompleteWebWorkerPreparation( const PolicyContainerPolicies& policy_container_policies, ukm::SourceId worker_ukm_source_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -1169,19 +1211,7 @@ SetExecutionReady(); } -void ServiceWorkerContainerHostForServiceWorker::UpdateUrls( - const GURL& url, - const std::optional<url::Origin>& top_frame_origin, - const blink::StorageKey& storage_key) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(!url.has_ref()); - url_ = url; - top_frame_origin_ = top_frame_origin; - key_ = storage_key; - service_worker_security_utils::CheckOnUpdateUrls(url, key_); -} - -void ServiceWorkerContainerHostForClient::UpdateUrls( +void ServiceWorkerClient::UpdateUrls( const GURL& url, const std::optional<url::Origin>& top_frame_origin, const blink::StorageKey& storage_key) { @@ -1227,11 +1257,10 @@ SyncMatchingRegistrations(); } -void ServiceWorkerContainerHost::SetControllerRegistration( +void ServiceWorkerClient::SetControllerRegistration( scoped_refptr<ServiceWorkerRegistration> controller_registration, bool notify_controllerchange) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); if (controller_registration) { CHECK(IsEligibleForServiceWorkerController()); @@ -1246,9 +1275,8 @@ } mojo::Remote<blink::mojom::ControllerServiceWorker> -ServiceWorkerContainerHost::GetRemoteControllerServiceWorker() { +ServiceWorkerClient::GetRemoteControllerServiceWorker() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); DCHECK(controller_); if (controller_->fetch_handler_existence() == @@ -1290,8 +1318,8 @@ const GURL& scope, const GURL& script_url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(context_); - auto* browser_context = context_->wrapper()->browser_context(); + DCHECK(context()); + auto* browser_context = context()->wrapper()->browser_context(); // Check that the browser context is not nullptr. It becomes nullptr // when the service worker process manager is being shutdown. if (!browser_context) { @@ -1299,14 +1327,19 @@ } AllowServiceWorkerResult allowed = GetContentClient()->browser()->AllowServiceWorker( - scope, service_worker_security_utils::site_for_cookies(key_), - top_frame_origin(), script_url, browser_context); - if (IsContainerForWindowClient()) { - auto* rfh = RenderFrameHostImpl::FromID(GetRenderFrameHostId()); + scope, + service_worker_security_utils::site_for_cookies( + service_worker_client().key()), + service_worker_client().top_frame_origin(), script_url, + browser_context); + if (service_worker_client().IsContainerForWindowClient()) { + auto* rfh = RenderFrameHostImpl::FromID( + service_worker_client().GetRenderFrameHostId()); auto* web_contents = static_cast<WebContentsImpl*>(WebContents::FromRenderFrameHost(rfh)); - if (web_contents) + if (web_contents) { web_contents->OnServiceWorkerAccessed(rfh, scope, allowed); + } } return allowed; } @@ -1315,8 +1348,8 @@ const GURL& scope, const GURL& script_url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(context_); - auto* browser_context = context_->wrapper()->browser_context(); + DCHECK(context()); + auto* browser_context = context()->wrapper()->browser_context(); // Check that the browser context is not nullptr. It becomes nullptr // when the service worker process manager is being shutdown. if (!browser_context) { @@ -1327,9 +1360,8 @@ top_frame_origin(), script_url, browser_context); } -bool ServiceWorkerContainerHost::IsEligibleForServiceWorkerController() const { +bool ServiceWorkerClient::IsEligibleForServiceWorkerController() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); if (!url_.is_valid()) return false; @@ -1351,9 +1383,8 @@ return schemes.find(url_.scheme()) != schemes.end(); } -bool ServiceWorkerContainerHost::is_response_committed() const { +bool ServiceWorkerClient::is_response_committed() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); switch (client_phase_) { case ClientPhase::kInitial: return false; @@ -1361,34 +1392,27 @@ case ClientPhase::kExecutionReady: return true; } - NOTREACHED(); - return false; } -void ServiceWorkerContainerHost::AddExecutionReadyCallback( +void ServiceWorkerClient::AddExecutionReadyCallback( ExecutionReadyCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); - DCHECK(!is_execution_ready()); execution_ready_callbacks_.push_back(std::move(callback)); } -bool ServiceWorkerContainerHost::is_execution_ready() const { +bool ServiceWorkerClient::is_execution_ready() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); - return client_phase_ == ClientPhase::kExecutionReady; } -GlobalRenderFrameHostId ServiceWorkerContainerHost::GetRenderFrameHostId() - const { +GlobalRenderFrameHostId ServiceWorkerClient::GetRenderFrameHostId() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsContainerForWindowClient()); return absl::get<GlobalRenderFrameHostId>(*client_info_); } -int ServiceWorkerContainerHost::GetProcessId() const { +int ServiceWorkerClient::GetProcessId() const { if (IsContainerForWindowClient()) { return GetRenderFrameHostId().child_id; } @@ -1396,8 +1420,7 @@ return process_id_for_worker_client_; } -NavigationRequest* -ServiceWorkerContainerHost::GetOngoingNavigationRequestBeforeCommit( +NavigationRequest* ServiceWorkerClient::GetOngoingNavigationRequestBeforeCommit( base::PassKey<StoragePartitionImpl>) const { DCHECK(IsContainerForWindowClient()); DCHECK_NE(ongoing_navigation_frame_tree_node_id_, @@ -1419,16 +1442,14 @@ return frame_tree_node ? frame_tree_node->navigation_request() : nullptr; } -const std::string& ServiceWorkerContainerHost::client_uuid() const { +const std::string& ServiceWorkerClient::client_uuid() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); return client_uuid_; } blink::mojom::ControllerServiceWorkerMode -ServiceWorkerContainerHost::GetControllerMode() const { +ServiceWorkerClient::GetControllerMode() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); if (!controller_) return blink::mojom::ControllerServiceWorkerMode::kNoController; switch (controller_->fetch_handler_existence()) { @@ -1445,7 +1466,7 @@ return blink::mojom::ControllerServiceWorkerMode::kNoController; } -ServiceWorkerVersion* ServiceWorkerContainerHost::controller() const { +ServiceWorkerVersion* ServiceWorkerClient::controller() const { #if DCHECK_IS_ON() DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CheckControllerConsistency(false); @@ -1453,7 +1474,7 @@ return controller_.get(); } -ServiceWorkerRegistration* ServiceWorkerContainerHost::controller_registration() +ServiceWorkerRegistration* ServiceWorkerClient::controller_registration() const { #if DCHECK_IS_ON() DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -1462,22 +1483,55 @@ return controller_registration_.get(); } +const base::WeakPtr<ServiceWorkerContextCore>& +ServiceWorkerContainerHostForClient::context() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return service_worker_client().context(); +} + +const GURL& ServiceWorkerContainerHostForClient::url() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return service_worker_client().url(); +} + +const base::WeakPtr<ServiceWorkerContextCore>& +ServiceWorkerContainerHostForServiceWorker::context() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return context_; +} + +const GURL& ServiceWorkerContainerHostForServiceWorker::url() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return url_; +} + ServiceWorkerHost* ServiceWorkerContainerHostForServiceWorker::service_worker_host() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return service_worker_host_; } -bool ServiceWorkerContainerHost::IsInBackForwardCache() const { +const blink::StorageKey& ServiceWorkerContainerHostForServiceWorker::key() + const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return key_; +} + +const url::Origin& +ServiceWorkerContainerHostForServiceWorker::top_frame_origin() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return top_frame_origin_; +} + +bool ServiceWorkerClient::IsInBackForwardCache() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return is_in_back_forward_cache_; } -void ServiceWorkerContainerHost::EvictFromBackForwardCache( +void ServiceWorkerClient::EvictFromBackForwardCache( BackForwardCacheMetrics::NotRestoredReason reason) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsBackForwardCacheEnabled()); - DCHECK(IsContainerForClient()); is_in_back_forward_cache_ = false; if (!IsContainerForWindowClient()) @@ -1489,25 +1543,23 @@ rfh->EvictFromBackForwardCacheWithReason(reason); } -void ServiceWorkerContainerHost::OnEnterBackForwardCache() { +void ServiceWorkerClient::OnEnterBackForwardCache() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsBackForwardCacheEnabled()); - DCHECK(IsContainerForClient()); if (controller_) controller_->MoveControlleeToBackForwardCacheMap(client_uuid()); is_in_back_forward_cache_ = true; } -void ServiceWorkerContainerHost::OnRestoreFromBackForwardCache() { +void ServiceWorkerClient::OnRestoreFromBackForwardCache() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(IsBackForwardCacheEnabled()); - DCHECK(IsContainerForClient()); if (controller_) controller_->RestoreControlleeFromBackForwardCacheMap(client_uuid()); is_in_back_forward_cache_ = false; } -void ServiceWorkerContainerHost::SyncMatchingRegistrations() { +void ServiceWorkerClient::SyncMatchingRegistrations() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!controller_registration_); @@ -1526,7 +1578,7 @@ } #if DCHECK_IS_ON() -bool ServiceWorkerContainerHost::IsMatchingRegistration( +bool ServiceWorkerClient::IsMatchingRegistration( ServiceWorkerRegistration* registration) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::string spec = registration->scope().spec(); @@ -1541,7 +1593,7 @@ } #endif // DCHECK_IS_ON() -void ServiceWorkerContainerHost::RemoveAllMatchingRegistrations() { +void ServiceWorkerClient::RemoveAllMatchingRegistrations() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!controller_registration_); for (const auto& it : matching_registrations_) { @@ -1551,17 +1603,18 @@ matching_registrations_.clear(); } -void ServiceWorkerContainerHost::ReturnRegistrationForReadyIfNeeded() { +void ServiceWorkerContainerHostForClient::ReturnRegistrationForReadyIfNeeded() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!get_ready_callback_ || get_ready_callback_->is_null()) return; - ServiceWorkerRegistration* registration = MatchRegistration(); + ServiceWorkerRegistration* registration = + service_worker_client().MatchRegistration(); if (!registration || !registration->active_version()) return; TRACE_EVENT_NESTABLE_ASYNC_END1( "ServiceWorker", "ServiceWorkerContainerHost::GetRegistrationForReady", TRACE_ID_LOCAL(this), "Registration ID", registration->id()); - if (!context_) { + if (!context()) { // Here no need to run or destroy |get_ready_callback_|, which will destroy // together with |receiver_| when |this| destroys. return; @@ -1572,7 +1625,7 @@ scoped_refptr<ServiceWorkerRegistration>(registration))); } -void ServiceWorkerContainerHost::SetExecutionReady() { +void ServiceWorkerClient::SetExecutionReady() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!is_execution_ready()); TransitionToClientPhase(ClientPhase::kExecutionReady); @@ -1584,9 +1637,8 @@ FlushFeatures(); } -void ServiceWorkerContainerHost::RunExecutionReadyCallbacks() { +void ServiceWorkerClient::RunExecutionReadyCallbacks() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); std::vector<ExecutionReadyCallback> callbacks; execution_ready_callbacks_.swap(callbacks); @@ -1594,8 +1646,7 @@ FROM_HERE, base::BindOnce(&RunCallbacks, std::move(callbacks))); } -void ServiceWorkerContainerHost::TransitionToClientPhase( - ClientPhase new_phase) { +void ServiceWorkerClient::TransitionToClientPhase(ClientPhase new_phase) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (client_phase_ == new_phase) return; @@ -1613,8 +1664,7 @@ client_phase_ = new_phase; } -void ServiceWorkerContainerHost::UpdateController( - bool notify_controllerchange) { +void ServiceWorkerClient::UpdateController(bool notify_controllerchange) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); ServiceWorkerVersion* version = controller_registration_ ? controller_registration_->active_version() @@ -1653,9 +1703,6 @@ } } - // SetController message should be sent only for clients. - DCHECK(IsContainerForClient()); - // No need to `SetController` if the container is not ready because // when the container gets ready, `ControllerServiceWorkerInfoPtr` is also // sent in the same IPC call. Moreover, it is harmful to resend the past @@ -1673,15 +1720,13 @@ } #if DCHECK_IS_ON() -void ServiceWorkerContainerHost::CheckControllerConsistency( - bool should_crash) const { +void ServiceWorkerClient::CheckControllerConsistency(bool should_crash) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!controller_) { DCHECK(!controller_registration_); return; } - DCHECK(IsContainerForClient()); DCHECK(controller_registration_); DCHECK_EQ(controller_->registration_id(), controller_registration_->id()); @@ -1710,11 +1755,10 @@ } #endif // DCHECK_IS_ON() -void ServiceWorkerContainerHostForClient::StartControllerComplete( +void ServiceWorkerClient::StartControllerComplete( mojo::PendingReceiver<blink::mojom::ControllerServiceWorker> receiver, blink::ServiceWorkerStatusCode status) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); if (status == blink::ServiceWorkerStatusCode::kOk) { DCHECK(is_response_committed()); @@ -1766,7 +1810,7 @@ return; } - if (!context_) { + if (!context()) { std::move(callback).Run( blink::mojom::ServiceWorkerErrorType::kAbort, base::StringPrintf( @@ -1793,7 +1837,7 @@ } scoped_refptr<ServiceWorkerRegistration> registration = - context_->GetLiveRegistration(registration_id); + context()->GetLiveRegistration(registration_id); // ServiceWorkerRegisterJob calls its completion callback, which results in // this function being called, while the registration is live. DCHECK(registration); @@ -1819,7 +1863,7 @@ registration ? registration->id() : blink::mojom::kInvalidServiceWorkerRegistrationId); - if (!context_) { + if (!context()) { std::move(callback).Run( blink::mojom::ServiceWorkerErrorType::kAbort, std::string( @@ -1868,7 +1912,7 @@ trace_id), "Status", blink::ServiceWorkerStatusToString(status)); - if (!context_) { + if (!context()) { std::move(callback).Run( blink::mojom::ServiceWorkerErrorType::kAbort, std::string( @@ -1919,7 +1963,7 @@ const GURL& client_url, std::string* out_error) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!IsContainerForWindowClient()) { + if (!service_worker_client().IsContainerForWindowClient()) { *out_error = ServiceWorkerConsts::kBadMessageFromNonWindow; return false; } @@ -1927,7 +1971,7 @@ *out_error = ServiceWorkerConsts::kBadMessageInvalidURL; return false; } - std::vector<GURL> urls = {url_, client_url}; + std::vector<GURL> urls = {url(), client_url}; if (!service_worker_security_utils::AllOriginsMatchAndCanAccessServiceWorkers( urls)) { *out_error = ServiceWorkerConsts::kBadMessageImproperOrigins; @@ -1940,11 +1984,11 @@ bool ServiceWorkerContainerHostForClient::IsValidGetRegistrationsMessage( std::string* out_error) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!IsContainerForWindowClient()) { + if (!service_worker_client().IsContainerForWindowClient()) { *out_error = ServiceWorkerConsts::kBadMessageFromNonWindow; return false; } - if (!OriginCanAccessServiceWorkers(url_)) { + if (!OriginCanAccessServiceWorkers(url())) { *out_error = ServiceWorkerConsts::kBadMessageImproperOrigins; return false; } @@ -1955,7 +1999,7 @@ bool ServiceWorkerContainerHostForClient::IsValidGetRegistrationForReadyMessage( std::string* out_error) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!IsContainerForWindowClient()) { + if (!service_worker_client().IsContainerForWindowClient()) { *out_error = ServiceWorkerConsts::kBadMessageFromNonWindow; return false; } @@ -1977,7 +2021,7 @@ const char* error_prefix, Args... args) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!context_) { + if (!context()) { std::move(*callback).Run( blink::mojom::ServiceWorkerErrorType::kAbort, std::string(error_prefix) + @@ -1988,7 +2032,7 @@ // TODO(falken): This check can be removed once crbug.com/439697 is fixed. // (Also see crbug.com/776408) - if (url_.is_empty()) { + if (url().is_empty()) { std::move(*callback).Run( blink::mojom::ServiceWorkerErrorType::kSecurity, std::string(error_prefix) + @@ -2009,18 +2053,16 @@ return true; } -const GURL& ServiceWorkerContainerHost::GetUrlForScopeMatch() const { - DCHECK(IsContainerForClient()); +const GURL& ServiceWorkerClient::GetUrlForScopeMatch() const { if (!scope_match_url_for_blob_client_.is_empty()) return scope_match_url_for_blob_client_; return url_; } -void ServiceWorkerContainerHost::InheritControllerFrom( - ServiceWorkerContainerHost& creator_host, +void ServiceWorkerClient::InheritControllerFrom( + ServiceWorkerClient& creator_host, const GURL& blob_url) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); DCHECK(base::FeatureList::IsEnabled(kSharedWorkerBlobURLFix) || blink::mojom::ServiceWorkerClientType::kDedicatedWorker == GetClientType()); @@ -2042,9 +2084,8 @@ } mojo::PendingRemote<blink::mojom::CacheStorage> -ServiceWorkerContainerHost::GetRemoteCacheStorage() { +ServiceWorkerClient::GetRemoteCacheStorage() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK(IsContainerForClient()); DCHECK(controller_); auto* control = GetCacheStorageControl(controller_); @@ -2072,12 +2113,12 @@ } mojo::PendingReceiver<blink::mojom::ServiceWorkerRunningStatusCallback> -ServiceWorkerContainerHost::GetRunningStatusCallbackReceiver() { +ServiceWorkerClient::GetRunningStatusCallbackReceiver() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CHECK(controller_); if (!running_status_observer_) { - running_status_observer_ = absl::make_unique< - ServiceWorkerContainerHost::ServiceWorkerRunningStatusObserver>(); + running_status_observer_ = + absl::make_unique<ServiceWorkerRunningStatusObserver>(); controller_->AddObserver(running_status_observer_.get()); } mojo::PendingRemote<blink::mojom::ServiceWorkerRunningStatusCallback> @@ -2087,12 +2128,11 @@ return receiver; } -SubresourceLoaderParams -ServiceWorkerContainerHost::MaybeCreateSubresourceLoaderParams( - base::WeakPtr<ServiceWorkerContainerHost> container_host) { +SubresourceLoaderParams ServiceWorkerClient::MaybeCreateSubresourceLoaderParams( + base::WeakPtr<ServiceWorkerClient> service_worker_client) { // We didn't find a matching service worker for this request, and // ServiceWorkerContainerHost::SetControllerRegistration() was not called. - if (!container_host || !container_host->controller()) { + if (!service_worker_client || !service_worker_client->controller()) { return {}; } @@ -2100,20 +2140,21 @@ // with the navigation commit. SubresourceLoaderParams params; params.controller_service_worker_info = - container_host->CreateControllerServiceWorkerInfo(); + service_worker_client->CreateControllerServiceWorkerInfo(); if (base::WeakPtr<ServiceWorkerObjectHost> object_host = - container_host->version_object_manager().GetOrCreateHost( - container_host->controller())) { + service_worker_client->container_host() + .version_object_manager() + .GetOrCreateHost(service_worker_client->controller())) { params.controller_service_worker_object_host = object_host; params.controller_service_worker_info->object_info = object_host->CreateIncompleteObjectInfo(); } - params.container_host = container_host; + params.service_worker_client = service_worker_client; return params; } -void ServiceWorkerContainerHost::SetContainerReady() { +void ServiceWorkerClient::SetContainerReady() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); is_container_ready_ = true; std::vector<std::tuple<base::WeakPtr<ServiceWorkerObjectHost>, @@ -2124,18 +2165,15 @@ base::UmaHistogramCounts1000("ServiceWorker.PostMessage.QueueSize", messages.size()); for (auto& [object_host, message] : messages) { - blink::mojom::ServiceWorkerObjectInfoPtr info; - if (object_host) { - info = object_host->CreateCompleteObjectInfoToSend(); - } - container_->PostMessageToClient(std::move(info), std::move(message)); + container_host().PostMessageToClient(std::move(object_host), + std::move(message)); } CHECK(buffered_messages_.empty()); FlushFeatures(); } -void ServiceWorkerContainerHost::FlushFeatures() { +void ServiceWorkerClient::FlushFeatures() { std::set<blink::mojom::WebFeature> features; features.swap(buffered_used_features_); for (const auto& feature : features) { @@ -2345,13 +2383,14 @@ scoped_refptr<ServiceWorkerVersion> version, ::blink::TransferableMessage message, StatusCallback callback) { - if (IsContainerForWindowClient()) { + if (service_worker_client().IsContainerForWindowClient()) { service_worker_client_utils::GetClient( - this, base::BindOnce(&DispatchExtendableMessageEventFromClient, - context(), std::move(version), std::move(message), - url::Origin::Create(url()), std::move(callback))); + &service_worker_client(), + base::BindOnce(&DispatchExtendableMessageEventFromClient, context(), + std::move(version), std::move(message), + url::Origin::Create(url()), std::move(callback))); } else { - DCHECK(IsContainerForWorkerClient()); + DCHECK(service_worker_client().IsContainerForWorkerClient()); // Web workers don't yet have access to ServiceWorker objects, so they // can't postMessage to one (https://crbug.com/371690).
diff --git a/content/browser/service_worker/service_worker_container_host.h b/content/browser/service_worker/service_worker_container_host.h index eb570a2..db73d976 100644 --- a/content/browser/service_worker/service_worker_container_host.h +++ b/content/browser/service_worker/service_worker_container_host.h
@@ -144,46 +144,46 @@ SEQUENCE_CHECKER(sequence_checker_); }; -// ServiceWorkerContainerHost is the host of a service worker client -// (`ServiceWorkerContainerHostForClient`: a window, dedicated worker, or shared -// worker) or service worker execution context -// (`ServiceWorkerContainerHostForServiceWorker` in the renderer process. +// `ServiceWorkerClient` is owned by `ServiceWorkerContextCore` and represents a +// service worker client in the spec. +// https://w3c.github.io/ServiceWorker/#dfn-service-worker-client // -// Most of its functionality helps implement the web-exposed -// ServiceWorkerContainer interface (navigator.serviceWorker). The long-term -// goal is for it to be the host of ServiceWorkerContainer in the renderer, -// although currently only windows support ServiceWorkerContainers (see -// https://crbug.com/371690). +// TODO(https://crbug.com/336154571): Move this to a separate file. // -// ServiceWorkerContainerHost is also responsible for handling service worker -// related things in the execution context where the container lives. For -// example, the container host manages service worker (registration) JavaScript -// object hosts, delivers messages to/from the service worker, and dispatches -// events on the container. -// -// TODO(crbug.com/336154571): Migrate the members specific to clients or service -// worker execution contexts to -// ServiceWorkerContainerHostFor{Client,ServiceWorker} subclasses. -class CONTENT_EXPORT ServiceWorkerContainerHost - : public blink::mojom::ServiceWorkerContainerHost, - public ServiceWorkerRegistration::Listener, - public base::SupportsWeakPtr<ServiceWorkerContainerHost> { +// Example: +// When a new service worker registration is created, the browser process +// iterates over all ServiceWorkerClients to find clients (frames, +// dedicated workers if PlzDedicatedWorker is enabled, and shared workers) with +// a URL inside the registration's scope, and has the container host watch the +// registration in order to resolve navigator.serviceWorker.ready once the +// registration settles, if need. +class CONTENT_EXPORT ServiceWorkerClient final + : public ServiceWorkerRegistration::Listener, + public base::SupportsWeakPtr<ServiceWorkerClient> { public: using ExecutionReadyCallback = base::OnceClosure; - ~ServiceWorkerContainerHost() override; + // Constructor for window clients. + ServiceWorkerClient(base::WeakPtr<ServiceWorkerContextCore> context, + bool is_parent_frame_secure, + int frame_tree_node_id); - ServiceWorkerContainerHost(const ServiceWorkerContainerHost& other) = delete; - ServiceWorkerContainerHost& operator=( - const ServiceWorkerContainerHost& other) = delete; - ServiceWorkerContainerHost(ServiceWorkerContainerHost&& other) = delete; - ServiceWorkerContainerHost& operator=(ServiceWorkerContainerHost&& other) = - delete; + // Constructor for worker clients. + ServiceWorkerClient(base::WeakPtr<ServiceWorkerContextCore> context, + int process_id, + ServiceWorkerClientInfo client_info); - // Implements blink::mojom::ServiceWorkerContainerHost. - void CloneContainerHost( - mojo::PendingReceiver<blink::mojom::ServiceWorkerContainerHost> receiver) - override; + ServiceWorkerClient(const ServiceWorkerClient& other) = delete; + ServiceWorkerClient& operator=(const ServiceWorkerClient& other) = delete; + + virtual ~ServiceWorkerClient(); + + ServiceWorkerContainerHostForClient& container_host() { + return *container_host_; + } + + void set_container_host( + std::unique_ptr<ServiceWorkerContainerHostForClient> container_host); // ServiceWorkerRegistration::Listener overrides. void OnVersionAttributesChanged( @@ -245,9 +245,6 @@ // script cache. void NotifyControllerLost(); - // Returns true if this container host is for a service worker client. - bool IsContainerForClient() const; - // Returns the client type of this container host. Can only be called when // IsContainerForClient() is true. blink::mojom::ServiceWorkerClientType GetClientType() const; @@ -289,19 +286,9 @@ const PolicyContainerPolicies& cross_origin_embedder_policy, ukm::SourceId worker_ukm_source_id); - // Sets the URL and storage key for the owner of this container. - // - // For a ServiceWorkerContainerHost representing a service worker - // (IsContainerForServiceWorker()), the URL is the service worker's script; - // for all other clients (IsContainerForClient()), it is the main resource. - // - // The top_frame_origin is the origin of the top frame of the client, or for a - // service worker the origin of the service worker's scope URL. This is more - // specific than the `top_frame_site` in the storage key, so must be passed - // separately. - virtual void UpdateUrls(const GURL& url, - const std::optional<url::Origin>& top_frame_origin, - const blink::StorageKey& storage_key) = 0; + void UpdateUrls(const GURL& url, + const std::optional<url::Origin>& top_frame_origin, + const blink::StorageKey& storage_key); // For service worker clients. Makes this client be controlled by // |registration|'s active worker, or makes this client be not @@ -362,22 +349,20 @@ void ClaimedByRegistration( scoped_refptr<ServiceWorkerRegistration> registration); - // The URL of this context. For service worker clients, this is the document - // URL (for documents) or script URL (for workers). For service worker - // execution contexts, this is the script URL. + // The URL of the main resource of the client: the document URL (for + // documents) or script URL (for workers). // - // For clients, url() may be empty if loading has not started, or our custom - // loading handler didn't see the load (because e.g. another handler did - // first, or the initial request URL was such that - // OriginCanAccessServiceWorkers returned false). + // url() may be empty if loading has not started, or our custom loading + // handler didn't see the load (because e.g. another handler did first, or the + // initial request URL was such that OriginCanAccessServiceWorkers returned + // false). // // The URL may also change on redirects during loading. Once // is_response_committed() is true, the URL should no longer change. const GURL& url() const { return url_; } - // The URL representing the first-party site for this context. - // For service worker execution contexts, top_frame_origin() always - // returns the origin of the service worker scope's URL. + // The origin of the top frame of the client. This is more specific than the + // `top_frame_site` in the storage key, so must be passed separately. // For shared worker it is the origin of the document that created the worker. // For dedicated worker it is the top-frame origin of the document that owns // the worker. @@ -393,14 +378,6 @@ // and its usages for more details. const blink::StorageKey& key() const { return key_; } - // Calls ContentBrowserClient::AllowServiceWorker(). Returns true if content - // settings allows service workers to run at |scope|. If this container is for - // a window client, the check involves the topmost frame url as well as - // |scope|, and may display tab-level UI. - // If non-empty, |script_url| is the script the service worker will run. - virtual bool AllowServiceWorker(const GURL& scope, - const GURL& script_url) = 0; - // Returns whether this container host is secure enough to have a service // worker controller. // Analogous to Blink's Document::IsSecureContext. Because of how service @@ -494,14 +471,14 @@ // For service worker clients that are dedicated workers. Inherits the // controller of the creator document or worker. Used when the client was // created with a blob URL. - void InheritControllerFrom(ServiceWorkerContainerHost& creator_host, + void InheritControllerFrom(ServiceWorkerClient& creator_host, const GURL& blob_url); // Returns params with the ControllerServiceWorkerInfoPtr if we have found // a matching controller service worker for non-null |container_host|. // Otherwise this returns std::nullopt. static SubresourceLoaderParams MaybeCreateSubresourceLoaderParams( - base::WeakPtr<ServiceWorkerContainerHost> container_host); + base::WeakPtr<ServiceWorkerClient> service_worker_client); ukm::SourceId ukm_source_id() const { return ukm_source_id_; } @@ -510,43 +487,32 @@ bool is_inherited() const { return is_inherited_; } void SetInherited() { is_inherited_ = true; } - const base::WeakPtr<ServiceWorkerContextCore>& context() { return context_; } - - ServiceWorkerRegistrationObjectManager& registration_object_manager() { - return registration_object_manager_; - } - ServiceWorkerObjectManager& version_object_manager() { - return version_object_manager_; + const base::WeakPtr<ServiceWorkerContextCore>& context() const { + return context_; } - using StatusCallback = - base::OnceCallback<void(blink::ServiceWorkerStatusCode)>; - virtual void DispatchExtendableMessageEvent( - scoped_refptr<ServiceWorkerVersion> version, - ::blink::TransferableMessage message, - StatusCallback callback) = 0; - virtual void Update( - scoped_refptr<ServiceWorkerRegistration> registration, - blink::mojom::FetchClientSettingsObjectPtr - outside_fetch_client_settings_object, - blink::mojom::ServiceWorkerRegistrationObjectHost::UpdateCallback - callback) = 0; + // Implements blink::mojom::ServiceWorkerContainerHost and called from + // ServiceWorkerContainerHostForClient. + void EnsureControllerServiceWorker( + mojo::PendingReceiver<blink::mojom::ControllerServiceWorker> receiver, + blink::mojom::ControllerServiceWorkerPurpose purpose); + void HintToUpdateServiceWorker(); + void EnsureFileAccess( + const std::vector<base::FilePath>& file_paths, + blink::mojom::ServiceWorkerContainerHost::EnsureFileAccessCallback + callback); + void OnExecutionReady(); - // TODO(crbug.com/336154571): For now `protected` is used to expose all - // members to subclasses for easier migration. Once the migration is done, use - // `private` for stricter access control. - protected: + const std::optional<PolicyContainerPolicies>& policy_container_policies() + const { + return policy_container_policies_; + } + + private: class ServiceWorkerRunningStatusObserver; friend class ServiceWorkerContainerHostTest; - ServiceWorkerContainerHost( - base::WeakPtr<ServiceWorkerContextCore> context, - bool is_parent_frame_secure, - mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> - container_remote, - int process_id_for_worker_client); - // Syncs matching registrations with live registrations. void SyncMatchingRegistrations(); @@ -557,8 +523,6 @@ // Discards all references to matching registrations. void RemoveAllMatchingRegistrations(); - void ReturnRegistrationForReadyIfNeeded(); - // Sets |execution_ready_| and runs execution ready callbacks. void SetExecutionReady(); @@ -595,8 +559,17 @@ // If it is still not ready to send, the features are buffered again. void FlushFeatures(); + // Callback for ServiceWorkerVersion::RunAfterStartWorker() + void StartControllerComplete( + mojo::PendingReceiver<blink::mojom::ControllerServiceWorker> receiver, + blink::ServiceWorkerStatusCode status); + base::WeakPtr<ServiceWorkerContextCore> context_; + // The corresponding container host. + // Always valid and non-null except for initialization/destruction. + std::unique_ptr<ServiceWorkerContainerHostForClient> container_host_; + // The time when the container host is created. const base::TimeTicks create_time_; @@ -625,15 +598,6 @@ // Callbacks to run upon transition to kExecutionReady. std::vector<ExecutionReadyCallback> execution_ready_callbacks_; - // The ready() promise is only allowed to be created once. - // |get_ready_callback_| has three states: - // 1. |get_ready_callback_| is null when ready() has not yet been called. - // 2. |*get_ready_callback_| is a valid OnceCallback after ready() has been - // called and the callback has not yet been run. - // 3. |*get_ready_callback_| is a null OnceCallback after the callback has - // been run. - std::unique_ptr<GetRegistrationForReadyCallback> get_ready_callback_; - // The controller service worker (i.e., ServiceWorkerContainer#controller) and // its registration. The controller is typically the same as the // registration's active version, but during algorithms such as the update, @@ -668,15 +632,6 @@ mojo::PendingReceiver<blink::mojom::ControllerServiceWorker> pending_controller_receiver_; - // Container host receivers other than the original |receiver_|. These include - // receivers used from (dedicated or shared) worker threads, or from - // ServiceWorkerSubresourceLoaderFactory. - mojo::ReceiverSet<blink::mojom::ServiceWorkerContainerHost> - additional_receivers_; - - // |container_| is the remote renderer-side ServiceWorkerContainer that |this| - // is hosting. - mojo::AssociatedRemote<blink::mojom::ServiceWorkerContainer> container_; // |is_container_ready_| is set to be true after |container_| has been passed // to the renderer process. This flag is needed to prevent |container_| used // before the association to the existing message pipe, which happens when @@ -756,50 +711,142 @@ // For all instances -------------------------------------------------------- - ServiceWorkerRegistrationObjectManager registration_object_manager_{this}; - ServiceWorkerObjectManager version_object_manager_{this}; - SEQUENCE_CHECKER(sequence_checker_); }; -// ServiceWorkerContainerHostForClient is owned by ServiceWorkerContextCore. The -// container host has a Mojo connection to the container in the renderer, and -// destruction of the container host happens upon disconnection of the Mojo +// `ServiceWorkerContainerHost` is the host of a ServiceWorkerContainer in the +// renderer process: https://w3c.github.io/ServiceWorker/#serviceworkercontainer +// - `ServiceWorkerContainerHostForClient` for a window, dedicated worker, or +// shared worker. +// - `ServiceWorkerContainerHostForServiceWorker` for a service worker execution +// context. +// +// Most of its functionality helps implement the web-exposed +// ServiceWorkerContainer interface (navigator.serviceWorker). The long-term +// goal is for it to be the host of ServiceWorkerContainer in the renderer, +// although currently only windows support ServiceWorkerContainers (see +// https://crbug.com/371690). +// +// ServiceWorkerContainerHost is also responsible for handling service worker +// related things in the execution context where the container lives. For +// example, the container host manages service worker (registration) JavaScript +// object hosts, delivers messages to/from the service worker, and dispatches +// events on the container. +class CONTENT_EXPORT ServiceWorkerContainerHost + : public blink::mojom::ServiceWorkerContainerHost, + public base::SupportsWeakPtr<ServiceWorkerContainerHost> { + public: + ServiceWorkerContainerHost(const ServiceWorkerContainerHost& other) = delete; + ServiceWorkerContainerHost& operator=( + const ServiceWorkerContainerHost& other) = delete; + ServiceWorkerContainerHost(ServiceWorkerContainerHost&& other) = delete; + ServiceWorkerContainerHost& operator=(ServiceWorkerContainerHost&& other) = + delete; + + ~ServiceWorkerContainerHost() override; + + // Implements blink::mojom::ServiceWorkerContainerHost. + void CloneContainerHost( + mojo::PendingReceiver<blink::mojom::ServiceWorkerContainerHost> receiver) + override; + + virtual const base::WeakPtr<ServiceWorkerContextCore>& context() const = 0; + + // The URL of this context. + virtual const GURL& url() const = 0; + + // Calls ContentBrowserClient::AllowServiceWorker(). Returns true if content + // settings allows service workers to run at |scope|. If this container is for + // a window client, the check involves the topmost frame url as well as + // |scope|, and may display tab-level UI. + // If non-empty, |script_url| is the script the service worker will run. + virtual bool AllowServiceWorker(const GURL& scope, + const GURL& script_url) = 0; + + using StatusCallback = + base::OnceCallback<void(blink::ServiceWorkerStatusCode)>; + virtual void DispatchExtendableMessageEvent( + scoped_refptr<ServiceWorkerVersion> version, + ::blink::TransferableMessage message, + StatusCallback callback) = 0; + virtual void Update( + scoped_refptr<ServiceWorkerRegistration> registration, + blink::mojom::FetchClientSettingsObjectPtr + outside_fetch_client_settings_object, + blink::mojom::ServiceWorkerRegistrationObjectHost::UpdateCallback + callback) = 0; + + ServiceWorkerRegistrationObjectManager& registration_object_manager() { + return registration_object_manager_; + } + ServiceWorkerObjectManager& version_object_manager() { + return version_object_manager_; + } + + protected: + ServiceWorkerContainerHost(); + + SEQUENCE_CHECKER(sequence_checker_); + + private: + // Container host receivers other than the original |receiver_|. These include + // receivers used from (dedicated or shared) worker threads, or from + // ServiceWorkerSubresourceLoaderFactory. + mojo::ReceiverSet<blink::mojom::ServiceWorkerContainerHost> + additional_receivers_; + + ServiceWorkerRegistrationObjectManager registration_object_manager_{this}; + ServiceWorkerObjectManager version_object_manager_{this}; +}; + +// `ServiceWorkerContainerHostForClient` is owned by and corresponds 1:1 to a +// `ServiceWorkerClient`. +// +// `ServiceWorkerContainerHostForClient` is created at the same time as the +// corresponding `ServiceWorkerClient` construction. +// TODO(https://crbug.com/336154571): Create +// `ServiceWorkerContainerHostForClient` once the global scope in the renderer +// process is created and ready to receive mojo calls. +// +// The container host has a Mojo connection to the container in the renderer, +// and destruction of the container host happens upon disconnection of the Mojo // pipe. -// -// The container host works as a source of truth of a service worker client. -// -// Example: -// When a new service worker registration is created, the browser process -// iterates over all ServiceWorkerContainerHosts to find clients (frames, -// dedicated workers if PlzDedicatedWorker is enabled, and shared workers) with -// a URL inside the registration's scope, and has the container host watch the -// registration in order to resolve navigator.serviceWorker.ready once the -// registration settles, if need. -// -// TODO(crbug.com/336154571): Introduce a new class `ServiceWorkerClient` for -// this purpose. class CONTENT_EXPORT ServiceWorkerContainerHostForClient final : public ServiceWorkerContainerHost { public: - // Constructor for window clients. - ServiceWorkerContainerHostForClient( - base::WeakPtr<ServiceWorkerContextCore> context, - bool is_parent_frame_secure, + // Creates `ServiceWorkerContainerHostForClient` and associates it with + // `service_worker_client`. + static void Create( + base::WeakPtr<ServiceWorkerClient> service_worker_client, mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> - container_remote, - int frame_tree_node_id); + container_remote); - // Constructor for worker clients. + // Use Create() instead. ServiceWorkerContainerHostForClient( - base::WeakPtr<ServiceWorkerContextCore> context, - int process_id, + base::WeakPtr<ServiceWorkerClient> service_worker_client, mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> - container_remote, - ServiceWorkerClientInfo client_info); - + container_remote); ~ServiceWorkerContainerHostForClient() override; + ServiceWorkerClient& service_worker_client() { + return *service_worker_client_; + } + const ServiceWorkerClient& service_worker_client() const { + return *service_worker_client_; + } + + // Called from ServiceWorkerClient. + void PostMessageToClient(base::WeakPtr<ServiceWorkerObjectHost> object_host, + blink::TransferableMessage message); + void SendSetController( + blink::mojom::ControllerServiceWorkerInfoPtr controller_info, + bool notify_controllerchange); + void CountFeature(blink::mojom::WebFeature feature); + void OnVersionAttributesChanged( + ServiceWorkerRegistration* registration, + blink::mojom::ChangedServiceWorkerObjectsMaskPtr changed_mask); + void ReturnRegistrationForReadyIfNeeded(); + // Implements blink::mojom::ServiceWorkerContainerHost. void Register(const GURL& script_url, blink::mojom::ServiceWorkerRegistrationOptionsPtr options, @@ -820,6 +867,8 @@ void OnExecutionReady() override; // Implements ServiceWorkerContainerHost. + const base::WeakPtr<ServiceWorkerContextCore>& context() const override; + const GURL& url() const override; bool AllowServiceWorker(const GURL& scope, const GURL& script_url) override; void DispatchExtendableMessageEvent( scoped_refptr<ServiceWorkerVersion> version, @@ -830,9 +879,6 @@ outside_fetch_client_settings_object, blink::mojom::ServiceWorkerRegistrationObjectHost::UpdateCallback callback) override; - void UpdateUrls(const GURL& url, - const std::optional<url::Origin>& top_frame_origin, - const blink::StorageKey& storage_key) override; private: // Callback for ServiceWorkerContextCore::RegisterServiceWorker(). @@ -857,10 +903,6 @@ blink::ServiceWorkerStatusCode status, const std::vector<scoped_refptr<ServiceWorkerRegistration>>& registrations); - // Callback for ServiceWorkerVersion::RunAfterStartWorker() - void StartControllerComplete( - mojo::PendingReceiver<blink::mojom::ControllerServiceWorker> receiver, - blink::ServiceWorkerStatusCode status); bool IsValidGetRegistrationMessage(const GURL& client_url, std::string* out_error) const; @@ -881,6 +923,23 @@ const GURL& script_url, const char* error_prefix, Args... args); + + // The corresponding service worker client that owns `this`. + // Always valid and non-null except for initialization/destruction. + base::WeakPtr<ServiceWorkerClient> service_worker_client_; + + // The ready() promise is only allowed to be created once. + // |get_ready_callback_| has three states: + // 1. |get_ready_callback_| is null when ready() has not yet been called. + // 2. |*get_ready_callback_| is a valid OnceCallback after ready() has been + // called and the callback has not yet been run. + // 3. |*get_ready_callback_| is a null OnceCallback after the callback has + // been run. + std::unique_ptr<GetRegistrationForReadyCallback> get_ready_callback_; + + // |container_| is the remote renderer-side ServiceWorkerContainer that |this| + // is hosting. + mojo::AssociatedRemote<blink::mojom::ServiceWorkerContainer> container_; }; // ServiceWorkerContainerHostForServiceWorker is owned by ServiceWorkerHost, @@ -916,6 +975,8 @@ void OnExecutionReady() override; // Implements ServiceWorkerContainerHost. + const base::WeakPtr<ServiceWorkerContextCore>& context() const override; + const GURL& url() const override; bool AllowServiceWorker(const GURL& scope, const GURL& script_url) override; void DispatchExtendableMessageEvent( scoped_refptr<ServiceWorkerVersion> version, @@ -926,15 +987,23 @@ outside_fetch_client_settings_object, blink::mojom::ServiceWorkerRegistrationObjectHost::UpdateCallback callback) override; - void UpdateUrls(const GURL& url, - const std::optional<url::Origin>& top_frame_origin, - const blink::StorageKey& storage_key) override; ServiceWorkerHost* service_worker_host(); + const blink::StorageKey& key() const; + const url::Origin& top_frame_origin() const; private: // The ServiceWorkerHost that owns |this|. const raw_ptr<ServiceWorkerHost> service_worker_host_; + + const base::WeakPtr<ServiceWorkerContextCore> context_; + + // The URL of the service worker's script. + const GURL url_; + + const blink::StorageKey key_; + + const url::Origin top_frame_origin_; }; CONTENT_EXPORT BASE_DECLARE_FEATURE(kSharedWorkerBlobURLFix);
diff --git a/content/browser/service_worker/service_worker_container_host_unittest.cc b/content/browser/service_worker/service_worker_container_host_unittest.cc index cab9975..c08e575 100644 --- a/content/browser/service_worker/service_worker_container_host_unittest.cc +++ b/content/browser/service_worker/service_worker_container_host_unittest.cc
@@ -182,7 +182,7 @@ return remote_endpoint; } - base::WeakPtr<ServiceWorkerContainerHost> CreateContainerHost( + base::WeakPtr<ServiceWorkerClient> CreateContainerHost( const GURL& document_url) { url::Origin top_frame_origin = url::Origin::Create(document_url); remote_endpoints_.emplace_back(); @@ -190,25 +190,25 @@ &remote_endpoints_.back()); } - base::WeakPtr<ServiceWorkerContainerHost> - CreateContainerHostWithInsecureParentFrame(const GURL& document_url) { + base::WeakPtr<ServiceWorkerClient> CreateContainerHostWithInsecureParentFrame( + const GURL& document_url) { remote_endpoints_.emplace_back(); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/false, helper_->context()->AsWeakPtr(), &remote_endpoints_.back()); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( document_url, url::Origin::Create(document_url), blink::StorageKey::CreateFirstParty(url::Origin::Create(document_url))); - return container_host; + return service_worker_client; } - void FinishNavigation(ServiceWorkerContainerHost* container_host) { + void FinishNavigation(ServiceWorkerClient* service_worker_client) { // In production code, the loader/request handler does this. const GURL url("https://www.example.com/page"); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( url, url::Origin::Create(url), blink::StorageKey::CreateFirstParty(url::Origin::Create(url))); @@ -219,13 +219,13 @@ // In production code this is called from NavigationRequest in the browser // process right before navigation commit. - container_host->OnBeginNavigationCommit( + service_worker_client->OnBeginNavigationCommit( GlobalRenderFrameHostId(helper_->mock_render_process_id(), 1 /* route_id */), PolicyContainerPolicies(), std::move(reporter), ukm::UkmRecorder::GetNewSourceID()); // After the navigation commit, it is ready to call the container's methods. - container_host->SetContainerReady(); + service_worker_client->SetContainerReady(); } blink::mojom::ServiceWorkerErrorType Register( @@ -294,13 +294,14 @@ void OnMojoError(const std::string& error) { bad_messages_.push_back(error); } - bool CanFindClientContainerHost(ServiceWorkerContainerHost* container_host) { + bool CanFindClientContainerHost(ServiceWorkerClient* service_worker_client) { if (context_) { for (auto it = context_->GetServiceWorkerClients( - container_host->key(), false /* include_reserved_clients */, + service_worker_client->key(), + false /* include_reserved_clients */, false /* include_back_forward_cached_clients */); !it.IsAtEnd(); ++it) { - if (container_host == &*it) { + if (service_worker_client == &*it) { return true; } } @@ -318,15 +319,16 @@ EXPECT_FALSE(version->update_timer_.IsRunning()); } - bool HasVersionToUpdate(ServiceWorkerContainerHost* container_host) { - return !container_host->versions_to_update_.empty(); + bool HasVersionToUpdate(ServiceWorkerClient* service_worker_client) { + return !service_worker_client->versions_to_update_.empty(); } blink::StorageKey GetCorrectStorageKeyForWebSecurityState( - ServiceWorkerContainerHost* container_host, + ServiceWorkerClient* service_worker_client, const GURL& url) const { return service_worker_security_utils:: - GetCorrectStorageKeyForWebSecurityState(container_host->key(), url); + GetCorrectStorageKeyForWebSecurityState(service_worker_client->key(), + url); } void TestReservedClientsAreNotExposed(ServiceWorkerClientInfo client_info, @@ -351,20 +353,20 @@ std::vector<std::string> bad_messages_; private: - base::WeakPtr<ServiceWorkerContainerHost> CreateContainerHostInternal( + base::WeakPtr<ServiceWorkerClient> CreateContainerHostInternal( const GURL& document_url, const std::optional<url::Origin>& top_frame_origin, ServiceWorkerRemoteContainerEndpoint* remote_endpoint) { - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), remote_endpoint); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( document_url, top_frame_origin, blink::StorageKey::CreateFirstParty(url::Origin::Create(document_url))); - return container_host; + return service_worker_client; } url::ScopedSchemeRegistryForTests scoped_registry_; @@ -377,7 +379,7 @@ : public ServiceWorkerContainerHostTest { public: ServiceWorkerContainerHostTestWithPlzDedicatedWorker() { - // ServiceWorkerContainerHost for dedicated workers is available only when + // ServiceWorkerClient for dedicated workers is available only when // PlzDedicatedWorker is enabled. scoped_feature_list_.InitAndEnableFeature( blink::features::kPlzDedicatedWorker); @@ -388,66 +390,66 @@ }; TEST_F(ServiceWorkerContainerHostTest, MatchRegistration) { - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(GURL("https://www.example.com/example1.html")); // Match registration should return the longest matching one. - ASSERT_EQ(registration2_, container_host->MatchRegistration()); - container_host->RemoveMatchingRegistration(registration2_.get()); - ASSERT_EQ(registration1_, container_host->MatchRegistration()); + ASSERT_EQ(registration2_, service_worker_client->MatchRegistration()); + service_worker_client->RemoveMatchingRegistration(registration2_.get()); + ASSERT_EQ(registration1_, service_worker_client->MatchRegistration()); // Should return nullptr after removing all matching registrations. - container_host->RemoveMatchingRegistration(registration1_.get()); - ASSERT_EQ(nullptr, container_host->MatchRegistration()); + service_worker_client->RemoveMatchingRegistration(registration1_.get()); + ASSERT_EQ(nullptr, service_worker_client->MatchRegistration()); // UpdateUrls sets all of matching registrations - container_host->UpdateUrls( + service_worker_client->UpdateUrls( GURL("https://www.example.com/example1"), url::Origin::Create(GURL("https://www.example.com/example1")), blink::StorageKey::CreateFromStringForTesting( "https://www.example.com/example1")); - ASSERT_EQ(registration2_, container_host->MatchRegistration()); - container_host->RemoveMatchingRegistration(registration2_.get()); - ASSERT_EQ(registration1_, container_host->MatchRegistration()); + ASSERT_EQ(registration2_, service_worker_client->MatchRegistration()); + service_worker_client->RemoveMatchingRegistration(registration2_.get()); + ASSERT_EQ(registration1_, service_worker_client->MatchRegistration()); // UpdateUrls with another origin also updates matching registrations - container_host->UpdateUrls( + service_worker_client->UpdateUrls( GURL("https://other.example.com/example"), url::Origin::Create(GURL("https://other.example.com/example")), blink::StorageKey::CreateFromStringForTesting( "https://other.example.com/example1")); - ASSERT_EQ(registration3_, container_host->MatchRegistration()); - container_host->RemoveMatchingRegistration(registration3_.get()); - ASSERT_EQ(nullptr, container_host->MatchRegistration()); + ASSERT_EQ(registration3_, service_worker_client->MatchRegistration()); + service_worker_client->RemoveMatchingRegistration(registration3_.get()); + ASSERT_EQ(nullptr, service_worker_client->MatchRegistration()); } TEST_F(ServiceWorkerContainerHostTest, ContextSecurity) { - base::WeakPtr<ServiceWorkerContainerHost> container_host_secure_parent = + base::WeakPtr<ServiceWorkerClient> service_worker_client_secure_parent = CreateContainerHost(GURL("https://www.example.com/example1.html")); - base::WeakPtr<ServiceWorkerContainerHost> container_host_insecure_parent = + base::WeakPtr<ServiceWorkerClient> service_worker_client_insecure_parent = CreateContainerHostWithInsecureParentFrame( GURL("https://www.example.com/example1.html")); // Insecure document URL. - container_host_secure_parent->UpdateUrls( + service_worker_client_secure_parent->UpdateUrls( GURL("http://host"), url::Origin::Create(GURL("http://host")), blink::StorageKey::CreateFromStringForTesting("http://host")); - EXPECT_FALSE( - container_host_secure_parent->IsEligibleForServiceWorkerController()); + EXPECT_FALSE(service_worker_client_secure_parent + ->IsEligibleForServiceWorkerController()); // Insecure parent frame. - container_host_insecure_parent->UpdateUrls( + service_worker_client_insecure_parent->UpdateUrls( GURL("https://host"), url::Origin::Create(GURL("https://host")), blink::StorageKey::CreateFromStringForTesting("https://host")); - EXPECT_FALSE( - container_host_insecure_parent->IsEligibleForServiceWorkerController()); + EXPECT_FALSE(service_worker_client_insecure_parent + ->IsEligibleForServiceWorkerController()); // Secure URL and parent frame. - container_host_secure_parent->UpdateUrls( + service_worker_client_secure_parent->UpdateUrls( GURL("https://host"), url::Origin::Create(GURL("https://host")), blink::StorageKey::CreateFromStringForTesting("https://host")); - EXPECT_TRUE( - container_host_secure_parent->IsEligibleForServiceWorkerController()); + EXPECT_TRUE(service_worker_client_secure_parent + ->IsEligibleForServiceWorkerController()); // Exceptional service worker scheme. GURL url(std::string(kServiceWorkerScheme) + "://host"); @@ -455,69 +457,71 @@ EXPECT_TRUE(url.is_valid()); EXPECT_FALSE(network::IsUrlPotentiallyTrustworthy(url)); EXPECT_TRUE(OriginCanAccessServiceWorkers(url)); - container_host_secure_parent->UpdateUrls( + service_worker_client_secure_parent->UpdateUrls( url, origin, blink::StorageKey::CreateFirstParty(origin)); - EXPECT_TRUE( - container_host_secure_parent->IsEligibleForServiceWorkerController()); + EXPECT_TRUE(service_worker_client_secure_parent + ->IsEligibleForServiceWorkerController()); // Exceptional service worker scheme with insecure parent frame. - container_host_insecure_parent->UpdateUrls( + service_worker_client_insecure_parent->UpdateUrls( url, origin, blink::StorageKey::CreateFirstParty(origin)); - EXPECT_FALSE( - container_host_insecure_parent->IsEligibleForServiceWorkerController()); + EXPECT_FALSE(service_worker_client_insecure_parent + ->IsEligibleForServiceWorkerController()); } TEST_F(ServiceWorkerContainerHostTest, UpdateUrls_SameOriginRedirect) { const GURL url1("https://origin1.example.com/page1.html"); const GURL url2("https://origin1.example.com/page2.html"); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(url1); - const std::string uuid1 = container_host->client_uuid(); - EXPECT_EQ(url1, container_host->url()); - EXPECT_TRUE( - service_worker_security_utils::site_for_cookies(container_host->key()) - .IsEquivalent(net::SiteForCookies::FromUrl(url1))); + const std::string uuid1 = service_worker_client->client_uuid(); + EXPECT_EQ(url1, service_worker_client->url()); + EXPECT_TRUE(service_worker_security_utils::site_for_cookies( + service_worker_client->key()) + .IsEquivalent(net::SiteForCookies::FromUrl(url1))); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( url2, url::Origin::Create(url2), blink::StorageKey::CreateFirstParty(url::Origin::Create(url2))); - EXPECT_EQ(url2, container_host->url()); - EXPECT_TRUE( - service_worker_security_utils::site_for_cookies(container_host->key()) - .IsEquivalent(net::SiteForCookies::FromUrl(url2))); - EXPECT_EQ(uuid1, container_host->client_uuid()); + EXPECT_EQ(url2, service_worker_client->url()); + EXPECT_TRUE(service_worker_security_utils::site_for_cookies( + service_worker_client->key()) + .IsEquivalent(net::SiteForCookies::FromUrl(url2))); + EXPECT_EQ(uuid1, service_worker_client->client_uuid()); ASSERT_TRUE(context_); - EXPECT_EQ(container_host.get(), context_->GetContainerHostByClientID( - container_host->client_uuid())); + EXPECT_EQ(service_worker_client.get(), + context_->GetContainerHostByClientID( + service_worker_client->client_uuid())); } TEST_F(ServiceWorkerContainerHostTest, UpdateUrls_CrossOriginRedirect) { const GURL url1("https://origin1.example.com/page1.html"); const GURL url2("https://origin2.example.com/page2.html"); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(url1); - const std::string uuid1 = container_host->client_uuid(); - EXPECT_EQ(url1, container_host->url()); - EXPECT_TRUE( - service_worker_security_utils::site_for_cookies(container_host->key()) - .IsEquivalent(net::SiteForCookies::FromUrl(url1))); + const std::string uuid1 = service_worker_client->client_uuid(); + EXPECT_EQ(url1, service_worker_client->url()); + EXPECT_TRUE(service_worker_security_utils::site_for_cookies( + service_worker_client->key()) + .IsEquivalent(net::SiteForCookies::FromUrl(url1))); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( url2, url::Origin::Create(url2), blink::StorageKey::CreateFirstParty(url::Origin::Create(url2))); - EXPECT_EQ(url2, container_host->url()); - EXPECT_TRUE( - service_worker_security_utils::site_for_cookies(container_host->key()) - .IsEquivalent(net::SiteForCookies::FromUrl(url2))); - EXPECT_NE(uuid1, container_host->client_uuid()); + EXPECT_EQ(url2, service_worker_client->url()); + EXPECT_TRUE(service_worker_security_utils::site_for_cookies( + service_worker_client->key()) + .IsEquivalent(net::SiteForCookies::FromUrl(url2))); + EXPECT_NE(uuid1, service_worker_client->client_uuid()); ASSERT_TRUE(context_); EXPECT_FALSE(context_->GetContainerHostByClientID(uuid1)); - EXPECT_EQ(container_host.get(), context_->GetContainerHostByClientID( - container_host->client_uuid())); + EXPECT_EQ(service_worker_client.get(), + context_->GetContainerHostByClientID( + service_worker_client->client_uuid())); } TEST_F(ServiceWorkerContainerHostTest, UpdateUrls_CorrectStorageKey) { @@ -528,12 +532,12 @@ const blink::StorageKey key2 = blink::StorageKey::CreateFirstParty(url::Origin::Create(url2)); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(url1); - EXPECT_EQ(key1, container_host->key()); + EXPECT_EQ(key1, service_worker_client->key()); - container_host->UpdateUrls(url2, url::Origin::Create(url2), key2); - EXPECT_EQ(key2, container_host->key()); + service_worker_client->UpdateUrls(url2, url::Origin::Create(url2), key2); + EXPECT_EQ(key2, service_worker_client->key()); } TEST_F(ServiceWorkerContainerHostTest, ForServiceWorker_CorrectStorageKey) { @@ -577,42 +581,46 @@ const blink::StorageKey key3 = blink::StorageKey::CreateFirstParty(url::Origin::Create(url3)); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(url1); - EXPECT_EQ(container_host->key(), key1); + EXPECT_EQ(service_worker_client->key(), key1); - EXPECT_EQ(container_host->key(), GetCorrectStorageKeyForWebSecurityState( - container_host.get(), url1)); - EXPECT_EQ(container_host->key(), GetCorrectStorageKeyForWebSecurityState( - container_host.get(), url2)); - EXPECT_EQ(container_host->key(), GetCorrectStorageKeyForWebSecurityState( - container_host.get(), url3)); + EXPECT_EQ(service_worker_client->key(), + GetCorrectStorageKeyForWebSecurityState(service_worker_client.get(), + url1)); + EXPECT_EQ(service_worker_client->key(), + GetCorrectStorageKeyForWebSecurityState(service_worker_client.get(), + url2)); + EXPECT_EQ(service_worker_client->key(), + GetCorrectStorageKeyForWebSecurityState(service_worker_client.get(), + url3)); // With disable-web-security we should get a new key for the cross-origin // urls. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); command_line->AppendSwitch(switches::kDisableWebSecurity); - EXPECT_EQ(container_host->key(), GetCorrectStorageKeyForWebSecurityState( - container_host.get(), url1)); - EXPECT_EQ(key2, GetCorrectStorageKeyForWebSecurityState(container_host.get(), - url2)); - EXPECT_EQ(key3, GetCorrectStorageKeyForWebSecurityState(container_host.get(), - url3)); + EXPECT_EQ(service_worker_client->key(), + GetCorrectStorageKeyForWebSecurityState(service_worker_client.get(), + url1)); + EXPECT_EQ(key2, GetCorrectStorageKeyForWebSecurityState( + service_worker_client.get(), url2)); + EXPECT_EQ(key3, GetCorrectStorageKeyForWebSecurityState( + service_worker_client.get(), url3)); } TEST_F(ServiceWorkerContainerHostTest, RemoveProvider) { // Create a container host connected with the renderer process. - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(GURL("https://www.example.com/example1.html")); - EXPECT_TRUE(container_host); + EXPECT_TRUE(service_worker_client); // Disconnect the mojo pipe from the renderer side. ASSERT_TRUE(remote_endpoints_.back().host_remote()->is_bound()); remote_endpoints_.back().host_remote()->reset(); base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(container_host); + EXPECT_FALSE(service_worker_client); } class MockServiceWorkerContainer : public blink::mojom::ServiceWorkerContainer { @@ -642,13 +650,13 @@ TEST_F(ServiceWorkerContainerHostTest, Controller) { // Create a host. - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(helper_->context()->AsWeakPtr(), /*are_ancestors_secure=*/true); - base::WeakPtr<ServiceWorkerContainerHost> container_host = - std::move(host_and_info->host); + base::WeakPtr<ServiceWorkerClient> service_worker_client = + std::move(client_and_info->service_worker_client); remote_endpoints_.emplace_back(); - remote_endpoints_.back().BindForWindow(std::move(host_and_info->info)); + remote_endpoints_.back().BindForWindow(std::move(client_and_info->info)); auto container = std::make_unique<MockServiceWorkerContainer>( std::move(*remote_endpoints_.back().client_receiver())); @@ -664,28 +672,28 @@ registration1_->SetActiveVersion(version); // Finish the navigation. - FinishNavigation(container_host.get()); - container_host->SetControllerRegistration( + FinishNavigation(service_worker_client.get()); + service_worker_client->SetControllerRegistration( registration1_, false /* notify_controllerchange */); remote_endpoints_.back().host_remote()->get()->OnExecutionReady(); base::RunLoop().RunUntilIdle(); // The page should be controlled since there was an active version at the // time navigation started. The SetController IPC should have been sent. - EXPECT_TRUE(container_host->controller()); + EXPECT_TRUE(service_worker_client->controller()); EXPECT_TRUE(container->was_set_controller_called()); - EXPECT_EQ(registration1_.get(), container_host->MatchRegistration()); + EXPECT_EQ(registration1_.get(), service_worker_client->MatchRegistration()); } TEST_F(ServiceWorkerContainerHostTest, UncontrolledWithMatchingRegistration) { // Create a host. - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(helper_->context()->AsWeakPtr(), /*are_ancestors_secure=*/true); - base::WeakPtr<ServiceWorkerContainerHost> container_host = - std::move(host_and_info->host); + base::WeakPtr<ServiceWorkerClient> service_worker_client = + std::move(client_and_info->service_worker_client); remote_endpoints_.emplace_back(); - remote_endpoints_.back().BindForWindow(std::move(host_and_info->info)); + remote_endpoints_.back().BindForWindow(std::move(client_and_info->info)); auto container = std::make_unique<MockServiceWorkerContainer>( std::move(*remote_endpoints_.back().client_receiver())); @@ -698,7 +706,7 @@ registration1_->SetInstallingVersion(version); // Finish the navigation. - FinishNavigation(container_host.get()); + FinishNavigation(service_worker_client.get()); // Promote the worker to active while navigation is still happening. registration1_->SetActiveVersion(version); base::RunLoop().RunUntilIdle(); @@ -706,11 +714,11 @@ // The page should not be controlled since there was no active version at the // time navigation started. Furthermore, no SetController IPC should have been // sent. - EXPECT_FALSE(container_host->controller()); + EXPECT_FALSE(service_worker_client->controller()); EXPECT_FALSE(container->was_set_controller_called()); // However, the host should know the registration is its best match, for // .ready and claim(). - EXPECT_EQ(registration1_.get(), container_host->MatchRegistration()); + EXPECT_EQ(registration1_.get(), service_worker_client->MatchRegistration()); } TEST_F(ServiceWorkerContainerHostTest, @@ -1082,8 +1090,8 @@ // Let the shutdown reach the simulated IO thread. base::RunLoop().RunUntilIdle(); - // Because ServiceWorkerContextCore owns ServiceWorkerContainerHost, our - // ServiceWorkerContainerHost instance has destroyed. + // Because ServiceWorkerContextCore owns ServiceWorkerClient, our + // ServiceWorkerClient instance has destroyed. EXPECT_FALSE(remote_endpoint.host_remote()->is_connected()); } @@ -1182,36 +1190,36 @@ container_info->host_remote.InitWithNewEndpointAndPassReceiver(); ASSERT_TRUE(context_); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = context_->CreateContainerHostForWorker( std::move(host_receiver), helper_->mock_render_process_id(), std::move(client_remote), client_info); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( url, url::Origin::Create(url), blink::StorageKey::CreateFirstParty(url::Origin::Create(url))); - EXPECT_FALSE(CanFindClientContainerHost(container_host.get())); - container_host->CompleteWebWorkerPreparation( + EXPECT_FALSE(CanFindClientContainerHost(service_worker_client.get())); + service_worker_client->CompleteWebWorkerPreparation( PolicyContainerPolicies(), ukm::UkmRecorder::GetNewSourceID()); - EXPECT_TRUE(CanFindClientContainerHost(container_host.get())); + EXPECT_TRUE(CanFindClientContainerHost(service_worker_client.get())); } { - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(helper_->context()->AsWeakPtr(), /*are_ancestors_secure=*/true); - base::WeakPtr<ServiceWorkerContainerHost> container_host = - std::move(host_and_info->host); + base::WeakPtr<ServiceWorkerClient> service_worker_client = + std::move(client_and_info->service_worker_client); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - remote_endpoint.BindForWindow(std::move(host_and_info->info)); + remote_endpoint.BindForWindow(std::move(client_and_info->info)); - FinishNavigation(container_host.get()); - EXPECT_FALSE(CanFindClientContainerHost(container_host.get())); + FinishNavigation(service_worker_client.get()); + EXPECT_FALSE(CanFindClientContainerHost(service_worker_client.get())); base::RunLoop run_loop; - container_host->AddExecutionReadyCallback(run_loop.QuitClosure()); + service_worker_client->AddExecutionReadyCallback(run_loop.QuitClosure()); remote_endpoint.host_remote()->get()->OnExecutionReady(); run_loop.Run(); - EXPECT_TRUE(CanFindClientContainerHost(container_host.get())); + EXPECT_TRUE(CanFindClientContainerHost(service_worker_client.get())); } } @@ -1233,26 +1241,26 @@ // Tests the client phase transitions for a navigation. TEST_F(ServiceWorkerContainerHostTest, ClientPhaseForWindow) { - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(helper_->context()->AsWeakPtr(), /*are_ancestors_secure=*/true); - base::WeakPtr<ServiceWorkerContainerHost> container_host = - std::move(host_and_info->host); + base::WeakPtr<ServiceWorkerClient> service_worker_client = + std::move(client_and_info->service_worker_client); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - remote_endpoint.BindForWindow(std::move(host_and_info->info)); - EXPECT_FALSE(container_host->is_response_committed()); - EXPECT_FALSE(container_host->is_execution_ready()); + remote_endpoint.BindForWindow(std::move(client_and_info->info)); + EXPECT_FALSE(service_worker_client->is_response_committed()); + EXPECT_FALSE(service_worker_client->is_execution_ready()); - FinishNavigation(container_host.get()); - EXPECT_TRUE(container_host->is_response_committed()); - EXPECT_FALSE(container_host->is_execution_ready()); + FinishNavigation(service_worker_client.get()); + EXPECT_TRUE(service_worker_client->is_response_committed()); + EXPECT_FALSE(service_worker_client->is_execution_ready()); base::RunLoop run_loop; - container_host->AddExecutionReadyCallback(run_loop.QuitClosure()); + service_worker_client->AddExecutionReadyCallback(run_loop.QuitClosure()); remote_endpoint.host_remote()->get()->OnExecutionReady(); run_loop.Run(); - EXPECT_TRUE(container_host->is_response_committed()); - EXPECT_TRUE(container_host->is_execution_ready()); + EXPECT_TRUE(service_worker_client->is_response_committed()); + EXPECT_TRUE(service_worker_client->is_execution_ready()); } // Tests the client phase transitions for workers. @@ -1270,21 +1278,21 @@ host_receiver = container_info->host_remote.InitWithNewEndpointAndPassReceiver(); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = helper_->context()->CreateContainerHostForWorker( std::move(host_receiver), helper_->mock_render_process_id(), std::move(client_remote), client_info); - EXPECT_FALSE(container_host->is_response_committed()); - EXPECT_FALSE(container_host->is_execution_ready()); + EXPECT_FALSE(service_worker_client->is_response_committed()); + EXPECT_FALSE(service_worker_client->is_execution_ready()); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( url, url::Origin::Create(url), blink::StorageKey::CreateFirstParty(url::Origin::Create(url))); - container_host->CompleteWebWorkerPreparation( + service_worker_client->CompleteWebWorkerPreparation( PolicyContainerPolicies(), ukm::UkmRecorder::GetNewSourceID()); - EXPECT_TRUE(container_host->is_response_committed()); - EXPECT_TRUE(container_host->is_execution_ready()); + EXPECT_TRUE(service_worker_client->is_response_committed()); + EXPECT_TRUE(service_worker_client->is_execution_ready()); } TEST_F(ServiceWorkerContainerHostTestWithPlzDedicatedWorker, @@ -1339,26 +1347,26 @@ ASSERT_TRUE(worker_host); } { - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(helper_->context()->AsWeakPtr(), /*are_ancestors_secure=*/true); - base::WeakPtr<ServiceWorkerContainerHost> container_host = - std::move(host_and_info->host); + base::WeakPtr<ServiceWorkerClient> service_worker_client = + std::move(client_and_info->service_worker_client); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - remote_endpoint.BindForWindow(std::move(host_and_info->info)); + remote_endpoint.BindForWindow(std::move(client_and_info->info)); - FinishNavigation(container_host.get()); - EXPECT_FALSE(CanFindClientContainerHost(container_host.get())); + FinishNavigation(service_worker_client.get()); + EXPECT_FALSE(CanFindClientContainerHost(service_worker_client.get())); base::RunLoop run_loop; - container_host->AddExecutionReadyCallback(run_loop.QuitClosure()); + service_worker_client->AddExecutionReadyCallback(run_loop.QuitClosure()); remote_endpoint.host_remote()->get()->OnExecutionReady(); run_loop.Run(); - EXPECT_TRUE(CanFindClientContainerHost(container_host.get())); - container_host->EnterBackForwardCacheForTesting(); - EXPECT_FALSE(CanFindClientContainerHost(container_host.get())); - container_host->LeaveBackForwardCacheForTesting(); - EXPECT_TRUE(CanFindClientContainerHost(container_host.get())); + EXPECT_TRUE(CanFindClientContainerHost(service_worker_client.get())); + service_worker_client->EnterBackForwardCacheForTesting(); + EXPECT_FALSE(CanFindClientContainerHost(service_worker_client.get())); + service_worker_client->LeaveBackForwardCacheForTesting(); + EXPECT_TRUE(CanFindClientContainerHost(service_worker_client.get())); } } @@ -1416,13 +1424,13 @@ TestServiceWorkerContextCoreObserver observer(helper_->context_wrapper()); // Create a host. - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(helper_->context()->AsWeakPtr(), /*are_ancestors_secure=*/true); - base::WeakPtr<ServiceWorkerContainerHost> container_host = - std::move(host_and_info->host); + base::WeakPtr<ServiceWorkerClient> service_worker_client = + std::move(client_and_info->service_worker_client); remote_endpoints_.emplace_back(); - remote_endpoints_.back().BindForWindow(std::move(host_and_info->info)); + remote_endpoints_.back().BindForWindow(std::move(client_and_info->info)); auto container = std::make_unique<MockServiceWorkerContainer>( std::move(*remote_endpoints_.back().client_receiver())); @@ -1438,8 +1446,8 @@ registration1_->SetActiveVersion(version); // Finish the navigation. - FinishNavigation(container_host.get()); - container_host->SetControllerRegistration( + FinishNavigation(service_worker_client.get()); + service_worker_client->SetControllerRegistration( registration1_, false /* notify_controllerchange */); remote_endpoints_.back().host_remote()->get()->OnExecutionReady(); base::RunLoop().RunUntilIdle(); @@ -1450,14 +1458,15 @@ // The navigation commit ending should send the // OnControlleeNavigationCommitted() notification. - container_host->OnEndNavigationCommit(); + service_worker_client->OnEndNavigationCommit(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(observer.on_controllee_added_count(), 1); EXPECT_EQ(observer.on_controllee_navigation_committed_count(), 1); EXPECT_EQ(observer.on_controllee_removed_count(), 0); - version->MoveControlleeToBackForwardCacheMap(container_host->client_uuid()); + version->MoveControlleeToBackForwardCacheMap( + service_worker_client->client_uuid()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(observer.on_controllee_added_count(), 1); @@ -1465,7 +1474,7 @@ EXPECT_EQ(observer.on_controllee_removed_count(), 1); version->RestoreControlleeFromBackForwardCacheMap( - container_host->client_uuid()); + service_worker_client->client_uuid()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(observer.on_controllee_added_count(), 2); @@ -1478,7 +1487,7 @@ // destroyed. TEST_F(ServiceWorkerContainerHostTest, UpdateServiceWorkerOnDestruction) { // Make a window. - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(GURL("https://www.example.com/example.html")); // Make an active version. @@ -1502,8 +1511,8 @@ version2->SetStatus(ServiceWorkerVersion::ACTIVATED); registration2_->SetActiveVersion(version1); - container_host->AddServiceWorkerToUpdate(version1); - container_host->AddServiceWorkerToUpdate(version2); + service_worker_client->AddServiceWorkerToUpdate(version1); + service_worker_client->AddServiceWorkerToUpdate(version2); ExpectUpdateIsNotScheduled(version1.get()); ExpectUpdateIsNotScheduled(version2.get()); @@ -1532,14 +1541,14 @@ registration1_->SetActiveVersion(version1); // Make a window. - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(GURL("https://www.example.com/example.html")); // Mark the service worker as needing update. Update should not be scheduled // yet. - container_host->AddServiceWorkerToUpdate(version1); + service_worker_client->AddServiceWorkerToUpdate(version1); ExpectUpdateIsNotScheduled(version1.get()); - EXPECT_TRUE(HasVersionToUpdate(container_host.get())); + EXPECT_TRUE(HasVersionToUpdate(service_worker_client.get())); // Send the hint from the renderer. Update should be scheduled. mojo::AssociatedRemote<blink::mojom::ServiceWorkerContainerHost>* @@ -1547,7 +1556,7 @@ (*host_remote)->HintToUpdateServiceWorker(); base::RunLoop().RunUntilIdle(); ExpectUpdateIsScheduled(version1.get()); - EXPECT_FALSE(HasVersionToUpdate(container_host.get())); + EXPECT_FALSE(HasVersionToUpdate(service_worker_client.get())); } // Tests that the host receives a HintToUpdateServiceWorker message but @@ -1556,7 +1565,7 @@ TEST_F(ServiceWorkerContainerHostTest, HintToUpdateServiceWorkerButNoVersionToUpdate) { // Make a window. - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(GURL("https://www.example.com/example.html")); // Make an active version. @@ -1574,7 +1583,7 @@ // resource request, so AddServiceWorkerToUpdate() is not called. ExpectUpdateIsNotScheduled(version1.get()); - EXPECT_FALSE(HasVersionToUpdate(container_host.get())); + EXPECT_FALSE(HasVersionToUpdate(service_worker_client.get())); // Send the hint from the renderer. Update should not be scheduled, since // AddServiceWorkerToUpdate() was not called. @@ -1583,7 +1592,7 @@ (*host_remote)->HintToUpdateServiceWorker(); base::RunLoop().RunUntilIdle(); ExpectUpdateIsNotScheduled(version1.get()); - EXPECT_FALSE(HasVersionToUpdate(container_host.get())); + EXPECT_FALSE(HasVersionToUpdate(service_worker_client.get())); } TEST_F(ServiceWorkerContainerHostTest, HintToUpdateServiceWorkerMultiple) { @@ -1619,18 +1628,18 @@ registration3_->SetActiveVersion(version1); // Make a window. - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHost(GURL("https://www.example.com/example.html")); // Mark the service worker as needing update. Update should not be scheduled // yet. - container_host->AddServiceWorkerToUpdate(version1); - container_host->AddServiceWorkerToUpdate(version2); - container_host->AddServiceWorkerToUpdate(version3); + service_worker_client->AddServiceWorkerToUpdate(version1); + service_worker_client->AddServiceWorkerToUpdate(version2); + service_worker_client->AddServiceWorkerToUpdate(version3); ExpectUpdateIsNotScheduled(version1.get()); ExpectUpdateIsNotScheduled(version2.get()); ExpectUpdateIsNotScheduled(version3.get()); - EXPECT_TRUE(HasVersionToUpdate(container_host.get())); + EXPECT_TRUE(HasVersionToUpdate(service_worker_client.get())); // Pretend another page also used version3. version3->IncrementPendingUpdateHintCount(); @@ -1644,7 +1653,7 @@ ExpectUpdateIsScheduled(version1.get()); ExpectUpdateIsScheduled(version2.get()); ExpectUpdateIsNotScheduled(version3.get()); - EXPECT_FALSE(HasVersionToUpdate(container_host.get())); + EXPECT_FALSE(HasVersionToUpdate(service_worker_client.get())); // Pretend the other page also finished for version3. version3->DecrementPendingUpdateHintCount();
diff --git a/content/browser/service_worker/service_worker_context_core.cc b/content/browser/service_worker/service_worker_context_core.cc index f829fe1..89d169e 100644 --- a/content/browser/service_worker/service_worker_context_core.cc +++ b/content/browser/service_worker/service_worker_context_core.cc
@@ -134,8 +134,7 @@ const blink::StorageKey& key, bool allow_reserved_client, bool allow_back_forward_cached_client, - ServiceWorkerContainerHost& service_worker_client) { - DCHECK(service_worker_client.IsContainerForClient()); + ServiceWorkerClient& service_worker_client) { // If |service_worker_client| is in BackForwardCache, it should be skipped in // iteration, because (1) hosts in BackForwardCache should never be exposed to // web as clients and (2) hosts could be in an unknown state after eviction @@ -153,8 +152,7 @@ bool IsSameOriginWindowServiceWorkerClient( const blink::StorageKey& key, bool allow_reserved_client, - ServiceWorkerContainerHost& service_worker_client) { - DCHECK(service_worker_client.IsContainerForClient()); + ServiceWorkerClient& service_worker_client) { // If |service_worker_client| is in BackForwardCache, it should be skipped in // iteration, because (1) service worker clients in BackForwardCache should // never be exposed to web as clients and (2) service worker clients could be @@ -236,13 +234,13 @@ ServiceWorkerContextCore::ServiceWorkerClientIterator:: ~ServiceWorkerClientIterator() = default; -ServiceWorkerContainerHost& +ServiceWorkerClient& ServiceWorkerContextCore::ServiceWorkerClientIterator::operator*() const { DCHECK(!IsAtEnd()); return *iterator_->second; } -ServiceWorkerContainerHost* +ServiceWorkerClient* ServiceWorkerContextCore::ServiceWorkerClientIterator::operator->() const { DCHECK(!IsAtEnd()); return iterator_->second.get(); @@ -290,7 +288,7 @@ : wrapper_(wrapper), container_host_receivers_(std::make_unique<mojo::AssociatedReceiverSet< blink::mojom::ServiceWorkerContainerHost, - ServiceWorkerContainerHost*>>()), + ServiceWorkerContainerHostForClient*>>()), registry_( std::make_unique<ServiceWorkerRegistry>(this, quota_manager_proxy, @@ -334,7 +332,8 @@ ServiceWorkerContextCore* old_context, ServiceWorkerContextWrapper* wrapper) : wrapper_(wrapper), - container_host_by_uuid_(std::move(old_context->container_host_by_uuid_)), + service_worker_clients_by_uuid_( + std::move(old_context->service_worker_clients_by_uuid_)), container_host_receivers_( std::move(old_context->container_host_receivers_)), registry_( @@ -379,7 +378,7 @@ bool include_back_forward_cached_clients) { DCHECK_CURRENTLY_ON(BrowserThread::UI); return ServiceWorkerClientIterator( - &container_host_by_uuid_, + &service_worker_clients_by_uuid_, base::BindRepeating(IsSameOriginServiceWorkerClient, key, include_reserved_clients, include_back_forward_cached_clients)); @@ -391,7 +390,7 @@ bool include_reserved_clients) { DCHECK_CURRENTLY_ON(BrowserThread::UI); return ServiceWorkerClientIterator( - &container_host_by_uuid_, + &service_worker_clients_by_uuid_, base::BindRepeating(IsSameOriginWindowServiceWorkerClient, key, include_reserved_clients)); } @@ -419,7 +418,7 @@ FROM_HERE, base::BindOnce(std::move(callback), has_main_frame)); } -base::WeakPtr<ServiceWorkerContainerHost> +base::WeakPtr<ServiceWorkerClient> ServiceWorkerContextCore::CreateContainerHostForWindow( mojo::PendingAssociatedReceiver<blink::mojom::ServiceWorkerContainerHost> host_receiver, @@ -427,26 +426,25 @@ mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> container_remote, int frame_tree_node_id) { - auto container_host = std::make_unique<ServiceWorkerContainerHostForClient>( - AsWeakPtr(), are_ancestors_secure, std::move(container_remote), - frame_tree_node_id); - - ServiceWorkerContainerHost* container_host_ptr = container_host.get(); - - auto inserted = - container_host_by_uuid_ - .emplace(container_host_ptr->client_uuid(), std::move(container_host)) - .second; + auto client = std::make_unique<ServiceWorkerClient>( + AsWeakPtr(), are_ancestors_secure, frame_tree_node_id); + auto weak_client = client->AsWeakPtr(); + auto inserted = service_worker_clients_by_uuid_ + .emplace(weak_client->client_uuid(), std::move(client)) + .second; DCHECK(inserted); // Bind the host receiver. - container_host_receivers_->Add(container_host_ptr, std::move(host_receiver), - container_host_ptr); + ServiceWorkerContainerHostForClient::Create(weak_client, + std::move(container_remote)); + container_host_receivers_->Add(&weak_client->container_host(), + std::move(host_receiver), + &weak_client->container_host()); - return base::AsWeakPtr(container_host_ptr); + return weak_client; } -base::WeakPtr<ServiceWorkerContainerHost> +base::WeakPtr<ServiceWorkerClient> ServiceWorkerContextCore::CreateContainerHostForWorker( mojo::PendingAssociatedReceiver<blink::mojom::ServiceWorkerContainerHost> host_receiver, @@ -454,53 +452,52 @@ mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> container_remote, ServiceWorkerClientInfo client_info) { - auto container_host = std::make_unique<ServiceWorkerContainerHostForClient>( - AsWeakPtr(), process_id, std::move(container_remote), client_info); - - ServiceWorkerContainerHost* container_host_ptr = container_host.get(); - - bool inserted = - container_host_by_uuid_ - .emplace(container_host_ptr->client_uuid(), std::move(container_host)) - .second; + auto client = std::make_unique<ServiceWorkerClient>(AsWeakPtr(), process_id, + client_info); + auto weak_client = client->AsWeakPtr(); + auto inserted = service_worker_clients_by_uuid_ + .emplace(weak_client->client_uuid(), std::move(client)) + .second; DCHECK(inserted); // Bind the host receiver. - container_host_receivers_->Add(container_host_ptr, std::move(host_receiver), - container_host_ptr); + ServiceWorkerContainerHostForClient::Create(weak_client, + std::move(container_remote)); + container_host_receivers_->Add(&weak_client->container_host(), + std::move(host_receiver), + &weak_client->container_host()); - return base::AsWeakPtr(container_host_ptr); + return weak_client; } void ServiceWorkerContextCore::UpdateContainerHostClientID( const std::string& current_client_uuid, const std::string& new_client_uuid) { - auto it = container_host_by_uuid_.find(current_client_uuid); - DCHECK(it != container_host_by_uuid_.end()); - std::unique_ptr<ServiceWorkerContainerHost> container_host = + auto it = service_worker_clients_by_uuid_.find(current_client_uuid); + DCHECK(it != service_worker_clients_by_uuid_.end()); + std::unique_ptr<ServiceWorkerClient> service_worker_client = std::move(it->second); - container_host_by_uuid_.erase(it); + service_worker_clients_by_uuid_.erase(it); - bool inserted = container_host_by_uuid_ - .emplace(new_client_uuid, std::move(container_host)) - .second; + bool inserted = + service_worker_clients_by_uuid_ + .emplace(new_client_uuid, std::move(service_worker_client)) + .second; DCHECK(inserted); } -ServiceWorkerContainerHost* -ServiceWorkerContextCore::GetContainerHostByClientID( +ServiceWorkerClient* ServiceWorkerContextCore::GetContainerHostByClientID( const std::string& client_uuid) { - auto it = container_host_by_uuid_.find(client_uuid); - if (it == container_host_by_uuid_.end()) + auto it = service_worker_clients_by_uuid_.find(client_uuid); + if (it == service_worker_clients_by_uuid_.end()) { return nullptr; - DCHECK(it->second->IsContainerForClient()); + } return it->second.get(); } -ServiceWorkerContainerHost* -ServiceWorkerContextCore::GetContainerHostByWindowId( +ServiceWorkerClient* ServiceWorkerContextCore::GetContainerHostByWindowId( const base::UnguessableToken& window_id) { - for (auto& it : container_host_by_uuid_) { + for (auto& it : service_worker_clients_by_uuid_) { if (it.second->fetch_request_window_id() == window_id) return it.second.get(); } @@ -509,15 +506,17 @@ } void ServiceWorkerContextCore::OnContainerHostReceiverDisconnected() { - ServiceWorkerContainerHost* container_host = + ServiceWorkerContainerHostForClient* container_host = container_host_receivers_->current_context(); - observer_list_->Notify(FROM_HERE, - &ServiceWorkerContextCoreObserver::OnClientDestroyed, - container_host->ukm_source_id(), container_host->url(), - container_host->GetClientType()); + observer_list_->Notify( + FROM_HERE, &ServiceWorkerContextCoreObserver::OnClientDestroyed, + container_host->service_worker_client().ukm_source_id(), + container_host->url(), + container_host->service_worker_client().GetClientType()); - size_t removed = container_host_by_uuid_.erase(container_host->client_uuid()); + size_t removed = service_worker_clients_by_uuid_.erase( + container_host->service_worker_client().client_uuid()); DCHECK_EQ(removed, 1u); } @@ -684,12 +683,12 @@ } void ServiceWorkerContextCore::NotifyClientIsExecutionReady( - const ServiceWorkerContainerHost& container_host) { - DCHECK(container_host.is_execution_ready()); + const ServiceWorkerClient& service_worker_client) { + DCHECK(service_worker_client.is_execution_ready()); observer_list_->Notify( FROM_HERE, &ServiceWorkerContextCoreObserver::OnClientIsExecutionReady, - container_host.ukm_source_id(), container_host.url(), - container_host.GetClientType()); + service_worker_client.ukm_source_id(), service_worker_client.url(), + service_worker_client.GetClientType()); } bool ServiceWorkerContextCore::MaybeHasRegistrationForStorageKey(
diff --git a/content/browser/service_worker/service_worker_context_core.h b/content/browser/service_worker/service_worker_context_core.h index 27d6fea..e76b5a1 100644 --- a/content/browser/service_worker/service_worker_context_core.h +++ b/content/browser/service_worker/service_worker_context_core.h
@@ -6,7 +6,6 @@ #define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_CONTEXT_CORE_H_ #include <stdint.h> - #include <map> #include <memory> #include <optional> @@ -43,12 +42,14 @@ } // namespace storage namespace content { +class ServiceWorkerContainerHostForClient; class ServiceWorkerContextCoreObserver; -struct ServiceWorkerContextSynchronousObserverList; class ServiceWorkerContextWrapper; class ServiceWorkerJobCoordinator; class ServiceWorkerQuotaClient; class ServiceWorkerRegistration; +struct ServiceWorkerContextSynchronousObserverList; + #if !BUILDFLAG(IS_ANDROID) class ServiceWorkerHidDelegateObserver; class ServiceWorkerUsbDelegateObserver; @@ -76,13 +77,13 @@ using UnregistrationCallback = base::OnceCallback<void(blink::ServiceWorkerStatusCode status)>; using ContainerHostByClientUUIDMap = - std::map<std::string, std::unique_ptr<ServiceWorkerContainerHost>>; + std::map<std::string, std::unique_ptr<ServiceWorkerClient>>; using WarmUpRequest = std::tuple<GURL, blink::StorageKey, ServiceWorkerContext::WarmUpServiceWorkerCallback>; - // Iterates over ServiceWorkerContainerHost objects in the + // Iterates over ServiceWorkerClient objects in the // ContainerHostByClientUUIDMap. // Note: As ServiceWorkerClientIterator is operating on a member of // ServiceWorkerContextCore, users must ensure the ServiceWorkerContextCore @@ -98,13 +99,13 @@ ServiceWorkerClientIterator& operator++(); bool IsAtEnd() const; - ServiceWorkerContainerHost& operator*() const; - ServiceWorkerContainerHost* operator->() const; + ServiceWorkerClient& operator*() const; + ServiceWorkerClient* operator->() const; private: friend class ServiceWorkerContextCore; using ContainerHostPredicate = - base::RepeatingCallback<bool(ServiceWorkerContainerHost&)>; + base::RepeatingCallback<bool(ServiceWorkerClient&)>; ServiceWorkerClientIterator(ContainerHostByClientUUIDMap* map, ContainerHostPredicate predicate); void ForwardUntilMatchingServiceWorkerClient(); @@ -160,9 +161,8 @@ void OnClientNavigated(const GURL& script_url, const GURL& url); // OnControlleeAdded/Removed are called asynchronously. It is possible the - // container host identified by |client_uuid| was already destroyed when they - // are called. - // Note regarding BackForwardCache integration: + // service worker client identified by |client_uuid| was already destroyed + // when they are called. Note regarding BackForwardCache integration: // OnControlleeRemoved is called when a controllee enters back-forward // cache, and OnControlleeAdded is called when a controllee is restored from // back-forward cache. @@ -228,19 +228,19 @@ const blink::StorageKey& key, bool include_reserved_clients); - // Runs the callback with true if there is a ContainerHost for `key` of - // type blink::mojom::ServiceWorkerContainerType::kForWindow which is a main - // (top-level) frame. Reserved clients are ignored. + // Runs the callback with true if there is a service worker client for `key` + // of type blink::mojom::ServiceWorkerContainerType::kForWindow which is a + // main (top-level) frame. Reserved clients are ignored. // TODO(crbug.com/40568315): Make this synchronously return bool when the core // thread is UI. void HasMainFrameWindowClient(const blink::StorageKey& key, BoolCallback callback); - // Used to create a ServiceWorkerContainerHost for a window during a + // Used to create a ServiceWorkerClient for a window during a // navigation. |are_ancestors_secure| should be true for main frames. // Otherwise it is true iff all ancestor frames of this frame have a secure // origin. |frame_tree_node_id| is FrameTreeNode id. - base::WeakPtr<ServiceWorkerContainerHost> CreateContainerHostForWindow( + base::WeakPtr<ServiceWorkerClient> CreateContainerHostForWindow( mojo::PendingAssociatedReceiver<blink::mojom::ServiceWorkerContainerHost> host_receiver, bool are_ancestors_secure, @@ -249,8 +249,8 @@ int frame_tree_node_id); // Used for starting a web worker (dedicated worker or shared worker). Returns - // a container host for the worker. - base::WeakPtr<ServiceWorkerContainerHost> CreateContainerHostForWorker( + // a service worker client for the worker. + base::WeakPtr<ServiceWorkerClient> CreateContainerHostForWorker( mojo::PendingAssociatedReceiver<blink::mojom::ServiceWorkerContainerHost> host_receiver, int process_id, @@ -258,16 +258,16 @@ container_remote, ServiceWorkerClientInfo client_info); - // Updates the client UUID of an existing container host. + // Updates the client UUID of an existing service worker client. void UpdateContainerHostClientID(const std::string& current_client_uuid, const std::string& new_client_uuid); - // Retrieves a container host given its client UUID. - ServiceWorkerContainerHost* GetContainerHostByClientID( + // Retrieves a service worker client given its client UUID. + ServiceWorkerClient* GetContainerHostByClientID( const std::string& client_uuid); - // Retrieves a container host given its window ID. - ServiceWorkerContainerHost* GetContainerHostByWindowId( + // Retrieves a service worker client given its window ID. + ServiceWorkerClient* GetContainerHostByWindowId( const base::UnguessableToken& window_id); void OnContainerHostReceiverDisconnected(); @@ -407,7 +407,7 @@ int GetNextEmbeddedWorkerId(); void NotifyClientIsExecutionReady( - const ServiceWorkerContainerHost& container_host); + const ServiceWorkerClient& service_worker_client); bool MaybeHasRegistrationForStorageKey(const blink::StorageKey& key); @@ -522,14 +522,13 @@ // Bind() to hold a reference to |wrapper_| until |this| is fully destroyed. raw_ptr<ServiceWorkerContextWrapper> wrapper_; - // |container_host_by_uuid_| owns container hosts for service worker clients. - // Container hosts for service worker execution contexts are owned by - // ServiceWorkerHost. - ContainerHostByClientUUIDMap container_host_by_uuid_; + // Owns `ServiceWorkerContainerForClient` (via `ServiceWorkerClient`). + // `ServiceWorkerContainerForServiceWorker`s are owned by `ServiceWorkerHost`. + ContainerHostByClientUUIDMap service_worker_clients_by_uuid_; std::unique_ptr< mojo::AssociatedReceiverSet<blink::mojom::ServiceWorkerContainerHost, - ServiceWorkerContainerHost*>> + ServiceWorkerContainerHostForClient*>> container_host_receivers_; std::unique_ptr<ServiceWorkerRegistry> registry_;
diff --git a/content/browser/service_worker/service_worker_context_core_unittest.cc b/content/browser/service_worker/service_worker_context_core_unittest.cc index a1b31ca0..957e4e0 100644 --- a/content/browser/service_worker/service_worker_context_core_unittest.cc +++ b/content/browser/service_worker/service_worker_context_core_unittest.cc
@@ -142,15 +142,15 @@ return status; } - ServiceWorkerContainerHost* CreateControllee() { + ServiceWorkerClient* CreateControllee() { remote_endpoints_.emplace_back(); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(/*mock process_id=*/33, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), &remote_endpoints_.back()); - return container_host.get(); + return service_worker_client.get(); } protected: @@ -271,10 +271,11 @@ RegisterServiceWorker(scope, key, options, ®istration); // Add a controlled client. - ServiceWorkerContainerHost* container_host = CreateControllee(); - container_host->UpdateUrls(scope, origin, key); - container_host->SetControllerRegistration(registration, - /*notify_controllerchange=*/false); + ServiceWorkerClient* service_worker_client = CreateControllee(); + service_worker_client->UpdateUrls(scope, origin, key); + service_worker_client->SetControllerRegistration( + registration, + /*notify_controllerchange=*/false); // Unregister, which will wait to clear until the controlled client unloads. EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, Unregister(scope, key));
diff --git a/content/browser/service_worker/service_worker_context_unittest.cc b/content/browser/service_worker/service_worker_context_unittest.cc index d2c540d..2953a6a 100644 --- a/content/browser/service_worker/service_worker_context_unittest.cc +++ b/content/browser/service_worker/service_worker_context_unittest.cc
@@ -478,7 +478,7 @@ version->SetStatus(ServiceWorkerVersion::ACTIVATED); ServiceWorkerRemoteContainerEndpoint endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), @@ -486,7 +486,7 @@ TestServiceWorkerContextObserver observer(context_wrapper()); - version->AddControllee(container_host.get()); + version->AddControllee(service_worker_client.get()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(1u, observer.events().size()); @@ -494,7 +494,8 @@ observer.events()[0].type); version->OnControlleeNavigationCommitted( - container_host->client_uuid(), container_host->GetRenderFrameHostId()); + service_worker_client->client_uuid(), + service_worker_client->GetRenderFrameHostId()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(2u, observer.events().size()); @@ -502,7 +503,7 @@ ControlleeNavigationCommitted, observer.events()[1].type); - version->RemoveControllee(container_host->client_uuid()); + version->RemoveControllee(service_worker_client->client_uuid()); base::RunLoop().RunUntilIdle(); ASSERT_EQ(4u, observer.events().size()); @@ -1121,33 +1122,36 @@ // Host1 : process_id=1, origin1. remote_endpoints.emplace_back(); - base::WeakPtr<ServiceWorkerContainerHost> container_host1 = + base::WeakPtr<ServiceWorkerClient> service_worker_client1 = CreateContainerHostForWindow( GlobalRenderFrameHostId(kRenderProcessId1, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoints.back()); - container_host1->UpdateUrls(kOrigin1, url::Origin::Create(kOrigin1), kKey1); + service_worker_client1->UpdateUrls(kOrigin1, url::Origin::Create(kOrigin1), + kKey1); // Host2 : process_id=2, origin2. remote_endpoints.emplace_back(); - base::WeakPtr<ServiceWorkerContainerHost> container_host2 = + base::WeakPtr<ServiceWorkerClient> service_worker_client2 = CreateContainerHostForWindow( GlobalRenderFrameHostId(kRenderProcessId2, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoints.back()); - container_host2->UpdateUrls(kOrigin2, url::Origin::Create(kOrigin2), kKey2); + service_worker_client2->UpdateUrls(kOrigin2, url::Origin::Create(kOrigin2), + kKey2); // Host3 : process_id=2, origin1. remote_endpoints.emplace_back(); - base::WeakPtr<ServiceWorkerContainerHost> container_host3 = + base::WeakPtr<ServiceWorkerClient> service_worker_client3 = CreateContainerHostForWindow( GlobalRenderFrameHostId(kRenderProcessId2, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoints.back()); - container_host3->UpdateUrls(kOrigin1, url::Origin::Create(kOrigin1), kKey1); + service_worker_client3->UpdateUrls(kOrigin1, url::Origin::Create(kOrigin1), + kKey1); // Host4 : process_id=2, origin2, for ServiceWorker. blink::mojom::ServiceWorkerRegistrationOptions registration_opt; @@ -1167,19 +1171,19 @@ mojo::PendingRemote<storage::mojom::ServiceWorkerLiveVersionRef>(), helper_->context()->AsWeakPtr()); remote_endpoints.emplace_back(); - // ServiceWorkerHost creates ServiceWorkerContainerHost for a service worker + // ServiceWorkerHost creates ServiceWorkerClient for a service worker // execution context. std::unique_ptr<ServiceWorkerHost> worker_host4 = CreateServiceWorkerHost( kRenderProcessId2, true /* is_parent_frame_secure */, *version, context()->AsWeakPtr(), &remote_endpoints.back()); - ASSERT_TRUE(container_host1); - ASSERT_TRUE(container_host2); - ASSERT_TRUE(container_host3); + ASSERT_TRUE(service_worker_client1); + ASSERT_TRUE(service_worker_client2); + ASSERT_TRUE(service_worker_client3); ASSERT_TRUE(worker_host4->container_host()); // Iterate over the client container hosts that belong to kOrigin1. - std::set<ServiceWorkerContainerHost*> results; + std::set<ServiceWorkerClient*> results; for (auto it = context()->GetServiceWorkerClients( kKey1, true /* include_reserved_clients */, false /* include_back_forward_cached_clients */); @@ -1187,11 +1191,11 @@ results.insert(&*it); } EXPECT_EQ(2u, results.size()); - EXPECT_TRUE(base::Contains(results, container_host1.get())); - EXPECT_TRUE(base::Contains(results, container_host3.get())); + EXPECT_TRUE(base::Contains(results, service_worker_client1.get())); + EXPECT_TRUE(base::Contains(results, service_worker_client3.get())); // Iterate over the container hosts that belong to kOrigin2. This should not - // include worker_host4->container_host() as it's not for controllee. + // include worker_host4->service_worker_client() as it's not for controllee. results.clear(); for (auto it = context()->GetServiceWorkerClients( kKey2, true /* include_reserved_clients */, @@ -1200,7 +1204,7 @@ results.insert(&*it); } EXPECT_EQ(1u, results.size()); - EXPECT_TRUE(base::Contains(results, container_host2.get())); + EXPECT_TRUE(base::Contains(results, service_worker_client2.get())); } class ServiceWorkerContextRecoveryTest
diff --git a/content/browser/service_worker/service_worker_controllee_request_handler.cc b/content/browser/service_worker/service_worker_controllee_request_handler.cc index 97f9240..9c13829 100644 --- a/content/browser/service_worker/service_worker_controllee_request_handler.cc +++ b/content/browser/service_worker/service_worker_controllee_request_handler.cc
@@ -95,13 +95,13 @@ ServiceWorkerControlleeRequestHandler::ServiceWorkerControlleeRequestHandler( base::WeakPtr<ServiceWorkerContextCore> context, - base::WeakPtr<ServiceWorkerContainerHost> container_host, + base::WeakPtr<ServiceWorkerClient> service_worker_client, network::mojom::RequestDestination destination, bool skip_service_worker, int frame_tree_node_id, ServiceWorkerAccessedCallback service_worker_accessed_callback) : context_(std::move(context)), - container_host_(std::move(container_host)), + service_worker_client_(std::move(service_worker_client)), destination_(destination), skip_service_worker_(skip_service_worker), force_update_started_(false), @@ -126,7 +126,7 @@ } void ServiceWorkerControlleeRequestHandler::MaybeScheduleUpdate() { - if (!container_host_ || !container_host_->controller()) { + if (!service_worker_client_ || !service_worker_client_->controller()) { return; } @@ -146,7 +146,7 @@ return; } - container_host_->controller()->ScheduleUpdate(); + service_worker_client_->controller()->ScheduleUpdate(); } void ServiceWorkerControlleeRequestHandler::MaybeCreateLoader( @@ -158,7 +158,7 @@ loader_callback_ = std::move(loader_callback); fallback_callback_ = std::move(fallback_callback); - if (!container_host_) { + if (!service_worker_client_) { // We can't do anything other than to fall back to network. CompleteWithoutLoader(); return; @@ -218,21 +218,23 @@ const blink::StorageKey& storage_key) { // Update the container host with this request, clearing old controller state // if this is a redirect. - container_host_->SetControllerRegistration(nullptr, - /*notify_controllerchange=*/false); + service_worker_client_->SetControllerRegistration( + nullptr, + /*notify_controllerchange=*/false); stripped_url_ = net::SimplifyUrlForRequest(tentative_resource_request.url); storage_key_ = storage_key; - container_host_->UpdateUrls(stripped_url_, - // The storage key only has a top_level_site, not - // an origin, so we must extract the origin from - // trusted_params. - tentative_resource_request.trusted_params - ? tentative_resource_request.trusted_params - ->isolation_info.top_frame_origin() - : std::nullopt, - storage_key_); + service_worker_client_->UpdateUrls( + stripped_url_, + // The storage key only has a top_level_site, not + // an origin, so we must extract the origin from + // trusted_params. + tentative_resource_request.trusted_params + ? tentative_resource_request.trusted_params->isolation_info + .top_frame_origin() + : std::nullopt, + storage_key_); } void ServiceWorkerControlleeRequestHandler::ContinueWithRegistration( @@ -273,7 +275,7 @@ } DCHECK(registration); - if (!container_host_) { + if (!service_worker_client_) { TRACE_EVENT_WITH_FLOW1( "ServiceWorker", "ServiceWorkerControlleeRequestHandler::ContinueWithRegistration", @@ -283,7 +285,7 @@ CompleteWithoutLoader(); return; } - container_host_->AddMatchingRegistration(registration.get()); + service_worker_client_->AddMatchingRegistration(registration.get()); if (!context_) { TRACE_EVENT_WITH_FLOW1( @@ -300,8 +302,8 @@ GetContentClient()->browser()->AllowServiceWorker( registration->scope(), service_worker_security_utils::site_for_cookies( - container_host_->key()), - container_host_->top_frame_origin(), /*script_url=*/GURL(), + service_worker_client_->key()), + service_worker_client_->top_frame_origin(), /*script_url=*/GURL(), context_->wrapper()->browser_context()); service_worker_accessed_callback_.Run(registration->scope(), @@ -318,7 +320,7 @@ return; } - if (!container_host_->IsEligibleForServiceWorkerController()) { + if (!service_worker_client_->IsEligibleForServiceWorkerController()) { // TODO(falken): Figure out a way to surface in the page's DevTools // console that the service worker was blocked for security. TRACE_EVENT_WITH_FLOW1( @@ -406,7 +408,7 @@ scoped_refptr<ServiceWorkerRegistration> registration, scoped_refptr<ServiceWorkerVersion> active_version, base::TimeTicks find_registration_start_time) { - if (!context_ || !container_host_) { + if (!context_ || !service_worker_client_) { TRACE_EVENT_WITH_FLOW1( "ServiceWorker", "ServiceWorkerControlleeRequestHandler::ContinueWithActivatedVersion", @@ -449,11 +451,11 @@ return; } - container_host_->SetControllerRegistration( + service_worker_client_->SetControllerRegistration( registration, false /* notify_controllerchange */); DCHECK_EQ(active_version, registration->active_version()); - DCHECK_EQ(active_version, container_host_->controller()); + DCHECK_EQ(active_version, service_worker_client_->controller()); DCHECK_NE(active_version->fetch_handler_existence(), ServiceWorkerVersion::FetchHandlerExistence::UNKNOWN); @@ -463,7 +465,7 @@ active_version->fetch_handler_type()); if (blink::IsRequestDestinationFrame(destination_)) { - container_host_->AddServiceWorkerToUpdate(active_version); + service_worker_client_->AddServiceWorkerToUpdate(active_version); } // If the router evaluation is needed, always forward to the service worker. @@ -530,16 +532,16 @@ base::TimeTicks find_registration_start_time) { loader_wrapper_ = std::make_unique<ServiceWorkerMainResourceLoaderWrapper>( std::make_unique<ServiceWorkerMainResourceLoader>( - std::move(fallback_callback_), container_host_, frame_tree_node_id_, - std::move(find_registration_start_time))); + std::move(fallback_callback_), service_worker_client_, + frame_tree_node_id_, std::move(find_registration_start_time))); loader_wrapper_->get()->set_worker_parent_client_uuid(parent_client_uuid_); std::move(loader_callback_) .Run(NavigationLoaderInterceptor::Result( base::MakeRefCounted<network::SingleRequestURLLoaderFactory>( base::BindOnce(&ServiceWorkerMainResourceLoader::StartRequest, loader_wrapper_->get()->AsWeakPtr())), - ServiceWorkerContainerHost::MaybeCreateSubresourceLoaderParams( - container_host_))); + ServiceWorkerClient::MaybeCreateSubresourceLoaderParams( + service_worker_client_))); } void ServiceWorkerControlleeRequestHandler::DidStartWorker( @@ -647,7 +649,7 @@ void ServiceWorkerControlleeRequestHandler::CompleteWithoutLoader() { fallback_callback_.Reset(); ServiceWorkerMainResourceLoaderInterceptor::CompleteWithoutLoader( - std::move(loader_callback_), container_host_); + std::move(loader_callback_), service_worker_client_); } void ServiceWorkerControlleeRequestHandler::MaybeStartServiceWorker(
diff --git a/content/browser/service_worker/service_worker_controllee_request_handler.h b/content/browser/service_worker/service_worker_controllee_request_handler.h index 0ab206f6..f297bf5d 100644 --- a/content/browser/service_worker/service_worker_controllee_request_handler.h +++ b/content/browser/service_worker/service_worker_controllee_request_handler.h
@@ -28,7 +28,7 @@ namespace content { -class ServiceWorkerContainerHost; +class ServiceWorkerClient; class ServiceWorkerContextCore; class ServiceWorkerRegistration; class ServiceWorkerVersion; @@ -38,7 +38,7 @@ // live across redirects. ServiceWorkerMainResourceLoaderInterceptor creates // one instance of this class for each request/redirect. // -// This class associates the ServiceWorkerContainerHost undergoing navigation +// This class associates the ServiceWorkerClient undergoing navigation // with a controller service worker, after looking up the registration and // activating the service worker if needed. Once ready, it creates // ServiceWorkerMainResourceLoader to perform the resource load. @@ -84,7 +84,7 @@ // request interception. ServiceWorkerControlleeRequestHandler( base::WeakPtr<ServiceWorkerContextCore> context, - base::WeakPtr<ServiceWorkerContainerHost> container_host, + base::WeakPtr<ServiceWorkerClient> service_worker_client, network::mojom::RequestDestination destination, bool skip_service_worker, int frame_tree_node_id, @@ -119,7 +119,7 @@ FRIEND_TEST_ALL_PREFIXES(ServiceWorkerControlleeRequestHandlerTest, ActivateWaitingVersion); - // Does all initialization of |container_host_| for a request. + // Does all initialization of |service_worker_client_| for a request. void InitializeContainerHost( const network::ResourceRequest& tentative_request, const blink::StorageKey& storage_key); @@ -170,7 +170,7 @@ start_service_worker_for_empty_fetch_handler_duration_for_testing_; const base::WeakPtr<ServiceWorkerContextCore> context_; - const base::WeakPtr<ServiceWorkerContainerHost> container_host_; + const base::WeakPtr<ServiceWorkerClient> service_worker_client_; const network::mojom::RequestDestination destination_; // If true, service workers are bypassed for request interception.
diff --git a/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc b/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc index 6f173b2..e31e65c 100644 --- a/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc +++ b/content/browser/service_worker/service_worker_controllee_request_handler_unittest.cc
@@ -84,7 +84,7 @@ TRAFFIC_ANNOTATION_FOR_TESTS)), handler_(std::make_unique<ServiceWorkerControlleeRequestHandler>( test->context()->AsWeakPtr(), - test->container_host_, + test->service_worker_client_, destination, /*skip_service_worker=*/false, /*frame_tree_node_id=*/RenderFrameHost::kNoFrameTreeNodeId, @@ -204,7 +204,7 @@ // An empty host. remote_endpoints_.emplace_back(); - container_host_ = CreateContainerHostForWindow( + service_worker_client_ = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), is_parent_frame_secure, helper_->context()->AsWeakPtr(), @@ -229,7 +229,7 @@ std::unique_ptr<EmbeddedWorkerTestHelper> helper_; scoped_refptr<ServiceWorkerRegistration> registration_; scoped_refptr<ServiceWorkerVersion> version_; - base::WeakPtr<ServiceWorkerContainerHost> container_host_; + base::WeakPtr<ServiceWorkerClient> service_worker_client_; std::unique_ptr<net::URLRequestContext> url_request_context_; net::TestDelegate url_request_delegate_; GURL scope_; @@ -436,8 +436,8 @@ // claim(). EXPECT_FALSE(test_resources.loader()); EXPECT_FALSE(version_->HasControllee()); - EXPECT_FALSE(container_host_->controller()); - EXPECT_EQ(registration_.get(), container_host_->MatchRegistration()); + EXPECT_FALSE(service_worker_client_->controller()); + EXPECT_EQ(registration_.get(), service_worker_client_->MatchRegistration()); } // Test to not regress crbug/414118. @@ -468,7 +468,7 @@ // the database lookup. CloseRemotes(); base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(container_host_); + EXPECT_FALSE(service_worker_client_); EXPECT_FALSE(test_resources.loader()); } @@ -491,7 +491,7 @@ network::mojom::RequestDestination::kDocument); test_resources.SetHandler( std::make_unique<ServiceWorkerControlleeRequestHandler>( - context()->AsWeakPtr(), container_host_, + context()->AsWeakPtr(), service_worker_client_, network::mojom::RequestDestination::kDocument, /*skip_service_worker=*/true, /*frame_tree_node_id=*/RenderFrameHost::kNoFrameTreeNodeId, @@ -508,7 +508,7 @@ EXPECT_FALSE(version_->HasControllee()); // The host should still have the correct URL. - EXPECT_EQ(GURL("https://host/scope/doc"), container_host_->url()); + EXPECT_EQ(GURL("https://host/scope/doc"), service_worker_client_->url()); } // Tests interception after the context core has been destroyed and the provider @@ -534,7 +534,7 @@ network::mojom::RequestDestination::kDocument); test_resources.SetHandler( std::make_unique<ServiceWorkerControlleeRequestHandler>( - context()->AsWeakPtr(), container_host_, + context()->AsWeakPtr(), service_worker_client_, network::mojom::RequestDestination::kDocument, /*skip_service_worker=*/false, /*frame_tree_node_id=*/RenderFrameHost::kNoFrameTreeNodeId, @@ -560,7 +560,7 @@ EXPECT_FALSE(version_->HasControllee()); // The host should still have the correct URL. - EXPECT_EQ(GURL("https://host/scope/doc"), container_host_->url()); + EXPECT_EQ(GURL("https://host/scope/doc"), service_worker_client_->url()); } #if BUILDFLAG(ENABLE_OFFLINE_PAGES)
diff --git a/content/browser/service_worker/service_worker_host.cc b/content/browser/service_worker/service_worker_host.cc index 5f834261..3e48cd4bc 100644 --- a/content/browser/service_worker/service_worker_host.cc +++ b/content/browser/service_worker/service_worker_host.cc
@@ -127,8 +127,7 @@ void ServiceWorkerHost::BindUsbService( mojo::PendingReceiver<blink::mojom::WebUsbService> receiver) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - DCHECK(container_host_->top_frame_origin()); - if (container_host_->top_frame_origin()->opaque()) { + if (container_host_->top_frame_origin().opaque()) { // Service worker should not be available to a window/worker client whose // origin is opaque according to Service Worker specification. However, this // can possibly be triggered by a compromised renderer, so reject it and @@ -139,7 +138,7 @@ return; } version_->embedded_worker()->BindUsbService( - *container_host_->top_frame_origin(), std::move(receiver)); + container_host_->top_frame_origin(), std::move(receiver)); } net::NetworkIsolationKey ServiceWorkerHost::GetNetworkIsolationKey() const {
diff --git a/content/browser/service_worker/service_worker_host.h b/content/browser/service_worker/service_worker_host.h index afe0700..e268442 100644 --- a/content/browser/service_worker/service_worker_host.h +++ b/content/browser/service_worker/service_worker_host.h
@@ -99,7 +99,7 @@ void BindUsbService( mojo::PendingReceiver<blink::mojom::WebUsbService> receiver); - content::ServiceWorkerContainerHost* container_host() { + content::ServiceWorkerContainerHostForServiceWorker* container_host() { return container_host_.get(); } @@ -165,7 +165,7 @@ mojo::Receiver<blink::mojom::BrowserInterfaceBroker> broker_receiver_{ &broker_}; - std::unique_ptr<ServiceWorkerContainerHost> container_host_; + std::unique_ptr<ServiceWorkerContainerHostForServiceWorker> container_host_; service_manager::InterfaceProvider remote_interfaces_{ base::SingleThreadTaskRunner::GetCurrentDefault()};
diff --git a/content/browser/service_worker/service_worker_job_unittest.cc b/content/browser/service_worker/service_worker_job_unittest.cc index 9f8a842..e40b030 100644 --- a/content/browser/service_worker/service_worker_job_unittest.cc +++ b/content/browser/service_worker/service_worker_job_unittest.cc
@@ -238,7 +238,7 @@ const blink::StorageKey& key, blink::ServiceWorkerStatusCode expected_status = blink::ServiceWorkerStatusCode::kOk); - ServiceWorkerContainerHost* CreateControllee(); + ServiceWorkerClient* CreateControllee(); scoped_refptr<ServiceWorkerRegistration> CreateRegistrationWithControllee( const GURL& script_url, const GURL& scope_url); @@ -316,15 +316,15 @@ return registration; } -ServiceWorkerContainerHost* ServiceWorkerJobTest::CreateControllee() { +ServiceWorkerClient* ServiceWorkerJobTest::CreateControllee() { remote_endpoints_.emplace_back(); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(/*mock process_id=*/33, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), &remote_endpoints_.back()); - return container_host.get(); + return service_worker_client.get(); } scoped_refptr<ServiceWorkerRegistration> @@ -343,11 +343,12 @@ TestServiceWorkerObserver observer(helper_->context_wrapper()); observer.RunUntilActivated(registration->installing_version(), runner); - ServiceWorkerContainerHost* container_host = CreateControllee(); - container_host->UpdateUrls(scope_url, url::Origin::Create(scope_url), - storage_key); - container_host->SetControllerRegistration(registration, - /*notify_controllerchange=*/false); + ServiceWorkerClient* service_worker_client = CreateControllee(); + service_worker_client->UpdateUrls(scope_url, url::Origin::Create(scope_url), + storage_key); + service_worker_client->SetControllerRegistration( + registration, + /*notify_controllerchange=*/false); return registration; } @@ -1017,8 +1018,8 @@ observer.RunUntilActivated(registration->installing_version(), runner); ASSERT_TRUE(registration.get()); - ServiceWorkerContainerHost* container_host = CreateControllee(); - registration->active_version()->AddControllee(container_host); + ServiceWorkerClient* service_worker_client = CreateControllee(); + registration->active_version()->AddControllee(service_worker_client); scoped_refptr<ServiceWorkerVersion> version = registration->active_version(); EXPECT_EQ(blink::EmbeddedWorkerStatus::kRunning, version->running_status()); @@ -1031,7 +1032,7 @@ EXPECT_EQ(ServiceWorkerVersion::ACTIVATED, version->status()); registration->active_version()->RemoveControllee( - container_host->client_uuid()); + service_worker_client->client_uuid()); WaitForVersionRunningStatus(version, blink::EmbeddedWorkerStatus::kStopped); // The version should be stopped since there is no controllee. @@ -1053,9 +1054,9 @@ registration->SetTaskRunnerForTest(runner); // Add a controllee and queue an unregister to force the uninstalling state. - ServiceWorkerContainerHost* container_host = CreateControllee(); + ServiceWorkerClient* service_worker_client = CreateControllee(); scoped_refptr<ServiceWorkerVersion> version = registration->active_version(); - version->AddControllee(container_host); + version->AddControllee(service_worker_client); RunUnregisterJob(options.scope, key); // Make sure the registration is deleted and purgable resources // set for purging once the version goes dead. @@ -1095,9 +1096,9 @@ registration->SetTaskRunnerForTest(runner); // Add a controllee and queue an unregister to force the uninstalling state. - ServiceWorkerContainerHost* container_host = CreateControllee(); + ServiceWorkerClient* service_worker_client = CreateControllee(); scoped_refptr<ServiceWorkerVersion> version = registration->active_version(); - version->AddControllee(container_host); + version->AddControllee(service_worker_client); RunUnregisterJob(options.scope, key); // Make sure the registration is deleted and purgable resources // set for purging once the version goes dead. @@ -1151,10 +1152,10 @@ registration->SetTaskRunnerForTest(runner); // Add a controllee and queue an unregister to force the uninstalling state. - ServiceWorkerContainerHost* container_host = CreateControllee(); + ServiceWorkerClient* service_worker_client = CreateControllee(); scoped_refptr<ServiceWorkerVersion> old_version = registration->active_version(); - old_version->AddControllee(container_host); + old_version->AddControllee(service_worker_client); RunUnregisterJob(options.scope, key); // Register another script. @@ -1175,7 +1176,7 @@ EXPECT_EQ(ServiceWorkerVersion::INSTALLED, new_version->status()); // Make the old version eligible for eviction. - old_version->RemoveControllee(container_host->client_uuid()); + old_version->RemoveControllee(service_worker_client->client_uuid()); RequestTermination(&initial_client->host()); // Wait for activated. @@ -1204,10 +1205,10 @@ base::RunLoop().RunUntilIdle(); // Add a controllee and queue an unregister to force the uninstalling state. - ServiceWorkerContainerHost* container_host = CreateControllee(); + ServiceWorkerClient* service_worker_client = CreateControllee(); scoped_refptr<ServiceWorkerVersion> old_version = registration->active_version(); - old_version->AddControllee(container_host); + old_version->AddControllee(service_worker_client); RunUnregisterJob(options.scope, key); EXPECT_EQ(registration, RunRegisterJob(script2, key, options)); @@ -1237,7 +1238,7 @@ new_version->running_status()); EXPECT_EQ(ServiceWorkerVersion::INSTALLED, new_version->status()); - old_version->RemoveControllee(container_host->client_uuid()); + old_version->RemoveControllee(service_worker_client->client_uuid()); WaitForVersionRunningStatus(old_version, blink::EmbeddedWorkerStatus::kStopped); @@ -1273,10 +1274,10 @@ registration->SetTaskRunnerForTest(runner); // Add a controllee and queue an unregister to force the uninstalling state. - ServiceWorkerContainerHost* container_host = CreateControllee(); + ServiceWorkerClient* service_worker_client = CreateControllee(); scoped_refptr<ServiceWorkerVersion> old_version = registration->active_version(); - old_version->AddControllee(container_host); + old_version->AddControllee(service_worker_client); RunUnregisterJob(options.scope, key); EXPECT_EQ(registration, RunRegisterJob(script2, key, options)); @@ -1307,7 +1308,7 @@ EXPECT_FALSE(registration->is_uninstalling()); EXPECT_EQ(new_version, registration->waiting_version()); - old_version->RemoveControllee(container_host->client_uuid()); + old_version->RemoveControllee(service_worker_client->client_uuid()); RequestTermination(&initial_client->host()); // Wait for activated. @@ -1431,21 +1432,21 @@ GURL out_scope("https://www.example.com/page"); // Make an in-scope client. - ServiceWorkerContainerHost* client = CreateControllee(); + ServiceWorkerClient* client = CreateControllee(); client->UpdateUrls(in_scope, url::Origin::Create(in_scope), GetTestStorageKey(in_scope)); // Make an in-scope reserved client. - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(helper_->context()->AsWeakPtr(), /*are_ancestors_secure=*/true); - base::WeakPtr<ServiceWorkerContainerHost> reserved_client = - host_and_info->host; + base::WeakPtr<ServiceWorkerClient> reserved_client = + client_and_info->service_worker_client; reserved_client->UpdateUrls(in_scope, url::Origin::Create(in_scope), GetTestStorageKey(in_scope)); // Make an out-scope client. - ServiceWorkerContainerHost* out_scope_client = CreateControllee(); + ServiceWorkerClient* out_scope_client = CreateControllee(); out_scope_client->UpdateUrls(out_scope, url::Origin::Create(out_scope), GetTestStorageKey(out_scope)); @@ -2244,10 +2245,10 @@ registration->SetTaskRunnerForTest(runner); // Add a controllee and queue an unregister to force the uninstalling state. - ServiceWorkerContainerHost* container_host = CreateControllee(); + ServiceWorkerClient* service_worker_client = CreateControllee(); scoped_refptr<ServiceWorkerVersion> first_version = registration->active_version(); - first_version->AddControllee(container_host); + first_version->AddControllee(service_worker_client); RunUnregisterJob(options.scope, key); EXPECT_EQ(registration, RunRegisterJob(script2, key, options)); @@ -2273,7 +2274,7 @@ EXPECT_FALSE(registration->is_uninstalling()); EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, second_version->status()); - first_version->RemoveControllee(container_host->client_uuid()); + first_version->RemoveControllee(service_worker_client->client_uuid()); RequestTermination(&initial_client->host()); // Wait for activated. @@ -2307,10 +2308,10 @@ registration->SetTaskRunnerForTest(runner); // Add a controllee. - ServiceWorkerContainerHost* container_host = CreateControllee(); + ServiceWorkerClient* service_worker_client = CreateControllee(); scoped_refptr<ServiceWorkerVersion> first_version = registration->active_version(); - first_version->AddControllee(container_host); + first_version->AddControllee(service_worker_client); // Update. The new version should be waiting. // Change script body. @@ -2334,7 +2335,7 @@ // Remove the controllee. The new version should be activating, and delayed // until the runner runs again. - first_version->RemoveControllee(container_host->client_uuid()); + first_version->RemoveControllee(service_worker_client->client_uuid()); base::RunLoop().RunUntilIdle(); // Activating the new version won't happen until
diff --git a/content/browser/service_worker/service_worker_main_resource_handle.cc b/content/browser/service_worker/service_worker_main_resource_handle.cc index 4df92f0..ede48f0 100644 --- a/content/browser/service_worker/service_worker_main_resource_handle.cc +++ b/content/browser/service_worker/service_worker_main_resource_handle.cc
@@ -49,26 +49,27 @@ return; *out_container_info = std::move(container_info_); - if (container_host_) { - container_host_->OnBeginNavigationCommit(rfh_id, policy_container_policies, - std::move(coep_reporter), - document_ukm_source_id); + if (service_worker_client_) { + service_worker_client_->OnBeginNavigationCommit( + rfh_id, policy_container_policies, std::move(coep_reporter), + document_ukm_source_id); } } void ServiceWorkerMainResourceHandle::OnEndNavigationCommit() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (container_host_) - container_host_->OnEndNavigationCommit(); + if (service_worker_client_) { + service_worker_client_->OnEndNavigationCommit(); + } } void ServiceWorkerMainResourceHandle::OnBeginWorkerCommit( const PolicyContainerPolicies& policy_container_policies, ukm::SourceId worker_ukm_source_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (container_host_) { - container_host_->CompleteWebWorkerPreparation(policy_container_policies, - worker_ukm_source_id); + if (service_worker_client_) { + service_worker_client_->CompleteWebWorkerPreparation( + policy_container_policies, worker_ukm_source_id); } }
diff --git a/content/browser/service_worker/service_worker_main_resource_handle.h b/content/browser/service_worker/service_worker_main_resource_handle.h index bb0540f..e2029a7 100644 --- a/content/browser/service_worker/service_worker_main_resource_handle.h +++ b/content/browser/service_worker/service_worker_main_resource_handle.h
@@ -21,8 +21,8 @@ namespace content { -struct GlobalRenderFrameHostId; class ServiceWorkerContextWrapper; +struct GlobalRenderFrameHostId; // This class is used to manage the lifetime of ServiceWorkerContainerHosts // created for main resource requests (navigations and web workers). @@ -32,20 +32,20 @@ // 1) We create a ServiceWorkerMainResourceHandle without populating the // member service worker container info. // -// 2) If we pre-create a ServiceWorkerContainerHost for this navigation, it +// 2) If we pre-create a ServiceWorkerClient for this navigation, it // is added to ServiceWorkerContextCore and its container info is passed to // ServiceWorkerMainResourceHandle::OnCreatedContainerHost(). // // 3) When the navigation is ready to commit, the NavigationRequest will // call ServiceWorkerMainResourceHandle::OnBeginNavigationCommit() to -// - complete the initialization for the ServiceWorkerContainerHost. +// - complete the initialization for the ServiceWorkerClient. // - take out the container info to be sent as part of navigation commit // IPC. // // 4) When the navigation finishes, the ServiceWorkerMainResourceHandle is // destroyed. The destructor of the ServiceWorkerMainResourceHandle destroys // the container info which in turn leads to the destruction of an unclaimed -// ServiceWorkerContainerHost. +// ServiceWorkerClient. class CONTENT_EXPORT ServiceWorkerMainResourceHandle { public: ServiceWorkerMainResourceHandle( @@ -59,17 +59,17 @@ ~ServiceWorkerMainResourceHandle(); - // Called after a ServiceWorkerContainerHost tied with |container_info| was + // Called after a ServiceWorkerClient tied with |container_info| was // pre-created for the navigation. void OnCreatedContainerHost( blink::mojom::ServiceWorkerContainerInfoForClientPtr container_info); // Called when the navigation is ready to commit. // Provides |rfh_id|, and |policy_container_policies| to the pre-created - // container host. Fills in |out_container_info| so the caller can send it to - // the renderer process as part of the navigation commit IPC. + // service worker client. Fills in |out_container_info| so the caller can send + // it to the renderer process as part of the navigation commit IPC. // |out_container_info| can be filled as null if we failed to pre-create the - // container host for some security reasons. + // service worker client for some security reasons. void OnBeginNavigationCommit( const GlobalRenderFrameHostId& rfh_id, const PolicyContainerPolicies& policy_container_policies, @@ -84,7 +84,8 @@ // Similar to OnBeginNavigationCommit() for shared workers (and dedicated // workers when PlzDedicatedWorker is on). - // |policy_container_policies| is passed to the pre-created container host. + // |policy_container_policies| is passed to the pre-created service worker + // client. void OnBeginWorkerCommit( const PolicyContainerPolicies& policy_container_policies, ukm::SourceId worker_ukm_source_id); @@ -95,23 +96,23 @@ bool has_container_info() const { return !!container_info_; } - void set_container_host( - base::WeakPtr<ServiceWorkerContainerHost> container_host) { - container_host_ = std::move(container_host); + void set_service_worker_client( + base::WeakPtr<ServiceWorkerClient> service_worker_client) { + service_worker_client_ = std::move(service_worker_client); } - base::WeakPtr<ServiceWorkerContainerHost> container_host() { - return container_host_; + base::WeakPtr<ServiceWorkerClient> service_worker_client() { + return service_worker_client_; } - void set_parent_container_host( - base::WeakPtr<ServiceWorkerContainerHost> container_host) { - DCHECK(!parent_container_host_); - parent_container_host_ = std::move(container_host); + void set_parent_service_worker_client( + base::WeakPtr<ServiceWorkerClient> service_worker_client) { + DCHECK(!parent_service_worker_client_); + parent_service_worker_client_ = std::move(service_worker_client); } - base::WeakPtr<ServiceWorkerContainerHost> parent_container_host() { - return parent_container_host_; + base::WeakPtr<ServiceWorkerClient> parent_service_worker_client() { + return parent_service_worker_client_; } const ServiceWorkerAccessedCallback& service_worker_accessed_callback() { @@ -129,10 +130,10 @@ private: blink::mojom::ServiceWorkerContainerInfoForClientPtr container_info_; - base::WeakPtr<ServiceWorkerContainerHost> container_host_; + base::WeakPtr<ServiceWorkerClient> service_worker_client_; // Only used for workers with a blob URL. - base::WeakPtr<ServiceWorkerContainerHost> parent_container_host_; + base::WeakPtr<ServiceWorkerClient> parent_service_worker_client_; ServiceWorkerAccessedCallback service_worker_accessed_callback_;
diff --git a/content/browser/service_worker/service_worker_main_resource_loader.cc b/content/browser/service_worker/service_worker_main_resource_loader.cc index efd3c39..7e4e9de 100644 --- a/content/browser/service_worker/service_worker_main_resource_loader.cc +++ b/content/browser/service_worker/service_worker_main_resource_loader.cc
@@ -89,11 +89,11 @@ std::string client_uuid; auto* frame_tree_node = FrameTreeNode::GloballyFindByID(frame_tree_node_id); if (frame_tree_node) { - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = frame_tree_node->current_frame_host() ->GetLastCommittedServiceWorkerHost(); - if (container_host) { - client_uuid = container_host->client_uuid(); + if (service_worker_client) { + client_uuid = service_worker_client->client_uuid(); } } return client_uuid; @@ -135,11 +135,11 @@ ServiceWorkerMainResourceLoader::ServiceWorkerMainResourceLoader( NavigationLoaderInterceptor::FallbackCallback fallback_callback, - base::WeakPtr<ServiceWorkerContainerHost> container_host, + base::WeakPtr<ServiceWorkerClient> service_worker_client, int frame_tree_node_id, base::TimeTicks find_registration_start_time) : fallback_callback_(std::move(fallback_callback)), - container_host_(std::move(container_host)), + service_worker_client_(std::move(service_worker_client)), frame_tree_node_id_(frame_tree_node_id), is_browser_startup_completed_( GetContentClient()->browser()->IsBrowserStartupComplete()), @@ -150,7 +150,7 @@ TRACE_EVENT_FLAG_FLOW_OUT); scoped_refptr<ServiceWorkerVersion> active_worker = - container_host_->controller(); + service_worker_client_->controller(); if (active_worker) { auto running_status = active_worker->running_status(); initial_service_worker_status_ = ConvertToServiceWorkerStatus( @@ -213,9 +213,10 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); resource_request_ = resource_request; - if (container_host_ && container_host_->fetch_request_window_id()) { + if (service_worker_client_ && + service_worker_client_->fetch_request_window_id()) { resource_request_.fetch_window_id = - std::make_optional(container_host_->fetch_request_window_id()); + std::make_optional(service_worker_client_->fetch_request_window_id()); } DCHECK(!receiver_.is_bound()); @@ -229,15 +230,15 @@ TransitionToStatus(Status::kStarted); CHECK_EQ(commit_responsibility(), FetchResponseFrom::kNoResponseYet); - if (!container_host_) { - // We lost |container_host_| (for the client) somehow before dispatching - // FetchEvent. + if (!service_worker_client_) { + // We lost |service_worker_client_| (for the client) somehow before + // dispatching FetchEvent. CommitCompleted(net::ERR_ABORTED, "No container host"); return; } scoped_refptr<ServiceWorkerVersion> active_worker = - container_host_->controller(); + service_worker_client_->controller(); if (!active_worker) { CommitCompleted(net::ERR_FAILED, "No active worker"); return; @@ -387,7 +388,7 @@ fetch_dispatcher_ = std::make_unique<ServiceWorkerFetchDispatcher>( blink::mojom::FetchAPIRequest::From(resource_request_), resource_request_.destination, client_uuid, - container_host_->client_uuid(), active_worker, + service_worker_client_->client_uuid(), active_worker, base::BindOnce(&ServiceWorkerMainResourceLoader::DidPrepareFetchEvent, weak_factory_.GetWeakPtr(), active_worker, active_worker->running_status()), @@ -395,7 +396,7 @@ weak_factory_.GetWeakPtr()), /*is_offline_capability_check=*/false); - if (container_host_->IsContainerForWindowClient()) { + if (service_worker_client_->IsContainerForWindowClient()) { MaybeDispatchPreload(race_network_request_mode, context, active_worker); } @@ -822,7 +823,7 @@ ServiceWorkerMetrics::RecordFetchEventStatus(true /* is_main_resource */, status); - if (!container_host_) { + if (!service_worker_client_) { // The navigation or shared worker startup is cancelled. Just abort. CommitCompleted(net::ERR_ABORTED, "No container host"); return; @@ -839,7 +840,7 @@ // The `SubresourceLoaderParams` previously returned by `loader_callback` // will be reset by `NavigationURLLoaderImpl` by detecting the controller // lost. - container_host_->NotifyControllerLost(); + service_worker_client_->NotifyControllerLost(); if (fallback_callback_) { std::move(fallback_callback_).Run(ResponseHeadUpdateParams()); } @@ -949,9 +950,13 @@ DCHECK(version->GetMainScriptResponse()); response_head_->ssl_info = version->GetMainScriptResponse()->ssl_info; - CHECK(version->policy_container_host()); - response_head_->client_address_space = - version->policy_container_host()->ip_address_space(); + CHECK(version->policy_container_host(), base::NotFatalUntil::M129); + // TODO(https://crbug.com/339200481): Find out why some ServiceWorker versions + // have null policy container host. + if (version->policy_container_host()) { + response_head_->client_address_space = + version->policy_container_host()->ip_address_space(); + } // Handle a redirect response. ComputeRedirectInfo returns non-null redirect // info if the given response is a redirect.
diff --git a/content/browser/service_worker/service_worker_main_resource_loader.h b/content/browser/service_worker/service_worker_main_resource_loader.h index 8a6deece..110c70b 100644 --- a/content/browser/service_worker/service_worker_main_resource_loader.h +++ b/content/browser/service_worker/service_worker_main_resource_loader.h
@@ -36,7 +36,7 @@ namespace content { -class ServiceWorkerContainerHost; +class ServiceWorkerClient; class ServiceWorkerVersion; // ServiceWorkerMainResourceLoader is the URLLoader used for main resource @@ -75,7 +75,7 @@ // is used instead of NavigationURLLoaderImpl. ServiceWorkerMainResourceLoader( NavigationLoaderInterceptor::FallbackCallback fallback_callback, - base::WeakPtr<ServiceWorkerContainerHost> container_host, + base::WeakPtr<ServiceWorkerClient> service_worker_client, int frame_tree_node_id, base::TimeTicks find_registration_start_time); @@ -258,7 +258,7 @@ network::ResourceRequest resource_request_; - base::WeakPtr<ServiceWorkerContainerHost> container_host_; + base::WeakPtr<ServiceWorkerClient> service_worker_client_; const int frame_tree_node_id_; std::unique_ptr<ServiceWorkerFetchDispatcher> fetch_dispatcher_;
diff --git a/content/browser/service_worker/service_worker_main_resource_loader_interceptor.cc b/content/browser/service_worker/service_worker_main_resource_loader_interceptor.cc index 02b88af..8dc60e5 100644 --- a/content/browser/service_worker/service_worker_main_resource_loader_interceptor.cc +++ b/content/browser/service_worker/service_worker_main_resource_loader_interceptor.cc
@@ -65,10 +65,11 @@ // created for a worker with this |url|. bool ShouldCreateForWorker( const GURL& url, - base::WeakPtr<ServiceWorkerContainerHost> parent_container_host) { + base::WeakPtr<ServiceWorkerClient> parent_service_worker_client) { // Blob URL can be controlled by a parent's controller. - if (url.SchemeIsBlob() && parent_container_host) + if (url.SchemeIsBlob() && parent_service_worker_client) { return true; + } // Create the handler even for insecure HTTP since it's used in the // case of redirect to HTTPS. return url.SchemeIsHTTPOrHTTPS() || OriginCanAccessServiceWorkers(url); @@ -113,9 +114,11 @@ network::mojom::RequestDestination::kSharedWorker) << resource_request.destination; - if (!ShouldCreateForWorker(resource_request.url, - navigation_handle->parent_container_host())) + if (!ShouldCreateForWorker( + resource_request.url, + navigation_handle->parent_service_worker_client())) { return nullptr; + } return base::WrapUnique(new ServiceWorkerMainResourceLoaderInterceptor( std::move(navigation_handle), resource_request.destination, @@ -141,7 +144,7 @@ handle_->context_wrapper()->context(); if (!context_core || !browser_context) { CompleteWithoutLoader(std::move(loader_callback), - handle_->container_host()); + handle_->service_worker_client()); return; } @@ -163,12 +166,12 @@ // Create the ServiceWorkerContainerHost. Its lifetime is bound to // `container_info`. - DCHECK(!handle_->container_host()); - base::WeakPtr<ServiceWorkerContainerHost> container_host; + DCHECK(!handle_->service_worker_client()); + base::WeakPtr<ServiceWorkerClient> service_worker_client; bool inherit_controller_only = false; if (blink::IsRequestDestinationFrame(request_destination_)) { - container_host = context_core->CreateContainerHostForWindow( + service_worker_client = context_core->CreateContainerHostForWindow( std::move(host_receiver), are_ancestors_secure_, std::move(client_remote), frame_tree_node_id_); } else { @@ -180,7 +183,7 @@ ServiceWorkerClientInfo client_info = absl::ConvertVariantTo<ServiceWorkerClientInfo>(*worker_token_); - container_host = context_core->CreateContainerHostForWorker( + service_worker_client = context_core->CreateContainerHostForWorker( std::move(host_receiver), process_id_, std::move(client_remote), client_info); @@ -197,19 +200,19 @@ // For the blob worker case, inherit the controller from the worker's // parent. See // https://w3c.github.io/ServiceWorker/#control-and-use-worker-client - base::WeakPtr<ServiceWorkerContainerHost> parent_container_host = - handle_->parent_container_host(); - if (parent_container_host && + base::WeakPtr<ServiceWorkerClient> parent_service_worker_client = + handle_->parent_service_worker_client(); + if (parent_service_worker_client && tentative_resource_request.url.SchemeIsBlob()) { - container_host->InheritControllerFrom( - *parent_container_host, + service_worker_client->InheritControllerFrom( + *parent_service_worker_client, net::SimplifyUrlForRequest(tentative_resource_request.url)); inherit_controller_only = true; } } } - DCHECK(container_host); - handle_->set_container_host(container_host); + DCHECK(service_worker_client); + handle_->set_service_worker_client(service_worker_client); // For the blob worker case, we only inherit the controller and do not let // it intercept the main resource request. Blob URLs are not eligible to @@ -217,7 +220,7 @@ // callback now. if (inherit_controller_only) { CompleteWithoutLoader(std::move(loader_callback), - handle_->container_host()); + handle_->service_worker_client()); return; } } @@ -265,15 +268,15 @@ // Create and start the handler for this request. It will invoke the loader // callback or fallback callback. request_handler_ = std::make_unique<ServiceWorkerControlleeRequestHandler>( - context_core->AsWeakPtr(), handle_->container_host(), + context_core->AsWeakPtr(), handle_->service_worker_client(), request_destination_, skip_service_worker, frame_tree_node_id_, handle_->service_worker_accessed_callback()); - if (handle_->parent_container_host()) { + if (handle_->parent_service_worker_client()) { // Set a parent container's client UUID. // This is needed for PlzDedicatedWorker to have the client id for // nested case. request_handler_->set_parent_client_uuid( - handle_->parent_container_host()->client_uuid()); + handle_->parent_service_worker_client()->client_uuid()); } request_handler_->MaybeCreateLoader( @@ -283,10 +286,10 @@ void ServiceWorkerMainResourceLoaderInterceptor::CompleteWithoutLoader( LoaderCallback loader_callback, - base::WeakPtr<ServiceWorkerContainerHost> container_host) { + base::WeakPtr<ServiceWorkerClient> service_worker_client) { auto subresource_loader_params = - ServiceWorkerContainerHost::MaybeCreateSubresourceLoaderParams( - container_host); + ServiceWorkerClient::MaybeCreateSubresourceLoaderParams( + service_worker_client); if (subresource_loader_params.controller_service_worker_info) { std::move(loader_callback) .Run(NavigationLoaderInterceptor::Result(
diff --git a/content/browser/service_worker/service_worker_main_resource_loader_interceptor.h b/content/browser/service_worker/service_worker_main_resource_loader_interceptor.h index 5522c73f6..1ccc889 100644 --- a/content/browser/service_worker/service_worker_main_resource_loader_interceptor.h +++ b/content/browser/service_worker/service_worker_main_resource_loader_interceptor.h
@@ -81,7 +81,7 @@ static void CompleteWithoutLoader( NavigationLoaderInterceptor::LoaderCallback loader_callback, - base::WeakPtr<ServiceWorkerContainerHost> container_host); + base::WeakPtr<ServiceWorkerClient> service_worker_client); private: friend class ServiceWorkerMainResourceLoaderInterceptorTest;
diff --git a/content/browser/service_worker/service_worker_main_resource_loader_unittest.cc b/content/browser/service_worker/service_worker_main_resource_loader_unittest.cc index 13f4c969..5306102 100644 --- a/content/browser/service_worker/service_worker_main_resource_loader_unittest.cc +++ b/content/browser/service_worker/service_worker_main_resource_loader_unittest.cc
@@ -517,20 +517,20 @@ // caller can use functions like client_.RunUntilComplete() to wait for // completion. void StartRequest(std::unique_ptr<network::ResourceRequest> request) { - // Create a ServiceWorkerContainerHost and simulate what + // Create a ServiceWorkerClient and simulate what // ServiceWorkerControlleeRequestHandler does to assign it a controller. - if (!container_host_) { - container_host_ = CreateContainerHostForWindow( + if (!service_worker_client_) { + service_worker_client_ = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), &container_endpoints_); - container_host_->UpdateUrls(request->url, - url::Origin::Create(request->url), - blink::StorageKey::CreateFirstParty( - url::Origin::Create(request->url))); - container_host_->AddMatchingRegistration(registration_.get()); - container_host_->SetControllerRegistration( + service_worker_client_->UpdateUrls( + request->url, url::Origin::Create(request->url), + blink::StorageKey::CreateFirstParty( + url::Origin::Create(request->url))); + service_worker_client_->AddMatchingRegistration(registration_.get()); + service_worker_client_->SetControllerRegistration( registration_, /*notify_controllerchange=*/false); } @@ -538,7 +538,7 @@ loader_ = std::make_unique<ServiceWorkerMainResourceLoader>( base::BindOnce(&ServiceWorkerMainResourceLoaderTest::Fallback, base::Unretained(this)), - container_host_, + service_worker_client_, /*frame_tree_node_id=*/RenderFrameHost::kNoFrameTreeNodeId, /*find_registration_start_time=*/base::TimeTicks::Now()); @@ -622,7 +622,7 @@ network::TestURLLoaderClient client_; std::unique_ptr<ServiceWorkerMainResourceLoader> loader_; mojo::Remote<network::mojom::URLLoader> loader_remote_; - base::WeakPtr<ServiceWorkerContainerHost> container_host_; + base::WeakPtr<ServiceWorkerClient> service_worker_client_; ServiceWorkerRemoteContainerEndpoint container_endpoints_; bool did_call_fallback_callback_ = false; @@ -663,12 +663,12 @@ base::HistogramTester histogram_tester; // Make a container host without a controller. - container_host_ = CreateContainerHostForWindow( + service_worker_client_ = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), &container_endpoints_); - container_host_->UpdateUrls( + service_worker_client_->UpdateUrls( GURL("https://example.com/"), url::Origin::Create(GURL("https://example.com/")), blink::StorageKey::CreateFromStringForTesting("https://example.com/")); @@ -984,7 +984,7 @@ // The request should not be handled by the loader, but it shouldn't be a // failure. - EXPECT_TRUE(container_host_->controller()); + EXPECT_TRUE(service_worker_client_->controller()); histogram_tester.ExpectUniqueSample(kHistogramMainResourceFetchEvent, blink::ServiceWorkerStatusCode::kOk, 1); if (LoaderRecordsTimingMetrics()) { @@ -1037,7 +1037,7 @@ // The fallback callback should be called. RunUntilFallbackCallback(); - EXPECT_FALSE(container_host_->controller()); + EXPECT_FALSE(service_worker_client_->controller()); histogram_tester.ExpectUniqueSample( kHistogramMainResourceFetchEvent, @@ -1138,9 +1138,8 @@ } TEST_F(ServiceWorkerMainResourceLoaderTest, CancelNavigationDuringFetchEvent) { - // This test simulates failure by resetting - // ServiceWorkerContainerHost. But without disabling - // HighPriorityFetchResponseCallback, + // This test simulates failure by resetting ServiceWorkerClient. But without + // disabling HighPriorityFetchResponseCallback, // `container_endpoints_.host_remote()->reset()` comes later than // request processing, and doesn't cancel navigation during the fetch // event. This test is still valid after introducing @@ -1154,7 +1153,7 @@ // crashing. container_endpoints_.host_remote()->reset(); base::RunLoop().RunUntilIdle(); - EXPECT_FALSE(container_host_); + EXPECT_FALSE(service_worker_client_); client_.RunUntilComplete(); EXPECT_EQ(net::ERR_ABORTED, client_.completion_status().error_code);
diff --git a/content/browser/service_worker/service_worker_object_host_unittest.cc b/content/browser/service_worker/service_worker_object_host_unittest.cc index 7ff248a..e39f5e4e 100644 --- a/content/browser/service_worker/service_worker_object_host_unittest.cc +++ b/content/browser/service_worker/service_worker_object_host_unittest.cc
@@ -255,13 +255,13 @@ registration_->SetInstallingVersion(version_); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), &remote_endpoint); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( scope, url::Origin::Create(scope), blink::StorageKey::CreateFirstParty(url::Origin::Create(scope))); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr registration_info = @@ -411,7 +411,7 @@ auto* worker = helper_->AddNewPendingServiceWorker<MessageEventWorker>(helper_.get()); - // Prepare a ServiceWorkerContainerHost for a window client. A + // Prepare a ServiceWorkerClient for a window client. A // WebContents/RenderFrameHost must be created too because it's needed for // DispatchExtendableMessageEvent to populate ExtendableMessageEvent#source. RenderViewHostTestEnabler rvh_test_enabler; @@ -420,19 +420,20 @@ nullptr)); RenderFrameHost* frame_host = web_contents->GetPrimaryMainFrame(); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( frame_host->GetGlobalId(), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), &remote_endpoint); - container_host->UpdateUrls(scope, url::Origin::Create(scope), key); + service_worker_client->UpdateUrls(scope, url::Origin::Create(scope), key); // Prepare a ServiceWorkerObjectHost for the worker. blink::mojom::ServiceWorkerObjectInfoPtr info = - container_host->version_object_manager() + service_worker_client->container_host() + .version_object_manager() .GetOrCreateHost(version_) ->CreateCompleteObjectInfoToSend(); - ServiceWorkerObjectHost* object_host = - GetServiceWorkerObjectHost(container_host.get(), version_->version_id()); + ServiceWorkerObjectHost* object_host = GetServiceWorkerObjectHost( + &service_worker_client->container_host(), version_->version_id()); // Simulate postMessage() from the window client to the worker. blink::TransferableMessage message; @@ -449,15 +450,15 @@ EXPECT_EQ(blink::ServiceWorkerStatusCode::kOk, status); // The worker should have received an ExtendableMessageEvent whose - // source is |container_host|. + // source is |service_worker_client|. const std::vector<blink::mojom::ExtendableMessageEventPtr>& events = worker->events(); EXPECT_EQ(1u, events.size()); EXPECT_FALSE(events[0]->source_info_for_service_worker); EXPECT_TRUE(events[0]->source_info_for_client); - EXPECT_EQ(container_host->client_uuid(), + EXPECT_EQ(service_worker_client->client_uuid(), events[0]->source_info_for_client->client_uuid); - EXPECT_EQ(container_host->GetClientType(), + EXPECT_EQ(service_worker_client->GetClientType(), events[0]->source_info_for_client->client_type); }
diff --git a/content/browser/service_worker/service_worker_register_job.cc b/content/browser/service_worker/service_worker_register_job.cc index 164127e..e36d28f9b 100644 --- a/content/browser/service_worker/service_worker_register_job.cc +++ b/content/browser/service_worker/service_worker_register_job.cc
@@ -916,7 +916,6 @@ registration->key(), true /* include_reserved_clients */, true /* include_back_forward_cached_clients */); !it.IsAtEnd(); ++it) { - DCHECK(it->IsContainerForClient()); if (!blink::ServiceWorkerScopeMatches(registration->scope(), it->GetUrlForScopeMatch())) { continue;
diff --git a/content/browser/service_worker/service_worker_registration_unittest.cc b/content/browser/service_worker/service_worker_registration_unittest.cc index 8bd421cf..da1c69fa 100644 --- a/content/browser/service_worker/service_worker_registration_unittest.cc +++ b/content/browser/service_worker/service_worker_registration_unittest.cc
@@ -324,7 +324,7 @@ blink::mojom::AncestorFrameType::kNormalFrame); // Prepare a ServiceWorkerContainerHost. ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), @@ -332,7 +332,8 @@ &remote_endpoint); auto registration_object_host = std::make_unique<ServiceWorkerRegistrationObjectHost>( - context()->AsWeakPtr(), container_host.get(), registration); + context()->AsWeakPtr(), &service_worker_client->container_host(), + registration); // To enable the caller end point // |registration_object_host->remote_registration_| to make calls safely with // no need to pass |object_info_->receiver| through a message pipe endpoint. @@ -436,15 +437,15 @@ ASSERT_EQ(blink::ServiceWorkerStatusCode::kOk, status.value()); // Give the active version a controllee. - container_host_ = CreateContainerHostForWindow( + service_worker_client_ = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoint_); DCHECK(remote_endpoint_.client_receiver()->is_valid()); DCHECK(remote_endpoint_.host_remote()->is_bound()); - container_host_->UpdateUrls(kUrl, url::Origin::Create(kUrl), kKey); - container_host_->SetControllerRegistration( + service_worker_client_->UpdateUrls(kUrl, url::Origin::Create(kUrl), kKey); + service_worker_client_->SetControllerRegistration( registration_, false /* notify_controllerchange */); // Setup the Mojo implementation fakes for the renderer-side service worker. @@ -511,12 +512,12 @@ int inflight_request_id() const { return inflight_request_id_; } void AddControllee() { - container_host_->SetControllerRegistration( + service_worker_client_->SetControllerRegistration( registration(), false /* notify_controllerchange */); } void RemoveControllee() { - container_host_->SetControllerRegistration( + service_worker_client_->SetControllerRegistration( nullptr, false /* notify_controllerchange */); } @@ -572,7 +573,7 @@ raw_ptr<FakeEmbeddedWorkerInstanceClient> version_2_client_ = nullptr; raw_ptr<FakeServiceWorker> version_2_service_worker_ = nullptr; - base::WeakPtr<ServiceWorkerContainerHost> container_host_; + base::WeakPtr<ServiceWorkerClient> service_worker_client_; ServiceWorkerRemoteContainerEndpoint remote_endpoint_; int inflight_request_id_ = -1; }; @@ -951,21 +952,21 @@ return registration->id(); } - ServiceWorkerRemoteContainerEndpoint PrepareContainerHost( + ServiceWorkerRemoteContainerEndpoint PrepareServiceWorkerClient( const GURL& document_url, - base::WeakPtr<ServiceWorkerContainerHost>* out_container_host) { + base::WeakPtr<ServiceWorkerClient>* out_service_worker_client) { ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoint); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( document_url, url::Origin::Create(document_url), blink::StorageKey::CreateFirstParty(url::Origin::Create(document_url))); - if (out_container_host) { - *out_container_host = container_host; + if (out_service_worker_client) { + *out_service_worker_client = service_worker_client; } return remote_endpoint; } @@ -1020,7 +1021,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); int64_t registration_id = SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = GetRegistrationFromRemote(remote_endpoint.host_remote()->get(), kScope); mojo::AssociatedRemote<blink::mojom::ServiceWorkerRegistrationObjectHost> @@ -1038,7 +1040,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); mojo::AssociatedRemote<blink::mojom::ServiceWorkerRegistrationObjectHost> registration_host; blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = @@ -1058,9 +1061,9 @@ const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); SetUpRegistration(kScope, kScriptUrl); - base::WeakPtr<ServiceWorkerContainerHost> container_host; + base::WeakPtr<ServiceWorkerClient> service_worker_client; ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, &container_host); + PrepareServiceWorkerClient(kScope, &service_worker_client); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = GetRegistrationFromRemote(remote_endpoint.host_remote()->get(), kScope); mojo::AssociatedRemote<blink::mojom::ServiceWorkerRegistrationObjectHost> @@ -1069,7 +1072,7 @@ ASSERT_TRUE(bad_messages_.empty()); GURL url("https://does.not.exist/"); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( url, url::Origin::Create(url), blink::StorageKey::CreateFirstParty(url::Origin::Create(url))); CallUpdate(registration_host.get(), /*out_error_msg=*/nullptr); @@ -1082,7 +1085,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = GetRegistrationFromRemote(remote_endpoint.host_remote()->get(), kScope); mojo::AssociatedRemote<blink::mojom::ServiceWorkerRegistrationObjectHost> @@ -1109,7 +1113,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); int64_t registration_id = SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); mojo::AssociatedRemote<blink::mojom::ServiceWorkerRegistrationObjectHost> registration_host; @@ -1173,16 +1178,16 @@ version->SetStatus(ServiceWorkerVersion::ACTIVATED); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(helper_->mock_render_process_id(), /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoint); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( kScope, url::Origin::Create(kScope), blink::StorageKey::CreateFirstParty(url::Origin::Create(kScope))); - version->AddControllee(container_host.get()); + version->AddControllee(service_worker_client.get()); // Initially set |self_update_delay| to zero. registration->set_self_update_delay(base::TimeDelta()); @@ -1203,7 +1208,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); int64_t registration_id = SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); mojo::AssociatedRemote<blink::mojom::ServiceWorkerRegistrationObjectHost> registration_host; blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = @@ -1235,9 +1241,9 @@ const GURL kScope("https://www.example.com/"); const GURL kScriptUrl("https://www.example.com/sw.js"); SetUpRegistration(kScope, kScriptUrl); - base::WeakPtr<ServiceWorkerContainerHost> container_host; + base::WeakPtr<ServiceWorkerClient> service_worker_client; ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, &container_host); + PrepareServiceWorkerClient(kScope, &service_worker_client); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = GetRegistrationFromRemote(remote_endpoint.host_remote()->get(), kScope); mojo::AssociatedRemote<blink::mojom::ServiceWorkerRegistrationObjectHost> @@ -1245,7 +1251,7 @@ registration_host.Bind(std::move(info->host_remote)); ASSERT_TRUE(bad_messages_.empty()); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( GURL("https://does.not.exist/"), url::Origin::Create(GURL("https://does.not.exist/")), blink::StorageKey::CreateFromStringForTesting("https://does.not.exist/")); @@ -1259,7 +1265,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = GetRegistrationFromRemote(remote_endpoint.host_remote()->get(), kScope); mojo::AssociatedRemote<blink::mojom::ServiceWorkerRegistrationObjectHost> @@ -1279,7 +1286,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); int64_t registration_id = SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = GetRegistrationFromRemote(remote_endpoint.host_remote()->get(), kScope); EXPECT_EQ(registration_id, info->registration_id); @@ -1367,7 +1375,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); int64_t registration_id = SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = GetRegistrationFromRemote(remote_endpoint.host_remote()->get(), kScope); EXPECT_EQ(registration_id, info->registration_id); @@ -1418,7 +1427,8 @@ const GURL kScriptUrl("https://www.example.com/sw.js"); int64_t registration_id = SetUpRegistration(kScope, kScriptUrl); ServiceWorkerRemoteContainerEndpoint remote_endpoint = - PrepareContainerHost(kScope, nullptr /* out_container_host */); + PrepareServiceWorkerClient(kScope, + nullptr /* out_service_worker_client */); blink::mojom::ServiceWorkerRegistrationObjectInfoPtr info = GetRegistrationFromRemote(remote_endpoint.host_remote()->get(), kScope); EXPECT_EQ(registration_id, info->registration_id);
diff --git a/content/browser/service_worker/service_worker_registry_unittest.cc b/content/browser/service_worker/service_worker_registry_unittest.cc index 192abf8b..05f33e5 100644 --- a/content/browser/service_worker/service_worker_registry_unittest.cc +++ b/content/browser/service_worker/service_worker_registry_unittest.cc
@@ -3235,13 +3235,13 @@ registry()->UpdateToActiveState(registration_->id(), registration_->key(), base::DoNothing()); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(/*mock process_id=*/33, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoint); - registration_->active_version()->AddControllee(container_host.get()); + registration_->active_version()->AddControllee(service_worker_client.get()); // Deleting the registration should move the resources to the purgeable list // but keep them available. @@ -3256,7 +3256,7 @@ base::RunLoop loop; storage_control()->SetPurgingCompleteCallbackForTest(loop.QuitClosure()); registration_->active_version()->RemoveControllee( - container_host->client_uuid()); + service_worker_client->client_uuid()); registration_->active_version()->Doom(); loop.Run(); EXPECT_TRUE(GetPurgeableResourceIds().empty()); @@ -3272,13 +3272,13 @@ registry()->UpdateToActiveState(registration_->id(), registration_->key(), base::DoNothing()); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(/*mock process_id=*/33, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoint); - registration_->active_version()->AddControllee(container_host.get()); + registration_->active_version()->AddControllee(service_worker_client.get()); // Make an updated registration. scoped_refptr<ServiceWorkerVersion> live_version = @@ -3309,7 +3309,7 @@ storage_control()->SetPurgingCompleteCallbackForTest(loop.QuitClosure()); scoped_refptr<ServiceWorkerVersion> old_version( registration_->active_version()); - old_version->RemoveControllee(container_host->client_uuid()); + old_version->RemoveControllee(service_worker_client->client_uuid()); registration_->ActivateWaitingVersionWhenReady(); EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, old_version->status()); @@ -3365,13 +3365,13 @@ registry()->UpdateToActiveState(registration_->id(), registration_->key(), base::DoNothing()); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(/*mock process_id=*/33, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, context()->AsWeakPtr(), &remote_endpoint); - registration_->active_version()->AddControllee(container_host.get()); + registration_->active_version()->AddControllee(service_worker_client.get()); // Deleting the registration should move the resources to the purgeable list // but keep them available.
diff --git a/content/browser/service_worker/service_worker_test_utils.cc b/content/browser/service_worker/service_worker_test_utils.cc index 603a4da..156503b 100644 --- a/content/browser/service_worker/service_worker_test_utils.cc +++ b/content/browser/service_worker/service_worker_test_utils.cc
@@ -298,24 +298,24 @@ host_remote_.Bind(std::move(info->host_remote)); } -ServiceWorkerContainerHostAndInfo::ServiceWorkerContainerHostAndInfo( - base::WeakPtr<ServiceWorkerContainerHost> host, +ServiceWorkerClientAndInfo::ServiceWorkerClientAndInfo( + base::WeakPtr<ServiceWorkerClient> service_worker_client, blink::mojom::ServiceWorkerContainerInfoForClientPtr info) - : host(std::move(host)), info(std::move(info)) {} + : service_worker_client(std::move(service_worker_client)), + info(std::move(info)) {} -ServiceWorkerContainerHostAndInfo::~ServiceWorkerContainerHostAndInfo() = - default; +ServiceWorkerClientAndInfo::~ServiceWorkerClientAndInfo() = default; -base::WeakPtr<ServiceWorkerContainerHost> CreateContainerHostForWindow( +base::WeakPtr<ServiceWorkerClient> CreateContainerHostForWindow( const GlobalRenderFrameHostId& render_frame_host_id, bool is_parent_frame_secure, base::WeakPtr<ServiceWorkerContextCore> context, ServiceWorkerRemoteContainerEndpoint* output_endpoint) { - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(context, is_parent_frame_secure); - base::WeakPtr<ServiceWorkerContainerHost> container_host = - std::move(host_and_info->host); - output_endpoint->BindForWindow(std::move(host_and_info->info)); + base::WeakPtr<ServiceWorkerClient> service_worker_client = + std::move(client_and_info->service_worker_client); + output_endpoint->BindForWindow(std::move(client_and_info->info)); // Establish a dummy connection to allow sending messages without errors. mojo::PendingRemote<network::mojom::CrossOriginEmbedderPolicyReporter> @@ -324,14 +324,13 @@ // In production code this is called from NavigationRequest in the browser // process right before navigation commit. - container_host->OnBeginNavigationCommit( + service_worker_client->OnBeginNavigationCommit( render_frame_host_id, PolicyContainerPolicies(), std::move(reporter), ukm::kInvalidSourceId); - return container_host; + return service_worker_client; } -std::unique_ptr<ServiceWorkerContainerHostAndInfo> -CreateContainerHostAndInfoForWindow( +std::unique_ptr<ServiceWorkerClientAndInfo> CreateContainerHostAndInfoForWindow( base::WeakPtr<ServiceWorkerContextCore> context, bool are_ancestors_secure) { mojo::PendingAssociatedRemote<blink::mojom::ServiceWorkerContainer> @@ -341,7 +340,7 @@ auto info = blink::mojom::ServiceWorkerContainerInfoForClient::New(); info->client_receiver = client_remote.InitWithNewEndpointAndPassReceiver(); host_receiver = info->host_remote.InitWithNewEndpointAndPassReceiver(); - return std::make_unique<ServiceWorkerContainerHostAndInfo>( + return std::make_unique<ServiceWorkerClientAndInfo>( context->CreateContainerHostForWindow( std::move(host_receiver), are_ancestors_secure, std::move(client_remote), /*frame_tree_node_id=*/1),
diff --git a/content/browser/service_worker/service_worker_test_utils.h b/content/browser/service_worker/service_worker_test_utils.h index 1d0d673d..ee33ab00 100644 --- a/content/browser/service_worker/service_worker_test_utils.h +++ b/content/browser/service_worker/service_worker_test_utils.h
@@ -104,34 +104,32 @@ client_receiver_; }; -struct ServiceWorkerContainerHostAndInfo { - ServiceWorkerContainerHostAndInfo( - base::WeakPtr<ServiceWorkerContainerHost> host, +struct ServiceWorkerClientAndInfo { + ServiceWorkerClientAndInfo( + base::WeakPtr<ServiceWorkerClient> service_worker_client, blink::mojom::ServiceWorkerContainerInfoForClientPtr); - ServiceWorkerContainerHostAndInfo(const ServiceWorkerContainerHostAndInfo&) = + ServiceWorkerClientAndInfo(const ServiceWorkerClientAndInfo&) = delete; + ServiceWorkerClientAndInfo& operator=(const ServiceWorkerClientAndInfo&) = delete; - ServiceWorkerContainerHostAndInfo& operator=( - const ServiceWorkerContainerHostAndInfo&) = delete; - ~ServiceWorkerContainerHostAndInfo(); + ~ServiceWorkerClientAndInfo(); - base::WeakPtr<ServiceWorkerContainerHost> host; + base::WeakPtr<ServiceWorkerClient> service_worker_client; blink::mojom::ServiceWorkerContainerInfoForClientPtr info; }; // Creates a container host that finished navigation. Test code can typically // use this function, but if more control is required // CreateContainerHostAndInfoForWindow() can be used instead. -base::WeakPtr<ServiceWorkerContainerHost> CreateContainerHostForWindow( +base::WeakPtr<ServiceWorkerClient> CreateContainerHostForWindow( const GlobalRenderFrameHostId& render_frame_host_id, bool is_parent_frame_secure, base::WeakPtr<ServiceWorkerContextCore> context, ServiceWorkerRemoteContainerEndpoint* output_endpoint); // Creates a container host that can be used for a navigation. -std::unique_ptr<ServiceWorkerContainerHostAndInfo> -CreateContainerHostAndInfoForWindow( +std::unique_ptr<ServiceWorkerClientAndInfo> CreateContainerHostAndInfoForWindow( base::WeakPtr<ServiceWorkerContextCore> context, bool are_ancestors_secure);
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index 618a704..d93eab4 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -461,9 +461,9 @@ embedded_worker()->worker_devtools_agent_route_id(), ukm_source_id(), ancestor_frame_type_, router_rules); for (const auto& controllee : controllee_map_) { - ServiceWorkerContainerHost* container_host = controllee.second.get(); - info.clients.emplace(container_host->client_uuid(), - container_host->GetServiceWorkerClientInfo()); + ServiceWorkerClient* service_worker_client = controllee.second.get(); + info.clients.emplace(service_worker_client->client_uuid(), + service_worker_client->GetServiceWorkerClientInfo()); } info.script_response_time = script_response_time_for_devtools_; @@ -904,18 +904,18 @@ } void ServiceWorkerVersion::AddControllee( - ServiceWorkerContainerHost* container_host) { + ServiceWorkerClient* service_worker_client) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // TODO(crbug.com/40657227): Remove this CHECK once we figure out the cause of // crash. - CHECK(container_host); - const std::string& uuid = container_host->client_uuid(); - CHECK(!container_host->client_uuid().empty()); + CHECK(service_worker_client); + const std::string& uuid = service_worker_client->client_uuid(); + CHECK(!service_worker_client->client_uuid().empty()); // TODO(crbug.com/40657227): Change to DCHECK once we figure out the cause of // crash. CHECK(!base::Contains(controllee_map_, uuid)); - controllee_map_[uuid] = container_host->AsWeakPtr(); + controllee_map_[uuid] = service_worker_client->AsWeakPtr(); embedded_worker_->UpdateForegroundPriority(); ClearTick(&no_controllees_time_); @@ -927,15 +927,17 @@ // Notify observers asynchronously for consistency with RemoveControllee. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( - FROM_HERE, base::BindOnce(&ServiceWorkerVersion::NotifyControlleeAdded, - weak_factory_.GetWeakPtr(), uuid, - container_host->GetServiceWorkerClientInfo())); + FROM_HERE, + base::BindOnce(&ServiceWorkerVersion::NotifyControlleeAdded, + weak_factory_.GetWeakPtr(), uuid, + service_worker_client->GetServiceWorkerClientInfo())); // Also send a notification if OnEndNavigationCommit() was already invoked for // this container. - if (container_host->navigation_commit_ended()) { - OnControlleeNavigationCommitted(container_host->client_uuid(), - container_host->GetRenderFrameHostId()); + if (service_worker_client->navigation_commit_ended()) { + OnControlleeNavigationCommitted( + service_worker_client->client_uuid(), + service_worker_client->GetRenderFrameHostId()); } } @@ -1056,7 +1058,7 @@ } void ServiceWorkerVersion::EvictBackForwardCachedControllee( - ServiceWorkerContainerHost* controllee, + ServiceWorkerClient* controllee, BackForwardCacheMetrics::NotRestoredReason reason) { controllee->EvictFromBackForwardCache(reason); controllees_to_be_evicted_[controllee->client_uuid()] = reason; @@ -1101,9 +1103,9 @@ // ServiceWorkerVersion::RemoveControllee(), so be careful with iterators. auto iter = controllee_map_.begin(); while (iter != controllee_map_.end()) { - ServiceWorkerContainerHost* container_host = iter->second.get(); + ServiceWorkerClient* service_worker_client = iter->second.get(); ++iter; - container_host->NotifyControllerLost(); + service_worker_client->NotifyControllerLost(); } // Tell the bfcached controllees that this version is dead. Each controllee // will call ServiceWorkerContainerHost:EvictFromBackForwardCache(). @@ -1118,9 +1120,9 @@ // count as true controllees for service worker lifecycle purposes. auto bf_iter = bfcached_controllee_map_.begin(); while (bf_iter != bfcached_controllee_map_.end()) { - ServiceWorkerContainerHost* bf_container_host = bf_iter->second.get(); + ServiceWorkerClient* bf_service_worker_client = bf_iter->second.get(); ++bf_iter; - bf_container_host->NotifyControllerLost(); + bf_service_worker_client->NotifyControllerLost(); } // Any controllee this version had should have removed itself. @@ -1620,10 +1622,11 @@ std::move(callback).Run(nullptr); return; } - ServiceWorkerContainerHost* container_host = + ServiceWorkerClient* service_worker_client = context_->GetContainerHostByClientID(client_uuid); - if (!container_host || container_host->url().DeprecatedGetOriginAsURL() != - script_url_.DeprecatedGetOriginAsURL()) { + if (!service_worker_client || + service_worker_client->url().DeprecatedGetOriginAsURL() != + script_url_.DeprecatedGetOriginAsURL()) { // The promise will be resolved to 'undefined'. // Note that we don't BadMessage here since Clients#get() can be passed an // arbitrary UUID. The BadMessages for the origin mismatches below are @@ -1632,13 +1635,14 @@ std::move(callback).Run(nullptr); return; } - if (!container_host->is_execution_ready()) { - container_host->AddExecutionReadyCallback( + if (!service_worker_client->is_execution_ready()) { + service_worker_client->AddExecutionReadyCallback( base::BindOnce(&ServiceWorkerVersion::GetClientInternal, this, client_uuid, std::move(callback))); return; } - service_worker_client_utils::GetClient(container_host, std::move(callback)); + service_worker_client_utils::GetClient(service_worker_client, + std::move(callback)); } void ServiceWorkerVersion::GetClientInternal(const std::string& client_uuid, @@ -1649,13 +1653,14 @@ return; } - ServiceWorkerContainerHost* container_host = + ServiceWorkerClient* service_worker_client = context_->GetContainerHostByClientID(client_uuid); - if (!container_host || !container_host->is_execution_ready()) { + if (!service_worker_client || !service_worker_client->is_execution_ready()) { std::move(callback).Run(nullptr); return; } - service_worker_client_utils::GetClient(container_host, std::move(callback)); + service_worker_client_utils::GetClient(service_worker_client, + std::move(callback)); } void ServiceWorkerVersion::OpenNewTab(const GURL& url, @@ -1699,9 +1704,9 @@ blink::TransferableMessage message) { if (!context_) return; - ServiceWorkerContainerHost* container_host = + ServiceWorkerClient* service_worker_client = context_->GetContainerHostByClientID(client_uuid); - if (!container_host) { + if (!service_worker_client) { // The client may already have been closed, just ignore. return; } @@ -1709,15 +1714,15 @@ if (IsBackForwardCacheEnabled()) { // When |PostMessageToClient| is called on a client that is in bfcache, // evict the bfcache entry. - if (container_host->IsInBackForwardCache()) { + if (service_worker_client->IsInBackForwardCache()) { EvictBackForwardCachedControllee( - container_host, BackForwardCacheMetrics::NotRestoredReason:: - kServiceWorkerPostMessage); + service_worker_client, BackForwardCacheMetrics::NotRestoredReason:: + kServiceWorkerPostMessage); return; } } - if (container_host->url().DeprecatedGetOriginAsURL() != + if (service_worker_client->url().DeprecatedGetOriginAsURL() != script_url_.DeprecatedGetOriginAsURL()) { associated_interface_receiver_.ReportBadMessage( "Received Client#postMessage() request for a cross-origin client."); @@ -1725,8 +1730,8 @@ return; } base::UmaHistogramBoolean("ServiceWorker.PostMessage.IsExecutionReady", - container_host->is_execution_ready()); - if (!container_host->is_execution_ready()) { + service_worker_client->is_execution_ready()); + if (!service_worker_client->is_execution_ready()) { // It's subtle why this ReportBadMessage is correct. Consider the // sequence: // 1. Page does ServiceWorker.postMessage(). @@ -1757,7 +1762,7 @@ // As we don't track tasks between workers and renderers, we can nullify the // message's parent task ID. message.parent_task_id = std::nullopt; - container_host->PostMessageToClient(this, std::move(message)); + service_worker_client->PostMessageToClient(this, std::move(message)); } void ServiceWorkerVersion::FocusClient(const std::string& client_uuid, @@ -1766,21 +1771,21 @@ std::move(callback).Run(nullptr /* client */); return; } - ServiceWorkerContainerHost* container_host = + ServiceWorkerClient* service_worker_client = context_->GetContainerHostByClientID(client_uuid); - if (!container_host) { + if (!service_worker_client) { // The client may already have been closed, just fail. std::move(callback).Run(nullptr /* client */); return; } - if (container_host->url().DeprecatedGetOriginAsURL() != + if (service_worker_client->url().DeprecatedGetOriginAsURL() != script_url_.DeprecatedGetOriginAsURL()) { associated_interface_receiver_.ReportBadMessage( "Received WindowClient#focus() request for a cross-origin client."); receiver_.reset(); return; } - if (!container_host->IsContainerForWindowClient()) { + if (!service_worker_client->IsContainerForWindowClient()) { // focus() should be called only for WindowClient. associated_interface_receiver_.ReportBadMessage( "Received WindowClient#focus() request for a non-window client."); @@ -1788,7 +1793,7 @@ return; } - service_worker_client_utils::FocusWindowClient(container_host, + service_worker_client_utils::FocusWindowClient(service_worker_client, std::move(callback)); } @@ -1822,28 +1827,28 @@ return; } - ServiceWorkerContainerHost* container_host = + ServiceWorkerClient* service_worker_client = context_->GetContainerHostByClientID(client_uuid); - if (!container_host) { + if (!service_worker_client) { std::move(callback).Run(false /* success */, nullptr /* client */, std::string("The client was not found.")); return; } - if (container_host->url().DeprecatedGetOriginAsURL() != + if (service_worker_client->url().DeprecatedGetOriginAsURL() != script_url_.DeprecatedGetOriginAsURL()) { associated_interface_receiver_.ReportBadMessage( "Received WindowClient#navigate() request for a cross-origin client."); receiver_.reset(); return; } - if (!container_host->IsContainerForWindowClient()) { + if (!service_worker_client->IsContainerForWindowClient()) { // navigate() should be called only for WindowClient. associated_interface_receiver_.ReportBadMessage( "Received WindowClient#navigate() request for a non-window client."); receiver_.reset(); return; } - if (container_host->controller() != this) { + if (service_worker_client->controller() != this) { std::move(callback).Run( false /* success */, nullptr /* client */, std::string( @@ -1852,8 +1857,8 @@ } service_worker_client_utils::NavigateClient( - url, script_url_, key_, container_host->GetRenderFrameHostId(), context_, - base::BindOnce(&DidNavigateClient, std::move(callback), url)); + url, script_url_, key_, service_worker_client->GetRenderFrameHostId(), + context_, base::BindOnce(&DidNavigateClient, std::move(callback), url)); NotifyClientNavigated(script_url_, url); } @@ -2011,14 +2016,15 @@ // Take snapshot of the `controllee_map_` instead of iterating on it directly. // This is to rule out the possibility of `controllee_map_` being modified // while we call `CountFeature`. - std::vector<base::WeakPtr<ServiceWorkerContainerHost>> hosts_snapshot; - hosts_snapshot.reserve(controllee_map_.size()); - for (auto container_host_by_uuid : controllee_map_) { - hosts_snapshot.push_back(container_host_by_uuid.second); + std::vector<base::WeakPtr<ServiceWorkerClient>> snapshot; + snapshot.reserve(controllee_map_.size()); + for (auto service_worker_client_by_uuid : controllee_map_) { + snapshot.push_back(service_worker_client_by_uuid.second); } - for (auto container_host : hosts_snapshot) { - if (container_host) - container_host->CountFeature(feature); + for (auto service_worker_client : snapshot) { + if (service_worker_client) { + service_worker_client->CountFeature(feature); + } } }
diff --git a/content/browser/service_worker/service_worker_version.h b/content/browser/service_worker/service_worker_version.h index 8abfb1f..49de6a4 100644 --- a/content/browser/service_worker/service_worker_version.h +++ b/content/browser/service_worker/service_worker_version.h
@@ -72,7 +72,7 @@ namespace content { -class ServiceWorkerContainerHost; +class ServiceWorkerClient; class ServiceWorkerContextCore; class ServiceWorkerHost; class ServiceWorkerInstalledScriptsSender; @@ -423,7 +423,7 @@ } // Adds and removes the specified host as a controllee of this service worker. - void AddControllee(ServiceWorkerContainerHost* container_host); + void AddControllee(ServiceWorkerClient* service_worker_client); void RemoveControllee(const std::string& client_uuid); // Called when the navigation for a window client commits to a render frame @@ -448,7 +448,7 @@ // Note regarding BackForwardCache: // Clients in back-forward cache don't count as controllees. bool HasControllee() const { return !controllee_map_.empty(); } - const std::map<std::string, base::WeakPtr<ServiceWorkerContainerHost>>& + const std::map<std::string, base::WeakPtr<ServiceWorkerClient>>& controllee_map() const { return controllee_map_; } @@ -462,7 +462,7 @@ void EvictBackForwardCachedControllees( BackForwardCacheMetrics::NotRestoredReason reason); void EvictBackForwardCachedControllee( - ServiceWorkerContainerHost* controllee, + ServiceWorkerClient* controllee, BackForwardCacheMetrics::NotRestoredReason reason); // The worker host hosting this version. Only valid while the version is @@ -1156,18 +1156,17 @@ std::unique_ptr<content::ServiceWorkerHost> worker_host_; // |controllee_map_| and |bfcached_controllee_map_| should not share the same - // controllee. ServiceWorkerContainerHost in the controllee maps should be + // controllee. ServiceWorkerClient in the controllee maps should be // non-null. // TODO(crbug.com/40199210): Fix cases where hosts can become nullptr while // stored in the maps. - std::map<std::string, base::WeakPtr<ServiceWorkerContainerHost>> - controllee_map_; - std::map<std::string, base::WeakPtr<ServiceWorkerContainerHost>> + std::map<std::string, base::WeakPtr<ServiceWorkerClient>> controllee_map_; + std::map<std::string, base::WeakPtr<ServiceWorkerClient>> bfcached_controllee_map_; - // Keeps track of the |client_uuid| of ContainerHost that is being evicted, - // and the reason why it is evicted. Once eviction is complete, the entry will - // be removed. + // Keeps track of the |client_uuid| of ServiceWorkerClient that is being + // evicted, and the reason why it is evicted. Once eviction is complete, the + // entry will be removed. // TODO(crbug.com/40657227): Remove this once we fix the crash. std::map<std::string, BackForwardCacheMetrics::NotRestoredReason> controllees_to_be_evicted_;
diff --git a/content/browser/service_worker/service_worker_version_browsertest.cc b/content/browser/service_worker/service_worker_version_browsertest.cc index 62df5af9..4c0db17 100644 --- a/content/browser/service_worker/service_worker_version_browsertest.cc +++ b/content/browser/service_worker/service_worker_version_browsertest.cc
@@ -457,17 +457,17 @@ void AddControllee() { ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI)); remote_endpoints_.emplace_back(); - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(/*mock process_id=*/33, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, wrapper()->context()->AsWeakPtr(), &remote_endpoints_.back()); const GURL url = embedded_test_server()->GetURL("/service_worker/host"); - container_host->UpdateUrls( + service_worker_client->UpdateUrls( url, url::Origin::Create(url), blink::StorageKey::CreateFirstParty(url::Origin::Create(url))); - container_host->SetControllerRegistration( + service_worker_client->SetControllerRegistration( registration_, false /* notify_controllerchange */); }
diff --git a/content/browser/service_worker/service_worker_version_unittest.cc b/content/browser/service_worker/service_worker_version_unittest.cc index 19508bb..887ada2 100644 --- a/content/browser/service_worker/service_worker_version_unittest.cc +++ b/content/browser/service_worker/service_worker_version_unittest.cc
@@ -209,19 +209,19 @@ controllee_process_id = version_->embedded_worker()->process_id(); } - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(controllee_process_id, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), &remote_endpoint); - container_host->UpdateUrls(registration_->scope(), - registration_->key().origin(), - registration_->key()); - container_host->SetControllerRegistration( + service_worker_client->UpdateUrls(registration_->scope(), + registration_->key().origin(), + registration_->key()); + service_worker_client->SetControllerRegistration( registration_, false /* notify_controllerchange */); EXPECT_TRUE(version_->HasControllee()); - EXPECT_TRUE(container_host->controller()); + EXPECT_TRUE(service_worker_client->controller()); return remote_endpoint; } @@ -533,18 +533,18 @@ version_->SetStatus(ServiceWorkerVersion::ACTIVATED); registration_->SetActiveVersion(version_); ServiceWorkerRemoteContainerEndpoint remote_endpoint; - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = CreateContainerHostForWindow( GlobalRenderFrameHostId(/*mock process_id=*/33, /*mock frame_routing_id=*/1), /*is_parent_frame_secure=*/true, helper_->context()->AsWeakPtr(), &remote_endpoint); - container_host->UpdateUrls(registration_->scope(), - registration_->key().origin(), - registration_->key()); - container_host->SetControllerRegistration(registration_, false); + service_worker_client->UpdateUrls(registration_->scope(), + registration_->key().origin(), + registration_->key()); + service_worker_client->SetControllerRegistration(registration_, false); EXPECT_TRUE(version_->HasControllee()); - EXPECT_TRUE(container_host->controller()); + EXPECT_TRUE(service_worker_client->controller()); // Set main_script_load_params_. version_->set_main_script_load_params( @@ -559,7 +559,7 @@ // The controllee should have been removed. EXPECT_EQ(ServiceWorkerVersion::REDUNDANT, version_->status()); EXPECT_FALSE(version_->HasControllee()); - EXPECT_FALSE(container_host->controller()); + EXPECT_FALSE(service_worker_client->controller()); // Ensure that the params are released. EXPECT_TRUE(version_->main_script_load_params_.is_null()); @@ -1445,19 +1445,19 @@ // cause the client to have an invalid process id like we see in real // navigations. ServiceWorkerRemoteContainerEndpoint remote_endpoint; - std::unique_ptr<ServiceWorkerContainerHostAndInfo> host_and_info = + std::unique_ptr<ServiceWorkerClientAndInfo> client_and_info = CreateContainerHostAndInfoForWindow(helper_->context()->AsWeakPtr(), /*are_ancestors_secure=*/true); - base::WeakPtr<ServiceWorkerContainerHost> container_host = - std::move(host_and_info->host); - remote_endpoint.BindForWindow(std::move(host_and_info->info)); - container_host->UpdateUrls(registration_->scope(), - registration_->key().origin(), - registration_->key()); - container_host->SetControllerRegistration( + base::WeakPtr<ServiceWorkerClient> service_worker_client = + std::move(client_and_info->service_worker_client); + remote_endpoint.BindForWindow(std::move(client_and_info->info)); + service_worker_client->UpdateUrls(registration_->scope(), + registration_->key().origin(), + registration_->key()); + service_worker_client->SetControllerRegistration( registration_, false /* notify_controllerchange */); EXPECT_TRUE(version_->HasControllee()); - EXPECT_TRUE(container_host->controller()); + EXPECT_TRUE(service_worker_client->controller()); // RenderProcessHost should be notified of foreground worker. base::RunLoop().RunUntilIdle(); @@ -1466,7 +1466,8 @@ helper_->mock_render_process_host()->foreground_service_worker_count()); // This is necessary to make OnBeginNavigationCommit() work. - auto remote_controller = container_host->GetRemoteControllerServiceWorker(); + auto remote_controller = + service_worker_client->GetRemoteControllerServiceWorker(); // Establish a dummy connection to allow sending messages without errors. mojo::PendingRemote<network::mojom::CrossOriginEmbedderPolicyReporter> @@ -1476,7 +1477,7 @@ // Now begin the navigation commit with the same process id used by the // worker. This should cause the worker to stop being considered foreground // priority. - container_host->OnBeginNavigationCommit( + service_worker_client->OnBeginNavigationCommit( GlobalRenderFrameHostId(version_->embedded_worker()->process_id(), /*frame_routing_id=*/1), PolicyContainerPolicies(), std::move(reporter),
diff --git a/content/browser/site_per_process_hit_test_browsertest.cc b/content/browser/site_per_process_hit_test_browsertest.cc index 9353e0a0..78e1afb 100644 --- a/content/browser/site_per_process_hit_test_browsertest.cc +++ b/content/browser/site_per_process_hit_test_browsertest.cc
@@ -5637,7 +5637,7 @@ // Clobber the real hit test data once it comes in. WaitForHitTestData(root->current_frame_host()); ASSERT_TRUE(GetHostFrameSinkManager()); - viz::HostFrameSinkManager::DisplayHitTestQueryMap empty_hit_test_map; + viz::DisplayHitTestQueryMap empty_hit_test_map; viz::HostFrameSinkManagerTestApi(GetHostFrameSinkManager()) .SetDisplayHitTestQuery(std::move(empty_hit_test_map));
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 43fec7c..482b7a1e 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -52,6 +52,7 @@ #include "components/download/public/common/download_stats.h" #include "components/url_formatter/url_formatter.h" #include "components/viz/common/features.h" +#include "components/viz/host/host_frame_sink_manager.h" #include "content/browser/accessibility/browser_accessibility.h" #include "content/browser/accessibility/browser_accessibility_state_impl.h" #include "content/browser/attribution_reporting/attribution_host.h" @@ -63,6 +64,7 @@ #include "content/browser/browser_plugin/browser_plugin_guest.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/closewatcher/close_listener_manager.h" +#include "content/browser/compositor/surface_utils.h" #include "content/browser/device_posture/device_posture_provider_impl.h" #include "content/browser/devtools/protocol/page_handler.h" #include "content/browser/devtools/render_frame_devtools_agent_host.h" @@ -3693,12 +3695,13 @@ TRACE_DISABLED_BY_DEFAULT("content.verbose"), "WebContentsImpl::AddRenderWidgetHostDestructionObserver"); - if (!base::Contains(render_widget_host_destruction_observers_, - render_widget_host)) { - render_widget_host_destruction_observers_[render_widget_host] = - std::make_unique<RenderWidgetHostDestructionObserver>( - this, render_widget_host); - } + DCHECK(!base::Contains(render_widget_host_destruction_observers_, + render_widget_host)); + + render_widget_host_destruction_observers_.insert( + {render_widget_host, + std::make_unique<RenderWidgetHostDestructionObserver>( + this, render_widget_host)}); } void WebContentsImpl::RemoveRenderWidgetHostDestructionObserver( @@ -3902,7 +3905,8 @@ if (!rwh_input_event_router_.get()) { rwh_input_event_router_ = - std::make_unique<RenderWidgetHostInputEventRouter>(); + std::make_unique<RenderWidgetHostInputEventRouter>( + GetHostFrameSinkManager()); } } return rwh_input_event_router_.get(); @@ -4806,8 +4810,9 @@ widget_view->SetWidgetType(WidgetType::kPopup); // Save the created widget associated with the route so we can show it later. - pending_widgets_[GlobalRoutingID(site_instance_group->process()->GetID(), - route_id)] = widget_host; + pending_widgets_.insert( + {GlobalRoutingID(site_instance_group->process()->GetID(), route_id), + widget_host}); AddRenderWidgetHostDestructionObserver(widget_host); return widget_host;
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index 515d25c..7684d73 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -1680,6 +1680,17 @@ // Clears a pending contents that has been closed before being shown. void OnWebContentsDestroyed(WebContentsImpl* web_contents); + // Creates and adds to the map a destruction observer watching + // `render_widget_host`. There must be no observer already watching + // `render_widget_host`. + void AddRenderWidgetHostDestructionObserver( + RenderWidgetHost* render_widget_host); + + // Deletes and removes from the map a destruction observer + // watching `render_widget_host`. No-op if there is no such observer. + void RemoveRenderWidgetHostDestructionObserver( + RenderWidgetHost* render_widget_host); + // Clears a pending render widget host that has been closed before being // shown. void OnRenderWidgetHostDestroyed(RenderWidgetHost* render_widget_host); @@ -1692,16 +1703,6 @@ // watching `web_contents`. No-op if there is no such observer. void RemoveWebContentsDestructionObserver(WebContentsImpl* web_contents); - // Creates and adds to the map a destruction observer watching - // `render_widget_host`. No-op if such an observer already exists. - void AddRenderWidgetHostDestructionObserver( - RenderWidgetHost* render_widget_host); - - // Deletes and removes from the map a destruction observer - // watching `render_widget_host`. No-op if there is no such observer. - void RemoveRenderWidgetHostDestructionObserver( - RenderWidgetHost* render_widget_host); - // Traverses all the WebContents in the WebContentsTree and creates a set of // all the unique RenderWidgetHostViews. std::set<RenderWidgetHostViewBase*>
diff --git a/content/browser/worker_host/dedicated_worker_host.cc b/content/browser/worker_host/dedicated_worker_host.cc index 4dd9dc5fe..427c52e 100644 --- a/content/browser/worker_host/dedicated_worker_host.cc +++ b/content/browser/worker_host/dedicated_worker_host.cc
@@ -301,12 +301,13 @@ // Also, we need the worker's parent to set FetchEvent::client_id. if (creator_render_frame_host) { // The creator of this worker is a frame. - service_worker_handle_->set_parent_container_host( + service_worker_handle_->set_parent_service_worker_client( creator_render_frame_host->GetLastCommittedServiceWorkerHost()); } else { - base::WeakPtr<ServiceWorkerContainerHost> creator_container_host = - creator_worker->service_worker_handle()->container_host(); - service_worker_handle_->set_parent_container_host(creator_container_host); + base::WeakPtr<ServiceWorkerClient> creator_service_worker_client = + creator_worker->service_worker_handle()->service_worker_client(); + service_worker_handle_->set_parent_service_worker_client( + creator_service_worker_client); } network::mojom::ClientSecurityStatePtr client_security_state; @@ -498,8 +499,8 @@ subresource_loader_updater_.BindNewPipeAndPassReceiver(), std::move(controller), BindAndPassRemoteForBackForwardCacheControllerHost()); - if (service_worker_handle_->container_host()) { - service_worker_handle_->container_host()->SetContainerReady(); + if (service_worker_handle_->service_worker_client()) { + service_worker_handle_->service_worker_client()->SetContainerReady(); } // |service_worker_remote_object| is an associated remote, so calls can't be @@ -940,24 +941,24 @@ return; } - base::WeakPtr<ServiceWorkerContainerHost> container_host = + base::WeakPtr<ServiceWorkerClient> service_worker_client = ancestor_render_frame_host->GetLastCommittedServiceWorkerHost(); - if (!container_host || !container_host->controller()) { + if (!service_worker_client || !service_worker_client->controller()) { return; } - if (!blink::ServiceWorkerScopeMatches(container_host->controller()->scope(), - script_url) || - container_host->key() != storage_key_) { + if (!blink::ServiceWorkerScopeMatches( + service_worker_client->controller()->scope(), script_url) || + service_worker_client->key() != storage_key_) { // Count the number of dedicated workers that 1) are controlled by a service // worker that is inherited from a controlled document, and 2) will not be // controlled by that service worker after PlzDedicatedWorker is enabled. - container_host->CountFeature( + service_worker_client->CountFeature( blink::mojom::WebFeature::kWorkerControlledByServiceWorkerOutOfScope); - DCHECK_NE(container_host->controller()->fetch_handler_existence(), + DCHECK_NE(service_worker_client->controller()->fetch_handler_existence(), ServiceWorkerVersion::FetchHandlerExistence::UNKNOWN); - if (container_host->controller()->fetch_handler_existence() == + if (service_worker_client->controller()->fetch_handler_existence() == ServiceWorkerVersion::FetchHandlerExistence::EXISTS) { // Count the number of dedicated workers that 1) are controlled by a // service worker that is inherited from a controlled document, 2) will @@ -965,7 +966,7 @@ // enabled, and 3) have a fetch event handler. // `kControlledWorkerWillBeUncontrolled` excludes the cases if a // dedicated worker is controlled by any registered service worker. - container_host->CountFeature( + service_worker_client->CountFeature( blink::mojom::WebFeature:: kWorkerControlledByServiceWorkerWithFetchEventHandlerOutOfScope); @@ -982,19 +983,19 @@ ancestor_render_frame_host->GetLastCommittedOrigin()), base::BindOnce(&DedicatedWorkerHost::ContinueOnMaybeCountWebFeature, weak_factory_.GetWeakPtr(), script_url, - std::move(container_host))); + std::move(service_worker_client))); } } } void DedicatedWorkerHost::ContinueOnMaybeCountWebFeature( const GURL& script_url, - base::WeakPtr<ServiceWorkerContainerHost> ancestor_container_host, + base::WeakPtr<ServiceWorkerClient> ancestor_service_worker_client, blink::ServiceWorkerStatusCode status, const std::vector<scoped_refptr<ServiceWorkerRegistration>>& registrations) { DCHECK(!base::FeatureList::IsEnabled(blink::features::kPlzDedicatedWorker)); - if (!ancestor_container_host || + if (!ancestor_service_worker_client || status != blink::ServiceWorkerStatusCode::kOk) { return; } @@ -1013,13 +1014,13 @@ // Count the number of dedicated workers that are not controlled by any // service worker registered for the origin after PlzDedicatedWorker is // enabled. - ancestor_container_host->CountFeature( + ancestor_service_worker_client->CountFeature( blink::mojom::WebFeature::kControlledWorkerWillBeUncontrolled); // Exclude the cases that `script_url` is a blob URL from // kControlledWorkerWillBeUncontrolled. if (!script_url.SchemeIsBlob()) { - ancestor_container_host->CountFeature( + ancestor_service_worker_client->CountFeature( blink::mojom::WebFeature:: kControlledNonBlobURLWorkerWillBeUncontrolled); } @@ -1125,12 +1126,12 @@ return bfcache_blocking_details_; } -base::WeakPtr<ServiceWorkerContainerHost> -DedicatedWorkerHost::GetServiceWorkerContainerHost() { +base::WeakPtr<ServiceWorkerClient> +DedicatedWorkerHost::GetServiceWorkerClient() { if (!service_worker_handle_) { return nullptr; } - return service_worker_handle_->container_host(); + return service_worker_handle_->service_worker_client(); } mojo::PendingRemote<blink::mojom::BackForwardCacheControllerHost>
diff --git a/content/browser/worker_host/dedicated_worker_host.h b/content/browser/worker_host/dedicated_worker_host.h index 8ed5aa6..ce63b4e 100644 --- a/content/browser/worker_host/dedicated_worker_host.h +++ b/content/browser/worker_host/dedicated_worker_host.h
@@ -61,7 +61,7 @@ namespace content { -class ServiceWorkerContainerHost; +class ServiceWorkerClient; class ServiceWorkerRegistration; class DedicatedWorkerServiceImpl; class ServiceWorkerMainResourceHandle; @@ -184,7 +184,7 @@ // enabled by default. void ContinueOnMaybeCountWebFeature( const GURL& script_url, - base::WeakPtr<ServiceWorkerContainerHost> container_host, + base::WeakPtr<ServiceWorkerClient> service_worker_client, blink::ServiceWorkerStatusCode status, const std::vector<scoped_refptr<ServiceWorkerRegistration>>& registrations); @@ -256,7 +256,7 @@ const BackForwardCacheBlockingDetails& GetBackForwardCacheBlockingDetails() const; - base::WeakPtr<ServiceWorkerContainerHost> GetServiceWorkerContainerHost(); + base::WeakPtr<ServiceWorkerClient> GetServiceWorkerClient(); mojo::PendingRemote<blink::mojom::BackForwardCacheControllerHost> BindAndPassRemoteForBackForwardCacheControllerHost();
diff --git a/content/browser/worker_host/dedicated_worker_hosts_for_document.cc b/content/browser/worker_host/dedicated_worker_hosts_for_document.cc index 8f56dca..db857950 100644 --- a/content/browser/worker_host/dedicated_worker_hosts_for_document.cc +++ b/content/browser/worker_host/dedicated_worker_hosts_for_document.cc
@@ -58,9 +58,9 @@ RenderFrameHost::LifecycleState::kInBackForwardCache); for (auto worker : dedicated_workers_) { - if (base::WeakPtr<ServiceWorkerContainerHost> container_host = - worker->GetServiceWorkerContainerHost()) { - container_host->OnEnterBackForwardCache(); + if (base::WeakPtr<ServiceWorkerClient> service_worker_client = + worker->GetServiceWorkerClient()) { + service_worker_client->OnEnterBackForwardCache(); } } } @@ -71,9 +71,9 @@ RenderFrameHost::LifecycleState::kInBackForwardCache); for (auto worker : dedicated_workers_) { - if (base::WeakPtr<ServiceWorkerContainerHost> container_host = - worker->GetServiceWorkerContainerHost()) { - container_host->OnRestoreFromBackForwardCache(); + if (base::WeakPtr<ServiceWorkerClient> service_worker_client = + worker->GetServiceWorkerClient()) { + service_worker_client->OnRestoreFromBackForwardCache(); } } }
diff --git a/content/browser/worker_host/shared_worker_host.cc b/content/browser/worker_host/shared_worker_host.cc index 5e957b1d..812d60e 100644 --- a/content/browser/worker_host/shared_worker_host.cc +++ b/content/browser/worker_host/shared_worker_host.cc
@@ -370,8 +370,8 @@ receiver_.BindNewPipeAndPassRemote(), std::move(worker_receiver_), std::move(browser_interface_broker), ukm_source_id_, instance_.DoesRequireCrossSiteRequestForCookies()); - if (service_worker_handle_->container_host()) { - service_worker_handle_->container_host()->SetContainerReady(); + if (service_worker_handle_->service_worker_client()) { + service_worker_handle_->service_worker_client()->SetContainerReady(); } // |service_worker_remote_object| is an associated interface ptr, so calls
diff --git a/content/browser/worker_host/shared_worker_service_impl.cc b/content/browser/worker_host/shared_worker_service_impl.cc index a1e0cbf2..fa07d91e4 100644 --- a/content/browser/worker_host/shared_worker_service_impl.cc +++ b/content/browser/worker_host/shared_worker_service_impl.cc
@@ -363,7 +363,7 @@ auto service_worker_handle = std::make_unique<ServiceWorkerMainResourceHandle>( storage_partition_->GetServiceWorkerContext(), base::DoNothing()); - service_worker_handle->set_parent_container_host( + service_worker_handle->set_parent_service_worker_client( creator.GetLastCommittedServiceWorkerHost()); auto* service_worker_handle_raw = service_worker_handle.get(); host->SetServiceWorkerHandle(std::move(service_worker_handle));
diff --git a/content/browser/worker_host/worker_script_loader_factory_unittest.cc b/content/browser/worker_host/worker_script_loader_factory_unittest.cc index 413d0034..0cdc7301 100644 --- a/content/browser/worker_host/worker_script_loader_factory_unittest.cc +++ b/content/browser/worker_host/worker_script_loader_factory_unittest.cc
@@ -111,11 +111,11 @@ EXPECT_EQ(net::OK, client.completion_status().error_code); // The container host should be set up. - base::WeakPtr<ServiceWorkerContainerHost> container_host = - service_worker_handle_->container_host(); - EXPECT_TRUE(container_host->is_response_committed()); - EXPECT_TRUE(container_host->is_execution_ready()); - EXPECT_EQ(url, container_host->url()); + base::WeakPtr<ServiceWorkerClient> service_worker_client = + service_worker_handle_->service_worker_client(); + EXPECT_TRUE(service_worker_client->is_response_committed()); + EXPECT_TRUE(service_worker_client->is_execution_ready()); + EXPECT_EQ(url, service_worker_client->url()); } // Test a null service worker handle. This typically only happens during
diff --git a/content/public/test/hit_test_region_observer.cc b/content/public/test/hit_test_region_observer.cc index 7e6f764..74f819c 100644 --- a/content/public/test/hit_test_region_observer.cc +++ b/content/public/test/hit_test_region_observer.cc
@@ -7,7 +7,7 @@ #include <algorithm> #include "base/test/test_timeouts.h" -#include "components/viz/host/hit_test/hit_test_query.h" +#include "components/viz/common/hit_test/hit_test_query.h" #include "components/viz/host/host_frame_sink_manager.h" #include "content/browser/compositor/surface_utils.h" #include "content/browser/renderer_host/render_frame_host_impl.h" @@ -57,7 +57,7 @@ void HitTestRegionObserver::WaitForHitTestData() { DCHECK(cached_hit_test_data_.empty()); - for (auto& it : GetHostFrameSinkManager()->display_hit_test_query()) { + for (auto& it : GetHostFrameSinkManager()->GetDisplayHitTestQuery()) { if (it.second->ContainsActiveFrameSinkId(frame_sink_id_)) { cached_hit_test_data_ = it.second->GetHitTestData(); return; @@ -72,7 +72,7 @@ void HitTestRegionObserver::WaitForHitTestDataChange() { DCHECK(!cached_hit_test_data_.empty()); - for (auto& it : GetHostFrameSinkManager()->display_hit_test_query()) { + for (auto& it : GetHostFrameSinkManager()->GetDisplayHitTestQuery()) { DCHECK(it.second->ContainsActiveFrameSinkId(frame_sink_id_)); if (it.second->GetHitTestData() != cached_hit_test_data_) { cached_hit_test_data_ = it.second->GetHitTestData(); @@ -109,7 +109,7 @@ const std::vector<viz::AggregatedHitTestRegion>& HitTestRegionObserver::GetHitTestData() { const auto& hit_test_query_map = - GetHostFrameSinkManager()->display_hit_test_query(); + GetHostFrameSinkManager()->GetDisplayHitTestQuery(); const auto iter = hit_test_query_map.find(frame_sink_id_); DCHECK(iter != hit_test_query_map.end()); return iter->second.get()->GetHitTestData();
diff --git a/content/public/test/hit_test_region_observer.h b/content/public/test/hit_test_region_observer.h index 3c86d5f..87d8216 100644 --- a/content/public/test/hit_test_region_observer.h +++ b/content/public/test/hit_test_region_observer.h
@@ -10,8 +10,8 @@ #include "base/run_loop.h" #include "components/viz/common/hit_test/aggregated_hit_test_region.h" +#include "components/viz/common/hit_test/hit_test_region_observer.h" #include "components/viz/common/surfaces/frame_sink_id.h" -#include "components/viz/host/hit_test/hit_test_region_observer.h" namespace content { class RenderFrameHost;
diff --git a/content/services/auction_worklet/real_time_reporting_bindings.cc b/content/services/auction_worklet/real_time_reporting_bindings.cc index ea518ec..53e5798 100644 --- a/content/services/auction_worklet/real_time_reporting_bindings.cc +++ b/content/services/auction_worklet/real_time_reporting_bindings.cc
@@ -28,10 +28,6 @@ namespace { -// Total number of buckets. Supported buckets will be [0, kNumBuckets). -// [0, kNumReservedBuckets) are reserved, and [kNumReservedBuckets, kNumBuckets) -// are for real time reporting APIs to use. -static const int kNumBuckets = 1024; // Reserved buckets, [0, kNumReservedBuckets), for errors not detectable in // worklet JS, such as failures to fetch the bidding script, trusted real-time // signals. @@ -83,9 +79,11 @@ return; } - // [0, kNumBuckets) are supported buckets, while [0, kNumReservedBuckets) are - // reserved buckets which cannot be used by real time reporting APIs. - if (bucket < kNumReservedBuckets || bucket >= kNumBuckets) { + // [0, features::kFledgeRealTimeReportingNumBuckets) are supported buckets, + // while [0, kNumReservedBuckets) are reserved buckets which cannot be used by + // real time reporting APIs. + if (bucket < kNumReservedBuckets || + bucket >= blink::features::kFledgeRealTimeReportingNumBuckets.Get()) { // Don't throw, to be forward compatible. return; }
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index b160aab20d..b5e0b3cf 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -2496,6 +2496,7 @@ "../browser/interest_group/interest_group_permissions_cache_unittest.cc", "../browser/interest_group/interest_group_permissions_checker_unittest.cc", "../browser/interest_group/interest_group_priority_util_unittest.cc", + "../browser/interest_group/interest_group_real_time_report_util_unittest.cc", "../browser/interest_group/interest_group_storage_unittest.cc", "../browser/interest_group/mock_auction_process_manager.cc", "../browser/interest_group/mock_auction_process_manager.h",
diff --git a/content/test/mock_render_widget_host_delegate.cc b/content/test/mock_render_widget_host_delegate.cc index a2eb515..5be1cf4c 100644 --- a/content/test/mock_render_widget_host_delegate.cc +++ b/content/test/mock_render_widget_host_delegate.cc
@@ -4,6 +4,9 @@ #include "content/test/mock_render_widget_host_delegate.h" +#include "components/viz/common/hit_test/hit_test_data_provider.h" +#include "components/viz/host/host_frame_sink_manager.h" +#include "content/browser/compositor/surface_utils.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "content/public/common/input/native_web_keyboard_event.h" @@ -45,8 +48,8 @@ void MockRenderWidgetHostDelegate::SelectAll() {} void MockRenderWidgetHostDelegate::CreateInputEventRouter() { - rwh_input_event_router_ = - std::make_unique<RenderWidgetHostInputEventRouter>(); + rwh_input_event_router_ = std::make_unique<RenderWidgetHostInputEventRouter>( + GetHostFrameSinkManager()); } RenderWidgetHostInputEventRouter*
diff --git a/docs/android_build_instructions.md b/docs/android_build_instructions.md index d2de132..2e94a05e 100644 --- a/docs/android_build_instructions.md +++ b/docs/android_build_instructions.md
@@ -125,11 +125,9 @@ ```gn target_os = "android" target_cpu = "arm64" # See "Figuring out target_cpu" below +use_remoteexec = true # Enables distributed builds. See "Faster Builds". ``` -* There are several settings that will speed up compile/deploy time at the cost - of some unusual edge cases that will not affect most developers. See - `incremental_install` and other options below. * You only have to run this once for each new build directory, Ninja will update the build files as needed. * You can replace `Default` with another name, but @@ -164,28 +162,6 @@ as the WebView provider. *** -### Faster builds - -This section contains some things you can change to speed up your builds, -sorted so that the things that make the biggest difference are first. - -#### Use Reclient - -*** note -**Warning:** If you are a Google employee, do not follow the instructions below. -See -[go/building-android-chrome#initialize-remote-execution-distributed-builds](https://goto.google.com/building-android-chrome#initialize-remote-execution-distributed-builds) -instead. -*** - -Chromium's build can be sped up significantly by using a remote execution system -compatible with [REAPI](https://github.com/bazelbuild/remote-apis). This allows -you to benefit from remote caching and executing many build actions in parallel -on a shared cluster of workers. - -To use Reclient, follow the corresponding -[Linux build instructions](linux/build_instructions.md#use-reclient). - ## Build Chromium Build Chromium with Ninja using the command: @@ -379,14 +355,38 @@ For information on running tests, see [Android Test Instructions](/docs/testing/android_test_instructions.md) -### Faster Edit/Deploy +## Faster Builds -#### GN Args +### Use Reclient + +*** note +**Warning:** If you are a Google employee, do not follow the instructions below. +See +[go/building-android-chrome#initialize-remote-execution-distributed-builds](https://goto.google.com/building-android-chrome#initialize-remote-execution-distributed-builds) +instead. +*** + +Chromium's build can be sped up significantly by using a remote execution system +compatible with [REAPI](https://github.com/bazelbuild/remote-apis). This allows +you to benefit from remote caching and executing many build actions in parallel +on a shared cluster of workers. + +To use Reclient, follow the corresponding +[Linux build instructions](linux/build_instructions.md#use-reclient). + +### GN Args + Args that affect build speed: + * `use_remoteexec = true` *(default=false)* + * What it does: Enables distributed builds via Reclient + * `symbol_level = 0` *(default=1)* + * What it does: Disables debug information in native code. + * Use this when doing primarily Java development. + * To disable symbols only in Blink / V8: `blink_symbol_level = 0`, `v8_symbol_level = 0` * `is_component_build = true` *(default=`is_debug`)* * What it does: Uses multiple `.so` files instead of just one (faster links) * `is_java_debug = true` *(default=`is_debug`)* - * What it does: Disables ProGuard (slow build step) + * What it does: Disables R8 (whole-program Java optimizer) * `treat_warnings_as_errors = false` *(default=`true`)* * Causes any compiler warnings or lint checks to not fail the build. * Allows you to iterate without needing to satisfy static analysis checks. @@ -395,19 +395,22 @@ * Set this to `"off"` if you want to turn off static analysis altogether. * `incremental_install = true` *(default=`false`)* * Makes build and install quite a bit faster. Explained in a later section. + * `enable_chrome_android_internal = false` *(Googlers only)* + * Disables non-public code, which exists even when building public targets. + * Use this is you do not need to test internal-only things. -#### Running static analysis with the build server -Normally analysis build steps like lint and errorprone will run in parallel with -the rest of the build. The build will then wait for all analysis steps to -complete successfully. By offloading analysis build steps to a separate build -server to be run lazily at a low priority when the machine is idle, the actual -build can complete up to 50-80% faster. +### Running Static Analysis Asynchronously + +Normally analysis build steps like Lint and Error Prone will run as normal build +steps. The build will then wait for all analysis steps to complete successfully. +By offloading analysis build steps to a separate build server to be run lazily at +a low priority when the machine is idle, the actual build can complete much faster. **Note**: Since the build completes before the analysis checks finish, the build will not fail if an analysis check fails. Make sure to check the server's output at regular intervals to fix outstanding issues caught by these analysis checks. -##### First way (by running it manually) +#### First way (by running it manually) There are **two** steps to using the build server. 1. Add the gn arg `android_static_analysis = "build_server"` @@ -419,7 +422,7 @@ If you run (2) in a terminal, the output of the checks will be displayed there. -##### Second way (using systemd) +#### Second way (using systemd) Alternatively, you can set up the server as a Linux service, so it runs on the background and starts on boot. If you're using systemd:
diff --git a/extensions/browser/api/web_request/extension_web_request_event_router.cc b/extensions/browser/api/web_request/extension_web_request_event_router.cc index a97249b..1414f30 100644 --- a/extensions/browser/api/web_request/extension_web_request_event_router.cc +++ b/extensions/browser/api/web_request/extension_web_request_event_router.cc
@@ -215,23 +215,10 @@ return false; } - const std::set<std::string> extension_ids = - ProcessMap::Get(context)->GetExtensionsInProcess( + const Extension* extension = + ProcessMap::Get(context)->GetEnabledExtensionByProcessID( request.render_process_id); - if (extension_ids.empty()) { - return false; - } - - // Treat hosted apps as normal web pages (crbug.com/526413). - for (const ExtensionId& extension_id : extension_ids) { - const Extension* extension = - ExtensionRegistry::Get(context)->enabled_extensions().GetByID( - extension_id); - if (extension && !extension->is_hosted_app()) { - return true; - } - } - return false; + return extension && !extension->is_hosted_app(); } // Sends an event to subscribers of chrome.declarativeWebRequest.onMessage or
diff --git a/extensions/browser/event_router_unittest.cc b/extensions/browser/event_router_unittest.cc index 4545ea4f..1a560bf 100644 --- a/extensions/browser/event_router_unittest.cc +++ b/extensions/browser/event_router_unittest.cc
@@ -437,6 +437,9 @@ // A fake that pretends that all contexts are WebUI. class ProcessMapFake : public ProcessMap { public: + explicit ProcessMapFake(content::BrowserContext* browser_context) + : ProcessMap(browser_context) {} + mojom::ContextType GetMostLikelyContextType(const Extension* extension, int process_id, const GURL* url) const override { @@ -446,7 +449,7 @@ std::unique_ptr<KeyedService> BuildProcessMap( content::BrowserContext* profile) { - return std::make_unique<ProcessMapFake>(); + return std::make_unique<ProcessMapFake>(profile); } } // namespace
diff --git a/extensions/browser/process_map.cc b/extensions/browser/process_map.cc index 868027e..b67b710 100644 --- a/extensions/browser/process_map.cc +++ b/extensions/browser/process_map.cc
@@ -8,6 +8,8 @@ #include <tuple> #include "base/containers/contains.h" +#include "base/containers/map_util.h" +#include "base/types/optional_util.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/url_constants.h" @@ -57,42 +59,50 @@ } // namespace // ProcessMap -ProcessMap::ProcessMap() = default; +ProcessMap::ProcessMap(content::BrowserContext* browser_context) + : browser_context_(browser_context) {} ProcessMap::~ProcessMap() = default; +void ProcessMap::Shutdown() { + browser_context_ = nullptr; +} + // static ProcessMap* ProcessMap::Get(content::BrowserContext* browser_context) { return ProcessMapFactory::GetForBrowserContext(browser_context); } bool ProcessMap::Insert(const ExtensionId& extension_id, int process_id) { - return items_.emplace(extension_id, process_id).second; + return items_.emplace(process_id, extension_id).second; } -int ProcessMap::RemoveAllFromProcess(int process_id) { - return std::erase_if( - items_, [&](const auto& item) { return item.second == process_id; }); +int ProcessMap::Remove(int process_id) { + return items_.erase(process_id); } -bool ProcessMap::Contains(const ExtensionId& extension_id, +bool ProcessMap::Contains(const ExtensionId& extension_id_in, int process_id) const { - return items_.contains({extension_id, process_id}); + auto* extension_id = base::FindOrNull(items_, process_id); + return extension_id && *extension_id == extension_id_in; } bool ProcessMap::Contains(int process_id) const { - return base::Contains(items_, process_id, &Item::second); + return base::Contains(items_, process_id); } -std::set<ExtensionId> ProcessMap::GetExtensionsInProcess( - int process_id_in) const { - std::set<ExtensionId> result; - for (const auto& [extension_id, process_id] : items_) { - if (process_id == process_id_in) { - result.insert(extension_id); - } - } - return result; +const Extension* ProcessMap::GetEnabledExtensionByProcessID( + int process_id) const { + auto* extension_id = base::FindOrNull(items_, process_id); + return extension_id ? ExtensionRegistry::Get(browser_context_) + ->enabled_extensions() + .GetByID(*extension_id) + : nullptr; +} + +std::optional<ExtensionId> ProcessMap::GetExtensionIdForProcess( + int process_id) const { + return base::OptionalFromPtr(base::FindOrNull(items_, process_id)); } bool ProcessMap::IsPrivilegedExtensionProcess(const Extension& extension,
diff --git a/extensions/browser/process_map.h b/extensions/browser/process_map.h index d9360f93..183a343 100644 --- a/extensions/browser/process_map.h +++ b/extensions/browser/process_map.h
@@ -7,8 +7,9 @@ #include <stddef.h> -#include <set> +#include <optional> +#include "base/containers/flat_map.h" #include "components/keyed_service/core/keyed_service.h" #include "content/public/browser/site_instance.h" #include "extensions/common/extension_id.h" @@ -17,7 +18,7 @@ namespace content { class BrowserContext; -} +} // namespace content namespace extensions { class Extension; @@ -33,14 +34,13 @@ // - There are also hosted apps, which are a kind of extensions, and those // usually have a process model similar to normal web sites: multiple // processes per-profile. -// - A single hosted app can have more than one SiteInstance in the same process -// if we're over the process limit and force them to share a process. // - An extension can also opt into Cross Origin Isolation in which case it can // have multiple processes per profile since cross-origin-isolated and // non-cross-origin-isolated contexts don't share a process. // -// In general, we seem to play with the process model of extensions a lot, so -// it is safest to assume it is many-to-many in most places in the codebase. +// Under the current model, a single extension can correspond to multiple +// processes (see explanation below), but a single process cannot be shared by +// multiple extensions. // // Note that because of content scripts, frames, and other edge cases in // Chrome's process isolation, extension code can still end up running outside @@ -78,13 +78,15 @@ // enforce single thread. Investigation required. class ProcessMap : public KeyedService { public: - ProcessMap(); + explicit ProcessMap(content::BrowserContext* browser_context); ProcessMap(const ProcessMap&) = delete; ProcessMap& operator=(const ProcessMap&) = delete; ~ProcessMap() override; + void Shutdown() override; + // Returns the instance for |browser_context|. An instance is shared between // an incognito and a regular context. static ProcessMap* Get(content::BrowserContext* browser_context); @@ -93,12 +95,16 @@ bool Insert(const ExtensionId& extension_id, int process_id); - int RemoveAllFromProcess(int process_id); + int Remove(int process_id); bool Contains(const ExtensionId& extension_id, int process_id) const; bool Contains(int process_id) const; - std::set<ExtensionId> GetExtensionsInProcess(int process_id) const; + // Returns a pointer to an enabled extension running in `process_id` or + // nullptr. + const Extension* GetEnabledExtensionByProcessID(int process_id) const; + + std::optional<ExtensionId> GetExtensionIdForProcess(int process_id) const; // Returns true if the given `process_id` is considered a privileged context // for the given `extension`. That is, if it would *probably* correspond to a @@ -200,13 +206,14 @@ private: using ProcessId = int; - using Item = std::pair<ExtensionId, ProcessId>; - std::set<Item> items_; + base::flat_map<ProcessId, ExtensionId> items_; // Whether the process map belongs to the browser context used on Chrome OS // lock screen. bool is_lock_screen_context_ = false; + + raw_ptr<content::BrowserContext> browser_context_; }; } // namespace extensions
diff --git a/extensions/browser/process_map_factory.cc b/extensions/browser/process_map_factory.cc index da42c9e5..f1ebc99 100644 --- a/extensions/browser/process_map_factory.cc +++ b/extensions/browser/process_map_factory.cc
@@ -5,6 +5,7 @@ #include "extensions/browser/process_map_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "extensions/browser/extension_registry_factory.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/process_map.h" @@ -27,7 +28,7 @@ : BrowserContextKeyedServiceFactory( "ProcessMap", BrowserContextDependencyManager::GetInstance()) { - // No dependencies on other services. + DependsOn(ExtensionRegistryFactory::GetInstance()); } ProcessMapFactory::~ProcessMapFactory() = default; @@ -35,7 +36,8 @@ std::unique_ptr<KeyedService> ProcessMapFactory::BuildServiceInstanceForBrowserContext( BrowserContext* context) const { - std::unique_ptr<ProcessMap> process_map = std::make_unique<ProcessMap>(); + std::unique_ptr<ProcessMap> process_map = + std::make_unique<ProcessMap>(context); process_map->set_is_lock_screen_context( ExtensionsBrowserClient::Get()->IsLockScreenContext(context)); return process_map;
diff --git a/extensions/browser/process_map_unittest.cc b/extensions/browser/process_map_unittest.cc index 17ee8a0c..6ccb46b 100644 --- a/extensions/browser/process_map_unittest.cc +++ b/extensions/browser/process_map_unittest.cc
@@ -59,11 +59,11 @@ using extensions::ProcessMap; TEST(ExtensionProcessMapTest, Test) { - ProcessMap map; + ProcessMap map(/*browser_context=*/nullptr); // Test behavior when empty. EXPECT_FALSE(map.Contains("a", 1)); - EXPECT_FALSE(map.RemoveAllFromProcess(1)); + EXPECT_FALSE(map.Remove(1)); EXPECT_EQ(0u, map.size()); // Test insertion and behavior with one item. @@ -96,27 +96,27 @@ // At this point we have {a,1}, {a,2}, {b,3}, and {b,4} in the map. Test // removal of these processes. - EXPECT_EQ(1, map.RemoveAllFromProcess(1)); + EXPECT_EQ(1, map.Remove(1)); EXPECT_EQ(3u, map.size()); EXPECT_FALSE(map.Contains("a", 1)); EXPECT_TRUE(map.Contains("a", 2)); - EXPECT_EQ(1, map.RemoveAllFromProcess(2)); + EXPECT_EQ(1, map.Remove(2)); EXPECT_EQ(2u, map.size()); - EXPECT_EQ(0, map.RemoveAllFromProcess(2)); + EXPECT_EQ(0, map.Remove(2)); EXPECT_EQ(2u, map.size()); - EXPECT_EQ(1, map.RemoveAllFromProcess(3)); + EXPECT_EQ(1, map.Remove(3)); EXPECT_EQ(1u, map.size()); - EXPECT_EQ(0, map.RemoveAllFromProcess(3)); + EXPECT_EQ(0, map.Remove(3)); EXPECT_EQ(1u, map.size()); - EXPECT_EQ(1, map.RemoveAllFromProcess(4)); + EXPECT_EQ(1, map.Remove(4)); EXPECT_EQ(0u, map.size()); - EXPECT_EQ(0, map.RemoveAllFromProcess(4)); + EXPECT_EQ(0, map.Remove(4)); EXPECT_EQ(0u, map.size()); } TEST(ExtensionProcessMapTest, GetMostLikelyContextType) { - ProcessMap map; + ProcessMap map(/*browser_context=*/nullptr); const GURL web_url("https://foo.example"); const GURL extension_url("chrome-extension://foobar"); const GURL untrusted_webui_url("chrome-untrusted://foo/index.html");
diff --git a/gpu/command_buffer/service/shared_image/dawn_ozone_image_representation.cc b/gpu/command_buffer/service/shared_image/dawn_ozone_image_representation.cc index 4a51cbc..2dc2211 100644 --- a/gpu/command_buffer/service/shared_image/dawn_ozone_image_representation.cc +++ b/gpu/command_buffer/service/shared_image/dawn_ozone_image_representation.cc
@@ -62,9 +62,14 @@ std::vector<gfx::GpuFenceHandle> fences; bool need_end_fence; + // We will treat this access as a write if the client 'usage' implies write + // access and if the image has been initialized (cleared). The latter test is + // necessary because internally dawn will initialize (clear) the buffer if it + // has not yet been cleared. + is_readonly_ = (usage & kWriteUsage) == 0 && IsCleared(); if (!ozone_backing()->BeginAccess( - /*readonly=*/false, OzoneImageBacking::AccessStream::kWebGPU, &fences, - need_end_fence)) { + /*readonly=*/is_readonly_, OzoneImageBacking::AccessStream::kWebGPU, + &fences, need_end_fence)) { return nullptr; } DCHECK(need_end_fence); @@ -81,14 +86,17 @@ texture_descriptor.mipLevelCount = 1; texture_descriptor.sampleCount = 1; - // We need to have internal usages of CopySrc for copies, - // RenderAttachment for clears, and TextureBinding for copyTextureForBrowser. + // We need to have internal usages of CopySrc for copies and TextureBinding + // for copyTextureForBrowser. wgpu::DawnTextureInternalUsageDescriptor internalDesc; internalDesc.internalUsage = wgpu::TextureUsage::CopySrc; // No write access to multi-planar pixmaps. if (pixmap_->GetNumberOfPlanes() == 1) { - internalDesc.internalUsage |= wgpu::TextureUsage::RenderAttachment | - wgpu::TextureUsage::TextureBinding; + internalDesc.internalUsage |= wgpu::TextureUsage::TextureBinding; + if (!IsCleared()) { + // RenderAttachment for (lazy) clears. + internalDesc.internalUsage |= wgpu::TextureUsage::RenderAttachment; + } } texture_descriptor.nextInChain = &internalDesc; @@ -118,7 +126,7 @@ texture_ = wgpu::Texture::Acquire( dawn::native::vulkan::WrapVulkanImage(device_.Get(), &descriptor)); if (!texture_) { - ozone_backing()->EndAccess(/*readonly=*/false, + ozone_backing()->EndAccess(is_readonly_, OzoneImageBacking::AccessStream::kWebGPU, gfx::GpuFenceHandle()); close(fd); @@ -146,7 +154,7 @@ DCHECK(export_info.semaphoreHandles.size() == 1); gfx::GpuFenceHandle fence; fence.Adopt(base::ScopedFD(export_info.semaphoreHandles[0])); - ozone_backing()->EndAccess(/*readonly=*/false, + ozone_backing()->EndAccess(is_readonly_, OzoneImageBacking::AccessStream::kWebGPU, std::move(fence)); }
diff --git a/gpu/command_buffer/service/shared_image/dawn_ozone_image_representation.h b/gpu/command_buffer/service/shared_image/dawn_ozone_image_representation.h index f8baaf1e..2de3c5d 100644 --- a/gpu/command_buffer/service/shared_image/dawn_ozone_image_representation.h +++ b/gpu/command_buffer/service/shared_image/dawn_ozone_image_representation.h
@@ -52,6 +52,7 @@ std::vector<wgpu::TextureFormat> view_formats_; scoped_refptr<gfx::NativePixmap> pixmap_; wgpu::Texture texture_; + bool is_readonly_ = false; }; } // namespace gpu
diff --git a/internal b/internal index 6b8f062..08c6d52 160000 --- a/internal +++ b/internal
@@ -1 +1 @@ -Subproject commit 6b8f06285faa0d9e7e9dbc8b30f6fe8f2c73df36 +Subproject commit 08c6d52feed1b28526673b31c960af555f673b3d
diff --git a/ios/chrome/browser/autofill/model/autofill_controller_unittest.mm b/ios/chrome/browser/autofill/model/autofill_controller_unittest.mm index 76159b02..8dc8090a 100644 --- a/ios/chrome/browser/autofill/model/autofill_controller_unittest.mm +++ b/ios/chrome/browser/autofill/model/autofill_controller_unittest.mm
@@ -532,7 +532,7 @@ ResetWaitForSuggestionRetrieval(); web::test::ExecuteJavaScript(@"document.forms[0].name.focus()", web_state()); WaitForSuggestionRetrieval(/*wait_for_trigger=*/YES); - ExpectMetric("Autofill.AddressSuggestionsCount", 1); + ExpectMetric("Autofill.SuggestionsCount.Address", 1); EXPECT_EQ(1U, [suggestion_controller() suggestions].count); FormSuggestion* suggestion = [suggestion_controller() suggestions][0]; EXPECT_NSEQ(@"Homer Simpson", suggestion.value); @@ -553,7 +553,7 @@ ResetWaitForSuggestionRetrieval(); web::test::ExecuteJavaScript(@"document.forms[0].name.focus()", web_state()); WaitForSuggestionRetrieval(/*wait_for_trigger=*/YES); - ExpectMetric("Autofill.AddressSuggestionsCount", 1); + ExpectMetric("Autofill.SuggestionsCount.Address", 1); EXPECT_EQ(1U, [suggestion_controller() suggestions].count); FormSuggestion* suggestion = [suggestion_controller() suggestions][0]; EXPECT_NSEQ(@"Homer Simpson", suggestion.value); @@ -573,7 +573,7 @@ ResetWaitForSuggestionRetrieval(); web::test::ExecuteJavaScript(@"document.forms[0].state.focus()", web_state()); WaitForSuggestionRetrieval(/*wait_for_trigger=*/YES); - ExpectMetric("Autofill.AddressSuggestionsCount", 1); + ExpectMetric("Autofill.SuggestionsCount.Address", 1); EXPECT_EQ(1U, [suggestion_controller() suggestions].count); FormSuggestion* suggestion = [suggestion_controller() suggestions][0]; EXPECT_NSEQ(@"IL", suggestion.value); @@ -621,7 +621,7 @@ ResetWaitForSuggestionRetrieval(); web::test::ExecuteJavaScript(@"document.forms[0].name.focus()", web_state()); WaitForSuggestionRetrieval(/*wait_for_trigger=*/YES); - ExpectMetric("Autofill.AddressSuggestionsCount", 2); + ExpectMetric("Autofill.SuggestionsCount.Address", 2); EXPECT_EQ(2U, [suggestion_controller() suggestions].count); }
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/create_tab_group_view_controller.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/create_tab_group_view_controller.mm index d1bc7d3..f213df30 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/create_tab_group_view_controller.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/create_tab_group_view_controller.mm
@@ -51,6 +51,7 @@ const CGFloat kSnapshotViewVerticalMargin = 25; const CGFloat kSingleSnapshotRatio = 0.7; const CGFloat kMultipleSnapshotsRatio = 0.90; +const CGFloat kSnapshotViewAnimationTime = 0.3; // Group title constants const CGFloat kTitleHorizontalMargin = 16; @@ -530,14 +531,16 @@ BOOL tooSmall = _snapshotsContainer.frame.size.height < 60; BOOL isVerticallyCompacted = self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassCompact; - BOOL isIpadConfiguration = - (ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_TABLET) && - _keyboardDisplayed; - if (tooSmall || isVerticallyCompacted || isIpadConfiguration) { - [_snapshotsContainer setHidden:YES]; - } else { - [_snapshotsContainer setHidden:NO]; + CGFloat updatedAlpha = (tooSmall || isVerticallyCompacted) ? 0 : 1; + if (_snapshotsContainer.alpha == updatedAlpha) { + return; } + + __weak UIView* weakSnapshotsContainer = _snapshotsContainer; + [UIView animateWithDuration:kSnapshotViewAnimationTime + animations:^{ + [weakSnapshotsContainer setAlpha:updatedAlpha]; + }]; } // Called when the virtual keyboard is shown.
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/tab_group_coordinator.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/tab_group_coordinator.mm index fc5311d..3693e0d 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/tab_group_coordinator.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/tab_group_coordinator.mm
@@ -165,6 +165,9 @@ [viewController animateGridPresentation]; } completion:nil]; + + UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, + nil); } - (void)hideViewControllerAnimated:(BOOL)animated { @@ -174,6 +177,8 @@ [viewController willMoveToParentViewController:nil]; [viewController.view removeFromSuperview]; [viewController removeFromParentViewController]; + UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, + nil); }; if (!animated) {
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/tab_group_view_controller.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/tab_group_view_controller.mm index dae6a2c..76ca6ef 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/tab_group_view_controller.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/tab_groups/tab_group_view_controller.mm
@@ -161,6 +161,7 @@ - (void)viewDidLoad { [super viewDidLoad]; self.view.accessibilityIdentifier = kTabGroupViewIdentifier; + self.view.accessibilityViewIsModal = YES; self.view.backgroundColor = UIColor.clearColor; if (!UIAccessibilityIsReduceTransparencyEnabled()) { _blurView = [[UIVisualEffectView alloc] initWithEffect:nil];
diff --git a/services/webnn/coreml/graph_builder.cc b/services/webnn/coreml/graph_builder.cc index 25ccdcb..19454ba 100644 --- a/services/webnn/coreml/graph_builder.cc +++ b/services/webnn/coreml/graph_builder.cc
@@ -1864,7 +1864,13 @@ GetOperandInfo(operation.input_operand_id); if (!kFloatDataTypes.contains(input_operand_info.mil_data_type)) { - return NewNotSupportedError("Unsupported input datatype."); + switch (operation.kind) { + case mojom::Pool2d::Kind::kAveragePool2d: + case mojom::Pool2d::Kind::kL2Pool2d: + NOTREACHED_NORETURN() << "Invalid input datatype."; + case mojom::Pool2d::Kind::kMaxPool2d: + return NewNotSupportedError("Unsupported input datatype."); + } } if (operation.layout != mojom::InputOperandLayout::kChannelsFirst) {
diff --git a/services/webnn/dml/graph_impl.cc b/services/webnn/dml/graph_impl.cc index f42c744..a95418e 100644 --- a/services/webnn/dml/graph_impl.cc +++ b/services/webnn/dml/graph_impl.cc
@@ -1872,9 +1872,9 @@ std::array<const NodeOutput*, 1> inputs = {input}; const OperatorNode* pool2d_node = nullptr; switch (pool2d->kind) { - // TODO(crbug.com/40206287): Add L2Pool2d operator. - case mojom::Pool2d::Kind::kAveragePool2d: { + CHECK(kDmlFloatDataTypes.contains(input_tensor_desc.GetDataType())); + // TODO(crbug.com/40206287): Work around dilation support for L2 and // average pooling. According to WebNN spec: // https://www.w3.org/TR/webnn/#api-mlgraphbuilder-pool2d, dilations are @@ -1906,6 +1906,8 @@ break; } case mojom::Pool2d::Kind::kL2Pool2d: { + CHECK(kDmlFloatDataTypes.contains(input_tensor_desc.GetDataType())); + DML_LP_POOLING_OPERATOR_DESC l2_pooling_desc = { .InputTensor = &input_tensor_desc.GetDMLTensorDesc(), .OutputTensor = &output_tensor_desc.GetDMLTensorDesc(), @@ -2443,38 +2445,43 @@ } // DirectML API does not have a real Reshape operator. The WebNN Reshape is -// implemented by creating a new NodeOutput for the input Node. The new -// NodeOutput has the reshaped dimensions and is used as the output of the WebNN -// Reshape operator. And if the input and output of the Reshape are exactly the -// input and output of the DirectML graph, we need to add another DirectML -// Identity operator to ensure that the DirectML graph can be compiled and -// calculated correctly. -void CreateNodeOutputForReshape(const IdToOperandMap& id_to_operand_map, - const mojom::ReshapePtr& reshape, - GraphBuilder& graph_builder, - IdToNodeOutputMap& id_to_node_output_map) { +// implemented by a DirectML Identity operator. DirectML runtime is able to +// optimize the unnecessary IDENTITY operators when compiling the graph. +base::expected<void, mojom::ErrorPtr> CreateOperatorNodeForReshape( + const IdToOperandMap& id_to_operand_map, + const mojom::ReshapePtr& reshape, + GraphBuilder& graph_builder, + IdToNodeOutputMap& id_to_node_output_map) { const NodeOutput* input = GetNodeOutputForOperand(id_to_node_output_map, reshape->input_operand_id); - - // Ensure the output tensor description having the - // `DML_TENSOR_FLAG_OWNED_BY_DML` flag if its corresponding node is a constant - // graph input. - uint64_t output_id = reshape->output_operand_id; - const OperandPtr& output_operand = id_to_operand_map.at(output_id); const auto& input_tensor_desc = input->GetTensorDesc(); - auto output_tensor_desc = - TensorDesc(input_tensor_desc.GetDataType(), input_tensor_desc.GetFlags(), - output_operand->dimensions); + // Ensure the the output tensor description of identity node having + // `DML_TENSOR_FLAG_NONE` flag. + auto input_tensor_desc_without_flags = TensorDesc( + input_tensor_desc.GetDataType(), input_tensor_desc.GetDimensions()); - const Node& input_node = input->GetNode(); + // Insert an identity node. + const OperatorNode* identity_node = + CreateUnaryOperator<DML_ELEMENT_WISE_IDENTITY_OPERATOR_DESC, + DML_OPERATOR_ELEMENT_WISE_IDENTITY>( + input_tensor_desc, input_tensor_desc_without_flags, input, + graph_builder); + if (!identity_node) { + return base::unexpected(CreateError(mojom::Error::Code::kUnknownError, + "Failed to create identity operator.")); + } - // The output_index of this NodeOutput should be the same as the input - // NodeOutput for creating correct intermediate edges of the graph. + uint64_t output_id = reshape->output_operand_id; + const auto output_tensor_desc = + CreateOutputTensorDesc(id_to_operand_map, output_id); + const NodeOutput* output = graph_builder.CreateNodeOutput( - &input_node, std::move(output_tensor_desc), input->GetOutputIndex()); + identity_node, std::move(output_tensor_desc)); // The output id must be unique in the map. CHECK(id_to_node_output_map.try_emplace(output_id, output).second); + + return base::ok(); } base::expected<void, mojom::ErrorPtr> CreateOperatorNodeForElu( @@ -5296,8 +5303,9 @@ break; } case Operation::Tag::kReshape: { - CreateNodeOutputForReshape(id_to_operand_map, operation->get_reshape(), - graph_builder, id_to_node_output_map); + create_operator_result = CreateOperatorNodeForReshape( + id_to_operand_map, operation->get_reshape(), graph_builder, + id_to_node_output_map); break; } case Operation::Tag::kSigmoid: {
diff --git a/services/webnn/tflite/graph_builder.cc b/services/webnn/tflite/graph_builder.cc index a95980c2..e1d30f5 100644 --- a/services/webnn/tflite/graph_builder.cc +++ b/services/webnn/tflite/graph_builder.cc
@@ -1109,8 +1109,7 @@ // Check for unsupported inputs. const mojom::Operand& output_operand = GetOperand(gemm.output_operand_id); CHECK_EQ(output_operand.dimensions.size(), 2u); - CHECK(output_operand.data_type == mojom::Operand::DataType::kFloat32 || - output_operand.data_type == mojom::Operand::DataType::kFloat16); + CHECK(kFloatDataTypes.contains(output_operand.data_type)); const uint32_t output_channels = output_operand.dimensions[1]; if (gemm.c_operand_id.has_value()) { // The TFLite fully connected operator only supports a 1-D bias tensor with @@ -1268,8 +1267,7 @@ -> OperatorOffset { const mojom::Operand::DataType a_operand_data_type = GetOperand(matmul.a_operand_id).data_type; - CHECK(a_operand_data_type == mojom::Operand::DataType::kFloat32 || - a_operand_data_type == mojom::Operand::DataType::kFloat16); + CHECK(kFloatDataTypes.contains(a_operand_data_type)); const auto matmul_options = ::tflite::CreateBatchMatMulOptions(builder_, /*adj_x=*/false, @@ -1410,12 +1408,14 @@ ::tflite::BuiltinOperator operator_code; switch (pool2d.kind) { case mojom::Pool2d::Kind::kAveragePool2d: + CHECK(kFloatDataTypes.contains(input_operand.data_type)); operator_code = ::tflite::BuiltinOperator_AVERAGE_POOL_2D; break; case mojom::Pool2d::Kind::kMaxPool2d: operator_code = ::tflite::BuiltinOperator_MAX_POOL_2D; break; case mojom::Pool2d::Kind::kL2Pool2d: + CHECK(kFloatDataTypes.contains(input_operand.data_type)); return base::unexpected("L2Pool2d is not supported in tflite."); } @@ -1523,8 +1523,7 @@ auto GraphBuilder::SerializeRelu(const mojom::Relu& relu) -> OperatorOffset { const mojom::Operand::DataType input_data_type = GetOperand(relu.input_operand_id).data_type; - CHECK(input_data_type == mojom::Operand::DataType::kFloat32 || - input_data_type == mojom::Operand::DataType::kFloat16 || + CHECK(kFloatDataTypes.contains(input_data_type) || input_data_type == mojom::Operand::DataType::kInt32 || input_data_type == mojom::Operand::DataType::kInt8);
diff --git a/services/webnn/webnn_graph_impl.cc b/services/webnn/webnn_graph_impl.cc index 614765f..a09f49e 100644 --- a/services/webnn/webnn_graph_impl.cc +++ b/services/webnn/webnn_graph_impl.cc
@@ -1595,6 +1595,14 @@ return false; } + if (pool2d->kind == mojom::Pool2d::Kind::kAveragePool2d || + pool2d->kind == mojom::Pool2d::Kind::kL2Pool2d) { + if (!(input->data_type == mojom::Operand::DataType::kFloat32 || + input->data_type == mojom::Operand::DataType::kFloat16)) { + return false; + } + } + if (output->dimensions.size() != 4) { // The element of output dimensions should be 4. return false;
diff --git a/services/webnn/webnn_graph_impl_backend_test.cc b/services/webnn/webnn_graph_impl_backend_test.cc index 5fe2f7e..f929b25 100644 --- a/services/webnn/webnn_graph_impl_backend_test.cc +++ b/services/webnn/webnn_graph_impl_backend_test.cc
@@ -350,7 +350,6 @@ "BuildAndComputeConcatWithConstants", "BuildAndComputeSingleOperatorElementWiseBinary", "BuildAndComputeSingleOperatorElementWiseUnary", - "BuildSingleOperatorInstanceNormalization", "BuildAndComputeSingleOperatorLeakyRelu", "BuildAndComputeSingleOperatorRelu", "BuildAndComputeSingleOperatorSigmoid",
diff --git a/services/webnn/webnn_graph_impl_unittest.cc b/services/webnn/webnn_graph_impl_unittest.cc index 9db63bbe..7d121305 100644 --- a/services/webnn/webnn_graph_impl_unittest.cc +++ b/services/webnn/webnn_graph_impl_unittest.cc
@@ -5161,34 +5161,34 @@ } { // Test pool2d with window dimensions. - Pool2dTester{.input = {.type = mojom::Operand::DataType::kInt8, + Pool2dTester{.input = {.type = mojom::Operand::DataType::kFloat32, .dimensions = {1, 3, 5, 5}}, .attributes = {.window_dimensions = {2, 2}, .strides = {2, 2}}, - .output = {.type = mojom::Operand::DataType::kInt8, + .output = {.type = mojom::Operand::DataType::kFloat32, .dimensions = {1, 3, 3, 3}}, .expected = true} .Test(); } { // Test pool2d with strides=2, padding=1 and floor rounding. - Pool2dTester{.input = {.type = mojom::Operand::DataType::kInt8, + Pool2dTester{.input = {.type = mojom::Operand::DataType::kFloat16, .dimensions = {1, 3, 7, 7}}, .attributes = {.window_dimensions = {4, 4}, .padding = {1, 1, 1, 1}, .strides = {2, 2}}, - .output = {.type = mojom::Operand::DataType::kInt8, + .output = {.type = mojom::Operand::DataType::kFloat16, .dimensions = {1, 3, 3, 3}}, .expected = true} .Test(); } { // Test pool2d with strides=2, padding=1 and ceil rounding. - Pool2dTester{.input = {.type = mojom::Operand::DataType::kInt8, + Pool2dTester{.input = {.type = mojom::Operand::DataType::kFloat32, .dimensions = {1, 3, 7, 7}}, .attributes = {.window_dimensions = {4, 4}, .padding = {1, 1, 1, 1}, .strides = {2, 2}}, - .output = {.type = mojom::Operand::DataType::kInt8, + .output = {.type = mojom::Operand::DataType::kFloat32, .dimensions = {1, 3, 4, 4}}, .expected = true} .Test(); @@ -5196,12 +5196,12 @@ { // Test pool2d with layout="nhwc". Pool2dTester{ - .input = {.type = mojom::Operand::DataType::kInt8, + .input = {.type = mojom::Operand::DataType::kFloat16, .dimensions = {1, 5, 5, 2}}, .attributes = {.window_dimensions = {3, 3}, .strides = {1, 1}, .layout = mojom::InputOperandLayout::kChannelsLast}, - .output = {.type = mojom::Operand::DataType::kInt8, + .output = {.type = mojom::Operand::DataType::kFloat16, .dimensions = {1, 3, 3, 2}}, .expected = true} .Test(); @@ -5265,11 +5265,33 @@ Pool2dTester{.input = {.type = mojom::Operand::DataType::kFloat32, .dimensions = {1, 3, 4, 4}}, .attributes = {.window_dimensions = {4, 4}, .strides = {1, 1}}, - .output = {.type = mojom::Operand::DataType::kInt32, + .output = {.type = mojom::Operand::DataType::kFloat16, .dimensions = {1, 3, 1, 1}}, .expected = false} .Test(); } + { + // Test the invalid graph if the input data type is not floating point for + // averagePool2d. + Pool2dTester{.input = {.type = mojom::Operand::DataType::kInt32, + .dimensions = {1, 3, 4, 4}}, + .attributes = {.window_dimensions = {4, 4}, .strides = {1, 1}}, + .output = {.type = mojom::Operand::DataType::kInt32, + .dimensions = {1, 3, 1, 1}}, + .expected = false} + .Test(mojom::Pool2d::Kind::kAveragePool2d); + } + { + // Test the invalid graph if the input data type is not floating point for + // l2Pool2d. + Pool2dTester{.input = {.type = mojom::Operand::DataType::kInt8, + .dimensions = {1, 3, 4, 4}}, + .attributes = {.window_dimensions = {4, 4}, .strides = {1, 1}}, + .output = {.type = mojom::Operand::DataType::kInt8, + .dimensions = {1, 3, 1, 1}}, + .expected = false} + .Test(mojom::Pool2d::Kind::kL2Pool2d); + } } struct PreluTester {
diff --git a/skia/BUILD.gn b/skia/BUILD.gn index 47db8e25..bbff45c6 100644 --- a/skia/BUILD.gn +++ b/skia/BUILD.gn
@@ -360,6 +360,7 @@ "//third_party/skia/src/codec/SkIcoCodec.cpp", "//third_party/skia/src/codec/SkJpegCodec.cpp", "//third_party/skia/src/codec/SkJpegDecoderMgr.cpp", + "//third_party/skia/src/codec/SkJpegMetadataDecoderImpl.cpp", "//third_party/skia/src/codec/SkJpegMultiPicture.cpp", "//third_party/skia/src/codec/SkJpegSegmentScan.cpp", "//third_party/skia/src/codec/SkJpegSourceMgr.cpp",
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 1a3539b5..8d07cdde 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -1398,6 +1398,9 @@ "experiments": [ { "name": "Enabled", + "params": { + "cache_size": "1000" + }, "enable_features": [ "AutofillEnableCacheForRegexMatching" ] @@ -1690,6 +1693,27 @@ ] } ], + "AutofillFixCachingOnJavaScriptChanges": [ + { + "platforms": [ + "android", + "android_webview", + "chromeos", + "chromeos_lacros", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "AutofillFixCachingOnJavaScriptChanges" + ] + } + ] + } + ], "AutofillGranularFillingAndManualFallbackForUnclassifiedFieldsAvailable": [ { "platforms": [ @@ -2002,6 +2026,27 @@ ] } ], + "AutofillUnifyAndFixFormTracking": [ + { + "platforms": [ + "android", + "android_webview", + "chromeos", + "chromeos_lacros", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "AutofillUnifyAndFixFormTracking" + ] + } + ] + } + ], "AutofillUploadVotesForFieldsWithEmail": [ { "platforms": [ @@ -2046,7 +2091,7 @@ ] } ], - "AutofillUseI18nAddressModel": [ + "AutofillUseI18nAddressModelV2": [ { "platforms": [ "android", @@ -9199,6 +9244,25 @@ ] } ], + "HistoryEmbeddings": [ + { + "platforms": [ + "chromeos", + "chromeos_lacros", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "HistoryEmbeddings" + ] + } + ] + } + ], "HlsBuiltinPlayer": [ { "platforms": [ @@ -13028,10 +13092,10 @@ ] }, { - "name": "EnabledWithAllowAlwaysFirst", + "name": "EnabledWithAllowOnEveryVisitAsFirstButton", "params": { "show_allow_always_as_first_button": "true", - "use_stronger_prompt_language": "false" + "use_stronger_prompt_language": "true" }, "enable_features": [ "ActiveContentSettingExpiry", @@ -13039,7 +13103,7 @@ ] }, { - "name": "EnabledWithAllowWhileVisitingFirst", + "name": "EnabledWithAllowWhileVisitingAsFirstButton", "params": { "show_allow_always_as_first_button": "true", "use_stronger_prompt_language": "true", @@ -13049,6 +13113,18 @@ "ActiveContentSettingExpiry", "OneTimePermission" ] + }, + { + "name": "EnabledWithAllowWhileVisitingAsSecondButton", + "params": { + "show_allow_always_as_first_button": "false", + "use_stronger_prompt_language": "true", + "use_while_visiting_language": "true" + }, + "enable_features": [ + "ActiveContentSettingExpiry", + "OneTimePermission" + ] } ] } @@ -13062,13 +13138,13 @@ { "name": "EnabledWithNormalLanguage", "params": { - "experimental_custom_invitation_arm_trigger_id": "tZMcjst2x0tK1KeaPYj0VbPmvceJ,bpnHbhSrK0tK1KeaPYj0RBC9zv7H,ZDjpUDFx20tK1KeaPYj0WbM2hHXy", + "experimental_custom_invitation_arm_trigger_id": "eaHr88umj0tK1KeaPYj0YkhJEi1Y,8U6CRfLYU0tK1KeaPYj0RbTHRpNZ,qrWTeaJaK0tK1KeaPYj0XjFWabba", "probability": "1", "probability_vector": "0.5,1.0,1.0", "prompt_disposition_reason_filter": "DefaultFallback", "request_type_filter": "Geolocation,VideoCapture,AudioCapture", "survey_display_time": "OnPromptResolved", - "trigger_id": "xTNFzsgeH0tK1KeaPYj0VueEfPNg,rMwYPzTTj0tK1KeaPYj0XB5xXsRF,5XkVTH91f0tK1KeaPYj0SJhtw5pX", + "trigger_id": "hCatPbt6B0tK1KeaPYj0WXqMjcvX,89BwvKxbJ0tK1KeaPYj0NtK7Ybn8,3fTPt7XMF0tK1KeaPYj0TXd8QN47", "use_stronger_prompt_language": "false" }, "enable_features": [ @@ -13123,31 +13199,41 @@ ] }, { - "name": "EnabledWithAllowAlwaysFirst", + "name": "EnabledWithAllowOnEveryVisitAsFirstButton", "params": { + "experimental_custom_invitation_arm_trigger_id": "nDDiJNFrQ0tK1KeaPYj0R9NRSBEm,NBn5wUuPR0tK1KeaPYj0XpG6yifA,LvQ3ywBFy0tK1KeaPYj0X474g3gp", + "probability": "1", + "probability_vector": "0.5,1.0,1.0", + "prompt_disposition_reason_filter": "DefaultFallback", + "request_type_filter": "Geolocation,VideoCapture,AudioCapture", "show_allow_always_as_first_button": "true", - "use_stronger_prompt_language": "false" + "survey_display_time": "OnPromptResolved", + "trigger_id": "987xHCa770tK1KeaPYj0UE9kej8g,iTZrdKPCv0tK1KeaPYj0YTA7ooTP,Z5Gbxz1BA0tK1KeaPYj0ToLe1txW", + "use_stronger_prompt_language": "true" }, "enable_features": [ "ActiveContentSettingExpiry", - "OneTimePermission" - ], - "disable_features": [ + "OneTimePermission", "PermissionsPromptSurvey" ] }, { - "name": "EnabledWithAllowWhileVisitingFirst", + "name": "EnabledWithAllowWhileVisitingAsFirstButton", "params": { + "experimental_custom_invitation_arm_trigger_id": "7maHuvQzn0tK1KeaPYj0Q9rdJDda,KzHiqHzxP0tK1KeaPYj0XSzYX5y2,DXfHq8LEH0tK1KeaPYj0PMxrXHu1", + "probability": "1", + "probability_vector": "0.5,1.0,1.0", + "prompt_disposition_reason_filter": "DefaultFallback", + "request_type_filter": "Geolocation,VideoCapture,AudioCapture", "show_allow_always_as_first_button": "true", + "survey_display_time": "OnPromptResolved", + "trigger_id": "bCKnj4pzu0tK1KeaPYj0UG86EvNX,anf8vbQh20tK1KeaPYj0QSBJzzY9,p9ppMFjWE0tK1KeaPYj0RB2a6d8D", "use_stronger_prompt_language": "true", "use_while_visiting_language": "true" }, "enable_features": [ "ActiveContentSettingExpiry", - "OneTimePermission" - ], - "disable_features": [ + "OneTimePermission", "PermissionsPromptSurvey" ] }
diff --git a/third_party/angle b/third_party/angle index 5c78d08..da1fbbc 160000 --- a/third_party/angle +++ b/third_party/angle
@@ -1 +1 @@ -Subproject commit 5c78d084206f095337c663ac7747e02fdc5b72d9 +Subproject commit da1fbbc6497d299d488beba33fc56d068ab01c45
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index abd5538..fe6c57708 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -1039,6 +1039,11 @@ "FledgeAlwaysReuseSellerContext", base::FEATURE_DISABLED_BY_DEFAULT); +const base::FeatureParam<int> kFledgeRealTimeReportingNumBuckets{ + &kFledgeRealTimeReporting, "FledgeRealTimeReportingNumBuckets", 1024}; +const base::FeatureParam<double> kFledgeRealTimeReportingEpsilon{ + &kFledgeRealTimeReporting, "FledgeRealTimeReportingEpsilon", 1}; + BASE_FEATURE(kForceDeferScriptIntervention, "ForceDeferScriptIntervention", base::FEATURE_DISABLED_BY_DEFAULT);
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index ab41591..e162437 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -569,6 +569,15 @@ // Reuse a single V8 context to score all ads in a seller worklet. BLINK_COMMON_EXPORT BASE_DECLARE_FEATURE(kFledgeAlwaysReuseSellerContext); +// Feature params for feature kFledgeRealTimeReporting. +// Epsilon of Rappor noise algorithm. +BLINK_COMMON_EXPORT extern const base::FeatureParam<double> + kFledgeRealTimeReportingEpsilon; +// Total number of buckets supported for real time reporting. Supported buckets +// will be [0, kFledgeRealTimeReportingNumBuckets). +BLINK_COMMON_EXPORT extern const base::FeatureParam<int> + kFledgeRealTimeReportingNumBuckets; + BLINK_COMMON_EXPORT BASE_DECLARE_FEATURE(kForceWebContentsDarkMode); BLINK_COMMON_EXPORT extern const base::FeatureParam<ForceDarkInversionMethod> kForceDarkInversionMethodParam;
diff --git a/third_party/blink/renderer/bindings/core/v8/binding_security.cc b/third_party/blink/renderer/bindings/core/v8/binding_security.cc index ff64f66..43562b4 100644 --- a/third_party/blink/renderer/bindings/core/v8/binding_security.cc +++ b/third_party/blink/renderer/bindings/core/v8/binding_security.cc
@@ -294,9 +294,10 @@ if (LIKELY(accessing_context == target_context)) return true; + v8::Isolate* isolate = accessing_context->GetIsolate(); return ShouldAllowAccessToV8ContextInternal( - ScriptState::From(accessing_context), ScriptState::From(target_context), - exception_state); + ScriptState::From(isolate, accessing_context), + ScriptState::From(isolate, target_context), exception_state); } void BindingSecurity::FailedAccessCheckFor(v8::Isolate* isolate,
diff --git a/third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc b/third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc index aa499e15..fe359ec2 100644 --- a/third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc +++ b/third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc
@@ -230,7 +230,7 @@ const String& value, const String& enum_type_name, ExceptionState& exception_state) { - ScriptState* script_state = ScriptState::From(isolate->GetCurrentContext()); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); ExecutionContext* execution_context = ExecutionContext::From(script_state); exception_state.ThrowTypeError("The provided value '" + value + @@ -320,7 +320,7 @@ } v8::Local<v8::Context> context = script_state->GetContext(); - V8PerContextData* per_context_data = V8PerContextData::From(context); + V8PerContextData* per_context_data = script_state->PerContextData(); v8::Local<v8::Function> function; if (!function_template->GetFunction(context).ToLocal(&function)) { return v8::MaybeLocal<v8::Value>();
diff --git a/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc b/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc index ced1d9e..c1866c1 100644 --- a/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc +++ b/third_party/blink/renderer/bindings/core/v8/js_event_handler_for_content_attribute.cc
@@ -76,7 +76,7 @@ return v8::Null(GetIsolate()); ScriptState* script_state_of_event_target = - ScriptState::From(v8_context_of_event_target); + ScriptState::From(GetIsolate(), v8_context_of_event_target); if (!script_state_of_event_target->ContextIsValid()) return v8::Null(GetIsolate());
diff --git a/third_party/blink/renderer/bindings/core/v8/module_record.cc b/third_party/blink/renderer/bindings/core/v8/module_record.cc index 8375ffbc..7562aad 100644 --- a/third_party/blink/renderer/bindings/core/v8/module_record.cc +++ b/third_party/blink/renderer/bindings/core/v8/module_record.cc
@@ -198,7 +198,7 @@ v8::Local<v8::FixedArray> import_attributes, v8::Local<v8::Module> referrer) { v8::Isolate* isolate = context->GetIsolate(); - Modulator* modulator = Modulator::From(ScriptState::From(context)); + Modulator* modulator = Modulator::From(ScriptState::From(isolate, context)); DCHECK(modulator); ModuleRequest module_request(
diff --git a/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h b/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h index 4c70cec..626fbb0 100644 --- a/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h +++ b/third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h
@@ -938,7 +938,7 @@ v8::Local<v8::Value> value, ExceptionState& exception_state) { return ScriptPromiseUntyped::FromUntypedValueForBindings( - ScriptState::From(isolate->GetCurrentContext()), value); + ScriptState::ForCurrentRealm(isolate), value); } };
diff --git a/third_party/blink/renderer/bindings/core/v8/observable_array_exotic_object_handler.h b/third_party/blink/renderer/bindings/core/v8/observable_array_exotic_object_handler.h index 14b7a52..c5c3c89b 100644 --- a/third_party/blink/renderer/bindings/core/v8/observable_array_exotic_object_handler.h +++ b/third_party/blink/renderer/bindings/core/v8/observable_array_exotic_object_handler.h
@@ -158,7 +158,7 @@ V8SetReturnValue(info, false); return; } - ScriptState* script_state = ScriptState::From(current_context); + ScriptState* script_state = ScriptState::From(isolate, current_context); ExceptionState exception_state( isolate, ExceptionContextType::kOperationInvoke, BackingListWrappable::ObservableArrayNameInIDL(), "deleteProperty"); @@ -207,7 +207,7 @@ V8SetReturnValue(info, v8::Undefined(isolate)); return; } - ScriptState* script_state = ScriptState::From(current_context); + ScriptState* script_state = ScriptState::From(isolate, current_context); v8::Local<v8::Value> v8_element = ToV8Traits<ElementIdlType>::ToV8(script_state, backing_list[index]); V8SetReturnValue(info, v8_element); @@ -252,7 +252,7 @@ V8SetReturnValue(info, v8::Undefined(isolate)); return; } - ScriptState* script_state = ScriptState::From(current_context); + ScriptState* script_state = ScriptState::From(isolate, current_context); v8::Local<v8::Value> v8_element = ToV8Traits<ElementIdlType>::ToV8(script_state, backing_list[index]); v8::PropertyDescriptor prop_desc(v8_element, true); @@ -343,7 +343,7 @@ keys_vector.push_back(String::Number(index)); v8::Local<v8::Value> own_keys_as_value = ToV8Traits<IDLSequence<IDLString>>::ToV8( - ScriptState::From(current_context), keys_vector); + ScriptState::From(isolate, current_context), keys_vector); v8::Local<v8::Array> own_keys = own_keys_as_value.As<v8::Array>(); // 6. Extend keys with ! O.[[OwnPropertyKeys]](). @@ -510,7 +510,7 @@ if (backing_list.size() == 0) return true; - ScriptState* script_state = ScriptState::From(current_context); + ScriptState* script_state = ScriptState::From(isolate, current_context); uint32_t index_to_delete = backing_list.size() - 1; while (length <= index_to_delete) { if (!RunDeleteAlgorithm(script_state, backing_list, index_to_delete, @@ -546,7 +546,7 @@ if (exception_state.HadException()) return false; - ScriptState* script_state = ScriptState::From(current_context); + ScriptState* script_state = ScriptState::From(isolate, current_context); if (index < backing_list.size()) { if (!RunDeleteAlgorithm(script_state, backing_list, index, exception_state)) {
diff --git a/third_party/blink/renderer/bindings/core/v8/script_function.cc b/third_party/blink/renderer/bindings/core/v8/script_function.cc index ac39200..647aad0e 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_function.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_function.cc
@@ -51,10 +51,10 @@ RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(args.GetIsolate(), "Blink_CallCallback"); v8::Local<v8::Object> data = v8::Local<v8::Object>::Cast(args.Data()); - auto* holder = static_cast<CallableHolder*>( - ToScriptWrappable(args.GetIsolate(), data)); - ScriptState* script_state = - ScriptState::From(args.GetIsolate()->GetCurrentContext()); + v8::Isolate* isolate = args.GetIsolate(); + auto* holder = + static_cast<CallableHolder*>(ToScriptWrappable(isolate, data)); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); holder->callable_->CallRaw(script_state, args); }
diff --git a/third_party/blink/renderer/bindings/core/v8/script_iterator.cc b/third_party/blink/renderer/bindings/core/v8/script_iterator.cc index b1d68a8..604634c 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_iterator.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_iterator.cc
@@ -85,8 +85,8 @@ v8::Local<v8::Value> value) { DCHECK(!IsNull()); - v8::Local<v8::Value> next_method = - next_method_.Get(ScriptState::From(isolate_->GetCurrentContext())); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate_); + v8::Local<v8::Value> next_method = next_method_.Get(script_state); if (!next_method->IsFunction()) { exception_state.ThrowTypeError("Expected next() function on iterator."); done_ = true; @@ -95,10 +95,10 @@ v8::TryCatch try_catch(isolate_); v8::Local<v8::Value> result; - if (!V8ScriptRunner::CallFunction( - next_method.As<v8::Function>(), execution_context, - iterator_.Get(ScriptState::From(isolate_->GetCurrentContext())), - value.IsEmpty() ? 0 : 1, &value, isolate_) + if (!V8ScriptRunner::CallFunction(next_method.As<v8::Function>(), + execution_context, + iterator_.Get(script_state), + value.IsEmpty() ? 0 : 1, &value, isolate_) .ToLocal(&result)) { exception_state.RethrowV8Exception(try_catch.Exception()); done_ = true; @@ -112,7 +112,7 @@ } v8::Local<v8::Object> result_object = result.As<v8::Object>(); - v8::Local<v8::Context> context = isolate_->GetCurrentContext(); + v8::Local<v8::Context> context = script_state->GetContext(); v8::MaybeLocal<v8::Value> maybe_value = result_object->Get(context, value_key_); value_ = WorldSafeV8Reference(isolate_,
diff --git a/third_party/blink/renderer/bindings/core/v8/script_iterator.h b/third_party/blink/renderer/bindings/core/v8/script_iterator.h index 9d569aef..d10cc2c7 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_iterator.h +++ b/third_party/blink/renderer/bindings/core/v8/script_iterator.h
@@ -81,7 +81,7 @@ v8::Local<v8::Value> value = v8::Local<v8::Value>()); v8::MaybeLocal<v8::Value> GetValue() { - return value_.Get(ScriptState::From(isolate_->GetCurrentContext())); + return value_.Get(ScriptState::ForCurrentRealm(isolate_)); } void Trace(Visitor* visitor) const {
diff --git a/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc b/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc index 0dc9278..8a5d46297 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_promise_property_test.cc
@@ -126,7 +126,7 @@ } DOMWrapperWorld& OtherWorld() { return *other_world_; } ScriptState* CurrentScriptState() { - return ScriptState::Current(GetIsolate()); + return ScriptState::ForCurrentRealm(GetIsolate()); } void PerformMicrotaskCheckpoint() { @@ -162,12 +162,13 @@ ScriptValue Wrap(DOMWrapperWorld& world, GarbageCollectedScriptWrappable* value) { - v8::HandleScope handle_scope(GetIsolate()); + v8::Isolate* isolate = GetIsolate(); + v8::HandleScope handle_scope(isolate); ScriptState* script_state = - ScriptState::From(ToV8Context(DomWindow(), world)); + ScriptState::From(isolate, ToV8Context(DomWindow(), world)); ScriptState::Scope scope(script_state); return ScriptValue( - GetIsolate(), + isolate, ToV8Traits<GarbageCollectedScriptWrappable>::ToV8(script_state, value)); }
diff --git a/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h b/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h index 7a23c5a..680f0de 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h +++ b/third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h
@@ -213,7 +213,7 @@ void OverrideScriptStateToCurrentContext() { v8::Isolate* isolate = script_state_->GetIsolate(); CHECK(isolate->InContext()); - script_state_ = ScriptState::From(isolate->GetCurrentContext()); + script_state_ = ScriptState::ForCurrentRealm(isolate); } void NotifyResolveOrReject();
diff --git a/third_party/blink/renderer/bindings/core/v8/script_value.cc b/third_party/blink/renderer/bindings/core/v8/script_value.cc index 8c0b9eb..eadaf711 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_value.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_value.cc
@@ -41,7 +41,7 @@ return v8::Local<v8::Value>(); DCHECK(GetIsolate()->InContext()); - return value_.Get(ScriptState::From(isolate_->GetCurrentContext())); + return value_.Get(ScriptState::ForCurrentRealm(isolate_)); } v8::Local<v8::Value> ScriptValue::V8ValueFor(
diff --git a/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_factory.cc b/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_factory.cc index 15fa270..3ca53d1 100644 --- a/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_factory.cc +++ b/third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value_factory.cc
@@ -28,7 +28,8 @@ const SerializedScriptValue::SerializeOptions& options, ExceptionState& exception_state) { TRACE_EVENT0("blink", "SerializedScriptValueFactory::create"); - V8ScriptValueSerializer serializer(ScriptState::Current(isolate), options); + V8ScriptValueSerializer serializer(ScriptState::ForCurrentRealm(isolate), + options); return serializer.Serialize(value, exception_state); } @@ -37,7 +38,7 @@ v8::Isolate* isolate, const SerializedScriptValue::DeserializeOptions& options) { TRACE_EVENT0("blink", "SerializedScriptValueFactory::deserialize"); - V8ScriptValueDeserializer deserializer(ScriptState::Current(isolate), + V8ScriptValueDeserializer deserializer(ScriptState::ForCurrentRealm(isolate), std::move(value), options); return deserializer.Deserialize(); } @@ -47,8 +48,8 @@ v8::Isolate* isolate, const SerializedScriptValue::DeserializeOptions& options) { TRACE_EVENT0("blink", "SerializedScriptValueFactory::deserialize"); - V8ScriptValueDeserializer deserializer(ScriptState::Current(isolate), value, - options); + V8ScriptValueDeserializer deserializer(ScriptState::ForCurrentRealm(isolate), + value, options); return deserializer.Deserialize(); }
diff --git a/third_party/blink/renderer/bindings/core/v8/to_v8_traits.h b/third_party/blink/renderer/bindings/core/v8/to_v8_traits.h index 248a1d2..b20b89de 100644 --- a/third_party/blink/renderer/bindings/core/v8/to_v8_traits.h +++ b/third_party/blink/renderer/bindings/core/v8/to_v8_traits.h
@@ -281,7 +281,7 @@ CHECK(!creation_context_object.IsEmpty()); ScriptState* script_state = - ScriptState::From(creation_context_object->GetCreationContextChecked()); + ScriptState::ForRelevantRealm(isolate, creation_context_object); return script_wrappable->Wrap(script_state); }
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc b/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc index c4cd8e089..ba15bef 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.cc
@@ -669,7 +669,8 @@ ExecutionContext* ToExecutionContext(v8::Local<v8::Context> context) { DCHECK(!context.IsEmpty()); - ScriptState* script_state = ScriptState::MaybeFrom(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::MaybeFrom(isolate, context); return script_state ? ToExecutionContext(script_state) : nullptr; } @@ -694,7 +695,8 @@ v8::Local<v8::Context> context = ToV8ContextEvenIfDetached(frame, world); if (context.IsEmpty()) return nullptr; - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); if (!script_state->ContextIsValid()) return nullptr; DCHECK_EQ(frame, ToLocalFrameIfNotDetached(context)); @@ -725,6 +727,8 @@ return script_state->GetContext(); } +// TODO(ishell): return ScriptState* in order to avoid unnecessary hops +// script_state -> context -> script_state on caller side. v8::Local<v8::Context> ToV8ContextEvenIfDetached(LocalFrame* frame, DOMWrapperWorld& world) { // TODO(yukishiino): this method probably should not force context creation,
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc b/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc index 0a731352..49a6173 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_html_constructor.cc
@@ -31,7 +31,7 @@ DCHECK(info.IsConstructCall()); v8::Isolate* isolate = info.GetIsolate(); - ScriptState* script_state = ScriptState::Current(isolate); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); v8::Local<v8::Value> new_target = info.NewTarget(); if (!script_state->ContextIsValid()) { @@ -118,8 +118,10 @@ // 7. If Type(prototype) is not Object, then: ... if (!prototype->IsObject()) { - if (V8PerContextData* per_context_data = V8PerContextData::From( - new_target.As<v8::Object>()->GetCreationContextChecked())) { + ScriptState* new_target_script_state = + ScriptState::ForRelevantRealm(isolate, new_target.As<v8::Object>()); + if (V8PerContextData* per_context_data = + new_target_script_state->PerContextData()) { prototype = per_context_data->PrototypeForType(&wrapper_type_info); } else { V8ThrowException::ThrowError(isolate, "The context has been destroyed");
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc b/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc index 5b4e929..3727d03 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc
@@ -163,7 +163,7 @@ return; // If called during context initialization, there will be no entered context. - ScriptState* script_state = ScriptState::Current(isolate); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); if (!script_state->ContextIsValid()) return; @@ -206,11 +206,8 @@ void V8Initializer::MessageHandlerInWorker(v8::Local<v8::Message> message, v8::Local<v8::Value> data) { v8::Isolate* isolate = message->GetIsolate(); - v8::Local<v8::Context> v8_context = isolate->GetCurrentContext(); - CHECK(!v8_context.IsEmpty()); // During the frame teardown, there may not be a valid context. - auto* script_state = ScriptState::From(v8_context); - CHECK(script_state); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); if (!script_state->ContextIsValid()) return; @@ -323,7 +320,7 @@ return; // Bail out if called during context initialization. - ScriptState* script_state = ScriptState::Current(isolate); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); if (!script_state->ContextIsValid()) return; @@ -337,7 +334,7 @@ // Bail out if called during context initialization. v8::Isolate* isolate = promise->GetIsolate(); - ScriptState* script_state = ScriptState::Current(isolate); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); if (!script_state->ContextIsValid()) return; @@ -507,7 +504,7 @@ v8::Local<v8::Promise::Resolver> resolver, v8::Local<v8::Value> compilation_result, v8::WasmAsyncSuccess success) { - ScriptState* script_state = ScriptState::MaybeFrom(context); + ScriptState* script_state = ScriptState::MaybeFrom(isolate, context); if (!script_state || !IsInParallelAlgorithmRunnable(ExecutionContext::From(script_state), script_state)) { @@ -633,7 +630,8 @@ v8::Local<v8::Value> v8_referrer_resource_url, v8::Local<v8::String> v8_specifier, v8::Local<v8::FixedArray> v8_import_attributes) { - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); Modulator* modulator = Modulator::From(script_state); if (!modulator) { @@ -707,8 +705,8 @@ void HostGetImportMetaProperties(v8::Local<v8::Context> context, v8::Local<v8::Module> module, v8::Local<v8::Object> meta) { - ScriptState* script_state = ScriptState::From(context); v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); v8::HandleScope handle_scope(isolate); Modulator* modulator = Modulator::From(script_state);
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_page_popup_controller_binding.cc b/third_party/blink/renderer/bindings/core/v8/v8_page_popup_controller_binding.cc index c39da5d..55c1fdb 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_page_popup_controller_binding.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_page_popup_controller_binding.cc
@@ -27,10 +27,9 @@ V8SetReturnValue(info, v8::Null(info.GetIsolate())); return; } - V8SetReturnValue( - info, ToV8Traits<PagePopupController>::ToV8( - ScriptState::From(info.GetIsolate()->GetCurrentContext()), - PagePopupController::From(*frame->GetPage()))); + V8SetReturnValue(info, ToV8Traits<PagePopupController>::ToV8( + ScriptState::ForCurrentRealm(info.GetIsolate()), + PagePopupController::From(*frame->GetPage()))); } void PagePopupControllerAttributeGetterCallback(
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.cc b/third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.cc index 28a3a19..eacd955b 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.cc
@@ -83,8 +83,8 @@ // We use the isolate's current context here because we are creating an // exception object. v8::Local<v8::Object> exception_obj = - ToV8Traits<DOMException>::ToV8(ScriptState::From(current_context), - dom_exception) + ToV8Traits<DOMException>::ToV8( + ScriptState::From(isolate, current_context), dom_exception) .As<v8::Object>(); // Attach an Error object to the DOMException. This is then lazily used to get
diff --git a/third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.cc b/third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.cc index 355e740..c8b49ba 100644 --- a/third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.cc +++ b/third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.cc
@@ -46,7 +46,8 @@ if (!value.As<v8::Object>()->GetCreationContext().ToLocal(&context)) return; - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); CHECK_EQ(&world, &script_state->World()); }
diff --git a/third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.h b/third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.h index ee0e726..81fba5d 100644 --- a/third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.h +++ b/third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.h
@@ -70,8 +70,8 @@ WorldSafeV8ReferenceInternal::MaybeCheckCreationContextWorld( *world_.Get(), value); } else if (value->IsObject()) { - ScriptState* script_state = ScriptState::From( - value.template As<v8::Object>()->GetCreationContextChecked()); + ScriptState* script_state = ScriptState::ForRelevantRealm( + isolate, value.template As<v8::Object>()); world_ = &script_state->World(); } }
diff --git a/third_party/blink/renderer/bindings/modules/v8/serialization/serialized_script_value_for_modules_factory.cc b/third_party/blink/renderer/bindings/modules/v8/serialization/serialized_script_value_for_modules_factory.cc index 2c63d161..6a304895 100644 --- a/third_party/blink/renderer/bindings/modules/v8/serialization/serialized_script_value_for_modules_factory.cc +++ b/third_party/blink/renderer/bindings/modules/v8/serialization/serialized_script_value_for_modules_factory.cc
@@ -27,8 +27,8 @@ const SerializedScriptValue::SerializeOptions& options, ExceptionState& exception_state) { TRACE_EVENT0("blink", "SerializedScriptValueFactory::create"); - V8ScriptValueSerializerForModules serializer(ScriptState::Current(isolate), - options); + V8ScriptValueSerializerForModules serializer( + ScriptState::ForCurrentRealm(isolate), options); return serializer.Serialize(value, exception_state); } @@ -38,7 +38,7 @@ const SerializedScriptValue::DeserializeOptions& options) { TRACE_EVENT0("blink", "SerializedScriptValueFactory::deserialize"); V8ScriptValueDeserializerForModules deserializer( - ScriptState::Current(isolate), std::move(value), options); + ScriptState::ForCurrentRealm(isolate), std::move(value), options); return deserializer.Deserialize(); } @@ -48,7 +48,7 @@ const SerializedScriptValue::DeserializeOptions& options) { TRACE_EVENT0("blink", "SerializedScriptValueFactory::deserialize"); V8ScriptValueDeserializerForModules deserializer( - ScriptState::Current(isolate), value, options); + ScriptState::ForCurrentRealm(isolate), value, options); return deserializer.Deserialize(); }
diff --git a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc index baf49df..6c497b5d 100644 --- a/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc +++ b/third_party/blink/renderer/bindings/modules/v8/v8_binding_for_modules.cc
@@ -330,8 +330,8 @@ continue; } if (element == "lastModifiedDate") { - v8_value = file->lastModifiedDate(ScriptState::From(context)).V8Value(); - ScriptState* script_state = ScriptState::From(context); + ScriptState* script_state = ScriptState::From(isolate, context); + v8_value = file->lastModifiedDate(script_state).V8Value(); ExecutionContext* execution_context = ToExecutionContext(script_state); UseCounter::Count(execution_context, WebFeature::kIndexedDBFileLastModifiedDate);
diff --git a/third_party/blink/renderer/bindings/scripts/bind_gen/interface.py b/third_party/blink/renderer/bindings/scripts/bind_gen/interface.py index 0b746d6..1cad82ed 100644 --- a/third_party/blink/renderer/bindings/scripts/bind_gen/interface.py +++ b/third_party/blink/renderer/bindings/scripts/bind_gen/interface.py
@@ -319,8 +319,9 @@ "\"${class_like.identifier}\";")), S("current_context", ("v8::Local<v8::Context> ${current_context} = " "${isolate}->GetCurrentContext();")), - S("current_script_state", ("ScriptState* ${current_script_state} = " - "ScriptState::From(${current_context});")), + S("current_script_state", + ("ScriptState* ${current_script_state} = " + "ScriptState::From(${isolate}, ${current_context});")), S("isolate", "v8::Isolate* ${isolate} = ${info}.GetIsolate();"), S("non_undefined_argument_length", ("const int ${non_undefined_argument_length} = " @@ -486,7 +487,7 @@ # + ScriptState::GetContext # is faster than # v8::Object::GetCreationContextChecked - # + ScriptState::From(v8::Local<v8::Context>) + # + ScriptState::From(v8::Isolate*, v8::Local<v8::Context>) # Depending on already-defined symbols, select the best way to get # ${receiver_script_state}. node.append( @@ -494,11 +495,12 @@ SymbolSensitiveSelectionNode.Choice( ["receiver_context"], T("ScriptState* ${receiver_script_state} = " - "ScriptState::From(${receiver_context});")), + "ScriptState::From(${isolate}, ${receiver_context});")), SymbolSensitiveSelectionNode.Choice( [], T("ScriptState* ${receiver_script_state} = " - "ScriptState::ForRelevantRealm(${v8_receiver});")), + "ScriptState::ForRelevantRealm(${isolate}, " + "${v8_receiver});")), ])) return node @@ -4402,8 +4404,8 @@ ("const bool ${is_in_secure_context} = " "${execution_context}->IsSecureContext();")), S("isolate", "v8::Isolate* ${isolate} = ${v8_context}->GetIsolate();"), - S("script_state", - "ScriptState* ${script_state} = ScriptState::From(${v8_context});"), + S("script_state", ("ScriptState* ${script_state} = " + "ScriptState::From(${isolate}, ${v8_context});")), S("wrapper_type_info", ("const WrapperTypeInfo* const ${wrapper_type_info} = " "${class_name}::GetWrapperTypeInfo();")),
diff --git a/third_party/blink/renderer/controller/javascript_call_stack_collector.cc b/third_party/blink/renderer/controller/javascript_call_stack_collector.cc index bab4ce68..b1d611e 100644 --- a/third_party/blink/renderer/controller/javascript_call_stack_collector.cc +++ b/third_party/blink/renderer/controller/javascript_call_stack_collector.cc
@@ -73,7 +73,7 @@ } v8::Local<v8::Context> context = isolate->GetCurrentContext(); - ScriptState* script_state = ScriptState::MaybeFrom(context); + ScriptState* script_state = ScriptState::MaybeFrom(isolate, context); if (!script_state) { PostHandleCollectedCallStackTask(collector, builder); return;
diff --git a/third_party/blink/renderer/controller/performance_manager/v8_detailed_memory_reporter_impl.cc b/third_party/blink/renderer/controller/performance_manager/v8_detailed_memory_reporter_impl.cc index 12d416f..266dfb6d 100644 --- a/third_party/blink/renderer/controller/performance_manager/v8_detailed_memory_reporter_impl.cc +++ b/third_party/blink/renderer/controller/performance_manager/v8_detailed_memory_reporter_impl.cc
@@ -70,7 +70,8 @@ isolate_memory_usage->detached_bytes_used += size; continue; } - if (DOMWrapperWorld::World(context).GetWorldId() != + v8::Isolate* isolate = context->GetIsolate(); + if (DOMWrapperWorld::World(isolate, context).GetWorldId() != DOMWrapperWorld::kMainWorldId) { // TODO(crbug.com/1085129): Handle extension contexts once they get // their own V8ContextToken.
diff --git a/third_party/blink/renderer/core/css/parser/css_property_parser.cc b/third_party/blink/renderer/core/css/parser/css_property_parser.cc index 7f065dc0..87e0fa09 100644 --- a/third_party/blink/renderer/core/css/parser/css_property_parser.cc +++ b/third_party/blink/renderer/core/css/parser/css_property_parser.cc
@@ -162,7 +162,8 @@ // variable ref parser below. if (To<Shorthand>(property).ParseShorthand(important, value_.range, *context_, local_context, - *parsed_properties_)) { + *parsed_properties_) && + value_.range.AtEnd()) { return true; } } else {
diff --git a/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc b/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc index fe839e0..37a69e6 100644 --- a/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc +++ b/third_party/blink/renderer/core/css/properties/css_parsing_utils.cc
@@ -1776,6 +1776,8 @@ // <ratio> = <number [0,+inf]> [ / <number [0,+inf]> ]? CSSValue* ConsumeRatio(CSSParserTokenRange& range, const CSSParserContext& context) { + CSSParserSavePoint savepoint(range); + CSSPrimitiveValue* first = ConsumeNumber( range, context, CSSPrimitiveValue::ValueRange::kNonNegative); if (!first) { @@ -1795,6 +1797,7 @@ 1, CSSPrimitiveValue::UnitType::kInteger); } + savepoint.Release(); return MakeGarbageCollected<cssvalue::CSSRatioValue>(*first, *second); } @@ -4299,7 +4302,7 @@ AddProperty(longhands[1]->PropertyID(), shorthand.id(), *end, important, IsImplicitProperty::kNotImplicit, properties); - return range.AtEnd(); + return true; } bool ConsumeShorthandVia4Longhands( @@ -4350,7 +4353,7 @@ AddProperty(longhands[3]->PropertyID(), shorthand.id(), *left, important, IsImplicitProperty::kNotImplicit, properties); - return range.AtEnd(); + return true; } bool ConsumeShorthandGreedilyViaLonghands( @@ -4365,9 +4368,11 @@ const CSSValue* longhands[6] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; const CSSProperty** shorthand_properties = shorthand.properties(); + bool found_any = false; + bool found_longhand; do { - bool found_longhand = false; - for (size_t i = 0; !found_longhand && i < shorthand.length(); ++i) { + found_longhand = false; + for (size_t i = 0; i < shorthand.length(); ++i) { if (longhands[i]) { continue; } @@ -4376,12 +4381,15 @@ if (longhands[i]) { found_longhand = true; + found_any = true; + break; } } - if (!found_longhand) { - return false; - } - } while (!range.AtEnd()); + } while (found_longhand && !range.AtEnd()); + + if (!found_any) { + return false; + } for (size_t i = 0; i < shorthand.length(); ++i) { if (longhands[i]) { @@ -4582,10 +4590,12 @@ CSSValueID::kInvalid); } + CSSParserSavePoint savepoint(range); CSSValueID overflow = IsOverflowKeyword(id) ? range.ConsumeIncludingWhitespace().Id() : CSSValueID::kInvalid; if (is_position_keyword(range.Peek().Id())) { + savepoint.Release(); return MakeGarbageCollected<cssvalue::CSSContentDistributionValue>( CSSValueID::kInvalid, range.ConsumeIncludingWhitespace().Id(), overflow); @@ -4847,6 +4857,7 @@ do { bool parsed_longhand[kMaxNumAnimationLonghands] = {false}; + bool found_any = false; do { bool found_property = false; for (unsigned i = 0; i < longhand_count; ++i) { @@ -4860,15 +4871,20 @@ if (value) { parsed_longhand[i] = true; found_property = true; + found_any = true; longhands[i]->Append(*value); break; } } if (!found_property) { - return false; + break; } } while (!range.AtEnd() && range.Peek().GetType() != kCommaToken); + if (!found_any) { + return false; + } + for (unsigned i = 0; i < longhand_count; ++i) { const Longhand& longhand = *To<Longhand>(shorthand.properties()[i]); if (!parsed_longhand[i]) { @@ -5264,11 +5280,14 @@ CHECK_LE(longhand_count, 10u); bool implicit = false; + bool previous_layer_had_background_color = false; do { bool parsed_longhand[10] = {false}; CSSValue* origin_value = nullptr; + bool found_property; + bool found_any = false; do { - bool found_property = false; + found_property = false; bool bg_position_parsed_in_current_layer = false; for (unsigned i = 0; i < longhand_count; ++i) { if (parsed_longhand[i]) { @@ -5317,6 +5336,7 @@ } parsed_longhand[i] = true; found_property = true; + found_any = true; longhands[i].push_back(value); if (value_y) { parsed_longhand[i + 1] = true; @@ -5324,23 +5344,28 @@ } } } - if (!found_property) { - return false; - } - } while (!range.AtEnd() && range.Peek().GetType() != kCommaToken); + } while (found_property && !range.AtEnd() && + range.Peek().GetType() != kCommaToken); + + if (!found_any) { + return false; + } + if (previous_layer_had_background_color) { + // Colors are only allowed in the last layer; previous layer had + // a background color and we now know for sure it was not the last one, + // so return parse failure. + return false; + } // TODO(timloh): This will make invalid longhands, see crbug.com/386459 for (unsigned i = 0; i < longhand_count; ++i) { const CSSProperty& property = *shorthand.properties()[i]; - if (property.IDEquals(CSSPropertyID::kBackgroundColor) && - !range.AtEnd()) { + if (property.IDEquals(CSSPropertyID::kBackgroundColor)) { if (parsed_longhand[i]) { - return false; // Colors are only allowed in the last layer. + previous_layer_had_background_color = true; } - continue; } - if (!parsed_longhand[i]) { if ((property.IDEquals(CSSPropertyID::kBackgroundClip) || property.IDEquals(CSSPropertyID::kMaskClip)) && @@ -5357,16 +5382,21 @@ } } } while (ConsumeCommaIncludingWhitespace(range)); - if (!range.AtEnd()) { - return false; - } for (unsigned i = 0; i < longhand_count; ++i) { const CSSProperty& property = *shorthand.properties()[i]; - // To conserve memory we don't wrap a single value in a list. - const CSSValue* longhand = GetSingleValueOrMakeList( - CSSValue::kCommaSeparator, std::move(longhands[i])); + const CSSValue* longhand; + if (property.IDEquals(CSSPropertyID::kBackgroundColor)) { + // There can only be one background-color (we've verified this earlier, + // by means of previous_layer_had_background_color), so pick out only + // the last one (any others will just be “initial” over and over again). + longhand = longhands[i].back().Get(); + } else { + // To conserve memory we don't wrap a single value in a list. + longhand = GetSingleValueOrMakeList(CSSValue::kCommaSeparator, + std::move(longhands[i])); + } AddProperty(property.PropertyID(), shorthand.id(), *longhand, important, implicit ? IsImplicitProperty::kImplicit @@ -5448,6 +5478,7 @@ } } if (!slice) { + CSSParserSavePoint savepoint(range); slice = ConsumeBorderImageSlice(range, context, default_fill); if (slice) { DCHECK(!width); @@ -5457,19 +5488,23 @@ if (ConsumeSlashIncludingWhitespace(range)) { outset = ConsumeBorderImageOutset(range, context); if (!outset) { - return false; + break; } } else if (!width) { - return false; + break; } } } else { - return false; + break; } + savepoint.Release(); } else { - return false; + break; } } while (!range.AtEnd()); + if (!source && !repeat && !slice) { + return false; + } return true; } @@ -7079,7 +7114,7 @@ : CSSIdentifierValue::Create(CSSValueID::kAuto); } - return range.AtEnd(); + return true; } bool ConsumeGridTemplateShorthand(bool important, @@ -7094,41 +7129,51 @@ DCHECK_EQ(gridTemplateShorthand().length(), 3u); - CSSParserTokenRange range_copy = range; - template_rows = ConsumeIdent<CSSValueID::kNone>(range); + { + // 1- <grid-template-rows> / <grid-template-columns> + CSSParserSavePoint savepoint(range); + template_rows = ConsumeIdent<CSSValueID::kNone>(range); + if (!template_rows) { + template_rows = ConsumeGridTemplatesRowsOrColumns(range, context); + } - // 1- 'none' case. - if (template_rows && range.AtEnd()) { + if (template_rows && ConsumeSlashIncludingWhitespace(range)) { + template_columns = ConsumeGridTemplatesRowsOrColumns(range, context); + if (template_columns) { + template_areas = CSSIdentifierValue::Create(CSSValueID::kNone); + savepoint.Release(); + return true; + } + } + + template_rows = nullptr; + template_columns = nullptr; + template_areas = nullptr; + } + + { + // 2- [ <line-names>? <string> <track-size>? <line-names>? ]+ + // [ / <track-list> ]? + CSSParserSavePoint savepoint(range); + if (ConsumeGridTemplateRowsAndAreasAndColumns( + important, range, context, template_rows, template_columns, + template_areas)) { + savepoint.Release(); + return true; + } + } + + // 3- 'none' alone case. This must come after the others, since “none“ + // could also be the start of case 1. + template_rows = ConsumeIdent<CSSValueID::kNone>(range); + if (template_rows) { template_rows = CSSIdentifierValue::Create(CSSValueID::kNone); template_columns = CSSIdentifierValue::Create(CSSValueID::kNone); template_areas = CSSIdentifierValue::Create(CSSValueID::kNone); return true; } - // 2- <grid-template-rows> / <grid-template-columns> - if (!template_rows) { - template_rows = ConsumeGridTemplatesRowsOrColumns(range, context); - } - - if (template_rows) { - if (!ConsumeSlashIncludingWhitespace(range)) { - return false; - } - template_columns = ConsumeGridTemplatesRowsOrColumns(range, context); - if (!template_columns || !range.AtEnd()) { - return false; - } - - template_areas = CSSIdentifierValue::Create(CSSValueID::kNone); - return true; - } - - // 3- [ <line-names>? <string> <track-size>? <line-names>? ]+ - // [ / <track-list> ]? - range = range_copy; - return ConsumeGridTemplateRowsAndAreasAndColumns( - important, range, context, template_rows, template_columns, - template_areas); + return false; } CSSValue* ConsumeHyphenateLimitChars(CSSParserTokenRange& range, @@ -7145,7 +7190,7 @@ list->Append(*ident); continue; } - return nullptr; + break; } if (list->length()) { return list; @@ -7549,19 +7594,30 @@ const CSSParserContext& context, bool use_legacy_parsing) { unsigned horizontal_value_count = 0; - for (; horizontal_value_count < 4 && !stream.AtEnd() && - stream.Peek().GetType() != kDelimiterToken; + for (; + horizontal_value_count < 4 && stream.Peek().GetType() != kDelimiterToken; ++horizontal_value_count) { horizontal_radii[horizontal_value_count] = ConsumeLengthOrPercent( stream, context, CSSPrimitiveValue::ValueRange::kNonNegative); if (!horizontal_radii[horizontal_value_count]) { - return false; + break; } } if (!horizontal_radii[0]) { return false; } - if (stream.AtEnd()) { + if (ConsumeSlashIncludingWhitespace(stream)) { + for (unsigned i = 0; i < 4; ++i) { + vertical_radii[i] = ConsumeLengthOrPercent( + stream, context, CSSPrimitiveValue::ValueRange::kNonNegative); + if (!vertical_radii[i]) { + break; + } + } + if (!vertical_radii[0]) { + return false; + } + } else { // Legacy syntax: -webkit-border-radius: l1 l2; is equivalent to // border-radius: l1 / l2; if (use_legacy_parsing && horizontal_value_count == 2) { @@ -7574,20 +7630,6 @@ } return true; } - } else { - if (!ConsumeSlashIncludingWhitespace(stream)) { - return false; - } - for (unsigned i = 0; i < 4 && !stream.AtEnd(); ++i) { - vertical_radii[i] = ConsumeLengthOrPercent( - stream, context, CSSPrimitiveValue::ValueRange::kNonNegative); - if (!vertical_radii[i]) { - return false; - } - } - if (!vertical_radii[0] || !stream.AtEnd()) { - return false; - } } Complete4Sides(horizontal_radii); Complete4Sides(vertical_radii); @@ -7718,7 +7760,7 @@ // Consume the `text-box-edge` production. CSSValue* ConsumeTextBoxEdge(CSSParserTokenRange& range) { if (CSSIdentifierValue* leading = ConsumeIdent<CSSValueID::kLeading>(range)) { - return range.AtEnd() ? leading : nullptr; + return leading; } CSSIdentifierValue* over_type = ConsumeIdent<CSSValueID::kText, CSSValueID::kCap, CSSValueID::kEx>(range); @@ -7732,7 +7774,7 @@ } if (CSSIdentifierValue* under_type = ConsumeIdent<CSSValueID::kText, CSSValueID::kAlphabetic>(range); - under_type && range.AtEnd()) { + under_type) { // Align with the CSS specification: "If only one value is specified, // both edges are assigned that same keyword if possible; else 'text' is // assumed as the missing value.".
diff --git a/third_party/blink/renderer/core/css/properties/longhand.h b/third_party/blink/renderer/core/css/properties/longhand.h index dd996be..8d97f6b7 100644 --- a/third_party/blink/renderer/core/css/properties/longhand.h +++ b/third_party/blink/renderer/core/css/properties/longhand.h
@@ -24,6 +24,14 @@ public: // Parses and consumes a longhand property value from the token range. // Returns nullptr if the input is invalid. + // + // NOTE: This function must accept arbitrary tokens after the value, + // without returning error. In particular, it must not check for + // end-of-stream, since it may be called as part of parsing a shorthand, or + // there may be “!important” after the value that the caller is responsible + // for consuming. (Currently, !important is stripped away before this function + // is called, but this will change in the future.) End-of-stream is checked + // by the caller. virtual const CSSValue* ParseSingleValueFromRange( CSSParserTokenRange&, const CSSParserContext&,
diff --git a/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc b/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc index 0dd6807..6d2bfc9 100644 --- a/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc +++ b/third_party/blink/renderer/core/css/properties/longhands/longhands_custom.cc
@@ -590,28 +590,18 @@ CSSParserTokenRange& range, const CSSParserContext& context, const CSSParserLocalContext&) const { - // Syntax: auto | auto 1/2 | 1/2 auto + // Syntax: auto | auto 1/2 | 1/2 auto | 1/2 CSSValue* auto_value = nullptr; if (range.Peek().Id() == CSSValueID::kAuto) { auto_value = css_parsing_utils::ConsumeIdent(range); } - if (range.AtEnd()) { - return auto_value; - } - CSSValue* ratio = css_parsing_utils::ConsumeRatio(range, context); if (!ratio) { - return nullptr; + return auto_value; // Either auto alone, or failure. } - if (!range.AtEnd()) { - if (auto_value) { - return nullptr; - } - if (range.Peek().Id() != CSSValueID::kAuto) { - return nullptr; - } + if (!auto_value && range.Peek().Id() == CSSValueID::kAuto) { auto_value = css_parsing_utils::ConsumeIdent(range); } @@ -1796,6 +1786,7 @@ return nullptr; } + CSSParserSavePoint savepoint(range); CSSParserTokenRange args = css_parsing_utils::ConsumeFunction(range); // rect(t, r, b, l) || rect(t r b l) CSSValue* top = ConsumeClipComponent(args, context); @@ -1815,8 +1806,11 @@ } CSSValue* left = ConsumeClipComponent(args, context); if (!left || !args.AtEnd()) { + // NOTE: This AtEnd() is fine, because we test args, not range. + // But we need the savepoint to rewind in that case. return nullptr; } + savepoint.Release(); return MakeGarbageCollected<CSSQuadValue>(top, right, bottom, left, CSSQuadValue::kSerializeAsRect); } @@ -2063,7 +2057,7 @@ value = css_parsing_utils::ConsumeCustomIdent(range, context); } if (!value) { - return nullptr; + break; } values->Append(*value); } while (!range.AtEnd()); @@ -2488,6 +2482,8 @@ AtomicString attr_name = args.ConsumeIncludingWhitespace().Value().ToAtomicString(); if (!args.AtEnd()) { + // NOTE: This AtEnd() is fine, because we don't take in the entire + // stream here, just the contents of a function. return nullptr; } @@ -2539,6 +2535,8 @@ } if (!list_style || !args.AtEnd()) { + // NOTE: This AtEnd() is fine, because we don't take in the entire + // stream here, just the contents of a function. return nullptr; } return MakeGarbageCollected<cssvalue::CSSCounterValue>(identifier, list_style, @@ -2852,16 +2850,14 @@ } CSSValueID id = range.Peek().Id(); - if (!range.AtEnd()) { - if (id == CSSValueID::kWebkitZoomIn) { - context.Count(WebFeature::kPrefixedCursorZoomIn); - } else if (id == CSSValueID::kWebkitZoomOut) { - context.Count(WebFeature::kPrefixedCursorZoomOut); - } else if (id == CSSValueID::kWebkitGrab) { - context.Count(WebFeature::kPrefixedCursorGrab); - } else if (id == CSSValueID::kWebkitGrabbing) { - context.Count(WebFeature::kPrefixedCursorGrabbing); - } + if (id == CSSValueID::kWebkitZoomIn) { + context.Count(WebFeature::kPrefixedCursorZoomIn); + } else if (id == CSSValueID::kWebkitZoomOut) { + context.Count(WebFeature::kPrefixedCursorZoomOut); + } else if (id == CSSValueID::kWebkitGrab) { + context.Count(WebFeature::kPrefixedCursorGrab); + } else if (id == CSSValueID::kWebkitGrabbing) { + context.Count(WebFeature::kPrefixedCursorGrabbing); } CSSIdentifierValue* cursor_type = nullptr; if (id == CSSValueID::kHand) { @@ -3121,13 +3117,10 @@ CSSValueList* values = CSSValueList::CreateSpaceSeparated(); values->Append(*first_value); values->Append(*css_parsing_utils::ConsumeIdent(range)); - if (!range.AtEnd()) { - if (range.Peek().Id() == CSSValueID::kInvalid) { - return nullptr; - } + if (range.Peek().Id() != CSSValueID::kInvalid) { values->Append(*css_parsing_utils::ConsumeIdent(range)); } - // `values` has two or three CSSIdentifierValue pointers. + // `values` now has two or three CSSIdentifierValue pointers. auto result = ValidateDisplayKeywords(*values); if (!result) { @@ -3168,20 +3161,19 @@ CSSValueID id = range.Peek().Id(); if (id != CSSValueID::kInvalid) { const CSSIdentifierValue* value = css_parsing_utils::ConsumeIdent(range); - if (!range.AtEnd()) { - if (range.Peek().Id() == CSSValueID::kInvalid) { - return nullptr; - } + if (range.Peek().Id() != CSSValueID::kInvalid) { return ParseDisplayMultipleKeywords(range, value); } - // The property has only one keyword. + // The property has only one keyword (or one keyword and then junk, + // in which case the caller will abort for us). if (id == CSSValueID::kListItem || IsDisplayBox(id) || IsDisplayInternal(id) || IsDisplayLegacy(id) || IsDisplayInside(id) || IsDisplayOutside(id)) { return value; + } else { + return nullptr; } - return nullptr; } if (!RuntimeEnabledFeatures::CSSLayoutAPIEnabled()) { @@ -3198,18 +3190,20 @@ return nullptr; } - CSSParserTokenRange range_copy = range; - CSSParserTokenRange args = css_parsing_utils::ConsumeFunction(range_copy); + CSSParserSavePoint savepoint(range); + CSSParserTokenRange args = css_parsing_utils::ConsumeFunction(range); CSSCustomIdentValue* name = css_parsing_utils::ConsumeCustomIdent(args, context); // If we didn't get a custom-ident or didn't exhaust the function arguments // return nothing. + // NOTE: This AtEnd() is fine, because we test args, not range. + // But we need the savepoint to rewind in that case. if (!name || !args.AtEnd()) { return nullptr; } - range = range_copy; + savepoint.Release(); return MakeGarbageCollected<cssvalue::CSSLayoutFunctionValue>( name, /* is_inline */ function == CSSValueID::kInlineLayout); } @@ -3826,14 +3820,21 @@ return css_parsing_utils::ConsumeIdent(range); } + bool found_any = false; + FontVariantEastAsianParser east_asian_parser; do { if (east_asian_parser.ConsumeEastAsian(range) != FontVariantEastAsianParser::ParseResult::kConsumedValue) { - return nullptr; + break; } + found_any = true; } while (!range.AtEnd()); + if (!found_any) { + return nullptr; + } + return east_asian_parser.FinalizeValue(); } @@ -3854,14 +3855,21 @@ return css_parsing_utils::ConsumeIdent(range); } + bool found_any = false; + FontVariantLigaturesParser ligatures_parser; do { if (ligatures_parser.ConsumeLigature(range) != FontVariantLigaturesParser::ParseResult::kConsumedValue) { - return nullptr; + break; } + found_any = true; } while (!range.AtEnd()); + if (!found_any) { + return nullptr; + } + return ligatures_parser.FinalizeValue(); } @@ -3881,14 +3889,21 @@ return css_parsing_utils::ConsumeIdent(range); } + bool found_any = false; + FontVariantNumericParser numeric_parser; do { if (numeric_parser.ConsumeNumeric(range) != FontVariantNumericParser::ParseResult::kConsumedValue) { - return nullptr; + break; } + found_any = true; } while (!range.AtEnd()); + if (!found_any) { + return nullptr; + } + return numeric_parser.FinalizeValue(); } @@ -3908,14 +3923,21 @@ return css_parsing_utils::ConsumeIdent(range); } + bool found_any = false; + FontVariantAlternatesParser alternates_parser; do { if (alternates_parser.ConsumeAlternates(range, context) != FontVariantAlternatesParser::ParseResult::kConsumedValue) { - return nullptr; + break; } + found_any = true; } while (!range.AtEnd()); + if (!found_any) { + return nullptr; + } + return alternates_parser.FinalizeValue(); } @@ -5444,11 +5466,7 @@ const CSSParserContext& context, const CSSParserLocalContext&) const { if (range.Peek().Id() == CSSValueID::kNone) { - const CSSIdentifierValue* value = css_parsing_utils::ConsumeIdent(range); - if (!range.AtEnd()) { - return nullptr; - } - return value; + return css_parsing_utils::ConsumeIdent(range); } else { return css_parsing_utils::ConsumePositiveInteger(range, context); } @@ -6833,11 +6851,15 @@ } else if (id == CSSValueID::kMarkers && !markers) { markers = css_parsing_utils::ConsumeIdent(range); } else { - return nullptr; + break; } paint_type_list.push_back(id); } while (!range.AtEnd()); + if (paint_type_list.empty()) { + return nullptr; + } + // After parsing we serialize the paint-order list. Since it is not possible // to pop a last list items from CSSValueList without bigger cost, we create // the list after parsing. @@ -7088,7 +7110,13 @@ while (!range.AtEnd()) { CSSStringValue* parsed_value = css_parsing_utils::ConsumeString(range); if (!parsed_value) { - return nullptr; + // NOTE: Technically, if we consumed an odd number of strings, + // we should have returned success here but un-consumed + // the last string (since we should allow any arbitrary junk). + // However, in practice, the only thing we need to care about + // is !important, since we're not part of a shorthand, + // so we let it slip. + break; } values->Append(*parsed_value); } @@ -7438,7 +7466,10 @@ if (id == CSSValueID::kBothEdges && !both_edges) { both_edges = css_parsing_utils::ConsumeIdent(range); } else { - return nullptr; + // Something that didn't parse, or end-of-stream, or duplicate both-edges. + // End-of-stream is success; the caller will clean up for us in the + // failure case (since we didn't consume the erroneous token). + break; } } if (!stable) { @@ -7697,9 +7728,6 @@ if (!block_value) { return nullptr; } - if (range.AtEnd()) { - return block_value; - } CSSValue* inline_value = css_parsing_utils::ConsumeIdent<CSSValueID::kNone, CSSValueID::kStart, @@ -7741,7 +7769,7 @@ return nullptr; } CSSValue* axis_value = css_parsing_utils::ConsumeIdent(range); - if (range.AtEnd() || axis_id == CSSValueID::kNone) { + if (axis_id == CSSValueID::kNone) { return axis_value; } @@ -8240,6 +8268,7 @@ CSSParserTokenRange& range, const CSSParserContext& context, const CSSParserLocalContext&) const { + // Syntax: comma- or whitespace-separated list of <length-or-percent> CSSValueID id = range.Peek().Id(); if (id == CSSValueID::kNone) { return css_parsing_utils::ConsumeIdent(range); @@ -8247,15 +8276,20 @@ CSSParserContext::ParserModeOverridingScope scope(context, kSVGAttributeMode); CSSValueList* dashes = CSSValueList::CreateCommaSeparated(); - do { + bool need_next_value = true; + for (;;) { CSSPrimitiveValue* dash = css_parsing_utils::ConsumeLengthOrPercent( range, context, CSSPrimitiveValue::ValueRange::kNonNegative); - if (!dash || (css_parsing_utils::ConsumeCommaIncludingWhitespace(range) && - range.AtEnd())) { - return nullptr; + if (!dash) { + if (need_next_value) { + return nullptr; + } else { + break; + } } dashes->Append(*dash); - } while (!range.AtEnd()); + need_next_value = css_parsing_utils::ConsumeCommaIncludingWhitespace(range); + } return dashes; } @@ -8615,19 +8649,9 @@ const CSSParserContext& context, const CSSParserLocalContext&) const { // [ <length> | <percentage> ] - CSSValue* length_percentage = nullptr; - do { - if (!length_percentage) { - length_percentage = css_parsing_utils::ConsumeLengthOrPercent( - range, context, CSSPrimitiveValue::ValueRange::kAll, - css_parsing_utils::UnitlessQuirk::kAllow); - if (length_percentage) { - continue; - } - } - return nullptr; - } while (!range.AtEnd()); - + CSSValue* length_percentage = css_parsing_utils::ConsumeLengthOrPercent( + range, context, CSSPrimitiveValue::ValueRange::kAll, + css_parsing_utils::UnitlessQuirk::kAllow); if (!length_percentage) { return nullptr; } @@ -8933,12 +8957,8 @@ if (!ConsumePan(range, pan_x, pan_y, pinch_zoom)) { return nullptr; } - if (!range.AtEnd() && !ConsumePan(range, pan_x, pan_y, pinch_zoom)) { - return nullptr; - } - if (!range.AtEnd() && !ConsumePan(range, pan_x, pan_y, pinch_zoom)) { - return nullptr; - } + ConsumePan(range, pan_x, pan_y, pinch_zoom); // May fail. + ConsumePan(range, pan_x, pan_y, pinch_zoom); // May fail. if (pan_x) { list->Append(*pan_x); @@ -9652,28 +9672,22 @@ return nullptr; } - CSSPrimitiveValue* offset = nullptr; - if (range.AtEnd()) { + CSSPrimitiveValue* offset = ConsumeLengthOrPercent( + range, context, CSSPrimitiveValue::ValueRange::kAll, + css_parsing_utils::UnitlessQuirk::kForbid); + if (!offset) { + // End of stream or parse error; in the latter case, + // the caller will clean up since we're not at the end. offset = CSSNumericLiteralValue::Create(0, CSSPrimitiveValue::UnitType::kPixels); - } else { - offset = ConsumeLengthOrPercent(range, context, - CSSPrimitiveValue::ValueRange::kAll, - css_parsing_utils::UnitlessQuirk::kForbid); - if (!offset) { - return nullptr; - } + return MakeGarbageCollected<cssvalue::CSSReflectValue>(direction, offset, + /*mask=*/nullptr); } - CSSValue* mask = nullptr; - if (!range.AtEnd()) { - mask = css_parsing_utils::ConsumeWebkitBorderImage(range, context); - if (!mask) { - return nullptr; - } - } + CSSValue* mask_or_null = + css_parsing_utils::ConsumeWebkitBorderImage(range, context); return MakeGarbageCollected<cssvalue::CSSReflectValue>(direction, offset, - mask); + mask_or_null); } } // namespace
diff --git a/third_party/blink/renderer/core/css/properties/shorthand.h b/third_party/blink/renderer/core/css/properties/shorthand.h index c7dc758..f21d5ec5 100644 --- a/third_party/blink/renderer/core/css/properties/shorthand.h +++ b/third_party/blink/renderer/core/css/properties/shorthand.h
@@ -20,7 +20,20 @@ public: // Parses and consumes entire shorthand value from the token range and adds // all constituent parsed longhand properties to the 'properties' set. - // Returns false if the input is invalid. + // Returns false if the input is invalid. (If so, all longhands added to + // 'properties' will be removed again by the caller.) + // + // NOTE: This function must accept arbitrary tokens after the value, + // without returning error. In particular, it must not check for + // end-of-stream, since there may be “!important” after the value that + // the caller is responsible for consuming. (Currently, this is stripped + // away before ParseShorthand() is called, but this will change + // in the future.) End-of-stream is checked by the caller. + // + // (In practice, there are a few of these implementations that are not + // robust against _any_ arbitrary tokens, especially those that may be + // the start of useful values. However, they absolutely need to be + // resistant against “!important”, at the very least.) virtual bool ParseShorthand( bool important, CSSParserTokenRange&,
diff --git a/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc b/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc index 436fed6..3b73772 100644 --- a/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc +++ b/third_party/blink/renderer/core/css/properties/shorthands/shorthands_custom.cc
@@ -15,6 +15,7 @@ #include "third_party/blink/renderer/core/css/parser/css_parser_context.h" #include "third_party/blink/renderer/core/css/parser/css_parser_fast_paths.h" #include "third_party/blink/renderer/core/css/parser/css_parser_local_context.h" +#include "third_party/blink/renderer/core/css/parser/css_parser_save_point.h" #include "third_party/blink/renderer/core/css/parser/font_variant_alternates_parser.h" #include "third_party/blink/renderer/core/css/parser/font_variant_east_asian_parser.h" #include "third_party/blink/renderer/core/css/parser/font_variant_ligatures_parser.h" @@ -118,7 +119,7 @@ important, css_parsing_utils::IsImplicitProperty::kNotImplicit, properties); } - return range.AtEnd(); + return true; } const CSSValue* CSSValueFromComputedAnimation( @@ -192,8 +193,7 @@ const CSSValue* result_y = nullptr; if (!css_parsing_utils::ConsumeBackgroundPosition( range, context, css_parsing_utils::UnitlessQuirk::kAllow, - three_value_position, result_x, result_y) || - !range.AtEnd()) { + three_value_position, result_x, result_y)) { return false; } const CSSProperty** longhands = shorthand.properties(); @@ -333,7 +333,7 @@ *end_list, important, IsImplicitProperty::kNotImplicit, properties); - return range.AtEnd(); + return true; } const CSSValue* AnimationRange::CSSValueFromComputedStyleInternal( @@ -465,7 +465,7 @@ css_parsing_utils::AddExpandedPropertyForValue( CSSPropertyID::kBorderBlockColor, *color, important, properties); - return range.AtEnd(); + return true; } const CSSValue* BorderBlock::CSSValueFromComputedStyleInternal( @@ -610,7 +610,7 @@ *CSSInitialValue::Create(), important, properties); - return range.AtEnd(); + return true; } const CSSValue* Border::CSSValueFromComputedStyleInternal( @@ -731,7 +731,7 @@ css_parsing_utils::AddExpandedPropertyForValue( CSSPropertyID::kBorderInlineColor, *color, important, properties); - return range.AtEnd(); + return true; } const CSSValue* BorderInline::CSSValueFromComputedStyleInternal( @@ -917,14 +917,11 @@ if (!horizontal_spacing) { return false; } - CSSValue* vertical_spacing = horizontal_spacing; - if (!range.AtEnd()) { - vertical_spacing = ConsumeLength( - range, context, CSSPrimitiveValue::ValueRange::kNonNegative, - css_parsing_utils::UnitlessQuirk::kAllow); - } - if (!vertical_spacing || !range.AtEnd()) { - return false; + CSSValue* vertical_spacing = + ConsumeLength(range, context, CSSPrimitiveValue::ValueRange::kNonNegative, + css_parsing_utils::UnitlessQuirk::kAllow); + if (!vertical_spacing) { + vertical_spacing = horizontal_spacing; } css_parsing_utils::AddProperty( CSSPropertyID::kWebkitBorderHorizontalSpacing, @@ -1042,9 +1039,6 @@ } css_parsing_utils::ConsumeColumnWidthOrCount(range, context, column_width, column_count); - if (!range.AtEnd()) { - return false; - } if (!column_width) { column_width = CSSIdentifierValue::Create(CSSValueID::kAuto); } @@ -1117,10 +1111,6 @@ } } - if (!range.AtEnd()) { - return false; - } - css_parsing_utils::AddProperty( CSSPropertyID::kContainerName, CSSPropertyID::kContainer, *name, important, css_parsing_utils::IsImplicitProperty::kNotImplicit, @@ -1159,25 +1149,27 @@ flex_basis = CSSIdentifierValue::Create(CSSValueID::kAuto); range.ConsumeIncludingWhitespace(); } else { - unsigned index = 0; - while (!range.AtEnd() && index++ < 3) { + for (;;) { + CSSParserSavePoint savepoint(range); double num; if (css_parsing_utils::ConsumeNumberRaw(range, context, num)) { if (num < 0) { - return false; + break; } if (flex_grow == kUnsetValue) { flex_grow = num; + savepoint.Release(); } else if (flex_shrink == kUnsetValue) { flex_shrink = num; - } else if (!num) { - // flex only allows a basis of 0 (sans units) if - // flex-grow and flex-shrink values have already been - // set. + savepoint.Release(); + } else if (!num && !flex_basis) { + // Unitless zero is a valid <'flex-basis'>. All other <length>s + // must have some unit, and are handled by the other branch. flex_basis = CSSNumericLiteralValue::Create( 0, CSSPrimitiveValue::UnitType::kPixels); + savepoint.Release(); } else { - return false; + break; } } else if (!flex_basis) { if (css_parsing_utils::IdentMatches< @@ -1190,12 +1182,23 @@ flex_basis = css_parsing_utils::ConsumeLengthOrPercent( range, context, CSSPrimitiveValue::ValueRange::kNonNegative); } - if (index == 2 && !range.AtEnd()) { - return false; + if (flex_basis) { + // <'flex-basis'> may not appear between <'flex-grow'> and + // <'flex-shrink'>. We therefore ensure that grow and shrink are + // either both set, or both unset, once <'flex-basis'> is seen. + if (flex_grow != kUnsetValue && flex_shrink == kUnsetValue) { + flex_shrink = 1; + } + DCHECK_EQ(flex_grow == kUnsetValue, flex_shrink == kUnsetValue); + savepoint.Release(); + } else { + break; } + } else { + break; } } - if (index == 0) { + if (flex_grow == kUnsetValue && flex_shrink == kUnsetValue && !flex_basis) { return false; } if (flex_grow == kUnsetValue) { @@ -1210,9 +1213,6 @@ } } - if (!range.AtEnd()) { - return false; - } css_parsing_utils::AddProperty( CSSPropertyID::kFlexGrow, CSSPropertyID::kFlex, *CSSNumericLiteralValue::Create(ClampTo<float>(flex_grow), @@ -1269,9 +1269,6 @@ HeapVector<CSSPropertyValue, 64>& properties) { CSSValueID system_font_id = range.ConsumeIncludingWhitespace().Id(); DCHECK(CSSParserFastPaths::IsValidSystemFont(system_font_id)); - if (!range.AtEnd()) { - return false; - } css_parsing_utils::AddExpandedPropertyForValue( CSSPropertyID::kFont, @@ -1301,6 +1298,9 @@ (id == CSSValueID::kItalic || id == CSSValueID::kOblique)) { font_style = css_parsing_utils::ConsumeFontStyle(range, context); if (!font_style) { + // NOTE: Strictly speaking, perhaps we should rewind the stream here + // and return true instead, but given that this rule exists solely + // for accepting !important, we can just as well give a parse error. return false; } continue; @@ -1457,7 +1457,7 @@ important, css_parsing_utils::IsImplicitProperty::kNotImplicit, properties); - return range.AtEnd(); + return true; } } // namespace @@ -1520,7 +1520,7 @@ *CSSIdentifierValue::Create(CSSValueID::kNormal), important, css_parsing_utils::IsImplicitProperty::kNotImplicit, properties); } - return range.AtEnd(); + return true; } CSSIdentifierValue* caps_value = nullptr; @@ -1530,6 +1530,7 @@ FontVariantAlternatesParser alternates_parser; CSSIdentifierValue* position_value = nullptr; CSSIdentifierValue* emoji_value = nullptr; + bool first_value = true; do { FontVariantLigaturesParser::ParseResult ligatures_parse_result = ligatures_parser.ConsumeLigature(range); @@ -1562,6 +1563,7 @@ } CSSValueID id = range.Peek().Id(); + bool fail = false; switch (id) { case CSSValueID::kSmallCaps: case CSSValueID::kAllSmallCaps: @@ -1596,8 +1598,19 @@ emoji_value = css_parsing_utils::ConsumeIdent(range); break; default: - return false; + // Random junk at the end is allowed (could be “!important”, + // and if it's not, the caller will reject the value for us). + fail = true; + break; } + if (fail) { + if (first_value) { + // Need at least one good value. + return false; + } + break; + } + first_value = false; } while (!range.AtEnd()); css_parsing_utils::AddProperty( @@ -1668,13 +1681,15 @@ CSSPropertyID::kFontSynthesisSmallCaps, CSSPropertyID::kFontSynthesis, *CSSIdentifierValue::Create(CSSValueID::kNone), important, css_parsing_utils::IsImplicitProperty::kNotImplicit, properties); - return range.AtEnd(); + return true; } CSSValue* font_synthesis_weight = nullptr; CSSValue* font_synthesis_style = nullptr; CSSValue* font_synthesis_small_caps = nullptr; do { + CSSParserSavePoint savepoint(range); + bool fail = false; CSSValueID id = range.ConsumeIncludingWhitespace().Id(); switch (id) { case CSSValueID::kWeight: @@ -1682,12 +1697,14 @@ return false; } font_synthesis_weight = CSSIdentifierValue::Create(CSSValueID::kAuto); + savepoint.Release(); break; case CSSValueID::kStyle: if (font_synthesis_style) { return false; } font_synthesis_style = CSSIdentifierValue::Create(CSSValueID::kAuto); + savepoint.Release(); break; case CSSValueID::kSmallCaps: if (font_synthesis_small_caps) { @@ -1695,12 +1712,24 @@ } font_synthesis_small_caps = CSSIdentifierValue::Create(CSSValueID::kAuto); + savepoint.Release(); break; default: - return false; + // Random junk at the end is allowed (could be “!important”, + // and if it's not, the caller will reject the value for us). + fail = true; + break; + } + if (fail) { + break; } } while (!range.AtEnd()); + if (!font_synthesis_weight && !font_synthesis_style && + !font_synthesis_small_caps) { + return false; + } + css_parsing_utils::AddProperty( CSSPropertyID::kFontSynthesisWeight, CSSPropertyID::kFontSynthesis, font_synthesis_weight ? *font_synthesis_weight @@ -1740,7 +1769,7 @@ DCHECK_EQ(shorthandForProperty(CSSPropertyID::kGap).length(), 2u); CSSValue* row_gap = css_parsing_utils::ConsumeGapLength(range, context); CSSValue* column_gap = css_parsing_utils::ConsumeGapLength(range, context); - if (!row_gap || !range.AtEnd()) { + if (!row_gap) { return false; } if (!column_gap) { @@ -1798,9 +1827,6 @@ } } } - if (!range.AtEnd()) { - return false; - } if (!column_start_value) { column_start_value = row_start_value->IsCustomIdentValue() ? row_start_value @@ -1930,9 +1956,18 @@ const CSSValue* template_columns = nullptr; const CSSValue* template_areas = nullptr; - if (css_parsing_utils::ConsumeGridTemplateShorthand( - important, range, context, template_rows, template_columns, - template_areas)) { + // NOTE: The test for range.AtEnd() here is a practical concession; + // we should accept any arbitrary junk afterwards, but for cases like + // “none / auto-flow 100px”, ConsumeGridTemplateShorthand() will consume + // the “none” alone and return success, which is not what we want + // (we want to fall back to the part below). So we make a quick fix + // to check for either end _or_ !important. + const bool ok = css_parsing_utils::ConsumeGridTemplateShorthand( + important, range, context, template_rows, template_columns, + template_areas); + range.ConsumeWhitespace(); + if (ok && (range.AtEnd() || (range.Peek().GetType() == kDelimiterToken && + range.Peek().Delimiter() == '!'))) { DCHECK(template_rows); DCHECK(template_columns); DCHECK(template_areas); @@ -2019,23 +2054,17 @@ if (!grid_auto_flow) { return false; } - if (range.AtEnd()) { + auto_columns_value = css_parsing_utils::ConsumeGridTrackList( + range, context, css_parsing_utils::TrackListType::kGridAuto); + if (!auto_columns_value) { + // End of stream or parse error; in the latter case, + // the caller will clean up since we're not at the end. auto_columns_value = GetCSSPropertyGridAutoColumns().InitialValue(); - } else { - auto_columns_value = css_parsing_utils::ConsumeGridTrackList( - range, context, css_parsing_utils::TrackListType::kGridAuto); - if (!auto_columns_value) { - return false; - } } template_columns = GetCSSPropertyGridTemplateColumns().InitialValue(); auto_rows_value = GetCSSPropertyGridAutoRows().InitialValue(); } - if (!range.AtEnd()) { - return false; - } - // It can only be specified the explicit or the implicit grid properties in a // single grid declaration. The sub-properties not specified are set to their // initial value, as normal for shorthands. @@ -2281,8 +2310,11 @@ continue; } } - return false; + break; } while (!range.AtEnd()); + if (!none && !list_style_position && !list_style_image && !list_style_type) { + return false; + } if (none) { if (!list_style_type) { list_style_type = none; @@ -2428,7 +2460,7 @@ HeapVector<CSSPropertyValue, 64>& properties) const { const CSSValue* marker = css_parsing_utils::ParseLonghand( CSSPropertyID::kMarkerStart, CSSPropertyID::kMarker, context, range); - if (!marker || !range.AtEnd()) { + if (!marker) { return false; } @@ -2494,7 +2526,7 @@ return false; } } - if ((!offset_position && !offset_path) || !range.AtEnd()) { + if (!offset_position && !offset_path) { return false; } @@ -2784,23 +2816,24 @@ return false; } - const CSSValue* justify_content_value = nullptr; - if (range.AtEnd()) { + const CSSValue* justify_content_value = + GetCSSPropertyJustifyContent().ParseSingleValueFromRange(range, context, + local_context); + if (!justify_content_value) { if (is_baseline) { justify_content_value = MakeGarbageCollected<cssvalue::CSSContentDistributionValue>( CSSValueID::kInvalid, CSSValueID::kStart, CSSValueID::kInvalid); } else { + // Rewind the parser and use the value we just parsed as align-content, as + // justify-content, too. range = range_copy; + justify_content_value = + GetCSSPropertyJustifyContent().ParseSingleValueFromRange( + range, context, local_context); } } if (!justify_content_value) { - justify_content_value = - GetCSSPropertyJustifyContent().ParseSingleValueFromRange(range, context, - local_context); - } - - if (!justify_content_value || !range.AtEnd()) { return false; } @@ -2845,15 +2878,21 @@ return false; } - if (range.AtEnd()) { - range = range_copy; - } - const CSSValue* justify_items_value = GetCSSPropertyJustifyItems().ParseSingleValueFromRange(range, context, local_context); - if (!justify_items_value || !range.AtEnd()) { - return false; + if (!justify_items_value) { + // End-of-stream or parse error. If it's the former, + // we try to to parse what we already parsed as align-items again, + // just as justify-items. If it's the latter, the caller will + // clean up for us (as we won't end on end-of-stream). + justify_items_value = + GetCSSPropertyJustifyItems().ParseSingleValueFromRange( + range_copy, context, local_context); + if (!justify_items_value || + range.RemainingSpan() != range_copy.RemainingSpan()) { + return false; + } } DCHECK(align_items_value); @@ -2897,15 +2936,20 @@ return false; } - if (range.AtEnd()) { - range = range_copy; - } - const CSSValue* justify_self_value = GetCSSPropertyJustifySelf().ParseSingleValueFromRange(range, context, local_context); - if (!justify_self_value || !range.AtEnd()) { - return false; + if (!justify_self_value) { + // End-of-stream or parse error. If it's the former, + // we try to to parse what we already parsed as align-items again, + // just as justify-items. If it's the latter, the caller will + // clean up for us (as we won't end on end-of-stream). + justify_self_value = GetCSSPropertyJustifySelf().ParseSingleValueFromRange( + range_copy, context, local_context); + if (!justify_self_value || + range.RemainingSpan() != range_copy.RemainingSpan()) { + return false; + } } DCHECK(align_self_value); @@ -2956,7 +3000,7 @@ CSSPropertyID::kPositionTryOptions, CSSPropertyID::kPositionTry, *options, important, css_parsing_utils::IsImplicitProperty::kNotImplicit, properties); - return range.AtEnd(); + return true; } return false; } @@ -3200,7 +3244,7 @@ properties); } - return range.AtEnd(); + return true; } static CSSValue* CSSValueForTimelineShorthand( @@ -3256,7 +3300,7 @@ AddProperty(scrollStartShorthand().properties()[1]->PropertyID(), scrollStartShorthand().id(), *inline_value, important, css_parsing_utils::IsImplicitProperty::kNotImplicit, properties); - return range.AtEnd(); + return true; } const CSSValue* ScrollStart::CSSValueFromComputedStyleInternal( @@ -3298,7 +3342,7 @@ AddProperty(scrollStartTargetShorthand().properties()[1]->PropertyID(), scrollStartTargetShorthand().id(), *inline_value, important, css_parsing_utils::IsImplicitProperty::kNotImplicit, properties); - return range.AtEnd(); + return true; } const CSSValue* ScrollStartTarget::CSSValueFromComputedStyleInternal( @@ -3455,7 +3499,7 @@ properties); } - return range.AtEnd(); + return true; } const CSSValue* Transition::CSSValueFromComputedStyleInternal( @@ -3740,22 +3784,15 @@ // https://drafts.csswg.org/css-text-4/#text-spacing-property // // Try `none` first. - if (const CSSIdentifierValue* ident = - css_parsing_utils::ConsumeIdent<CSSValueID::kNone>(range); - ident && range.AtEnd()) { + if (css_parsing_utils::ConsumeIdent<CSSValueID::kNone>(range)) { autospace = CSSIdentifierValue::Create(CSSValueID::kNoAutospace); spacing_trim = CSSIdentifierValue::Create(CSSValueID::kSpaceAll); - } - - // Try `<autospace> || <spacing-trim>`. - if (!autospace) { + } else { + // Try `<autospace> || <spacing-trim>`. range = original_range; wtf_size_t num_values = 0; - while (!range.AtEnd()) { - if (++num_values > 2) { - return false; - } + while (!range.AtEnd() && ++num_values <= 2) { if (css_parsing_utils::ConsumeIdent<CSSValueID::kNormal>(range)) { // `normal` can be either `text-autospace`, `text-spacing-trim`, or // both. Keep parsing without setting the value. @@ -3769,7 +3806,10 @@ (spacing_trim = css_parsing_utils::ConsumeSpacingTrim(range))) { continue; } - return false; + + // Parse error, but we must accept whatever junk might be after our own + // tokens. Fail only if we didn't parse any useful values. + break; } if (!num_values) { @@ -3869,7 +3909,19 @@ range)) { // Parse as a pre-defined keyword only if it is at the end. Some keywords // can be both a pre-defined keyword or a longhand value. - if (range.AtEnd()) { + // + // TODO(sesse): Figure out some less hacky way of figuring out + // whether we are at the end or not. In theory, we are supposed to + // accept arbitrary junk after our input, but we are being saved + // by the fact that shorthands only need to worry about !important + // (and none of our longhands accept anything involving the ! delimiter). + bool at_end = range.AtEnd(); + if (!at_end) { + range.ConsumeWhitespace(); + at_end = range.Peek().GetType() == kDelimiterToken && + range.Peek().Delimiter() == '!'; + } + if (at_end) { const EWhiteSpace whitespace = CssValueIDToPlatformEnum<EWhiteSpace>(value->GetValueID()); DCHECK(IsValidWhiteSpace(whitespace));
diff --git a/third_party/blink/renderer/core/events/message_event.cc b/third_party/blink/renderer/core/events/message_event.cc index 8de8d4c..b79c6d66 100644 --- a/third_party/blink/renderer/core/events/message_event.cc +++ b/third_party/blink/renderer/core/events/message_event.cc
@@ -434,10 +434,9 @@ case kDataTypeArrayBuffer: V8PrivateProperty::GetSymbol(isolate, kPrivatePropertyMessageEventCachedData) - .Set(wrapper, - ToV8Traits<DOMArrayBuffer>::ToV8( - ScriptState::From(wrapper->GetCreationContextChecked()), - data_as_array_buffer_)); + .Set(wrapper, ToV8Traits<DOMArrayBuffer>::ToV8( + ScriptState::ForRelevantRealm(isolate, wrapper), + data_as_array_buffer_)); break; }
diff --git a/third_party/blink/renderer/core/exported/web_array_buffer_converter.cc b/third_party/blink/renderer/core/exported/web_array_buffer_converter.cc index cdfedf2..9f892a2 100644 --- a/third_party/blink/renderer/core/exported/web_array_buffer_converter.cc +++ b/third_party/blink/renderer/core/exported/web_array_buffer_converter.cc
@@ -41,8 +41,8 @@ v8::Isolate* isolate) { if (!buffer) return v8::Local<v8::Value>(); - return ToV8Traits<DOMArrayBuffer>::ToV8( - ScriptState::From(isolate->GetCurrentContext()), *buffer); + return ToV8Traits<DOMArrayBuffer>::ToV8(ScriptState::ForCurrentRealm(isolate), + *buffer); } WebArrayBuffer* WebArrayBufferConverter::CreateFromV8Value(
diff --git a/third_party/blink/renderer/core/exported/web_blob.cc b/third_party/blink/renderer/core/exported/web_blob.cc index f10a9bf3..0293e21f 100644 --- a/third_party/blink/renderer/core/exported/web_blob.cc +++ b/third_party/blink/renderer/core/exported/web_blob.cc
@@ -88,7 +88,7 @@ if (!private_.Get()) return v8::Local<v8::Value>(); v8::Local<v8::Value> value = ToV8Traits<Blob>::ToV8( - ScriptState::From(isolate->GetCurrentContext()), private_.Get()); + ScriptState::ForCurrentRealm(isolate), private_.Get()); return value; }
diff --git a/third_party/blink/renderer/core/exported/web_isolated_world_info.cc b/third_party/blink/renderer/core/exported/web_isolated_world_info.cc index eb675273..5c4831a2 100644 --- a/third_party/blink/renderer/core/exported/web_isolated_world_info.cc +++ b/third_party/blink/renderer/core/exported/web_isolated_world_info.cc
@@ -34,13 +34,15 @@ } WebString GetIsolatedWorldStableId(v8::Local<v8::Context> context) { - const DOMWrapperWorld& world = DOMWrapperWorld::World(context); + v8::Isolate* isolate = context->GetIsolate(); + const DOMWrapperWorld& world = DOMWrapperWorld::World(isolate, context); DCHECK(!world.IsMainWorld()); return world.NonMainWorldStableId(); } WebString GetIsolatedWorldHumanReadableName(v8::Local<v8::Context> context) { - const DOMWrapperWorld& world = DOMWrapperWorld::World(context); + v8::Isolate* isolate = context->GetIsolate(); + const DOMWrapperWorld& world = DOMWrapperWorld::World(isolate, context); DCHECK(!world.IsMainWorld()); return world.NonMainWorldHumanReadableName(); }
diff --git a/third_party/blink/renderer/core/exported/web_node.cc b/third_party/blink/renderer/core/exported/web_node.cc index fff07777..1e2b41a 100644 --- a/third_party/blink/renderer/core/exported/web_node.cc +++ b/third_party/blink/renderer/core/exported/web_node.cc
@@ -167,7 +167,7 @@ v8::Local<v8::Value> WebNode::ToV8Value(v8::Isolate* isolate) { if (!private_.Get()) return v8::Local<v8::Value>(); - return ToV8Traits<Node>::ToV8(ScriptState::From(isolate->GetCurrentContext()), + return ToV8Traits<Node>::ToV8(ScriptState::ForCurrentRealm(isolate), private_.Get()); }
diff --git a/third_party/blink/renderer/core/exported/web_v8_features.cc b/third_party/blink/renderer/core/exported/web_v8_features.cc index 69b152d..22996dd 100644 --- a/third_party/blink/renderer/core/exported/web_v8_features.cc +++ b/third_party/blink/renderer/core/exported/web_v8_features.cc
@@ -22,7 +22,8 @@ // (crbug.com/976506) ContextFeatureSettings::CrashIfMojoJSNotAllowed(); } - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); DCHECK(script_state->World().IsMainWorld()); ContextFeatureSettings::From( ExecutionContext::From(script_state), @@ -56,7 +57,8 @@ // (crbug.com/976506) ContextFeatureSettings::CrashIfMojoJSNotAllowed(); } - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); DCHECK(script_state->World().IsMainWorld()); auto* context_feature_settings = ContextFeatureSettings::From( @@ -76,7 +78,8 @@ // static bool WebV8Features::IsMojoJSEnabledForTesting(v8::Local<v8::Context> context) { - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); DCHECK(script_state->World().IsMainWorld()); ContextFeatureSettings* settings = ContextFeatureSettings::From( ExecutionContext::From(script_state), @@ -87,7 +90,8 @@ // static void WebV8Features::EnableMojoJSWithoutSecurityChecksForTesting( v8::Local<v8::Context> context) { - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); DCHECK(script_state->World().IsMainWorld()); ContextFeatureSettings::From( ExecutionContext::From(script_state),
diff --git a/third_party/blink/renderer/core/frame/animation_frame_timing_monitor.cc b/third_party/blink/renderer/core/frame/animation_frame_timing_monitor.cc index d054ef4e..5b5a7d1 100644 --- a/third_party/blink/renderer/core/frame/animation_frame_timing_monitor.cc +++ b/third_party/blink/renderer/core/frame/animation_frame_timing_monitor.cc
@@ -545,7 +545,9 @@ // In some cases we get here without a EvaluateScriptBlock, e.g. when // executing an imported module script. // This is true for both imported and element-created scripts. - if (PushScriptEntryPoint(ScriptState::From(probe_data.v8_context))) { + v8::Isolate* isolate = probe_data.context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, probe_data.v8_context); + if (PushScriptEntryPoint(script_state)) { pending_script_info_ = PendingScriptInfo{ .invoker_type = ScriptTimingInfo::InvokerType::kModuleScript, .start_time = probe_data.CaptureStartTime(),
diff --git a/third_party/blink/renderer/core/frame/animation_frame_timing_monitor.h b/third_party/blink/renderer/core/frame/animation_frame_timing_monitor.h index 1ba808c..b1c700e 100644 --- a/third_party/blink/renderer/core/frame/animation_frame_timing_monitor.h +++ b/third_party/blink/renderer/core/frame/animation_frame_timing_monitor.h
@@ -83,7 +83,10 @@ } void Will(const probe::ExecuteScript&); void Did(const probe::ExecuteScript& probe_data) { - PopScriptEntryPoint(ScriptState::From(probe_data.v8_context), &probe_data); + v8::Isolate* isolate = probe_data.context->GetIsolate(); + ScriptState* script_state = + ScriptState::From(isolate, probe_data.v8_context); + PopScriptEntryPoint(script_state, &probe_data); } void Will(const probe::RecalculateStyle&); void Did(const probe::RecalculateStyle&);
diff --git a/third_party/blink/renderer/core/frame/dom_window.cc b/third_party/blink/renderer/core/frame/dom_window.cc index 723a268..1d386a37 100644 --- a/third_party/blink/renderer/core/frame/dom_window.cc +++ b/third_party/blink/renderer/core/frame/dom_window.cc
@@ -187,7 +187,7 @@ RecordWindowProxyAccessMetrics( WebFeature::kWindowProxyCrossOriginAccessOpener, WebFeature::kWindowProxyCrossOriginAccessFromOtherPageOpener); - ScriptState* script_state = ScriptState::From(isolate->GetCurrentContext()); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); return ScriptValue(isolate, ToV8Traits<IDLNullable<DOMWindow>>::ToV8( script_state, opener())); } @@ -229,7 +229,7 @@ // [[Enumerable]]: true, [[Configurable]]: true }). v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Object> this_wrapper = - ToV8Traits<DOMWindow>::ToV8(ScriptState::From(context), this) + ToV8Traits<DOMWindow>::ToV8(ScriptState::From(isolate, context), this) .As<v8::Object>(); v8::PropertyDescriptor desc(opener.V8Value(), /*writable=*/true); desc.set_enumerable(true);
diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc index 738d70b..2b64eec1 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc
@@ -1108,7 +1108,7 @@ static_cast<LocalWindowProxyManager*>(GetWindowProxyManager()) ->SetAbortScriptExecution( [](v8::Isolate* isolate, v8::Local<v8::Context> context) { - ScriptState* script_state = ScriptState::From(context); + ScriptState* script_state = ScriptState::From(isolate, context); LocalDOMWindow* window = LocalDOMWindow::From(script_state); DCHECK(window); LocalFrame* frame = window->GetFrame();
diff --git a/third_party/blink/renderer/core/frame/pausable_script_executor.cc b/third_party/blink/renderer/core/frame/pausable_script_executor.cc index c456bca..f16d5463 100644 --- a/third_party/blink/renderer/core/frame/pausable_script_executor.cc +++ b/third_party/blink/renderer/core/frame/pausable_script_executor.cc
@@ -238,7 +238,8 @@ v8::Local<v8::Value> argv[], mojom::blink::WantResultOption want_result_option, WebScriptExecutionCallback callback) { - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); if (!script_state->ContextIsValid()) { if (callback) std::move(callback).Run({}, {});
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index 46fe735..76b8c132 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -1141,7 +1141,8 @@ int32_t WebLocalFrameImpl::GetScriptContextWorldId( v8::Local<v8::Context> script_context) const { DCHECK_EQ(this, FrameForContext(script_context)); - return DOMWrapperWorld::World(script_context).GetWorldId(); + v8::Isolate* isolate = script_context->GetIsolate(); + return DOMWrapperWorld::World(isolate, script_context).GetWorldId(); } v8::Local<v8::Context> WebLocalFrameImpl::GetScriptContextFromWorldId(
diff --git a/third_party/blink/renderer/core/frame/window_properties.cc b/third_party/blink/renderer/core/frame/window_properties.cc index 14bbcb1..0b7448b 100644 --- a/third_party/blink/renderer/core/frame/window_properties.cc +++ b/third_party/blink/renderer/core/frame/window_properties.cc
@@ -74,8 +74,8 @@ if (frame->GetSecurityContext()->GetSecurityOrigin()->CanAccess( child->GetSecurityContext()->GetSecurityOrigin()) || name == child->Owner()->BrowsingContextContainerName()) { - return ToV8Traits<DOMWindow>::ToV8( - ScriptState::From(isolate->GetCurrentContext()), child->DomWindow()); + return ToV8Traits<DOMWindow>::ToV8(ScriptState::ForCurrentRealm(isolate), + child->DomWindow()); } UseCounter::Count(
diff --git a/third_party/blink/renderer/core/html/canvas/image_data.cc b/third_party/blink/renderer/core/html/canvas/image_data.cc index 4522815c..06c77bc 100644 --- a/third_party/blink/renderer/core/html/canvas/image_data.cc +++ b/third_party/blink/renderer/core/html/canvas/image_data.cc
@@ -380,8 +380,7 @@ // // This is a perf hack breaking the web interop. - ScriptState* script_state = - ScriptState::From(wrapper->GetCreationContextChecked()); + ScriptState* script_state = ScriptState::ForRelevantRealm(isolate, wrapper); v8::Local<v8::Value> v8_data = ToV8Traits<V8ImageDataArray>::ToV8(script_state, data_); bool defined_property;
diff --git a/third_party/blink/renderer/core/html/html_plugin_element.cc b/third_party/blink/renderer/core/html/html_plugin_element.cc index 679f543..ab5c579 100644 --- a/third_party/blink/renderer/core/html/html_plugin_element.cc +++ b/third_party/blink/renderer/core/html/html_plugin_element.cc
@@ -425,9 +425,9 @@ return ScriptValue(); } - v8::Local<v8::Context> context = - GetExecutionContext()->GetIsolate()->GetCurrentContext(); - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = GetExecutionContext()->GetIsolate(); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + ScriptState* script_state = ScriptState::From(isolate, context); if (!script_state->World().IsMainWorld()) { if (script_state->World().IsIsolatedWorld()) { UseCounter::Count(GetExecutionContext(), @@ -467,9 +467,9 @@ return NamedPropertySetterResult::kDidNotIntercept; } - v8::Local<v8::Context> context = - GetExecutionContext()->GetIsolate()->GetCurrentContext(); - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = GetExecutionContext()->GetIsolate(); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + ScriptState* script_state = ScriptState::From(isolate, context); if (!script_state->World().IsMainWorld()) { // The plugin system cannot deal with multiple worlds, so block any // non-main world access.
diff --git a/third_party/blink/renderer/core/inspector/main_thread_debugger.cc b/third_party/blink/renderer/core/inspector/main_thread_debugger.cc index eb780f27..da19ccb 100644 --- a/third_party/blink/renderer/core/inspector/main_thread_debugger.cc +++ b/third_party/blink/renderer/core/inspector/main_thread_debugger.cc
@@ -414,7 +414,7 @@ v8::Local<v8::Context> context) { DCHECK(ToLocalDOMWindow(context)); return ToV8Traits<MemoryInfo>::ToV8( - ScriptState::From(context), + ScriptState::From(isolate, context), MakeGarbageCollected<MemoryInfo>(MemoryInfo::Precision::kBucketized)); } @@ -467,7 +467,7 @@ return; if (element) { ScriptState* script_state = - ScriptState::From(info.This()->GetCreationContextChecked()); + ScriptState::ForRelevantRealm(info.GetIsolate(), info.This()); info.GetReturnValue().Set(ToV8Traits<Element>::ToV8(script_state, element)); } else { info.GetReturnValue().Set(v8::Null(info.GetIsolate())); @@ -498,7 +498,7 @@ v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Array> nodes = v8::Array::New(isolate, element_list->length()); ScriptState* script_state = - ScriptState::From(info.This()->GetCreationContextChecked()); + ScriptState::ForRelevantRealm(info.GetIsolate(), info.This()); for (wtf_size_t i = 0; i < element_list->length(); ++i) { Element* element = element_list->item(i); v8::Local<v8::Value> value = @@ -531,7 +531,7 @@ if (exception_state.HadException() || !result) return; ScriptState* script_state = - ScriptState::From(info.This()->GetCreationContextChecked()); + ScriptState::ForRelevantRealm(info.GetIsolate(), info.This()); if (result->resultType() == XPathResult::kNumberType) { V8SetReturnValue(info, result->numberValue(exception_state)); } else if (result->resultType() == XPathResult::kStringType) {
diff --git a/third_party/blink/renderer/core/inspector/resolve_node.cc b/third_party/blink/renderer/core/inspector/resolve_node.cc index eb0ea94..d76fcd96 100644 --- a/third_party/blink/renderer/core/inspector/resolve_node.cc +++ b/third_party/blink/renderer/core/inspector/resolve_node.cc
@@ -22,7 +22,7 @@ !BindingSecurity::ShouldAllowAccessTo(CurrentDOMWindow(isolate), node)) { return v8::Null(isolate); } - return ToV8Traits<Node>::ToV8(ScriptState::From(context), node); + return ToV8Traits<Node>::ToV8(ScriptState::From(isolate, context), node); } std::unique_ptr<v8_inspector::protocol::Runtime::API::RemoteObject> ResolveNode(
diff --git a/third_party/blink/renderer/core/inspector/thread_debugger_common_impl.cc b/third_party/blink/renderer/core/inspector/thread_debugger_common_impl.cc index 65e757cd..96d5915 100644 --- a/third_party/blink/renderer/core/inspector/thread_debugger_common_impl.cc +++ b/third_party/blink/renderer/core/inspector/thread_debugger_common_impl.cc
@@ -760,11 +760,13 @@ "function getAccessibleRole(node) { [Command Line API] }", v8::SideEffectType::kHasNoSideEffect); + v8::Isolate* isolate = context->GetIsolate(); ScriptEvaluationResult result = ClassicScript::CreateUnspecifiedScript( "(function(e) { console.log(e.type, e); })", ScriptSourceLocationType::kInternal) - ->RunScriptOnScriptStateAndReturnValue(ScriptState::From(context)); + ->RunScriptOnScriptStateAndReturnValue( + ScriptState::From(isolate, context)); if (result.GetResultType() != ScriptEvaluationResult::ResultType::kSuccess) { // On pages where scripting is disabled or CSP sandbox directive is used, // this can be blocked and thus early exited here.
diff --git a/third_party/blink/renderer/core/layout/inline/line_breaker.cc b/third_party/blink/renderer/core/layout/inline/line_breaker.cc index 6a0b57a3..c6266d5 100644 --- a/third_party/blink/renderer/core/layout/inline/line_breaker.cc +++ b/third_party/blink/renderer/core/layout/inline/line_breaker.cc
@@ -407,23 +407,7 @@ } // namespace inline bool LineBreaker::ShouldAutoWrap(const ComputedStyle& style) const { - // TODO(crbug.com/366553): SVG <text> should not be auto_wrap_ for now. - if (UNLIKELY(is_svg_text_)) - return false; - // Combine text should not cause line break. - if (UNLIKELY(is_text_combine_)) - return false; - // TODO(crbug.com/1276900): Once we implement multiple line initial letter, - // we should allow auto wrap. Below example causes multiple lines text in - // initial letter box. - // <style> - // p::.first-letter { line-break: anywhere; } - // p { width: 0px; } - // </style> - // <p>(A) punctuation characters can be part of ::first-letter.</p> - if (UNLIKELY(is_initial_letter_box_)) - return false; - return style.ShouldWrapLine(); + return !UNLIKELY(disallow_auto_wrap_) && style.ShouldWrapLine(); } void LineBreaker::UpdateAvailableWidth() { @@ -496,6 +480,20 @@ char_data_list); } } + // TODO(crbug.com/40362375): SVG <text> should not be auto_wrap_ for now. + // + // Combine text should not cause line break. + // + // TODO(crbug.com/40207613): Once we implement multiple line initial letter, + // we should allow auto wrap. Below example causes multiple lines text in + // initial letter box. + // <style> + // p::.first-letter { line-break: anywhere; } + // p { width: 0px; } + // </style> + // <p>(A) punctuation characters can be part of ::first-letter.</p> + disallow_auto_wrap_ = + is_svg_text_ || is_text_combine_ || is_initial_letter_box_; if (!break_token) return; @@ -3216,13 +3214,14 @@ const InlineItem& item = Items()[open_column_item_index]; LineInfo base_line_info = CreateSubLineInfo( - base_start, base_end_index, LayoutUnit::Max(), trailing_whitespace_); + base_start, base_end_index, LineBreakerMode::kMaxContent, kIndefiniteSize, + trailing_whitespace_); HeapVector<LineInfo, 1> annotation_line_list; for (const auto& data : annotation_data) { - annotation_line_list.push_back( - CreateSubLineInfo(data.start, data.end_item_index, LayoutUnit::Max(), - WhitespaceState::kLeading)); + annotation_line_list.push_back(CreateSubLineInfo( + data.start, data.end_item_index, LineBreakerMode::kMaxContent, + kIndefiniteSize, WhitespaceState::kLeading)); } LayoutUnit ruby_size = MaxLineWidth(base_line_info, annotation_line_list); @@ -3231,12 +3230,13 @@ // Recreate lines because lines created with LineBreakerMode::kMaxContent // are not usable in InlineLayoutAlgorithm. base_line_info = - CreateSubLineInfo(base_start, base_end_index, LayoutUnit::NearlyMax(), - trailing_whitespace_); + CreateSubLineInfo(base_start, base_end_index, LineBreakerMode::kContent, + kIndefiniteSize, trailing_whitespace_); for (wtf_size_t i = 0; i < annotation_data.size(); ++i) { annotation_line_list[i] = CreateSubLineInfo( annotation_data[i].start, annotation_data[i].end_item_index, - LayoutUnit::NearlyMax(), WhitespaceState::kLeading); + LineBreakerMode::kContent, kIndefiniteSize, + WhitespaceState::kLeading); } AddRubyColumnResult(item, base_line_info, annotation_line_list, @@ -3253,20 +3253,28 @@ LineInfo LineBreaker::CreateSubLineInfo( InlineItemTextIndex start, wtf_size_t end_item_index, + LineBreakerMode mode, LayoutUnit limit, WhitespaceState initial_whitespace_state) { + bool disallow_auto_wrap = false; + if (limit == kIndefiniteSize) { + limit = LayoutUnit::Max(); + disallow_auto_wrap = true; + } ExclusionSpace empty_exclusion_space; LeadingFloats empty_leading_floats; LineInfo sub_line_info; LineBreaker sub_line_breaker( - node_, - limit == LayoutUnit::Max() ? LineBreakerMode::kMaxContent - : LineBreakerMode::kContent, - constraint_space_, LineLayoutOpportunity(limit), empty_leading_floats, + node_, mode, constraint_space_, LineLayoutOpportunity(limit), + empty_leading_floats, /* break_token */ nullptr, /* column_spanner_path */ nullptr, &empty_exclusion_space); + sub_line_breaker.disallow_auto_wrap_ = disallow_auto_wrap; sub_line_breaker.SetInputRange(start, end_item_index, initial_whitespace_state); + // OverrideAvailableWidth() prevents HandleFloat() from updating + // available_width_. + sub_line_breaker.OverrideAvailableWidth(limit); sub_line_breaker.NextLine(&sub_line_info); return sub_line_info; }
diff --git a/third_party/blink/renderer/core/layout/inline/line_breaker.h b/third_party/blink/renderer/core/layout/inline/line_breaker.h index d6616400..9c33974 100644 --- a/third_party/blink/renderer/core/layout/inline/line_breaker.h +++ b/third_party/blink/renderer/core/layout/inline/line_breaker.h
@@ -222,8 +222,11 @@ InlineItemResult*); // Returns false if we can't handle the current InlineItem as a ruby. bool HandleRuby(LineInfo* line_info); + // `mode`: Must be kMaxContent or kContent. + // `limit`: Must be non-negative or kIndefiniteSize, which means no auto-wrap. LineInfo CreateSubLineInfo(InlineItemTextIndex start, wtf_size_t end_item_index, + LineBreakerMode mode, LayoutUnit limit, WhitespaceState initial_whitespace_state); InlineItemResult* AddRubyColumnResult( @@ -344,6 +347,9 @@ // True when current box allows line wrapping. bool auto_wrap_ = false; + // Disallow line wrapping even if the ComputedStyle allows it. + bool disallow_auto_wrap_ = false; + // True when current box should fallback to break anywhere if it overflows. bool break_anywhere_if_overflow_ = false;
diff --git a/third_party/blink/renderer/core/layout/inline/line_breaker_test.cc b/third_party/blink/renderer/core/layout/inline/line_breaker_test.cc index 8c727bc..648588c 100644 --- a/third_party/blink/renderer/core/layout/inline/line_breaker_test.cc +++ b/third_party/blink/renderer/core/layout/inline/line_breaker_test.cc
@@ -2,15 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "third_party/blink/renderer/core/layout/base_layout_algorithm_test.h" +#include "third_party/blink/renderer/core/layout/inline/line_breaker.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" +#include "third_party/blink/renderer/core/layout/base_layout_algorithm_test.h" #include "third_party/blink/renderer/core/layout/box_fragment_builder.h" #include "third_party/blink/renderer/core/layout/constraint_space_builder.h" #include "third_party/blink/renderer/core/layout/inline/inline_break_token.h" #include "third_party/blink/renderer/core/layout/inline/inline_cursor.h" +#include "third_party/blink/renderer/core/layout/inline/inline_item_result_ruby_column.h" #include "third_party/blink/renderer/core/layout/inline/inline_node.h" -#include "third_party/blink/renderer/core/layout/inline/line_breaker.h" #include "third_party/blink/renderer/core/layout/inline/line_info.h" #include "third_party/blink/renderer/core/layout/layout_ng_block_flow.h" #include "third_party/blink/renderer/core/layout/positioned_float.h" @@ -1099,6 +1100,34 @@ EXPECT_EQ(line_info_list[1].Results().front().item_index, 4u); } +// We have a crash with content wider than LayoutUnit::Max() in a ruby. +// crbug.com/338437458 +TEST_F(LineBreakerTest, WideContentInRuby) { + InlineNode node = CreateInlineNode(R"HTML( + <div id=container> + <ruby><div style="width:109162843px; margin-right:1000px"></div><div> + a</div><rt>a</ruby> + </div>)HTML"); + GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc); + GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kStyleClean); + GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInPerformLayout); + node.PrepareLayoutIfNeeded(); + ConstraintSpace space = ConstraintSpaceForAvailableSize(LayoutUnit::Max()); + ExclusionSpace exclusion_space; + LeadingFloats leading_floats; + LineBreaker line_breaker(node, LineBreakerMode::kContent, space, + LineLayoutOpportunity(LayoutUnit::Max()), + leading_floats, nullptr, nullptr, &exclusion_space); + LineInfo line_info; + line_breaker.NextLine(&line_info); + EXPECT_EQ(InlineItem::kOpenRubyColumn, line_info.Results()[1].item->Type()); + // The base result should contain both <div>s. + const auto& base_results = + line_info.Results()[1].ruby_column->base_line.Results(); + EXPECT_EQ(InlineItem::kAtomicInline, base_results[1].item->Type()); + EXPECT_EQ(InlineItem::kAtomicInline, base_results[2].item->Type()); +} + TEST_F(LineBreakerTest, SetInputRange) { ScopedRubyLineBreakableForTest enable_ruby_line_breakable(true); InlineNode node = CreateInlineNode(R"HTML( @@ -1121,6 +1150,31 @@ EXPECT_EQ(InlineItem::kCloseTag, line_info.Results()[2].item->Type()); } +// crbug.com/338350369 Floats should not update available_width_ for +// sub-LineBreakers. +TEST_F(LineBreakerTest, CreateSubLineInfoAvailableWidth) { + LoadAhem(); + InlineNode node = CreateInlineNode(R"HTML( + <div id=container style="font: 40px Ahem"><ruby><b> + foo bar foo bar foo bar foo bar foo bar + foo bar foo bar foo bar foo bar foo bar + <button style="float:left;">f</button></b> + <rt>annotation</ruby></div>)HTML"); + node.PrepareLayoutIfNeeded(); + ExclusionSpace exclusion_space; + LeadingFloats leading_floats; + LayoutUnit width(30); + ConstraintSpace space = ConstraintSpaceForAvailableSize(width); + LineBreaker line_breaker(node, LineBreakerMode::kContent, space, + LineLayoutOpportunity(width), leading_floats, + nullptr, nullptr, &exclusion_space); + LineInfo line_info; + line_breaker.NextLine(&line_info); + // The line should contain the whole text. + EXPECT_EQ(InlineItem::kOpenRubyColumn, line_info.Results()[1].item->Type()); + EXPECT_GE(line_info.Results()[1].ruby_column->base_line.EndTextOffset(), 79u); +} + struct CanBreakInsideTestData { bool can_break_insde; const char* html;
diff --git a/third_party/blink/renderer/core/paint/box_painter_base.cc b/third_party/blink/renderer/core/paint/box_painter_base.cc index 26a060f1..fd35aaf 100644 --- a/third_party/blink/renderer/core/paint/box_painter_base.cc +++ b/third_party/blink/renderer/core/paint/box_painter_base.cc
@@ -33,6 +33,7 @@ #include "third_party/blink/renderer/core/style/style_mask_source_image.h" #include "third_party/blink/renderer/platform/geometry/layout_rect.h" #include "third_party/blink/renderer/platform/graphics/bitmap_image.h" +#include "third_party/blink/renderer/platform/graphics/draw_looper_builder.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
diff --git a/third_party/blink/renderer/core/paint/text_painter.cc b/third_party/blink/renderer/core/paint/text_painter.cc index 5969b24c..6c323e9a 100644 --- a/third_party/blink/renderer/core/paint/text_painter.cc +++ b/third_party/blink/renderer/core/paint/text_painter.cc
@@ -23,6 +23,7 @@ #include "third_party/blink/renderer/core/style/shadow_list.h" #include "third_party/blink/renderer/platform/fonts/font.h" #include "third_party/blink/renderer/platform/fonts/text_fragment_paint_info.h" +#include "third_party/blink/renderer/platform/graphics/draw_looper_builder.h" #include "third_party/blink/renderer/platform/graphics/graphics_context.h" #include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
diff --git a/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.cc b/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.cc index 7827432..096c9cb3 100644 --- a/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.cc +++ b/third_party/blink/renderer/core/script/value_wrapper_synthetic_module_script.cc
@@ -193,7 +193,7 @@ v8::Local<v8::Context> context, v8::Local<v8::Module> module) { v8::Isolate* isolate = context->GetIsolate(); - ScriptState* script_state = ScriptState::From(context); + ScriptState* script_state = ScriptState::From(isolate, context); Modulator* modulator = Modulator::From(script_state); ModuleRecordResolver* module_record_resolver = modulator->GetModuleRecordResolver();
diff --git a/third_party/blink/renderer/core/style/shadow_list.h b/third_party/blink/renderer/core/style/shadow_list.h index 3cbddd7c..096cc7d0 100644 --- a/third_party/blink/renderer/core/style/shadow_list.h +++ b/third_party/blink/renderer/core/style/shadow_list.h
@@ -32,10 +32,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_SHADOW_LIST_H_ #include "third_party/blink/renderer/core/style/shadow_data.h" -#include "third_party/blink/renderer/platform/graphics/draw_looper_builder.h" -#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" -#include "third_party/blink/renderer/platform/wtf/ref_counted.h" -#include "third_party/blink/renderer/platform/wtf/vector.h" +#include "third_party/blink/renderer/platform/heap/collection_support/heap_vector.h" namespace gfx { class OutsetsF;
diff --git a/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc b/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc index 8c64688d..1c44dc7 100644 --- a/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc +++ b/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc
@@ -44,7 +44,8 @@ namespace { v8::Local<v8::Value> CreateInternalsObject(v8::Local<v8::Context> context) { - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); ExecutionContext* execution_context = ExecutionContext::From(script_state); if (execution_context->IsWindow()) { return ToV8Traits<Internals>::ToV8( @@ -60,17 +61,18 @@ } // namespace void InjectInternalsObject(v8::Local<v8::Context> context) { - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); ScriptState::Scope scope(script_state); - v8::Local<v8::Object> global = script_state->GetContext()->Global(); v8::Local<v8::Value> internals = CreateInternalsObject(context); if (internals.IsEmpty()) return; + v8::Local<v8::Object> global = context->Global(); global ->CreateDataProperty( - script_state->GetContext(), - V8AtomicString(script_state->GetIsolate(), "internals"), internals) + context, V8AtomicString(script_state->GetIsolate(), "internals"), + internals) .ToChecked(); } @@ -79,7 +81,8 @@ if (context.IsEmpty()) return; - ScriptState* script_state = ScriptState::From(context); + v8::Isolate* isolate = context->GetIsolate(); + ScriptState* script_state = ScriptState::From(isolate, context); ScriptState::Scope scope(script_state); LocalFrame* frame = LocalDOMWindow::From(script_state)->GetFrame(); // Should the frame have been detached, the page is assumed being destroyed
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index 1db6579..b1c7676 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -6060,10 +6060,13 @@ return; } - CHECK(!AXObjectCache().IsFrozen()) - << "Object should have already had its children updated in " - "AXObjectCacheImpl::UpdateTreeIfNeeded(): " - << this; + if (AXObjectCache().IsFrozen()) { + DUMP_WILL_BE_CHECK(!AXObjectCache().IsFrozen()) + << "Object should have already had its children updated in " + "AXObjectCacheImpl::UpdateTreeIfNeeded(): " + << this; + return; + } if (!CanHaveChildren()) { // Clear any children in case the node previously allowed children.
diff --git a/third_party/blink/renderer/modules/exported/web_dom_file_system.cc b/third_party/blink/renderer/modules/exported/web_dom_file_system.cc index 1db0428..d9b652ab 100644 --- a/third_party/blink/renderer/modules/exported/web_dom_file_system.cc +++ b/third_party/blink/renderer/modules/exported/web_dom_file_system.cc
@@ -117,8 +117,8 @@ v8::Local<v8::Value> WebDOMFileSystem::ToV8Value(v8::Isolate* isolate) { if (!private_.Get()) return v8::Local<v8::Value>(); - return ToV8Traits<DOMFileSystem>::ToV8( - ScriptState::From(isolate->GetCurrentContext()), private_.Get()); + return ToV8Traits<DOMFileSystem>::ToV8(ScriptState::ForCurrentRealm(isolate), + private_.Get()); } v8::Local<v8::Value> WebDOMFileSystem::CreateV8Entry( @@ -128,16 +128,16 @@ if (!private_.Get()) return v8::Local<v8::Value>(); v8::Local<v8::Value> value; + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); switch (entry_type) { case kEntryTypeDirectory: value = ToV8Traits<DirectoryEntry>::ToV8( - ScriptState::From(isolate->GetCurrentContext()), + script_state, MakeGarbageCollected<DirectoryEntry>(private_.Get(), path)); break; case kEntryTypeFile: value = ToV8Traits<FileEntry>::ToV8( - ScriptState::From(isolate->GetCurrentContext()), - MakeGarbageCollected<FileEntry>(private_.Get(), path)); + script_state, MakeGarbageCollected<FileEntry>(private_.Get(), path)); break; } return value;
diff --git a/third_party/blink/renderer/modules/ml/webnn/ml_graph_builder.cc b/third_party/blink/renderer/modules/ml/webnn/ml_graph_builder.cc index 4900a85..c3ff3c16 100644 --- a/third_party/blink/renderer/modules/ml/webnn/ml_graph_builder.cc +++ b/third_party/blink/renderer/modules/ml/webnn/ml_graph_builder.cc
@@ -1771,6 +1771,13 @@ ExceptionState& exception_state) { THROW_AND_RETURN_TYPE_IF_ERROR(ValidateInput(input), nullptr); + if (!(input->DataType() == V8MLOperandDataType::Enum::kFloat32 || + input->DataType() == V8MLOperandDataType::Enum::kFloat16)) { + exception_state.ThrowTypeError( + "The input data type must be a floating point type."); + return nullptr; + } + return BuildPool2d(this, webnn::mojom::blink::Pool2d::Kind::kAveragePool2d, input, options, exception_state); } @@ -1780,6 +1787,13 @@ ExceptionState& exception_state) { THROW_AND_RETURN_TYPE_IF_ERROR(ValidateInput(input), nullptr); + if (!(input->DataType() == V8MLOperandDataType::Enum::kFloat32 || + input->DataType() == V8MLOperandDataType::Enum::kFloat16)) { + exception_state.ThrowTypeError( + "The input data type must be a floating point type."); + return nullptr; + } + return BuildPool2d(this, webnn::mojom::blink::Pool2d::Kind::kL2Pool2d, input, options, exception_state); }
diff --git a/third_party/blink/renderer/modules/payments/payment_request_test.cc b/third_party/blink/renderer/modules/payments/payment_request_test.cc index 6270c1a..81745e3df 100644 --- a/third_party/blink/renderer/modules/payments/payment_request_test.cc +++ b/third_party/blink/renderer/modules/payments/payment_request_test.cc
@@ -706,6 +706,7 @@ auto* isolate = ToIsolate(&frame); v8::HandleScope handle_scope(isolate); ScriptState* script_state = ScriptState::From( + isolate, ToV8ContextEvenIfDetached(&frame, DOMWrapperWorld::MainWorld(isolate))); v8::Local<v8::Context> context(script_state->GetContext()); v8::Context::Scope context_scope(context);
diff --git a/third_party/blink/renderer/platform/bindings/callback_function_base.cc b/third_party/blink/renderer/platform/bindings/callback_function_base.cc index ee91a83..815436e 100644 --- a/third_party/blink/renderer/platform/bindings/callback_function_base.cc +++ b/third_party/blink/renderer/platform/bindings/callback_function_base.cc
@@ -18,7 +18,8 @@ v8::Isolate* isolate = callback_function->GetIsolate(); callback_function_.Reset(isolate, callback_function); - incumbent_script_state_ = ScriptState::From(isolate->GetIncumbentContext()); + incumbent_script_state_ = + ScriptState::From(isolate, isolate->GetIncumbentContext()); // Set |callback_relevant_script_state_| iff the creation context and the // incumbent context are the same origin-domain. Otherwise, leave it as @@ -30,14 +31,14 @@ // callsite to run arbitrary script in the context. No need to protect it. // This is an optimization faster than ShouldAllowAccessToV8Context below. callback_relevant_script_state_ = - ScriptState::ForRelevantRealm(callback_function); + ScriptState::ForRelevantRealm(isolate, callback_function); } else { v8::MaybeLocal<v8::Context> creation_context = callback_function->GetCreationContext(); if (BindingSecurityForPlatform::ShouldAllowAccessToV8Context( incumbent_script_state_->GetContext(), creation_context)) { callback_relevant_script_state_ = - ScriptState::From(creation_context.ToLocalChecked()); + ScriptState::From(isolate, creation_context.ToLocalChecked()); } } }
diff --git a/third_party/blink/renderer/platform/bindings/callback_interface_base.cc b/third_party/blink/renderer/platform/bindings/callback_interface_base.cc index dfc6657..70f8ec04 100644 --- a/third_party/blink/renderer/platform/bindings/callback_interface_base.cc +++ b/third_party/blink/renderer/platform/bindings/callback_interface_base.cc
@@ -18,7 +18,8 @@ v8::Isolate* isolate = callback_object->GetIsolate(); callback_object_.Reset(isolate, callback_object); - incumbent_script_state_ = ScriptState::From(isolate->GetIncumbentContext()); + incumbent_script_state_ = + ScriptState::From(isolate, isolate->GetIncumbentContext()); is_callback_object_callable_ = (single_op_or_not == kSingleOperation) && callback_object->IsCallable(); @@ -31,15 +32,15 @@ // it's not the same origin-domain, it's already been possible for the // callsite to run arbitrary script in the context. No need to protect it. // This is an optimization faster than ShouldAllowAccessToV8Context below. - callback_relevant_script_state_ = ScriptState::From( - callback_object->GetCreationContext().ToLocalChecked()); + callback_relevant_script_state_ = + ScriptState::ForRelevantRealm(isolate, callback_object); } else { v8::MaybeLocal<v8::Context> creation_context = callback_object->GetCreationContext(); if (BindingSecurityForPlatform::ShouldAllowAccessToV8Context( incumbent_script_state_->GetContext(), creation_context)) { callback_relevant_script_state_ = - ScriptState::From(creation_context.ToLocalChecked()); + ScriptState::From(isolate, creation_context.ToLocalChecked()); } } }
diff --git a/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h b/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h index d956ca1d..e138c891 100644 --- a/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h +++ b/third_party/blink/renderer/platform/bindings/dom_wrapper_world.h
@@ -151,12 +151,13 @@ static void AllWorldsInIsolate(v8::Isolate* isolate, HeapVector<Member<DOMWrapperWorld>>& worlds); - static DOMWrapperWorld& World(v8::Local<v8::Context> context) { - return ScriptState::From(context)->World(); + static DOMWrapperWorld& World(v8::Isolate* isolate, + v8::Local<v8::Context> context) { + return ScriptState::From(isolate, context)->World(); } static DOMWrapperWorld& Current(v8::Isolate* isolate) { - return World(isolate->GetCurrentContext()); + return World(isolate, isolate->GetCurrentContext()); } static DOMWrapperWorld& MainWorld(v8::Isolate* isolate);
diff --git a/third_party/blink/renderer/platform/bindings/multi_worlds_v8_reference.cc b/third_party/blink/renderer/platform/bindings/multi_worlds_v8_reference.cc index 409f8649..46c0c11 100644 --- a/third_party/blink/renderer/platform/bindings/multi_worlds_v8_reference.cc +++ b/third_party/blink/renderer/platform/bindings/multi_worlds_v8_reference.cc
@@ -14,7 +14,7 @@ : value_(isolate, value) { if (value->IsObject()) { script_state_ = - ScriptState::From(value.As<v8::Object>()->GetCreationContextChecked()); + ScriptState::ForRelevantRealm(isolate, value.As<v8::Object>()); } else { script_state_ = nullptr; }
diff --git a/third_party/blink/renderer/platform/bindings/script_regexp.cc b/third_party/blink/renderer/platform/bindings/script_regexp.cc index 5ad5a5f..614e32f3 100644 --- a/third_party/blink/renderer/platform/bindings/script_regexp.cc +++ b/third_party/blink/renderer/platform/bindings/script_regexp.cc
@@ -40,8 +40,10 @@ ScriptState* GetScriptState(v8::Isolate* isolate) { v8::HandleScope handle_scope(isolate); + // TODO(ishell): make EnsureScriptRegexpContext() return ScriptState* to + // avoid unnecessary hops script_state -> context -> script_state. return ScriptState::From( - V8PerIsolateData::From(isolate)->EnsureScriptRegexpContext()); + isolate, V8PerIsolateData::From(isolate)->EnsureScriptRegexpContext()); } } // namespace
diff --git a/third_party/blink/renderer/platform/bindings/script_state.h b/third_party/blink/renderer/platform/bindings/script_state.h index 5dcd351..e9b16a9 100644 --- a/third_party/blink/renderer/platform/bindings/script_state.h +++ b/third_party/blink/renderer/platform/bindings/script_state.h
@@ -132,40 +132,43 @@ virtual void Trace(Visitor*) const; - static ScriptState* Current(v8::Isolate* isolate) { // DEPRECATED - return From(isolate->GetCurrentContext()); + static ScriptState* ForCurrentRealm(v8::Isolate* isolate) { + DCHECK(isolate->InContext()); + return From(isolate, isolate->GetCurrentContext()); } static ScriptState* ForCurrentRealm( const v8::FunctionCallbackInfo<v8::Value>& info) { - return From(info.GetIsolate()->GetCurrentContext()); + return ForCurrentRealm(info.GetIsolate()); } static ScriptState* ForCurrentRealm( const v8::PropertyCallbackInfo<v8::Value>& info) { - return From(info.GetIsolate()->GetCurrentContext()); + return ForCurrentRealm(info.GetIsolate()); } - static ScriptState* ForRelevantRealm(v8::Local<v8::Object> object) { + static ScriptState* ForRelevantRealm(v8::Isolate* isolate, + v8::Local<v8::Object> object) { DCHECK(!object.IsEmpty()); ScriptState* script_state = static_cast<ScriptState*>( object->GetAlignedPointerFromEmbedderDataInCreationContext( - kV8ContextPerContextDataIndex)); + isolate, kV8ContextPerContextDataIndex)); // ScriptState::ForRelevantRealm() must be called only for objects having a // creation context while the context must have a valid embedder data in // the embedder field. - SECURITY_CHECK(script_state); + DCHECK(script_state); return script_state; } - static ScriptState* From(v8::Local<v8::Context> context) { + static ScriptState* From(v8::Isolate* isolate, + v8::Local<v8::Context> context) { DCHECK(!context.IsEmpty()); ScriptState* script_state = static_cast<ScriptState*>(context->GetAlignedPointerFromEmbedderData( - kV8ContextPerContextDataIndex)); + isolate, kV8ContextPerContextDataIndex)); // ScriptState::From() must not be called for a context that does not have // valid embedder data in the embedder field. - SECURITY_CHECK(script_state); + DCHECK(script_state); SECURITY_CHECK(script_state->context_ == context); return script_state; } @@ -177,7 +180,8 @@ // This is also called in some situations where DissociateContext() has // already been called and therefore the ScriptState pointer on the // v8::Context has already been nulled. - static ScriptState* MaybeFrom(v8::Local<v8::Context> context) { + static ScriptState* MaybeFrom(v8::Isolate* isolate, + v8::Local<v8::Context> context) { DCHECK(!context.IsEmpty()); if (context->GetNumberOfEmbedderDataFields() <= kV8ContextPerContextDataIndex) { @@ -185,7 +189,7 @@ } ScriptState* script_state = static_cast<ScriptState*>(context->GetAlignedPointerFromEmbedderData( - kV8ContextPerContextDataIndex)); + isolate, kV8ContextPerContextDataIndex)); SECURITY_CHECK(!script_state || script_state->context_ == context); return script_state; }
diff --git a/third_party/blink/renderer/platform/bindings/script_wrappable.cc b/third_party/blink/renderer/platform/bindings/script_wrappable.cc index 9733be3..98f2553 100644 --- a/third_party/blink/renderer/platform/bindings/script_wrappable.cc +++ b/third_party/blink/renderer/platform/bindings/script_wrappable.cc
@@ -37,7 +37,7 @@ } CHECK(!creation_context_object.IsEmpty()); ScriptState* script_state = - ScriptState::From(creation_context_object->GetCreationContextChecked()); + ScriptState::ForRelevantRealm(isolate, creation_context_object); return Wrap(script_state); }
diff --git a/third_party/blink/renderer/platform/bindings/v8_cross_origin_property_support.cc b/third_party/blink/renderer/platform/bindings/v8_cross_origin_property_support.cc index c42ff2f..f23b98bd 100644 --- a/third_party/blink/renderer/platform/bindings/v8_cross_origin_property_support.cc +++ b/third_party/blink/renderer/platform/bindings/v8_cross_origin_property_support.cc
@@ -18,7 +18,7 @@ int func_length, const WrapperTypeInfo* wrapper_type_info) { v8::Local<v8::Context> current_context = isolate->GetCurrentContext(); - ScriptState* script_state = ScriptState::From(current_context); + ScriptState* script_state = ScriptState::From(isolate, current_context); V8PerIsolateData* per_isolate_data = V8PerIsolateData::From(isolate); const void* callback_key = reinterpret_cast<const void*>(callback);
diff --git a/third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.cc b/third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.cc index 7bd17e53..f4fa5deb 100644 --- a/third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.cc +++ b/third_party/blink/renderer/platform/bindings/v8_dom_activity_logger.cc
@@ -95,9 +95,8 @@ return nullptr; v8::HandleScope handle_scope(isolate); - v8::Local<v8::Context> context = isolate->GetCurrentContext(); - - V8PerContextData* context_data = ScriptState::From(context)->PerContextData(); + V8PerContextData* context_data = + ScriptState::ForCurrentRealm(isolate)->PerContextData(); if (!context_data) return nullptr; @@ -109,7 +108,7 @@ if (!isolate->InContext()) return nullptr; - ScriptState* script_state = ScriptState::From(isolate->GetCurrentContext()); + ScriptState* script_state = ScriptState::ForCurrentRealm(isolate); if (!script_state->World().IsIsolatedWorld()) return nullptr;
diff --git a/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc b/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc index 624ac876..64ce134 100644 --- a/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc +++ b/third_party/blink/renderer/platform/bindings/v8_dom_wrapper.cc
@@ -45,7 +45,7 @@ const V8WrapperInstantiationScope scope(script_state); v8::Local<v8::Object> wrapper; - auto* per_context_data = V8PerContextData::From(scope.GetContext()); + auto* per_context_data = script_state->PerContextData(); if (LIKELY(per_context_data)) { wrapper = per_context_data->CreateWrapperFromCache(type); CHECK(!wrapper.IsEmpty()); @@ -55,7 +55,7 @@ // the correct settings. Should follow the same way as // V8PerContextData::createWrapperFromCache, though there is no need to // cache resulting objects or their constructors. - const DOMWrapperWorld& world = DOMWrapperWorld::World(scope.GetContext()); + const DOMWrapperWorld& world = script_state->World(); wrapper = type->GetV8ClassTemplate(script_state->GetIsolate(), world) .As<v8::FunctionTemplate>() ->InstanceTemplate()
diff --git a/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc b/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc index bbd988a9..887ec08 100644 --- a/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc +++ b/third_party/blink/renderer/platform/bindings/v8_per_context_data.cc
@@ -87,10 +87,6 @@ visitor->Trace(data_map_); } -V8PerContextData* V8PerContextData::From(v8::Local<v8::Context> context) { - return ScriptState::From(context)->PerContextData(); -} - v8::Local<v8::Object> V8PerContextData::CreateWrapperFromCacheSlowCase( const WrapperTypeInfo* type) { DCHECK(!wrapper_boilerplates_.Contains(type)); @@ -140,7 +136,7 @@ parent_interface_object = ConstructorForType(parent); } - const DOMWrapperWorld& world = DOMWrapperWorld::World(context); + const DOMWrapperWorld& world = DOMWrapperWorld::World(isolate_, context); v8::Local<v8::Function> interface_object = V8ObjectConstructor::CreateInterfaceObject( type, context, world, isolate_, parent_interface_object,
diff --git a/third_party/blink/renderer/platform/bindings/v8_per_context_data.h b/third_party/blink/renderer/platform/bindings/v8_per_context_data.h index e88dd46..6712fcc 100644 --- a/third_party/blink/renderer/platform/bindings/v8_per_context_data.h +++ b/third_party/blink/renderer/platform/bindings/v8_per_context_data.h
@@ -62,8 +62,6 @@ V8PerContextData(const V8PerContextData&) = delete; V8PerContextData& operator=(const V8PerContextData&) = delete; - static V8PerContextData* From(v8::Local<v8::Context>); - ~V8PerContextData(); void Trace(Visitor* visitor) const;
diff --git a/third_party/blink/renderer/platform/bindings/v8_set_return_value.cc b/third_party/blink/renderer/platform/bindings/v8_set_return_value.cc index 9313de8..1a8e824 100644 --- a/third_party/blink/renderer/platform/bindings/v8_set_return_value.cc +++ b/third_party/blink/renderer/platform/bindings/v8_set_return_value.cc
@@ -50,7 +50,7 @@ RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT( isolate, "Blink_GetInterfaceObjectExposedOnGlobal"); ScriptState* script_state = - ScriptState::From(creation_context->GetCreationContextChecked()); + ScriptState::ForRelevantRealm(isolate, creation_context); if (!script_state->ContextIsValid()) return v8::Undefined(isolate); @@ -64,19 +64,19 @@ RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT( isolate, "Blink_GetInterfaceObjectExposedOnGlobal"); ScriptState* script_state = - ScriptState::From(creation_context->GetCreationContextChecked()); + ScriptState::ForRelevantRealm(isolate, creation_context); if (!script_state->ContextIsValid()) return v8::Undefined(isolate); - v8::Context::Scope v8_context_scope(script_state->GetContext()); + v8::Local<v8::Context> v8_context = script_state->GetContext(); + v8::Context::Scope v8_context_scope(v8_context); v8::Local<v8::ObjectTemplate> namespace_template = wrapper_type_info->GetV8ClassTemplate(isolate, script_state->World()) .As<v8::ObjectTemplate>(); v8::Local<v8::Object> namespace_object = - namespace_template->NewInstance(script_state->GetContext()) - .ToLocalChecked(); + namespace_template->NewInstance(v8_context).ToLocalChecked(); wrapper_type_info->InstallConditionalFeatures( - script_state->GetContext(), script_state->World(), + v8_context, script_state->World(), v8::Local<v8::Object>(), // instance_object v8::Local<v8::Object>(), // prototype_object namespace_object, // interface_object
diff --git a/third_party/blink/renderer/platform/bindings/v8_set_return_value.h b/third_party/blink/renderer/platform/bindings/v8_set_return_value.h index 6b3b9db..056b954 100644 --- a/third_party/blink/renderer/platform/bindings/v8_set_return_value.h +++ b/third_party/blink/renderer/platform/bindings/v8_set_return_value.h
@@ -67,7 +67,7 @@ ScriptWrappable* wrappable, v8::Local<v8::Context> creation_context) { v8::Local<v8::Value> wrapper = - wrappable->Wrap(ScriptState::From(creation_context)); + wrappable->Wrap(ScriptState::From(info.GetIsolate(), creation_context)); info.GetReturnValue().SetNonEmpty(wrapper); } };
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource.cc b/third_party/blink/renderer/platform/graphics/canvas_resource.cc index 39fe0afa..f1e2949 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource.cc
@@ -372,10 +372,6 @@ return shared_bitmap_id_; } -bool CanvasResourceSharedBitmap::HasGpuMailbox() const { - return !shared_bitmap_id_.IsZero(); -} - void CanvasResourceSharedBitmap::TakeSkImage(sk_sp<SkImage> image) { SkImageInfo image_info = SkImageInfo::Make( SkISize::Make(Size().width(), Size().height()), GetSkColorInfo()); @@ -775,10 +771,6 @@ : empty_mailbox_; } -bool CanvasResourceRasterSharedImage::HasGpuMailbox() const { - return client_shared_image() != nullptr; -} - const gpu::SyncToken CanvasResourceRasterSharedImage::GetSyncToken() { if (is_cross_thread()) { // Sync token should be generated at Transfer time, which must always be
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource.h b/third_party/blink/renderer/platform/graphics/canvas_resource.h index 65bca06..5597ede1 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource.h
@@ -227,10 +227,6 @@ // for direct scanout by the display. virtual bool IsOverlayCandidate() const { return false; } - // Returns true if the resource is backed by memory that can be referenced - // using a mailbox. - virtual bool HasGpuMailbox() const = 0; - // Destroys the backing memory and any other references to it kept alive by // this object. This must be called from the same thread where the resource // was created. @@ -309,7 +305,6 @@ private: void TearDown() override; - bool HasGpuMailbox() const override; CanvasResourceSharedBitmap(const SkImageInfo&, base::WeakPtr<CanvasResourceProvider>, @@ -437,7 +432,6 @@ void Abandon() override; base::WeakPtr<WebGraphicsContext3DProviderWrapper> ContextProviderWrapper() const override; - bool HasGpuMailbox() const override; const gpu::SyncToken GetSyncToken() override; bool IsOverlayCandidate() const final { return is_overlay_candidate_; } @@ -551,7 +545,7 @@ bool IsOverlayCandidate() const final { return transferable_resource_.is_overlay_candidate; } - bool HasGpuMailbox() const override; + bool HasGpuMailbox() const; const gpu::SyncToken GetSyncToken() override; base::WeakPtr<WebGraphicsContext3DProviderWrapper> ContextProviderWrapper() const override; @@ -615,7 +609,7 @@ private: void TearDown() override; bool IsOverlayCandidate() const final { return true; } - bool HasGpuMailbox() const override; + bool HasGpuMailbox() const; const gpu::SyncToken GetSyncToken() override; base::WeakPtr<WebGraphicsContext3DProviderWrapper> ContextProviderWrapper() const override;
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc index 2a0c2b2..8ccdd80 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.cc
@@ -455,12 +455,13 @@ void CanvasResourceDispatcher::DidAllocateSharedBitmap( base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id) { + const viz::SharedBitmapId& id) { if (sink_) sink_->DidAllocateSharedBitmap(std::move(region), id); } -void CanvasResourceDispatcher::DidDeleteSharedBitmap(const gpu::Mailbox& id) { +void CanvasResourceDispatcher::DidDeleteSharedBitmap( + const viz::SharedBitmapId& id) { if (sink_) sink_->DidDeleteSharedBitmap(id); }
diff --git a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h index 75b0c90..62d752c 100644 --- a/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h +++ b/third_party/blink/renderer/platform/graphics/canvas_resource_dispatcher.h
@@ -108,8 +108,8 @@ void OnSurfaceEvicted(const viz::LocalSurfaceId& local_surface_id) final {} void DidAllocateSharedBitmap(base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id); - void DidDeleteSharedBitmap(const gpu::Mailbox& id); + const viz::SharedBitmapId& id); + void DidDeleteSharedBitmap(const viz::SharedBitmapId& id); void SetFilterQuality(cc::PaintFlags::FilterQuality filter_quality); void SetPlaceholderCanvasDispatcher(int placeholder_canvas_id);
diff --git a/third_party/blink/renderer/platform/graphics/test/mock_compositor_frame_sink.h b/third_party/blink/renderer/platform/graphics/test/mock_compositor_frame_sink.h index 727a246c..43046fc 100644 --- a/third_party/blink/renderer/platform/graphics/test/mock_compositor_frame_sink.h +++ b/third_party/blink/renderer/platform/graphics/test/mock_compositor_frame_sink.h
@@ -62,8 +62,9 @@ MOCK_METHOD1(SubmitCompositorFrameSync_, void(viz::CompositorFrame*)); MOCK_METHOD1(DidNotProduceFrame, void(const viz::BeginFrameAck&)); MOCK_METHOD2(DidAllocateSharedBitmap, - void(base::ReadOnlySharedMemoryRegion, const gpu::Mailbox&)); - MOCK_METHOD1(DidDeleteSharedBitmap, void(const gpu::Mailbox&)); + void(base::ReadOnlySharedMemoryRegion, + const viz::SharedBitmapId&)); + MOCK_METHOD1(DidDeleteSharedBitmap, void(const viz::SharedBitmapId&)); MOCK_METHOD1(SetPreferredFrameInterval, void(base::TimeDelta)); MOCK_METHOD1(InitializeCompositorFrameSinkType, void(viz::mojom::CompositorFrameSinkType));
diff --git a/third_party/blink/renderer/platform/graphics/test/mock_frame_sink_bundle.h b/third_party/blink/renderer/platform/graphics/test/mock_frame_sink_bundle.h index 59d405f..dd45d6ed 100644 --- a/third_party/blink/renderer/platform/graphics/test/mock_frame_sink_bundle.h +++ b/third_party/blink/renderer/platform/graphics/test/mock_frame_sink_bundle.h
@@ -45,7 +45,7 @@ MOCK_METHOD3(DidAllocateSharedBitmap, void(uint32_t, base::ReadOnlySharedMemoryRegion, - const gpu::Mailbox&)); + const viz::SharedBitmapId&)); #if BUILDFLAG(IS_ANDROID) MOCK_METHOD2(SetThreadIds, void(uint32_t, const WTF::Vector<int32_t>&)); #endif
diff --git a/third_party/blink/renderer/platform/graphics/video_frame_sink_bundle.cc b/third_party/blink/renderer/platform/graphics/video_frame_sink_bundle.cc index 5de8add..de88536f 100644 --- a/third_party/blink/renderer/platform/graphics/video_frame_sink_bundle.cc +++ b/third_party/blink/renderer/platform/graphics/video_frame_sink_bundle.cc
@@ -200,12 +200,13 @@ void VideoFrameSinkBundle::DidAllocateSharedBitmap( uint32_t sink_id, base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id) { + const viz::SharedBitmapId& id) { bundle_->DidAllocateSharedBitmap(sink_id, std::move(region), id); } -void VideoFrameSinkBundle::DidDeleteSharedBitmap(uint32_t sink_id, - const gpu::Mailbox& id) { +void VideoFrameSinkBundle::DidDeleteSharedBitmap( + uint32_t sink_id, + const viz::SharedBitmapId& id) { // These messages are not urgent, but they must be well-ordered with respect // to frame submissions. Hence they are batched in the same queue and // flushed whenever any other messages are fit to flush.
diff --git a/third_party/blink/renderer/platform/graphics/video_frame_sink_bundle.h b/third_party/blink/renderer/platform/graphics/video_frame_sink_bundle.h index 6e58c1e..9f661b05 100644 --- a/third_party/blink/renderer/platform/graphics/video_frame_sink_bundle.h +++ b/third_party/blink/renderer/platform/graphics/video_frame_sink_bundle.h
@@ -125,8 +125,8 @@ void DidNotProduceFrame(uint32_t sink_id, const viz::BeginFrameAck& ack); void DidAllocateSharedBitmap(uint32_t sink_id, base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id); - void DidDeleteSharedBitmap(uint32_t sink_id, const gpu::Mailbox& id); + const viz::SharedBitmapId& id); + void DidDeleteSharedBitmap(uint32_t sink_id, const viz::SharedBitmapId& id); #if BUILDFLAG(IS_ANDROID) void SetThreadIds(uint32_t sink_id, const WTF::Vector<int32_t>& thread_ids); #endif
diff --git a/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc b/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc index 48919380..318abc438 100644 --- a/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc +++ b/third_party/blink/renderer/platform/graphics/video_frame_submitter.cc
@@ -139,7 +139,7 @@ } void DidAllocateSharedBitmap(base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id) override { + const viz::SharedBitmapId& id) override { if (!bundle_) { return; } @@ -147,7 +147,7 @@ std::move(region), id); } - void DidDeleteSharedBitmap(const gpu::Mailbox& id) override { + void DidDeleteSharedBitmap(const viz::SharedBitmapId& id) override { if (!bundle_) { return; }
diff --git a/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc b/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc index bf0d86e..4c0b153 100644 --- a/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc +++ b/third_party/blink/renderer/platform/graphics/video_frame_submitter_test.cc
@@ -117,8 +117,8 @@ MOCK_METHOD1(DidNotProduceFrame, void(const viz::BeginFrameAck&)); MOCK_METHOD2(DidAllocateSharedBitmap, void(base::ReadOnlySharedMemoryRegion region, - const gpu::Mailbox& id)); - MOCK_METHOD1(DidDeleteSharedBitmap, void(const gpu::Mailbox& id)); + const viz::SharedBitmapId& id)); + MOCK_METHOD1(DidDeleteSharedBitmap, void(const viz::SharedBitmapId& id)); MOCK_METHOD1(InitializeCompositorFrameSinkType, void(viz::mojom::CompositorFrameSinkType)); MOCK_METHOD1(BindLayerContext,
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 9e21e8d..85d8484 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -2199,7 +2199,6 @@ { name: "LayoutBlockButton", depends_on: ["LayoutBaselineFix"], - status: "stable", }, { name: "LayoutFlexNewRowAlgorithmV3",
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 6a00a6de..1897e46 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1626,6 +1626,8 @@ crbug.com/1223214 external/wpt/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/legend-tall.html [ Failure ] crbug.com/1172023 external/wpt/html/rendering/non-replaced-elements/tables/table-border-3s.html [ Failure ] crbug.com/1172023 external/wpt/html/rendering/non-replaced-elements/tables/table-border-3q.html [ Failure ] +crbug.com/962936 external/wpt/html/rendering/widgets/button-layout/anonymous-button-content-box.html [ Failure ] +crbug.com/962936 external/wpt/html/rendering/widgets/button-layout/inline-level.html [ Failure ] crbug.com/707210 external/wpt/html/rendering/non-replaced-elements/the-page/body-margin-1i.html [ Failure ] crbug.com/707210 external/wpt/html/rendering/non-replaced-elements/the-page/body-margin-1j.html [ Failure ] crbug.com/707210 external/wpt/html/rendering/non-replaced-elements/the-page/body-margin-1k.html [ Failure ]
diff --git a/third_party/blink/web_tests/external/wpt/css/css-flexbox/parsing/flex-shorthand.html b/third_party/blink/web_tests/external/wpt/css/css-flexbox/parsing/flex-shorthand.html index 1d74df80..d229579 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-flexbox/parsing/flex-shorthand.html +++ b/third_party/blink/web_tests/external/wpt/css/css-flexbox/parsing/flex-shorthand.html
@@ -64,6 +64,12 @@ 'flex-shrink': '0', 'flex-basis': 'max-content' }); + +test_shorthand_value('flex', 'auto 1 2', { + 'flex-grow': '1', + 'flex-shrink': '2', + 'flex-basis': 'auto' +}); </script> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/fledge_http_server_util.py b/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/fledge_http_server_util.py index 162c93e..92733eed 100644 --- a/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/fledge_http_server_util.py +++ b/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/fledge_http_server_util.py
@@ -1,5 +1,6 @@ """Utility functions shared across multiple endpoints.""" - +from collections import namedtuple +from urllib.parse import unquote_plus, urlparse def headers_to_ascii(headers): """Converts a header map with binary values to one with ASCII values. @@ -65,3 +66,81 @@ response.status = (204, b"No Content") return True + +def decode_trusted_scoring_signals_params(request): + """Decodes query parameters to trusted query params handler. + + Args: + request: the wptserve Request that was passed to main + + If successful, returns a named tuple TrustedScoringSignalsParams decoding the + various expected query fields, as a hostname, plus a field urlLists which is a list of + {type: <render URL type>, urls: <render URL list>} pairs, where <render URL type> is + one of the two render URL dictionary keys used in the response ("renderURLs" or + "adComponentRenderURLs"). May be of length 1 or 2, depending on whether there + are any component URLs. + + On failure, throws a ValueError with a message. + """ + TrustedScoringSignalsParams = namedtuple( + 'TrustedScoringSignalsParams', ['hostname', 'urlLists']) + + hostname = None + renderUrls = None + adComponentRenderURLs = None + urlLists = [] + + # Manually parse query params. Can't use request.GET because it unescapes as well as splitting, + # and commas mean very different things from escaped commas. + for param in request.url_parts.query.split("&"): + pair = param.split("=", 1) + if len(pair) != 2: + raise ValueError("Bad query parameter: " + param) + # Browsers should escape query params consistently. + if "%20" in pair[1]: + raise ValueError("Query parameter should escape using '+': " + param) + + # Hostname can't be empty. The empty string can be a key or interest group name, though. + if pair[0] == "hostname" and hostname == None and len(pair[1]) > 0: + hostname = pair[1] + continue + if pair[0] == "renderUrls" and renderUrls == None: + renderUrls = list(map(unquote_plus, pair[1].split(","))) + urlLists.append({"type":"renderURLs", "urls":renderUrls}) + continue + if pair[0] == "adComponentRenderUrls" and adComponentRenderURLs == None: + adComponentRenderURLs = list(map(unquote_plus, pair[1].split(","))) + urlLists.append({"type":"adComponentRenderURLs", "urls":adComponentRenderURLs}) + continue + raise ValueError("Unexpected query parameter: " + param) + + # "hostname" and "renderUrls" are mandatory. + if not hostname: + raise ValueError("hostname missing") + if not renderUrls: + raise ValueError("renderUrls missing") + + return TrustedScoringSignalsParams(hostname, urlLists) + +def decode_render_url_signals_params(renderUrl): + """Decodes signalsParams field encoded inside a renderURL. + + Args: renderUrl to extract signalsParams from. + + Returns an array of fields in signal params string. + """ + signalsParams = None + for param in urlparse(renderUrl).query.split("&"): + pair = param.split("=", 1) + if len(pair) != 2: + continue + if pair[0] == "signalsParams": + if signalsParams != None: + raise ValueError("renderUrl has multiple signalsParams: " + renderUrl) + signalsParams = pair[1] + + if signalsParams is None: + return [] + + signalsParams = unquote_plus(signalsParams) + return signalsParams.split(",")
diff --git a/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/request-tracker.py b/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/request-tracker.py index 3514741..dea8427 100644 --- a/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/request-tracker.py +++ b/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/request-tracker.py
@@ -36,6 +36,29 @@ dispatch = request.GET.first(b"dispatch", None) uuid = request.GET.first(b"uuid", None) + # If we're used as a trusted scoring signals handler, our params are + # smuggled in via renderURLs. We won't have dispatch and uuid provided + # directly then. + if dispatch is None and uuid is None: + try: + signals_params = fledge_http_server_util.decode_trusted_scoring_signals_params(request) + for urlList in signals_params.urlLists: + for renderUrl in urlList["urls"]: + try: + signalsParams = fledge_http_server_util.decode_render_url_signals_params(renderUrl) + except ValueError as ve: + return simple_response(request, response, 500, + b"InternalError", str(ve)) + for signalsParam in signalsParams: + if signalsParam.startswith("dispatch:"): + dispatch = signalsParam.split(':', 1)[1].encode("utf-8") + elif signalsParam.startswith("uuid:"): + uuid = signalsParam.split(':', 1)[1].encode("utf-8") + except ValueError: + # It doesn't look like a trusted scoring signals request, so + # never mind. + pass + if not uuid or not dispatch: return simple_response(request, response, 404, b"Not found", b"Invalid query parameters")
diff --git a/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/trusted-scoring-signals.py b/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/trusted-scoring-signals.py index fd0a81f..934d2e9 100644 --- a/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/trusted-scoring-signals.py +++ b/third_party/blink/web_tests/external/wpt/fledge/tentative/resources/trusted-scoring-signals.py
@@ -1,5 +1,4 @@ import json -from urllib.parse import unquote_plus, urlparse from fledge.tentative.resources import fledge_http_server_util @@ -11,44 +10,10 @@ # each affect either the value associated with the renderUrl, or the # response as a whole. def main(request, response): - hostname = None - renderUrls = None - adComponentRenderURLs = None - # List of {type: <render URL type>, urls: <render URL list>} pairs, where <render URL type> is - # one of the two render URL dictionary keys used in the response ("renderURLs" or - # "adComponentRenderURLs"). May be of length 1 or 2, depending on whether there - # are any component URLs. - urlLists = [] - - # Manually parse query params. Can't use request.GET because it unescapes as well as splitting, - # and commas mean very different things from escaped commas. - for param in request.url_parts.query.split("&"): - pair = param.split("=", 1) - if len(pair) != 2: - return fail(response, "Bad query parameter: " + param) - # Browsers should escape query params consistently. - if "%20" in pair[1]: - return fail(response, "Query parameter should escape using '+': " + param) - - # Hostname can't be empty. The empty string can be a key or interest group name, though. - if pair[0] == "hostname" and hostname == None and len(pair[1]) > 0: - hostname = pair[1] - continue - if pair[0] == "renderUrls" and renderUrls == None: - renderUrls = list(map(unquote_plus, pair[1].split(","))) - urlLists.append({"type":"renderURLs", "urls":renderUrls}) - continue - if pair[0] == "adComponentRenderUrls" and adComponentRenderURLs == None: - adComponentRenderURLs = list(map(unquote_plus, pair[1].split(","))) - urlLists.append({"type":"adComponentRenderURLs", "urls":adComponentRenderURLs}) - continue - return fail(response, "Unexpected query parameter: " + param) - - # "hostname" and "renderUrls" are mandatory. - if not hostname: - return fail(response, "hostname missing") - if not renderUrls: - return fail(response, "renderUrls missing") + try: + params = fledge_http_server_util.decode_trusted_scoring_signals_params(request) + except ValueError as ve: + return fail(response, str(ve)) response.status = (200, b"OK") @@ -63,70 +28,64 @@ adAuctionAllowed = "true" dataVersion = None cors = False - for urlList in urlLists: + for urlList in params.urlLists: for renderUrl in urlList["urls"]: value = "default value" addValue = True - signalsParams = None - for param in urlparse(renderUrl).query.split("&"): - pair = param.split("=", 1) - if len(pair) != 2: - continue - if pair[0] == "signalsParams": - if signalsParams != None: - return fail(response, "renderUrl has multiple signalsParams: " + renderUrl) - signalsParams = pair[1] - if signalsParams != None: - signalsParams = unquote_plus(signalsParams) - for signalsParam in signalsParams.split(","): - if signalsParam == "close-connection": - # Close connection without writing anything, to simulate a - # network error. The write call is needed to avoid writing the - # default headers. - response.writer.write("") - response.close_connection = True - return - elif signalsParam.startswith("replace-body:"): - # Replace entire response body. Continue to run through other - # renderUrls, to allow them to modify request headers. - body = signalsParam.split(':', 1)[1] - elif signalsParam.startswith("data-version:"): - dataVersion = signalsParam.split(':', 1)[1] - elif signalsParam == "http-error": - response.status = (404, b"Not found") - elif signalsParam == "no-content-type": - contentType = None - elif signalsParam == "wrong-content-type": - contentType = 'text/plain' - elif signalsParam == "bad-ad-auction-allowed": - adAuctionAllowed = "sometimes" - elif signalsParam == "ad-auction-not-allowed": - adAuctionAllowed = "false" - elif signalsParam == "no-ad-auction-allow": - adAuctionAllowed = None - elif signalsParam == "wrong-url": - renderUrl = "https://wrong-url.test/" - elif signalsParam == "no-value": - addValue = False - elif signalsParam == "null-value": - value = None - elif signalsParam == "num-value": - value = 1 - elif signalsParam == "string-value": - value = "1" - elif signalsParam == "array-value": - value = [1, "foo", None] - elif signalsParam == "object-value": - value = {"a":"b", "c":["d"]} - elif signalsParam == "hostname": - value = request.GET.first(b"hostname", b"not-found").decode("ASCII") - elif signalsParam == "headers": - value = fledge_http_server_util.headers_to_ascii(request.headers) - elif signalsParam == "url": - value = request.url - elif signalsParam == "cors": - cors = True + try: + signalsParams = fledge_http_server_util.decode_render_url_signals_params(renderUrl) + except ValueError as ve: + return fail(response, str(ve)) + + for signalsParam in signalsParams: + if signalsParam == "close-connection": + # Close connection without writing anything, to simulate a + # network error. The write call is needed to avoid writing the + # default headers. + response.writer.write("") + response.close_connection = True + return + elif signalsParam.startswith("replace-body:"): + # Replace entire response body. Continue to run through other + # renderUrls, to allow them to modify request headers. + body = signalsParam.split(':', 1)[1] + elif signalsParam.startswith("data-version:"): + dataVersion = signalsParam.split(':', 1)[1] + elif signalsParam == "http-error": + response.status = (404, b"Not found") + elif signalsParam == "no-content-type": + contentType = None + elif signalsParam == "wrong-content-type": + contentType = 'text/plain' + elif signalsParam == "bad-ad-auction-allowed": + adAuctionAllowed = "sometimes" + elif signalsParam == "ad-auction-not-allowed": + adAuctionAllowed = "false" + elif signalsParam == "no-ad-auction-allow": + adAuctionAllowed = None + elif signalsParam == "wrong-url": + renderUrl = "https://wrong-url.test/" + elif signalsParam == "no-value": + addValue = False + elif signalsParam == "null-value": + value = None + elif signalsParam == "num-value": + value = 1 + elif signalsParam == "string-value": + value = "1" + elif signalsParam == "array-value": + value = [1, "foo", None] + elif signalsParam == "object-value": + value = {"a":"b", "c":["d"]} + elif signalsParam == "hostname": + value = params.hostname + elif signalsParam == "headers": + value = fledge_http_server_util.headers_to_ascii(request.headers) + elif signalsParam == "url": + value = request.url + elif signalsParam == "cors": + cors = True if addValue: if urlList["type"] not in responseBody: responseBody[urlList["type"]] = {}
diff --git a/third_party/blink/web_tests/external/wpt/fledge/tentative/trusted-scoring-signals.https.window.js b/third_party/blink/web_tests/external/wpt/fledge/tentative/trusted-scoring-signals.https.window.js index 4dd4f96..46570da 100644 --- a/third_party/blink/web_tests/external/wpt/fledge/tentative/trusted-scoring-signals.https.window.js +++ b/third_party/blink/web_tests/external/wpt/fledge/tentative/trusted-scoring-signals.https.window.js
@@ -12,7 +12,8 @@ // META: variant=?31-35 // META: variant=?36-40 // META: variant=?41-45 -// META: variant=?45-last +// META: variant=?45-50 +// META: variant=?50-last "use strict"; @@ -35,14 +36,11 @@ createDecisionScriptURL(uuid, { scoreAd: `if (!(${scoreAdCheck})) throw "error";`, ...decisionScriptParamOverrides})}; - await joinGroupAndRunBasicFledgeTestExpectingWinner( - test, - { - uuid: uuid, - interestGroupOverrides: {ads: [{ renderURL: renderURL }], - ...additionalInterestGroupOverrides}, - auctionConfigOverrides: auctionConfigOverrides - }); + await joinInterestGroup(test, uuid, + {ads: [{ renderURL: renderURL }], + ...additionalInterestGroupOverrides}); + return await runBasicFledgeTestExpectingWinner( + test, uuid, auctionConfigOverrides); } // Much like runTrustedScoringSignalsTest, but runs auctions through reporting @@ -344,6 +342,35 @@ subsetTest(promise_test, async test => { const uuid = generateUuid(test); + const sellerReportURL = createSellerReportURL(uuid); + const renderURL = createRenderURL(uuid, /*script=*/null, + /*signalsParam=*/`string-value,data-version:3,uuid:${uuid},dispatch:track_get`); + // Use the request tracker for trusted scoring signals, to have it + // record whether they got fetched or not. + const crossOriginRequestTrackerURL = OTHER_ORIGIN1 + BASE_PATH + + 'resources/request-tracker.py'; + + let combinedTrustedSignalsURL = new URL(crossOriginRequestTrackerURL); + combinedTrustedSignalsURL.search = + `hostname=${window.location.hostname}&renderUrls=${encodeURIComponent(renderURL)}` + + let result = await runTrustedScoringSignalsTest( + test, uuid, renderURL, + `trustedScoringSignals === null && + !('dataVersion' in browserSignals) && + crossOriginTrustedScoringSignals === null && + !('crossOriginDataVersion' in browserSignals)`, + /*additionalInterestGroupOverrides=*/ {}, + crossOriginRequestTrackerURL, + {permitCrossOriginTrustedSignals: `"${OTHER_ORIGIN1}"`, + reportResult: `sendReportTo("${sellerReportURL}")`}); + createAndNavigateFencedFrame(test, result); + await waitForObservedRequests( + uuid, [combinedTrustedSignalsURL.href, createBidderReportURL(uuid), sellerReportURL]); +}, 'Cross-origin trusted scoring signals w/o CORS authorization sends request.'); + +subsetTest(promise_test, async test => { + const uuid = generateUuid(test); const renderURL = createRenderURL(uuid, /*script=*/null, /*signalsParam=*/'string-value,data-version:3, cors'); await runTrustedScoringSignalsTest( @@ -372,6 +399,31 @@ `"${OTHER_ORIGIN2}", "${window.location.origin}"`}); }, 'Cross-origin trusted scoring signals with wrong script allow header.'); +subsetTest(promise_test, async test => { + const uuid = generateUuid(test); + const sellerReportURL = createSellerReportURL(uuid); + const renderURL = createRenderURL(uuid, /*script=*/null, + /*signalsParam=*/`string-value,data-version:3,uuid:${uuid},dispatch:track_get`); + // Use the request tracker for trusted scoring signals, to have it + // record whether they got fetched or not. + const crossOriginRequestTrackerURL = OTHER_ORIGIN1 + BASE_PATH + + 'resources/request-tracker.py'; + let result = await runTrustedScoringSignalsTest( + test, uuid, renderURL, + `trustedScoringSignals === null && + !('dataVersion' in browserSignals) && + crossOriginTrustedScoringSignals === null && + !('crossOriginDataVersion' in browserSignals)`, + /*additionalInterestGroupOverrides=*/ {}, + crossOriginRequestTrackerURL, + {permitCrossOriginTrustedSignals: + `"${OTHER_ORIGIN2}", "${window.location.origin}"`, + reportResult: `sendReportTo("${sellerReportURL}")`}); + createAndNavigateFencedFrame(test, result); + await waitForObservedRequests(uuid, + [createBidderReportURL(uuid), sellerReportURL]); +}, 'Cross-origin trusted scoring signals with wrong script allow header not fetched.'); + ///////////////////////////////////////////////////////////////////////////// // Data-Version tests /////////////////////////////////////////////////////////////////////////////
diff --git a/third_party/blink/web_tests/external/wpt/webnn/validation_tests/pooling.https.any.js b/third_party/blink/web_tests/external/wpt/webnn/validation_tests/pooling.https.any.js index e8add05..08a78f2 100644 --- a/third_party/blink/web_tests/external/wpt/webnn/validation_tests/pooling.https.any.js +++ b/third_party/blink/web_tests/external/wpt/webnn/validation_tests/pooling.https.any.js
@@ -11,7 +11,6 @@ operatorName, {dataType: 'float32', dimensions: [2, 2, 2, 2]}); }); - const tests = [ { name: 'Test pool2d with default options.', @@ -20,11 +19,11 @@ }, { name: 'Test pool2d with windowDimensions', - input: {dataType: 'float32', dimensions: [1, 3, 4, 4]}, + input: {dataType: 'float16', dimensions: [1, 3, 4, 4]}, options: { windowDimensions: [3, 3], }, - output: {dataType: 'float32', dimensions: [1, 3, 2, 2]} + output: {dataType: 'float16', dimensions: [1, 3, 2, 2]} }, { name: 'Test pool2d with padding.', @@ -37,12 +36,12 @@ }, { name: 'Test pool2d with strides.', - input: {dataType: 'float32', dimensions: [1, 3, 5, 5]}, + input: {dataType: 'float16', dimensions: [1, 3, 5, 5]}, options: { windowDimensions: [2, 2], strides: [2, 2], }, - output: {dataType: 'float32', dimensions: [1, 3, 2, 2]} + output: {dataType: 'float16', dimensions: [1, 3, 2, 2]} }, { name: 'Test pool2d with strides and padding.', @@ -77,14 +76,14 @@ }, { name: 'Test pool2d with strides, padding and roundingType="ceil".', - input: {dataType: 'float32', dimensions: [1, 3, 7, 7]}, + input: {dataType: 'float16', dimensions: [1, 3, 7, 7]}, options: { windowDimensions: [4, 4], padding: [1, 1, 1, 1], strides: [2, 2], roundingType: 'ceil', }, - output: {dataType: 'float32', dimensions: [1, 3, 4, 4]} + output: {dataType: 'float16', dimensions: [1, 3, 4, 4]} }, { name: 'Test pool2d with explicit outputSizes ignored roundingType', @@ -131,12 +130,12 @@ }, { name: 'Test pool2d with layout="nhwc".', - input: {dataType: 'float32', dimensions: [1, 5, 5, 2]}, + input: {dataType: 'float16', dimensions: [1, 5, 5, 2]}, options: { windowDimensions: [3, 3], layout: 'nhwc', }, - output: {dataType: 'float32', dimensions: [1, 3, 3, 2]} + output: {dataType: 'float16', dimensions: [1, 3, 3, 2]} }, { name: 'Throw if the input is not a 4-D tensor.', @@ -273,3 +272,24 @@ } }); }, test.name)); + +['int32', 'uint32', 'int8', 'uint8'].forEach( + dataType => promise_test(async t => { + const input = builder.input( + 'input', {dataType: dataType, dimensions: [1, 3, 4, 4]}); + const output = builder.maxPool2d(input); + assert_equals(output.dataType(), dataType); + assert_array_equals(output.shape(), [1, 3, 1, 1]); + }, `[maxPool2d] Test maxPool2d with data type ${dataType}`)); + +promise_test(async t => { + const input = + builder.input('input', {dataType: 'int64', dimensions: [1, 2, 3, 3]}); + assert_throws_js(TypeError, () => builder.averagePool2d(input)); +}, '[averagePool2d] Throw if the input data type is not floating point'); + +promise_test(async t => { + const input = + builder.input('input', {dataType: 'uint8', dimensions: [1, 2, 4, 4]}); + assert_throws_js(TypeError, () => builder.l2Pool2d(input)); +}, '[l2Pool2d] Throw if the input data type is not floating point');
diff --git a/third_party/blink/web_tests/flag-specific/skia-vulkan-swiftshader/css3/flexbox/button-expected.png b/third_party/blink/web_tests/flag-specific/skia-vulkan-swiftshader/css3/flexbox/button-expected.png index 366af47..2696261 100644 --- a/third_party/blink/web_tests/flag-specific/skia-vulkan-swiftshader/css3/flexbox/button-expected.png +++ b/third_party/blink/web_tests/flag-specific/skia-vulkan-swiftshader/css3/flexbox/button-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-expected.txt index 0dcd6aa..baa936a 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-flex-expected.txt
@@ -304,7 +304,7 @@ "isKeyboardFocusable": true, "accessibleName": "click", "accessibleRole": "button", - "layoutObjectName": "LayoutNGBlockFlow", + "layoutObjectName": "LayoutButton", "showAccessibilityInfo": true } }
diff --git a/third_party/blink/web_tests/paint/invalidation/button-inner-no-repaint.html b/third_party/blink/web_tests/paint/invalidation/button-inner-no-repaint.html index 84ce28e..eb45682 100644 --- a/third_party/blink/web_tests/paint/invalidation/button-inner-no-repaint.html +++ b/third_party/blink/web_tests/paint/invalidation/button-inner-no-repaint.html
@@ -13,4 +13,4 @@ height: 100px; } </style> -<button><div>Should not repaint on style change that doesn't change visual.<br></div></button> +<button>Should not repaint on style change that doesn't change visual.<br></button>
diff --git a/third_party/blink/web_tests/platform/linux/css3/flexbox/button-expected.png b/third_party/blink/web_tests/platform/linux/css3/flexbox/button-expected.png index 7c97bc5a..23e925a0 100644 --- a/third_party/blink/web_tests/platform/linux/css3/flexbox/button-expected.png +++ b/third_party/blink/web_tests/platform/linux/css3/flexbox/button-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/fast/forms/control-clip-expected.png b/third_party/blink/web_tests/platform/linux/fast/forms/control-clip-expected.png index 3667b7a4..f8f7020 100644 --- a/third_party/blink/web_tests/platform/linux/fast/forms/control-clip-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/forms/control-clip-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/linux/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt b/third_party/blink/web_tests/platform/linux/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt index c058d276..e899630 100644 --- a/third_party/blink/web_tests/platform/linux/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt +++ b/third_party/blink/web_tests/platform/linux/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt
@@ -92,7 +92,7 @@ "isKeyboardFocusable": true, "accessibleName": "click", "accessibleRole": "button", - "layoutObjectName": "LayoutNGBlockFlow", + "layoutObjectName": "LayoutButton", "showAccessibilityInfo": true } }
diff --git a/third_party/blink/web_tests/platform/mac/compositing/contents-opaque/control-layer-expected.txt b/third_party/blink/web_tests/platform/mac/compositing/contents-opaque/control-layer-expected.txt index cc32310..89e35b6 100644 --- a/third_party/blink/web_tests/platform/mac/compositing/contents-opaque/control-layer-expected.txt +++ b/third_party/blink/web_tests/platform/mac/compositing/contents-opaque/control-layer-expected.txt
@@ -7,7 +7,7 @@ "backgroundColor": "#FFFFFF" }, { - "name": "LayoutNGBlockFlow (inline, children-inline) INPUT id='control' class='composited'", + "name": "LayoutButton (inline) INPUT id='control' class='composited'", "bounds": [130, 21], "contentsOpaqueForText": true, "backgroundColor": "#EFEFEF",
diff --git a/third_party/blink/web_tests/platform/mac/css3/flexbox/button-expected.png b/third_party/blink/web_tests/platform/mac/css3/flexbox/button-expected.png index 78b9144..e4f86a34 100644 --- a/third_party/blink/web_tests/platform/mac/css3/flexbox/button-expected.png +++ b/third_party/blink/web_tests/platform/mac/css3/flexbox/button-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/forms/control-clip-expected.png b/third_party/blink/web_tests/platform/mac/fast/forms/control-clip-expected.png index 572192fe..9e12245 100644 --- a/third_party/blink/web_tests/platform/mac/fast/forms/control-clip-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/forms/control-clip-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt b/third_party/blink/web_tests/platform/mac/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt index fe045e5f..24974e9 100644 --- a/third_party/blink/web_tests/platform/mac/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt +++ b/third_party/blink/web_tests/platform/mac/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt
@@ -92,7 +92,7 @@ "isKeyboardFocusable": true, "accessibleName": "click", "accessibleRole": "button", - "layoutObjectName": "LayoutNGBlockFlow", + "layoutObjectName": "LayoutButton", "showAccessibilityInfo": true } }
diff --git a/third_party/blink/web_tests/platform/win/compositing/contents-opaque/control-layer-expected.txt b/third_party/blink/web_tests/platform/win/compositing/contents-opaque/control-layer-expected.txt index 27fa436..22c2911c 100644 --- a/third_party/blink/web_tests/platform/win/compositing/contents-opaque/control-layer-expected.txt +++ b/third_party/blink/web_tests/platform/win/compositing/contents-opaque/control-layer-expected.txt
@@ -7,7 +7,7 @@ "backgroundColor": "#FFFFFF" }, { - "name": "LayoutNGBlockFlow (inline, children-inline) INPUT id='control' class='composited'", + "name": "LayoutButton (inline) INPUT id='control' class='composited'", "bounds": [127, 22], "contentsOpaqueForText": true, "backgroundColor": "#EFEFEF",
diff --git a/third_party/blink/web_tests/platform/win/css3/flexbox/button-expected.png b/third_party/blink/web_tests/platform/win/css3/flexbox/button-expected.png index c6a41517..d7586f2 100644 --- a/third_party/blink/web_tests/platform/win/css3/flexbox/button-expected.png +++ b/third_party/blink/web_tests/platform/win/css3/flexbox/button-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/forms/control-clip-expected.png b/third_party/blink/web_tests/platform/win/fast/forms/control-clip-expected.png index 9ccc59c..e0f9298 100644 --- a/third_party/blink/web_tests/platform/win/fast/forms/control-clip-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/forms/control-clip-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt b/third_party/blink/web_tests/platform/win/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt index 0bbcd62..5ee08bb0 100644 --- a/third_party/blink/web_tests/platform/win/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt +++ b/third_party/blink/web_tests/platform/win/http/tests/devtools/elements/highlight/highlight-node-a11y-expected.txt
@@ -92,7 +92,7 @@ "isKeyboardFocusable": true, "accessibleName": "click", "accessibleRole": "button", - "layoutObjectName": "LayoutNGBlockFlow", + "layoutObjectName": "LayoutButton", "showAccessibilityInfo": true } }
diff --git a/third_party/chromium-variations b/third_party/chromium-variations index a347efc..4f6faff 160000 --- a/third_party/chromium-variations +++ b/third_party/chromium-variations
@@ -1 +1 @@ -Subproject commit a347efc4c1f5abb194a8b4e9b26d374a86af3050 +Subproject commit 4f6faffd4655ac33ce079be7e4e8b7b5eb5debb7
diff --git a/third_party/dawn b/third_party/dawn index ddc1dd3..e201fce 160000 --- a/third_party/dawn +++ b/third_party/dawn
@@ -1 +1 @@ -Subproject commit ddc1dd344b11360f51b621506a363f297ae2aa8c +Subproject commit e201fce6bc0bb4626e8d520857df8c21f9459826
diff --git a/third_party/devtools-frontend-internal b/third_party/devtools-frontend-internal index ab637d2..8bfede2 160000 --- a/third_party/devtools-frontend-internal +++ b/third_party/devtools-frontend-internal
@@ -1 +1 @@ -Subproject commit ab637d2bb43890b3a3fd4d3f83317e6e3bed42a8 +Subproject commit 8bfede243c85f66eb062119d3ac9b1bd54d92202
diff --git a/third_party/devtools-frontend/src b/third_party/devtools-frontend/src index fb2f1f8..9f8a3d4 160000 --- a/third_party/devtools-frontend/src +++ b/third_party/devtools-frontend/src
@@ -1 +1 @@ -Subproject commit fb2f1f877cd5e7c86bcbf681c271bb3171121ca2 +Subproject commit 9f8a3d4c3d9f00977d355782005554a096b3d1d1
diff --git a/third_party/r8/README.chromium b/third_party/r8/README.chromium index d2b27cc7..96902c1 100644 --- a/third_party/r8/README.chromium +++ b/third_party/r8/README.chromium
@@ -110,8 +110,8 @@ You can run this script like so: ``` cd $R8_REPO -git bisect start <known_good_rev> <known_bad_rev> -git bisect run <path_to_script.sh> +git bisect start <known_bad_rev> <known_good_rev> +git bisect run bash <path_to_script.sh> ``` Tip: When you are done, you can delete the r8 jar and gclient sync to get back to ToT R8. @@ -126,4 +126,4 @@ # To public APK: tools/binary_size/print_trybot_sizes.py --grep "Roll R8" -n 20 # To internal APK: -tools/binary_size/print_trybot_sizes.py --grep "Roll R8" -n 20 --internal \ No newline at end of file +tools/binary_size/print_trybot_sizes.py --grep "Roll R8" -n 20 --internal
diff --git a/third_party/skia b/third_party/skia index 6a50e52..bea3840 160000 --- a/third_party/skia +++ b/third_party/skia
@@ -1 +1 @@ -Subproject commit 6a50e5207dedc0ad967beb987c97a6c17b316dbf +Subproject commit bea3840c4307aea5cb9a691b4c1f48db1882d9e9
diff --git a/third_party/webrtc b/third_party/webrtc index da648b5..6866da1 160000 --- a/third_party/webrtc +++ b/third_party/webrtc
@@ -1 +1 @@ -Subproject commit da648b596043e999975bbf7053b3294c9039738a +Subproject commit 6866da182230618c8cd8653c5894c9791a2b0470
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 99a5870d8..c07bebc 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -14526,6 +14526,8 @@ <int value="14" label="Timeout loading force-installed extensions"/> <int value="15" label="Invalid ExtensionInstallForcelist policy"/> <int value="16" label="Failed to login because the user is not allowlisted"/> + <int value="17" label="Lacros migration is in progress"/> + <int value="18" label="Lacros backward migration is in progress"/> </enum> <enum name="KioskLaunchType"> @@ -16987,6 +16989,7 @@ <int value="-1899342084" label="ArcGhostWindow:enabled"/> <int value="-1898963163" label="OmniboxKeywordSpaceTriggeringSetting:disabled"/> + <int value="-1898905225" label="FetchGaiaHashOnSignIn:enabled"/> <int value="-1898386671" label="PasswordCheck:enabled"/> <int value="-1898229093" label="WebApkGenerator:enabled"/> <int value="-1898129939" label="U2fPermissionPrompt:enabled"/> @@ -21604,6 +21607,7 @@ <int value="141482401" label="ConsumerAutoUpdateToggleAllowed:disabled"/> <int value="141830539" label="MediaAppPdfSignature:enabled"/> <int value="143725809" label="DownloadProgressInfoBar:enabled"/> + <int value="143972631" label="FetchGaiaHashOnSignIn:disabled"/> <int value="144868136" label="DesktopPWAsNotificationIconAndTitle:enabled"/> <int value="145296783" label="CameraMicPreview:disabled"/> <int value="146139744" label="CrOSLateBootPermissiveUsbPassthrough:disabled"/>
diff --git a/tools/metrics/histograms/metadata/android/histograms.xml b/tools/metrics/histograms/metadata/android/histograms.xml index 427527a3..544da80 100644 --- a/tools/metrics/histograms/metadata/android/histograms.xml +++ b/tools/metrics/histograms/metadata/android/histograms.xml
@@ -3011,7 +3011,7 @@ <histogram name="Android.Omnibox.{AndroidSearchPrefetch}.GeoLocationHeaderTime.{AndroidNavigationOrSuggestionPrefetch}" - units="ms" expires_after="2024-06-15"> + units="ms" expires_after="2024-11-15"> <owner>nhiroki@chromium.org</owner> <owner>ryansturm@chromium.org</owner> <owner>curranmax@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/ash/histograms.xml b/tools/metrics/histograms/metadata/ash/histograms.xml index 0f4843a5..a98bcd0e 100644 --- a/tools/metrics/histograms/metadata/ash/histograms.xml +++ b/tools/metrics/histograms/metadata/ash/histograms.xml
@@ -6387,6 +6387,18 @@ </summary> </histogram> +<histogram name="Ash.PowerNotification.TimeToEmptyPluggedIn" units="seconds" + expires_after="2025-05-01"> + <owner>dpad@google.com</owner> + <owner>longbowei@google.com</owner> + <owner>cros-peripherals@google.com</owner> + <summary> + Record the remaining battery time when the device transitions from a + critical state to charging state upon connecting the charger. Fires at the + moment charger is connected. + </summary> +</histogram> + <histogram name="Ash.PowerSoundsController.PluggedInBatteryLevel" units="%" expires_after="2024-11-03"> <owner>hongyulong@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/autofill/histograms.xml b/tools/metrics/histograms/metadata/autofill/histograms.xml index 2012242d..0050e2c 100644 --- a/tools/metrics/histograms/metadata/autofill/histograms.xml +++ b/tools/metrics/histograms/metadata/autofill/histograms.xml
@@ -687,17 +687,6 @@ </summary> </histogram> -<histogram name="Autofill.AddressSuggestionsCount" units="units" - expires_after="2024-09-15"> - <owner>battre@chromium.org</owner> - <owner>chrome-autofill-alerts@google.com</owner> - <summary> - The number of address suggestions shown in the Autofill popup. Recorded - whenever suggestions are shown. To be replaced by - Autofill.SuggestionCount.Address. - </summary> -</histogram> - <histogram name="Autofill.AddressTokenVerificationStatusAtProfileUsage.{AddressType}" enum="AufofillStructuredTokenVerificationStatus" expires_after="2024-06-30">
diff --git a/tools/metrics/histograms/metadata/cros_audio/histograms.xml b/tools/metrics/histograms/metadata/cros_audio/histograms.xml index 2915077..845a641 100644 --- a/tools/metrics/histograms/metadata/cros_audio/histograms.xml +++ b/tools/metrics/histograms/metadata/cros_audio/histograms.xml
@@ -234,6 +234,26 @@ </histogram> <histogram + name="ChromeOS.AudioSelection.{AudioType}.UserOverrideSystem{SwitchDecision}Audio.BeforeAndAfterAudioDeviceSet" + units="counts" expires_after="2025-02-25"> + <owner>zhangwenyu@google.com</owner> + <owner>cros-peripherals@google.com</owner> + <summary> + Record all the connected audio device types when users override the system + decision of {SwitchDecision} {AudioType} audio devices. Record both before + and after condition of audio device set. + </summary> + <token key="AudioType"> + <variant name="Input" summary="input"/> + <variant name="Output" summary="output"/> + </token> + <token key="SwitchDecision"> + <variant name="NotSwitch" summary="not switching"/> + <variant name="Switch" summary="switching"/> + </token> +</histogram> + +<histogram name="ChromeOS.AudioSelection.{AudioType}.UserOverrideSystem{SwitchDecision}TimeElapsed" units="minutes" expires_after="2024-11-03"> <owner>zhangwenyu@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/enterprise/enums.xml b/tools/metrics/histograms/metadata/enterprise/enums.xml index cf468dc..ce622ead 100644 --- a/tools/metrics/histograms/metadata/enterprise/enums.xml +++ b/tools/metrics/histograms/metadata/enterprise/enums.xml
@@ -2254,6 +2254,13 @@ <int value="11" label="Browser crash event"/> </enum> +<enum name="EnterpriseUserInfoFetchStatus"> + <int value="0" label="Success"/> + <int value="1" label="Failed with a network error"/> + <int value="2" label="Can't parse JSON in response"/> + <int value="3" label="Response is not a dictionary"/> +</enum> + <enum name="EnterpriseUserPolicyChromeOSReregistrationResult"> <summary>Re-registration results after a failed policy fetch.</summary> <int value="0" label="Re-registration triggered"/>
diff --git a/tools/metrics/histograms/metadata/enterprise/histograms.xml b/tools/metrics/histograms/metadata/enterprise/histograms.xml index bbd6d356..6044f5d 100644 --- a/tools/metrics/histograms/metadata/enterprise/histograms.xml +++ b/tools/metrics/histograms/metadata/enterprise/histograms.xml
@@ -3114,6 +3114,31 @@ </summary> </histogram> +<histogram name="Enterprise.UserInfoFetch.HttpErrorCode" + enum="CombinedHttpResponseAndNetErrorCode" expires_after="2025-02-12"> + <owner>vincb@google.com</owner> + <owner>zmin@chromium.org</owner> + <summary> + Records the http error code when there is a network error that comes with a + http error code. + + Recorded at the end of an user info fetch if there is a network error that + comes with a http error code. + </summary> +</histogram> + +<histogram name="Enterprise.UserInfoFetch.Status" + enum="EnterpriseUserInfoFetchStatus" expires_after="2025-02-12"> + <owner>vincb@google.com</owner> + <owner>zmin@chromium.org</owner> + <summary> + Records the status of fetching user info when doing registration for user + policy. + + Recorded at the end of each user info fetch. + </summary> +</histogram> + <histogram name="Enterprise.UserPolicy.Count" units="policies" expires_after="2024-10-13"> <owner>vincb@google.com</owner>
diff --git a/tools/metrics/histograms/metadata/magic_stack/histograms.xml b/tools/metrics/histograms/metadata/magic_stack/histograms.xml index 8ee4c4a..fa3d092 100644 --- a/tools/metrics/histograms/metadata/magic_stack/histograms.xml +++ b/tools/metrics/histograms/metadata/magic_stack/histograms.xml
@@ -75,6 +75,17 @@ </summary> </histogram> +<histogram name="MagicStack.Clank.TabResumption.IsSalientImageAvailable" + enum="Boolean" expires_after="2024-10-28"> + <owner>hanxi@google.com</owner> + <owner>huangs@google.com</owner> + <summary> + Records whether a salient image is fetched successfully. The histogram is + logged when a tile is shown and a image is fetched for the tile. + Android-only. + </summary> +</histogram> + <histogram name="MagicStack.Clank.TabResumption.ModuleNotShownReason" enum="MagicStack.Clank.TabResumption.ModuleNotShownReason" expires_after="2024-11-03"> @@ -321,7 +332,7 @@ <histogram name="MagicStack.Clank.{ModuleDelegateHost}.Module.ProfileReadyDelayMs" - units="ms" expires_after="2024-06-20"> + units="ms" expires_after="2024-10-28"> <owner>hanxi@chromium.org</owner> <owner>xinyiji@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/new_tab_page/histograms.xml b/tools/metrics/histograms/metadata/new_tab_page/histograms.xml index 0455d2e..a5c4820 100644 --- a/tools/metrics/histograms/metadata/new_tab_page/histograms.xml +++ b/tools/metrics/histograms/metadata/new_tab_page/histograms.xml
@@ -1727,7 +1727,7 @@ <histogram name="NewTabPage.SearchResumptionModule.NotShown" enum="SearchResumptionModule.ModuleNotShownReason" - expires_after="2024-05-07"> + expires_after="2025-01-31"> <owner>hanxi@chromium.org</owner> <owner>xinyiji@chromium.org</owner> <summary> @@ -1738,7 +1738,7 @@ </histogram> <histogram name="NewTabPage.SearchResumptionModule.Show" - enum="SearchResumptionModule.ModuleShowStatus" expires_after="2024-05-07"> + enum="SearchResumptionModule.ModuleShowStatus" expires_after="2025-01-31"> <owner>hanxi@chromium.org</owner> <owner>xinyiji@chromium.org</owner> <summary> @@ -1749,7 +1749,7 @@ </histogram> <histogram name="NewTabPage.SearchResumptionModule.Show.Cached" - enum="SearchResumptionModule.ModuleShowStatus" expires_after="2024-05-07"> + enum="SearchResumptionModule.ModuleShowStatus" expires_after="2025-01-31"> <owner>hanxi@chromium.org</owner> <owner>xinyiji@chromium.org</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/others/enums.xml b/tools/metrics/histograms/metadata/others/enums.xml index c9d77fa..6ea6bee8 100644 --- a/tools/metrics/histograms/metadata/others/enums.xml +++ b/tools/metrics/histograms/metadata/others/enums.xml
@@ -40,6 +40,20 @@ <int value="3" label="Wayland"/> </enum> +<!-- LINT.IfChange(LensOverlayInvocationSource) --> + +<enum name="LensOverlayInvocationSource"> + <summary>The UI source of a Lens Overlay invocation.</summary> + <int value="0" label="App menu"/> + <int value="1" label="Content area page context menu"/> + <int value="2" label="Content area image context menu"/> + <int value="3" label="Toolbar button"/> + <int value="4" label="Find in page dialog button"/> + <int value="5" label="Omnibox button"/> +</enum> + +<!-- LINT.ThenChange(//chrome/browser/ui/lens/lens_overlay_controller.h:InvocationSource) --> + <enum name="RedactionToolCaller"> <summary>The caller of the redaction tool.</summary> <int value="1" label="System Logs Uploader"/>
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index c649e79..1f0badd 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -4984,7 +4984,7 @@ </histogram> <histogram name="DisplayManager.UpdateDisplayConfigurationTask.Success" - enum="BooleanSuccess" expires_after="2024-06-17"> + enum="BooleanSuccess" expires_after="2025-04-15"> <owner>zhangwenyu@google.com</owner> <owner>cros-peripherals@google.com</owner> <summary> @@ -7059,6 +7059,24 @@ </summary> </histogram> +<histogram name="Lens.Overlay.Invoked" enum="LensOverlayInvocationSource" + expires_after="2025-05-06"> + <owner>jdonnelly@chromium.org</owner> + <owner>mercerd@google.com</owner> + <summary> + Recorded once when the Lens Overlay feature is invoked, enumerated by the UI + entry point used. In general, it should not be possible to attempt to invoke + the feature if the overlay is already showing but if this happens, nothing + will be recorded. + + See also Desktop.LensOverlay.Shown, which is recoded when the overlay is + successfully shown. + + This UMA histogram is used to track feature usage and retention, and thus + should never expire. + </summary> +</histogram> + <histogram name="Lens.QuickActionSearchWidget.LensSupportStatus" enum="LensSupportStatus" expires_after="2024-06-21"> <owner>benwgold@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/signin/enums.xml b/tools/metrics/histograms/metadata/signin/enums.xml index 205c101..de5d06b 100644 --- a/tools/metrics/histograms/metadata/signin/enums.xml +++ b/tools/metrics/histograms/metadata/signin/enums.xml
@@ -806,6 +806,9 @@ <int value="19" label="LogoutTabHelper::DidFinishNavigation"/> <int value="20" label="ForceSigninReauthWithDifferentAccount"/> <int value="21" label="AccountReconcilor::RevokeTokensNotInCookies"/> + <int value="22" + label="DiceResponseHandler::Signin from sign in promo after password + save"/> </enum> <enum name="SyncButtonClicked">
diff --git a/ui/events/velocity_tracker/velocity_tracker.cc b/ui/events/velocity_tracker/velocity_tracker.cc index 56c3a07..e8b24f9 100644 --- a/ui/events/velocity_tracker/velocity_tracker.cc +++ b/ui/events/velocity_tracker/velocity_tracker.cc
@@ -10,7 +10,6 @@ #include <ostream> #include "base/check_op.h" -#include "base/feature_list.h" #include "base/notreached.h" #include "build/build_config.h" #include "ui/events/velocity_tracker/motion_event.h" @@ -247,19 +246,6 @@ return CreateStrategy(VelocityTracker::STRATEGY_DEFAULT); } -// We updated the timestamp used in AddMovement to correctly use the latest. -// However we would like to confirm if an increase in jank seen is a measurement -// only change caused by the timestamp accuracy. This feature re-enables using -// the oldest timestamp from the event for the purpose of validation. -// -// This is only to validate whether this change was the cause of the jank -// regression. -// -// TODO(b/332930087): clean this up after the validation has been completed. -BASE_FEATURE(kUseOldestTimestamp, - "UseOldestTimestamp", - base::FEATURE_DISABLED_BY_DEFAULT); - } // namespace // --- VelocityTracker --- @@ -384,10 +370,7 @@ positions[index].x = event.GetX(i); positions[index].y = event.GetY(i); } - AddMovement(base::FeatureList::IsEnabled(kUseOldestTimestamp) - ? event.GetEventTime() - : event.GetLatestEventTime(), - id_bits, positions); + AddMovement(event.GetLatestEventTime(), id_bits, positions); } bool VelocityTracker::GetVelocity(uint32_t id,
diff --git a/ui/ozone/platform/wayland/host/wayland_cursor.cc b/ui/ozone/platform/wayland/host/wayland_cursor.cc index 1b7d3032..b85b959 100644 --- a/ui/ozone/platform/wayland/host/wayland_cursor.cc +++ b/ui/ozone/platform/wayland/host/wayland_cursor.cc
@@ -161,10 +161,20 @@ wl_surface_damage(pointer_surface_.get(), 0, 0, buffer_width, buffer_height); // Note: should the offset be non-zero, use wl_surface_offset() to set it. wl_surface_attach(pointer_surface_.get(), buffer, 0, 0); - wl_surface_commit(pointer_surface_.get()); - + // Set cursor before commit to ensure a role is set on the surface, so that + // the compositor can exclude this surface from being checked that its buffer + // size is divisible by the buffer scale. + // For more details see the following: + // - https://gitlab.freedesktop.org/wayland/wayland/-/issues/194 + // - https://gitlab.freedesktop.org/wayland/wayland/-/merge_requests/65 + // - https://wayland.app/protocols/wayland#wl_pointer:request:set_cursor + // + // Gnome in particular made a change which expects a role to be set, or it + // will throw a protocol error when the size is not divisible by the scale: + // https://gitlab.gnome.org/GNOME/mutter/-/commit/98c8c03729fd3fe72980d55fc3dccd8a0e9702e9 wl_pointer_set_cursor(pointer_->wl_object(), pointer_enter_serial->value, pointer_surface_.get(), hotspot_x_dip, hotspot_y_dip); + wl_surface_commit(pointer_surface_.get()); connection_->Flush(); }
diff --git a/ui/ozone/platform/wayland/host/wayland_data_device.cc b/ui/ozone/platform/wayland/host/wayland_data_device.cc index f3dcd6e..5a7ec2c 100644 --- a/ui/ozone/platform/wayland/host/wayland_data_device.cc +++ b/ui/ozone/platform/wayland/host/wayland_data_device.cc
@@ -153,8 +153,12 @@ // potential leaks and/or UAFs, forcibly call corresponding delegate callback // here, in Lacros. TODO(crbug.com/40819972): Remove once Exo bug is fixed. #if BUILDFLAG(IS_CHROMEOS_LACROS) - self->drag_delegate_->OnDragLeave(timestamp); - self->ResetDragDelegateIfNotDragSource(); + // Delegate might have been reset already if the drag was cancelled in + // response to the drop event. + if (self->drag_delegate_) { + self->drag_delegate_->OnDragLeave(timestamp); + self->ResetDragDelegateIfNotDragSource(); + } #endif }
diff --git a/ui/ozone/platform/wayland/host/wayland_data_drag_controller.cc b/ui/ozone/platform/wayland/host/wayland_data_drag_controller.cc index c0d2ca5..5272865 100644 --- a/ui/ozone/platform/wayland/host/wayland_data_drag_controller.cc +++ b/ui/ozone/platform/wayland/host/wayland_data_drag_controller.cc
@@ -202,6 +202,11 @@ } void WaylandDataDragController::CancelSession() { + // Inform the compositor that we're no longer interested in the data offer. + if (data_offer_) { + data_offer_->SetDndActions(0); + } + // If this is an outgoing drag session, Reset() will reset the wl_data_source // we created for the drag, which as per the spec for // wl_data_device.start_drag() will cancel the DnD session. @@ -495,11 +500,15 @@ window_->OnDragDrop(); - // Offer must be finished and destroyed here as some compositors may delay to - // send wl_data_source::finished|cancelled until owning client destroys the - // drag offer. e.g: Exosphere. - data_offer_->FinishOffer(); - data_offer_.reset(); + // Might have already been reset if the drag was cancelled in response to the + // drop event. + if (data_offer_) { + // Offer must be finished and destroyed here as some compositors may delay + // to send wl_data_source::finished|cancelled until owning client destroys + // the drag offer. e.g: Exosphere. + data_offer_->FinishOffer(); + data_offer_.reset(); + } } void WaylandDataDragController::OnDataSourceFinish(WaylandDataSource* source,
diff --git a/ui/ozone/platform/wayland/host/wayland_data_drag_controller.h b/ui/ozone/platform/wayland/host/wayland_data_drag_controller.h index 3a12fbc..bb8fb24 100644 --- a/ui/ozone/platform/wayland/host/wayland_data_drag_controller.h +++ b/ui/ozone/platform/wayland/host/wayland_data_drag_controller.h
@@ -254,12 +254,12 @@ // holds the provider for the data to be sent through Wayland protocol. std::unique_ptr<OSExchangeDataProvider> offered_exchange_data_provider_; - // Offer to receive data from another process via drag-and-drop, or null if - // no drag-and-drop from another process is in progress. + // The data offer through wl_data_device for the current drag and drop + // session, or null if there is no session running. // - // The data offer from another Wayland client through wl_data_device, that - // triggered the current drag and drop session. If null, either there is no - // dnd session running or Chromium is the data source. + // Note that this is non-null even for a drag initiated by ourselves, we just + // don't do anything with the offer as we handle all the data transfer + // internally. std::unique_ptr<WaylandDataOffer> data_offer_; // The window that initiated the drag session. Can be null when the session
diff --git a/v8 b/v8 index 00ad288..9a7273c 160000 --- a/v8 +++ b/v8
@@ -1 +1 @@ -Subproject commit 00ad28834aceb9cf29d5a118497a175067902d26 +Subproject commit 9a7273cb2581805e0a6c283fd1469b7804df56a4