Automated commit: libchrome r1094370 uprev
Merge with upstream commit 72c156f4e5b9941565dd54ccf5a70c97f1f62fa3
* resolve merge conflict in base/system/sys_info_posix.cc
(upstream CL: crrev.com/1092582); remove local change
* remove long-term-1200-...patch in base/values.h that hides
base::DictionaryValue since it was removed from upstream at all
(upstream CL: crrev.com/1092142)
* rebase long-term-1900-...patch
Temporary patches
* update backward-compatibility-0200-...patch to reintroduce the removed
task posting files (upstream: crrev.com/1091839) until migration is
completed in CrOS (b/265541831)
* add temporary forwarding headers for base{=>/functional}/
headers (removed in crrev.com/1093705) until all client packages
include the new headers directly (b/266161904)
* restore include of <ostream> in base/numerics/safe_conversions.h until
all client packages include it directly (b/266510143)
BUG=b:265541831, b:266161904, b:266510143
TEST=sudo emerge libchrome
Change-Id: Ie2477c3c438a2a71664ca15cf32ccf11a9d2b031
diff --git a/BASE_VER b/BASE_VER
index 2b77fe1..e5419ce 100644
--- a/BASE_VER
+++ b/BASE_VER
@@ -1 +1 @@
-1091741
+1094370
diff --git a/base/allocator/dispatcher/dispatcher.cc b/base/allocator/dispatcher/dispatcher.cc
index f820383..9a1b471 100644
--- a/base/allocator/dispatcher/dispatcher.cc
+++ b/base/allocator/dispatcher/dispatcher.cc
@@ -250,16 +250,6 @@
#endif // BUILDFLAG(USE_PARTITION_ALLOC) && !BUILDFLAG(IS_NACL)
}
-void RemoveStandardAllocatorHooksForTesting() {
-#if BUILDFLAG(USE_ALLOCATOR_SHIM)
- allocator_shim::RemoveAllocatorDispatchForTesting(
- &allocator_shim_details::g_allocator_dispatch); // IN-TEST
-#endif
-#if BUILDFLAG(USE_PARTITION_ALLOC) && !BUILDFLAG(IS_NACL)
- partition_alloc::PartitionAllocHooks::SetObserverHooks(nullptr, nullptr);
-#endif
-}
-
} // namespace base::allocator::dispatcher
namespace base::allocator::dispatcher {
diff --git a/base/allocator/dispatcher/dispatcher.h b/base/allocator/dispatcher/dispatcher.h
index f786bc2..d7cc068 100644
--- a/base/allocator/dispatcher/dispatcher.h
+++ b/base/allocator/dispatcher/dispatcher.h
@@ -13,7 +13,6 @@
namespace base::allocator::dispatcher {
void BASE_EXPORT InstallStandardAllocatorHooks();
-void BASE_EXPORT RemoveStandardAllocatorHooksForTesting();
namespace internal {
struct DispatchData;
@@ -75,4 +74,4 @@
};
} // namespace base::allocator::dispatcher
-#endif // BASE_ALLOCATOR_DISPATCHER_DISPATCHER_H_
\ No newline at end of file
+#endif // BASE_ALLOCATOR_DISPATCHER_DISPATCHER_H_
diff --git a/base/allocator/partition_alloc_support.cc b/base/allocator/partition_alloc_support.cc
index 77fcf03..bc03424 100644
--- a/base/allocator/partition_alloc_support.cc
+++ b/base/allocator/partition_alloc_support.cc
@@ -23,13 +23,13 @@
#include "base/allocator/partition_allocator/shim/allocator_shim.h"
#include "base/allocator/partition_allocator/shim/allocator_shim_default_dispatch_to_partition_alloc.h"
#include "base/allocator/partition_allocator/thread_cache.h"
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/check.h"
#include "base/debug/dump_without_crashing.h"
#include "base/debug/stack_trace.h"
#include "base/debug/task_trace.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/immediate_crash.h"
#include "base/location.h"
#include "base/memory/raw_ptr_asan_service.h"
diff --git a/base/allocator/partition_allocator/partition_alloc-inl.h b/base/allocator/partition_allocator/partition_alloc-inl.h
index 327f681..e5725de 100644
--- a/base/allocator/partition_allocator/partition_alloc-inl.h
+++ b/base/allocator/partition_allocator/partition_alloc-inl.h
@@ -10,6 +10,7 @@
#include "base/allocator/partition_allocator/partition_alloc_base/compiler_specific.h"
#include "base/allocator/partition_allocator/partition_alloc_base/debug/debugging_buildflags.h"
+#include "base/allocator/partition_allocator/partition_alloc_config.h"
#include "base/allocator/partition_allocator/partition_ref_count.h"
#include "base/allocator/partition_allocator/pkey.h"
#include "base/allocator/partition_allocator/random.h"
@@ -28,7 +29,7 @@
// This is a `memset` that resists being optimized away. Adapted from
// boringssl/src/crypto/mem.c. (Copying and pasting is bad, but //base can't
// depend on //third_party, and this is small enough.)
-#if defined(COMPILER_MSVC) && !defined(__clang__)
+#if PA_CONFIG(IS_NONCLANG_MSVC)
// MSVC only supports inline assembly on x86. This preprocessor directive
// is intended to be a replacement for the same.
//
@@ -39,14 +40,14 @@
PA_ALWAYS_INLINE void SecureMemset(void* ptr, uint8_t value, size_t size) {
memset(ptr, value, size);
-#if !defined(COMPILER_MSVC) || defined(__clang__)
+#if !PA_CONFIG(IS_NONCLANG_MSVC)
// As best as we can tell, this is sufficient to break any optimisations that
// might try to eliminate "superfluous" memsets. If there's an easy way to
// detect memset_s, it would be better to use that.
__asm__ __volatile__("" : : "r"(ptr) : "memory");
-#endif // !defined(COMPILER_MSVC) || defined(__clang__)
+#endif // !PA_CONFIG(IS_NONCLANG_MSVC)
}
-#if defined(COMPILER_MSVC) && !defined(__clang__)
+#if PA_CONFIG(IS_NONCLANG_MSVC)
#pragma optimize("", on)
#endif
diff --git a/base/allocator/partition_allocator/partition_alloc.gni b/base/allocator/partition_allocator/partition_alloc.gni
index e1adaa9..cc6855a 100644
--- a/base/allocator/partition_allocator/partition_alloc.gni
+++ b/base/allocator/partition_allocator/partition_alloc.gni
@@ -90,12 +90,12 @@
# Use probe-on-destruct unowned ptr detection with ASAN.
use_asan_unowned_ptr = false
-
- # Use the version of raw_ptr<T> that allows the embedder to implement custom
- # logic.
- use_hookable_raw_ptr = false
}
+# Use the version of raw_ptr<T> that allows the embedder to implement custom
+# logic.
+use_hookable_raw_ptr = use_asan_backup_ref_ptr
+
declare_args() {
# - put_ref_count_in_previous_slot: place the ref-count at the end of the
# previous slot (or in metadata if a slot starts on the page boundary), as
@@ -205,11 +205,6 @@
!use_hookable_raw_ptr || !enable_backup_ref_ptr_support,
"Both HookableRawPtrImpl and BackupRefPtr can't be enabled at the same time")
-# HookableRawPtrImpl and AsanBackupRefPtr are mutually exclusive variants of raw_ptr.
-assert(
- !use_hookable_raw_ptr || !use_asan_backup_ref_ptr,
- "Both HookableRawPtrImpl and AsanBackupRefPtr can't be enabled at the same time")
-
# HookableRawPtrImpl and AsanUnownedPtr are mutually exclusive variants of raw_ptr.
assert(
!use_hookable_raw_ptr || !use_asan_unowned_ptr,
@@ -227,6 +222,9 @@
assert(build_with_chromium || !use_asan_backup_ref_ptr,
"AsanBackupRefPtr is not supported outside Chromium")
+assert(!use_asan_backup_ref_ptr || use_hookable_raw_ptr,
+ "AsanBackupRefPtr requires HookableRawPtrImpl")
+
declare_args() {
enable_pkeys = is_linux && target_cpu == "x64"
}
diff --git a/base/allocator/partition_allocator/partition_alloc_config.h b/base/allocator/partition_allocator/partition_alloc_config.h
index 35994ff..a8cce36 100644
--- a/base/allocator/partition_allocator/partition_alloc_config.h
+++ b/base/allocator/partition_allocator/partition_alloc_config.h
@@ -360,4 +360,13 @@
#define PA_CONFIG_POINTER_COMPRESSION() 0
#endif
+// PA_CONFIG(IS_NONCLANG_MSVC): mimics the compound condition used by
+// Chromium's `//base/compiler_specific.h` to detect true (non-Clang)
+// MSVC.
+#if defined(COMPILER_MSVC) && !defined(__clang__)
+#define PA_CONFIG_IS_NONCLANG_MSVC() 1
+#else
+#define PA_CONFIG_IS_NONCLANG_MSVC() 0
+#endif
+
#endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_CONFIG_H_
diff --git a/base/allocator/partition_allocator/partition_alloc_forward.h b/base/allocator/partition_allocator/partition_alloc_forward.h
index fd62e11..ab93272 100644
--- a/base/allocator/partition_allocator/partition_alloc_forward.h
+++ b/base/allocator/partition_allocator/partition_alloc_forward.h
@@ -7,11 +7,12 @@
#include <algorithm>
#include <cstddef>
+#include <type_traits>
#include "base/allocator/partition_allocator/partition_alloc_base/compiler_specific.h"
#include "base/allocator/partition_allocator/partition_alloc_base/component_export.h"
#include "base/allocator/partition_allocator/partition_alloc_base/debug/debugging_buildflags.h"
-#include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
+#include "base/allocator/partition_allocator/partition_alloc_config.h"
namespace partition_alloc {
@@ -44,6 +45,32 @@
void CheckThatSlotOffsetIsZero(uintptr_t address);
#endif
+// This type trait verifies a type can be used as a pointer offset.
+//
+// We support pointer offsets in signed (ptrdiff_t) or unsigned (size_t) values.
+// Smaller types are also allowed.
+template <typename Z>
+static constexpr bool offset_type =
+ std::is_integral_v<Z> && sizeof(Z) <= sizeof(ptrdiff_t);
+
+template <typename Z, typename = std::enable_if_t<offset_type<Z>, void>>
+struct PtrDelta {
+ Z delta_in_bytes;
+#if PA_CONFIG(USE_OOB_POISON)
+ // Size of the element type referenced by the pointer
+ size_t type_size;
+#endif
+
+ constexpr PtrDelta(Z delta_in_bytes, size_t type_size)
+ : delta_in_bytes(delta_in_bytes)
+#if PA_CONFIG(USE_OOB_POISON)
+ ,
+ type_size(type_size)
+#endif
+ {
+ }
+};
+
} // namespace internal
class PartitionStatsDumper;
diff --git a/base/allocator/partition_allocator/partition_alloc_unittest.cc b/base/allocator/partition_allocator/partition_alloc_unittest.cc
index 7e3e46c..2c96a60 100644
--- a/base/allocator/partition_allocator/partition_alloc_unittest.cc
+++ b/base/allocator/partition_allocator/partition_alloc_unittest.cc
@@ -1452,62 +1452,101 @@
}
uintptr_t address = UntagPtr(ptr);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, -kFarFarAwayDelta),
- PtrPosWithinAlloc::kFarOOB);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, -kSuperPageSize),
- PtrPosWithinAlloc::kFarOOB);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, -1),
- PtrPosWithinAlloc::kFarOOB);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, 0),
- PtrPosWithinAlloc::kInBounds);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, requested_size / 2),
- PtrPosWithinAlloc::kInBounds);
-#if PA_CONFIG(USE_OOB_POISON)
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, requested_size),
- PtrPosWithinAlloc::kAllocEnd);
-#else
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, requested_size),
- PtrPosWithinAlloc::kInBounds);
-#endif
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, requested_size + 1),
- PtrPosWithinAlloc::kFarOOB);
EXPECT_EQ(PartitionAllocIsValidPtrDelta(address,
- requested_size + kSuperPageSize),
- PtrPosWithinAlloc::kFarOOB);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(
- address, requested_size + kFarFarAwayDelta),
- PtrPosWithinAlloc::kFarOOB);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
- kFarFarAwayDelta),
- PtrPosWithinAlloc::kFarOOB);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
- kSuperPageSize),
- PtrPosWithinAlloc::kFarOOB);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size, 1),
- PtrPosWithinAlloc::kFarOOB);
-#if PA_CONFIG(USE_OOB_POISON)
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size, 0),
- PtrPosWithinAlloc::kAllocEnd);
-#else
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size, 0),
- PtrPosWithinAlloc::kInBounds);
-#endif
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
- -(requested_size / 2)),
- PtrPosWithinAlloc::kInBounds);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
- -requested_size),
- PtrPosWithinAlloc::kInBounds);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
- -requested_size - 1),
- PtrPosWithinAlloc::kFarOOB);
- EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
- -requested_size - kSuperPageSize),
+ PtrDelta(-kFarFarAwayDelta, 0)),
PtrPosWithinAlloc::kFarOOB);
EXPECT_EQ(
- PartitionAllocIsValidPtrDelta(address + requested_size,
- -requested_size - kFarFarAwayDelta),
+ PartitionAllocIsValidPtrDelta(address, PtrDelta(-kSuperPageSize, 0)),
PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, PtrDelta(-1, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address, PtrDelta(0, 0)),
+ PtrPosWithinAlloc::kInBounds);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address,
+ PtrDelta(requested_size / 2, 0)),
+ PtrPosWithinAlloc::kInBounds);
+#if PA_CONFIG(USE_OOB_POISON)
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address,
+ PtrDelta(requested_size - 1, 1)),
+ PtrPosWithinAlloc::kInBounds);
+ EXPECT_EQ(
+ PartitionAllocIsValidPtrDelta(address, PtrDelta(requested_size, 1)),
+ PtrPosWithinAlloc::kAllocEnd);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address,
+ PtrDelta(requested_size - 4, 4)),
+ PtrPosWithinAlloc::kInBounds);
+ for (size_t subtrahend = 0; subtrahend < 4; subtrahend++) {
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(
+ address, PtrDelta(requested_size - subtrahend, 4)),
+ PtrPosWithinAlloc::kAllocEnd);
+ }
+#else
+ EXPECT_EQ(
+ PartitionAllocIsValidPtrDelta(address, PtrDelta(requested_size, 0)),
+ PtrPosWithinAlloc::kInBounds);
+#endif
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address,
+ PtrDelta(requested_size + 1, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(
+ address, PtrDelta(requested_size + kSuperPageSize, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(
+ address, PtrDelta(requested_size + kFarFarAwayDelta, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
+ PtrDelta(kFarFarAwayDelta, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
+ PtrDelta(kSuperPageSize, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
+ PtrDelta(1, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+#if PA_CONFIG(USE_OOB_POISON)
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size - 1,
+ PtrDelta(0, 1)),
+ PtrPosWithinAlloc::kInBounds);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size - 1,
+ PtrDelta(1, 1)),
+ PtrPosWithinAlloc::kAllocEnd);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
+ PtrDelta(0, 1)),
+ PtrPosWithinAlloc::kAllocEnd);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size - 1,
+ PtrDelta(1, 1)),
+ PtrPosWithinAlloc::kAllocEnd);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size - 4,
+ PtrDelta(0, 4)),
+ PtrPosWithinAlloc::kInBounds);
+ for (size_t addend = 1; addend < 4; addend++) {
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size - 4,
+ PtrDelta(addend, 4)),
+ PtrPosWithinAlloc::kAllocEnd);
+ }
+#else
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
+ PtrDelta(0, 0)),
+ PtrPosWithinAlloc::kInBounds);
+#endif
+ EXPECT_EQ(
+ PartitionAllocIsValidPtrDelta(address + requested_size,
+ PtrDelta(-(requested_size / 2), 0)),
+ PtrPosWithinAlloc::kInBounds);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
+ PtrDelta(-requested_size, 0)),
+ PtrPosWithinAlloc::kInBounds);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(address + requested_size,
+ PtrDelta(-requested_size - 1, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(
+ address + requested_size,
+ PtrDelta(-requested_size - kSuperPageSize, 0)),
+ PtrPosWithinAlloc::kFarOOB);
+ EXPECT_EQ(PartitionAllocIsValidPtrDelta(
+ address + requested_size,
+ PtrDelta(-requested_size - kFarFarAwayDelta, 0)),
+ PtrPosWithinAlloc::kFarOOB);
}
for (void* ptr : ptrs) {
diff --git a/base/allocator/partition_allocator/partition_root.h b/base/allocator/partition_allocator/partition_root.h
index 4ac4104..8387aa9 100644
--- a/base/allocator/partition_allocator/partition_root.h
+++ b/base/allocator/partition_allocator/partition_root.h
@@ -89,14 +89,6 @@
namespace partition_alloc::internal {
-// This type trait verifies a type can be used as a pointer offset.
-//
-// We support pointer offsets in signed (ptrdiff_t) or unsigned (size_t) values.
-// Smaller types are also allowed.
-template <typename Z>
-static constexpr bool offset_type =
- std::is_integral_v<Z> && sizeof(Z) <= sizeof(ptrdiff_t);
-
// We want this size to be big enough that we have time to start up other
// scripts _before_ we wrap around.
static constexpr size_t kAllocInfoSize = 1 << 24;
@@ -1047,9 +1039,9 @@
//
// This isn't a general purpose function. The caller is responsible for ensuring
// that the ref-count is in place for this allocation.
-template <typename Z, typename = std::enable_if_t<offset_type<Z>, void>>
+template <typename Z>
PA_ALWAYS_INLINE PtrPosWithinAlloc
-PartitionAllocIsValidPtrDelta(uintptr_t address, Z delta_in_bytes) {
+PartitionAllocIsValidPtrDelta(uintptr_t address, PtrDelta<Z> delta) {
// Required for pointers right past an allocation. See
// |PartitionAllocGetSlotStartInBRPPool()|.
uintptr_t adjusted_address = address - kPartitionPastAllocationAdjustment;
@@ -1068,21 +1060,19 @@
PA_DCHECK(root->brp_enabled());
uintptr_t object_addr = root->SlotStartToObjectAddr(slot_start);
- uintptr_t new_address = address + static_cast<uintptr_t>(delta_in_bytes);
+ uintptr_t new_address =
+ address + static_cast<uintptr_t>(delta.delta_in_bytes);
uintptr_t object_end = object_addr + slot_span->GetUsableSize(root);
+ if (new_address < object_addr || object_end < new_address) {
+ return PtrPosWithinAlloc::kFarOOB;
#if PA_CONFIG(USE_OOB_POISON)
- bool below_object_end = new_address < object_end;
-#else
- bool below_object_end = new_address <= object_end;
-#endif
- if (object_addr <= new_address && below_object_end) {
- return PtrPosWithinAlloc::kInBounds;
-#if PA_CONFIG(USE_OOB_POISON)
- } else if (new_address == object_end) {
+ } else if (object_end - delta.type_size < new_address) {
+ // Not even a single element of the type referenced by the pointer can fit
+ // between the pointer and the end of the object.
return PtrPosWithinAlloc::kAllocEnd;
#endif
} else {
- return PtrPosWithinAlloc::kFarOOB;
+ return PtrPosWithinAlloc::kInBounds;
}
}
@@ -1459,7 +1449,7 @@
RawFree(slot_start, slot_span);
}
-#if defined(COMPILER_MSVC) && !defined(__clang__)
+#if PA_CONFIG(IS_NONCLANG_MSVC)
// MSVC only supports inline assembly on x86. This preprocessor directive
// is intended to be a replacement for the same.
//
@@ -1501,14 +1491,14 @@
// OS page. No need to write to the second one as well.
//
// Do not move the store above inside the locked section.
-#if !(defined(COMPILER_MSVC) && !defined(__clang__))
+#if !(PA_CONFIG(IS_NONCLANG_MSVC))
__asm__ __volatile__("" : : "r"(slot_start) : "memory");
#endif
::partition_alloc::internal::ScopedGuard guard{lock_};
FreeInSlotSpan(slot_start, slot_span);
}
-#if defined(COMPILER_MSVC) && !defined(__clang__)
+#if PA_CONFIG(IS_NONCLANG_MSVC)
#pragma optimize("", on)
#endif
diff --git a/base/allocator/partition_allocator/reverse_bytes.h b/base/allocator/partition_allocator/reverse_bytes.h
index 52f2e3b..2443d47 100644
--- a/base/allocator/partition_allocator/reverse_bytes.h
+++ b/base/allocator/partition_allocator/reverse_bytes.h
@@ -12,28 +12,29 @@
#include <cstdint>
+#include "base/allocator/partition_allocator/partition_alloc_config.h"
#include "build/build_config.h"
namespace partition_alloc::internal {
constexpr uint32_t ReverseFourBytes(uint32_t value) {
-#if defined(COMPILER_MSVC) && !defined(__clang__)
+#if PA_CONFIG(IS_NONCLANG_MSVC)
return value >> 24 | (value >> 8 & 0xff00) | (value & 0xff00) << 8 |
value << 24;
#else
return __builtin_bswap32(value);
-#endif // defined(COMPILER_MSVC) && !defined(__clang__)
+#endif // PA_CONFIG(IS_NONCLANG_MSVC)
}
constexpr uint64_t ReverseEightBytes(uint64_t value) {
-#if defined(COMPILER_MSVC) && !defined(__clang__)
+#if PA_CONFIG(IS_NONCLANG_MSVC)
return value >> 56 | (value >> 40 & 0xff00) | (value >> 24 & 0xff0000) |
(value >> 8 & 0xff000000) | (value & 0xff000000) << 8 |
(value & 0xff0000) << 24 | (value & 0xff00) << 40 |
(value & 0xff) << 56;
#else
return __builtin_bswap64(value);
-#endif // defined(COMPILER_MSVC) && !defined(__clang__)
+#endif // PA_CONFIG(IS_NONCLANG_MSVC)
}
constexpr uintptr_t ReverseBytes(uintptr_t value) {
diff --git a/base/allocator/partition_allocator/yield_processor.h b/base/allocator/partition_allocator/yield_processor.h
index 486532c..b94ee1a 100644
--- a/base/allocator/partition_allocator/yield_processor.h
+++ b/base/allocator/partition_allocator/yield_processor.h
@@ -5,6 +5,7 @@
#ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_YIELD_PROCESSOR_H_
#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_YIELD_PROCESSOR_H_
+#include "base/allocator/partition_allocator/partition_alloc_config.h"
#include "build/build_config.h"
// The PA_YIELD_PROCESSOR macro wraps an architecture specific-instruction that
@@ -16,7 +17,7 @@
#if BUILDFLAG(IS_NACL)
// Inline assembly not allowed.
#define PA_YIELD_PROCESSOR ((void)0)
-#elif defined(COMPILER_MSVC) && !defined(__clang__)
+#elif PA_CONFIG(IS_NONCLANG_MSVC)
// MSVC is in its own assemblyless world (crbug.com/1351310#c6).
#include <windows.h>
#define PA_YIELD_PROCESSOR (YieldProcessor())
diff --git a/base/android/application_status_listener.cc b/base/android/application_status_listener.cc
index e8fb9f9..464343f 100644
--- a/base/android/application_status_listener.cc
+++ b/base/android/application_status_listener.cc
@@ -7,7 +7,7 @@
#include <jni.h>
#include "base/base_jni_headers/ApplicationStatus_jni.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/lazy_instance.h"
#include "base/metrics/user_metrics.h"
#include "base/observer_list_threadsafe.h"
diff --git a/base/android/application_status_listener.h b/base/android/application_status_listener.h
index 854b0e2..dbbc36b 100644
--- a/base/android/application_status_listener.h
+++ b/base/android/application_status_listener.h
@@ -10,7 +10,7 @@
#include "base/android/jni_android.h"
#include "base/base_export.h"
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
namespace base {
namespace android {
diff --git a/base/android/application_status_listener_unittest.cc b/base/android/application_status_listener_unittest.cc
index c9629b5..224732c 100644
--- a/base/android/application_status_listener_unittest.cc
+++ b/base/android/application_status_listener_unittest.cc
@@ -6,7 +6,7 @@
#include <memory>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/task_environment.h"
diff --git a/base/android/base_jni_onload.cc b/base/android/base_jni_onload.cc
index df45b53..0b64a91 100644
--- a/base/android/base_jni_onload.cc
+++ b/base/android/base_jni_onload.cc
@@ -7,7 +7,7 @@
#include "base/android/jni_android.h"
#include "base/android/jni_utils.h"
#include "base/android/library_loader/library_loader_hooks.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
namespace base {
namespace android {
diff --git a/base/android/base_jni_onload.h b/base/android/base_jni_onload.h
index c725db7..5f98903 100644
--- a/base/android/base_jni_onload.h
+++ b/base/android/base_jni_onload.h
@@ -8,7 +8,7 @@
#include <jni.h>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
namespace base {
namespace android {
diff --git a/base/android/java/src/org/chromium/base/BundleUtils.java b/base/android/java/src/org/chromium/base/BundleUtils.java
index 61e4c78..774613f 100644
--- a/base/android/java/src/org/chromium/base/BundleUtils.java
+++ b/base/android/java/src/org/chromium/base/BundleUtils.java
@@ -12,12 +12,11 @@
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
+import android.util.ArrayMap;
import android.view.LayoutInflater;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
-import androidx.collection.ArrayMap;
-import androidx.collection.SimpleArrayMap;
import dalvik.system.BaseDexClassLoader;
import dalvik.system.PathClassLoader;
@@ -58,8 +57,7 @@
// This cache is needed to support the workaround for b/172602571, see
// createIsolatedSplitContext() for more info.
- private static final SimpleArrayMap<String, ClassLoader> sCachedClassLoaders =
- new SimpleArrayMap<>();
+ private static final ArrayMap<String, ClassLoader> sCachedClassLoaders = new ArrayMap<>();
private static final Map<String, ClassLoader> sInflationClassLoaders =
Collections.synchronizedMap(new ArrayMap<>());
diff --git a/base/android/java/src/org/chromium/base/ContentUriUtils.java b/base/android/java/src/org/chromium/base/ContentUriUtils.java
index e5e1ec2..2750131 100644
--- a/base/android/java/src/org/chromium/base/ContentUriUtils.java
+++ b/base/android/java/src/org/chromium/base/ContentUriUtils.java
@@ -248,7 +248,6 @@
* @return True for virtual file, false for any other file.
*/
private static boolean isVirtualDocument(Uri uri) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return false;
if (uri == null) return false;
if (!DocumentsContract.isDocumentUri(ContextUtils.getApplicationContext(), uri)) {
return false;
diff --git a/base/android/java/src/org/chromium/base/RequiredCallback.java b/base/android/java/src/org/chromium/base/RequiredCallback.java
new file mode 100644
index 0000000..20d847a
--- /dev/null
+++ b/base/android/java/src/org/chromium/base/RequiredCallback.java
@@ -0,0 +1,31 @@
+// 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.
+
+package org.chromium.base;
+
+import androidx.annotation.NonNull;
+
+/**
+ * A simple single-argument callback to handle the result of a computation that must be called
+ * exactly once.
+ *
+ * @param <T> The type of the computation's result.
+ */
+public class RequiredCallback<T> implements Callback<T> {
+ // Enforces (under test) that this callback is invoked before it is GC'd.
+ private final LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this);
+ private Callback<T> mCallback;
+
+ public RequiredCallback(@NonNull Callback<T> callback) {
+ mCallback = callback;
+ }
+
+ @Override
+ public void onResult(T result) {
+ assert mCallback != null : "Callback was already called.";
+ mCallback.onResult(result);
+ LifetimeAssert.setSafeToGc(mLifetimeAssert, true);
+ mCallback = null;
+ }
+}
diff --git a/base/android/java/src/org/chromium/base/SysUtils.java b/base/android/java/src/org/chromium/base/SysUtils.java
index e46c600..049aa06 100644
--- a/base/android/java/src/org/chromium/base/SysUtils.java
+++ b/base/android/java/src/org/chromium/base/SysUtils.java
@@ -182,7 +182,7 @@
// For evaluation purposes check whether our computation agrees with Android API value.
Context appContext = ContextUtils.getApplicationContext();
boolean isLowRam = false;
- if (appContext != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ if (appContext != null) {
isLowRam = ((ActivityManager) ContextUtils.getApplicationContext().getSystemService(
Context.ACTIVITY_SERVICE))
.isLowRamDevice();
diff --git a/base/android/java/src/org/chromium/base/TraceEvent.java b/base/android/java/src/org/chromium/base/TraceEvent.java
index e0fd1c7..1f9f6be 100644
--- a/base/android/java/src/org/chromium/base/TraceEvent.java
+++ b/base/android/java/src/org/chromium/base/TraceEvent.java
@@ -494,7 +494,7 @@
private static final class IdleTracingLooperMonitor extends BasicLooperMonitor
implements MessageQueue.IdleHandler {
// Tags for dumping to logcat or TraceEvent
- private static final String TAG = "TraceEvent_LooperMonitor";
+ private static final String TAG = "TraceEvt_LooperMonitor";
private static final String IDLE_EVENT_NAME = "Looper.queueIdle";
// Calculation constants
diff --git a/base/android/java/src/org/chromium/base/annotations/JniIgnoreNatives.java b/base/android/java/src/org/chromium/base/annotations/JniIgnoreNatives.java
deleted file mode 100644
index 0105791..0000000
--- a/base/android/java/src/org/chromium/base/annotations/JniIgnoreNatives.java
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2018 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.base.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Causes generate_jni_registration() to skip native methods in a file.
- */
-@Target(ElementType.TYPE)
-@Retention(RetentionPolicy.SOURCE)
-public @interface JniIgnoreNatives {}
diff --git a/base/android/java/src/org/chromium/base/compat/ApiHelperForM.java b/base/android/java/src/org/chromium/base/compat/ApiHelperForM.java
index 1a868f4..6c54203 100644
--- a/base/android/java/src/org/chromium/base/compat/ApiHelperForM.java
+++ b/base/android/java/src/org/chromium/base/compat/ApiHelperForM.java
@@ -5,7 +5,6 @@
package org.chromium.base.compat;
import android.app.Activity;
-import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
@@ -26,7 +25,6 @@
import android.webkit.WebViewClient;
import androidx.annotation.RequiresApi;
-import androidx.annotation.RequiresPermission;
/**
* Utility class to use new APIs that were added in M (API level 23). These need to exist in a
@@ -140,13 +138,6 @@
return event.getActionButton();
}
- /** See {@link AlarmManager#setExactAndAllowWhileIdle(int, long, PendingIntent) }. */
- @RequiresPermission(android.Manifest.permission.SCHEDULE_EXACT_ALARM)
- public static void setAlarmManagerExactAndAllowWhileIdle(AlarmManager alarmManager, int type,
- long triggerAtMillis, PendingIntent pendingIntent) {
- alarmManager.setExactAndAllowWhileIdle(type, triggerAtMillis, pendingIntent);
- }
-
/** See {@link Display.Mode#getPhysicalWidth() }. */
public static int getModePhysicalWidth(Display.Mode mode) {
return mode.getPhysicalWidth();
diff --git a/base/android/java/src/org/chromium/base/library_loader/Linker.java b/base/android/java/src/org/chromium/base/library_loader/Linker.java
index b503843..1d23797 100644
--- a/base/android/java/src/org/chromium/base/library_loader/Linker.java
+++ b/base/android/java/src/org/chromium/base/library_loader/Linker.java
@@ -18,7 +18,6 @@
import org.chromium.base.StreamUtil;
import org.chromium.base.TimeUtils.UptimeMillisTimer;
import org.chromium.base.annotations.AccessedByNative;
-import org.chromium.base.annotations.JniIgnoreNatives;
import org.chromium.base.metrics.RecordHistogram;
import java.io.BufferedReader;
@@ -73,7 +72,6 @@
* available to then send the Bundle to Linkers in other processes, consumed
* by takeSharedRelrosFromBundle().
*/
-@JniIgnoreNatives
class Linker {
private static final String TAG = "Linker";
@@ -769,7 +767,6 @@
* well.
*/
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
- @JniIgnoreNatives
static class LibInfo implements Parcelable {
private static final String EXTRA_LINKER_LIB_INFO = "libinfo";
@@ -870,8 +867,7 @@
public int mRelroFd = -1; // shared RELRO file descriptor, or -1
}
- // Intentionally omitting @NativeMethods because generation of the stubs it requires (as
- // GEN_JNI.java) is disabled by the @JniIgnoreNatives.
+ // Intentionally omitting @NativeMethods because this class does manual JNI.
interface Natives {
/**
* Reserves a memory region (=mapping) of sufficient size to hold the loaded library before
diff --git a/base/android/java/src/org/chromium/base/library_loader/LinkerJni.java b/base/android/java/src/org/chromium/base/library_loader/LinkerJni.java
index c614e2e..80abb1e 100644
--- a/base/android/java/src/org/chromium/base/library_loader/LinkerJni.java
+++ b/base/android/java/src/org/chromium/base/library_loader/LinkerJni.java
@@ -7,7 +7,6 @@
import androidx.annotation.NonNull;
import org.chromium.base.annotations.CalledByNative;
-import org.chromium.base.annotations.JniIgnoreNatives;
/**
* Mockable stub for all native methods in Linker.
@@ -15,11 +14,9 @@
* This functionality is usually generated from @NativeMethods, which cannot be used for the
* auxiliary native library used by classes in Linker and other classes in this package.
*
- * Generation of JNI stubs for classes in this package is omitted via @JniIgnoreNatives because
- * otherwise the generated native parts would have been linked into lib{,mono}chrome.so instead of
- * lib$LINKER_JNI_LIBRARY.so, where they are needed.
+ * Does not use jni_generator because otherwise the generated native parts would have been
+ * linked into libmonochrome.so instead of lib$LINKER_JNI_LIBRARY.so, where they are needed.
*/
-@JniIgnoreNatives
class LinkerJni implements Linker.Natives {
@Override
public void findMemoryRegionAtRandomAddress(@NonNull Linker.LibInfo libInfo) {
diff --git a/base/android/java_exception_reporter.cc b/base/android/java_exception_reporter.cc
index 2ebd181..395e976 100644
--- a/base/android/java_exception_reporter.cc
+++ b/base/android/java_exception_reporter.cc
@@ -8,9 +8,9 @@
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/base_jni_headers/JavaExceptionReporter_jni.h"
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/debug/dump_without_crashing.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/lazy_instance.h"
using base::android::JavaParamRef;
diff --git a/base/android/java_exception_reporter.h b/base/android/java_exception_reporter.h
index 56baef7..50c3cab 100644
--- a/base/android/java_exception_reporter.h
+++ b/base/android/java_exception_reporter.h
@@ -9,7 +9,7 @@
#include "base/android/scoped_java_ref.h"
#include "base/base_export.h"
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
namespace base {
namespace android {
diff --git a/base/android/java_handler_thread.cc b/base/android/java_handler_thread.cc
index 81a1c10..74fb75b 100644
--- a/base/android/java_handler_thread.cc
+++ b/base/android/java_handler_thread.cc
@@ -9,7 +9,7 @@
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/base_jni_headers/JavaHandlerThread_jni.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/message_loop/message_pump.h"
#include "base/message_loop/message_pump_type.h"
#include "base/run_loop.h"
diff --git a/base/android/jni_generator/README.md b/base/android/jni_generator/README.md
index b254205..1cdd208 100644
--- a/base/android/jni_generator/README.md
+++ b/base/android/jni_generator/README.md
@@ -128,13 +128,6 @@
void MyClass::NonStatic(JNIEnv* env) { ... }
```
-**Using the 'native' keyword**
-
-- The binding generator also looks for `native` JNI method declarations and
- generates stubs for them. This used to be the norm, but is now obsolete.
-- If you have native methods that you don't want stubs generated for, you should
- add @JniIgnoreNatives to the class.
-
#### Testing Mockable Natives
1. Add the `JniMocker` rule to your test.
diff --git a/base/android/jni_generator/golden/testMultipleJNIAdditionalImport.golden b/base/android/jni_generator/golden/testMultipleJNIAdditionalImport.golden
index 5398b32..a2570c7 100644
--- a/base/android/jni_generator/golden/testMultipleJNIAdditionalImport.golden
+++ b/base/android/jni_generator/golden/testMultipleJNIAdditionalImport.golden
@@ -35,18 +35,6 @@
// Step 3: Method stubs.
-static void JNI_Foo_DoSomething(JNIEnv* env, const base::android::JavaParamRef<jobject>& callback1,
- const base::android::JavaParamRef<jobject>& callback2);
-
-JNI_GENERATOR_EXPORT void Java_org_chromium_foo_Foo_nativeDoSomething(
- JNIEnv* env,
- jclass jcaller,
- jobject callback1,
- jobject callback2) {
- return JNI_Foo_DoSomething(env, base::android::JavaParamRef<jobject>(env, callback1),
- base::android::JavaParamRef<jobject>(env, callback2));
-}
-
static std::atomic<jmethodID> g_org_chromium_foo_Foo_calledByNative(nullptr);
static void Java_Foo_calledByNative(JNIEnv* env, const base::android::JavaRef<jobject>& callback1,
diff --git a/base/android/jni_generator/golden/testProxyNativesWithNatives.golden b/base/android/jni_generator/golden/testProxyNativesWithNatives.golden
index 2c4cecd..a15fd81 100644
--- a/base/android/jni_generator/golden/testProxyNativesWithNatives.golden
+++ b/base/android/jni_generator/golden/testProxyNativesWithNatives.golden
@@ -18,42 +18,11 @@
// Step 1: Forward declarations.
-JNI_REGISTRATION_EXPORT extern const char kClassPath_org_chromium_foo_Foo[];
-const char kClassPath_org_chromium_foo_Foo[] = "org/chromium/foo/Foo";
-// Leaking this jclass as we cannot use LazyInstance from some threads.
-JNI_REGISTRATION_EXPORT std::atomic<jclass> g_org_chromium_foo_Foo_clazz(nullptr);
-#ifndef org_chromium_foo_Foo_clazz_defined
-#define org_chromium_foo_Foo_clazz_defined
-inline jclass org_chromium_foo_Foo_clazz(JNIEnv* env) {
- return base::android::LazyGetClass(env, kClassPath_org_chromium_foo_Foo,
- &g_org_chromium_foo_Foo_clazz);
-}
-#endif
-
// Step 2: Constants (optional).
// Step 3: Method stubs.
-JNI_GENERATOR_EXPORT void Java_org_chromium_foo_Foo_nativeInstanceMethod(
- JNIEnv* env,
- jobject jcaller,
- jlong nativeInstance) {
- TRACE_EVENT0("jni", "Instance::InstanceMethod");
- Instance* native = reinterpret_cast<Instance*>(nativeInstance);
- CHECK_NATIVE_PTR(env, jcaller, native, "InstanceMethod");
- return native->InstanceMethod(env, base::android::JavaParamRef<jobject>(env, jcaller));
-}
-
-static void JNI_Foo_StaticMethod(JNIEnv* env);
-
-JNI_GENERATOR_EXPORT void Java_org_chromium_foo_Foo_nativeStaticMethod(
- JNIEnv* env,
- jclass jcaller) {
- TRACE_EVENT0("jni", "JNI_Foo_StaticMethod");
- return JNI_Foo_StaticMethod(env);
-}
-
static void JNI_Foo_Foo(JNIEnv* env);
JNI_GENERATOR_EXPORT void Java_org_chromium_base_natives_GEN_1JNI_org_1chromium_1foo_1Foo_1foo(
diff --git a/base/android/jni_generator/golden/testSingleJNIAdditionalImport.golden b/base/android/jni_generator/golden/testSingleJNIAdditionalImport.golden
index bfcd98c..82cc21e 100644
--- a/base/android/jni_generator/golden/testSingleJNIAdditionalImport.golden
+++ b/base/android/jni_generator/golden/testSingleJNIAdditionalImport.golden
@@ -35,15 +35,6 @@
// Step 3: Method stubs.
-static void JNI_Foo_DoSomething(JNIEnv* env, const base::android::JavaParamRef<jobject>& callback);
-
-JNI_GENERATOR_EXPORT void Java_org_chromium_foo_Foo_nativeDoSomething(
- JNIEnv* env,
- jclass jcaller,
- jobject callback) {
- return JNI_Foo_DoSomething(env, base::android::JavaParamRef<jobject>(env, callback));
-}
-
static std::atomic<jmethodID> g_org_chromium_foo_Foo_calledByNative(nullptr);
static void Java_Foo_calledByNative(JNIEnv* env, const base::android::JavaRef<jobject>& callback) {
diff --git a/base/android/jni_generator/jni_generator.py b/base/android/jni_generator/jni_generator.py
index 6f3e432..e765c9a 100755
--- a/base/android/jni_generator/jni_generator.py
+++ b/base/android/jni_generator/jni_generator.py
@@ -39,25 +39,14 @@
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
re.DOTALL | re.MULTILINE)
-_EXTRACT_NATIVES_REGEX = re.compile(
- r'(@NativeClassQualifiedName'
- r'\(\"(?P<native_class_name>.*?)\"\)\s+)?'
- r'(@NativeCall(\(\"(?P<java_class_name>.*?)\"\))\s+)?'
- r'(?P<qualifiers>\w+\s\w+|\w+|\s+)\s*native '
- r'(?P<return_type>\S*) '
- r'(?P<name>native\w+)\((?P<params>.*?)\);')
-
_MAIN_DEX_REGEX = re.compile(r'^\s*(?:@(?:\w+\.)*\w+\s+)*@MainDex\b',
re.MULTILINE)
-# Matches on method declarations unlike _EXTRACT_NATIVES_REGEX
-# doesn't require name to be prefixed with native, and does not
-# require a native qualifier.
_EXTRACT_METHODS_REGEX = re.compile(
r'(@NativeClassQualifiedName'
r'\(\"(?P<native_class_name>.*?)\"\)\s*)?'
r'(?P<qualifiers>'
- r'((public|private|static|final|abstract|protected|native)\s*)*)\s+'
+ r'((public|private|static|final|abstract|protected)\s*)*)\s+'
r'(?P<return_type>\S*)\s+'
r'(?P<name>\w+)\((?P<params>.*?)\);',
flags=re.DOTALL)
@@ -534,23 +523,6 @@
return class_path + '/' + class_name
-def ExtractNatives(contents, ptr_type):
- """Returns a list of dict containing information about a native method."""
- contents = contents.replace('\n', '')
- natives = []
- for match in _EXTRACT_NATIVES_REGEX.finditer(contents):
- native = NativeMethod(
- static='static' in match.group('qualifiers'),
- java_class_name=match.group('java_class_name'),
- native_class_name=match.group('native_class_name'),
- return_type=match.group('return_type'),
- name=match.group('name').replace('native', ''),
- params=JniParams.Parse(match.group('params')),
- ptr_type=ptr_type)
- natives += [native]
- return natives
-
-
def IsMainDexJavaClass(contents):
"""Returns True if the class or any of its methods are annotated as @MainDex.
@@ -971,13 +943,10 @@
self.jni_params = JniParams(fully_qualified_class)
self.jni_params.ExtractImportsAndInnerClasses(contents)
jni_namespace = ExtractJNINamespace(contents) or options.namespace
- natives = ExtractNatives(contents, options.ptr_type)
called_by_natives = ExtractCalledByNatives(self.jni_params, contents,
options.always_mangle)
-
- natives += ProxyHelpers.ExtractStaticProxyNatives(fully_qualified_class,
- contents,
- options.ptr_type)
+ natives = ProxyHelpers.ExtractStaticProxyNatives(fully_qualified_class,
+ contents, options.ptr_type)
if len(natives) == 0 and len(called_by_natives) == 0:
raise SyntaxError(
diff --git a/base/android/jni_generator/jni_generator_tests.py b/base/android/jni_generator/jni_generator_tests.py
index 60fd271..382cfaf 100755
--- a/base/android/jni_generator/jni_generator_tests.py
+++ b/base/android/jni_generator/jni_generator_tests.py
@@ -219,280 +219,6 @@
self.assertRaises(AssertionError, willRaise)
- def testNatives(self):
- test_data = """"
- import android.graphics.Bitmap;
- import android.view.View;
-
- interface OnFrameAvailableListener {}
- private native int nativeInit();
- private native void nativeDestroy(int nativeChromeBrowserProvider);
- private native long nativeAddBookmark(
- int nativeChromeBrowserProvider,
- String url, String title, boolean isFolder, long parentId);
- private static native String nativeGetDomainAndRegistry(String url);
- private static native void nativeCreateHistoricalTabFromState(
- byte[] state, int tab_index);
- private native byte[] nativeGetStateAsByteArray(View view);
- private static native String[] nativeGetAutofillProfileGUIDs();
- private native void nativeSetRecognitionResults(
- int sessionId, String[] results);
- private native long nativeAddBookmarkFromAPI(
- int nativeChromeBrowserProvider,
- String url, Long created, Boolean isBookmark,
- Long date, byte[] favicon, String title, Integer visits);
- native int nativeFindAll(String find);
- private static native OnFrameAvailableListener nativeGetInnerClass();
- private native Bitmap nativeQueryBitmap(
- int nativeChromeBrowserProvider,
- String[] projection, String selection,
- String[] selectionArgs, String sortOrder);
- private native void nativeGotOrientation(
- int nativeDataFetcherImplAndroid,
- double alpha, double beta, double gamma);
- private static native Throwable nativeMessWithJavaException(Throwable e);
- """
- jni_params = jni_generator.JniParams(
- 'org/chromium/example/jni_generator/SampleForTests')
- jni_params.ExtractImportsAndInnerClasses(test_data)
- natives = jni_generator.ExtractNatives(test_data, 'int')
- golden_natives = [
- NativeMethod(
- return_type='int',
- static=False,
- name='Init',
- params=[],
- java_class_name=None),
- NativeMethod(
- return_type='void',
- static=False,
- name='Destroy',
- params=[Param(datatype='int', name='nativeChromeBrowserProvider')],
- java_class_name=None),
- NativeMethod(
- return_type='long',
- static=False,
- name='AddBookmark',
- params=[
- Param(datatype='int', name='nativeChromeBrowserProvider'),
- Param(datatype='String', name='url'),
- Param(datatype='String', name='title'),
- Param(datatype='boolean', name='isFolder'),
- Param(datatype='long', name='parentId')
- ],
- java_class_name=None),
- NativeMethod(
- return_type='String',
- static=True,
- name='GetDomainAndRegistry',
- params=[Param(datatype='String', name='url')],
- java_class_name=None),
- NativeMethod(
- return_type='void',
- static=True,
- name='CreateHistoricalTabFromState',
- params=[
- Param(datatype='byte[]', name='state'),
- Param(datatype='int', name='tab_index')
- ],
- java_class_name=None),
- NativeMethod(
- return_type='byte[]',
- static=False,
- name='GetStateAsByteArray',
- params=[Param(datatype='View', name='view')],
- java_class_name=None),
- NativeMethod(
- return_type='String[]',
- static=True,
- name='GetAutofillProfileGUIDs',
- params=[],
- java_class_name=None),
- NativeMethod(
- return_type='void',
- static=False,
- name='SetRecognitionResults',
- params=[
- Param(datatype='int', name='sessionId'),
- Param(datatype='String[]', name='results')
- ],
- java_class_name=None),
- NativeMethod(
- return_type='long',
- static=False,
- name='AddBookmarkFromAPI',
- params=[
- Param(datatype='int', name='nativeChromeBrowserProvider'),
- Param(datatype='String', name='url'),
- Param(datatype='Long', name='created'),
- Param(datatype='Boolean', name='isBookmark'),
- Param(datatype='Long', name='date'),
- Param(datatype='byte[]', name='favicon'),
- Param(datatype='String', name='title'),
- Param(datatype='Integer', name='visits')
- ],
- java_class_name=None),
- NativeMethod(
- return_type='int',
- static=False,
- name='FindAll',
- params=[Param(datatype='String', name='find')],
- java_class_name=None),
- NativeMethod(
- return_type='OnFrameAvailableListener',
- static=True,
- name='GetInnerClass',
- params=[],
- java_class_name=None),
- NativeMethod(
- return_type='Bitmap',
- static=False,
- name='QueryBitmap',
- params=[
- Param(datatype='int', name='nativeChromeBrowserProvider'),
- Param(datatype='String[]', name='projection'),
- Param(datatype='String', name='selection'),
- Param(datatype='String[]', name='selectionArgs'),
- Param(datatype='String', name='sortOrder'),
- ],
- java_class_name=None),
- NativeMethod(
- return_type='void',
- static=False,
- name='GotOrientation',
- params=[
- Param(datatype='int', name='nativeDataFetcherImplAndroid'),
- Param(datatype='double', name='alpha'),
- Param(datatype='double', name='beta'),
- Param(datatype='double', name='gamma'),
- ],
- java_class_name=None),
- NativeMethod(
- return_type='Throwable',
- static=True,
- name='MessWithJavaException',
- params=[Param(datatype='Throwable', name='e')],
- java_class_name=None)
- ]
- self.AssertListEquals(golden_natives, natives)
- h1 = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
- natives, [], [], jni_params,
- TestOptions())
- self.AssertGoldenTextEquals(h1.GetContent())
- h2 = jni_registration_generator.HeaderGenerator('',
- '',
- 'org/chromium/TestJni',
- natives,
- jni_params,
- True,
- use_proxy_hash=False)
- content = TestGenerator._MergeRegistrationForTests([h2.Generate()])
-
- self.AssertGoldenTextEquals(jni_registration_generator.CreateFromDict(
- content, use_hash=False, manual_jni_registration=True),
- suffix='Registrations')
-
- def testInnerClassNatives(self):
- test_data = """
- class MyInnerClass {
- @NativeCall("MyInnerClass")
- private native int nativeInit();
- }
- """
- natives = jni_generator.ExtractNatives(test_data, 'int')
- golden_natives = [
- NativeMethod(
- return_type='int',
- static=False,
- name='Init',
- params=[],
- java_class_name='MyInnerClass')
- ]
- self.AssertListEquals(golden_natives, natives)
- jni_params = jni_generator.JniParams('')
- h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
- natives, [], [], jni_params,
- TestOptions())
- self.AssertGoldenTextEquals(h.GetContent())
-
- def testInnerClassNativesMultiple(self):
- test_data = """
- class MyInnerClass {
- @NativeCall("MyInnerClass")
- private native int nativeInit();
- }
- class MyOtherInnerClass {
- @NativeCall("MyOtherInnerClass")
- private native int nativeInit();
- }
- """
- natives = jni_generator.ExtractNatives(test_data, 'int')
- golden_natives = [
- NativeMethod(
- return_type='int',
- static=False,
- name='Init',
- params=[],
- java_class_name='MyInnerClass'),
- NativeMethod(
- return_type='int',
- static=False,
- name='Init',
- params=[],
- java_class_name='MyOtherInnerClass')
- ]
- self.AssertListEquals(golden_natives, natives)
- jni_params = jni_generator.JniParams('')
- h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
- natives, [], [], jni_params,
- TestOptions())
- self.AssertGoldenTextEquals(h.GetContent())
-
- def testInnerClassNativesBothInnerAndOuter(self):
- test_data = """
- class MyOuterClass {
- private native int nativeInit();
- class MyOtherInnerClass {
- @NativeCall("MyOtherInnerClass")
- private native int nativeInit();
- }
- }
- """
- natives = jni_generator.ExtractNatives(test_data, 'int')
- golden_natives = [
- NativeMethod(
- return_type='int',
- static=False,
- name='Init',
- params=[],
- java_class_name=None),
- NativeMethod(
- return_type='int',
- static=False,
- name='Init',
- params=[],
- java_class_name='MyOtherInnerClass')
- ]
- self.AssertListEquals(golden_natives, natives)
- jni_params = jni_generator.JniParams('')
- h = jni_generator.InlHeaderFileGenerator('', 'org/chromium/TestJni',
- natives, [], [], jni_params,
- TestOptions())
- self.AssertGoldenTextEquals(h.GetContent())
-
- h2 = jni_registration_generator.HeaderGenerator('',
- '',
- 'org/chromium/TestJni',
- natives,
- jni_params,
- True,
- use_proxy_hash=False)
- content = TestGenerator._MergeRegistrationForTests([h2.Generate()])
-
- self.AssertGoldenTextEquals(jni_registration_generator.CreateFromDict(
- content, use_hash=False, manual_jni_registration=True),
- suffix='Registrations')
-
def testCalledByNatives(self):
test_data = """"
import android.graphics.Bitmap;
@@ -993,27 +719,6 @@
self.assertEqual(86, len(jni_from_javap.called_by_natives))
self.AssertGoldenTextEquals(jni_from_javap.GetContent())
- def testREForNatives(self):
- # We should not match "native SyncSetupFlow" inside the comment.
- test_data = """
- /**
- * Invoked when the setup process is complete so we can disconnect from the
- * private native void nativeSyncSetupFlowHandler();.
- */
- public void destroy() {
- Log.v(TAG, "Destroying native SyncSetupFlow");
- if (mNativeSyncSetupFlow != 0) {
- nativeSyncSetupEnded(mNativeSyncSetupFlow);
- mNativeSyncSetupFlow = 0;
- }
- }
- private native void nativeSyncSetupEnded(
- int nativeAndroidSyncSetupFlowHandler);
- """
- jni_from_java = jni_generator.JNIFromJavaSource(
- test_data, 'foo/bar', TestOptions())
- self.AssertGoldenTextEquals(jni_from_java.GetContent())
-
def testRaisesOnNonJNIMethod(self):
test_data = """
class MyInnerClass {
@@ -1031,24 +736,6 @@
self.AssertGoldenTextEquals(
generated_text, golden_file='SampleForTests_jni.golden')
- def testNoWrappingPreprocessorLines(self):
- test_data = """
- package com.google.lookhowextremelylongiam.snarf.icankeepthisupallday;
-
- class ReallyLongClassNamesAreAllTheRage {
- private static native int nativeTest();
- }
- """
- jni_from_java = jni_generator.JNIFromJavaSource(
- test_data, ('com/google/lookhowextremelylongiam/snarf/'
- 'icankeepthisupallday/ReallyLongClassNamesAreAllTheRage'),
- TestOptions())
- jni_lines = jni_from_java.GetContent().split('\n')
- line = next(
- line for line in jni_lines if line.lstrip().startswith('#ifndef'))
- self.assertTrue(
- len(line) > 80, ('Expected #ifndef line to be > 80 chars: ', line))
-
def testImports(self):
import_header = """
// Copyright 2012 The Chromium Authors
@@ -1109,29 +796,6 @@
self.AssertTextEquals('[Ljava/nio/ByteBuffer;',
jni_params.JavaToJni('java/nio/ByteBuffer[]'))
- def testNativesLong(self):
- test_options = TestOptions()
- test_options.ptr_type = 'long'
- test_data = """"
- private native void nativeDestroy(long nativeChromeBrowserProvider);
- """
- jni_params = jni_generator.JniParams('')
- jni_params.ExtractImportsAndInnerClasses(test_data)
- natives = jni_generator.ExtractNatives(test_data, test_options.ptr_type)
- golden_natives = [
- NativeMethod(
- return_type='void',
- static=False,
- name='Destroy',
- params=[Param(datatype='long', name='nativeChromeBrowserProvider')],
- java_class_name=None,
- ptr_type=test_options.ptr_type),
- ]
- self.AssertListEquals(golden_natives, natives)
- h = jni_generator.InlHeaderFileGenerator(
- '', 'org/chromium/TestJni', natives, [], [], jni_params, test_options)
- self.AssertGoldenTextEquals(h.GetContent())
-
def testMainDexAnnotation(self):
mainDexEntries = [
'@MainDex public class Test {',
@@ -1176,43 +840,6 @@
for entry in noMainDexEntries:
self.assertEqual(False, IsMainDexJavaClass(entry))
- def testNativeExportsOnlyOption(self):
- test_data = """
- package org.chromium.example.jni_generator;
-
- /** The pointer to the native Test. */
- long nativeTest;
-
- class Test {
- private static native int nativeStaticMethod(long nativeTest, int arg1);
- private native int nativeMethod(long nativeTest, int arg1);
- @CalledByNative
- private void testMethodWithParam(int iParam);
- @CalledByNative
- private String testMethodWithParamAndReturn(int iParam);
- @CalledByNative
- private static int testStaticMethodWithParam(int iParam);
- @CalledByNative
- private static double testMethodWithNoParam();
- @CalledByNative
- private static String testStaticMethodWithNoParam();
-
- class MyInnerClass {
- @NativeCall("MyInnerClass")
- private native int nativeInit();
- }
- class MyOtherInnerClass {
- @NativeCall("MyOtherInnerClass")
- private native int nativeInit();
- }
- }
- """
- options = TestOptions()
- options.native_exports_optional = False
- jni_from_java = jni_generator.JNIFromJavaSource(
- test_data, 'org/chromium/example/jni_generator/SampleForTests', options)
- self.AssertGoldenTextEquals(jni_from_java.GetContent())
-
def testOuterInnerRaises(self):
test_data = """
package org.chromium.media;
@@ -1240,9 +867,6 @@
@CalledByNative
private static void calledByNative(Bar.Callback callback) {
}
-
- private static native void nativeDoSomething(Bar.Callback callback);
- }
"""
jni_from_java = jni_generator.JNIFromJavaSource(test_data,
'org/chromium/foo/Foo',
@@ -1260,9 +884,6 @@
private static void calledByNative(Bar1.Callback callback1,
Bar2.Callback callback2) {
}
-
- private static native void nativeDoSomething(Bar1.Callback callback1,
- Bar2.Callback callback2);
}
"""
jni_from_java = jni_generator.JNIFromJavaSource(test_data,
@@ -1270,50 +891,6 @@
TestOptions())
self.AssertGoldenTextEquals(jni_from_java.GetContent())
- def testTracing(self):
- test_data = """
- package org.chromium.foo;
-
- @JNINamespace("org::chromium_foo")
- class Foo {
-
- @CalledByNative
- Foo();
-
- @CalledByNative
- void callbackFromNative();
-
- native void nativeInstanceMethod(long nativeInstance);
-
- static native void nativeStaticMethod();
- }
- """
- options_with_tracing = TestOptions()
- options_with_tracing.enable_tracing = True
- jni_from_java = jni_generator.JNIFromJavaSource(
- test_data, 'org/chromium/foo/Foo', options_with_tracing)
- self.AssertGoldenTextEquals(jni_from_java.GetContent())
-
- def testStaticBindingCaller(self):
- test_data = """
- package org.chromium.foo;
-
- class Bar {
- static native void nativeShouldBindCaller(Object caller);
- static native void nativeShouldBindCaller(Object caller, int a);
- static native void nativeFoo(long nativeNativeObject, Bar caller);
- static native void nativeFoo(long nativeNativeObject, Bar caller, int a);
- native void nativeCallNativeMethod(long nativePtr);
- @NativeClassQualifiedName("Foo::Bar")
- native void nativeCallWithQualifiedObject(long nativePtr);
- }
- """
-
- jni_from_java = jni_generator.JNIFromJavaSource(test_data,
- 'org/chromium/foo/Foo',
- TestOptions())
- self.AssertGoldenTextEquals(jni_from_java.GetContent())
-
def testSplitNameExample(self):
opts = TestOptions()
opts.split_name = "sample"
diff --git a/base/android/jni_generator/jni_registration_generator.py b/base/android/jni_generator/jni_registration_generator.py
index f939014..639bd88 100755
--- a/base/android/jni_generator/jni_registration_generator.py
+++ b/base/android/jni_generator/jni_registration_generator.py
@@ -146,9 +146,8 @@
fully_qualified_class = jni_generator.ExtractFullyQualifiedJavaClassName(
path, contents)
- natives = jni_generator.ExtractNatives(contents, 'long')
- natives += jni_generator.ProxyHelpers.ExtractStaticProxyNatives(
+ natives = jni_generator.ProxyHelpers.ExtractStaticProxyNatives(
fully_qualified_class=fully_qualified_class,
contents=contents,
ptr_type='long',
diff --git a/base/android/library_loader/library_loader_hooks.h b/base/android/library_loader/library_loader_hooks.h
index 8e16c95..52734ae 100644
--- a/base/android/library_loader/library_loader_hooks.h
+++ b/base/android/library_loader/library_loader_hooks.h
@@ -8,8 +8,8 @@
#include <jni.h>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/command_line.h"
+#include "base/functional/callback.h"
#include "base/metrics/field_trial.h"
namespace base {
diff --git a/base/android/reached_code_profiler.cc b/base/android/reached_code_profiler.cc
index bf3767b..619cf95 100644
--- a/base/android/reached_code_profiler.cc
+++ b/base/android/reached_code_profiler.cc
@@ -15,12 +15,12 @@
#include "base/android/orderfile/orderfile_buildflags.h"
#include "base/android/reached_addresses_bitset.h"
#include "base/base_switches.h"
-#include "base/bind.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/important_file_writer.h"
+#include "base/functional/bind.h"
#include "base/linux_util.h"
#include "base/logging.h"
#include "base/no_destructor.h"
diff --git a/base/android/task_scheduler/task_runner_android.cc b/base/android/task_scheduler/task_runner_android.cc
index 7371b21..304b8af 100644
--- a/base/android/task_scheduler/task_runner_android.cc
+++ b/base/android/task_scheduler/task_runner_android.cc
@@ -11,8 +11,8 @@
#include "base/android/jni_string.h"
#include "base/android_runtime_jni_headers/Runnable_jni.h"
#include "base/base_jni_headers/TaskRunnerImpl_jni.h"
-#include "base/bind.h"
#include "base/check.h"
+#include "base/functional/bind.h"
#include "base/strings/strcat.h"
#include "base/task/task_executor.h"
#include "base/task/thread_pool/thread_pool_impl.h"
diff --git a/base/android/unguessable_token_android_unittest.cc b/base/android/unguessable_token_android_unittest.cc
index faabb79..7d06c5b 100644
--- a/base/android/unguessable_token_android_unittest.cc
+++ b/base/android/unguessable_token_android_unittest.cc
@@ -14,7 +14,8 @@
JNIEnv* env = AttachCurrentThread();
uint64_t high = 0x1234567812345678;
uint64_t low = 0x0583503029282304;
- base::UnguessableToken token = base::UnguessableToken::Deserialize(high, low);
+ base::UnguessableToken token =
+ base::UnguessableToken::CreateForTesting(high, low);
ScopedJavaLocalRef<jobject> jtoken =
UnguessableTokenAndroid::Create(env, token);
base::UnguessableToken result =
@@ -27,7 +28,8 @@
JNIEnv* env = AttachCurrentThread();
uint64_t high = 0x1234567812345678;
uint64_t low = 0x0583503029282304;
- base::UnguessableToken token = base::UnguessableToken::Deserialize(high, low);
+ base::UnguessableToken token =
+ base::UnguessableToken::CreateForTesting(high, low);
ScopedJavaLocalRef<jobject> jtoken =
UnguessableTokenAndroid::Create(env, token);
ScopedJavaLocalRef<jobject> jtoken_clone =
diff --git a/base/at_exit.cc b/base/at_exit.cc
index 69f1f42..a71988f 100644
--- a/base/at_exit.cc
+++ b/base/at_exit.cc
@@ -8,9 +8,9 @@
#include <ostream>
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/notreached.h"
namespace base {
diff --git a/base/at_exit.h b/base/at_exit.h
index c68fad5..62e547a 100644
--- a/base/at_exit.h
+++ b/base/at_exit.h
@@ -6,9 +6,9 @@
#define BASE_AT_EXIT_H_
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/containers/stack.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/lock.h"
#include "base/thread_annotations.h"
diff --git a/base/at_exit_unittest.cc b/base/at_exit_unittest.cc
index 92c7ef1..3363cb0 100644
--- a/base/at_exit_unittest.cc
+++ b/base/at_exit_unittest.cc
@@ -3,7 +3,7 @@
// found in the LICENSE file.
#include "base/at_exit.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/barrier_callback.h b/base/barrier_callback.h
index c9d8af9..7738782 100644
--- a/base/barrier_callback.h
+++ b/base/barrier_callback.h
@@ -10,11 +10,11 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/check.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/synchronization/lock.h"
#include "base/template_util.h"
#include "base/thread_annotations.h"
diff --git a/base/barrier_callback_unittest.cc b/base/barrier_callback_unittest.cc
index fc93439..3d98940 100644
--- a/base/barrier_callback_unittest.cc
+++ b/base/barrier_callback_unittest.cc
@@ -4,8 +4,8 @@
#include "base/barrier_callback.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
diff --git a/base/barrier_closure.cc b/base/barrier_closure.cc
index 2b4be53..613b46c 100644
--- a/base/barrier_closure.cc
+++ b/base/barrier_closure.cc
@@ -7,7 +7,7 @@
#include <utility>
#include "base/atomic_ref_count.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/numerics/safe_conversions.h"
diff --git a/base/barrier_closure.h b/base/barrier_closure.h
index a88c475..e151946 100644
--- a/base/barrier_closure.h
+++ b/base/barrier_closure.h
@@ -6,7 +6,7 @@
#define BASE_BARRIER_CLOSURE_H_
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
namespace base {
diff --git a/base/barrier_closure_unittest.cc b/base/barrier_closure_unittest.cc
index 47578db..98db45d 100644
--- a/base/barrier_closure_unittest.cc
+++ b/base/barrier_closure_unittest.cc
@@ -4,9 +4,9 @@
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
diff --git a/base/bind.h b/base/bind.h
deleted file mode 100644
index 721f61a..0000000
--- a/base/bind.h
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2022 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//
-// TODO(https://crbug.com/1364441): Temporary forwarding header.
-
-#ifndef BASE_BIND_H_
-#define BASE_BIND_H_
-
-#include "base/functional/bind.h"
-
-#endif // BASE_BIND_H_
diff --git a/base/callback.h b/base/callback.h
deleted file mode 100644
index d561a3d..0000000
--- a/base/callback.h
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2022 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//
-// TODO(https://crbug.com/1364441): Temporary forwarding header.
-
-#ifndef BASE_CALLBACK_H_
-#define BASE_CALLBACK_H_
-
-#include "base/functional/callback.h"
-
-#endif // BASE_CALLBACK_H_
diff --git a/base/callback_forward.h b/base/callback_forward.h
deleted file mode 100644
index 5d18a25..0000000
--- a/base/callback_forward.h
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2022 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//
-// TODO(https://crbug.com/1364441): Temporary forwarding header.
-
-#ifndef BASE_CALLBACK_FORWARD_H_
-#define BASE_CALLBACK_FORWARD_H_
-
-#include "base/functional/callback_forward.h"
-
-#endif // BASE_CALLBACK_FORWARD_H_
diff --git a/base/callback_helpers.h b/base/callback_helpers.h
deleted file mode 100644
index 324877d..0000000
--- a/base/callback_helpers.h
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright 2022 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//
-// TODO(https://crbug.com/1364441): Temporary forwarding header.
-
-#ifndef BASE_CALLBACK_HELPERS_H_
-#define BASE_CALLBACK_HELPERS_H_
-
-#include "base/functional/callback_helpers.h"
-
-#endif // BASE_CALLBACK_HELPERS_H_
diff --git a/base/callback_list.cc b/base/callback_list.cc
index 53557f8..a50252e 100644
--- a/base/callback_list.cc
+++ b/base/callback_list.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "base/callback.h"
+#include "base/functional/callback.h"
namespace base {
diff --git a/base/callback_list.h b/base/callback_list.h
index 72b7d03..bf1c0c5 100644
--- a/base/callback_list.h
+++ b/base/callback_list.h
@@ -11,11 +11,11 @@
#include "base/auto_reset.h"
#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/check.h"
#include "base/containers/cxx20_erase_list.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/weak_ptr.h"
#include "base/ranges/algorithm.h"
diff --git a/base/callback_list_unittest.cc b/base/callback_list_unittest.cc
index 831a8d4..52fffc5 100644
--- a/base/callback_list_unittest.cc
+++ b/base/callback_list_unittest.cc
@@ -7,8 +7,8 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/callback_list_unittest.nc b/base/callback_list_unittest.nc
index dd93139..cc98db5 100644
--- a/base/callback_list_unittest.nc
+++ b/base/callback_list_unittest.nc
@@ -10,8 +10,8 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
namespace base {
diff --git a/base/cancelable_callback.h b/base/cancelable_callback.h
index c4d4b3b..73add8f 100644
--- a/base/cancelable_callback.h
+++ b/base/cancelable_callback.h
@@ -47,10 +47,10 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/check.h"
#include "base/compiler_specific.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/functional/callback_internal.h"
#include "base/memory/weak_ptr.h"
diff --git a/base/cancelable_callback_unittest.cc b/base/cancelable_callback_unittest.cc
index 577a60d..ee6bac7 100644
--- a/base/cancelable_callback_unittest.cc
+++ b/base/cancelable_callback_unittest.cc
@@ -6,8 +6,8 @@
#include <memory>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
diff --git a/base/check.cc b/base/check.cc
index 712a6e4..d263c76 100644
--- a/base/check.cc
+++ b/base/check.cc
@@ -22,9 +22,9 @@
namespace {
-// DCHECK_IS_CONFIGURABLE and ENABLE_LOG_ERROR_NOT_REACHED are both interested
-// in non-FATAL DCHECK()/NOTREACHED() reports.
-#if BUILDFLAG(DCHECK_IS_CONFIGURABLE) || BUILDFLAG(ENABLE_LOG_ERROR_NOT_REACHED)
+// TODO(crbug.com/851128): Once landed this needs to be under
+// BUILDFLAG(DCHECK_IS_CONFIGURABLE) and NotReachedLogMessage cleaned up and
+// instead just be a LogMessage using FATAL.
void DumpOnceWithoutCrashing(LogMessage* log_message) {
// Best-effort gate to prevent multiple DCHECKs from being dumped. This will
// race if multiple threads DCHECK at the same time, but we'll eventually stop
@@ -63,10 +63,6 @@
}
}
};
-#else
-using NotReachedLogMessage = LogMessage;
-#endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE) ||
- // BUILDFLAG(ENABLE_LOG_ERROR_NOT_REACHED)
#if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
diff --git a/base/check.h b/base/check.h
index bc67848..99db3eb 100644
--- a/base/check.h
+++ b/base/check.h
@@ -81,7 +81,9 @@
// Stream for adding optional details to the error message.
std::ostream& stream();
- NOMERGE NOT_TAIL_CALLED ~CheckError();
+ // Try really hard to get the call site and callee as separate stack frames in
+ // crash reports.
+ NOMERGE NOINLINE NOT_TAIL_CALLED ~CheckError();
CheckError(const CheckError&) = delete;
CheckError& operator=(const CheckError&) = delete;
@@ -101,11 +103,11 @@
// Used to trigger a NOTREACHED() without providing file or line while also
// discarding log-stream arguments. See base/notreached.h.
- NOMERGE NOT_TAIL_CALLED static void TriggerNotReached();
+ NOMERGE NOINLINE NOT_TAIL_CALLED static void TriggerNotReached();
// TODO(crbug.com/851128): Mark [[noreturn]] once this is CHECK-fatal on all
// builds.
- NOMERGE NOT_TAIL_CALLED ~NotReachedError();
+ NOMERGE NOINLINE NOT_TAIL_CALLED ~NotReachedError();
private:
using CheckError::CheckError;
diff --git a/base/check_op.h b/base/check_op.h
index 9bc38d9..07ad07d 100644
--- a/base/check_op.h
+++ b/base/check_op.h
@@ -13,6 +13,7 @@
#include "base/check.h"
#include "base/dcheck_is_on.h"
#include "base/debug/debugging_buildflags.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/template_util.h"
// This header defines the (DP)CHECK_EQ etc. macros.
@@ -146,7 +147,9 @@
char* v2_str);
private:
- LogMessage* const log_message_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION LogMessage* const log_message_ = nullptr;
};
// Helper macro for binary operators.
diff --git a/base/check_unittest.cc b/base/check_unittest.cc
index 32b6855..8a7a583 100644
--- a/base/check_unittest.cc
+++ b/base/check_unittest.cc
@@ -4,9 +4,9 @@
#include <tuple>
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/check_deref.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/strings/string_piece.h"
#include "base/test/gtest_util.h"
diff --git a/base/containers/checked_iterators.h b/base/containers/checked_iterators.h
index eeef4b3..0c98b8f 100644
--- a/base/containers/checked_iterators.h
+++ b/base/containers/checked_iterators.h
@@ -11,6 +11,7 @@
#include "base/check_op.h"
#include "base/containers/util.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "build/build_config.h"
namespace base {
@@ -207,9 +208,15 @@
CHECK_EQ(end_, other.end_);
}
- const T* start_ = nullptr;
- T* current_ = nullptr;
- const T* end_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const T* start_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION T* current_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const T* end_ = nullptr;
};
template <typename T>
diff --git a/base/containers/intrusive_heap_unittest.cc b/base/containers/intrusive_heap_unittest.cc
index cdb64d1..f6d83ec 100644
--- a/base/containers/intrusive_heap_unittest.cc
+++ b/base/containers/intrusive_heap_unittest.cc
@@ -4,9 +4,10 @@
#include "base/containers/intrusive_heap.h"
-#include "base/callback_helpers.h"
#include "base/check_op.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/notreached.h"
#include "base/rand_util.h"
#include "base/test/bind.h"
@@ -526,7 +527,9 @@
// the contract expected of the DefaultHeapHandleAccessor.
struct TestElement {
int key;
- HeapHandle* handle;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #reinterpret-cast-trivial-type
+ RAW_PTR_EXCLUSION HeapHandle* handle;
// Make this a min-heap by return > instead of <.
bool operator<(const TestElement& other) const { return key > other.key; }
diff --git a/base/critical_closure.h b/base/critical_closure.h
index d25be8e..228131e 100644
--- a/base/critical_closure.h
+++ b/base/critical_closure.h
@@ -7,13 +7,13 @@
#include <utility>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/strings/string_piece.h"
#include "build/build_config.h"
#if BUILDFLAG(IS_IOS)
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/ios/scoped_critical_action.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#endif
diff --git a/base/debug/activity_analyzer_unittest.cc b/base/debug/activity_analyzer_unittest.cc
index 771c347..414ab86 100644
--- a/base/debug/activity_analyzer_unittest.cc
+++ b/base/debug/activity_analyzer_unittest.cc
@@ -8,13 +8,13 @@
#include <memory>
#include "base/auto_reset.h"
-#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/debug/activity_tracker.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/memory_mapped_file.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/read_only_shared_memory_region.h"
diff --git a/base/debug/activity_tracker.h b/base/debug/activity_tracker.h
index 07c0ed5..f4160da 100644
--- a/base/debug/activity_tracker.h
+++ b/base/debug/activity_tracker.h
@@ -18,10 +18,10 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/containers/span.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/callback.h"
#include "base/gtest_prod_util.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/debug/activity_tracker_unittest.cc b/base/debug/activity_tracker_unittest.cc
index 317e4f5..8f1e16a 100644
--- a/base/debug/activity_tracker_unittest.cc
+++ b/base/debug/activity_tracker_unittest.cc
@@ -7,12 +7,12 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/memory_mapped_file.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/pending_task.h"
diff --git a/base/debug/asan_service.cc b/base/debug/asan_service.cc
index da7366c..1ec961a 100644
--- a/base/debug/asan_service.cc
+++ b/base/debug/asan_service.cc
@@ -7,6 +7,7 @@
#if defined(ADDRESS_SANITIZER)
#include <sanitizer/asan_interface.h>
+#include "base/debug/task_trace.h"
#include "base/no_destructor.h"
#include "base/process/process.h"
#include "base/process/process_handle.h"
@@ -24,10 +25,35 @@
namespace base {
namespace debug {
+namespace {
+NO_SANITIZE("address")
+void TaskTraceErrorCallback(const char* error, bool*) {
+ // Use the sanitizer api to symbolize the task trace, which otherwise might
+ // not symbolize properly. This also lets us format the task trace in the
+ // same way as the address sanitizer backtraces, which also means that we can
+ // get the stack trace symbolized with asan_symbolize.py in the cases where
+ // symbolization at runtime fails.
+ std::array<const void*, 4> addresses;
+ size_t address_count = TaskTrace().GetAddresses(addresses);
+
+ AsanService::GetInstance()->Log("Task trace:");
+ size_t frame_index = 0;
+ for (size_t i = 0; i < std::min(address_count, addresses.size()); ++i) {
+ char buffer[4096] = {};
+ void* address = const_cast<void*>(addresses[i]);
+ __sanitizer_symbolize_pc(address, "%p %F %L", buffer, sizeof(buffer));
+ for (char* ptr = buffer; *ptr != 0; ptr += strlen(ptr)) {
+ AsanService::GetInstance()->Log(" #%i %s", frame_index++, ptr);
+ }
+ }
+ AsanService::GetInstance()->Log("");
+}
+} // namespace
+
// static
NO_SANITIZE("address")
AsanService* AsanService::GetInstance() {
- static base::NoDestructor<AsanService> instance;
+ static NoDestructor<AsanService> instance;
return instance.get();
}
@@ -35,6 +61,7 @@
AutoLock lock(lock_);
if (!is_initialized_) {
__asan_set_error_report_callback(ErrorReportCallback);
+ error_callbacks_.push_back(TaskTraceErrorCallback);
is_initialized_ = true;
}
}
diff --git a/base/debug/asan_service_unittest.cc b/base/debug/asan_service_unittest.cc
index e2328b6..f4d9c7c 100644
--- a/base/debug/asan_service_unittest.cc
+++ b/base/debug/asan_service_unittest.cc
@@ -11,7 +11,10 @@
#include <sstream>
#include "base/debug/asan_invalid_access.h"
+#include "base/run_loop.h"
#include "base/strings/string_piece.h"
+#include "base/test/bind.h"
+#include "base/test/task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -93,6 +96,34 @@
EXPECT_EXIT(AsanHeapUseAfterFree(), ExitedCleanly, "EXITING");
}
+class AsanTaskTraceTest {
+ public:
+ AsanTaskTraceTest() {}
+
+ void Run() {
+ task_runner_.PostTask(
+ FROM_HERE, BindOnce(&AsanTaskTraceTest::PostingTask, Unretained(this)));
+ task_environment_.RunUntilIdle();
+ }
+
+ private:
+ void PostingTask() {
+ task_runner_.PostTask(FROM_HERE, BindOnce(&AsanHeapUseAfterFree));
+ }
+
+ test::TaskEnvironment task_environment_;
+ SingleThreadTaskRunner& task_runner_ =
+ *task_environment_.GetMainThreadTaskRunner();
+};
+
+TEST_F(AsanServiceTest, TaskTraceCallback) {
+ AsanTaskTraceTest test;
+ // We can't check the symbolization of the task trace, as this will fail on
+ // build configurations that don't include symbols. We instead just check
+ // that the task trace has the correct number of entries.
+ EXPECT_DEATH(test.Run(), "#0 0x.* .*\\n\\s+#1 0x.*");
+}
+
} // namespace debug
} // namespace base
diff --git a/base/debug/task_trace.cc b/base/debug/task_trace.cc
index 901008b..8a9f8a8 100644
--- a/base/debug/task_trace.cc
+++ b/base/debug/task_trace.cc
@@ -93,12 +93,16 @@
return stream.str();
}
-base::span<const void* const> TaskTrace::AddressesForTesting() const {
- if (empty())
- return {};
+size_t TaskTrace::GetAddresses(span<const void*> addresses) const {
size_t count = 0;
- const void* const* addresses = stack_trace_->Addresses(&count);
- return {addresses, count};
+ if (empty()) {
+ return count;
+ }
+ const void* const* current_addresses = stack_trace_->Addresses(&count);
+ for (size_t i = 0; i < count && i < addresses.size(); ++i) {
+ addresses[i] = current_addresses[i];
+ }
+ return count;
}
std::ostream& operator<<(std::ostream& os, const TaskTrace& task_trace) {
diff --git a/base/debug/task_trace.h b/base/debug/task_trace.h
index ebe3862..7cad531 100644
--- a/base/debug/task_trace.h
+++ b/base/debug/task_trace.h
@@ -49,8 +49,10 @@
// Resolves trace to symbols and returns as string.
std::string ToString() const;
- // Returns the list of addresses in the task trace for testing.
- base::span<const void* const> AddressesForTesting() const;
+ // Reads the list of addresses currently in the task trace into `addresses`,
+ // and returns the maximum length of addresses that could have been read,
+ // which may differ from `addresses.size()`.
+ size_t GetAddresses(span<const void*> addresses) const;
private:
absl::optional<StackTrace> stack_trace_;
diff --git a/base/debug/task_trace_unittest.cc b/base/debug/task_trace_unittest.cc
index 76596ca..fdc010a 100644
--- a/base/debug/task_trace_unittest.cc
+++ b/base/debug/task_trace_unittest.cc
@@ -20,7 +20,8 @@
TEST(TaskTraceTest, NoTask) {
TaskTrace task_trace;
EXPECT_TRUE(task_trace.empty());
- EXPECT_EQ(task_trace.AddressesForTesting().size(), 0ul);
+ std::array<const void*, 4> addresses = {0};
+ EXPECT_EQ(task_trace.GetAddresses(addresses), 0ul);
}
class ThreeTasksTest {
@@ -36,8 +37,8 @@
void TaskA() {
TaskTrace task_trace;
EXPECT_FALSE(task_trace.empty());
- base::span<const void* const> addresses = task_trace.AddressesForTesting();
- EXPECT_EQ(addresses.size(), 1ul);
+ std::array<const void*, 4> addresses = {0};
+ EXPECT_EQ(task_trace.GetAddresses(addresses), 1ul);
task_a_address = addresses[0];
task_runner->PostTask(FROM_HERE, base::BindOnce(&ThreeTasksTest::TaskB,
base::Unretained(this)));
@@ -46,8 +47,8 @@
void TaskB() {
TaskTrace task_trace;
EXPECT_FALSE(task_trace.empty());
- base::span<const void* const> addresses = task_trace.AddressesForTesting();
- EXPECT_EQ(addresses.size(), 2ul);
+ std::array<const void*, 4> addresses = {0};
+ EXPECT_EQ(task_trace.GetAddresses(addresses), 2ul);
task_b_address = addresses[0];
EXPECT_EQ(addresses[1], task_a_address);
task_runner->PostTask(FROM_HERE, base::BindOnce(&ThreeTasksTest::TaskC,
@@ -57,8 +58,8 @@
void TaskC() {
TaskTrace task_trace;
EXPECT_FALSE(task_trace.empty());
- base::span<const void* const> addresses = task_trace.AddressesForTesting();
- EXPECT_EQ(addresses.size(), 3ul);
+ std::array<const void*, 4> addresses;
+ EXPECT_EQ(task_trace.GetAddresses(addresses), 3ul);
EXPECT_EQ(addresses[1], task_b_address);
EXPECT_EQ(addresses[2], task_a_address);
}
diff --git a/base/features.cc b/base/features.cc
index a94eadb..2f9e53c 100644
--- a/base/features.cc
+++ b/base/features.cc
@@ -13,7 +13,7 @@
// backed by executable files.
BASE_FEATURE(kEnforceNoExecutableFileHandles,
"EnforceNoExecutableFileHandles",
- FEATURE_ENABLED_BY_DEFAULT);
+ FEATURE_DISABLED_BY_DEFAULT);
// Optimizes parsing and loading of data: URLs.
BASE_FEATURE(kOptimizeDataUrls, "OptimizeDataUrls", FEATURE_ENABLED_BY_DEFAULT);
diff --git a/base/files/file_descriptor_watcher_posix.cc b/base/files/file_descriptor_watcher_posix.cc
index 7529b15..06bf1dc 100644
--- a/base/files/file_descriptor_watcher_posix.cc
+++ b/base/files/file_descriptor_watcher_posix.cc
@@ -6,8 +6,8 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ref.h"
#include "base/message_loop/message_pump_for_io.h"
diff --git a/base/files/file_descriptor_watcher_posix.h b/base/files/file_descriptor_watcher_posix.h
index f485ee7..21ec010 100644
--- a/base/files/file_descriptor_watcher_posix.h
+++ b/base/files/file_descriptor_watcher_posix.h
@@ -8,8 +8,8 @@
#include <memory>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_pump_for_io.h"
diff --git a/base/files/file_descriptor_watcher_posix_unittest.cc b/base/files/file_descriptor_watcher_posix_unittest.cc
index 5645d7c..099f148 100644
--- a/base/files/file_descriptor_watcher_posix_unittest.cc
+++ b/base/files/file_descriptor_watcher_posix_unittest.cc
@@ -8,9 +8,9 @@
#include <memory>
-#include "base/bind.h"
#include "base/containers/span.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_pump_type.h"
#include "base/posix/eintr_wrapper.h"
diff --git a/base/files/file_path_watcher.h b/base/files/file_path_watcher.h
index ac9f638..2f3a53a 100644
--- a/base/files/file_path_watcher.h
+++ b/base/files/file_path_watcher.h
@@ -11,7 +11,7 @@
#include <utility>
#include "base/base_export.h"
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/scoped_refptr.h"
#include "base/sequence_checker.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/files/file_path_watcher_fsevents.cc b/base/files/file_path_watcher_fsevents.cc
index c4caff9..6c9461e 100644
--- a/base/files/file_path_watcher_fsevents.cc
+++ b/base/files/file_path_watcher_fsevents.cc
@@ -9,9 +9,9 @@
#include <algorithm>
#include <list>
-#include "base/bind.h"
#include "base/check.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/stringprintf.h"
diff --git a/base/files/file_path_watcher_inotify.cc b/base/files/file_path_watcher_inotify.cc
index 89020b9..bf72568 100644
--- a/base/files/file_path_watcher_inotify.cc
+++ b/base/files/file_path_watcher_inotify.cc
@@ -23,12 +23,12 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_path_watcher_inotify.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/logging.h"
diff --git a/base/files/file_path_watcher_kqueue.cc b/base/files/file_path_watcher_kqueue.cc
index 98bc395..3e911fe 100644
--- a/base/files/file_path_watcher_kqueue.cc
+++ b/base/files/file_path_watcher_kqueue.cc
@@ -11,9 +11,9 @@
#include <string>
#include <vector>
-#include "base/bind.h"
#include "base/file_descriptor_posix.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/ranges/algorithm.h"
#include "base/strings/stringprintf.h"
diff --git a/base/files/file_path_watcher_unittest.cc b/base/files/file_path_watcher_unittest.cc
index 84c4377..5165f3e 100644
--- a/base/files/file_path_watcher_unittest.cc
+++ b/base/files/file_path_watcher_unittest.cc
@@ -9,11 +9,11 @@
#include <string>
#include <vector>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/run_loop.h"
diff --git a/base/files/file_proxy.cc b/base/files/file_proxy.cc
index 1209172..c3b8083 100644
--- a/base/files/file_proxy.cc
+++ b/base/files/file_proxy.cc
@@ -7,10 +7,10 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/task/task_runner.h"
diff --git a/base/files/file_proxy.h b/base/files/file_proxy.h
index 6a6415c..680a511 100644
--- a/base/files/file_proxy.h
+++ b/base/files/file_proxy.h
@@ -8,9 +8,9 @@
#include <stdint.h>
#include "base/base_export.h"
-#include "base/callback_forward.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/weak_ptr.h"
namespace base {
diff --git a/base/files/file_proxy_unittest.cc b/base/files/file_proxy_unittest.cc
index 1861e64..6ae91d1 100644
--- a/base/files/file_proxy_unittest.cc
+++ b/base/files/file_proxy_unittest.cc
@@ -9,10 +9,10 @@
#include <utility>
-#include "base/bind.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/test/task_environment.h"
diff --git a/base/files/file_util.h b/base/files/file_util.h
index ff8314a..7ec9f2b 100644
--- a/base/files/file_util.h
+++ b/base/files/file_util.h
@@ -17,11 +17,11 @@
#include <string>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/containers/span.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/scoped_file.h"
+#include "base/functional/callback.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/base/files/file_util_unittest.cc b/base/files/file_util_unittest.cc
index 27cdb16..42c5cb0 100644
--- a/base/files/file_util_unittest.cc
+++ b/base/files/file_util_unittest.cc
@@ -17,16 +17,17 @@
#include <vector>
#include "base/base_paths.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/environment.h"
+#include "base/features.h"
#include "base/files/file.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/platform_file.h"
#include "base/files/scoped_file.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/guid.h"
#include "base/logging.h"
#include "base/path_service.h"
@@ -37,6 +38,7 @@
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/multiprocess_test.h"
+#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/test/test_file_util.h"
#include "base/test/test_timeouts.h"
@@ -778,6 +780,9 @@
}
TEST_F(FileUtilTest, PreventExecuteMappingNewFile) {
+ base::test::ScopedFeatureList enforcement_feature;
+ enforcement_feature.InitAndEnableFeature(
+ features::kEnforceNoExecutableFileHandles);
FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
ASSERT_FALSE(PathExists(file));
@@ -797,6 +802,9 @@
}
TEST_F(FileUtilTest, PreventExecuteMappingExisting) {
+ base::test::ScopedFeatureList enforcement_feature;
+ enforcement_feature.InitAndEnableFeature(
+ features::kEnforceNoExecutableFileHandles);
FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
CreateTextFile(file, bogus_content);
ASSERT_TRUE(PathExists(file));
@@ -816,6 +824,9 @@
}
TEST_F(FileUtilTest, PreventExecuteMappingOpenFile) {
+ base::test::ScopedFeatureList enforcement_feature;
+ enforcement_feature.InitAndEnableFeature(
+ features::kEnforceNoExecutableFileHandles);
FilePath file = temp_dir_.GetPath().Append(FPL("afile.txt"));
CreateTextFile(file, bogus_content);
ASSERT_TRUE(PathExists(file));
@@ -841,6 +852,9 @@
}
TEST(FileUtilDeathTest, DisallowNoExecuteOnUnsafeFile) {
+ base::test::ScopedFeatureList enforcement_feature;
+ enforcement_feature.InitAndEnableFeature(
+ features::kEnforceNoExecutableFileHandles);
base::FilePath local_app_data;
// This test places a file in %LOCALAPPDATA% to verify that the checks in
// IsPathSafeToSetAclOn work correctly.
@@ -862,14 +876,42 @@
"Unsafe to deny execute access to path");
}
-TEST_F(FileUtilTest, NoExecuteOnSafeFile) {
+MULTIPROCESS_TEST_MAIN(NoExecuteOnSafeFileMain) {
base::FilePath temp_file;
- // A file created in temp dir should always be permitted.
- ASSERT_TRUE(base::CreateTemporaryFile(&temp_file));
+ CHECK(base::CreateTemporaryFile(&temp_file));
+
+ // A file with FLAG_WIN_NO_EXECUTE created in temp dir should always be
+ // permitted.
File reopen_file(temp_file, File::FLAG_READ | File::FLAG_WRITE |
File::FLAG_WIN_NO_EXECUTE |
File::FLAG_OPEN_ALWAYS |
File::FLAG_DELETE_ON_CLOSE);
+ return 0;
+}
+
+TEST_F(FileUtilTest, NoExecuteOnSafeFile) {
+ FilePath new_dir;
+ ASSERT_TRUE(CreateTemporaryDirInDir(
+ temp_dir_.GetPath(), FILE_PATH_LITERAL("NoExecuteOnSafeFileLongPath"),
+ &new_dir));
+
+ FilePath short_dir = base::MakeShortFilePath(new_dir);
+
+ // Verify that the path really is 8.3 now.
+ ASSERT_NE(new_dir.value(), short_dir.value());
+
+ LaunchOptions options;
+ options.environment[L"TMP"] = short_dir.value();
+
+ CommandLine child_command_line(GetMultiProcessTestChildBaseCommandLine());
+
+ Process child_process = SpawnMultiProcessTestChild(
+ "NoExecuteOnSafeFileMain", child_command_line, options);
+ ASSERT_TRUE(child_process.IsValid());
+ int rv = -1;
+ ASSERT_TRUE(WaitForMultiprocessTestChildExit(
+ child_process, TestTimeouts::action_timeout(), &rv));
+ ASSERT_EQ(0, rv);
}
class FileUtilExecuteEnforcementTest
diff --git a/base/files/important_file_writer.cc b/base/files/important_file_writer.cc
index 1d53336..1eaedc5 100644
--- a/base/files/important_file_writer.cc
+++ b/base/files/important_file_writer.cc
@@ -12,8 +12,6 @@
#include <string>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/check.h"
#include "base/critical_closure.h"
#include "base/debug/alias.h"
@@ -21,6 +19,8 @@
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/important_file_writer_cleaner.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
diff --git a/base/files/important_file_writer.h b/base/files/important_file_writer.h
index 146e1c0..2c6a696 100644
--- a/base/files/important_file_writer.h
+++ b/base/files/important_file_writer.h
@@ -9,8 +9,8 @@
#include <string>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/files/file_path.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/sequence_checker.h"
#include "base/strings/string_piece.h"
diff --git a/base/files/important_file_writer_cleaner.cc b/base/files/important_file_writer_cleaner.cc
index 66841ce..46e1263 100644
--- a/base/files/important_file_writer_cleaner.cc
+++ b/base/files/important_file_writer_cleaner.cc
@@ -9,9 +9,9 @@
#include <iterator>
#include <utility>
-#include "base/bind.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
#include "base/no_destructor.h"
#include "base/process/process.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/files/important_file_writer_unittest.cc b/base/files/important_file_writer_unittest.cc
index 605cbd3..8d36b34 100644
--- a/base/files/important_file_writer_unittest.cc
+++ b/base/files/important_file_writer_unittest.cc
@@ -4,11 +4,11 @@
#include "base/files/important_file_writer.h"
-#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/notreached.h"
diff --git a/base/functional/bind_internal.h b/base/functional/bind_internal.h
index 8f625f4..c078a3a 100644
--- a/base/functional/bind_internal.h
+++ b/base/functional/bind_internal.h
@@ -35,7 +35,7 @@
#include "base/mac/scoped_block.h"
#endif
-// See base/callback.h for user documentation.
+// See base/functional/callback.h for user documentation.
//
//
// CONCEPTS:
@@ -176,14 +176,10 @@
// before invoking the bound functor (unless stated otherwise, see
// `UnsafeDangling()` and `UnsafeDanglingUntriaged()`), when retrieving the
// pointer value via `get()` above.
- using StorageType = std::conditional_t<
- raw_ptr_traits::IsSupportedType<T>::value,
- raw_ptr<T,
- std::conditional_t<
- std::is_same_v<Trait, unretained_traits::MayDangleUntriaged>,
- DanglingUntriaged,
- DisableDanglingPtrDetection>>,
- T*>;
+ using StorageType =
+ std::conditional_t<raw_ptr_traits::IsSupportedType<T>::value,
+ MayBeDangling<T>,
+ T*>;
#endif // PA_CONFIG(ENABLE_MTE_CHECKED_PTR_SUPPORT_WITH_64_BITS_POINTERS)
// Avoid converting between different `raw_ptr` types when calling `get()`.
// See the comment by `GetPtrType` describing why this wouldn't be good.
@@ -1404,15 +1400,16 @@
// (or `MayBeDangling<T>`).
static constexpr bool kParamIsDanglingRawPtr =
IsRawPtrMayDangleV<FunctionParamType>;
- // true if the bound parameter is of type `UnretainedWrapper<T,
- // RawPtrMayDangle>`.
+ // true if the bound parameter is of type
+ // `UnretainedWrapper<T, unretained_traits::MayDangle>`.
static constexpr bool kBoundPtrMayDangle =
IsUnretainedMayDangle<StorageType>;
// true if the receiver argument **must** be of type `MayBeDangling<T>`.
static constexpr bool kMayBeDanglingMustBeUsed =
kBoundPtrMayDangle && kParamIsDanglingRawPtr;
// true iff:
- // - bound parameter is of type `UnretainedWrapper<T, RawPtrMayDangle>`
+ // - bound parameter is of type
+ // `UnretainedWrapper<T, unretained_traits::MayDangle>`
// - the receiving argument is of type `MayBeDangling<T>`
template <bool is_method>
static constexpr bool kMayBeDanglingPtrPassedCorrectly =
diff --git a/base/functional/callback.h b/base/functional/callback.h
index 5c4bf00..189259f 100644
--- a/base/functional/callback.h
+++ b/base/functional/callback.h
@@ -4,7 +4,7 @@
//
// NOTE: Header files that do not require the full definition of
// base::{Once,Repeating}Callback or base::{Once,Repeating}Closure should
-// #include "base/callback_forward.h" instead of this file.
+// #include "base/functional/callback_forward.h" instead of this file.
#ifndef BASE_FUNCTIONAL_CALLBACK_H_
#define BASE_FUNCTIONAL_CALLBACK_H_
diff --git a/base/functional/function_ref_unittest.nc b/base/functional/function_ref_unittest.nc
index 927c778..72098e1 100644
--- a/base/functional/function_ref_unittest.nc
+++ b/base/functional/function_ref_unittest.nc
@@ -5,8 +5,8 @@
// This is a "No Compile Test" suite.
// http://dev.chromium.org/developers/testing/no-compile-tests
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/functional/function_ref.h"
#include "third_party/abseil-cpp/absl/functional/function_ref.h"
diff --git a/base/i18n/streaming_utf8_validator_perftest.cc b/base/i18n/streaming_utf8_validator_perftest.cc
index 8d385f1..ac6a649 100644
--- a/base/i18n/streaming_utf8_validator_perftest.cc
+++ b/base/i18n/streaming_utf8_validator_perftest.cc
@@ -16,8 +16,8 @@
#include <string>
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/test/perf_time_logger.h"
diff --git a/base/i18n/streaming_utf8_validator_unittest.cc b/base/i18n/streaming_utf8_validator_unittest.cc
index 770ceed..765edbb 100644
--- a/base/i18n/streaming_utf8_validator_unittest.cc
+++ b/base/i18n/streaming_utf8_validator_unittest.cc
@@ -11,7 +11,7 @@
#include <string>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
diff --git a/base/json/json_parser.cc b/base/json/json_parser.cc
index c9b4062..fbb226e 100644
--- a/base/json/json_parser.cc
+++ b/base/json/json_parser.cc
@@ -197,9 +197,13 @@
void JSONParser::StringBuilder::Append(base_icu::UChar32 point) {
DCHECK(IsValidCodepoint(point));
- if (point < kExtendedASCIIStart && !string_) {
- DCHECK_EQ(static_cast<char>(point), pos_[length_]);
- ++length_;
+ if (point < kExtendedASCIIStart) {
+ if (!string_) {
+ DCHECK_EQ(static_cast<char>(point), pos_[length_]);
+ ++length_;
+ } else {
+ string_->push_back(static_cast<char>(point));
+ }
} else {
Convert();
if (UNLIKELY(point == kUnicodeReplacementPoint)) {
@@ -529,11 +533,14 @@
// std::string.
StringBuilder string(pos());
- while (PeekChar()) {
+ while (absl::optional<char> c = PeekChar()) {
base_icu::UChar32 next_char = 0;
- if (!ReadUnicodeCharacter(input_.data(), input_.length(), &index_,
- &next_char) ||
- !IsValidCodepoint(next_char)) {
+ if (static_cast<unsigned char>(*c) < kExtendedASCIIStart) {
+ // Fast path for ASCII.
+ next_char = *c;
+ } else if (!ReadUnicodeCharacter(input_.data(), input_.length(), &index_,
+ &next_char) ||
+ !IsValidCodepoint(next_char)) {
if ((options_ & JSON_REPLACE_INVALID_CHARACTERS) == 0) {
ReportError(JSON_UNSUPPORTED_ENCODING, 0);
return false;
diff --git a/base/json/values_util_unittest.cc b/base/json/values_util_unittest.cc
index 167d050..33fefea 100644
--- a/base/json/values_util_unittest.cc
+++ b/base/json/values_util_unittest.cc
@@ -95,7 +95,7 @@
};
for (const auto& test_case : kTestCases) {
UnguessableToken input =
- UnguessableToken::Deserialize(test_case.high, test_case.low);
+ UnguessableToken::CreateForTesting(test_case.high, test_case.low);
Value expected(test_case.expected);
SCOPED_TRACE(testing::Message() << "expected: " << test_case.expected);
diff --git a/base/lazy_instance_unittest.cc b/base/lazy_instance_unittest.cc
index dfc9f40..89bdd5b 100644
--- a/base/lazy_instance_unittest.cc
+++ b/base/lazy_instance_unittest.cc
@@ -12,8 +12,8 @@
#include "base/atomic_sequence_num.h"
#include "base/atomicops.h"
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/lazy_instance.h"
#include "base/memory/aligned_memory.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/logging.cc b/base/logging.cc
index 1ec14b5..615b432 100644
--- a/base/logging.cc
+++ b/base/logging.cc
@@ -86,7 +86,6 @@
#include <utility>
#include "base/base_switches.h"
-#include "base/callback.h"
#include "base/command_line.h"
#include "base/containers/stack.h"
#include "base/debug/activity_tracker.h"
@@ -94,6 +93,7 @@
#include "base/debug/debugger.h"
#include "base/debug/stack_trace.h"
#include "base/debug/task_trace.h"
+#include "base/functional/callback.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
diff --git a/base/logging.h b/base/logging.h
index 50579d3..1ae198e 100644
--- a/base/logging.h
+++ b/base/logging.h
@@ -13,9 +13,9 @@
#include <string>
#include "base/base_export.h"
-#include "base/callback_forward.h"
#include "base/compiler_specific.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/callback_forward.h"
#include "base/logging_buildflags.h"
#include "base/scoped_clear_last_error.h"
#include "base/strings/string_piece_forward.h"
diff --git a/base/logging_unittest.cc b/base/logging_unittest.cc
index 6cfe45c..3b17939 100644
--- a/base/logging_unittest.cc
+++ b/base/logging_unittest.cc
@@ -5,11 +5,11 @@
#include <sstream>
#include <string>
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "base/process/process.h"
diff --git a/base/memory/MIRACLE_PTR_OWNERS b/base/memory/MIRACLE_PTR_OWNERS
index 49ec7a4..c1390d5 100644
--- a/base/memory/MIRACLE_PTR_OWNERS
+++ b/base/memory/MIRACLE_PTR_OWNERS
@@ -3,3 +3,4 @@
dcheng@chromium.org
glazunov@google.com
keishi@chromium.org
+lukasza@chromium.org
diff --git a/base/memory/discardable_memory_allocator.h b/base/memory/discardable_memory_allocator.h
index 6459281..f7a7605 100644
--- a/base/memory/discardable_memory_allocator.h
+++ b/base/memory/discardable_memory_allocator.h
@@ -10,7 +10,7 @@
#include <memory>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/discardable_memory.h"
namespace base {
diff --git a/base/memory/madv_free_discardable_memory_allocator_posix.h b/base/memory/madv_free_discardable_memory_allocator_posix.h
index 04d9b3b..3e12720 100644
--- a/base/memory/madv_free_discardable_memory_allocator_posix.h
+++ b/base/memory/madv_free_discardable_memory_allocator_posix.h
@@ -11,8 +11,8 @@
#include <memory>
#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/memory/discardable_memory.h"
#include "base/memory/discardable_memory_allocator.h"
#include "base/memory/madv_free_discardable_memory_posix.h"
diff --git a/base/memory/madv_free_discardable_memory_posix.cc b/base/memory/madv_free_discardable_memory_posix.cc
index 051cc08..ffb6676 100644
--- a/base/memory/madv_free_discardable_memory_posix.cc
+++ b/base/memory/madv_free_discardable_memory_posix.cc
@@ -14,7 +14,7 @@
#include "base/atomicops.h"
#include "base/bits.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/memory/madv_free_discardable_memory_allocator_posix.h"
#include "base/memory/page_size.h"
diff --git a/base/memory/madv_free_discardable_memory_posix.h b/base/memory/madv_free_discardable_memory_posix.h
index 2cca982..bdee8b8 100644
--- a/base/memory/madv_free_discardable_memory_posix.h
+++ b/base/memory/madv_free_discardable_memory_posix.h
@@ -12,7 +12,7 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/discardable_memory.h"
#include "base/memory/raw_ptr.h"
#include "base/sequence_checker.h"
diff --git a/base/memory/madv_free_discardable_memory_posix_unittest.cc b/base/memory/madv_free_discardable_memory_posix_unittest.cc
index 4b0b2fd..11d5404 100644
--- a/base/memory/madv_free_discardable_memory_posix_unittest.cc
+++ b/base/memory/madv_free_discardable_memory_posix_unittest.cc
@@ -8,10 +8,10 @@
#include <sys/mman.h>
#include <memory>
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/files/scoped_file.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/madv_free_discardable_memory_allocator_posix.h"
#include "base/memory/madv_free_discardable_memory_posix.h"
#include "base/memory/page_size.h"
diff --git a/base/memory/memory_pressure_listener.h b/base/memory/memory_pressure_listener.h
index 7cf058c..29e9364 100644
--- a/base/memory/memory_pressure_listener.h
+++ b/base/memory/memory_pressure_listener.h
@@ -11,7 +11,7 @@
#define BASE_MEMORY_MEMORY_PRESSURE_LISTENER_H_
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/tracing_buildflags.h"
diff --git a/base/memory/memory_pressure_listener_unittest.cc b/base/memory/memory_pressure_listener_unittest.cc
index 79d4be5..13232c9 100644
--- a/base/memory/memory_pressure_listener_unittest.cc
+++ b/base/memory/memory_pressure_listener_unittest.cc
@@ -4,7 +4,7 @@
#include "base/memory/memory_pressure_listener.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/run_loop.h"
#include "base/test/task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
diff --git a/base/memory/memory_pressure_monitor.h b/base/memory/memory_pressure_monitor.h
index 10b5895..3e5401b 100644
--- a/base/memory/memory_pressure_monitor.h
+++ b/base/memory/memory_pressure_monitor.h
@@ -6,7 +6,7 @@
#define BASE_MEMORY_MEMORY_PRESSURE_MONITOR_H_
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/time/time.h"
diff --git a/base/memory/raw_ptr.cc b/base/memory/raw_ptr.cc
index 5ca1e2a..2dbab45 100644
--- a/base/memory/raw_ptr.cc
+++ b/base/memory/raw_ptr.cc
@@ -27,11 +27,12 @@
#endif
uintptr_t slot_start =
partition_alloc::PartitionAllocGetSlotStartInBRPPool(address);
- if constexpr (AllowDangling)
+ if constexpr (AllowDangling) {
partition_alloc::internal::PartitionRefCountPointer(slot_start)
->AcquireFromUnprotectedPtr();
- else
+ } else {
partition_alloc::internal::PartitionRefCountPointer(slot_start)->Acquire();
+ }
}
template <bool AllowDangling>
@@ -43,12 +44,14 @@
partition_alloc::PartitionAllocGetSlotStartInBRPPool(address);
if constexpr (AllowDangling) {
if (partition_alloc::internal::PartitionRefCountPointer(slot_start)
- ->ReleaseFromUnprotectedPtr())
+ ->ReleaseFromUnprotectedPtr()) {
partition_alloc::internal::PartitionAllocFreeForRefCounting(slot_start);
+ }
} else {
if (partition_alloc::internal::PartitionRefCountPointer(slot_start)
- ->Release())
+ ->Release()) {
partition_alloc::internal::PartitionAllocFreeForRefCounting(slot_start);
+ }
}
}
@@ -77,19 +80,13 @@
}
template <bool AllowDangling>
+template <typename Z>
partition_alloc::PtrPosWithinAlloc
-BackupRefPtrImpl<AllowDangling>::IsValidSignedDelta(uintptr_t address,
- ptrdiff_t delta_in_bytes) {
- return partition_alloc::internal::PartitionAllocIsValidPtrDelta(
- address, delta_in_bytes);
-}
-
-template <bool AllowDangling>
-partition_alloc::PtrPosWithinAlloc
-BackupRefPtrImpl<AllowDangling>::IsValidUnsignedDelta(uintptr_t address,
- size_t delta_in_bytes) {
- return partition_alloc::internal::PartitionAllocIsValidPtrDelta(
- address, delta_in_bytes);
+BackupRefPtrImpl<AllowDangling>::IsValidDelta(
+ uintptr_t address,
+ partition_alloc::internal::PtrDelta<Z> delta) {
+ return partition_alloc::internal::PartitionAllocIsValidPtrDelta(address,
+ delta);
}
// Explicitly instantiates the two BackupRefPtr variants in the .cc. This
@@ -97,6 +94,23 @@
template struct BackupRefPtrImpl</*AllowDangling=*/false>;
template struct BackupRefPtrImpl</*AllowDangling=*/true>;
+template PA_COMPONENT_EXPORT(RAW_PTR)
+ partition_alloc::PtrPosWithinAlloc BackupRefPtrImpl<false>::IsValidDelta(
+ uintptr_t,
+ partition_alloc::internal::PtrDelta<size_t>);
+template PA_COMPONENT_EXPORT(RAW_PTR)
+ partition_alloc::PtrPosWithinAlloc BackupRefPtrImpl<false>::IsValidDelta(
+ uintptr_t,
+ partition_alloc::internal::PtrDelta<ptrdiff_t>);
+template PA_COMPONENT_EXPORT(RAW_PTR)
+ partition_alloc::PtrPosWithinAlloc BackupRefPtrImpl<true>::IsValidDelta(
+ uintptr_t,
+ partition_alloc::internal::PtrDelta<size_t>);
+template PA_COMPONENT_EXPORT(RAW_PTR)
+ partition_alloc::PtrPosWithinAlloc BackupRefPtrImpl<true>::IsValidDelta(
+ uintptr_t,
+ partition_alloc::internal::PtrDelta<ptrdiff_t>);
+
#if BUILDFLAG(PA_DCHECK_IS_ON) || BUILDFLAG(ENABLE_BACKUP_REF_PTR_SLOW_CHECKS)
void CheckThatAddressIsntWithinFirstPartitionPage(uintptr_t address) {
if (partition_alloc::internal::IsManagedByDirectMap(address)) {
@@ -115,126 +129,7 @@
} // namespace base::internal
-#elif BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
-
-#include <sanitizer/asan_interface.h>
-#include "base/allocator/partition_allocator/partition_alloc_base/debug/alias.h"
-#include "base/compiler_specific.h"
-#include "base/debug/asan_service.h"
-#include "base/memory/raw_ptr_asan_service.h"
-#include "base/process/process.h"
-
-namespace base::internal {
-
-namespace {
-
-static bool asan_brp_callbacks_installed = false;
-static AsanBackupRefPtrCallbacks g_callbacks = {};
-
-bool IsFreedHeapPointer(void const volatile* ptr) {
- // Use `__asan_region_is_poisoned` instead of `__asan_address_is_poisoned`
- // because the latter may crash on an invalid pointer.
- if (!__asan_region_is_poisoned(const_cast<void*>(ptr), 1))
- return false;
-
- // Make sure the address is on the heap and is not in a redzone.
- void* region_ptr;
- size_t region_size;
- const char* allocation_type = __asan_locate_address(
- const_cast<void*>(ptr), nullptr, 0, ®ion_ptr, ®ion_size);
-
- auto address = reinterpret_cast<uintptr_t>(ptr);
- auto region_base = reinterpret_cast<uintptr_t>(region_ptr);
- if (strcmp(allocation_type, "heap") != 0 || address < region_base ||
- address >=
- region_base + region_size) { // We exclude pointers one past the end
- // of an allocations from the analysis
- // for now because they're to fragile.
- return false;
- }
-
- // Make sure the allocation has been actually freed rather than
- // user-poisoned.
- int free_thread_id = -1;
- __asan_get_free_stack(region_ptr, nullptr, 0, &free_thread_id);
- return free_thread_id != -1;
-}
-
-// Force a non-optimizable memory load operation to trigger an ASan crash.
-NOINLINE NOT_TAIL_CALLED void CrashImmediatelyOnUseAfterFree(
- void const volatile* ptr) {
- PA_NO_CODE_FOLDING();
- auto unused = *reinterpret_cast<char const volatile*>(ptr);
- asm volatile("" : "+r"(unused));
-}
-} // namespace
-
-void InstallAsanBackupRefPtrCallbacks(
- const AsanBackupRefPtrCallbacks& callbacks) {
- g_callbacks = callbacks;
- asan_brp_callbacks_installed = true;
-}
-
-NO_SANITIZE("address")
-void AsanBackupRefPtrImpl::AsanCheckIfValidDereference(
- void const volatile* ptr) {
- if (RawPtrAsanService::GetInstance().is_dereference_check_enabled() &&
- IsFreedHeapPointer(ptr)) {
- RawPtrAsanService::SetPendingReport(
- RawPtrAsanService::ReportType::kDereference, ptr);
- CrashImmediatelyOnUseAfterFree(ptr);
- }
-}
-
-NO_SANITIZE("address")
-void AsanBackupRefPtrImpl::AsanCheckIfValidExtraction(
- void const volatile* ptr) {
- auto& service = RawPtrAsanService::GetInstance();
-
- if ((service.is_extraction_check_enabled() ||
- service.is_dereference_check_enabled()) &&
- IsFreedHeapPointer(ptr)) {
- RawPtrAsanService::SetPendingReport(
- RawPtrAsanService::ReportType::kExtraction, ptr);
- // If the dereference check is enabled, we still record the extraction event
- // to catch the potential subsequent dangling dereference, but don't report
- // the extraction itself.
- if (service.is_extraction_check_enabled()) {
- debug::AsanService::GetInstance()->Log(
- "=================================================================\n"
- "==%d==WARNING: MiraclePtr: dangling-pointer-extraction on address "
- "%p\n"
- "extracted here:",
- Process::Current().Pid(), ptr);
- __sanitizer_print_stack_trace();
- __asan_describe_address(const_cast<void*>(ptr));
- debug::AsanService::GetInstance()->Log(
- "A regular ASan report will follow if the extracted pointer is "
- "dereferenced later.\n"
- "Otherwise, it is still likely a bug to rely on the address of an "
- "already freed allocation.\n"
- "Refer to "
- "https://chromium.googlesource.com/chromium/src/+/main/base/memory/"
- "raw_ptr.md for details.\n"
- "=================================================================");
- }
- }
-}
-
-NO_SANITIZE("address")
-void AsanBackupRefPtrImpl::AsanCheckIfValidInstantiation(
- void const volatile* ptr) {
- if (RawPtrAsanService::GetInstance().is_instantiation_check_enabled() &&
- IsFreedHeapPointer(ptr)) {
- RawPtrAsanService::SetPendingReport(
- RawPtrAsanService::ReportType::kInstantiation, ptr);
- CrashImmediatelyOnUseAfterFree(ptr);
- }
-}
-
-} // namespace base::internal
-
-#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
+#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
#if BUILDFLAG(USE_ASAN_UNOWNED_PTR)
@@ -256,7 +151,7 @@
bool AsanUnownedPtrImpl::LikelySmuggledScalar(const volatile void* ptr) {
intptr_t address = reinterpret_cast<intptr_t>(ptr);
- return address < 0x100; // Negative or small positive.
+ return address < 0x4000; // Negative or small positive.
}
} // namespace base::internal
diff --git a/base/memory/raw_ptr.h b/base/memory/raw_ptr.h
index f7266c9..f8707cd 100644
--- a/base/memory/raw_ptr.h
+++ b/base/memory/raw_ptr.h
@@ -19,6 +19,8 @@
#include "base/allocator/partition_allocator/partition_alloc_base/debug/debugging_buildflags.h"
#include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
#include "base/allocator/partition_allocator/partition_alloc_config.h"
+#include "base/allocator/partition_allocator/partition_alloc_forward.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "build/build_config.h"
#include "build/buildflag.h"
@@ -91,7 +93,6 @@
// change behavior depending on RawPtrType.
struct RawPtrMayDangle {};
struct RawPtrBanDanglingIfSupported {};
-struct RawPtrMayDangleUntriaged {};
struct RawPtrNoOp {};
@@ -102,22 +103,13 @@
template <typename RawPtrType>
inline constexpr bool IsValidRawPtrTypeV =
std::is_same_v<RawPtrType, RawPtrMayDangle> ||
- std::is_same_v<RawPtrType, RawPtrBanDanglingIfSupported> ||
- std::is_same_v<RawPtrType, RawPtrMayDangleUntriaged>;
-}
+ std::is_same_v<RawPtrType, RawPtrBanDanglingIfSupported>;
+} // namespace raw_ptr_traits
namespace internal {
// These classes/structures are part of the raw_ptr implementation.
// DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
-// This type trait verifies a type can be used as a pointer offset.
-//
-// We support pointer offsets in signed (ptrdiff_t) or unsigned (size_t) values.
-// Smaller types are also allowed.
-template <typename Z>
-static constexpr bool offset_type =
- std::is_integral_v<Z> && sizeof(Z) <= sizeof(ptrdiff_t);
-
struct RawPtrNoOpImpl {
// Wraps a pointer.
template <typename T>
@@ -161,9 +153,11 @@
}
// Advance the wrapped pointer by `delta_elems`.
- template <typename T,
- typename Z,
- typename = std::enable_if_t<offset_type<Z>, void>>
+ template <
+ typename T,
+ typename Z,
+ typename =
+ std::enable_if_t<partition_alloc::internal::offset_type<Z>, void>>
static PA_ALWAYS_INLINE T* Advance(T* wrapped_ptr, Z delta_elems) {
return wrapped_ptr + delta_elems;
}
@@ -181,6 +175,18 @@
return wrapped_ptr;
}
+ // `WrapRawPtrForDuplication` and `UnsafelyUnwrapPtrForDuplication` are used
+ // to create a new raw_ptr<T> from another raw_ptr<T> of a different flavor.
+ template <typename T>
+ static PA_ALWAYS_INLINE T* WrapRawPtrForDuplication(T* ptr) {
+ return ptr;
+ }
+
+ template <typename T>
+ static PA_ALWAYS_INLINE T* UnsafelyUnwrapPtrForDuplication(T* wrapped_ptr) {
+ return wrapped_ptr;
+ }
+
// This is for accounting only, used by unit tests.
static PA_ALWAYS_INLINE void IncrementSwapCountForTest() {}
static PA_ALWAYS_INLINE void IncrementLessCountForTest() {}
@@ -282,8 +288,9 @@
uintptr_t read_tag =
*static_cast<volatile partition_alloc::PartitionTag*>(
PartitionAllocSupport::TagPointer(ExtractAddress(wrapped_addr)));
- if (PA_UNLIKELY(tag != read_tag))
+ if (PA_UNLIKELY(tag != read_tag)) {
PA_IMMEDIATE_CRASH();
+ }
// See the disambiguation comment above.
// TODO(kdlee): Ensure that ptr's hardware MTE tag is preserved.
// TODO(kdlee): Ensure that hardware and software MTE tags don't conflict.
@@ -319,9 +326,11 @@
}
// Advance the wrapped pointer by `delta_elems`.
- template <typename T,
- typename Z,
- typename = std::enable_if_t<offset_type<Z>, void>>
+ template <
+ typename T,
+ typename Z,
+ typename =
+ std::enable_if_t<partition_alloc::internal::offset_type<Z>, void>>
static PA_ALWAYS_INLINE T* Advance(T* wrapped_ptr, Z delta_elems) {
return wrapped_ptr + delta_elems;
}
@@ -361,6 +370,18 @@
return wrapped_ptr;
}
+ // `WrapRawPtrForDuplication` and `UnsafelyUnwrapPtrForDuplication` are used
+ // to create a new raw_ptr<T> from another raw_ptr<T> of a different flavor.
+ template <typename T>
+ static PA_ALWAYS_INLINE T* WrapRawPtrForDuplication(T* ptr) {
+ return WrapRawPtr(ptr);
+ }
+
+ template <typename T>
+ static PA_ALWAYS_INLINE T* UnsafelyUnwrapPtrForDuplication(T* wrapped_ptr) {
+ return ExtractPtr(wrapped_ptr);
+ }
+
// This is for accounting only, used by unit tests.
static PA_ALWAYS_INLINE void IncrementSwapCountForTest() {}
static PA_ALWAYS_INLINE void IncrementLessCountForTest() {}
@@ -600,9 +621,11 @@
}
// Advance the wrapped pointer by `delta_elems`.
- template <typename T,
- typename Z,
- typename = std::enable_if_t<offset_type<Z>, void>>
+ template <
+ typename T,
+ typename Z,
+ typename =
+ std::enable_if_t<partition_alloc::internal::offset_type<Z>, void>>
static PA_ALWAYS_INLINE T* Advance(T* wrapped_ptr, Z delta_elems) {
#if BUILDFLAG(PUT_REF_COUNT_IN_PREVIOUS_SLOT)
T* unpoisoned_ptr = UnpoisonPtr(wrapped_ptr);
@@ -624,15 +647,17 @@
// TODO(bartekn): Consider adding support for non-BRP pools too (without
// removing the cross-pool migration check).
if (IsSupportedAndNotNull(address)) {
- auto ptr_pos_within_alloc =
- IsValidDelta(address, delta_elems * static_cast<Z>(sizeof(T)));
+ auto ptr_pos_within_alloc = IsValidDelta(
+ address, delta_elems * static_cast<Z>(sizeof(T)), sizeof(T));
// No need to check that |new_ptr| is in the same pool, as IsValidDeta()
// checks that it's within the same allocation, so must be the same pool.
PA_BASE_CHECK(ptr_pos_within_alloc !=
partition_alloc::PtrPosWithinAlloc::kFarOOB);
#if PA_CONFIG(USE_OOB_POISON)
- if (ptr_pos_within_alloc == partition_alloc::PtrPosWithinAlloc::kAllocEnd)
+ if (ptr_pos_within_alloc ==
+ partition_alloc::PtrPosWithinAlloc::kAllocEnd) {
new_ptr = PoisonOOBPtr(new_ptr);
+ }
#endif
} else {
// Check that the new address didn't migrate into the BRP pool, as it
@@ -681,7 +706,7 @@
// TODO(bartekn): Consider adding support for non-BRP pool too.
if (IsSupportedAndNotNull(address1)) {
PA_BASE_CHECK(IsSupportedAndNotNull(address2));
- PA_BASE_CHECK(IsValidDelta(address2, address1 - address2) !=
+ PA_BASE_CHECK(IsValidDelta(address2, address1 - address2, sizeof(T)) !=
partition_alloc::PtrPosWithinAlloc::kFarOOB);
} else {
PA_BASE_CHECK(!IsSupportedAndNotNull(address2));
@@ -703,6 +728,18 @@
ReportIfDanglingInternal(partition_alloc::UntagPtr(wrapped_ptr));
}
+ // `WrapRawPtrForDuplication` and `UnsafelyUnwrapPtrForDuplication` are used
+ // to create a new raw_ptr<T> from another raw_ptr<T> of a different flavor.
+ template <typename T>
+ static PA_ALWAYS_INLINE T* WrapRawPtrForDuplication(T* ptr) {
+ return WrapRawPtr(ptr);
+ }
+
+ template <typename T>
+ static PA_ALWAYS_INLINE T* UnsafelyUnwrapPtrForDuplication(T* wrapped_ptr) {
+ return UnpoisonPtr(wrapped_ptr);
+ }
+
// This is for accounting only, used by unit tests.
static PA_ALWAYS_INLINE void IncrementSwapCountForTest() {}
static PA_ALWAYS_INLINE void IncrementLessCountForTest() {}
@@ -723,134 +760,27 @@
bool IsPointeeAlive(uintptr_t address);
static PA_COMPONENT_EXPORT(RAW_PTR) PA_NOINLINE
void ReportIfDanglingInternal(uintptr_t address);
- template <typename Z, typename = std::enable_if_t<offset_type<Z>, void>>
- static PA_ALWAYS_INLINE partition_alloc::PtrPosWithinAlloc IsValidDelta(
- uintptr_t address,
- Z delta_in_bytes) {
- if constexpr (std::is_signed_v<Z>)
- return IsValidSignedDelta(address, ptrdiff_t{delta_in_bytes});
- else
- return IsValidUnsignedDelta(address, size_t{delta_in_bytes});
+ template <
+ typename Z,
+ typename =
+ std::enable_if_t<partition_alloc::internal::offset_type<Z>, void>>
+ static PA_ALWAYS_INLINE partition_alloc::PtrPosWithinAlloc
+ IsValidDelta(uintptr_t address, Z delta_in_bytes, size_t type_size) {
+ using delta_t = std::conditional_t<std::is_signed_v<Z>, ptrdiff_t, size_t>;
+ partition_alloc::internal::PtrDelta<delta_t> ptr_delta(delta_in_bytes,
+ type_size);
+
+ return IsValidDelta(address, ptr_delta);
}
+ template <typename Z>
static PA_COMPONENT_EXPORT(RAW_PTR)
PA_NOINLINE partition_alloc::PtrPosWithinAlloc
- IsValidSignedDelta(uintptr_t address, ptrdiff_t delta_in_bytes);
- static PA_COMPONENT_EXPORT(RAW_PTR)
- PA_NOINLINE partition_alloc::PtrPosWithinAlloc
- IsValidUnsignedDelta(uintptr_t address, size_t delta_in_bytes);
+ IsValidDelta(uintptr_t address,
+ partition_alloc::internal::PtrDelta<Z> delta);
};
#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
-#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
-// Maps 1-to-1 onto the public enum of `RawPtrAsanService`.
-enum class AsanBackupRefPtrReportType {
- kDereference,
- kExtraction,
- kInstantiation,
-};
-
-// Callback carrier struct that inverts a dependency from `raw_ptr` to
-// `//base`.
-struct AsanBackupRefPtrCallbacks {
- // `RawPtrAsanService` callbacks.
- bool (*is_dereference_check_enabled)() = nullptr;
- bool (*is_extraction_check_enabled)() = nullptr;
- bool (*is_instantiation_check_enabled)() = nullptr;
- void (*set_pending_report)(AsanBackupRefPtrReportType type,
- const volatile void* ptr) = nullptr;
-
- // Logs an invalid extraction for `ptr` without crashing.
- void (*emit_invalid_extraction)(void const volatile* ptr) = nullptr;
-};
-
-static_assert(std::is_trivially_destructible<AsanBackupRefPtrCallbacks>());
-
-void InstallAsanBackupRefPtrCallbacks(
- const AsanBackupRefPtrCallbacks& callbacks);
-
-// Implementation that allows us to detect BackupRefPtr problems in ASan builds.
-struct AsanBackupRefPtrImpl {
- // Wraps a pointer.
- template <typename T>
- static PA_ALWAYS_INLINE T* WrapRawPtr(T* ptr) {
- AsanCheckIfValidInstantiation(ptr);
- return ptr;
- }
-
- // Notifies the allocator when a wrapped pointer is being removed or replaced.
- template <typename T>
- static PA_ALWAYS_INLINE void ReleaseWrappedPtr(T*) {}
-
- // Unwraps the pointer, while asserting that memory hasn't been freed. The
- // function is allowed to crash on nullptr.
- template <typename T>
- static PA_ALWAYS_INLINE T* SafelyUnwrapPtrForDereference(T* wrapped_ptr) {
- AsanCheckIfValidDereference(wrapped_ptr);
- return wrapped_ptr;
- }
-
- // Unwraps the pointer, while asserting that memory hasn't been freed. The
- // function must handle nullptr gracefully.
- template <typename T>
- static PA_ALWAYS_INLINE T* SafelyUnwrapPtrForExtraction(T* wrapped_ptr) {
- AsanCheckIfValidExtraction(wrapped_ptr);
- return wrapped_ptr;
- }
-
- // Unwraps the pointer, without making an assertion on whether memory was
- // freed or not.
- template <typename T>
- static PA_ALWAYS_INLINE T* UnsafelyUnwrapPtrForComparison(T* wrapped_ptr) {
- return wrapped_ptr;
- }
-
- // Upcasts the wrapped pointer.
- template <typename To, typename From>
- static PA_ALWAYS_INLINE constexpr To* Upcast(From* wrapped_ptr) {
- static_assert(std::is_convertible<From*, To*>::value,
- "From must be convertible to To.");
- // Note, this cast may change the address if upcasting to base that lies in
- // the middle of the derived object.
- return wrapped_ptr;
- }
-
- // Advance the wrapped pointer by `delta_elems`.
- template <typename T,
- typename Z,
- typename = std::enable_if_t<offset_type<Z>, void>>
- static PA_ALWAYS_INLINE T* Advance(T* wrapped_ptr, Z delta_elems) {
- return wrapped_ptr + delta_elems;
- }
-
- template <typename T>
- static PA_ALWAYS_INLINE ptrdiff_t GetDeltaElems(T* wrapped_ptr1,
- T* wrapped_ptr2) {
- return wrapped_ptr1 - wrapped_ptr2;
- }
-
- // Returns a copy of a wrapped pointer, without making an assertion on whether
- // memory was freed or not.
- template <typename T>
- static PA_ALWAYS_INLINE T* Duplicate(T* wrapped_ptr) {
- return wrapped_ptr;
- }
-
- // This is for accounting only, used by unit tests.
- static PA_ALWAYS_INLINE void IncrementSwapCountForTest() {}
- static PA_ALWAYS_INLINE void IncrementLessCountForTest() {}
- static PA_ALWAYS_INLINE void IncrementPointerToMemberOperatorCountForTest() {}
-
- private:
- static PA_COMPONENT_EXPORT(RAW_PTR) PA_NOINLINE
- void AsanCheckIfValidInstantiation(void const volatile* ptr);
- static PA_COMPONENT_EXPORT(RAW_PTR) PA_NOINLINE
- void AsanCheckIfValidDereference(void const volatile* ptr);
- static PA_COMPONENT_EXPORT(RAW_PTR) PA_NOINLINE
- void AsanCheckIfValidExtraction(void const volatile* ptr);
-};
-#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
-
#if BUILDFLAG(USE_ASAN_UNOWNED_PTR)
struct AsanUnownedPtrImpl {
@@ -900,9 +830,11 @@
}
// Advance the wrapped pointer by `delta_elems`.
- template <typename T,
- typename Z,
- typename = std::enable_if_t<offset_type<Z>, void>>
+ template <
+ typename T,
+ typename Z,
+ typename =
+ std::enable_if_t<partition_alloc::internal::offset_type<Z>, void>>
static PA_ALWAYS_INLINE T* Advance(T* wrapped_ptr, Z delta_elems) {
return wrapped_ptr + delta_elems;
}
@@ -931,6 +863,18 @@
static bool EndOfAliveAllocation(const volatile void* ptr);
static bool LikelySmuggledScalar(const volatile void* ptr);
+ // `WrapRawPtrForDuplication` and `UnsafelyUnwrapPtrForDuplication` are used
+ // to create a new raw_ptr<T> from another raw_ptr<T> of a different flavor.
+ template <typename T>
+ static PA_ALWAYS_INLINE T* WrapRawPtrForDuplication(T* ptr) {
+ return ptr;
+ }
+
+ template <typename T>
+ static PA_ALWAYS_INLINE T* UnsafelyUnwrapPtrForDuplication(T* wrapped_ptr) {
+ return wrapped_ptr;
+ }
+
// This is for accounting only, used by unit tests.
static PA_ALWAYS_INLINE void IncrementSwapCountForTest() {}
static PA_ALWAYS_INLINE void IncrementLessCountForTest() {}
@@ -959,9 +903,9 @@
Duplicate* duplicate;
};
-const RawPtrHooks* GetRawPtrHooks();
-void InstallRawPtrHooks(const RawPtrHooks*);
-void ResetRawPtrHooks();
+PA_COMPONENT_EXPORT(RAW_PTR) const RawPtrHooks* GetRawPtrHooks();
+PA_COMPONENT_EXPORT(RAW_PTR) void InstallRawPtrHooks(const RawPtrHooks*);
+PA_COMPONENT_EXPORT(RAW_PTR) void ResetRawPtrHooks();
struct RawPtrHookableImpl {
// Wraps a pointer.
@@ -1015,9 +959,11 @@
}
// Advance the wrapped pointer by `delta_elems`.
- template <typename T,
- typename Z,
- typename = std::enable_if_t<offset_type<Z>, void>>
+ template <
+ typename T,
+ typename Z,
+ typename =
+ std::enable_if_t<partition_alloc::internal::offset_type<Z>, void>>
static PA_ALWAYS_INLINE T* Advance(T* wrapped_ptr, Z delta_elems) {
GetRawPtrHooks()->advance(
reinterpret_cast<uintptr_t>(wrapped_ptr),
@@ -1039,6 +985,18 @@
return wrapped_ptr;
}
+ // `WrapRawPtrForDuplication` and `UnsafelyUnwrapPtrForDuplication` are used
+ // to create a new raw_ptr<T> from another raw_ptr<T> of a different flavor.
+ template <typename T>
+ static PA_ALWAYS_INLINE T* WrapRawPtrForDuplication(T* ptr) {
+ return ptr;
+ }
+
+ template <typename T>
+ static PA_ALWAYS_INLINE T* UnsafelyUnwrapPtrForDuplication(T* wrapped_ptr) {
+ return wrapped_ptr;
+ }
+
// This is for accounting only, used by unit tests.
static PA_ALWAYS_INLINE void IncrementSwapCountForTest() {}
static PA_ALWAYS_INLINE void IncrementLessCountForTest() {}
@@ -1093,6 +1051,18 @@
++pointer_to_member_operator_cnt;
}
+ template <typename T>
+ static PA_ALWAYS_INLINE T* WrapRawPtrForDuplication(T* ptr) {
+ ++wrap_raw_ptr_for_dup_cnt;
+ return SuperImpl::WrapRawPtrForDuplication(ptr);
+ }
+
+ template <typename T>
+ static PA_ALWAYS_INLINE T* UnsafelyUnwrapPtrForDuplication(T* wrapped_ptr) {
+ ++get_for_duplication_cnt;
+ return SuperImpl::UnsafelyUnwrapPtrForDuplication(wrapped_ptr);
+ }
+
static void ClearCounters() {
wrap_raw_ptr_cnt = 0;
release_wrapped_ptr_cnt = 0;
@@ -1102,6 +1072,8 @@
wrapped_ptr_swap_cnt = 0;
wrapped_ptr_less_cnt = 0;
pointer_to_member_operator_cnt = 0;
+ wrap_raw_ptr_for_dup_cnt = 0;
+ get_for_duplication_cnt = 0;
}
static inline int wrap_raw_ptr_cnt = INT_MIN;
@@ -1112,6 +1084,8 @@
static inline int wrapped_ptr_swap_cnt = INT_MIN;
static inline int wrapped_ptr_less_cnt = INT_MIN;
static inline int pointer_to_member_operator_cnt = INT_MIN;
+ static inline int wrap_raw_ptr_for_dup_cnt = INT_MIN;
+ static inline int get_for_duplication_cnt = INT_MIN;
};
} // namespace internal
@@ -1213,8 +1187,6 @@
struct RawPtrTypeToImpl<RawPtrMayDangle> {
#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
using Impl = internal::BackupRefPtrImpl</*AllowDangling=*/true>;
-#elif BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
- using Impl = internal::AsanBackupRefPtrImpl;
#elif BUILDFLAG(USE_ASAN_UNOWNED_PTR)
// No special bookkeeping required for this case, just treat these
// as ordinary pointers.
@@ -1230,16 +1202,9 @@
};
template <>
-struct RawPtrTypeToImpl<RawPtrMayDangleUntriaged> {
- using Impl = RawPtrTypeToImpl<RawPtrMayDangle>::Impl;
-};
-
-template <>
struct RawPtrTypeToImpl<RawPtrBanDanglingIfSupported> {
#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
using Impl = internal::BackupRefPtrImpl</*AllowDangling=*/false>;
-#elif BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
- using Impl = internal::AsanBackupRefPtrImpl;
#elif BUILDFLAG(USE_ASAN_UNOWNED_PTR)
using Impl = internal::AsanUnownedPtrImpl;
#elif PA_CONFIG(ENABLE_MTE_CHECKED_PTR_SUPPORT_WITH_64_BITS_POINTERS)
@@ -1374,6 +1339,27 @@
#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) ||
// BUILDFLAG(USE_ASAN_UNOWNED_PTR)
+ template <typename PassedRawPtrType,
+ typename Unused =
+ std::enable_if_t<!std::is_same_v<RawPtrType, PassedRawPtrType>>>
+ PA_ALWAYS_INLINE explicit raw_ptr(
+ const raw_ptr<T, PassedRawPtrType>& p) noexcept
+ : wrapped_ptr_(Impl::WrapRawPtrForDuplication(
+ raw_ptr_traits::RawPtrTypeToImpl<PassedRawPtrType>::Impl::
+ UnsafelyUnwrapPtrForDuplication(p.wrapped_ptr_))) {}
+
+ template <typename PassedRawPtrType,
+ typename Unused =
+ std::enable_if_t<!std::is_same_v<RawPtrType, PassedRawPtrType>>>
+ PA_ALWAYS_INLINE raw_ptr& operator=(
+ const raw_ptr<T, PassedRawPtrType>& p) noexcept {
+ Impl::ReleaseWrappedPtr(wrapped_ptr_);
+ wrapped_ptr_ = Impl::WrapRawPtrForDuplication(
+ raw_ptr_traits::RawPtrTypeToImpl<PassedRawPtrType>::Impl::
+ UnsafelyUnwrapPtrForDuplication(p.wrapped_ptr_));
+ return *this;
+ }
+
// Deliberately implicit, because raw_ptr is supposed to resemble raw ptr.
// NOLINTNEXTLINE(google-explicit-constructor)
constexpr PA_ALWAYS_INLINE raw_ptr(std::nullptr_t) noexcept
@@ -1503,22 +1489,30 @@
--(*this);
return result;
}
- template <typename Z, typename = std::enable_if_t<internal::offset_type<Z>>>
+ template <
+ typename Z,
+ typename = std::enable_if_t<partition_alloc::internal::offset_type<Z>>>
PA_ALWAYS_INLINE raw_ptr& operator+=(Z delta_elems) {
wrapped_ptr_ = Impl::Advance(wrapped_ptr_, delta_elems);
return *this;
}
- template <typename Z, typename = std::enable_if_t<internal::offset_type<Z>>>
+ template <
+ typename Z,
+ typename = std::enable_if_t<partition_alloc::internal::offset_type<Z>>>
PA_ALWAYS_INLINE raw_ptr& operator-=(Z delta_elems) {
return *this += -delta_elems;
}
- template <typename Z, typename = std::enable_if_t<internal::offset_type<Z>>>
+ template <
+ typename Z,
+ typename = std::enable_if_t<partition_alloc::internal::offset_type<Z>>>
friend PA_ALWAYS_INLINE raw_ptr operator+(const raw_ptr& p, Z delta_elems) {
raw_ptr result = p;
return result += delta_elems;
}
- template <typename Z, typename = std::enable_if_t<internal::offset_type<Z>>>
+ template <
+ typename Z,
+ typename = std::enable_if_t<partition_alloc::internal::offset_type<Z>>>
friend PA_ALWAYS_INLINE raw_ptr operator-(const raw_ptr& p, Z delta_elems) {
raw_ptr result = p;
return result -= delta_elems;
@@ -1714,7 +1708,9 @@
return ptr;
}
- T* wrapped_ptr_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union, #global-scope, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION T* wrapped_ptr_;
template <typename U, typename V>
friend class raw_ptr;
@@ -1765,17 +1761,6 @@
template <typename T>
inline constexpr bool IsRawPtrMayDangleV<raw_ptr<T, RawPtrMayDangle>> = true;
-template <typename T>
-inline constexpr bool IsRawPtrDanglingUntriagedV = false;
-
-template <typename T>
-inline constexpr bool
- IsRawPtrDanglingUntriagedV<raw_ptr<T, RawPtrMayDangleUntriaged>> = true;
-
-template <typename T>
-inline constexpr bool IsRawPtrAllowedToDangleV =
- IsRawPtrMayDangleV<T> || IsRawPtrDanglingUntriagedV<T>;
-
// Template helpers for working with T* or raw_ptr<T>.
template <typename T>
struct IsPointer : std::false_type {};
@@ -1825,7 +1810,7 @@
// See `docs/dangling_ptr.md`
// Annotates known dangling raw_ptr. Those haven't been triaged yet. All the
// occurrences are meant to be removed. See https://crbug.com/1291138.
-using DanglingUntriaged = base::RawPtrMayDangleUntriaged;
+using DanglingUntriaged = base::RawPtrMayDangle;
// This type is to be used in callbacks arguments when it is known that they
// might receive dangling pointers. In any other cases, please use one of:
diff --git a/base/memory/raw_ptr_asan_hooks.cc b/base/memory/raw_ptr_asan_hooks.cc
new file mode 100644
index 0000000..30d1580
--- /dev/null
+++ b/base/memory/raw_ptr_asan_hooks.cc
@@ -0,0 +1,121 @@
+// 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 "base/memory/raw_ptr_asan_hooks.h"
+
+#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
+
+#include <cstring>
+
+#include <sanitizer/asan_interface.h>
+
+#include "base/compiler_specific.h"
+#include "base/debug/alias.h"
+#include "base/memory/raw_ptr_asan_service.h"
+
+namespace base::internal {
+
+namespace {
+bool IsFreedHeapPointer(uintptr_t address) {
+ // Use `__asan_region_is_poisoned` instead of `__asan_address_is_poisoned`
+ // because the latter may crash on an invalid pointer.
+ if (!__asan_region_is_poisoned(reinterpret_cast<void*>(address), 1)) {
+ return false;
+ }
+
+ // Make sure the address is on the heap and is not in a redzone.
+ void* region_ptr;
+ size_t region_size;
+ const char* allocation_type = __asan_locate_address(
+ reinterpret_cast<void*>(address), nullptr, 0, ®ion_ptr, ®ion_size);
+
+ auto region_base = reinterpret_cast<uintptr_t>(region_ptr);
+ if (strcmp(allocation_type, "heap") != 0 || address < region_base ||
+ address >=
+ region_base + region_size) { // We exclude pointers one past the end
+ // of an allocations from the analysis
+ // for now because they're to fragile.
+ return false;
+ }
+
+ // Make sure the allocation has been actually freed rather than
+ // user-poisoned.
+ int free_thread_id = -1;
+ __asan_get_free_stack(region_ptr, nullptr, 0, &free_thread_id);
+ return free_thread_id != -1;
+}
+
+// Force a non-optimizable memory load operation to trigger an ASan crash.
+NOINLINE NOT_TAIL_CALLED void CrashImmediatelyOnUseAfterFree(
+ uintptr_t address) {
+ NO_CODE_FOLDING();
+ auto unused = *reinterpret_cast<char const volatile*>(address);
+ asm volatile("" : "+r"(unused));
+}
+
+void WrapPtr(uintptr_t address) {
+ if (RawPtrAsanService::GetInstance().is_instantiation_check_enabled() &&
+ IsFreedHeapPointer(address)) {
+ RawPtrAsanService::SetPendingReport(
+ RawPtrAsanService::ReportType::kInstantiation,
+ reinterpret_cast<void*>(address));
+ CrashImmediatelyOnUseAfterFree(address);
+ }
+}
+
+void ReleaseWrappedPtr(uintptr_t) {}
+
+void SafelyUnwrapForDereference(uintptr_t address) {
+ if (RawPtrAsanService::GetInstance().is_dereference_check_enabled() &&
+ IsFreedHeapPointer(address)) {
+ RawPtrAsanService::SetPendingReport(
+ RawPtrAsanService::ReportType::kDereference,
+ reinterpret_cast<void*>(address));
+ CrashImmediatelyOnUseAfterFree(address);
+ }
+}
+
+void SafelyUnwrapForExtraction(uintptr_t address) {
+ auto& service = RawPtrAsanService::GetInstance();
+
+ if ((service.is_extraction_check_enabled() ||
+ service.is_dereference_check_enabled()) &&
+ IsFreedHeapPointer(address)) {
+ RawPtrAsanService::SetPendingReport(
+ RawPtrAsanService::ReportType::kExtraction,
+ reinterpret_cast<void*>(address));
+ // If the dereference check is enabled, we still record the extraction event
+ // to catch the potential subsequent dangling dereference, but don't report
+ // the extraction itself.
+ if (service.is_extraction_check_enabled()) {
+ service.WarnOnDanglingExtraction(reinterpret_cast<void*>(address));
+ }
+ }
+}
+
+void UnsafelyUnwrapForComparison(uintptr_t) {}
+
+void Advance(uintptr_t, uintptr_t) {}
+
+void Duplicate(uintptr_t) {}
+
+} // namespace
+
+const RawPtrHooks* GetRawPtrAsanHooks() {
+ static constexpr RawPtrHooks hooks = {
+ WrapPtr,
+ ReleaseWrappedPtr,
+ SafelyUnwrapForDereference,
+ SafelyUnwrapForExtraction,
+ UnsafelyUnwrapForComparison,
+ Advance,
+ Duplicate,
+ };
+
+ return &hooks;
+}
+
+} // namespace base::internal
+
+#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
diff --git a/base/memory/raw_ptr_asan_hooks.h b/base/memory/raw_ptr_asan_hooks.h
new file mode 100644
index 0000000..42185c5
--- /dev/null
+++ b/base/memory/raw_ptr_asan_hooks.h
@@ -0,0 +1,22 @@
+// 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 BASE_MEMORY_RAW_PTR_ASAN_HOOKS_H_
+#define BASE_MEMORY_RAW_PTR_ASAN_HOOKS_H_
+
+#include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
+
+#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
+
+#include "base/memory/raw_ptr.h"
+
+namespace base::internal {
+
+const RawPtrHooks* GetRawPtrAsanHooks();
+
+}
+
+#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
+
+#endif // BASE_MEMORY_RAW_PTR_ASAN_HOOKS_H_
diff --git a/base/memory/raw_ptr_asan_service.cc b/base/memory/raw_ptr_asan_service.cc
index 12617fe..5b1d58d 100644
--- a/base/memory/raw_ptr_asan_service.cc
+++ b/base/memory/raw_ptr_asan_service.cc
@@ -3,19 +3,23 @@
// found in the LICENSE file.
#include "base/memory/raw_ptr_asan_service.h"
-#include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
+
#include <sanitizer/allocator_interface.h>
#include <sanitizer/asan_interface.h>
#include <stdarg.h>
#include <string.h>
#include "base/check_op.h"
+#include "base/compiler_specific.h"
#include "base/debug/asan_service.h"
#include "base/logging.h"
+#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_asan_bound_arg_tracker.h"
+#include "base/memory/raw_ptr_asan_hooks.h"
#include "base/no_destructor.h"
+#include "base/process/process.h"
#include "base/strings/stringprintf.h"
#include "base/task/thread_pool/thread_group.h"
#include "base/threading/thread_local.h"
@@ -82,6 +86,7 @@
__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
debug::AsanService::GetInstance()->AddErrorCallback(ErrorReportCallback);
+ internal::InstallRawPtrHooks(base::internal::GetRawPtrAsanHooks());
is_dereference_check_enabled_ = !!enable_dereference_check;
is_extraction_check_enabled_ = !!enable_extraction_check;
@@ -141,8 +146,9 @@
// static
void RawPtrAsanService::ErrorReportCallback(const char* report, bool*) {
- if (strcmp(__asan_get_report_description(), "heap-use-after-free") != 0)
+ if (strcmp(__asan_get_report_description(), "heap-use-after-free") != 0) {
return;
+ }
struct {
ProtectionStatus protection_status;
@@ -271,6 +277,27 @@
crash_info.crash_details, crash_info.protection_details);
}
+void RawPtrAsanService::WarnOnDanglingExtraction(
+ const volatile void* ptr) const {
+ debug::AsanService::GetInstance()->Log(
+ "=================================================================\n"
+ "==%d==WARNING: MiraclePtr: dangling-pointer-extraction on address "
+ "%p\n"
+ "extracted here:",
+ Process::Current().Pid(), ptr);
+ __sanitizer_print_stack_trace();
+ __asan_describe_address(const_cast<void*>(ptr));
+ debug::AsanService::GetInstance()->Log(
+ "A regular ASan report will follow if the extracted pointer is "
+ "dereferenced later.\n"
+ "Otherwise, it is still likely a bug to rely on the address of an "
+ "already freed allocation.\n"
+ "Refer to "
+ "https://chromium.googlesource.com/chromium/src/+/main/base/memory/"
+ "raw_ptr.md for details.\n"
+ "=================================================================");
+}
+
// static
RawPtrAsanService::PendingReport& RawPtrAsanService::GetPendingReport() {
// Intentionally use thread-local-storage here. Making this sequence-local
diff --git a/base/memory/raw_ptr_asan_service.h b/base/memory/raw_ptr_asan_service.h
index 5cb09da..8418caa 100644
--- a/base/memory/raw_ptr_asan_service.h
+++ b/base/memory/raw_ptr_asan_service.h
@@ -59,6 +59,8 @@
return instance_;
}
+ void WarnOnDanglingExtraction(const volatile void* ptr) const;
+
static void SetPendingReport(ReportType type, const volatile void* ptr);
private:
diff --git a/base/memory/raw_ptr_asan_unittest.cc b/base/memory/raw_ptr_asan_unittest.cc
new file mode 100644
index 0000000..ae11c6c
--- /dev/null
+++ b/base/memory/raw_ptr_asan_unittest.cc
@@ -0,0 +1,452 @@
+// 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 "base/allocator/partition_allocator/partition_alloc_buildflags.h"
+
+#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
+
+#include <sanitizer/asan_interface.h>
+#include <thread>
+
+#include "base/debug/asan_service.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_asan_service.h"
+#include "base/task/thread_pool.h"
+#include "base/test/bind.h"
+#include "base/test/task_environment.h"
+#include "testing/gmock/include/gmock/gmock.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace base::internal {
+
+struct AsanStruct {
+ int x;
+
+ void func() { ++x; }
+};
+
+#define ASAN_BRP_PROTECTED(x) "MiraclePtr Status: PROTECTED\\n.*" x
+#define ASAN_BRP_MANUAL_ANALYSIS(x) \
+ "MiraclePtr Status: MANUAL ANALYSIS REQUIRED\\n.*" x
+#define ASAN_BRP_NOT_PROTECTED(x) "MiraclePtr Status: NOT PROTECTED\\n.*" x
+
+const char kAsanBrpProtected_Dereference[] =
+ ASAN_BRP_PROTECTED("dangling pointer was being dereferenced");
+const char kAsanBrpProtected_Callback[] = ASAN_BRP_PROTECTED(
+ "crash occurred inside a callback where a raw_ptr<T> pointing to the same "
+ "region");
+const char kAsanBrpMaybeProtected_Extraction[] = ASAN_BRP_MANUAL_ANALYSIS(
+ "pointer to the same region was extracted from a raw_ptr<T>");
+const char kAsanBrpNotProtected_Instantiation[] = ASAN_BRP_NOT_PROTECTED(
+ "pointer to an already freed region was assigned to a raw_ptr<T>");
+const char kAsanBrpNotProtected_EarlyAllocation[] = ASAN_BRP_NOT_PROTECTED(
+ "crash occurred while accessing a region that was allocated before "
+ "MiraclePtr was activated");
+const char kAsanBrpNotProtected_NoRawPtrAccess[] =
+ ASAN_BRP_NOT_PROTECTED("No raw_ptr<T> access to this region was detected");
+const char kAsanBrpMaybeProtected_Race[] =
+ ASAN_BRP_MANUAL_ANALYSIS("\\nThe \"use\" and \"free\" threads don't match");
+const char kAsanBrpMaybeProtected_ThreadPool[] =
+ ASAN_BRP_MANUAL_ANALYSIS("\\nThis crash occurred in the thread pool");
+
+#undef ASAN_BRP_PROTECTED
+#undef ASAN_BRP_MANUAL_ANALYSIS
+#undef ASAN_BRP_NOT_PROTECTED
+
+class AsanBackupRefPtrTest : public testing::Test {
+ protected:
+ void SetUp() override {
+ base::debug::AsanService::GetInstance()->Initialize();
+
+ if (!RawPtrAsanService::GetInstance().IsEnabled()) {
+ base::RawPtrAsanService::GetInstance().Configure(
+ base::EnableDereferenceCheck(true), base::EnableExtractionCheck(true),
+ base::EnableInstantiationCheck(true));
+ } else {
+ ASSERT_TRUE(base::RawPtrAsanService::GetInstance()
+ .is_dereference_check_enabled());
+ ASSERT_TRUE(
+ base::RawPtrAsanService::GetInstance().is_extraction_check_enabled());
+ ASSERT_TRUE(base::RawPtrAsanService::GetInstance()
+ .is_instantiation_check_enabled());
+ }
+ }
+
+ static void SetUpTestSuite() { early_allocation_ptr_ = new AsanStruct; }
+ static void TearDownTestSuite() { delete early_allocation_ptr_; }
+ static raw_ptr<AsanStruct> early_allocation_ptr_;
+};
+
+raw_ptr<AsanStruct> AsanBackupRefPtrTest::early_allocation_ptr_ = nullptr;
+
+TEST_F(AsanBackupRefPtrTest, Dereference) {
+ raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
+
+ // The four statements below should succeed.
+ (*protected_ptr).x = 1;
+ (*protected_ptr).func();
+ ++(protected_ptr->x);
+ protected_ptr->func();
+
+ delete protected_ptr.get();
+
+ EXPECT_DEATH_IF_SUPPORTED((*protected_ptr).x = 1,
+ kAsanBrpProtected_Dereference);
+ EXPECT_DEATH_IF_SUPPORTED((*protected_ptr).func(),
+ kAsanBrpProtected_Dereference);
+ EXPECT_DEATH_IF_SUPPORTED(++(protected_ptr->x),
+ kAsanBrpProtected_Dereference);
+ EXPECT_DEATH_IF_SUPPORTED(protected_ptr->func(),
+ kAsanBrpProtected_Dereference);
+
+ // The following statement should not trigger a dereference, so it should
+ // succeed without crashing even though *protected_ptr is no longer valid.
+ [[maybe_unused]] AsanStruct* ptr = protected_ptr;
+}
+
+TEST_F(AsanBackupRefPtrTest, Extraction) {
+ raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
+
+ AsanStruct* ptr1 = protected_ptr; // Shouldn't crash.
+ ptr1->x = 0;
+
+ delete protected_ptr.get();
+
+ EXPECT_DEATH_IF_SUPPORTED(
+ {
+ AsanStruct* ptr2 = protected_ptr;
+ ptr2->x = 1;
+ },
+ kAsanBrpMaybeProtected_Extraction);
+}
+
+TEST_F(AsanBackupRefPtrTest, Instantiation) {
+ AsanStruct* ptr = new AsanStruct;
+
+ raw_ptr<AsanStruct> protected_ptr1 = ptr; // Shouldn't crash.
+ protected_ptr1 = nullptr;
+
+ delete ptr;
+
+ EXPECT_DEATH_IF_SUPPORTED(
+ { [[maybe_unused]] raw_ptr<AsanStruct> protected_ptr2 = ptr; },
+ kAsanBrpNotProtected_Instantiation);
+}
+
+TEST_F(AsanBackupRefPtrTest, InstantiationInvalidPointer) {
+ void* ptr1 = reinterpret_cast<void*>(0xfefefefefefefefe);
+
+ [[maybe_unused]] raw_ptr<void> protected_ptr1 = ptr1; // Shouldn't crash.
+
+ size_t shadow_scale, shadow_offset;
+ __asan_get_shadow_mapping(&shadow_scale, &shadow_offset);
+ [[maybe_unused]] raw_ptr<void> protected_ptr2 =
+ reinterpret_cast<void*>(shadow_offset); // Shouldn't crash.
+}
+
+TEST_F(AsanBackupRefPtrTest, UserPoisoned) {
+ AsanStruct* ptr = new AsanStruct;
+ __asan_poison_memory_region(ptr, sizeof(AsanStruct));
+
+ [[maybe_unused]] raw_ptr<AsanStruct> protected_ptr1 =
+ ptr; // Shouldn't crash.
+
+ delete ptr; // Should crash now.
+ EXPECT_DEATH_IF_SUPPORTED(
+ { [[maybe_unused]] raw_ptr<AsanStruct> protected_ptr2 = ptr; },
+ kAsanBrpNotProtected_Instantiation);
+}
+
+TEST_F(AsanBackupRefPtrTest, EarlyAllocationDetection) {
+ raw_ptr<AsanStruct> late_allocation_ptr = new AsanStruct;
+ EXPECT_FALSE(RawPtrAsanService::GetInstance().IsSupportedAllocation(
+ early_allocation_ptr_.get()));
+ EXPECT_TRUE(RawPtrAsanService::GetInstance().IsSupportedAllocation(
+ late_allocation_ptr.get()));
+
+ delete late_allocation_ptr.get();
+ delete early_allocation_ptr_.get();
+
+ EXPECT_FALSE(RawPtrAsanService::GetInstance().IsSupportedAllocation(
+ early_allocation_ptr_.get()));
+ EXPECT_TRUE(RawPtrAsanService::GetInstance().IsSupportedAllocation(
+ late_allocation_ptr.get()));
+
+ EXPECT_DEATH_IF_SUPPORTED({ early_allocation_ptr_->func(); },
+ kAsanBrpNotProtected_EarlyAllocation);
+ EXPECT_DEATH_IF_SUPPORTED({ late_allocation_ptr->func(); },
+ kAsanBrpProtected_Dereference);
+
+ early_allocation_ptr_ = nullptr;
+}
+
+TEST_F(AsanBackupRefPtrTest, BoundRawPtr) {
+ // This test is for the handling of raw_ptr<T> type objects being passed
+ // directly to Bind.
+
+ raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
+
+ // First create our test callbacks while `*protected_ptr` is still valid, and
+ // we will then invoke them after deleting `*protected_ptr`.
+
+ // `ptr` is protected in this callback, as raw_ptr<T> will be mapped to an
+ // UnretainedWrapper containing a raw_ptr<T> which is guaranteed to outlive
+ // the function call.
+ auto ptr_callback = base::BindOnce(
+ [](AsanStruct* ptr) {
+ // This will crash and should be detected as a protected access.
+ ptr->func();
+ },
+ protected_ptr);
+
+ // Now delete `*protected_ptr` and check that the callbacks we created are
+ // handled correctly.
+ delete protected_ptr.get();
+ protected_ptr = nullptr;
+
+ EXPECT_DEATH_IF_SUPPORTED(std::move(ptr_callback).Run(),
+ kAsanBrpProtected_Callback);
+}
+
+TEST_F(AsanBackupRefPtrTest, BoundArgumentsProtected) {
+ raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
+ raw_ptr<AsanStruct> protected_ptr2 = new AsanStruct;
+
+ // First create our test callbacks while `*protected_ptr` is still valid, and
+ // we will then invoke them after deleting `*protected_ptr`.
+
+ // `ptr` is protected in this callback even after `*ptr` has been deleted,
+ // since the allocation will be kept alive by the internal `raw_ptr<T>` inside
+ // base::Unretained().
+ auto safe_callback = base::BindOnce(
+ [](AsanStruct* ptr) {
+ // This will crash and should be detected as a protected access.
+ ptr->func();
+ },
+ base::Unretained(protected_ptr));
+
+ // Both `inner_ptr` and `outer_ptr` are protected in these callbacks, since
+ // both are bound before `*ptr` is deleted. This test is making sure that
+ // `inner_ptr` is treated as protected.
+ auto safe_nested_inner_callback = base::BindOnce(
+ [](AsanStruct* outer_ptr, base::OnceClosure inner_callback) {
+ std::move(inner_callback).Run();
+ // This will never be executed, as we will crash in inner_callback
+ ASSERT_TRUE(false);
+ },
+ base::Unretained(protected_ptr),
+ base::BindOnce(
+ [](AsanStruct* inner_ptr) {
+ // This will crash and should be detected as a protected access.
+ inner_ptr->func();
+ },
+ base::Unretained(protected_ptr2)));
+
+ // Both `inner_ptr` and `outer_ptr` are protected in these callbacks, since
+ // both are bound before `*ptr` is deleted. This test is making sure that
+ // `outer_ptr` is still treated as protected after `inner_callback` has run.
+ auto safe_nested_outer_callback = base::BindOnce(
+ [](AsanStruct* outer_ptr, base::OnceClosure inner_callback) {
+ std::move(inner_callback).Run();
+ // This will crash and should be detected as a protected access.
+ outer_ptr->func();
+ },
+ base::Unretained(protected_ptr),
+ base::BindOnce(
+ [](AsanStruct* inner_ptr) {
+ // Do nothing - we don't want to trip the protection inside the
+ // inner callback.
+ },
+ base::Unretained(protected_ptr2)));
+
+ // Now delete `*protected_ptr` and check that the callbacks we created are
+ // handled correctly.
+ delete protected_ptr.get();
+ delete protected_ptr2.get();
+ protected_ptr = nullptr;
+ protected_ptr2 = nullptr;
+
+ EXPECT_DEATH_IF_SUPPORTED(std::move(safe_callback).Run(),
+ kAsanBrpProtected_Callback);
+ EXPECT_DEATH_IF_SUPPORTED(std::move(safe_nested_inner_callback).Run(),
+ kAsanBrpProtected_Callback);
+ EXPECT_DEATH_IF_SUPPORTED(std::move(safe_nested_outer_callback).Run(),
+ kAsanBrpProtected_Callback);
+}
+
+TEST_F(AsanBackupRefPtrTest, BoundArgumentsNotProtected) {
+ raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
+
+ // First create our test callbacks while `*protected_ptr` is still valid, and
+ // we will then invoke them after deleting `*protected_ptr`.
+
+ // `ptr` is not protected in this callback after `*ptr` has been deleted, as
+ // integer-type bind arguments do not use an internal `raw_ptr<T>`.
+ auto unsafe_callback = base::BindOnce(
+ [](uintptr_t address) {
+ AsanStruct* ptr = reinterpret_cast<AsanStruct*>(address);
+ // This will crash and should not be detected as a protected access.
+ ptr->func();
+ },
+ reinterpret_cast<uintptr_t>(protected_ptr.get()));
+
+ // In this case, `outer_ptr` is protected in these callbacks, since it is
+ // bound before `*ptr` is deleted. We want to make sure that the access to
+ // `inner_ptr` is not automatically treated as protected (although it actually
+ // is) because we're trying to limit the protection scope to be very
+ // conservative here.
+ auto unsafe_nested_inner_callback = base::BindOnce(
+ [](AsanStruct* outer_ptr, base::OnceClosure inner_callback) {
+ std::move(inner_callback).Run();
+ // This will never be executed, as we will crash in inner_callback
+ NOTREACHED();
+ },
+ base::Unretained(protected_ptr),
+ base::BindOnce(
+ [](uintptr_t inner_address) {
+ AsanStruct* inner_ptr =
+ reinterpret_cast<AsanStruct*>(inner_address);
+ // This will crash and should be detected as maybe protected, since
+ // it follows an extraction operation when the outer callback is
+ // invoked
+ inner_ptr->func();
+ },
+ reinterpret_cast<uintptr_t>(protected_ptr.get())));
+
+ // In this case, `inner_ptr` is protected in these callbacks, since it is
+ // bound before `*ptr` is deleted. We want to make sure that the access to
+ // `outer_ptr` is not automatically treated as protected, since it isn't.
+ auto unsafe_nested_outer_callback = base::BindOnce(
+ [](uintptr_t outer_address, base::OnceClosure inner_callback) {
+ { std::move(inner_callback).Run(); }
+ AsanStruct* outer_ptr = reinterpret_cast<AsanStruct*>(outer_address);
+ // This will crash and should be detected as maybe protected, since it
+ // follows an extraction operation when the inner callback is invoked.
+ outer_ptr->func();
+ },
+ reinterpret_cast<uintptr_t>(protected_ptr.get()),
+ base::BindOnce(
+ [](AsanStruct* inner_ptr) {
+ // Do nothing - we don't want to trip the protection inside the
+ // inner callback.
+ },
+ base::Unretained(protected_ptr)));
+
+ // Now delete `*protected_ptr` and check that the callbacks we created are
+ // handled correctly.
+ delete protected_ptr.get();
+ protected_ptr = nullptr;
+
+ EXPECT_DEATH_IF_SUPPORTED(std::move(unsafe_callback).Run(),
+ kAsanBrpNotProtected_NoRawPtrAccess);
+ EXPECT_DEATH_IF_SUPPORTED(std::move(unsafe_nested_inner_callback).Run(),
+ kAsanBrpMaybeProtected_Extraction);
+ EXPECT_DEATH_IF_SUPPORTED(std::move(unsafe_nested_outer_callback).Run(),
+ kAsanBrpMaybeProtected_Extraction);
+}
+
+TEST_F(AsanBackupRefPtrTest, BoundArgumentsInstantiation) {
+ // This test is ensuring that instantiations of `raw_ptr` inside callbacks are
+ // handled correctly.
+
+ raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
+
+ // First create our test callback while `*protected_ptr` is still valid.
+ auto callback = base::BindRepeating(
+ [](AsanStruct* ptr) {
+ // This will crash if `*protected_ptr` is not valid.
+ [[maybe_unused]] raw_ptr<AsanStruct> copy_ptr = ptr;
+ },
+ base::Unretained(protected_ptr));
+
+ // It is allowed to create a new `raw_ptr<T>` inside a callback while
+ // `*protected_ptr` is still valid.
+ callback.Run();
+
+ delete protected_ptr.get();
+ protected_ptr = nullptr;
+
+ // It is not allowed to create a new `raw_ptr<T>` inside a callback once
+ // `*protected_ptr` is no longer valid.
+ EXPECT_DEATH_IF_SUPPORTED(std::move(callback).Run(),
+ kAsanBrpNotProtected_Instantiation);
+}
+
+TEST_F(AsanBackupRefPtrTest, BoundReferences) {
+ auto ptr = ::std::make_unique<AsanStruct>();
+
+ // This test is ensuring that reference parameters inside callbacks are
+ // handled correctly.
+
+ // We should not crash during unwrapping a reference parameter if the
+ // parameter is not accessed inside the callback.
+ auto no_crash_callback = base::BindOnce(
+ [](AsanStruct& ref) {
+ // There should be no crash here as we don't access ref.
+ },
+ std::reference_wrapper(*ptr));
+
+ // `ref` is protected in this callback even after `*ptr` has been deleted,
+ // since the allocation will be kept alive by the internal `raw_ref<T>` inside
+ // base::UnretainedRefWrapper().
+ auto callback = base::BindOnce(
+ [](AsanStruct& ref) {
+ // This will crash and should be detected as protected
+ ref.func();
+ },
+ std::reference_wrapper(*ptr));
+
+ ptr.reset();
+
+ std::move(no_crash_callback).Run();
+
+ EXPECT_DEATH_IF_SUPPORTED(std::move(callback).Run(),
+ kAsanBrpProtected_Callback);
+}
+
+TEST_F(AsanBackupRefPtrTest, FreeOnAnotherThread) {
+ auto ptr = ::std::make_unique<AsanStruct>();
+ raw_ptr<AsanStruct> protected_ptr = ptr.get();
+
+ std::thread thread([&ptr] { ptr.reset(); });
+ thread.join();
+
+ EXPECT_DEATH_IF_SUPPORTED(protected_ptr->func(), kAsanBrpMaybeProtected_Race);
+}
+
+TEST_F(AsanBackupRefPtrTest, AccessOnThreadPoolThread) {
+ auto ptr = ::std::make_unique<AsanStruct>();
+ raw_ptr<AsanStruct> protected_ptr = ptr.get();
+
+ test::TaskEnvironment env;
+ RunLoop run_loop;
+
+ ThreadPool::PostTaskAndReply(
+ FROM_HERE, {}, base::BindLambdaForTesting([&ptr, &protected_ptr] {
+ ptr.reset();
+ EXPECT_DEATH_IF_SUPPORTED(protected_ptr->func(),
+ kAsanBrpMaybeProtected_ThreadPool);
+ }),
+ base::BindLambdaForTesting([&run_loop]() { run_loop.Quit(); }));
+ run_loop.Run();
+}
+
+TEST_F(AsanBackupRefPtrTest, DanglingUnretained) {
+ // The test should finish without crashing.
+
+ raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
+ delete protected_ptr.get();
+
+ auto ptr_callback = base::BindOnce(
+ [](AsanStruct* ptr) {
+ // Do nothing - we only check the behavior of `BindOnce` in this test.
+ },
+ protected_ptr);
+}
+
+} // namespace base::internal
+
+#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
diff --git a/base/memory/raw_ptr_unittest.cc b/base/memory/raw_ptr_unittest.cc
index dbf758f..3c1caa2 100644
--- a/base/memory/raw_ptr_unittest.cc
+++ b/base/memory/raw_ptr_unittest.cc
@@ -143,6 +143,8 @@
absl::optional<int> wrapped_ptr_swap_cnt;
absl::optional<int> wrapped_ptr_less_cnt;
absl::optional<int> pointer_to_member_operator_cnt;
+ absl::optional<int> wrap_raw_ptr_for_dup_cnt;
+ absl::optional<int> get_for_duplication_cnt;
};
#define REPORT_UNEQUAL_RAW_PTR_COUNTER(member_name, CounterClassImpl) \
@@ -155,18 +157,20 @@
result = false; \
} \
}
-#define REPORT_UNEQUAL_RAW_PTR_COUNTERS(result, CounterClassImpl) \
- { \
- result = true; \
- REPORT_UNEQUAL_RAW_PTR_COUNTER(wrap_raw_ptr_cnt, CounterClassImpl) \
- REPORT_UNEQUAL_RAW_PTR_COUNTER(release_wrapped_ptr_cnt, CounterClassImpl) \
- REPORT_UNEQUAL_RAW_PTR_COUNTER(get_for_dereference_cnt, CounterClassImpl) \
- REPORT_UNEQUAL_RAW_PTR_COUNTER(get_for_extraction_cnt, CounterClassImpl) \
- REPORT_UNEQUAL_RAW_PTR_COUNTER(get_for_comparison_cnt, CounterClassImpl) \
- REPORT_UNEQUAL_RAW_PTR_COUNTER(wrapped_ptr_swap_cnt, CounterClassImpl) \
- REPORT_UNEQUAL_RAW_PTR_COUNTER(wrapped_ptr_less_cnt, CounterClassImpl) \
- REPORT_UNEQUAL_RAW_PTR_COUNTER(pointer_to_member_operator_cnt, \
- CounterClassImpl) \
+#define REPORT_UNEQUAL_RAW_PTR_COUNTERS(result, CounterClassImpl) \
+ { \
+ result = true; \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(wrap_raw_ptr_cnt, CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(release_wrapped_ptr_cnt, CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(get_for_dereference_cnt, CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(get_for_extraction_cnt, CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(get_for_comparison_cnt, CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(wrapped_ptr_swap_cnt, CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(wrapped_ptr_less_cnt, CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(pointer_to_member_operator_cnt, \
+ CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(wrap_raw_ptr_for_dup_cnt, CounterClassImpl) \
+ REPORT_UNEQUAL_RAW_PTR_COUNTER(get_for_duplication_cnt, CounterClassImpl) \
}
// Matcher used with `CountingRawPtr`. Provides slightly shorter
@@ -269,11 +273,13 @@
CountingRawPtr<int> ptr = nullptr;
volatile bool is_valid = !!ptr; // !! to avoid implicit cast
is_valid = ptr || is_valid; // volatile, so won't be optimized
- if (ptr)
+ if (ptr) {
is_valid = true;
+ }
[[maybe_unused]] bool is_not_valid = !ptr;
- if (!ptr)
+ if (!ptr) {
is_not_valid = true;
+ }
std::ignore = IsValidNoCast(ptr);
std::ignore = IsValidNoCast2(ptr);
FuncThatAcceptsBool(!ptr);
@@ -1243,8 +1249,9 @@
size_t number_of_capacity_changes = 0;
do {
size_t previous_capacity = vector.capacity();
- while (vector.capacity() == previous_capacity)
+ while (vector.capacity() == previous_capacity) {
vector.emplace_back(&x);
+ }
number_of_capacity_changes++;
} while (number_of_capacity_changes < 10);
#if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) || \
@@ -1371,6 +1378,37 @@
EXPECT_EQ(&x, absl::get<raw_ptr<int>>(vary));
}
+TEST_F(RawPtrTest, CrossKindConversions) {
+ int x = 123;
+ CountingRawPtr<int> ptr1 = &x;
+
+ RawPtrCountingImpl::ClearCounters();
+ RawPtrCountingMayDangleImpl::ClearCounters();
+
+ CountingRawPtrMayDangle<int> ptr2(ptr1);
+
+ EXPECT_THAT((CountingRawPtrExpectations{.get_for_dereference_cnt = 0,
+ .get_for_extraction_cnt = 0,
+ .get_for_duplication_cnt = 1}),
+ CountingRawPtrHasCounts());
+ EXPECT_THAT((CountingRawPtrExpectations{.wrap_raw_ptr_cnt = 0,
+ .wrap_raw_ptr_for_dup_cnt = 1}),
+ MayDangleCountingRawPtrHasCounts());
+
+ RawPtrCountingImpl::ClearCounters();
+ RawPtrCountingMayDangleImpl::ClearCounters();
+
+ CountingRawPtr<int> ptr3(ptr2);
+
+ EXPECT_THAT((CountingRawPtrExpectations{.get_for_dereference_cnt = 0,
+ .get_for_extraction_cnt = 0,
+ .get_for_duplication_cnt = 1}),
+ MayDangleCountingRawPtrHasCounts());
+ EXPECT_THAT((CountingRawPtrExpectations{.wrap_raw_ptr_cnt = 0,
+ .wrap_raw_ptr_for_dup_cnt = 1}),
+ CountingRawPtrHasCounts());
+}
+
} // namespace
namespace base {
@@ -1561,6 +1599,21 @@
EXPECT_CHECK_DEATH(protected_ptr -= 1);
EXPECT_CHECK_DEATH(--protected_ptr);
+#if PA_CONFIG(USE_OOB_POISON)
+ // An array type that should be more than a third the size of the available
+ // memory for the allocation such that incrementing a pointer to this type
+ // twice causes it to point to a memory location that is too small to fit a
+ // complete element of this type.
+ typedef int OverThirdArray[200 / sizeof(int)];
+ raw_ptr<OverThirdArray> protected_arr_ptr =
+ reinterpret_cast<OverThirdArray*>(ptr);
+
+ protected_arr_ptr++;
+ **protected_arr_ptr = 4;
+ protected_arr_ptr++;
+ EXPECT_DEATH_IF_SUPPORTED(** protected_arr_ptr = 4, "");
+#endif
+
allocator.root()->Free(ptr);
}
@@ -1787,8 +1840,9 @@
void* ptr_1 = allocator_.root()->Alloc(16, "");
void* ptr_2 = allocator_.root()->Alloc(16, "");
- if (ptr_1 > ptr_2)
+ if (ptr_1 > ptr_2) {
std::swap(ptr_1, ptr_2);
+ }
raw_ptr<void, DisableDanglingPtrDetection> dangling_ptr_1 = ptr_1;
raw_ptr<void, DisableDanglingPtrDetection> dangling_ptr_2 = ptr_2;
@@ -2015,425 +2069,6 @@
#endif // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT) &&
// !defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
-#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
-
-struct AsanStruct {
- int x;
-
- void func() { ++x; }
-};
-
-#define ASAN_BRP_PROTECTED(x) "MiraclePtr Status: PROTECTED\\n.*" x
-#define ASAN_BRP_MANUAL_ANALYSIS(x) \
- "MiraclePtr Status: MANUAL ANALYSIS REQUIRED\\n.*" x
-#define ASAN_BRP_NOT_PROTECTED(x) "MiraclePtr Status: NOT PROTECTED\\n.*" x
-
-const char kAsanBrpProtected_Dereference[] =
- ASAN_BRP_PROTECTED("dangling pointer was being dereferenced");
-const char kAsanBrpProtected_Callback[] = ASAN_BRP_PROTECTED(
- "crash occurred inside a callback where a raw_ptr<T> pointing to the same "
- "region");
-const char kAsanBrpMaybeProtected_Extraction[] = ASAN_BRP_MANUAL_ANALYSIS(
- "pointer to the same region was extracted from a raw_ptr<T>");
-const char kAsanBrpNotProtected_Instantiation[] = ASAN_BRP_NOT_PROTECTED(
- "pointer to an already freed region was assigned to a raw_ptr<T>");
-const char kAsanBrpNotProtected_EarlyAllocation[] = ASAN_BRP_NOT_PROTECTED(
- "crash occurred while accessing a region that was allocated before "
- "MiraclePtr was activated");
-const char kAsanBrpNotProtected_NoRawPtrAccess[] =
- ASAN_BRP_NOT_PROTECTED("No raw_ptr<T> access to this region was detected");
-const char kAsanBrpMaybeProtected_Race[] =
- ASAN_BRP_MANUAL_ANALYSIS("\\nThe \"use\" and \"free\" threads don't match");
-const char kAsanBrpMaybeProtected_ThreadPool[] =
- ASAN_BRP_MANUAL_ANALYSIS("\\nThis crash occurred in the thread pool");
-
-#undef ASAN_BRP_PROTECTED
-#undef ASAN_BRP_MANUAL_ANALYSIS
-#undef ASAN_BRP_NOT_PROTECTED
-
-class AsanBackupRefPtrTest : public testing::Test {
- protected:
- void SetUp() override {
- base::debug::AsanService::GetInstance()->Initialize();
-
- if (!RawPtrAsanService::GetInstance().IsEnabled()) {
- base::RawPtrAsanService::GetInstance().Configure(
- base::EnableDereferenceCheck(true), base::EnableExtractionCheck(true),
- base::EnableInstantiationCheck(true));
- } else {
- ASSERT_TRUE(base::RawPtrAsanService::GetInstance()
- .is_dereference_check_enabled());
- ASSERT_TRUE(
- base::RawPtrAsanService::GetInstance().is_extraction_check_enabled());
- ASSERT_TRUE(base::RawPtrAsanService::GetInstance()
- .is_instantiation_check_enabled());
- }
- }
-
- static void SetUpTestSuite() { early_allocation_ptr_ = new AsanStruct; }
- static void TearDownTestSuite() { delete early_allocation_ptr_; }
- static raw_ptr<AsanStruct> early_allocation_ptr_;
-};
-
-raw_ptr<AsanStruct> AsanBackupRefPtrTest::early_allocation_ptr_ = nullptr;
-
-TEST_F(AsanBackupRefPtrTest, Dereference) {
- raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
-
- // The four statements below should succeed.
- (*protected_ptr).x = 1;
- (*protected_ptr).func();
- ++(protected_ptr->x);
- protected_ptr->func();
-
- delete protected_ptr.get();
-
- EXPECT_DEATH_IF_SUPPORTED((*protected_ptr).x = 1,
- kAsanBrpProtected_Dereference);
- EXPECT_DEATH_IF_SUPPORTED((*protected_ptr).func(),
- kAsanBrpProtected_Dereference);
- EXPECT_DEATH_IF_SUPPORTED(++(protected_ptr->x),
- kAsanBrpProtected_Dereference);
- EXPECT_DEATH_IF_SUPPORTED(protected_ptr->func(),
- kAsanBrpProtected_Dereference);
-
- // The following statement should not trigger a dereference, so it should
- // succeed without crashing even though *protected_ptr is no longer valid.
- [[maybe_unused]] AsanStruct* ptr = protected_ptr;
-}
-
-TEST_F(AsanBackupRefPtrTest, Extraction) {
- raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
-
- AsanStruct* ptr1 = protected_ptr; // Shouldn't crash.
- ptr1->x = 0;
-
- delete protected_ptr.get();
-
- EXPECT_DEATH_IF_SUPPORTED(
- {
- AsanStruct* ptr2 = protected_ptr;
- ptr2->x = 1;
- },
- kAsanBrpMaybeProtected_Extraction);
-}
-
-TEST_F(AsanBackupRefPtrTest, Instantiation) {
- AsanStruct* ptr = new AsanStruct;
-
- raw_ptr<AsanStruct> protected_ptr1 = ptr; // Shouldn't crash.
- protected_ptr1 = nullptr;
-
- delete ptr;
-
- EXPECT_DEATH_IF_SUPPORTED(
- { [[maybe_unused]] raw_ptr<AsanStruct> protected_ptr2 = ptr; },
- kAsanBrpNotProtected_Instantiation);
-}
-
-TEST_F(AsanBackupRefPtrTest, InstantiationInvalidPointer) {
- void* ptr1 = reinterpret_cast<void*>(0xfefefefefefefefe);
-
- [[maybe_unused]] raw_ptr<void> protected_ptr1 = ptr1; // Shouldn't crash.
-
- size_t shadow_scale, shadow_offset;
- __asan_get_shadow_mapping(&shadow_scale, &shadow_offset);
- [[maybe_unused]] raw_ptr<void> protected_ptr2 =
- reinterpret_cast<void*>(shadow_offset); // Shouldn't crash.
-}
-
-TEST_F(AsanBackupRefPtrTest, UserPoisoned) {
- AsanStruct* ptr = new AsanStruct;
- __asan_poison_memory_region(ptr, sizeof(AsanStruct));
-
- [[maybe_unused]] raw_ptr<AsanStruct> protected_ptr1 =
- ptr; // Shouldn't crash.
-
- delete ptr; // Should crash now.
- EXPECT_DEATH_IF_SUPPORTED(
- { [[maybe_unused]] raw_ptr<AsanStruct> protected_ptr2 = ptr; },
- kAsanBrpNotProtected_Instantiation);
-}
-
-TEST_F(AsanBackupRefPtrTest, EarlyAllocationDetection) {
- if (!early_allocation_ptr_) {
- // We can't run this test if we don't have a pre-BRP-ASan-initialization
- // allocation.
- return;
- }
- raw_ptr<AsanStruct> late_allocation_ptr = new AsanStruct;
- EXPECT_FALSE(RawPtrAsanService::GetInstance().IsSupportedAllocation(
- early_allocation_ptr_.get()));
- EXPECT_TRUE(RawPtrAsanService::GetInstance().IsSupportedAllocation(
- late_allocation_ptr.get()));
-
- delete late_allocation_ptr.get();
- delete early_allocation_ptr_.get();
-
- EXPECT_FALSE(RawPtrAsanService::GetInstance().IsSupportedAllocation(
- early_allocation_ptr_.get()));
- EXPECT_TRUE(RawPtrAsanService::GetInstance().IsSupportedAllocation(
- late_allocation_ptr.get()));
-
- EXPECT_DEATH_IF_SUPPORTED({ early_allocation_ptr_->func(); },
- kAsanBrpNotProtected_EarlyAllocation);
- EXPECT_DEATH_IF_SUPPORTED({ late_allocation_ptr->func(); },
- kAsanBrpProtected_Dereference);
-
- early_allocation_ptr_ = nullptr;
-}
-
-TEST_F(AsanBackupRefPtrTest, BoundRawPtr) {
- // This test is for the handling of raw_ptr<T> type objects being passed
- // directly to Bind.
-
- raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
-
- // First create our test callbacks while `*protected_ptr` is still valid, and
- // we will then invoke them after deleting `*protected_ptr`.
-
- // `ptr` is protected in this callback, as raw_ptr<T> will be mapped to an
- // UnretainedWrapper containing a raw_ptr<T> which is guaranteed to outlive
- // the function call.
- auto ptr_callback = base::BindOnce(
- [](AsanStruct* ptr) {
- // This will crash and should be detected as a protected access.
- ptr->func();
- },
- protected_ptr);
-
- // Now delete `*protected_ptr` and check that the callbacks we created are
- // handled correctly.
- delete protected_ptr.get();
- protected_ptr = nullptr;
-
- EXPECT_DEATH_IF_SUPPORTED(std::move(ptr_callback).Run(),
- kAsanBrpProtected_Callback);
-}
-
-TEST_F(AsanBackupRefPtrTest, BoundArgumentsProtected) {
- raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
- raw_ptr<AsanStruct> protected_ptr2 = new AsanStruct;
-
- // First create our test callbacks while `*protected_ptr` is still valid, and
- // we will then invoke them after deleting `*protected_ptr`.
-
- // `ptr` is protected in this callback even after `*ptr` has been deleted,
- // since the allocation will be kept alive by the internal `raw_ptr<T>` inside
- // base::Unretained().
- auto safe_callback = base::BindOnce(
- [](AsanStruct* ptr) {
- // This will crash and should be detected as a protected access.
- ptr->func();
- },
- base::Unretained(protected_ptr));
-
- // Both `inner_ptr` and `outer_ptr` are protected in these callbacks, since
- // both are bound before `*ptr` is deleted. This test is making sure that
- // `inner_ptr` is treated as protected.
- auto safe_nested_inner_callback = base::BindOnce(
- [](AsanStruct* outer_ptr, base::OnceClosure inner_callback) {
- std::move(inner_callback).Run();
- // This will never be executed, as we will crash in inner_callback
- ASSERT_TRUE(false);
- },
- base::Unretained(protected_ptr),
- base::BindOnce(
- [](AsanStruct* inner_ptr) {
- // This will crash and should be detected as a protected access.
- inner_ptr->func();
- },
- base::Unretained(protected_ptr2)));
-
- // Both `inner_ptr` and `outer_ptr` are protected in these callbacks, since
- // both are bound before `*ptr` is deleted. This test is making sure that
- // `outer_ptr` is still treated as protected after `inner_callback` has run.
- auto safe_nested_outer_callback = base::BindOnce(
- [](AsanStruct* outer_ptr, base::OnceClosure inner_callback) {
- std::move(inner_callback).Run();
- // This will crash and should be detected as a protected access.
- outer_ptr->func();
- },
- base::Unretained(protected_ptr),
- base::BindOnce(
- [](AsanStruct* inner_ptr) {
- // Do nothing.
- },
- base::Unretained(protected_ptr2)));
-
- // Now delete `*protected_ptr` and check that the callbacks we created are
- // handled correctly.
- delete protected_ptr.get();
- delete protected_ptr2.get();
- protected_ptr = nullptr;
- protected_ptr2 = nullptr;
-
- EXPECT_DEATH_IF_SUPPORTED(std::move(safe_callback).Run(),
- kAsanBrpProtected_Callback);
- EXPECT_DEATH_IF_SUPPORTED(std::move(safe_nested_inner_callback).Run(),
- kAsanBrpProtected_Callback);
- EXPECT_DEATH_IF_SUPPORTED(std::move(safe_nested_outer_callback).Run(),
- kAsanBrpProtected_Callback);
-}
-
-TEST_F(AsanBackupRefPtrTest, BoundArgumentsNotProtected) {
- raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
-
- // First create our test callbacks while `*protected_ptr` is still valid, and
- // we will then invoke them after deleting `*protected_ptr`.
-
- // `ptr` is not protected in this callback after `*ptr` has been deleted, as
- // integer-type bind arguments do not use an internal `raw_ptr<T>`.
- auto unsafe_callback = base::BindOnce(
- [](uintptr_t address) {
- AsanStruct* ptr = reinterpret_cast<AsanStruct*>(address);
- // This will crash and should not be detected as a protected access.
- ptr->func();
- },
- reinterpret_cast<uintptr_t>(protected_ptr.get()));
-
- // In this case, `outer_ptr` is protected in these callbacks, since it is
- // bound before `*ptr` is deleted. We want to make sure that the access to
- // `inner_ptr` is not automatically treated as protected (although it actually
- // is) because we're trying to limit the protection scope to be very
- // conservative here.
- auto unsafe_nested_inner_callback = base::BindOnce(
- [](AsanStruct* outer_ptr, base::OnceClosure inner_callback) {
- std::move(inner_callback).Run();
- // This will never be executed, as we will crash in inner_callback
- NOTREACHED();
- },
- base::Unretained(protected_ptr),
- base::BindOnce(
- [](uintptr_t inner_address) {
- AsanStruct* inner_ptr =
- reinterpret_cast<AsanStruct*>(inner_address);
- // This will crash and should be detected as maybe protected, since
- // it follows an extraction operation when the outer callback is
- // invoked
- inner_ptr->func();
- },
- reinterpret_cast<uintptr_t>(protected_ptr.get())));
-
- // In this case, `inner_ptr` is protected in these callbacks, since it is
- // bound before `*ptr` is deleted. We want to make sure that the access to
- // `outer_ptr` is not automatically treated as protected, since it isn't.
- auto unsafe_nested_outer_callback = base::BindOnce(
- [](uintptr_t outer_address, base::OnceClosure inner_callback) {
- { std::move(inner_callback).Run(); }
- AsanStruct* outer_ptr = reinterpret_cast<AsanStruct*>(outer_address);
- // This will crash and should be detected as maybe protected, since it
- // follows an extraction operation when the inner callback is invoked.
- outer_ptr->func();
- },
- reinterpret_cast<uintptr_t>(protected_ptr.get()),
- base::BindOnce(
- [](AsanStruct* inner_ptr) {
- // Do nothing
- },
- base::Unretained(protected_ptr)));
-
- // Now delete `*protected_ptr` and check that the callbacks we created are
- // handled correctly.
- delete protected_ptr.get();
- protected_ptr = nullptr;
-
- EXPECT_DEATH_IF_SUPPORTED(std::move(unsafe_callback).Run(),
- kAsanBrpNotProtected_NoRawPtrAccess);
- EXPECT_DEATH_IF_SUPPORTED(std::move(unsafe_nested_inner_callback).Run(),
- kAsanBrpMaybeProtected_Extraction);
- EXPECT_DEATH_IF_SUPPORTED(std::move(unsafe_nested_outer_callback).Run(),
- kAsanBrpMaybeProtected_Extraction);
-}
-
-TEST_F(AsanBackupRefPtrTest, BoundArgumentsInstantiation) {
- // This test is ensuring that instantiations of `raw_ptr` inside callbacks are
- // handled correctly.
-
- raw_ptr<AsanStruct> protected_ptr = new AsanStruct;
-
- // First create our test callback while `*protected_ptr` is still valid.
- auto callback = base::BindRepeating(
- [](AsanStruct* ptr) {
- // This will crash if `*protected_ptr` is not valid.
- [[maybe_unused]] raw_ptr<AsanStruct> copy_ptr = ptr;
- },
- base::Unretained(protected_ptr));
-
- // It is allowed to create a new `raw_ptr<T>` inside a callback while
- // `*protected_ptr` is still valid.
- callback.Run();
-
- delete protected_ptr.get();
- protected_ptr = nullptr;
-
- // It is not allowed to create a new `raw_ptr<T>` inside a callback once
- // `*protected_ptr` is no longer valid.
- EXPECT_DEATH_IF_SUPPORTED(std::move(callback).Run(),
- kAsanBrpNotProtected_Instantiation);
-}
-
-TEST_F(AsanBackupRefPtrTest, BoundReferences) {
- auto ptr = ::std::make_unique<AsanStruct>();
-
- // This test is ensuring that reference parameters inside callbacks are
- // handled correctly.
-
- // We should not crash during unwrapping a reference parameter if the
- // parameter is not accessed inside the callback.
- auto no_crash_callback = base::BindOnce(
- [](AsanStruct& ref) {
- // There should be no crash here as we don't access ref.
- },
- std::reference_wrapper(*ptr));
-
- // `ref` is protected in this callback even after `*ptr` has been deleted,
- // since the allocation will be kept alive by the internal `raw_ref<T>` inside
- // base::UnretainedRefWrapper().
- auto callback = base::BindOnce(
- [](AsanStruct& ref) {
- // This will crash and should be detected as protected
- ref.func();
- },
- std::reference_wrapper(*ptr));
-
- ptr.reset();
-
- std::move(no_crash_callback).Run();
-
- EXPECT_DEATH_IF_SUPPORTED(std::move(callback).Run(),
- kAsanBrpProtected_Callback);
-}
-
-TEST_F(AsanBackupRefPtrTest, FreeOnAnotherThread) {
- auto ptr = ::std::make_unique<AsanStruct>();
- raw_ptr<AsanStruct> protected_ptr = ptr.get();
-
- std::thread thread([&ptr] { ptr.reset(); });
- thread.join();
-
- EXPECT_DEATH_IF_SUPPORTED(protected_ptr->func(), kAsanBrpMaybeProtected_Race);
-}
-
-TEST_F(AsanBackupRefPtrTest, AccessOnThreadPoolThread) {
- auto ptr = ::std::make_unique<AsanStruct>();
- raw_ptr<AsanStruct> protected_ptr = ptr.get();
-
- test::TaskEnvironment env;
- RunLoop run_loop;
-
- ThreadPool::PostTaskAndReply(
- FROM_HERE, {}, base::BindLambdaForTesting([&ptr, &protected_ptr] {
- ptr.reset();
- EXPECT_DEATH_IF_SUPPORTED(protected_ptr->func(),
- kAsanBrpMaybeProtected_ThreadPool);
- }),
- base::BindLambdaForTesting([&run_loop]() { run_loop.Quit(); }));
- run_loop.Run();
-}
-
-#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
-
#if PA_CONFIG(ENABLE_MTE_CHECKED_PTR_SUPPORT_WITH_64_BITS_POINTERS)
static constexpr size_t kTagOffsetForTest = 2;
@@ -2460,8 +2095,9 @@
uintptr_t addr = reinterpret_cast<uintptr_t>(ptr);
uintptr_t mask = 0xFFFFFFFFFFFFFFFF;
- if (sizeof(partition_alloc::PartitionTag) < 2)
+ if (sizeof(partition_alloc::PartitionTag) < 2) {
mask = 0x00FFFFFFFFFFFFFF;
+ }
uintptr_t wrapped =
reinterpret_cast<uintptr_t>(MTECheckedPtrImplForTest::WrapRawPtr(ptr));
diff --git a/base/memory/raw_ptr_unittest.nc b/base/memory/raw_ptr_unittest.nc
index 2f2ac6e..ba54d7b 100644
--- a/base/memory/raw_ptr_unittest.nc
+++ b/base/memory/raw_ptr_unittest.nc
@@ -9,8 +9,8 @@
#include <tuple> // for std::ignore
#include <type_traits> // for std::remove_pointer_t
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
namespace {
diff --git a/base/memory/raw_ref.h b/base/memory/raw_ref.h
index 1369d9d..a122b76 100644
--- a/base/memory/raw_ref.h
+++ b/base/memory/raw_ref.h
@@ -80,9 +80,6 @@
internal::MTECheckedPtrImpl<
internal::MTECheckedPtrImplPartitionAllocSupport>> ||
#endif // PA_CONFIG(ENABLE_MTE_CHECKED_PTR_SUPPORT_WITH_64_BITS_POINTERS)
-#if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
- std::is_same_v<Impl, internal::AsanBackupRefPtrImpl> ||
-#endif // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
#if BUILDFLAG(USE_ASAN_UNOWNED_PTR)
std::is_same_v<Impl, internal::AsanUnownedPtrImpl> ||
#endif // BUILDFLAG(USE_ASAN_UNOWNED_PTR)
@@ -107,8 +104,9 @@
PA_ALWAYS_INLINE raw_ref(raw_ref&& p) noexcept : inner_(std::move(p.inner_)) {
PA_RAW_PTR_CHECK(inner_.get()); // Catch use-after-move.
- if constexpr (need_clear_after_move)
+ if constexpr (need_clear_after_move) {
p.inner_ = nullptr;
+ }
}
PA_ALWAYS_INLINE raw_ref& operator=(const raw_ref& p) noexcept {
@@ -120,8 +118,9 @@
PA_ALWAYS_INLINE raw_ref& operator=(raw_ref&& p) noexcept {
PA_RAW_PTR_CHECK(p.inner_.get()); // Catch use-after-move.
inner_.operator=(std::move(p.inner_));
- if constexpr (need_clear_after_move)
+ if constexpr (need_clear_after_move) {
p.inner_ = nullptr;
+ }
return *this;
}
@@ -138,8 +137,9 @@
PA_ALWAYS_INLINE raw_ref(raw_ref<U, RawPtrType>&& p) noexcept
: inner_(std::move(p.inner_)) {
PA_RAW_PTR_CHECK(inner_.get()); // Catch use-after-move.
- if constexpr (need_clear_after_move)
+ if constexpr (need_clear_after_move) {
p.inner_ = nullptr;
+ }
}
static PA_ALWAYS_INLINE raw_ref from_ptr(T* ptr) noexcept {
@@ -159,8 +159,9 @@
PA_ALWAYS_INLINE raw_ref& operator=(raw_ref<U, RawPtrType>&& p) noexcept {
PA_RAW_PTR_CHECK(p.inner_.get()); // Catch use-after-move.
inner_.operator=(std::move(p.inner_));
- if constexpr (need_clear_after_move)
+ if constexpr (need_clear_after_move) {
p.inner_ = nullptr;
+ }
return *this;
}
diff --git a/base/memory/raw_ref_unittest.cc b/base/memory/raw_ref_unittest.cc
index 3db0680..884da5d 100644
--- a/base/memory/raw_ref_unittest.cc
+++ b/base/memory/raw_ref_unittest.cc
@@ -747,11 +747,12 @@
struct S {
const raw_ref<const std::string> r;
};
- // Deduces as raw_ref<std::string>, for which the constructor call is valid making a mutable
- // reference, and then converts to raw_ref<const std::string>.
+ // Deduces as `raw_ref<std::string>`, for which the constructor call is valid
+ // making a mutable reference, and then converts to
+ // `raw_ref<const std::string>`.
S s1 = {.r = raw_ref(str)};
- // Deduces as raw_ref<const std::string>, for which the constructor call is valid from a const
- // ref.
+ // Deduces as raw_ref<const std::string>, for which the constructor call is
+ // valid from a const ref.
S s2 = {.r = raw_ref(static_cast<const std::string&>(str))};
EXPECT_EQ(&*s1.r, &str);
EXPECT_EQ(&*s2.r, &str);
diff --git a/base/memory/safe_ref_unittest.cc b/base/memory/safe_ref_unittest.cc
index 19a8054..bdeadb9 100644
--- a/base/memory/safe_ref_unittest.cc
+++ b/base/memory/safe_ref_unittest.cc
@@ -6,8 +6,9 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/weak_ptr.h"
#include "base/test/gtest_util.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -25,7 +26,9 @@
void Method() {}
int i = 1;
- WithWeak* self{this};
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION WithWeak* self{this};
base::WeakPtrFactory<WithWeak> factory{this};
};
diff --git a/base/memory/scoped_refptr.h b/base/memory/scoped_refptr.h
index 693e64f..79979fe 100644
--- a/base/memory/scoped_refptr.h
+++ b/base/memory/scoped_refptr.h
@@ -13,6 +13,7 @@
#include "base/check.h"
#include "base/compiler_specific.h"
+#include "base/memory/raw_ptr_exclusion.h"
template <class T>
class scoped_refptr;
@@ -332,7 +333,9 @@
}
protected:
- T* ptr_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union, #addr-of, #global-scope
+ RAW_PTR_EXCLUSION T* ptr_ = nullptr;
private:
template <typename U>
diff --git a/base/memory/weak_ptr_unittest.cc b/base/memory/weak_ptr_unittest.cc
index 5a6c873..869fed3 100644
--- a/base/memory/weak_ptr_unittest.cc
+++ b/base/memory/weak_ptr_unittest.cc
@@ -7,8 +7,8 @@
#include <memory>
#include <string>
-#include "base/bind.h"
#include "base/debug/leak_annotations.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/message_loop/fd_watch_controller_posix_unittest.cc b/base/message_loop/fd_watch_controller_posix_unittest.cc
index 70f7240..766f392 100644
--- a/base/message_loop/fd_watch_controller_posix_unittest.cc
+++ b/base/message_loop/fd_watch_controller_posix_unittest.cc
@@ -5,10 +5,10 @@
#include <sys/socket.h>
-#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
+#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_pump_for_io.h"
diff --git a/base/message_loop/message_pump_android.cc b/base/message_loop/message_pump_android.cc
index 645a192..eb8e897 100644
--- a/base/message_loop/message_pump_android.cc
+++ b/base/message_loop/message_pump_android.cc
@@ -17,8 +17,8 @@
#include "base/android/jni_android.h"
#include "base/android/scoped_java_ref.h"
-#include "base/callback_helpers.h"
#include "base/check_op.h"
+#include "base/functional/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/notreached.h"
#include "base/numerics/safe_conversions.h"
diff --git a/base/message_loop/message_pump_android.h b/base/message_loop/message_pump_android.h
index d28bd2e..0c8fe97 100644
--- a/base/message_loop/message_pump_android.h
+++ b/base/message_loop/message_pump_android.h
@@ -11,8 +11,8 @@
#include "base/android/scoped_java_ref.h"
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/compiler_specific.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/message_loop/message_pump.h"
#include "base/time/time.h"
diff --git a/base/message_loop/message_pump_default.cc b/base/message_loop/message_pump_default.cc
index 789545c..96abf52 100644
--- a/base/message_loop/message_pump_default.cc
+++ b/base/message_loop/message_pump_default.cc
@@ -23,7 +23,7 @@
namespace {
#if BUILDFLAG(IS_APPLE)
-bool g_use_thread_qos = false;
+bool g_use_thread_qos = true;
#endif
} // namespace
diff --git a/base/message_loop/message_pump_epoll.h b/base/message_loop/message_pump_epoll.h
index 3152d66..150a4aa 100644
--- a/base/message_loop/message_pump_epoll.h
+++ b/base/message_loop/message_pump_epoll.h
@@ -14,6 +14,7 @@
#include "base/containers/stack_container.h"
#include "base/files/scoped_file.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_pump.h"
@@ -128,7 +129,9 @@
// Null if Run() is not currently executing. Otherwise it's a pointer into the
// stack of the innermost nested Run() invocation.
- RunState* run_state_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #addr-of
+ RAW_PTR_EXCLUSION RunState* run_state_ = nullptr;
// Mapping of all file descriptors currently watched by this message pump.
// std::map was chosen because (1) the number of elements can vary widely,
diff --git a/base/message_loop/message_pump_glib_unittest.cc b/base/message_loop/message_pump_glib_unittest.cc
index b41443c..b202b40 100644
--- a/base/message_loop/message_pump_glib_unittest.cc
+++ b/base/message_loop/message_pump_glib_unittest.cc
@@ -10,10 +10,10 @@
#include <algorithm>
#include <vector>
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/message_loop/message_pump_kqueue_unittest.cc b/base/message_loop/message_pump_kqueue_unittest.cc
index 96a2f2f..49712c3 100644
--- a/base/message_loop/message_pump_kqueue_unittest.cc
+++ b/base/message_loop/message_pump_kqueue_unittest.cc
@@ -9,7 +9,7 @@
#include <utility>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
diff --git a/base/message_loop/message_pump_libevent.h b/base/message_loop/message_pump_libevent.h
index b99e244..4017d93 100644
--- a/base/message_loop/message_pump_libevent.h
+++ b/base/message_loop/message_pump_libevent.h
@@ -11,6 +11,7 @@
#include "base/base_export.h"
#include "base/compiler_specific.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_pump.h"
#include "base/message_loop/message_pump_buildflags.h"
@@ -232,7 +233,9 @@
#endif
// State for the current invocation of Run(). null if not running.
- RunState* run_state_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #addr-of
+ RAW_PTR_EXCLUSION RunState* run_state_ = nullptr;
// This flag is set if libevent has processed I/O events.
bool processed_io_events_ = false;
diff --git a/base/message_loop/message_pump_libevent_unittest.cc b/base/message_loop/message_pump_libevent_unittest.cc
index c829712..f163b8b 100644
--- a/base/message_loop/message_pump_libevent_unittest.cc
+++ b/base/message_loop/message_pump_libevent_unittest.cc
@@ -9,10 +9,10 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/containers/span.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/message_loop/message_pump_perftest.cc b/base/message_loop/message_pump_perftest.cc
index c5d7c4a..ae64cf1 100644
--- a/base/message_loop/message_pump_perftest.cc
+++ b/base/message_loop/message_pump_perftest.cc
@@ -7,9 +7,9 @@
#include <memory>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/format_macros.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_pump_type.h"
#include "base/strings/stringprintf.h"
diff --git a/base/message_loop/message_pump_unittest.cc b/base/message_loop/message_pump_unittest.cc
index 11c40c3..c650388 100644
--- a/base/message_loop/message_pump_unittest.cc
+++ b/base/message_loop/message_pump_unittest.cc
@@ -6,7 +6,7 @@
#include <type_traits>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/message_loop/message_pump_for_io.h"
diff --git a/base/message_loop/work_id_provider_unittest.cc b/base/message_loop/work_id_provider_unittest.cc
index 3b4ab0f..d5e70c1 100644
--- a/base/message_loop/work_id_provider_unittest.cc
+++ b/base/message_loop/work_id_provider_unittest.cc
@@ -8,7 +8,7 @@
#include <memory>
#include <utility>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/test/bind.h"
#include "base/threading/simple_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/metrics/field_trial.cc b/base/metrics/field_trial.cc
index 117e062..8756a3b 100644
--- a/base/metrics/field_trial.cc
+++ b/base/metrics/field_trial.cc
@@ -517,22 +517,6 @@
}
// static
-void FieldTrialList::StatesToString(std::string* output) {
- FieldTrial::ActiveGroups active_groups;
- GetActiveFieldTrialGroups(&active_groups);
- for (const auto& active_group : active_groups) {
- DCHECK_EQ(std::string::npos,
- active_group.trial_name.find(kPersistentStringSeparator));
- DCHECK_EQ(std::string::npos,
- active_group.group_name.find(kPersistentStringSeparator));
- output->append(active_group.trial_name);
- output->append(1, kPersistentStringSeparator);
- output->append(active_group.group_name);
- output->append(1, kPersistentStringSeparator);
- }
-}
-
-// static
std::vector<FieldTrial::State> FieldTrialList::GetAllFieldTrialStates(
PassKey<test::ScopedFeatureList>) {
std::vector<FieldTrial::State> states;
diff --git a/base/metrics/field_trial.h b/base/metrics/field_trial.h
index 67496e3..efa8ff6 100644
--- a/base/metrics/field_trial.h
+++ b/base/metrics/field_trial.h
@@ -371,9 +371,9 @@
//------------------------------------------------------------------------------
// Class with a list of all active field trials. A trial is active if it has
-// been registered, which includes evaluating its state based on its probaility.
-// Only one instance of this class exists and outside of testing, will live for
-// the entire life time of the process.
+// been registered, which includes evaluating its state based on its
+// probability. Only one instance of this class exists and outside of testing,
+// will live for the entire life time of the process.
class BASE_EXPORT FieldTrialList {
public:
using FieldTrialAllocator = PersistentMemoryAllocator;
@@ -450,16 +450,6 @@
// Returns true if the named trial exists and has been activated.
static bool IsTrialActive(StringPiece trial_name);
- // Creates a persistent representation of active FieldTrial instances for
- // resurrection in another process. This allows randomization to be done in
- // one process, and secondary processes can be synchronized on the result.
- // The resulting string contains the name and group name pairs of all
- // registered FieldTrials for which the group has been chosen and externally
- // observed (via |group()|) and which have not been disabled, with "/" used
- // to separate all names and to terminate the string. This string is parsed
- // by |CreateTrialsFromString()|.
- static void StatesToString(std::string* output);
-
// Creates a persistent representation of all FieldTrial instances for
// resurrection in another process. This allows randomization to be done in
// one process, and secondary processes can be synchronized on the result.
@@ -499,7 +489,7 @@
const CommandLine& command_line,
FieldTrial::ActiveGroups* active_groups);
- // Use a state string (re: StatesToString()) to augment the current list of
+ // Use a state string (re: AllStatesToString()) to augment the current list of
// field trials to include the supplied trials, and using a 100% probability
// for each trial, force them to have the same group string. This is commonly
// used in a non-browser process, to carry randomly selected state in a
diff --git a/base/metrics/field_trial_params.h b/base/metrics/field_trial_params.h
index 0caab78..39cc5f0 100644
--- a/base/metrics/field_trial_params.h
+++ b/base/metrics/field_trial_params.h
@@ -11,6 +11,7 @@
#include "base/base_export.h"
#include "base/feature_list.h"
#include "base/logging.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/notreached.h"
#include "base/time/time.h"
@@ -149,7 +150,9 @@
// GetFieldTrialParamValueByFeature() for more details.
BASE_EXPORT std::string Get() const;
- const Feature* const feature;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #global-scope, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const Feature* const feature;
const char* const name;
const char* const default_value;
};
@@ -172,7 +175,9 @@
// GetFieldTrialParamValueByFeature() for more details.
BASE_EXPORT double Get() const;
- const Feature* const feature;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #global-scope, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const Feature* const feature;
const char* const name;
const double default_value;
};
@@ -195,7 +200,9 @@
// GetFieldTrialParamValueByFeature() for more details.
BASE_EXPORT int Get() const;
- const Feature* const feature;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #global-scope, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const Feature* const feature;
const char* const name;
const int default_value;
};
@@ -218,7 +225,9 @@
// GetFieldTrialParamValueByFeature() for more details.
BASE_EXPORT bool Get() const;
- const Feature* const feature;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #global-scope, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const Feature* const feature;
const char* const name;
const bool default_value;
};
@@ -241,7 +250,9 @@
// GetFieldTrialParamValueByFeature() for more details.
BASE_EXPORT base::TimeDelta Get() const;
- const Feature* const feature;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #global-scope, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const Feature* const feature;
const char* const name;
const base::TimeDelta default_value;
};
@@ -310,10 +321,14 @@
return "";
}
- const base::Feature* const feature;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #global-scope, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const base::Feature* const feature;
const char* const name;
const Enum default_value;
- const Option* const options;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #global-scope, #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION const Option* const options;
const size_t option_count;
};
diff --git a/base/metrics/field_trial_unittest.cc b/base/metrics/field_trial_unittest.cc
index 22313e5..2699806 100644
--- a/base/metrics/field_trial_unittest.cc
+++ b/base/metrics/field_trial_unittest.cc
@@ -338,43 +338,6 @@
EXPECT_TRUE(FieldTrialList::IsTrialActive(kTrialName));
}
-TEST_F(FieldTrialTest, Save) {
- std::string save_string;
-
- scoped_refptr<FieldTrial> trial =
- CreateFieldTrial("Some name", 10, "Default some name");
- // There is no winner yet, so no textual group name is associated with trial.
- // In this case, the trial should not be included.
- EXPECT_EQ("", trial->group_name_internal());
- FieldTrialList::StatesToString(&save_string);
- EXPECT_EQ("", save_string);
- save_string.clear();
-
- // Create a winning group.
- trial->AppendGroup("Winner", 10);
- trial->Activate();
- FieldTrialList::StatesToString(&save_string);
- EXPECT_EQ("Some name/Winner/", save_string);
- save_string.clear();
-
- // Create a second trial and winning group.
- scoped_refptr<FieldTrial> trial2 = CreateFieldTrial("xxx", 10, "Default xxx");
- trial2->AppendGroup("yyyy", 10);
- trial2->Activate();
-
- FieldTrialList::StatesToString(&save_string);
- // We assume names are alphabetized... though this is not critical.
- EXPECT_EQ("Some name/Winner/xxx/yyyy/", save_string);
- save_string.clear();
-
- // Create a third trial with only the default group.
- scoped_refptr<FieldTrial> trial3 = CreateFieldTrial("zzz", 10, "default");
- trial3->Activate();
-
- FieldTrialList::StatesToString(&save_string);
- EXPECT_EQ("Some name/Winner/xxx/yyyy/zzz/default/", save_string);
-}
-
TEST_F(FieldTrialTest, SaveAll) {
std::string save_string;
@@ -459,8 +422,9 @@
trial->AppendGroup("Winner", 10);
trial->Activate();
std::string save_string;
- FieldTrialList::StatesToString(&save_string);
- EXPECT_EQ("Some name/Winner/", save_string);
+ FieldTrialList::AllStatesToString(&save_string);
+ // * prefix since it is activated.
+ EXPECT_EQ("*Some name/Winner/", save_string);
// It is OK if we redundantly specify a winner.
EXPECT_TRUE(FieldTrialList::CreateTrialsFromString(save_string));
@@ -854,9 +818,9 @@
FieldTrialList::GetActiveFieldTrialGroups(&active_groups);
EXPECT_TRUE(active_groups.empty());
- // The trial shouldn't be listed in the |StatesToString()| result.
+ // The trial shouldn't be listed in the |AllStatesToString()| result.
std::string states;
- FieldTrialList::StatesToString(&states);
+ FieldTrialList::AllStatesToString(&states);
EXPECT_TRUE(states.empty());
}
}
diff --git a/base/metrics/statistics_recorder.h b/base/metrics/statistics_recorder.h
index 62b5fc0..687e5fe 100644
--- a/base/metrics/statistics_recorder.h
+++ b/base/metrics/statistics_recorder.h
@@ -20,7 +20,7 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/gtest_prod_util.h"
#include "base/lazy_instance.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/metrics/statistics_recorder_unittest.cc b/base/metrics/statistics_recorder_unittest.cc
index 6a01878..9887829 100644
--- a/base/metrics/statistics_recorder_unittest.cc
+++ b/base/metrics/statistics_recorder_unittest.cc
@@ -10,7 +10,7 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/memory/weak_ptr.h"
diff --git a/base/metrics/user_metrics.cc b/base/metrics/user_metrics.cc
index ce4f834..cb55bfc 100644
--- a/base/metrics/user_metrics.cc
+++ b/base/metrics/user_metrics.cc
@@ -8,7 +8,7 @@
#include <vector>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/ranges/algorithm.h"
diff --git a/base/metrics/user_metrics.h b/base/metrics/user_metrics.h
index c6f5039..8181559 100644
--- a/base/metrics/user_metrics.h
+++ b/base/metrics/user_metrics.h
@@ -8,7 +8,7 @@
#include <string>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/metrics/user_metrics_action.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/no_destructor_unittest.cc b/base/no_destructor_unittest.cc
index 637e652..9dc2152 100644
--- a/base/no_destructor_unittest.cc
+++ b/base/no_destructor_unittest.cc
@@ -11,8 +11,8 @@
#include "base/atomicops.h"
#include "base/barrier_closure.h"
-#include "base/bind.h"
#include "base/check.h"
+#include "base/functional/bind.h"
#include "base/system/sys_info.h"
#include "base/threading/platform_thread.h"
#include "base/threading/simple_thread.h"
diff --git a/base/notreached.h b/base/notreached.h
index 23d2b5e..07f9d7d 100644
--- a/base/notreached.h
+++ b/base/notreached.h
@@ -12,7 +12,15 @@
namespace logging {
-// Under these conditions NOTREACHED() will effectively either log or DCHECK.
+// On DCHECK builds NOTREACHED() match the fatality of DCHECKs. When DCHECKs are
+// non-FATAL a crash report will be generated for the first NOTREACHED() that
+// hits per process.
+//
+// Outside DCHECK builds NOTREACHED() will LOG(ERROR) and also upload a crash
+// report without crashing in order to weed out prevalent NOTREACHED()s in the
+// wild before always turning NOTREACHED()s FATAL.
+//
+// TODO(crbug.com/851128): Turn NOTREACHED() FATAL and mark them [[noreturn]].
#if CHECK_WILL_STREAM()
#define NOTREACHED() \
CHECK_FUNCTION_IMPL( \
diff --git a/base/numerics/safe_conversions.h b/base/numerics/safe_conversions.h
index ea5d1a4..2fc2009 100644
--- a/base/numerics/safe_conversions.h
+++ b/base/numerics/safe_conversions.h
@@ -20,10 +20,6 @@
#define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0)
#endif
-#if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS
-#include <ostream>
-#endif
-
namespace base {
namespace internal {
diff --git a/base/observer_list.h b/base/observer_list.h
index 6cbdec1..ae1acac 100644
--- a/base/observer_list.h
+++ b/base/observer_list.h
@@ -22,6 +22,7 @@
#include "base/observer_list_internal.h"
#include "base/ranges/algorithm.h"
#include "base/sequence_checker.h"
+#include "build/build_config.h"
///////////////////////////////////////////////////////////////////////////////
//
@@ -341,6 +342,9 @@
std::string GetObserversCreationStackString() const {
#if DCHECK_IS_ON()
std::string result;
+#if BUILDFLAG(IS_IOS)
+ result += "Use go/observer-list-empty to interpret.\n";
+#endif
for (const auto& observer : observers_) {
result += observer.GetCreationStackString();
result += "\n";
diff --git a/base/observer_list_threadsafe.h b/base/observer_list_threadsafe.h
index 9bc7ba0..98d53a4 100644
--- a/base/observer_list_threadsafe.h
+++ b/base/observer_list_threadsafe.h
@@ -9,7 +9,6 @@
#include <utility>
#include "base/base_export.h"
-#include "base/bind.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/containers/contains.h"
diff --git a/base/observer_list_threadsafe_unittest.cc b/base/observer_list_threadsafe_unittest.cc
index e573e28..9514546 100644
--- a/base/observer_list_threadsafe_unittest.cc
+++ b/base/observer_list_threadsafe_unittest.cc
@@ -7,8 +7,8 @@
#include <memory>
#include <vector>
-#include "base/bind.h"
#include "base/compiler_specific.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/one_shot_event.cc b/base/one_shot_event.cc
index 132a079..051d63a 100644
--- a/base/one_shot_event.cc
+++ b/base/one_shot_event.cc
@@ -7,7 +7,7 @@
#include <stddef.h>
#include <utility>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_runner.h"
diff --git a/base/one_shot_event.h b/base/one_shot_event.h
index 43330d4..2c5753a 100644
--- a/base/one_shot_event.h
+++ b/base/one_shot_event.h
@@ -8,8 +8,8 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback_forward.h"
#include "base/check.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/weak_ptr.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_checker.h"
diff --git a/base/one_shot_event_unittest.cc b/base/one_shot_event_unittest.cc
index ea82adb..e187a91 100644
--- a/base/one_shot_event_unittest.cc
+++ b/base/one_shot_event_unittest.cc
@@ -4,7 +4,7 @@
#include "base/one_shot_event.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/path_service.cc b/base/path_service.cc
index e136bd1..ea626f0 100644
--- a/base/path_service.cc
+++ b/base/path_service.cc
@@ -11,6 +11,7 @@
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/synchronization/lock.h"
#include "build/build_config.h"
@@ -47,7 +48,9 @@
// providers claim overlapping keys.
struct Provider {
PathService::ProviderFunc func;
- struct Provider* next;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #reinterpret-cast-trivial-type, #global-scope
+ RAW_PTR_EXCLUSION struct Provider* next;
#ifndef NDEBUG
int key_start;
int key_end;
diff --git a/base/pending_task.h b/base/pending_task.h
index 1df5474..aa95a6b 100644
--- a/base/pending_task.h
+++ b/base/pending_task.h
@@ -8,7 +8,7 @@
#include <array>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/task/delay_policy.h"
#include "base/time/time.h"
diff --git a/base/posix/unix_domain_socket_unittest.cc b/base/posix/unix_domain_socket_unittest.cc
index 7af2215..9f716e1 100644
--- a/base/posix/unix_domain_socket_unittest.cc
+++ b/base/posix/unix_domain_socket_unittest.cc
@@ -10,10 +10,10 @@
#include <sys/types.h>
#include <unistd.h>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/pickle.h"
#include "base/posix/unix_domain_socket.h"
diff --git a/base/power_monitor/battery_level_provider.h b/base/power_monitor/battery_level_provider.h
index 9ce92a4..7c5f969 100644
--- a/base/power_monitor/battery_level_provider.h
+++ b/base/power_monitor/battery_level_provider.h
@@ -9,7 +9,7 @@
#include <memory>
#include <vector>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
diff --git a/base/power_monitor/iopm_power_source_sampling_event_source.h b/base/power_monitor/iopm_power_source_sampling_event_source.h
index 037d7b0..691d9b5 100644
--- a/base/power_monitor/iopm_power_source_sampling_event_source.h
+++ b/base/power_monitor/iopm_power_source_sampling_event_source.h
@@ -6,7 +6,7 @@
#define BASE_POWER_MONITOR_IOPM_POWER_SOURCE_SAMPLING_EVENT_SOURCE_H_
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/mac/scoped_ionotificationportref.h"
#include "base/mac/scoped_ioobject.h"
#include "base/power_monitor/sampling_event_source.h"
diff --git a/base/power_monitor/sampling_event_source.h b/base/power_monitor/sampling_event_source.h
index f4114ed..8cee81c 100644
--- a/base/power_monitor/sampling_event_source.h
+++ b/base/power_monitor/sampling_event_source.h
@@ -6,7 +6,7 @@
#define BASE_POWER_MONITOR_SAMPLING_EVENT_SOURCE_H_
#include "base/base_export.h"
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
namespace base {
diff --git a/base/process/kill.cc b/base/process/kill.cc
index 6f771d8..bbee81a 100644
--- a/base/process/kill.cc
+++ b/base/process/kill.cc
@@ -4,7 +4,7 @@
#include "base/process/kill.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/process/process_iterator.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
diff --git a/base/process/memory_unittest.cc b/base/process/memory_unittest.cc
index 2e14658..6c8a0fd 100644
--- a/base/process/memory_unittest.cc
+++ b/base/process/memory_unittest.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 "base/memory/raw_ptr_exclusion.h"
+
#define _CRT_SECURE_NO_WARNINGS
#include "base/process/memory.h"
@@ -149,7 +151,9 @@
signed_test_size_(std::numeric_limits<ssize_t>::max()) {}
protected:
- void* value_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #addr-of
+ RAW_PTR_EXCLUSION void* value_;
size_t test_size_;
size_t insecure_test_size_;
ssize_t signed_test_size_;
diff --git a/base/process/process_linux.cc b/base/process/process_linux.cc
index 5b98893..258061c 100644
--- a/base/process/process_linux.cc
+++ b/base/process/process_linux.cc
@@ -26,10 +26,10 @@
#include "build/chromeos_buildflags.h"
#if BUILDFLAG(IS_CHROMEOS)
-#include "base/bind.h"
#include "base/feature_list.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
+#include "base/functional/bind.h"
#include "base/process/process_handle.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
diff --git a/base/process/process_metrics.cc b/base/process/process_metrics.cc
index 29d6083..1b88164 100644
--- a/base/process/process_metrics.cc
+++ b/base/process/process_metrics.cc
@@ -69,23 +69,22 @@
return system_metrics;
}
-Value SystemMetrics::ToValue() const {
- Value res(Value::Type::DICTIONARY);
+Value::Dict SystemMetrics::ToDict() const {
+ Value::Dict res;
- res.SetIntKey("committed_memory", static_cast<int>(committed_memory_));
+ res.Set("committed_memory", static_cast<int>(committed_memory_));
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
- Value meminfo = memory_info_.ToValue();
- Value vmstat = vmstat_info_.ToValue();
- meminfo.MergeDictionary(&vmstat);
- res.SetKey("meminfo", std::move(meminfo));
- res.SetKey("diskinfo", disk_info_.ToValue());
+ Value::Dict meminfo = memory_info_.ToDict();
+ meminfo.Merge(vmstat_info_.ToDict());
+ res.Set("meminfo", std::move(meminfo));
+ res.Set("diskinfo", disk_info_.ToDict());
#endif
#if BUILDFLAG(IS_CHROMEOS)
- res.SetKey("swapinfo", swap_info_.ToValue());
- res.SetKey("gpu_meminfo", gpu_memory_info_.ToValue());
+ res.Set("swapinfo", swap_info_.ToDict());
+ res.Set("gpu_meminfo", gpu_memory_info_.ToDict());
#endif
#if BUILDFLAG(IS_WIN)
- res.SetKey("perfinfo", performance_.ToValue());
+ res.Set("perfinfo", performance_.ToDict());
#endif
return res;
diff --git a/base/process/process_metrics.h b/base/process/process_metrics.h
index 616ec4e..79d1238 100644
--- a/base/process/process_metrics.h
+++ b/base/process/process_metrics.h
@@ -19,6 +19,7 @@
#include "base/process/process_handle.h"
#include "base/strings/string_piece.h"
#include "base/time/time.h"
+#include "base/values.h"
#include "build/build_config.h"
#if BUILDFLAG(IS_APPLE)
@@ -46,8 +47,6 @@
namespace base {
-class Value;
-
// Full declaration is in process_metrics_iocounters.h.
struct IoCounters;
@@ -334,7 +333,7 @@
SystemMemoryInfoKB& operator=(const SystemMemoryInfoKB& other);
// Serializes the platform specific fields to value.
- Value ToValue() const;
+ Value::Dict ToDict() const;
int total = 0;
@@ -428,7 +427,7 @@
// Data from /proc/vmstat.
struct BASE_EXPORT VmStatInfo {
// Serializes the platform specific fields to value.
- Value ToValue() const;
+ Value::Dict ToDict() const;
uint64_t pswpin = 0;
uint64_t pswpout = 0;
@@ -452,7 +451,7 @@
SystemDiskInfo& operator=(const SystemDiskInfo&);
// Serializes the platform specific fields to value.
- Value ToValue() const;
+ Value::Dict ToDict() const;
uint64_t reads = 0;
uint64_t reads_merged = 0;
@@ -494,7 +493,7 @@
}
// Serializes the platform specific fields to value.
- Value ToValue() const;
+ Value::Dict ToDict() const;
uint64_t num_reads = 0;
uint64_t num_writes = 0;
@@ -523,7 +522,7 @@
// Data about GPU memory usage. These fields will be -1 if not supported.
struct BASE_EXPORT GraphicsMemoryInfoKB {
// Serializes the platform specific fields to value.
- Value ToValue() const;
+ Value::Dict ToDict() const;
int gpu_objects = -1;
int64_t gpu_memory_size = -1;
@@ -543,7 +542,7 @@
SystemPerformanceInfo& operator=(const SystemPerformanceInfo& other);
// Serializes the platform specific fields to value.
- Value ToValue() const;
+ Value::Dict ToDict() const;
// Total idle time of all processes in the system (units of 100 ns).
uint64_t idle_time = 0;
@@ -586,7 +585,7 @@
static SystemMetrics Sample();
// Serializes the system metrics to value.
- Value ToValue() const;
+ Value::Dict ToDict() const;
private:
FRIEND_TEST_ALL_PREFIXES(SystemMetricsTest, SystemMetrics);
diff --git a/base/process/process_metrics_linux.cc b/base/process/process_metrics_linux.cc
index 2275dbb..0536d6a 100644
--- a/base/process/process_metrics_linux.cc
+++ b/base/process/process_metrics_linux.cc
@@ -403,25 +403,25 @@
} // namespace
-Value SystemMemoryInfoKB::ToValue() const {
- Value res(Value::Type::DICTIONARY);
- res.SetIntKey("total", total);
- res.SetIntKey("free", free);
- res.SetIntKey("available", available);
- res.SetIntKey("buffers", buffers);
- res.SetIntKey("cached", cached);
- res.SetIntKey("active_anon", active_anon);
- res.SetIntKey("inactive_anon", inactive_anon);
- res.SetIntKey("active_file", active_file);
- res.SetIntKey("inactive_file", inactive_file);
- res.SetIntKey("swap_total", swap_total);
- res.SetIntKey("swap_free", swap_free);
- res.SetIntKey("swap_used", swap_total - swap_free);
- res.SetIntKey("dirty", dirty);
- res.SetIntKey("reclaimable", reclaimable);
+Value::Dict SystemMemoryInfoKB::ToDict() const {
+ Value::Dict res;
+ res.Set("total", total);
+ res.Set("free", free);
+ res.Set("available", available);
+ res.Set("buffers", buffers);
+ res.Set("cached", cached);
+ res.Set("active_anon", active_anon);
+ res.Set("inactive_anon", inactive_anon);
+ res.Set("active_file", active_file);
+ res.Set("inactive_file", inactive_file);
+ res.Set("swap_total", swap_total);
+ res.Set("swap_free", swap_free);
+ res.Set("swap_used", swap_total - swap_free);
+ res.Set("dirty", dirty);
+ res.Set("reclaimable", reclaimable);
#if BUILDFLAG(IS_CHROMEOS)
- res.SetIntKey("shmem", shmem);
- res.SetIntKey("slab", slab);
+ res.Set("shmem", shmem);
+ res.Set("slab", slab);
#endif
return res;
@@ -571,13 +571,13 @@
return true;
}
-Value VmStatInfo::ToValue() const {
- Value res(Value::Type::DICTIONARY);
+Value::Dict VmStatInfo::ToDict() const {
+ Value::Dict res;
// TODO(crbug.com/1334256): Make base::Value able to hold uint64_t and remove
// casts below.
- res.SetIntKey("pswpin", static_cast<int>(pswpin));
- res.SetIntKey("pswpout", static_cast<int>(pswpout));
- res.SetIntKey("pgmajfault", static_cast<int>(pgmajfault));
+ res.Set("pswpin", static_cast<int>(pswpin));
+ res.Set("pswpout", static_cast<int>(pswpout));
+ res.Set("pgmajfault", static_cast<int>(pgmajfault));
return res;
}
@@ -616,22 +616,22 @@
SystemDiskInfo& SystemDiskInfo::operator=(const SystemDiskInfo&) = default;
-Value SystemDiskInfo::ToValue() const {
- Value res(Value::Type::DICTIONARY);
+Value::Dict SystemDiskInfo::ToDict() const {
+ Value::Dict res;
// Write out uint64_t variables as doubles.
// Note: this may discard some precision, but for JS there's no other option.
- res.SetDoubleKey("reads", static_cast<double>(reads));
- res.SetDoubleKey("reads_merged", static_cast<double>(reads_merged));
- res.SetDoubleKey("sectors_read", static_cast<double>(sectors_read));
- res.SetDoubleKey("read_time", static_cast<double>(read_time));
- res.SetDoubleKey("writes", static_cast<double>(writes));
- res.SetDoubleKey("writes_merged", static_cast<double>(writes_merged));
- res.SetDoubleKey("sectors_written", static_cast<double>(sectors_written));
- res.SetDoubleKey("write_time", static_cast<double>(write_time));
- res.SetDoubleKey("io", static_cast<double>(io));
- res.SetDoubleKey("io_time", static_cast<double>(io_time));
- res.SetDoubleKey("weighted_io_time", static_cast<double>(weighted_io_time));
+ res.Set("reads", static_cast<double>(reads));
+ res.Set("reads_merged", static_cast<double>(reads_merged));
+ res.Set("sectors_read", static_cast<double>(sectors_read));
+ res.Set("read_time", static_cast<double>(read_time));
+ res.Set("writes", static_cast<double>(writes));
+ res.Set("writes_merged", static_cast<double>(writes_merged));
+ res.Set("sectors_written", static_cast<double>(sectors_written));
+ res.Set("write_time", static_cast<double>(write_time));
+ res.Set("io", static_cast<double>(io));
+ res.Set("io_time", static_cast<double>(io_time));
+ res.Set("weighted_io_time", static_cast<double>(weighted_io_time));
return res;
}
@@ -745,29 +745,29 @@
}
#if BUILDFLAG(IS_CHROMEOS)
-Value SwapInfo::ToValue() const {
- Value res(Value::Type::DICTIONARY);
+Value::Dict SwapInfo::ToDict() const {
+ Value::Dict res;
// Write out uint64_t variables as doubles.
// Note: this may discard some precision, but for JS there's no other option.
- res.SetDoubleKey("num_reads", static_cast<double>(num_reads));
- res.SetDoubleKey("num_writes", static_cast<double>(num_writes));
- res.SetDoubleKey("orig_data_size", static_cast<double>(orig_data_size));
- res.SetDoubleKey("compr_data_size", static_cast<double>(compr_data_size));
- res.SetDoubleKey("mem_used_total", static_cast<double>(mem_used_total));
+ res.Set("num_reads", static_cast<double>(num_reads));
+ res.Set("num_writes", static_cast<double>(num_writes));
+ res.Set("orig_data_size", static_cast<double>(orig_data_size));
+ res.Set("compr_data_size", static_cast<double>(compr_data_size));
+ res.Set("mem_used_total", static_cast<double>(mem_used_total));
double ratio = compr_data_size ? static_cast<double>(orig_data_size) /
static_cast<double>(compr_data_size)
: 0;
- res.SetDoubleKey("compression_ratio", ratio);
+ res.Set("compression_ratio", ratio);
return res;
}
-Value GraphicsMemoryInfoKB::ToValue() const {
- Value res(Value::Type::DICTIONARY);
+Value::Dict GraphicsMemoryInfoKB::ToDict() const {
+ Value::Dict res;
- res.SetIntKey("gpu_objects", gpu_objects);
- res.SetDoubleKey("gpu_memory_size", static_cast<double>(gpu_memory_size));
+ res.Set("gpu_objects", gpu_objects);
+ res.Set("gpu_memory_size", static_cast<double>(gpu_memory_size));
return res;
}
diff --git a/base/process/process_metrics_unittest.cc b/base/process/process_metrics_unittest.cc
index 9395e2d..19ea79a 100644
--- a/base/process/process_metrics_unittest.cc
+++ b/base/process/process_metrics_unittest.cc
@@ -12,11 +12,11 @@
#include <string>
#include <vector>
-#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
#include "base/memory/shared_memory_mapping.h"
#include "base/memory/writable_shared_memory_region.h"
#include "base/ranges/algorithm.h"
diff --git a/base/process/process_util_unittest.cc b/base/process/process_util_unittest.cc
index 3e4792c..dfb9ed5 100644
--- a/base/process/process_util_unittest.cc
+++ b/base/process/process_util_unittest.cc
@@ -10,7 +10,6 @@
#include <limits>
#include <tuple>
-#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/alias.h"
#include "base/debug/stack_trace.h"
@@ -18,6 +17,7 @@
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
+#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
diff --git a/base/profiler/libunwindstack_unwinder_android_unittest.cc b/base/profiler/libunwindstack_unwinder_android_unittest.cc
index 36291ac..76eaeed 100644
--- a/base/profiler/libunwindstack_unwinder_android_unittest.cc
+++ b/base/profiler/libunwindstack_unwinder_android_unittest.cc
@@ -11,7 +11,7 @@
#include <vector>
#include "base/android/build_info.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/profiler/register_context.h"
#include "base/profiler/stack_buffer.h"
#include "base/profiler/stack_copier_signal.h"
diff --git a/base/profiler/module_cache_unittest.cc b/base/profiler/module_cache_unittest.cc
index ea99ec6..fd4c9fa 100644
--- a/base/profiler/module_cache_unittest.cc
+++ b/base/profiler/module_cache_unittest.cc
@@ -8,9 +8,9 @@
#include <utility>
#include <vector>
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/containers/adapters.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/profiler/module_cache.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_piece.h"
diff --git a/base/profiler/native_unwinder_android_unittest.cc b/base/profiler/native_unwinder_android_unittest.cc
index 06054e4..f96b9bd 100644
--- a/base/profiler/native_unwinder_android_unittest.cc
+++ b/base/profiler/native_unwinder_android_unittest.cc
@@ -15,7 +15,7 @@
#include "base/android/build_info.h"
#include "base/android/jni_android.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/profiler/register_context.h"
#include "base/profiler/stack_buffer.h"
#include "base/profiler/stack_copier_signal.h"
diff --git a/base/profiler/stack_sampler.h b/base/profiler/stack_sampler.h
index b9a5ae8..9622453 100644
--- a/base/profiler/stack_sampler.h
+++ b/base/profiler/stack_sampler.h
@@ -9,8 +9,8 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/containers/circular_deque.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/profiler/frame.h"
#include "base/profiler/register_context.h"
diff --git a/base/profiler/stack_sampler_posix.cc b/base/profiler/stack_sampler_posix.cc
index 0d032b5..2df66ef 100644
--- a/base/profiler/stack_sampler_posix.cc
+++ b/base/profiler/stack_sampler_posix.cc
@@ -13,8 +13,8 @@
#include "build/build_config.h"
#if BUILDFLAG(IS_CHROMEOS) && defined(ARCH_CPU_X86_64)
-#include "base/bind.h"
#include "base/check.h"
+#include "base/functional/bind.h"
#include "base/profiler/frame_pointer_unwinder.h"
#include "base/profiler/stack_copier_signal.h"
#include "base/profiler/thread_delegate_posix.h"
diff --git a/base/profiler/stack_sampler_unittest.cc b/base/profiler/stack_sampler_unittest.cc
index 8b10555..41d593f 100644
--- a/base/profiler/stack_sampler_unittest.cc
+++ b/base/profiler/stack_sampler_unittest.cc
@@ -9,7 +9,7 @@
#include <numeric>
#include <utility>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
diff --git a/base/profiler/stack_sampling_profiler.cc b/base/profiler/stack_sampling_profiler.cc
index 3d57031..9e54820 100644
--- a/base/profiler/stack_sampling_profiler.cc
+++ b/base/profiler/stack_sampling_profiler.cc
@@ -11,9 +11,9 @@
#include "base/atomic_sequence_num.h"
#include "base/atomicops.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
@@ -765,7 +765,11 @@
#if (BUILDFLAG(IS_WIN) && defined(ARCH_CPU_X86_64)) || BUILDFLAG(IS_MAC) || \
(BUILDFLAG(IS_IOS) && defined(ARCH_CPU_64_BITS)) || \
(BUILDFLAG(IS_ANDROID) && \
- (BUILDFLAG(ENABLE_ARM_CFI_TABLE) || defined(ARCH_CPU_ARM64)))
+ ((defined(ARCH_CPU_ARMEL) && BUILDFLAG(ENABLE_ARM_CFI_TABLE)) || \
+ (defined(ARCH_CPU_ARM64) && \
+ BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)))) || \
+ (BUILDFLAG(IS_CHROMEOS) && defined(ARCH_CPU_X86_64) && \
+ BUILDFLAG(IS_CHROMEOS_DEVICE))
#if BUILDFLAG(IS_WIN)
// Do not start the profiler when Application Verifier is in use; running them
// simultaneously can cause crashes and has no known use case.
diff --git a/base/profiler/stack_sampling_profiler.h b/base/profiler/stack_sampling_profiler.h
index df9b426..0a98dba 100644
--- a/base/profiler/stack_sampling_profiler.h
+++ b/base/profiler/stack_sampling_profiler.h
@@ -9,7 +9,7 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/profiler/profile_builder.h"
#include "base/profiler/sampling_profiler_thread_token.h"
#include "base/synchronization/waitable_event.h"
diff --git a/base/profiler/stack_sampling_profiler_test_util.cc b/base/profiler/stack_sampling_profiler_test_util.cc
index 453a549..78730d2 100644
--- a/base/profiler/stack_sampling_profiler_test_util.cc
+++ b/base/profiler/stack_sampling_profiler_test_util.cc
@@ -7,8 +7,8 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/path_service.h"
#include "base/profiler/profiler_buildflags.h"
diff --git a/base/profiler/stack_sampling_profiler_test_util.h b/base/profiler/stack_sampling_profiler_test_util.h
index 4a8d6c6..3eff977 100644
--- a/base/profiler/stack_sampling_profiler_test_util.h
+++ b/base/profiler/stack_sampling_profiler_test_util.h
@@ -10,8 +10,9 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/native_library.h"
#include "base/profiler/frame.h"
#include "base/profiler/sampling_profiler_thread_token.h"
@@ -50,7 +51,9 @@
// Addresses near the start and end of a function.
struct FunctionAddressRange {
- const void* start;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #in-out-param-ref
+ RAW_PTR_EXCLUSION const void* start;
raw_ptr<const void> end;
};
diff --git a/base/profiler/stack_sampling_profiler_unittest.cc b/base/profiler/stack_sampling_profiler_unittest.cc
index 2663815..9d164fd 100644
--- a/base/profiler/stack_sampling_profiler_unittest.cc
+++ b/base/profiler/stack_sampling_profiler_unittest.cc
@@ -11,10 +11,10 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/profiler/unwinder.h b/base/profiler/unwinder.h
index e0061c2..107fcf4 100644
--- a/base/profiler/unwinder.h
+++ b/base/profiler/unwinder.h
@@ -8,6 +8,7 @@
#include <vector>
#include "base/base_export.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/profiler/frame.h"
#include "base/profiler/module_cache.h"
#include "base/profiler/register_context.h"
@@ -90,7 +91,9 @@
ModuleCache* module_cache() const { return module_cache_; }
private:
- ModuleCache* module_cache_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION ModuleCache* module_cache_ = nullptr;
};
} // namespace base
diff --git a/base/run_loop.cc b/base/run_loop.cc
index 83afb90..4ae85d5 100644
--- a/base/run_loop.cc
+++ b/base/run_loop.cc
@@ -4,10 +4,10 @@
#include "base/run_loop.h"
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/cancelable_callback.h"
#include "base/check.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/no_destructor.h"
#include "base/observer_list.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/run_loop.h b/base/run_loop.h
index 2a7e8ae..b46827b 100644
--- a/base/run_loop.h
+++ b/base/run_loop.h
@@ -10,12 +10,13 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/containers/stack.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/callback.h"
#include "base/gtest_prod_util.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/sequence_checker.h"
@@ -299,7 +300,9 @@
// A cached reference of RunLoop::Delegate for the thread driven by this
// RunLoop for quick access without using TLS (also allows access to state
// from another sequence during Run(), ref. |sequence_checker_| below).
- Delegate* const delegate_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union, #global-scope
+ RAW_PTR_EXCLUSION Delegate* const delegate_;
const Type type_;
diff --git a/base/run_loop_unittest.cc b/base/run_loop_unittest.cc
index 93fd5fb..dc72d22 100644
--- a/base/run_loop_unittest.cc
+++ b/base/run_loop_unittest.cc
@@ -8,9 +8,9 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/containers/queue.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
diff --git a/base/sampling_heap_profiler/poisson_allocation_sampler.cc b/base/sampling_heap_profiler/poisson_allocation_sampler.cc
index a8c0fcf..e96a91d 100644
--- a/base/sampling_heap_profiler/poisson_allocation_sampler.cc
+++ b/base/sampling_heap_profiler/poisson_allocation_sampler.cc
@@ -19,6 +19,7 @@
#include "base/rand_util.h"
#include "base/ranges/algorithm.h"
#include "build/build_config.h"
+#include "third_party/abseil-cpp/absl/base/attributes.h"
namespace base {
@@ -33,27 +34,12 @@
// Controls if sample intervals should not be randomized. Used for testing.
bool g_deterministic = false;
-// Controls if hooked samples should be ignored. Used for testing.
-std::atomic_bool g_mute_hooked_samples{false};
-
-// A positive value if profiling is running, otherwise it's zero.
-std::atomic_bool g_running{false};
-
// Pointer to the current |LockFreeAddressHashSet|.
std::atomic<LockFreeAddressHashSet*> g_sampled_addresses_set{nullptr};
// Sampling interval parameter, the mean value for intervals between samples.
std::atomic_size_t g_sampling_interval{kDefaultSamplingIntervalBytes};
-void (*g_hooks_install_callback)() = nullptr;
-
-// This will be true if *either* InstallAllocatorHooksOnce or
-// SetHooksInstallerCallback has run. `g_hooks_install_callback` should be
-// invoked when *both* have run, so each of them checks the value and, if it is
-// true, knows that the other function has already run so it's time to invoke
-// the callback.
-std::atomic_bool g_hooks_installed{false};
-
struct ThreadLocalData {
// Accumulated bytes towards sample.
intptr_t accumulated_bytes = 0;
@@ -169,19 +155,7 @@
PoissonAllocationSampler::ScopedMuteHookedSamplesForTesting::
ScopedMuteHookedSamplesForTesting() {
- DCHECK(!g_mute_hooked_samples);
- g_mute_hooked_samples = true;
-
- // `g_hooks_install_callback` can't be used with
- // ScopedMuteHookedSamplesForTesting because there's no way to remove it.
- DCHECK(!g_hooks_install_callback);
-
- // Make sure hooks have been installed, so that the only order of operations
- // that needs to be handled is Install Hooks -> Remove Hooks For Testing ->
- // Reinstall Hooks.
- PoissonAllocationSampler::Get()->InstallAllocatorHooksOnce();
-
- allocator::dispatcher::RemoveStandardAllocatorHooksForTesting(); // IN-TEST
+ SetProfilingStateFlag(ProfilingStateFlag::kHookedSamplesMutedForTesting);
// Reset the accumulated bytes to 0 on this thread.
ThreadLocalData* const thread_local_data = GetThreadLocalData();
@@ -191,18 +165,19 @@
PoissonAllocationSampler::ScopedMuteHookedSamplesForTesting::
~ScopedMuteHookedSamplesForTesting() {
- DCHECK(g_mute_hooked_samples);
- // Restore the allocator hooks and accumulated bytes.
+ // Restore the accumulated bytes.
ThreadLocalData* const thread_local_data = GetThreadLocalData();
thread_local_data->accumulated_bytes = accumulated_bytes_snapshot_;
-
- allocator::dispatcher::InstallStandardAllocatorHooks();
-
- g_mute_hooked_samples = false;
+ ResetProfilingStateFlag(ProfilingStateFlag::kHookedSamplesMutedForTesting);
}
+// static
PoissonAllocationSampler* PoissonAllocationSampler::instance_ = nullptr;
+// static
+ABSL_CONST_INIT std::atomic<PoissonAllocationSampler::ProfilingStateFlagMask>
+ PoissonAllocationSampler::profiling_state_{0};
+
PoissonAllocationSampler::PoissonAllocationSampler() {
CHECK_EQ(nullptr, instance_);
instance_ = this;
@@ -214,6 +189,15 @@
// static
void PoissonAllocationSampler::Init() {
[[maybe_unused]] static bool init_once = []() {
+ // Install the allocator hooks immediately, to better match the behaviour
+ // of base::allocator::Initializer.
+ //
+ // TODO(crbug/1137393): Use base::allocator::Initializer to install the
+ // PoissonAllocationSampler hooks. All observers need to be passed to the
+ // initializer at the same time so this will install the hooks even earlier
+ // in process startup.
+ allocator::dispatcher::InstallStandardAllocatorHooks();
+
// Touch thread local data on initialization to enforce proper setup of
// underlying storage system.
GetThreadLocalData();
@@ -222,44 +206,6 @@
}();
}
-void PoissonAllocationSampler::InstallAllocatorHooksOnce() {
- [[maybe_unused]] static bool hook_installed = [] {
- allocator::dispatcher::InstallStandardAllocatorHooks();
-
- bool expected = false;
- if (!g_hooks_installed.compare_exchange_strong(expected, true)) {
- // SetHooksInstallCallback already ran, so run the callback now.
- g_hooks_install_callback();
- }
- // The allocator hooks use `g_sampled_address_set` so it had better be
- // initialized.
- DCHECK(g_sampled_addresses_set.load(std::memory_order_acquire));
- return true;
- }();
-}
-
-// static
-void PoissonAllocationSampler::SetHooksInstallCallback(
- void (*hooks_install_callback)()) {
- // `g_hooks_install_callback` can't be used with
- // ScopedMuteHookedSamplesForTesting because there's no way to remove it.
- DCHECK(!g_mute_hooked_samples);
-
- CHECK(!g_hooks_install_callback && hooks_install_callback);
- g_hooks_install_callback = hooks_install_callback;
-
- bool expected = false;
- if (!g_hooks_installed.compare_exchange_strong(expected, true)) {
- // InstallAllocatorHooksOnce already ran, so run the callback now.
- g_hooks_install_callback();
- }
-}
-
-// static
-bool PoissonAllocationSampler::AreHookedSamplesMuted() {
- return g_mute_hooked_samples;
-}
-
void PoissonAllocationSampler::SetSamplingInterval(
size_t sampling_interval_bytes) {
// TODO(alph): Reset the sample being collected if running.
@@ -272,8 +218,9 @@
// static
size_t PoissonAllocationSampler::GetNextSampleInterval(size_t interval) {
- if (UNLIKELY(g_deterministic))
+ if (UNLIKELY(g_deterministic)) {
return interval;
+ }
// We sample with a Poisson process, with constant average sampling
// interval. This follows the exponential probability distribution with
@@ -290,10 +237,12 @@
// huge gaps in the sampling stream. Probability of the upper bound gets hit
// is exp(-20) ~ 2e-9, so it should not skew the distribution.
size_t max_value = interval * 20;
- if (UNLIKELY(value < min_value))
+ if (UNLIKELY(value < min_value)) {
return min_value;
- if (UNLIKELY(value > max_value))
+ }
+ if (UNLIKELY(value > max_value)) {
return max_value;
+ }
return static_cast<size_t>(value);
}
@@ -303,17 +252,39 @@
size_t size,
base::allocator::dispatcher::AllocationSubsystem type,
const char* context) {
+ // The allocation hooks may be installed before the sampler is started. Check
+ // if its ever been started first to avoid extra work on the fast path,
+ // because it's the most common case.
+ const ProfilingStateFlagMask state =
+ profiling_state_.load(std::memory_order_relaxed);
+ if (LIKELY(!(state & ProfilingStateFlag::kWasStarted))) {
+ return;
+ }
+
+ // When sampling is muted for testing, only handle manual calls to
+ // RecordAlloc. (This doesn't need to be checked in RecordFree because muted
+ // allocations won't be added to sampled_addresses_set(), so RecordFree
+ // already skips them.)
+ if (UNLIKELY((state & ProfilingStateFlag::kHookedSamplesMutedForTesting) &&
+ type != base::allocator::dispatcher::AllocationSubsystem::
+ kManualForTesting)) {
+ return;
+ }
+
ThreadLocalData* const thread_local_data = GetThreadLocalData();
thread_local_data->accumulated_bytes += size;
intptr_t accumulated_bytes = thread_local_data->accumulated_bytes;
- if (LIKELY(accumulated_bytes < 0))
+ if (LIKELY(accumulated_bytes < 0)) {
return;
+ }
- if (UNLIKELY(!g_running.load(std::memory_order_relaxed))) {
- // Sampling is in fact disabled. Reset the state of the sampler.
- // We do this check off the fast-path, because it's quite a rare state when
- // allocation hooks are installed but the sampler is not running.
+ if (UNLIKELY(!(state & ProfilingStateFlag::kIsRunning))) {
+ // Sampling was in fact disabled when the hook was called. Reset the state
+ // of the sampler. We do this check off the fast-path, because it's quite a
+ // rare state when the sampler is stopped after it's started. (The most
+ // common caller of PoissonAllocationSampler starts it and leaves it running
+ // for the rest of the Chrome session.)
thread_local_data->sampling_interval_initialized = false;
thread_local_data->accumulated_bytes = 0;
return;
@@ -329,8 +300,9 @@
base::allocator::dispatcher::AllocationSubsystem type,
const char* context) {
// Failed allocation? Skip the sample.
- if (UNLIKELY(!address))
+ if (UNLIKELY(!address)) {
return;
+ }
ThreadLocalData* const thread_local_data = GetThreadLocalData();
size_t mean_interval = g_sampling_interval.load(std::memory_order_relaxed);
@@ -360,8 +332,9 @@
thread_local_data->accumulated_bytes = accumulated_bytes;
- if (UNLIKELY(ScopedMuteThreadSamples::IsMuted()))
+ if (UNLIKELY(ScopedMuteThreadSamples::IsMuted())) {
return;
+ }
ScopedMuteThreadSamples no_reentrancy_scope;
std::vector<SamplesObserver*> observers_copy;
@@ -370,21 +343,24 @@
// TODO(alph): Sometimes RecordAlloc is called twice in a row without
// a RecordFree in between. Investigate it.
- if (sampled_addresses_set().Contains(address))
+ if (sampled_addresses_set().Contains(address)) {
return;
+ }
sampled_addresses_set().Insert(address);
BalanceAddressesHashSet();
observers_copy = observers_;
}
size_t total_allocated = mean_interval * samples;
- for (auto* observer : observers_copy)
+ for (auto* observer : observers_copy) {
observer->SampleAdded(address, size, total_allocated, type, context);
+ }
}
void PoissonAllocationSampler::DoRecordFree(void* address) {
- if (UNLIKELY(ScopedMuteThreadSamples::IsMuted()))
+ if (UNLIKELY(ScopedMuteThreadSamples::IsMuted())) {
return;
+ }
// There is a rare case on macOS and Android when the very first thread_local
// access in ScopedMuteThreadSamples constructor may allocate and
// thus reenter DoRecordAlloc. However the call chain won't build up further
@@ -396,8 +372,9 @@
observers_copy = observers_;
sampled_addresses_set().Remove(address);
}
- for (auto* observer : observers_copy)
+ for (auto* observer : observers_copy) {
observer->SampleRemoved(address);
+ }
}
void PoissonAllocationSampler::BalanceAddressesHashSet() {
@@ -409,8 +386,9 @@
// All the readers continue to use the old one until the atomic switch
// process takes place.
LockFreeAddressHashSet& current_set = sampled_addresses_set();
- if (current_set.load_factor() < 1)
+ if (current_set.load_factor() < 1) {
return;
+ }
auto new_set =
std::make_unique<LockFreeAddressHashSet>(current_set.buckets_count() * 2);
new_set->Copy(current_set);
@@ -432,6 +410,26 @@
return instance.get();
}
+// static
+void PoissonAllocationSampler::SetProfilingStateFlag(ProfilingStateFlag flag) {
+ ProfilingStateFlagMask flags = flag;
+ if (flag == ProfilingStateFlag::kIsRunning) {
+ flags |= ProfilingStateFlag::kWasStarted;
+ }
+ ProfilingStateFlagMask old_state =
+ profiling_state_.fetch_or(flags, std::memory_order_relaxed);
+ DCHECK(!(old_state & flag));
+}
+
+// static
+void PoissonAllocationSampler::ResetProfilingStateFlag(
+ ProfilingStateFlag flag) {
+ DCHECK_NE(flag, kWasStarted);
+ ProfilingStateFlagMask old_state =
+ profiling_state_.fetch_and(~flag, std::memory_order_relaxed);
+ DCHECK(old_state & flag);
+}
+
void PoissonAllocationSampler::AddSamplesObserver(SamplesObserver* observer) {
// The following implementation (including ScopedMuteThreadSamples) will use
// `thread_local`, which may cause a reentrancy issue. So, temporarily
@@ -441,9 +439,21 @@
ScopedMuteThreadSamples no_reentrancy_scope;
AutoLock lock(mutex_);
DCHECK(ranges::find(observers_, observer) == observers_.end());
+ bool profiler_was_stopped = observers_.empty();
observers_.push_back(observer);
- InstallAllocatorHooksOnce();
- g_running = !observers_.empty();
+
+ // Adding the observer will enable profiling. This will use
+ // `g_sampled_address_set` so it had better be initialized.
+ DCHECK(g_sampled_addresses_set.load(std::memory_order_relaxed));
+
+ // Start the profiler if this was the first observer. Setting/resetting
+ // kIsRunning isn't racy because it's performed based on `observers_.empty()`
+ // while holding `mutex_`.
+ if (profiler_was_stopped) {
+ SetProfilingStateFlag(ProfilingStateFlag::kIsRunning);
+ }
+ DCHECK(profiling_state_.load(std::memory_order_relaxed) &
+ ProfilingStateFlag::kIsRunning);
}
void PoissonAllocationSampler::RemoveSamplesObserver(
@@ -458,7 +468,15 @@
auto it = ranges::find(observers_, observer);
DCHECK(it != observers_.end());
observers_.erase(it);
- g_running = !observers_.empty();
+
+ // Stop the profiler if there are no more observers. Setting/resetting
+ // kIsRunning isn't racy because it's performed based on `observers_.empty()`
+ // while holding `mutex_`.
+ DCHECK(profiling_state_.load(std::memory_order_relaxed) &
+ ProfilingStateFlag::kIsRunning);
+ if (observers_.empty()) {
+ ResetProfilingStateFlag(ProfilingStateFlag::kIsRunning);
+ }
}
} // namespace base
diff --git a/base/sampling_heap_profiler/poisson_allocation_sampler.h b/base/sampling_heap_profiler/poisson_allocation_sampler.h
index 3a97657..02d5951 100644
--- a/base/sampling_heap_profiler/poisson_allocation_sampler.h
+++ b/base/sampling_heap_profiler/poisson_allocation_sampler.h
@@ -5,6 +5,7 @@
#ifndef BASE_SAMPLING_HEAP_PROFILER_POISSON_ALLOCATION_SAMPLER_H_
#define BASE_SAMPLING_HEAP_PROFILER_POISSON_ALLOCATION_SAMPLER_H_
+#include <atomic>
#include <vector>
#include "base/allocator/dispatcher/subsystem.h"
@@ -26,7 +27,6 @@
// This singleton class implements Poisson sampling of the incoming allocations
// stream. It hooks onto base::allocator and base::PartitionAlloc.
-// An extra custom allocator can be hooked via SetHooksInstallCallback method.
// The only control parameter is sampling interval that controls average value
// of the sampling intervals. The actual intervals between samples are
// randomized using Poisson distribution to mitigate patterns in the allocation
@@ -85,16 +85,6 @@
// reserves a TLS slot.
static void Init();
- // This is an entry point for plugging in an external allocator.
- // Profiler will invoke the provided callback upon initialization.
- // The callback should install hooks onto the corresponding memory allocator
- // and make them invoke PoissonAllocationSampler::RecordAlloc and
- // PoissonAllocationSampler::RecordFree upon corresponding allocation events.
- //
- // If the method is called after profiler is initialized, the callback
- // is invoked right away.
- static void SetHooksInstallCallback(void (*hooks_install_callback)());
-
void AddSamplesObserver(SamplesObserver*);
// Note: After an observer is removed it is still possible to receive
@@ -126,9 +116,27 @@
// Returns true if a ScopedMuteHookedSamplesForTesting exists. Only friends
// can create a ScopedMuteHookedSamplesForTesting but anyone can check the
// status of this. This can be read from any thread.
- static bool AreHookedSamplesMuted();
+ static bool AreHookedSamplesMuted() {
+ return profiling_state_.load(std::memory_order_relaxed) &
+ ProfilingStateFlag::kHookedSamplesMutedForTesting;
+ }
private:
+ // Flags recording the state of the profiler. This does not use enum class so
+ // flags can be used in a bitmask.
+ enum ProfilingStateFlag {
+ // Set if profiling has ever been started in this session of Chrome. Once
+ // this is set, it is never reset. This is used to optimize the common case
+ // where profiling is never used.
+ kWasStarted = 1 << 0,
+ // Set if profiling is currently running. This flag is toggled on and off
+ // as sample observers are added and removed.
+ kIsRunning = 1 << 1,
+ // Set if a ScopedMuteHookedSamplesForTesting object exists.
+ kHookedSamplesMutedForTesting = 1 << 2,
+ };
+ using ProfilingStateFlagMask = int;
+
// An instance of this class makes the sampler only report samples with
// AllocatorType kManualForTesting, not those from hooked allocators. This
// allows unit tests to set test expectations based on only explicit calls to
@@ -158,17 +166,25 @@
PoissonAllocationSampler();
~PoissonAllocationSampler() = delete;
- // Installs allocator hooks if they weren't already installed. This is not
- // static to ensure that allocator hooks can't be installed unless the
- // PoissonAllocationSampler singleton exists.
- void InstallAllocatorHooksOnce();
-
static size_t GetNextSampleInterval(size_t base_interval);
// Return the set of sampled addresses. This is only valid to call after
// Init().
static LockFreeAddressHashSet& sampled_addresses_set();
+ // Atomically adds `flag` to `profiling_state_`. DCHECK's if it was already
+ // set. If `flag` is kIsRunning, also sets kWasStarted. Uses
+ // std::memory_order_relaxed semantics and therefore doesn't synchronize the
+ // state of any other memory with future readers. (See the comment in
+ // RecordFree() for why this is safe.)
+ static void SetProfilingStateFlag(ProfilingStateFlag flag);
+
+ // Atomically removes `flag` from `profiling_state_`. DCHECK's if it was not
+ // already set. Uses std::memory_order_relaxed semantics and therefore doesn't
+ // synchronize the state of any other memory with future readers. (See the
+ // comment in RecordFree() for why this is safe.)
+ static void ResetProfilingStateFlag(ProfilingStateFlag flag);
+
void DoRecordAlloc(intptr_t accumulated_bytes,
size_t size,
void* address,
@@ -179,6 +195,7 @@
void BalanceAddressesHashSet();
Lock mutex_;
+
// The |observers_| list is guarded by |mutex_|, however a copy of it
// is made before invoking the observers (to avoid performing expensive
// operations under the lock) as such the SamplesObservers themselves need
@@ -188,8 +205,12 @@
static PoissonAllocationSampler* instance_;
+ // Fast, thread-safe access to the current profiling state.
+ static std::atomic<ProfilingStateFlagMask> profiling_state_;
+
friend class heap_profiling::HeapProfilerControllerTest;
friend class NoDestructor<PoissonAllocationSampler>;
+ friend class PoissonAllocationSamplerStateTest;
friend class SamplingHeapProfilerTest;
FRIEND_TEST_ALL_PREFIXES(PoissonAllocationSamplerTest, MuteHooksWithoutInit);
FRIEND_TEST_ALL_PREFIXES(SamplingHeapProfilerTest, HookedAllocatorMuted);
@@ -197,10 +218,64 @@
// static
ALWAYS_INLINE void PoissonAllocationSampler::RecordFree(void* address) {
- if (UNLIKELY(address == nullptr))
+ // The allocation hooks may be installed before the sampler is started. Check
+ // if its ever been started first to avoid extra work on the fast path,
+ // because it's the most common case. Note that DoRecordFree still needs to be
+ // called if the sampler was started but is now stopped, to track allocations
+ // that were recorded while the sampler was still running.
+ //
+ // Relaxed ordering is safe here because there's only one case where
+ // RecordAlloc and RecordFree MUST see the same value of `profiling_state_`.
+ // Assume thread A updates `profiling_state_` from 0 to kWasStarted |
+ // kIsRunning, thread B calls RecordAlloc, and thread C calls RecordFree.
+ // (Something else could update `profiling_state_` to remove kIsRunning before
+ // RecordAlloc or RecordFree.)
+ //
+ // 1. If RecordAlloc(p) sees !kWasStarted or !kIsRunning it will return
+ // immediately, so p won't be in sampled_address_set(). So no matter what
+ // RecordFree(p) sees it will also return immediately.
+ //
+ // 2. If RecordFree() is called with a pointer that was never passed to
+ // RecordAlloc(), again it will return immediately no matter what it sees.
+ //
+ // 3. If RecordAlloc(p) sees kIsRunning it will put p in
+ // sampled_address_set(). In this case RecordFree(p) MUST see !kWasStarted
+ // or it will return without removing p:
+ //
+ // 3a. If the program got p as the return value from malloc() and passed it
+ // to free(), then RecordFree() happens-after RecordAlloc() and
+ // therefore will see the same value of `profiling_state_` as
+ // RecordAlloc() for all memory orders. (Proof: using the definitions
+ // of sequenced-after, happens-after and inter-thread happens-after
+ // from https://en.cppreference.com/w/cpp/atomic/memory_order, malloc()
+ // calls RecordAlloc() so its return is sequenced-after RecordAlloc();
+ // free() inter-thread happens-after malloc's return because it
+ // consumes the result; RecordFree() is sequenced-after its caller,
+ // free(); therefore RecordFree() interthread happens-after
+ // RecordAlloc().)
+ // 3b. If the program is freeing a random pointer which coincidentally was
+ // also returned from malloc(), such that free(p) does not happen-after
+ // malloc(), then there is already an unavoidable race condition. If
+ // the profiler sees malloc() before free(p), then it will add p to
+ // sampled_addresses_set() and then remove it; otherwise it will do
+ // nothing in RecordFree() and add p to sampled_addresses_set() in
+ // RecordAlloc(), recording a potential leak. Reading
+ // `profiling_state_` with relaxed ordering adds another possibility:
+ // if the profiler sees malloc() with kWasStarted and then free without
+ // kWasStarted, it will add p to sampled_addresses_set() in
+ // RecordAlloc() and then do nothing in RecordFree(). This has the same
+ // outcome as the existing race.
+ const ProfilingStateFlagMask state =
+ profiling_state_.load(std::memory_order_relaxed);
+ if (LIKELY(!(state & ProfilingStateFlag::kWasStarted))) {
return;
- if (UNLIKELY(sampled_addresses_set().Contains(address)))
+ }
+ if (UNLIKELY(address == nullptr)) {
+ return;
+ }
+ if (UNLIKELY(sampled_addresses_set().Contains(address))) {
instance_->DoRecordFree(address);
+ }
}
} // namespace base
diff --git a/base/sampling_heap_profiler/poisson_allocation_sampler_unittest.cc b/base/sampling_heap_profiler/poisson_allocation_sampler_unittest.cc
index 0bb8cff..d9d2ca8 100644
--- a/base/sampling_heap_profiler/poisson_allocation_sampler_unittest.cc
+++ b/base/sampling_heap_profiler/poisson_allocation_sampler_unittest.cc
@@ -6,22 +6,347 @@
#include <stdlib.h>
+#include <array>
+#include <atomic>
+#include <bitset>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "base/barrier_closure.h"
+#include "base/containers/extend.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/memory/scoped_refptr.h"
+#include "base/run_loop.h"
+#include "base/task/bind_post_task.h"
+#include "base/task/single_thread_task_runner.h"
+#include "base/task/single_thread_task_runner_thread_mode.h"
+#include "base/task/thread_pool.h"
+#include "base/test/task_environment.h"
+#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
+namespace {
+
+using ::testing::AssertionFailure;
+using ::testing::AssertionResult;
+using ::testing::AssertionSuccess;
+
+class DummySamplesObserver : public PoissonAllocationSampler::SamplesObserver {
+ public:
+ void SampleAdded(void* address,
+ size_t size,
+ size_t total,
+ base::allocator::dispatcher::AllocationSubsystem type,
+ const char* context) final {}
+ void SampleRemoved(void* address) final {}
+};
+
+class AddRemoveObserversTester {
+ public:
+ AddRemoveObserversTester() = default;
+ ~AddRemoveObserversTester() = default;
+
+ // Posts tasks to add and remove observers to `task_runner_`. Invokes
+ // `barrier_closure` if a task fails or after `num_repetitions`.
+ void Start(base::RepeatingClosure* barrier_closure, int num_repetitions);
+
+ // Gives the caller ownership of the observers so that they can be safely
+ // deleted in single-threaded context once the PoissonAllocationSampler is not
+ // running.
+ std::vector<std::unique_ptr<DummySamplesObserver>> DetachObservers() {
+ std::vector<std::unique_ptr<DummySamplesObserver>> observers;
+ observers.push_back(std::move(observer1_));
+ observers.push_back(std::move(observer2_));
+ return observers;
+ }
+
+ private:
+ // Posts tasks to add and remove observers to `task_runner_`. If they fail or
+ // if this is the last repetition, invokes `barrier_closure`, otherwise
+ // schedules another repetition.
+ void TestAddRemoveObservers(base::RepeatingClosure* barrier_closure,
+ int remaining_repetitions);
+
+ // These observers must live until all threads are destroyed, because the
+ // profiler might call into them racily after they're removed. (See the
+ // comment on PoissonAllocationSampler::RemoveSamplesObserver().) They can
+ // safely be destroyed on the main thread after the test is back in a
+ // single-threaded context.
+ std::unique_ptr<DummySamplesObserver> observer1_ =
+ std::make_unique<DummySamplesObserver>();
+ std::unique_ptr<DummySamplesObserver> observer2_ =
+ std::make_unique<DummySamplesObserver>();
+
+ scoped_refptr<base::SequencedTaskRunner> task_runner_ =
+ base::ThreadPool::CreateSingleThreadTaskRunner(
+ {},
+ base::SingleThreadTaskRunnerThreadMode::DEDICATED);
+};
+
+class MuteHookedSamplesTester {
+ public:
+ MuteHookedSamplesTester() = default;
+ ~MuteHookedSamplesTester() = default;
+
+ // Posts tasks to mute and unmute samples to `task_runner_`. Invokes
+ // `barrier_closure` if a task fails or after `num_repetitions`.
+ void Start(base::RepeatingClosure* barrier_closure, int num_repetitions);
+
+ private:
+ // Posts tasks to mute and unmute samples to `task_runner_`. If they fail or
+ // if this is the last repetition, invokes `barrier_closure`, otherwise
+ // schedules another repetition.
+ void TestMuteUnmuteSamples(base::RepeatingClosure* barrier_closure,
+ int remaining_repetitions);
+
+ base::OnceClosure unmute_samples_closure_;
+
+ scoped_refptr<base::SequencedTaskRunner> task_runner_ =
+ base::ThreadPool::CreateSingleThreadTaskRunner(
+ {},
+ base::SingleThreadTaskRunnerThreadMode::DEDICATED);
+};
+
+} // namespace
+
+// PoissonAllocationSamplerStateTest has access to read the state of
+// PoissonAllocationSampler.
+class PoissonAllocationSamplerStateTest : public ::testing::Test {
+ public:
+ static void AddSamplesObservers(DummySamplesObserver* observer1,
+ DummySamplesObserver* observer2);
+
+ static void RemoveSamplesObservers(DummySamplesObserver* observer1,
+ DummySamplesObserver* observer2);
+
+ // Creates a ScopedMuteHookedSamplesForTesting object and returns a closure
+ // that will destroy it.
+ static base::OnceClosure MuteHookedSamples();
+
+ static void UnmuteHookedSamples(base::OnceClosure unmute_closure);
+
+ protected:
+ using ProfilingStateFlag = PoissonAllocationSampler::ProfilingStateFlag;
+ using ProfilingStateFlagMask =
+ PoissonAllocationSampler::ProfilingStateFlagMask;
+
+ static AssertionResult HasAllStateFlags(ProfilingStateFlagMask flags) {
+ const ProfilingStateFlagMask state =
+ PoissonAllocationSampler::profiling_state_.load(
+ std::memory_order_relaxed);
+ AssertionResult result =
+ (state & flags) == flags ? AssertionSuccess() : AssertionFailure();
+ return result << "Expected all of " << std::bitset<4>(flags) << ", got "
+ << std::bitset<4>(state);
+ }
+
+ static AssertionResult HasAnyStateFlags(ProfilingStateFlagMask flags) {
+ const ProfilingStateFlagMask state =
+ PoissonAllocationSampler::profiling_state_.load(
+ std::memory_order_relaxed);
+ AssertionResult result =
+ (state & flags) != 0 ? AssertionSuccess() : AssertionFailure();
+ return result << "Expected any of " << std::bitset<4>(flags) << ", got "
+ << std::bitset<4>(state);
+ }
+
+ // This must come before `task_environment_` do that it's deleted afterward,
+ // since DummySamplesObserver objects must be deleted in single-threaded
+ // context.
+ std::vector<std::unique_ptr<DummySamplesObserver>> observers_to_delete_;
+
+ base::test::TaskEnvironment task_environment_;
+};
+
+void AddRemoveObserversTester::Start(base::RepeatingClosure* barrier_closure,
+ int num_repetitions) {
+ // Unretained is safe because `this` isn't deleted until the
+ // `barrier_closure` is invoked often enough to quit the main RunLoop.
+ task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&AddRemoveObserversTester::TestAddRemoveObservers,
+ base::Unretained(this), barrier_closure, num_repetitions));
+}
+
+void AddRemoveObserversTester::TestAddRemoveObservers(
+ base::RepeatingClosure* barrier_closure,
+ int remaining_repetitions) {
+ if (!remaining_repetitions || ::testing::Test::HasFailure()) {
+ barrier_closure->Run();
+ return;
+ }
+ auto add_observers =
+ base::BindOnce(&PoissonAllocationSamplerStateTest::AddSamplesObservers,
+ observer1_.get(), observer2_.get());
+ auto remove_observers = base::BindPostTask(
+ task_runner_,
+ base::BindOnce(&PoissonAllocationSamplerStateTest::RemoveSamplesObservers,
+ observer1_.get(), observer2_.get()));
+ // Unretained is safe because `this` isn't deleted until the
+ // `barrier_closure` is invoked often enough to quit the main RunLoop.
+ auto next_repetition = base::BindPostTask(
+ task_runner_,
+ base::BindOnce(&AddRemoveObserversTester::TestAddRemoveObservers,
+ base::Unretained(this), barrier_closure,
+ remaining_repetitions - 1));
+ task_runner_->PostTask(FROM_HERE, std::move(add_observers)
+ .Then(std::move(remove_observers))
+ .Then(std::move(next_repetition)));
+}
+
+void MuteHookedSamplesTester::Start(base::RepeatingClosure* barrier_closure,
+ int num_repetitions) {
+ // Unretained is safe because `this` isn't deleted until the
+ // `barrier_closure` is invoked often enough to quit the main RunLoop.
+ task_runner_->PostTask(
+ FROM_HERE,
+ base::BindOnce(&MuteHookedSamplesTester::TestMuteUnmuteSamples,
+ base::Unretained(this), barrier_closure, num_repetitions));
+}
+
+void MuteHookedSamplesTester::TestMuteUnmuteSamples(
+ base::RepeatingClosure* barrier_closure,
+ int remaining_repetitions) {
+ if (!remaining_repetitions || ::testing::Test::HasFailure()) {
+ barrier_closure->Run();
+ return;
+ }
+ auto mute_samples =
+ base::BindOnce(&PoissonAllocationSamplerStateTest::MuteHookedSamples);
+ auto unmute_samples = base::BindPostTask(
+ task_runner_,
+ base::BindOnce(&PoissonAllocationSamplerStateTest::UnmuteHookedSamples));
+ // Unretained is safe because `this` isn't deleted until the
+ // `barrier_closure` is invoked often enough to quit the main RunLoop.
+ auto next_repetition = base::BindPostTask(
+ task_runner_,
+ base::BindOnce(&MuteHookedSamplesTester::TestMuteUnmuteSamples,
+ base::Unretained(this), barrier_closure,
+ remaining_repetitions - 1));
+ task_runner_->PostTask(FROM_HERE, std::move(mute_samples)
+ .Then(std::move(unmute_samples))
+ .Then(std::move(next_repetition)));
+}
+
+// static
+void PoissonAllocationSamplerStateTest::AddSamplesObservers(
+ DummySamplesObserver* observer1,
+ DummySamplesObserver* observer2) {
+ // The first observer should start the profiler running if it isn't already.
+ // The second should not change the state.
+ PoissonAllocationSampler::Get()->AddSamplesObserver(observer1);
+ EXPECT_TRUE(HasAllStateFlags(ProfilingStateFlag::kIsRunning |
+ ProfilingStateFlag::kWasStarted));
+ PoissonAllocationSampler::Get()->AddSamplesObserver(observer2);
+ EXPECT_TRUE(HasAllStateFlags(ProfilingStateFlag::kIsRunning |
+ ProfilingStateFlag::kWasStarted));
+}
+
+// static
+void PoissonAllocationSamplerStateTest::RemoveSamplesObservers(
+ DummySamplesObserver* observer1,
+ DummySamplesObserver* observer2) {
+ // Removing the first observer should leave the profiler running. Removing the
+ // second might leave it running, or might stop it. It should never remove the
+ // kWasStarted flag.
+ EXPECT_TRUE(HasAllStateFlags(ProfilingStateFlag::kIsRunning |
+ ProfilingStateFlag::kWasStarted));
+ PoissonAllocationSampler::Get()->RemoveSamplesObserver(observer1);
+ EXPECT_TRUE(HasAllStateFlags(ProfilingStateFlag::kIsRunning |
+ ProfilingStateFlag::kWasStarted));
+ PoissonAllocationSampler::Get()->RemoveSamplesObserver(observer2);
+ EXPECT_TRUE(HasAllStateFlags(ProfilingStateFlag::kWasStarted));
+}
+
+// static
+base::OnceClosure PoissonAllocationSamplerStateTest::MuteHookedSamples() {
+ using ScopedMuteHookedSamplesForTesting =
+ PoissonAllocationSampler::ScopedMuteHookedSamplesForTesting;
+ EXPECT_FALSE(
+ HasAllStateFlags(ProfilingStateFlag::kHookedSamplesMutedForTesting));
+ auto scoped_mute_hooked_samples =
+ std::make_unique<ScopedMuteHookedSamplesForTesting>();
+ EXPECT_TRUE(
+ HasAllStateFlags(ProfilingStateFlag::kHookedSamplesMutedForTesting));
+ auto unmute_closure = base::BindOnce(
+ [](std::unique_ptr<ScopedMuteHookedSamplesForTesting> p) { p.reset(); },
+ std::move(scoped_mute_hooked_samples));
+ return unmute_closure;
+}
+
+// static
+void PoissonAllocationSamplerStateTest::UnmuteHookedSamples(
+ base::OnceClosure unmute_closure) {
+ EXPECT_TRUE(
+ HasAllStateFlags(ProfilingStateFlag::kHookedSamplesMutedForTesting));
+ std::move(unmute_closure).Run();
+ EXPECT_FALSE(
+ HasAllStateFlags(ProfilingStateFlag::kHookedSamplesMutedForTesting));
+}
+
TEST(PoissonAllocationSamplerTest, MuteHooksWithoutInit) {
- // ScopedMuteHookedSamplesForTesting updates the allocator hooks. Make sure
- // is safe to call from tests that might not call
- // PoissonAllocationSampler::Get() to initialize the rest of the
- // PoissonAllocationSampler.
+ // Make sure it's safe to create a ScopedMuteHookedSamplesForTesting from
+ // tests that might not call PoissonAllocationSampler::Get() to initialize the
+ // rest of the PoissonAllocationSampler.
EXPECT_FALSE(PoissonAllocationSampler::AreHookedSamplesMuted());
void* volatile p = nullptr;
{
PoissonAllocationSampler::ScopedMuteHookedSamplesForTesting mute_hooks;
+ EXPECT_TRUE(PoissonAllocationSampler::AreHookedSamplesMuted());
p = malloc(10000);
}
+ EXPECT_FALSE(PoissonAllocationSampler::AreHookedSamplesMuted());
free(p);
}
+TEST_F(PoissonAllocationSamplerStateTest, UpdateProfilingState) {
+ constexpr int kNumObserverThreads = 100;
+ constexpr int kNumRepetitions = 100;
+
+ base::RunLoop run_loop;
+
+ // Quit the run loop once all AddRemoveObserversTesters and the
+ // MuteUnmuteSamplesTester signal that they're done.
+ auto barrier_closure =
+ base::BarrierClosure(kNumObserverThreads + 1, run_loop.QuitClosure());
+
+ // No observers or ScopedMuteHookedSamplesForTesting objects exist.
+ // The kWasStarted flag may or may not be set depending on whether other tests
+ // have changed the singleton state.
+ ASSERT_FALSE(
+ HasAnyStateFlags(ProfilingStateFlag::kIsRunning |
+ ProfilingStateFlag::kHookedSamplesMutedForTesting));
+
+ std::array<std::unique_ptr<AddRemoveObserversTester>, kNumObserverThreads>
+ observer_testers;
+ for (int i = 0; i < kNumObserverThreads; ++i) {
+ // Start a thread to add and remove observers, toggling the kIsRunning and
+ // kHookedSamplesMutedForTesting state flags.
+ observer_testers[i] = std::make_unique<AddRemoveObserversTester>();
+ observer_testers[i]->Start(&barrier_closure, kNumRepetitions);
+ }
+
+ // There can only be one ScopedMuteHookedSamplesForTesting object at a time so
+ // test them on only one thread.
+ MuteHookedSamplesTester mute_samples_tester;
+ mute_samples_tester.Start(&barrier_closure, kNumRepetitions);
+
+ run_loop.Run();
+
+ // No observers or ScopedMuteHookedSamplesForTesting objects exist again.
+ EXPECT_FALSE(
+ HasAnyStateFlags(ProfilingStateFlag::kIsRunning |
+ ProfilingStateFlag::kHookedSamplesMutedForTesting));
+
+ // Move the observers into `observers_to_delete_` to be destroyed during
+ // teardown, in single-threaded context.
+ for (int i = 0; i < kNumObserverThreads; ++i) {
+ base::Extend(observers_to_delete_, observer_testers[i]->DetachObservers());
+ }
+}
+
} // namespace base
diff --git a/base/sampling_heap_profiler/sampling_heap_profiler.cc b/base/sampling_heap_profiler/sampling_heap_profiler.cc
index 4acc2a3..8c7da26 100644
--- a/base/sampling_heap_profiler/sampling_heap_profiler.cc
+++ b/base/sampling_heap_profiler/sampling_heap_profiler.cc
@@ -10,10 +10,10 @@
#include "base/allocator/partition_allocator/partition_alloc.h"
#include "base/allocator/partition_allocator/shim/allocator_shim.h"
-#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/debug/stack_trace.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/no_destructor.h"
diff --git a/base/sequence_checker_unittest.cc b/base/sequence_checker_unittest.cc
index 4b01422..0141779 100644
--- a/base/sequence_checker_unittest.cc
+++ b/base/sequence_checker_unittest.cc
@@ -10,8 +10,8 @@
#include <string>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/sequence_token.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
diff --git a/base/strings/safe_sprintf.h b/base/strings/safe_sprintf.h
index 8e24a5a..ecdd8f0 100644
--- a/base/strings/safe_sprintf.h
+++ b/base/strings/safe_sprintf.h
@@ -9,6 +9,7 @@
#include <stdint.h>
#include <stdlib.h>
+#include "base/memory/raw_ptr_exclusion.h"
#include "build/build_config.h"
#if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
@@ -197,7 +198,9 @@
const char* str;
// A pointer to an arbitrary object.
- const void* ptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter
+ // for: #union
+ RAW_PTR_EXCLUSION const void* ptr;
};
const enum Type type;
};
diff --git a/base/substring_set_matcher/substring_set_matcher.h b/base/substring_set_matcher/substring_set_matcher.h
index ae45408..3dd00dc 100644
--- a/base/substring_set_matcher/substring_set_matcher.h
+++ b/base/substring_set_matcher/substring_set_matcher.h
@@ -14,6 +14,7 @@
#include "base/base_export.h"
#include "base/check_op.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/substring_set_matcher/matcher_string_pattern.h"
namespace base {
@@ -275,7 +276,9 @@
// Note that due to __attribute__((packed)) below, this pointer may be
// unaligned on 64-bit platforms, causing slightly less efficient
// access to it in some cases.
- AhoCorasickEdge* edges;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter
+ // for: #union
+ RAW_PTR_EXCLUSION AhoCorasickEdge* edges;
// Inline edge storage, used if edges_capacity_ == 0.
AhoCorasickEdge inline_edges[kNumInlineEdges];
diff --git a/base/synchronization/atomic_flag_unittest.cc b/base/synchronization/atomic_flag_unittest.cc
index 65b8268..b7dc132 100644
--- a/base/synchronization/atomic_flag_unittest.cc
+++ b/base/synchronization/atomic_flag_unittest.cc
@@ -4,8 +4,8 @@
#include "base/synchronization/atomic_flag.h"
-#include "base/bind.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/gtest_util.h"
diff --git a/base/synchronization/condition_variable_unittest.cc b/base/synchronization/condition_variable_unittest.cc
index fe7a082..cc2587d 100644
--- a/base/synchronization/condition_variable_unittest.cc
+++ b/base/synchronization/condition_variable_unittest.cc
@@ -12,7 +12,7 @@
#include <memory>
#include <vector>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/synchronization/lock.h"
diff --git a/base/synchronization/waitable_event.h b/base/synchronization/waitable_event.h
index d84604e..514bba9 100644
--- a/base/synchronization/waitable_event.h
+++ b/base/synchronization/waitable_event.h
@@ -19,7 +19,7 @@
#include <list>
#include <memory>
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
#include "base/mac/scoped_mach_port.h"
#include "base/memory/ref_counted.h"
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
diff --git a/base/synchronization/waitable_event_watcher.h b/base/synchronization/waitable_event_watcher.h
index da4b077..c69e35d 100644
--- a/base/synchronization/waitable_event_watcher.h
+++ b/base/synchronization/waitable_event_watcher.h
@@ -25,7 +25,7 @@
#endif
#if !BUILDFLAG(IS_WIN)
-#include "base/callback.h"
+#include "base/functional/callback.h"
#endif
namespace base {
diff --git a/base/synchronization/waitable_event_watcher_posix.cc b/base/synchronization/waitable_event_watcher_posix.cc
index b22f390..64f6518 100644
--- a/base/synchronization/waitable_event_watcher_posix.cc
+++ b/base/synchronization/waitable_event_watcher_posix.cc
@@ -6,8 +6,8 @@
#include <utility>
-#include "base/bind.h"
#include "base/check.h"
+#include "base/functional/bind.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
diff --git a/base/synchronization/waitable_event_watcher_unittest.cc b/base/synchronization/waitable_event_watcher_unittest.cc
index 17bc04a..1d85b72 100644
--- a/base/synchronization/waitable_event_watcher_unittest.cc
+++ b/base/synchronization/waitable_event_watcher_unittest.cc
@@ -4,8 +4,8 @@
#include "base/synchronization/waitable_event_watcher.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
diff --git a/base/system/sys_info.cc b/base/system/sys_info.cc
index c4e96dd..2c5bfc9 100644
--- a/base/system/sys_info.cc
+++ b/base/system/sys_info.cc
@@ -7,9 +7,9 @@
#include <algorithm>
#include "base/base_switches.h"
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/command_line.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/notreached.h"
#include "base/system/sys_info_internal.h"
diff --git a/base/system/sys_info.h b/base/system/sys_info.h
index e7ad457..4a803a1 100644
--- a/base/system/sys_info.h
+++ b/base/system/sys_info.h
@@ -12,7 +12,7 @@
#include <string>
#include "base/base_export.h"
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
#include "base/gtest_prod_util.h"
#include "base/time/time.h"
#include "build/build_config.h"
diff --git a/base/system/sys_info_posix.cc b/base/system/sys_info_posix.cc
index c9ad7a0..80c750b 100644
--- a/base/system/sys_info_posix.cc
+++ b/base/system/sys_info_posix.cc
@@ -67,13 +67,16 @@
if (HANDLE_EINTR(statfs(path.value().c_str(), &stats)) != 0)
return false;
- // In some platforms, |statfs_buf.f_type| is declared as signed, but some of
- // the values will overflow it, causing narrowing warnings. Cast to the
- // largest possible unsigned integer type to avoid it.
- switch (static_cast<uintmax_t>(stats.f_type)) {
+ // This static_cast is here because various libcs disagree about the size
+ // and signedness of statfs::f_type. In particular, glibc has it as either a
+ // signed long or a signed int depending on platform, and other libcs
+ // (following the statfs(2) man page) use unsigned int instead. To avoid
+ // either an unsigned -> signed cast, or a narrowing cast, we always upcast
+ // statfs::f_type to unsigned long. :(
+ switch (static_cast<unsigned long>(stats.f_type)) {
case TMPFS_MAGIC:
- case static_cast<int>(HUGETLBFS_MAGIC):
- case static_cast<int>(RAMFS_MAGIC):
+ case HUGETLBFS_MAGIC:
+ case RAMFS_MAGIC:
return true;
}
return false;
diff --git a/base/system/sys_info_unittest.cc b/base/system/sys_info_unittest.cc
index df2dca0..a0c96f7 100644
--- a/base/system/sys_info_unittest.cc
+++ b/base/system/sys_info_unittest.cc
@@ -7,9 +7,9 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
#include "base/environment.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
#include "base/numerics/safe_conversions.h"
#include "base/process/process_metrics.h"
#include "base/run_loop.h"
diff --git a/base/task/bind_post_task.h b/base/task/bind_post_task.h
index bedf9f5..37b1c40 100644
--- a/base/task/bind_post_task.h
+++ b/base/task/bind_post_task.h
@@ -9,8 +9,8 @@
#include <type_traits>
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/task/bind_post_task_internal.h"
#include "base/task/task_runner.h"
diff --git a/base/task/bind_post_task_internal.h b/base/task/bind_post_task_internal.h
index e2915eb..3e97f2f 100644
--- a/base/task/bind_post_task_internal.h
+++ b/base/task/bind_post_task_internal.h
@@ -7,9 +7,9 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/check.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/task/task_runner.h"
#include "base/task/thread_pool/thread_pool_instance.h"
diff --git a/base/task/bind_post_task_unittest.cc b/base/task/bind_post_task_unittest.cc
index f09072e..7bf7d29 100644
--- a/base/task/bind_post_task_unittest.cc
+++ b/base/task/bind_post_task_unittest.cc
@@ -4,8 +4,8 @@
#include "base/task/bind_post_task.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ref.h"
#include "base/sequence_checker_impl.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/task/bind_post_task_unittest.nc b/base/task/bind_post_task_unittest.nc
index 5aa1096..6cc2f88 100644
--- a/base/task/bind_post_task_unittest.nc
+++ b/base/task/bind_post_task_unittest.nc
@@ -8,8 +8,8 @@
#include "base/task/bind_post_task.h"
#include "base/task/sequenced_task_runner.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
namespace base {
diff --git a/base/task/cancelable_task_tracker.cc b/base/task/cancelable_task_tracker.cc
index 6b31f1a..0acac41 100644
--- a/base/task/cancelable_task_tracker.cc
+++ b/base/task/cancelable_task_tracker.cc
@@ -8,9 +8,9 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_macros.h"
diff --git a/base/task/cancelable_task_tracker.h b/base/task/cancelable_task_tracker.h
index 1010b2a..250c274 100644
--- a/base/task/cancelable_task_tracker.h
+++ b/base/task/cancelable_task_tracker.h
@@ -42,10 +42,10 @@
#include <utility>
#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/containers/small_map.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/sequence_checker.h"
diff --git a/base/task/cancelable_task_tracker_unittest.cc b/base/task/cancelable_task_tracker_unittest.cc
index 3c163b3..2f84bdc 100644
--- a/base/task/cancelable_task_tracker_unittest.cc
+++ b/base/task/cancelable_task_tracker_unittest.cc
@@ -7,9 +7,9 @@
#include <cstddef>
#include <tuple>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
diff --git a/base/task/common/task_annotator_unittest.cc b/base/task/common/task_annotator_unittest.cc
index 5c71c39..e071ba0 100644
--- a/base/task/common/task_annotator_unittest.cc
+++ b/base/task/common/task_annotator_unittest.cc
@@ -7,9 +7,9 @@
#include <algorithm>
#include <vector>
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/pending_task.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
diff --git a/base/task/current_thread.cc b/base/task/current_thread.cc
index d579f9f..cc4930f 100644
--- a/base/task/current_thread.cc
+++ b/base/task/current_thread.cc
@@ -4,8 +4,8 @@
#include "base/task/current_thread.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/message_loop/message_pump_for_io.h"
#include "base/message_loop/message_pump_for_ui.h"
#include "base/message_loop/message_pump_type.h"
diff --git a/base/task/current_thread.h b/base/task/current_thread.h
index e505af9..baddcc5 100644
--- a/base/task/current_thread.h
+++ b/base/task/current_thread.h
@@ -8,8 +8,8 @@
#include <ostream>
#include "base/base_export.h"
-#include "base/callback_forward.h"
#include "base/check.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/message_loop/message_pump_for_io.h"
diff --git a/base/task/default_delayed_task_handle_delegate.cc b/base/task/default_delayed_task_handle_delegate.cc
index df6846d..28dd357 100644
--- a/base/task/default_delayed_task_handle_delegate.cc
+++ b/base/task/default_delayed_task_handle_delegate.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "base/bind.h"
+#include "base/functional/bind.h"
namespace base {
diff --git a/base/task/default_delayed_task_handle_delegate.h b/base/task/default_delayed_task_handle_delegate.h
index d27a97f..beaf828 100644
--- a/base/task/default_delayed_task_handle_delegate.h
+++ b/base/task/default_delayed_task_handle_delegate.h
@@ -6,7 +6,7 @@
#define BASE_TASK_DEFAULT_DELAYED_TASK_HANDLE_DELEGATE_H_
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/weak_ptr.h"
#include "base/task/delayed_task_handle.h"
diff --git a/base/task/default_delayed_task_handle_delegate_unittest.cc b/base/task/default_delayed_task_handle_delegate_unittest.cc
index 7b92ddb..0017c7f 100644
--- a/base/task/default_delayed_task_handle_delegate_unittest.cc
+++ b/base/task/default_delayed_task_handle_delegate_unittest.cc
@@ -4,7 +4,7 @@
#include "base/task/default_delayed_task_handle_delegate.h"
-#include "base/callback_helpers.h"
+#include "base/functional/callback_helpers.h"
#include "base/task/delayed_task_handle.h"
#include "base/test/bind.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/task/deferred_sequenced_task_runner.cc b/base/task/deferred_sequenced_task_runner.cc
index 1e27f72..f712b61 100644
--- a/base/task/deferred_sequenced_task_runner.cc
+++ b/base/task/deferred_sequenced_task_runner.cc
@@ -7,8 +7,8 @@
#include <utility>
-#include "base/bind.h"
#include "base/check.h"
+#include "base/functional/bind.h"
namespace base {
@@ -33,6 +33,8 @@
AutoLock lock(lock_);
DCHECK(target_task_runner_);
#endif
+ task_runner_atomic_ptr_.store(target_task_runner_.get(),
+ std::memory_order_release);
}
DeferredSequencedTaskRunner::DeferredSequencedTaskRunner()
@@ -58,9 +60,13 @@
}
bool DeferredSequencedTaskRunner::RunsTasksInCurrentSequence() const {
- AutoLock lock(lock_);
- if (target_task_runner_)
- return target_task_runner_->RunsTasksInCurrentSequence();
+ // task_runner_atomic_ptr_ cannot change once it has been initialized, so it's
+ // safe to access it without lock.
+ SequencedTaskRunner* task_runner_ptr =
+ task_runner_atomic_ptr_.load(std::memory_order_acquire);
+ if (task_runner_ptr) {
+ return task_runner_ptr->RunsTasksInCurrentSequence();
+ }
return created_thread_id_ == PlatformThread::CurrentId();
}
@@ -91,6 +97,8 @@
DCHECK(!target_task_runner_);
DCHECK(target_task_runner);
target_task_runner_ = std::move(target_task_runner);
+ task_runner_atomic_ptr_.store(target_task_runner_.get(),
+ std::memory_order_release);
StartImpl();
}
diff --git a/base/task/deferred_sequenced_task_runner.h b/base/task/deferred_sequenced_task_runner.h
index 5ba7fdf..d1b4ac7 100644
--- a/base/task/deferred_sequenced_task_runner.h
+++ b/base/task/deferred_sequenced_task_runner.h
@@ -8,8 +8,8 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/compiler_specific.h"
+#include "base/functional/callback.h"
#include "base/synchronization/lock.h"
#include "base/task/sequenced_task_runner.h"
#include "base/threading/platform_thread.h"
@@ -85,6 +85,11 @@
const PlatformThreadId created_thread_id_;
+ // An atomic pointer that allows to call task_runner methods without lock.
+ // It's possible because the pointer starts as null, is set to a non-null
+ // value only once, and is never changed again.
+ // This is used to implement a lock-free RunsTasksInCurrentSequence method.
+ std::atomic<SequencedTaskRunner*> task_runner_atomic_ptr_{nullptr};
bool started_ GUARDED_BY(lock_) = false;
scoped_refptr<SequencedTaskRunner> target_task_runner_ GUARDED_BY(lock_);
std::vector<DeferredTask> deferred_tasks_queue_ GUARDED_BY(lock_);
diff --git a/base/task/deferred_sequenced_task_runner_unittest.cc b/base/task/deferred_sequenced_task_runner_unittest.cc
index b7c7153..9360c0d 100644
--- a/base/task/deferred_sequenced_task_runner_unittest.cc
+++ b/base/task/deferred_sequenced_task_runner_unittest.cc
@@ -4,8 +4,8 @@
#include "base/task/deferred_sequenced_task_runner.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
@@ -13,7 +13,6 @@
#include "base/task/single_thread_task_runner.h"
#include "base/test/task_environment.h"
#include "base/threading/thread.h"
-#include "base/threading/thread_task_runner_handle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/task/job_perftest.cc b/base/task/job_perftest.cc
index d309abd..1368516 100644
--- a/base/task/job_perftest.cc
+++ b/base/task/job_perftest.cc
@@ -7,9 +7,9 @@
#include <utility>
#include <vector>
-#include "base/callback_helpers.h"
#include "base/containers/queue.h"
#include "base/containers/stack.h"
+#include "base/functional/callback_helpers.h"
#include "base/synchronization/lock.h"
#include "base/task/post_job.h"
#include "base/task/thread_pool.h"
diff --git a/base/task/lazy_thread_pool_task_runner.h b/base/task/lazy_thread_pool_task_runner.h
index 424f96c..34d0de8 100644
--- a/base/task/lazy_thread_pool_task_runner.h
+++ b/base/task/lazy_thread_pool_task_runner.h
@@ -9,7 +9,7 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/task/common/checked_lock.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/task/lazy_thread_pool_task_runner_unittest.cc b/base/task/lazy_thread_pool_task_runner_unittest.cc
index 897eacb..e1a17a2 100644
--- a/base/task/lazy_thread_pool_task_runner_unittest.cc
+++ b/base/task/lazy_thread_pool_task_runner_unittest.cc
@@ -4,8 +4,8 @@
#include "base/task/lazy_thread_pool_task_runner.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/sequence_checker_impl.h"
#include "base/task/scoped_set_task_priority_for_current_thread.h"
#include "base/test/task_environment.h"
diff --git a/base/task/post_job.h b/base/task/post_job.h
index ff2a221..582aa61 100644
--- a/base/task/post_job.h
+++ b/base/task/post_job.h
@@ -8,8 +8,8 @@
#include <limits>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/task/post_task_and_reply_with_result_internal.h b/base/task/post_task_and_reply_with_result_internal.h
index 6e4f446..053ff77 100644
--- a/base/task/post_task_and_reply_with_result_internal.h
+++ b/base/task/post_task_and_reply_with_result_internal.h
@@ -8,8 +8,8 @@
#include <memory>
#include <utility>
-#include "base/callback.h"
#include "base/check.h"
+#include "base/functional/callback.h"
namespace base {
diff --git a/base/task/sequence_manager/atomic_flag_set.cc b/base/task/sequence_manager/atomic_flag_set.cc
index d8322eb..3460500 100644
--- a/base/task/sequence_manager/atomic_flag_set.cc
+++ b/base/task/sequence_manager/atomic_flag_set.cc
@@ -7,8 +7,8 @@
#include <utility>
#include "base/bits.h"
-#include "base/callback.h"
#include "base/check_op.h"
+#include "base/functional/callback.h"
namespace base {
namespace sequence_manager {
diff --git a/base/task/sequence_manager/atomic_flag_set.h b/base/task/sequence_manager/atomic_flag_set.h
index c6f52ca..e3c7d06 100644
--- a/base/task/sequence_manager/atomic_flag_set.h
+++ b/base/task/sequence_manager/atomic_flag_set.h
@@ -9,7 +9,7 @@
#include <memory>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/task/sequence_manager/associated_thread_id.h"
diff --git a/base/task/sequence_manager/sequence_manager_impl.cc b/base/task/sequence_manager/sequence_manager_impl.cc
index 321c609..4563065 100644
--- a/base/task/sequence_manager/sequence_manager_impl.cc
+++ b/base/task/sequence_manager/sequence_manager_impl.cc
@@ -8,12 +8,12 @@
#include <queue>
#include <vector>
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/compiler_specific.h"
#include "base/debug/crash_logging.h"
#include "base/debug/stack_trace.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/logging.h"
#include "base/memory/ptr_util.h"
diff --git a/base/task/sequence_manager/sequence_manager_impl.h b/base/task/sequence_manager/sequence_manager_impl.h
index 19c8fd6..8ac3dd7 100644
--- a/base/task/sequence_manager/sequence_manager_impl.h
+++ b/base/task/sequence_manager/sequence_manager_impl.h
@@ -14,11 +14,11 @@
#include "base/atomic_sequence_num.h"
#include "base/base_export.h"
-#include "base/callback_forward.h"
#include "base/cancelable_callback.h"
#include "base/containers/circular_deque.h"
#include "base/debug/crash_logging.h"
#include "base/feature_list.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
diff --git a/base/task/sequence_manager/sequence_manager_impl_unittest.cc b/base/task/sequence_manager/sequence_manager_impl_unittest.cc
index 3905f9d..3d857b1 100644
--- a/base/task/sequence_manager/sequence_manager_impl_unittest.cc
+++ b/base/task/sequence_manager/sequence_manager_impl_unittest.cc
@@ -12,11 +12,11 @@
#include <vector>
#include "base/auto_reset.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_forward.h"
-#include "base/callback_helpers.h"
#include "base/cancelable_callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_forward.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted_memory.h"
diff --git a/base/task/sequence_manager/sequence_manager_perftest.cc b/base/task/sequence_manager/sequence_manager_perftest.cc
index f8da3be..af5369c 100644
--- a/base/task/sequence_manager/sequence_manager_perftest.cc
+++ b/base/task/sequence_manager/sequence_manager_perftest.cc
@@ -8,7 +8,7 @@
#include <stddef.h>
#include <memory>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/message_loop/message_pump_default.h"
#include "base/message_loop/message_pump_type.h"
diff --git a/base/task/sequence_manager/sequenced_task_source.h b/base/task/sequence_manager/sequenced_task_source.h
index 0b33f7a..da2d273 100644
--- a/base/task/sequence_manager/sequenced_task_source.h
+++ b/base/task/sequence_manager/sequenced_task_source.h
@@ -6,7 +6,7 @@
#define BASE_TASK_SEQUENCE_MANAGER_SEQUENCED_TASK_SOURCE_H_
#include "base/base_export.h"
-#include "base/callback_helpers.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ref.h"
#include "base/pending_task.h"
#include "base/task/common/lazy_now.h"
diff --git a/base/task/sequence_manager/task_queue.cc b/base/task/sequence_manager/task_queue.cc
index df00478..2260bef 100644
--- a/base/task/sequence_manager/task_queue.cc
+++ b/base/task/sequence_manager/task_queue.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/task/sequence_manager/associated_thread_id.h"
#include "base/task/sequence_manager/sequence_manager_impl.h"
diff --git a/base/task/sequence_manager/task_queue_impl.h b/base/task/sequence_manager/task_queue_impl.h
index c763a2f..874d3b1 100644
--- a/base/task/sequence_manager/task_queue_impl.h
+++ b/base/task/sequence_manager/task_queue_impl.h
@@ -15,10 +15,10 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/containers/flat_map.h"
#include "base/containers/intrusive_heap.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
@@ -555,7 +555,7 @@
OnTaskPostedCallbackHandleImpl* on_task_posted_callback_handle);
QueueName name_;
- const raw_ptr<SequenceManagerImpl> sequence_manager_;
+ const raw_ptr<SequenceManagerImpl, DanglingUntriaged> sequence_manager_;
const scoped_refptr<const AssociatedThreadId> associated_thread_;
diff --git a/base/task/sequence_manager/task_queue_selector_unittest.cc b/base/task/sequence_manager/task_queue_selector_unittest.cc
index 7adaba4..b0a198b 100644
--- a/base/task/sequence_manager/task_queue_selector_unittest.cc
+++ b/base/task/sequence_manager/task_queue_selector_unittest.cc
@@ -12,7 +12,7 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/pending_task.h"
#include "base/task/sequence_manager/enqueue_order_generator.h"
diff --git a/base/task/sequence_manager/test/mock_time_message_pump.h b/base/task/sequence_manager/test/mock_time_message_pump.h
index 36752e0..6fca818 100644
--- a/base/task/sequence_manager/test/mock_time_message_pump.h
+++ b/base/task/sequence_manager/test/mock_time_message_pump.h
@@ -5,7 +5,7 @@
#ifndef BASE_TASK_SEQUENCE_MANAGER_TEST_MOCK_TIME_MESSAGE_PUMP_H_
#define BASE_TASK_SEQUENCE_MANAGER_TEST_MOCK_TIME_MESSAGE_PUMP_H_
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/message_loop/message_pump.h"
#include "base/synchronization/waitable_event.h"
diff --git a/base/task/sequence_manager/thread_controller_impl.cc b/base/task/sequence_manager/thread_controller_impl.cc
index 91f3b52..d5564e2 100644
--- a/base/task/sequence_manager/thread_controller_impl.cc
+++ b/base/task/sequence_manager/thread_controller_impl.cc
@@ -6,7 +6,7 @@
#include <algorithm>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_pump.h"
#include "base/notreached.h"
diff --git a/base/task/sequence_manager/thread_controller_with_message_pump_impl_unittest.cc b/base/task/sequence_manager/thread_controller_with_message_pump_impl_unittest.cc
index 5533ce3..a3d8a47 100644
--- a/base/task/sequence_manager/thread_controller_with_message_pump_impl_unittest.cc
+++ b/base/task/sequence_manager/thread_controller_with_message_pump_impl_unittest.cc
@@ -8,9 +8,9 @@
#include <string>
#include <utility>
#include <vector>
-#include "base/bind.h"
-#include "base/callback_forward.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_forward.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/task/sequence_manager/task_queue.h"
diff --git a/base/task/sequence_manager/time_domain.h b/base/task/sequence_manager/time_domain.h
index bf202c7..599a69d 100644
--- a/base/task/sequence_manager/time_domain.h
+++ b/base/task/sequence_manager/time_domain.h
@@ -7,6 +7,7 @@
#include "base/base_export.h"
#include "base/check.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/task/common/lazy_now.h"
#include "base/task/sequence_manager/tasks.h"
#include "base/time/tick_clock.h"
@@ -58,7 +59,10 @@
private:
friend class internal::SequenceManagerImpl;
- internal::SequenceManagerImpl* sequence_manager_ = nullptr; // Not owned.
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION internal::SequenceManagerImpl* sequence_manager_ =
+ nullptr; // Not owned.
};
} // namespace sequence_manager
diff --git a/base/task/sequence_manager/work_queue_sets_unittest.cc b/base/task/sequence_manager/work_queue_sets_unittest.cc
index 1031086..0b2e272 100644
--- a/base/task/sequence_manager/work_queue_sets_unittest.cc
+++ b/base/task/sequence_manager/work_queue_sets_unittest.cc
@@ -8,7 +8,7 @@
#include <memory>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/task/sequence_manager/enqueue_order.h"
#include "base/task/sequence_manager/fence.h"
diff --git a/base/task/sequence_manager/work_queue_unittest.cc b/base/task/sequence_manager/work_queue_unittest.cc
index 2c5291f..b606834 100644
--- a/base/task/sequence_manager/work_queue_unittest.cc
+++ b/base/task/sequence_manager/work_queue_unittest.cc
@@ -7,7 +7,7 @@
#include <stddef.h>
#include <memory>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/task/common/lazy_now.h"
#include "base/task/sequence_manager/enqueue_order.h"
#include "base/task/sequence_manager/fence.h"
diff --git a/base/task/sequenced_task_runner.cc b/base/task/sequenced_task_runner.cc
index c132346..7efadd3 100644
--- a/base/task/sequenced_task_runner.cc
+++ b/base/task/sequenced_task_runner.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/no_destructor.h"
#include "base/task/default_delayed_task_handle_delegate.h"
#include "base/threading/thread_local.h"
diff --git a/base/task/sequenced_task_runner.h b/base/task/sequenced_task_runner.h
index 16ae028..669f36a 100644
--- a/base/task/sequenced_task_runner.h
+++ b/base/task/sequenced_task_runner.h
@@ -8,7 +8,7 @@
#include <memory>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/task/delay_policy.h"
#include "base/task/delayed_task_handle.h"
#include "base/task/sequenced_task_runner_helpers.h"
diff --git a/base/task/sequenced_task_runner_unittest.cc b/base/task/sequenced_task_runner_unittest.cc
index c4fd0d8..465b25e 100644
--- a/base/task/sequenced_task_runner_unittest.cc
+++ b/base/task/sequenced_task_runner_unittest.cc
@@ -6,9 +6,9 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/gtest_prod_util.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/task/simple_task_executor.h b/base/task/simple_task_executor.h
index c550bde..d398b69 100644
--- a/base/task/simple_task_executor.h
+++ b/base/task/simple_task_executor.h
@@ -6,6 +6,7 @@
#define BASE_TASK_SIMPLE_TASK_EXECUTOR_H_
#include "base/base_export.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/task/task_executor.h"
#include "build/build_config.h"
@@ -45,7 +46,9 @@
// In tests there may already be a TaskExecutor registered for the thread, we
// keep tack of the previous TaskExecutor and restored it upon destruction.
- TaskExecutor* const previous_task_executor_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION TaskExecutor* const previous_task_executor_;
};
} // namespace base
diff --git a/base/task/single_thread_task_executor_unittest.cc b/base/task/single_thread_task_executor_unittest.cc
index ba694e8..0193713 100644
--- a/base/task/single_thread_task_executor_unittest.cc
+++ b/base/task/single_thread_task_executor_unittest.cc
@@ -10,9 +10,9 @@
#include <string>
#include <vector>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/compiler_specific.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/task/single_thread_task_runner.cc b/base/task/single_thread_task_runner.cc
index 5227cc3..ebf2867 100644
--- a/base/task/single_thread_task_runner.cc
+++ b/base/task/single_thread_task_runner.cc
@@ -3,19 +3,17 @@
// found in the LICENSE file.
#include "base/task/single_thread_task_runner.h"
-#include "base/threading/thread_task_runner_handle.h"
#include <memory>
#include <utility>
-#include "base/bind.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/no_destructor.h"
#include "base/run_loop.h"
-#include "base/threading/sequenced_task_runner_handle.h"
#include "base/threading/thread_local.h"
namespace base {
diff --git a/base/task/single_thread_task_runner.h b/base/task/single_thread_task_runner.h
index e94b01e..3cbc4ee 100644
--- a/base/task/single_thread_task_runner.h
+++ b/base/task/single_thread_task_runner.h
@@ -7,6 +7,7 @@
#include "base/base_export.h"
#include "base/dcheck_is_on.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/task/sequenced_task_runner.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
@@ -107,10 +108,6 @@
FRIEND_TEST_ALL_PREFIXES(SingleThreadTaskRunnerCurrentDefaultHandleTest,
NestedRunLoop);
- // This is in order for ThreadTaskRunnerHandleOverride to call this private
- // constructor during migration.
- friend class ThreadTaskRunnerHandleOverride;
-
// We expect SingleThreadTaskRunner::CurrentHandleOverride to be only needed
// under special circumstances. Require them to be enumerated as friends to
// require //base/OWNERS review. Use
@@ -136,7 +133,10 @@
scoped_refptr<SingleThreadTaskRunner> task_runner_to_restore_;
#if DCHECK_IS_ON()
- SingleThreadTaskRunner* expected_task_runner_before_restore_{nullptr};
+ // This field is not a raw_ptr<> because it was filtered by the rewriter
+ // for: #union
+ RAW_PTR_EXCLUSION SingleThreadTaskRunner*
+ expected_task_runner_before_restore_{nullptr};
#endif
std::unique_ptr<ScopedDisallowRunningRunLoop> no_running_during_override_;
diff --git a/base/task/task_runner.cc b/base/task/task_runner.cc
index 2b77db6..1ed7307 100644
--- a/base/task/task_runner.cc
+++ b/base/task/task_runner.cc
@@ -6,9 +6,9 @@
#include <utility>
-#include "base/bind.h"
#include "base/check.h"
#include "base/compiler_specific.h"
+#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/threading/post_task_and_reply_impl.h"
#include "base/time/time.h"
diff --git a/base/task/task_runner.h b/base/task/task_runner.h
index 6bb373f..287fc74 100644
--- a/base/task/task_runner.h
+++ b/base/task/task_runner.h
@@ -8,10 +8,10 @@
#include <stddef.h>
#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/check.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/task/post_task_and_reply_with_result_internal.h"
diff --git a/base/task/task_runner_unittest.cc b/base/task/task_runner_unittest.cc
index d844046..7091a4b 100644
--- a/base/task/task_runner_unittest.cc
+++ b/base/task/task_runner_unittest.cc
@@ -7,7 +7,7 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/task/thread_pool.h b/base/task/thread_pool.h
index 02e1b86..bc7ba0b 100644
--- a/base/task/thread_pool.h
+++ b/base/task/thread_pool.h
@@ -9,9 +9,9 @@
#include <utility>
#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/scoped_refptr.h"
#include "base/task/post_task_and_reply_with_result_internal.h"
diff --git a/base/task/thread_pool/delayed_priority_queue_unittest.cc b/base/task/thread_pool/delayed_priority_queue_unittest.cc
index 1543479..4300988 100644
--- a/base/task/thread_pool/delayed_priority_queue_unittest.cc
+++ b/base/task/thread_pool/delayed_priority_queue_unittest.cc
@@ -7,7 +7,7 @@
#include <memory>
#include <utility>
-#include "base/callback_helpers.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/task/task_traits.h"
diff --git a/base/task/thread_pool/delayed_task_manager.cc b/base/task/thread_pool/delayed_task_manager.cc
index fdc391d..4b61aa6 100644
--- a/base/task/thread_pool/delayed_task_manager.cc
+++ b/base/task/thread_pool/delayed_task_manager.cc
@@ -6,9 +6,9 @@
#include <algorithm>
-#include "base/bind.h"
#include "base/check.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
#include "base/task/common/checked_lock.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/task_features.h"
diff --git a/base/task/thread_pool/delayed_task_manager.h b/base/task/thread_pool/delayed_task_manager.h
index a04b4e3..b055a50 100644
--- a/base/task/thread_pool/delayed_task_manager.h
+++ b/base/task/thread_pool/delayed_task_manager.h
@@ -8,8 +8,8 @@
#include <functional>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/containers/intrusive_heap.h"
+#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/atomic_flag.h"
diff --git a/base/task/thread_pool/delayed_task_manager_unittest.cc b/base/task/thread_pool/delayed_task_manager_unittest.cc
index c9c0dd5..70f5fe8 100644
--- a/base/task/thread_pool/delayed_task_manager_unittest.cc
+++ b/base/task/thread_pool/delayed_task_manager_unittest.cc
@@ -7,9 +7,9 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/cancelable_callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/waitable_event.h"
diff --git a/base/task/thread_pool/job_task_source.cc b/base/task/thread_pool/job_task_source.cc
index de92c80..529f53c 100644
--- a/base/task/thread_pool/job_task_source.cc
+++ b/base/task/thread_pool/job_task_source.cc
@@ -7,10 +7,10 @@
#include <type_traits>
#include <utility>
-#include "base/bind.h"
#include "base/bits.h"
-#include "base/callback_helpers.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/notreached.h"
#include "base/task/common/checked_lock.h"
diff --git a/base/task/thread_pool/job_task_source.h b/base/task/thread_pool/job_task_source.h
index 5c43127..71d902a 100644
--- a/base/task/thread_pool/job_task_source.h
+++ b/base/task/thread_pool/job_task_source.h
@@ -13,7 +13,7 @@
#include <utility>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/condition_variable.h"
#include "base/task/common/checked_lock.h"
diff --git a/base/task/thread_pool/job_task_source_unittest.cc b/base/task/thread_pool/job_task_source_unittest.cc
index 4ff3f69..82a23e4 100644
--- a/base/task/thread_pool/job_task_source_unittest.cc
+++ b/base/task/thread_pool/job_task_source_unittest.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "base/callback_helpers.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/task/thread_pool/pooled_task_runner_delegate.h"
#include "base/task/thread_pool/test_utils.h"
diff --git a/base/task/thread_pool/pooled_parallel_task_runner.h b/base/task/thread_pool/pooled_parallel_task_runner.h
index d2a3745..030f742 100644
--- a/base/task/thread_pool/pooled_parallel_task_runner.h
+++ b/base/task/thread_pool/pooled_parallel_task_runner.h
@@ -6,7 +6,7 @@
#define BASE_TASK_THREAD_POOL_POOLED_PARALLEL_TASK_RUNNER_H_
#include "base/base_export.h"
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/task/task_runner.h"
diff --git a/base/task/thread_pool/pooled_sequenced_task_runner.h b/base/task/thread_pool/pooled_sequenced_task_runner.h
index 5d5a3fe..9f7fbdc 100644
--- a/base/task/thread_pool/pooled_sequenced_task_runner.h
+++ b/base/task/thread_pool/pooled_sequenced_task_runner.h
@@ -6,7 +6,7 @@
#define BASE_TASK_THREAD_POOL_POOLED_SEQUENCED_TASK_RUNNER_H_
#include "base/base_export.h"
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/task/task_traits.h"
diff --git a/base/task/thread_pool/pooled_single_thread_task_runner_manager.cc b/base/task/thread_pool/pooled_single_thread_task_runner_manager.cc
index 6585aff..2693e06 100644
--- a/base/task/thread_pool/pooled_single_thread_task_runner_manager.cc
+++ b/base/task/thread_pool/pooled_single_thread_task_runner_manager.cc
@@ -8,9 +8,9 @@
#include <string>
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/debug/leak_annotations.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/ranges/algorithm.h"
diff --git a/base/task/thread_pool/pooled_single_thread_task_runner_manager_unittest.cc b/base/task/thread_pool/pooled_single_thread_task_runner_manager_unittest.cc
index 136ea27..bd98250 100644
--- a/base/task/thread_pool/pooled_single_thread_task_runner_manager_unittest.cc
+++ b/base/task/thread_pool/pooled_single_thread_task_runner_manager_unittest.cc
@@ -4,8 +4,8 @@
#include "base/task/thread_pool/pooled_single_thread_task_runner_manager.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/atomic_flag.h"
diff --git a/base/task/thread_pool/priority_queue_unittest.cc b/base/task/thread_pool/priority_queue_unittest.cc
index 46d4618..a42ee1e 100644
--- a/base/task/thread_pool/priority_queue_unittest.cc
+++ b/base/task/thread_pool/priority_queue_unittest.cc
@@ -7,7 +7,7 @@
#include <memory>
#include <utility>
-#include "base/callback_helpers.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/task/task_traits.h"
diff --git a/base/task/thread_pool/sequence.cc b/base/task/thread_pool/sequence.cc
index 666a2c6..b82760e 100644
--- a/base/task/thread_pool/sequence.cc
+++ b/base/task/thread_pool/sequence.cc
@@ -6,10 +6,10 @@
#include <utility>
-#include "base/bind.h"
#include "base/check.h"
#include "base/critical_closure.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/task/task_features.h"
#include "base/time/time.h"
diff --git a/base/task/thread_pool/sequence_unittest.cc b/base/task/thread_pool/sequence_unittest.cc
index 2588415..84a7bf1 100644
--- a/base/task/thread_pool/sequence_unittest.cc
+++ b/base/task/thread_pool/sequence_unittest.cc
@@ -6,8 +6,8 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/test/gtest_util.h"
#include "base/time/time.h"
diff --git a/base/task/thread_pool/service_thread_unittest.cc b/base/task/thread_pool/service_thread_unittest.cc
index 4e16b0a..9a7e796 100644
--- a/base/task/thread_pool/service_thread_unittest.cc
+++ b/base/task/thread_pool/service_thread_unittest.cc
@@ -6,8 +6,8 @@
#include <string>
-#include "base/bind.h"
#include "base/debug/stack_trace.h"
+#include "base/functional/bind.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/task/thread_pool/task.h b/base/task/thread_pool/task.h
index 4e89eea..2af88aa 100644
--- a/base/task/thread_pool/task.h
+++ b/base/task/thread_pool/task.h
@@ -6,8 +6,8 @@
#define BASE_TASK_THREAD_POOL_TASK_H_
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/containers/intrusive_heap.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/pending_task.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/task/thread_pool/task_source.h b/base/task/thread_pool/task_source.h
index f9c6dff..af23db5 100644
--- a/base/task/thread_pool/task_source.h
+++ b/base/task/thread_pool/task_source.h
@@ -11,6 +11,7 @@
#include "base/containers/intrusive_heap.h"
#include "base/dcheck_is_on.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/ref_counted.h"
#include "base/sequence_token.h"
#include "base/task/common/checked_lock.h"
@@ -127,7 +128,9 @@
private:
friend class TaskSource;
- TaskSource* task_source_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter
+ // for: #union
+ RAW_PTR_EXCLUSION TaskSource* task_source_;
};
// |traits| is metadata that applies to all Tasks in the TaskSource.
@@ -336,7 +339,9 @@
#endif // DCHECK_IS_ON()
scoped_refptr<TaskSource> task_source_;
- TaskTracker* task_tracker_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION TaskTracker* task_tracker_ = nullptr;
};
// A pair of Transaction and RegisteredTaskSource. Useful to carry a
diff --git a/base/task/thread_pool/task_tracker.cc b/base/task/thread_pool/task_tracker.cc
index 479ac33..51f2e15 100644
--- a/base/task/thread_pool/task_tracker.cc
+++ b/base/task/thread_pool/task_tracker.cc
@@ -9,10 +9,10 @@
#include <utility>
#include "base/base_switches.h"
-#include "base/callback.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/debug/alias.h"
+#include "base/functional/callback.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
@@ -469,21 +469,21 @@
// Set up TaskRunner CurrentDefaultHandle as expected for the scope of the
// task.
absl::optional<SequencedTaskRunner::CurrentDefaultHandle>
- sequenced_task_runner_handle;
+ sequenced_task_runner_current_default_handle;
absl::optional<SingleThreadTaskRunner::CurrentDefaultHandle>
- single_thread_task_runner_handle;
+ single_thread_task_runner_current_default_handle;
switch (task_source->execution_mode()) {
case TaskSourceExecutionMode::kJob:
case TaskSourceExecutionMode::kParallel:
break;
case TaskSourceExecutionMode::kSequenced:
DCHECK(task_source->task_runner());
- sequenced_task_runner_handle.emplace(
+ sequenced_task_runner_current_default_handle.emplace(
static_cast<SequencedTaskRunner*>(task_source->task_runner()));
break;
case TaskSourceExecutionMode::kSingleThread:
DCHECK(task_source->task_runner());
- single_thread_task_runner_handle.emplace(
+ single_thread_task_runner_current_default_handle.emplace(
static_cast<SingleThreadTaskRunner*>(task_source->task_runner()));
break;
}
diff --git a/base/task/thread_pool/task_tracker.h b/base/task/thread_pool/task_tracker.h
index 508ac6e..2a25c36 100644
--- a/base/task/thread_pool/task_tracker.h
+++ b/base/task/thread_pool/task_tracker.h
@@ -14,8 +14,8 @@
#include "base/atomicops.h"
#include "base/base_export.h"
-#include "base/callback_forward.h"
#include "base/containers/circular_deque.h"
+#include "base/functional/callback_forward.h"
#include "base/sequence_checker.h"
#include "base/strings/string_piece.h"
#include "base/synchronization/waitable_event.h"
diff --git a/base/task/thread_pool/task_tracker_unittest.cc b/base/task/thread_pool/task_tracker_unittest.cc
index 920d0df..b89082a 100644
--- a/base/task/thread_pool/task_tracker_unittest.cc
+++ b/base/task/thread_pool/task_tracker_unittest.cc
@@ -11,10 +11,10 @@
#include <vector>
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
@@ -545,8 +545,8 @@
// Pretend |verify_task| is posted to respect TaskTracker's contract.
EXPECT_TRUE(tracker->WillPostTask(&verify_task, traits.shutdown_behavior()));
- // Confirm that the test conditions are right (no TaskRunnerHandles set
- // already).
+ // Confirm that the test conditions are right (no
+ // task runner CurrentDefaultHandles set already).
EXPECT_FALSE(SingleThreadTaskRunner::HasCurrentDefault());
EXPECT_FALSE(SequencedTaskRunner::HasCurrentDefault());
@@ -555,12 +555,12 @@
test::CreateSequenceWithTask(std::move(verify_task), traits,
std::move(task_runner), execution_mode));
- // TaskRunnerHandle state is reset outside of task's scope.
+ // task runner CurrentDefaultHandle state is reset outside of task's scope.
EXPECT_FALSE(SingleThreadTaskRunner::HasCurrentDefault());
EXPECT_FALSE(SequencedTaskRunner::HasCurrentDefault());
}
-static void VerifyNoTaskRunnerHandle() {
+static void VerifyNoTaskRunnerCurrentDefaultHandle() {
EXPECT_FALSE(SingleThreadTaskRunner::HasCurrentDefault());
EXPECT_FALSE(SequencedTaskRunner::HasCurrentDefault());
}
@@ -568,7 +568,7 @@
TEST_P(ThreadPoolTaskTrackerTest, TaskRunnerHandleIsNotSetOnParallel) {
// Create a task that will verify that TaskRunnerHandles are not set in its
// scope per no TaskRunner ref being set to it.
- Task verify_task(FROM_HERE, BindOnce(&VerifyNoTaskRunnerHandle),
+ Task verify_task(FROM_HERE, BindOnce(&VerifyNoTaskRunnerCurrentDefaultHandle),
TimeTicks::Now(), TimeDelta());
RunTaskRunnerCurrentDefaultHandleVerificationTask(
diff --git a/base/task/thread_pool/test_task_factory.cc b/base/task/thread_pool/test_task_factory.cc
index a038763..a9d9fa9 100644
--- a/base/task/thread_pool/test_task_factory.cc
+++ b/base/task/thread_pool/test_task_factory.cc
@@ -4,10 +4,10 @@
#include "base/task/thread_pool/test_task_factory.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/sequenced_task_runner.h"
@@ -59,7 +59,8 @@
->RunsTasksInCurrentSequence());
}
- // Verify TaskRunnerHandles are set as expected in the task's scope.
+ // Verify task runner CurrentDefaultHandles are set as expected in the task's
+ // scope.
switch (execution_mode_) {
case TaskSourceExecutionMode::kJob:
case TaskSourceExecutionMode::kParallel:
diff --git a/base/task/thread_pool/test_task_factory.h b/base/task/thread_pool/test_task_factory.h
index 4a894d9..9805eb3 100644
--- a/base/task/thread_pool/test_task_factory.h
+++ b/base/task/thread_pool/test_task_factory.h
@@ -9,7 +9,7 @@
#include <unordered_set>
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
@@ -27,8 +27,8 @@
// - The RunsTasksInCurrentSequence() method of the SequencedTaskRunner
// (kSequenced or kSingleThread modes) returns false on a thread on which a
// Task is run.
-// - The TaskRunnerHandles set in the context of the task don't match what's
-// expected for the tested TaskSourceExecutionMode.
+// - The task runner CurrentDefaultHandles set in the context of the task don't
+// match what's expected for the tested TaskSourceExecutionMode.
// - The TaskSourceExecutionMode of the TaskRunner is kSequenced or
// kSingleThread and Tasks don't run in posting order.
// - The TaskSourceExecutionMode of the TaskRunner is kSingleThread and Tasks
diff --git a/base/task/thread_pool/test_utils.cc b/base/task/thread_pool/test_utils.cc
index 63f8ea2..880b419 100644
--- a/base/task/thread_pool/test_utils.cc
+++ b/base/task/thread_pool/test_utils.cc
@@ -6,8 +6,8 @@
#include <utility>
-#include "base/bind.h"
#include "base/debug/leak_annotations.h"
+#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/condition_variable.h"
#include "base/task/thread_pool/pooled_parallel_task_runner.h"
diff --git a/base/task/thread_pool/test_utils.h b/base/task/thread_pool/test_utils.h
index e7a43db..1db33ff 100644
--- a/base/task/thread_pool/test_utils.h
+++ b/base/task/thread_pool/test_utils.h
@@ -8,7 +8,7 @@
#include <atomic>
#include <memory>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/task/common/checked_lock.h"
#include "base/task/post_job.h"
diff --git a/base/task/thread_pool/thread_group.cc b/base/task/thread_pool/thread_group.cc
index 5d9a5e0..8eb2e95 100644
--- a/base/task/thread_pool/thread_group.cc
+++ b/base/task/thread_pool/thread_group.cc
@@ -6,9 +6,9 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/task/task_features.h"
#include "base/task/thread_pool/task_tracker.h"
diff --git a/base/task/thread_pool/thread_group_impl.cc b/base/task/thread_pool/thread_group_impl.cc
index 32036d4..5329e5d 100644
--- a/base/task/thread_pool/thread_group_impl.cc
+++ b/base/task/thread_pool/thread_group_impl.cc
@@ -12,11 +12,11 @@
#include "base/atomicops.h"
#include "base/auto_reset.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/compiler_specific.h"
#include "base/containers/stack_container.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/task/thread_pool/thread_group_impl_unittest.cc b/base/task/thread_pool/thread_group_impl_unittest.cc
index e28c79e..3bbc5c9 100644
--- a/base/task/thread_pool/thread_group_impl_unittest.cc
+++ b/base/task/thread_pool/thread_group_impl_unittest.cc
@@ -15,9 +15,9 @@
#include "base/atomicops.h"
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
diff --git a/base/task/thread_pool/thread_group_unittest.cc b/base/task/thread_pool/thread_group_unittest.cc
index 233c84b..a487feb 100644
--- a/base/task/thread_pool/thread_group_unittest.cc
+++ b/base/task/thread_pool/thread_group_unittest.cc
@@ -9,8 +9,8 @@
#include <utility>
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/task/task_runner.h"
diff --git a/base/task/thread_pool/thread_pool_impl.cc b/base/task/thread_pool/thread_pool_impl.cc
index d6177c8..d8595fd 100644
--- a/base/task/thread_pool/thread_pool_impl.cc
+++ b/base/task/thread_pool/thread_pool_impl.cc
@@ -9,13 +9,13 @@
#include <utility>
#include "base/base_switches.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/debug/alias.h"
#include "base/debug/leak_annotations.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/message_loop/message_pump_type.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/string_util.h"
diff --git a/base/task/thread_pool/thread_pool_impl.h b/base/task/thread_pool/thread_pool_impl.h
index ebc0833..633c3e7 100644
--- a/base/task/thread_pool/thread_pool_impl.h
+++ b/base/task/thread_pool/thread_pool_impl.h
@@ -8,8 +8,8 @@
#include <memory>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/dcheck_is_on.h"
+#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/sequence_checker.h"
#include "base/strings/string_piece.h"
diff --git a/base/task/thread_pool/thread_pool_impl_unittest.cc b/base/task/thread_pool/thread_pool_impl_unittest.cc
index 0f882b3..a4d1d8b 100644
--- a/base/task/thread_pool/thread_pool_impl_unittest.cc
+++ b/base/task/thread_pool/thread_pool_impl_unittest.cc
@@ -13,12 +13,12 @@
#include <vector>
#include "base/base_switches.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/cfi_buildflags.h"
#include "base/containers/span.h"
#include "base/debug/stack_trace.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/message_loop/message_pump_type.h"
#include "base/metrics/field_trial.h"
diff --git a/base/task/thread_pool/thread_pool_instance.h b/base/task/thread_pool/thread_pool_instance.h
index 2366076..a4f78b3 100644
--- a/base/task/thread_pool/thread_pool_instance.h
+++ b/base/task/thread_pool/thread_pool_instance.h
@@ -8,7 +8,7 @@
#include <memory>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/gtest_prod_util.h"
#include "base/strings/string_piece.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/task/thread_pool/thread_pool_perftest.cc b/base/task/thread_pool/thread_pool_perftest.cc
index a29d57d..f0f8cfb 100644
--- a/base/task/thread_pool/thread_pool_perftest.cc
+++ b/base/task/thread_pool/thread_pool_perftest.cc
@@ -8,9 +8,9 @@
#include <vector>
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/thread_pool.h"
diff --git a/base/task/thread_pool/tracked_ref.h b/base/task/thread_pool/tracked_ref.h
index 191d265..14ad4bf 100644
--- a/base/task/thread_pool/tracked_ref.h
+++ b/base/task/thread_pool/tracked_ref.h
@@ -10,6 +10,7 @@
#include "base/gtest_prod_util.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/synchronization/waitable_event.h"
#include "base/template_util.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
@@ -119,8 +120,12 @@
factory_->live_tracked_refs_.Increment();
}
- T* ptr_;
- TrackedRefFactory<T>* factory_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION T* ptr_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION TrackedRefFactory<T>* factory_;
};
// TrackedRefFactory<T> should be the last member of T.
diff --git a/base/task/thread_pool/tracked_ref_unittest.cc b/base/task/thread_pool/tracked_ref_unittest.cc
index a846646..2c29b00 100644
--- a/base/task/thread_pool/tracked_ref_unittest.cc
+++ b/base/task/thread_pool/tracked_ref_unittest.cc
@@ -8,7 +8,7 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/synchronization/atomic_flag.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread.h"
diff --git a/base/task/thread_pool/worker_thread.cc b/base/task/thread_pool/worker_thread.cc
index 645abd2..85fc6e5 100644
--- a/base/task/thread_pool/worker_thread.cc
+++ b/base/task/thread_pool/worker_thread.cc
@@ -12,11 +12,11 @@
#include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
#include "base/allocator/partition_allocator/partition_alloc_config.h"
-#include "base/callback_helpers.h"
#include "base/check_op.h"
#include "base/compiler_specific.h"
#include "base/debug/alias.h"
#include "base/feature_list.h"
+#include "base/functional/callback_helpers.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/task_features.h"
#include "base/task/thread_pool/environment_config.h"
diff --git a/base/task/thread_pool/worker_thread_unittest.cc b/base/task/thread_pool/worker_thread_unittest.cc
index fd7e9b7..28cb0e0 100644
--- a/base/task/thread_pool/worker_thread_unittest.cc
+++ b/base/task/thread_pool/worker_thread_unittest.cc
@@ -15,9 +15,9 @@
#include "base/allocator/partition_allocator/partition_alloc_config.h"
#include "base/allocator/partition_allocator/shim/allocator_shim.h"
#include "base/allocator/partition_allocator/shim/allocator_shim_default_dispatch_to_partition_alloc.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/compiler_specific.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
diff --git a/base/task/thread_pool_unittest.cc b/base/task/thread_pool_unittest.cc
index da265c5..4f9d3fe 100644
--- a/base/task/thread_pool_unittest.cc
+++ b/base/task/thread_pool_unittest.cc
@@ -4,7 +4,7 @@
#include "base/task/thread_pool.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/run_loop.h"
#include "base/task/bind_post_task.h"
diff --git a/base/android/java/src/org/chromium/base/multidex/ChromiumMultiDexInstaller.java b/base/test/android/java/src/org/chromium/base/multidex/ChromiumMultiDexInstaller.java
similarity index 100%
rename from base/android/java/src/org/chromium/base/multidex/ChromiumMultiDexInstaller.java
rename to base/test/android/java/src/org/chromium/base/multidex/ChromiumMultiDexInstaller.java
diff --git a/base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java b/base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java
index 47adda5..df9b013 100644
--- a/base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java
+++ b/base/test/android/javatests/src/org/chromium/base/test/BaseJUnit4ClassRunner.java
@@ -236,7 +236,8 @@
*/
@CallSuper
protected List<TestRule> getDefaultTestRules() {
- return Arrays.asList(new BaseJUnit4TestRule(), new MockitoErrorHandler());
+ return Arrays.asList(new BaseJUnit4TestRule(), new MockitoErrorHandler(),
+ new UnitTestLifetimeAssertRule());
}
/**
diff --git a/base/test/android/javatests/src/org/chromium/base/test/UnitTestLifetimeAssertRule.java b/base/test/android/javatests/src/org/chromium/base/test/UnitTestLifetimeAssertRule.java
new file mode 100644
index 0000000..6b5f1d2
--- /dev/null
+++ b/base/test/android/javatests/src/org/chromium/base/test/UnitTestLifetimeAssertRule.java
@@ -0,0 +1,33 @@
+// 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.
+
+package org.chromium.base.test;
+
+import org.junit.rules.TestRule;
+import org.junit.runner.Description;
+import org.junit.runners.model.Statement;
+
+import org.chromium.base.LifetimeAssert;
+import org.chromium.base.test.util.Batch;
+import org.chromium.base.test.util.RequiresRestart;
+
+/**
+ * TestRule used to ensure we don't leak LifetimeAsserts in unit tests.
+ */
+public final class UnitTestLifetimeAssertRule implements TestRule {
+ @Override
+ public Statement apply(Statement base, Description description) {
+ return new Statement() {
+ @Override
+ public void evaluate() throws Throwable {
+ base.evaluate();
+ Batch annotation = description.getTestClass().getAnnotation(Batch.class);
+ if (annotation != null && annotation.value().equals(Batch.UNIT_TESTS)) {
+ if (description.getAnnotation(RequiresRestart.class) != null) return;
+ LifetimeAssert.assertAllInstancesDestroyedForTesting();
+ }
+ }
+ };
+ }
+}
diff --git a/base/test/bind.cc b/base/test/bind.cc
index e90dd31..707df71 100644
--- a/base/test/bind.cc
+++ b/base/test/bind.cc
@@ -6,8 +6,8 @@
#include <string>
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/strings/string_piece.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/test/bind.h b/base/test/bind.h
index 1d3b74c..f034763 100644
--- a/base/test/bind.h
+++ b/base/test/bind.h
@@ -8,7 +8,7 @@
#include <type_traits>
#include <utility>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/strings/string_piece.h"
namespace base {
diff --git a/base/test/gmock_callback_support.h b/base/test/gmock_callback_support.h
index af8b2cb..fb99024 100644
--- a/base/test/gmock_callback_support.h
+++ b/base/test/gmock_callback_support.h
@@ -10,7 +10,7 @@
#include <type_traits>
#include <utility>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
#include "testing/gmock/include/gmock/gmock.h"
diff --git a/base/test/gmock_callback_support_unittest.cc b/base/test/gmock_callback_support_unittest.cc
index 5441c10..e064e0f 100644
--- a/base/test/gmock_callback_support_unittest.cc
+++ b/base/test/gmock_callback_support_unittest.cc
@@ -6,8 +6,8 @@
#include <memory>
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/test/gtest_links_unittest.cc b/base/test/gtest_links_unittest.cc
index 239b6b2..e9cb0f2 100644
--- a/base/test/gtest_links_unittest.cc
+++ b/base/test/gtest_links_unittest.cc
@@ -4,20 +4,33 @@
#include "base/test/gtest_links.h"
+#include "base/command_line.h"
#include "base/test/gtest_util.h"
+#include "base/test/test_switches.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
-TEST(GtestLinksTest, AddInvalidLink) {
+class GtestLinksTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kTestLauncherOutput)) {
+ GTEST_SKIP() << "XmlUnitTestResultPrinterTest is not initialized "
+ << "for single process tests.";
+ }
+ }
+};
+
+TEST_F(GtestLinksTest, AddInvalidLink) {
EXPECT_DCHECK_DEATH(AddLinkToTestResult("unique_link", "invalid`"));
}
-TEST(GtestLinksTest, AddInvalidName) {
+TEST_F(GtestLinksTest, AddInvalidName) {
EXPECT_DCHECK_DEATH(AddLinkToTestResult("invalid-name", "http://google.com"));
}
-TEST(GtestLinksTest, AddValidLink) {
+TEST_F(GtestLinksTest, AddValidLink) {
AddLinkToTestResult("name", "http://google.com");
}
diff --git a/base/test/gtest_tags_unittest.cc b/base/test/gtest_tags_unittest.cc
index e19606c..4293d2b 100644
--- a/base/test/gtest_tags_unittest.cc
+++ b/base/test/gtest_tags_unittest.cc
@@ -4,16 +4,29 @@
#include "base/test/gtest_tags.h"
+#include "base/command_line.h"
#include "base/test/gtest_util.h"
+#include "base/test/test_switches.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
-TEST(GtestTagsTest, AddInvalidName) {
+class GtestTagsTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kTestLauncherOutput)) {
+ GTEST_SKIP() << "XmlUnitTestResultPrinterTest is not initialized "
+ << "for single process tests.";
+ }
+ }
+};
+
+TEST_F(GtestTagsTest, AddInvalidName) {
EXPECT_DCHECK_DEATH(AddTagToTestResult("", "value"));
}
-TEST(GtestTagsTest, AddValidTag) {
+TEST_F(GtestTagsTest, AddValidTag) {
AddTagToTestResult("name", "value");
}
diff --git a/base/test/gtest_xml_unittest_result_printer_unittest.cc b/base/test/gtest_xml_unittest_result_printer_unittest.cc
index 05eb5e8..5286db1 100644
--- a/base/test/gtest_xml_unittest_result_printer_unittest.cc
+++ b/base/test/gtest_xml_unittest_result_printer_unittest.cc
@@ -14,7 +14,18 @@
namespace base {
-TEST(XmlUnitTestResultPrinterTest, LinkInXmlFile) {
+class XmlUnitTestResultPrinterTest : public ::testing::Test {
+ public:
+ void SetUp() override {
+ if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
+ switches::kTestLauncherOutput)) {
+ GTEST_SKIP() << "XmlUnitTestResultPrinterTest is not initialized "
+ << "for single process tests.";
+ }
+ }
+};
+
+TEST_F(XmlUnitTestResultPrinterTest, LinkInXmlFile) {
XmlUnitTestResultPrinter::Get()->AddLink("unique_link", "http://google.com");
std::string file_path =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
@@ -31,7 +42,7 @@
<< expected_content << " not found in " << content;
}
-TEST(XmlUnitTestResultPrinterTest, EscapedLinkInXmlFile) {
+TEST_F(XmlUnitTestResultPrinterTest, EscapedLinkInXmlFile) {
XmlUnitTestResultPrinter::Get()->AddLink(
"unique_link", "http://google.com/path?id=\"'<>&\"");
std::string file_path =
@@ -49,7 +60,7 @@
<< expected_content << " not found in " << content;
}
-TEST(XmlUnitTestResultPrinterTest, TagInXmlFile) {
+TEST_F(XmlUnitTestResultPrinterTest, TagInXmlFile) {
XmlUnitTestResultPrinter::Get()->AddTag("tag_name", "tag_value");
std::string file_path =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc
index 125470c..98aaabe 100644
--- a/base/test/launcher/test_launcher.cc
+++ b/base/test/launcher/test_launcher.cc
@@ -14,7 +14,6 @@
#include <utility>
#include "base/at_exit.h"
-#include "base/bind.h"
#include "base/clang_profiling_buildflags.h"
#include "base/command_line.h"
#include "base/containers/adapters.h"
@@ -25,6 +24,7 @@
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
#include "base/format_macros.h"
+#include "base/functional/bind.h"
#include "base/hash/hash.h"
#include "base/lazy_instance.h"
#include "base/location.h"
diff --git a/base/test/launcher/test_launcher_unittest.cc b/base/test/launcher/test_launcher_unittest.cc
index e534155..6f157ba 100644
--- a/base/test/launcher/test_launcher_unittest.cc
+++ b/base/test/launcher/test_launcher_unittest.cc
@@ -7,11 +7,11 @@
#include <stddef.h>
#include "base/base64.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/no_destructor.h"
#include "base/process/launch.h"
diff --git a/base/test/launcher/test_results_tracker.h b/base/test/launcher/test_results_tracker.h
index a304d7b..e25dfa6 100644
--- a/base/test/launcher/test_results_tracker.h
+++ b/base/test/launcher/test_results_tracker.h
@@ -11,7 +11,7 @@
#include <utility>
#include <vector>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/test/launcher/test_result.h"
diff --git a/base/test/launcher/unit_test_launcher.cc b/base/test/launcher/unit_test_launcher.cc
index 343a948..522e95e 100644
--- a/base/test/launcher/unit_test_launcher.cc
+++ b/base/test/launcher/unit_test_launcher.cc
@@ -9,13 +9,13 @@
#include <utility>
#include "base/base_switches.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/debug/debugger.h"
#include "base/files/file_util.h"
#include "base/format_macros.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/message_loop/message_pump_type.h"
diff --git a/base/test/launcher/unit_test_launcher.h b/base/test/launcher/unit_test_launcher.h
index 7f66dbb..38f0eaf 100644
--- a/base/test/launcher/unit_test_launcher.h
+++ b/base/test/launcher/unit_test_launcher.h
@@ -10,9 +10,9 @@
#include <string>
#include <vector>
-#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/test/launcher/test_launcher.h"
#include "build/build_config.h"
diff --git a/base/test/metrics/user_action_tester.cc b/base/test/metrics/user_action_tester.cc
index 3bbcaaa..5b5e984 100644
--- a/base/test/metrics/user_action_tester.cc
+++ b/base/test/metrics/user_action_tester.cc
@@ -4,8 +4,8 @@
#include "base/test/metrics/user_action_tester.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/test/test_simple_task_runner.h"
namespace base {
diff --git a/base/test/mock_callback.h b/base/test/mock_callback.h
index 8493ddf..4b7d854 100644
--- a/base/test/mock_callback.h
+++ b/base/test/mock_callback.h
@@ -36,8 +36,8 @@
#ifndef BASE_TEST_MOCK_CALLBACK_H_
#define BASE_TEST_MOCK_CALLBACK_H_
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace base {
diff --git a/base/test/mock_callback.h.pump b/base/test/mock_callback.h.pump
index 17f24f1..f0d8c4f 100644
--- a/base/test/mock_callback.h.pump
+++ b/base/test/mock_callback.h.pump
@@ -43,8 +43,8 @@
#ifndef BASE_TEST_MOCK_CALLBACK_H_
#define BASE_TEST_MOCK_CALLBACK_H_
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace base {
diff --git a/base/test/mock_callback_unittest.cc b/base/test/mock_callback_unittest.cc
index 61d9dc0..a43e51a 100644
--- a/base/test/mock_callback_unittest.cc
+++ b/base/test/mock_callback_unittest.cc
@@ -4,7 +4,7 @@
#include "base/test/mock_callback.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "testing/gmock/include/gmock/gmock.h"
using testing::InSequence;
diff --git a/base/test/null_task_runner.h b/base/test/null_task_runner.h
index 390025d..1efc6ab 100644
--- a/base/test/null_task_runner.h
+++ b/base/test/null_task_runner.h
@@ -5,8 +5,8 @@
#ifndef BASE_TEST_NULL_TASK_RUNNER_H_
#define BASE_TEST_NULL_TASK_RUNNER_H_
-#include "base/callback.h"
#include "base/compiler_specific.h"
+#include "base/functional/callback.h"
#include "base/task/single_thread_task_runner.h"
namespace base {
diff --git a/base/test/power_monitor_test.h b/base/test/power_monitor_test.h
index c4e2c9b..71c71c9 100644
--- a/base/test/power_monitor_test.h
+++ b/base/test/power_monitor_test.h
@@ -5,6 +5,7 @@
#ifndef BASE_TEST_POWER_MONITOR_TEST_H_
#define BASE_TEST_POWER_MONITOR_TEST_H_
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_monitor_source.h"
#include "base/power_monitor/power_observer.h"
@@ -53,7 +54,10 @@
private:
// Owned by PowerMonitor.
- PowerMonitorTestSource* power_monitor_test_source_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION PowerMonitorTestSource* power_monitor_test_source_ =
+ nullptr;
};
class PowerMonitorTestObserver : public PowerSuspendObserver,
diff --git a/base/test/rectify_callback_unittest.cc b/base/test/rectify_callback_unittest.cc
index 66ec16a..7181e5a 100644
--- a/base/test/rectify_callback_unittest.cc
+++ b/base/test/rectify_callback_unittest.cc
@@ -7,8 +7,6 @@
#include <sstream>
#include <utility>
-#include "base/callback.h"
-#include "base/callback_forward.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_forward.h"
diff --git a/base/test/run_all_unittests.cc b/base/test/run_all_unittests.cc
index 572030e..4f0611a 100644
--- a/base/test/run_all_unittests.cc
+++ b/base/test/run_all_unittests.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 "base/bind.h"
+#include "base/functional/bind.h"
#include "base/metrics/persistent_histogram_allocator.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/test_suite.h"
diff --git a/base/test/scoped_mock_time_message_loop_task_runner.cc b/base/test/scoped_mock_time_message_loop_task_runner.cc
index e4486e4..2ff81f1 100644
--- a/base/test/scoped_mock_time_message_loop_task_runner.cc
+++ b/base/test/scoped_mock_time_message_loop_task_runner.cc
@@ -4,8 +4,8 @@
#include "base/test/scoped_mock_time_message_loop_task_runner.h"
-#include "base/bind.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
#include "base/run_loop.h"
#include "base/task/current_thread.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/test/scoped_mock_time_message_loop_task_runner_unittest.cc b/base/test/scoped_mock_time_message_loop_task_runner_unittest.cc
index 93610d9..e05f374 100644
--- a/base/test/scoped_mock_time_message_loop_task_runner_unittest.cc
+++ b/base/test/scoped_mock_time_message_loop_task_runner_unittest.cc
@@ -6,9 +6,9 @@
#include <memory>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/containers/circular_deque.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/task/current_thread.h"
diff --git a/base/test/scoped_run_loop_timeout.cc b/base/test/scoped_run_loop_timeout.cc
index 39ee1db..7ad61cf 100644
--- a/base/test/scoped_run_loop_timeout.cc
+++ b/base/test/scoped_run_loop_timeout.cc
@@ -4,8 +4,8 @@
#include "base/test/scoped_run_loop_timeout.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/strings/strcat.h"
diff --git a/base/test/scoped_run_loop_timeout.h b/base/test/scoped_run_loop_timeout.h
index a34c5b5..46b88e0 100644
--- a/base/test/scoped_run_loop_timeout.h
+++ b/base/test/scoped_run_loop_timeout.h
@@ -7,10 +7,11 @@
#include <string>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/gtest_prod_util.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/run_loop.h"
#include "base/time/time.h"
@@ -87,7 +88,9 @@
// Exposes the RunLoopTimeout to the friend tests (see above).
static const RunLoop::RunLoopTimeout* GetTimeoutForCurrentThread();
- const RunLoop::RunLoopTimeout* const nested_timeout_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION const RunLoop::RunLoopTimeout* const nested_timeout_;
RunLoop::RunLoopTimeout run_timeout_;
};
diff --git a/base/test/scoped_run_loop_timeout_unittest.cc b/base/test/scoped_run_loop_timeout_unittest.cc
index 20f495f..1e87d42 100644
--- a/base/test/scoped_run_loop_timeout_unittest.cc
+++ b/base/test/scoped_run_loop_timeout_unittest.cc
@@ -4,8 +4,8 @@
#include "base/test/scoped_run_loop_timeout.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/task/sequenced_task_runner.h"
#include "base/test/bind.h"
diff --git a/base/test/sequenced_task_runner_test_template.h b/base/test/sequenced_task_runner_test_template.h
index a495aa7..7a2ec12 100644
--- a/base/test/sequenced_task_runner_test_template.h
+++ b/base/test/sequenced_task_runner_test_template.h
@@ -14,8 +14,8 @@
#include <iosfwd>
#include <vector>
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
diff --git a/base/test/task_environment.cc b/base/test/task_environment.cc
index 70dd416..4db778d 100644
--- a/base/test/task_environment.cc
+++ b/base/test/task_environment.cc
@@ -8,9 +8,9 @@
#include <memory>
#include <ostream>
-#include "base/callback_helpers.h"
#include "base/check.h"
#include "base/debug/stack_trace.h"
+#include "base/functional/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/logging.h"
diff --git a/base/test/task_environment.h b/base/test/task_environment.h
index 9cacf2c..ffbc1a7 100644
--- a/base/test/task_environment.h
+++ b/base/test/task_environment.h
@@ -8,6 +8,7 @@
#include <memory>
#include "base/compiler_specific.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/ref_counted.h"
#include "base/observer_list_types.h"
#include "base/task/lazy_thread_pool_task_runner.h"
@@ -444,7 +445,9 @@
#endif
// Owned by the ThreadPoolInstance.
- TestTaskTracker* task_tracker_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION TestTaskTracker* task_tracker_ = nullptr;
// Ensures destruction of lazy TaskRunners when this is destroyed.
std::unique_ptr<base::internal::ScopedLazyTaskRunnerListForTesting>
diff --git a/base/test/task_environment_unittest.cc b/base/test/task_environment_unittest.cc
index 8d63331..815e96d 100644
--- a/base/test/task_environment_unittest.cc
+++ b/base/test/task_environment_unittest.cc
@@ -8,11 +8,11 @@
#include <memory>
#include "base/atomicops.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/cancelable_callback.h"
#include "base/check.h"
#include "base/debug/debugger.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "base/synchronization/atomic_flag.h"
diff --git a/base/test/task_runner_test_template.h b/base/test/task_runner_test_template.h
index 653115b..8eca3b4 100644
--- a/base/test/task_runner_test_template.h
+++ b/base/test/task_runner_test_template.h
@@ -50,8 +50,8 @@
#include <cstddef>
#include <map>
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/condition_variable.h"
diff --git a/base/test/test_future.h b/base/test/test_future.h
index 4a48669..13aa0b4 100644
--- a/base/test/test_future.h
+++ b/base/test/test_future.h
@@ -8,9 +8,9 @@
#include <memory>
#include <string>
-#include "base/bind.h"
-#include "base/callback_forward.h"
#include "base/check.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/sequence_checker.h"
diff --git a/base/test/test_io_thread.h b/base/test/test_io_thread.h
index e60958a..ce895a1 100644
--- a/base/test/test_io_thread.h
+++ b/base/test/test_io_thread.h
@@ -5,8 +5,8 @@
#ifndef BASE_TEST_TEST_IO_THREAD_H_
#define BASE_TEST_TEST_IO_THREAD_H_
-#include "base/callback_forward.h"
#include "base/compiler_specific.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/ref_counted.h"
#include "base/task/task_runner.h"
#include "base/threading/thread.h"
diff --git a/base/test/test_mock_time_task_runner.h b/base/test/test_mock_time_task_runner.h
index d011061..366b346 100644
--- a/base/test/test_mock_time_task_runner.h
+++ b/base/test/test_mock_time_task_runner.h
@@ -11,9 +11,9 @@
#include <queue>
#include <vector>
-#include "base/callback.h"
-#include "base/callback_helpers.h"
#include "base/containers/circular_deque.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/synchronization/condition_variable.h"
diff --git a/base/test/test_mock_time_task_runner_unittest.cc b/base/test/test_mock_time_task_runner_unittest.cc
index 4482495..fb8fd7a 100644
--- a/base/test/test_mock_time_task_runner_unittest.cc
+++ b/base/test/test_mock_time_task_runner_unittest.cc
@@ -4,9 +4,9 @@
#include "base/test/test_mock_time_task_runner.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/cancelable_callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/test/test_pending_task.h b/base/test/test_pending_task.h
index 685347d..2f16ad4 100644
--- a/base/test/test_pending_task.h
+++ b/base/test/test_pending_task.h
@@ -7,7 +7,7 @@
#include <string>
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/time/time.h"
#include "base/trace_event/base_tracing_forward.h"
diff --git a/base/test/test_pending_task_unittest.cc b/base/test/test_pending_task_unittest.cc
index 94c5278..96d6235 100644
--- a/base/test/test_pending_task_unittest.cc
+++ b/base/test/test_pending_task_unittest.cc
@@ -4,7 +4,7 @@
#include "base/test/test_pending_task.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/trace_event/base_tracing.h"
#include "base/tracing_buildflags.h"
#include "testing/gmock/include/gmock/gmock.h"
diff --git a/base/test/test_simple_task_runner.h b/base/test/test_simple_task_runner.h
index ccd8334..4639ab0 100644
--- a/base/test/test_simple_task_runner.h
+++ b/base/test/test_simple_task_runner.h
@@ -5,9 +5,9 @@
#ifndef BASE_TEST_TEST_SIMPLE_TASK_RUNNER_H_
#define BASE_TEST_TEST_SIMPLE_TASK_RUNNER_H_
-#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/containers/circular_deque.h"
+#include "base/functional/callback.h"
#include "base/synchronization/lock.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/test_pending_task.h"
diff --git a/base/test/test_suite.cc b/base/test/test_suite.cc
index bbc6f60..287c6ab 100644
--- a/base/test/test_suite.cc
+++ b/base/test/test_suite.cc
@@ -12,7 +12,6 @@
#include "base/at_exit.h"
#include "base/base_paths.h"
#include "base/base_switches.h"
-#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/profiler.h"
@@ -20,10 +19,12 @@
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
#include "base/i18n/icu_util.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
#include "base/process/launch.h"
@@ -210,10 +211,18 @@
}
private:
- FeatureList* feature_list_set_before_test_ = nullptr;
- FeatureList* feature_list_set_before_case_ = nullptr;
- ThreadPoolInstance* thread_pool_set_before_test_ = nullptr;
- ThreadPoolInstance* thread_pool_set_before_case_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION FeatureList* feature_list_set_before_test_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION FeatureList* feature_list_set_before_case_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION ThreadPoolInstance* thread_pool_set_before_test_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION ThreadPoolInstance* thread_pool_set_before_case_ = nullptr;
};
// iOS: base::Process is not available.
diff --git a/base/test/test_waitable_event_unittest.cc b/base/test/test_waitable_event_unittest.cc
index ea9dacb..7f501ae 100644
--- a/base/test/test_waitable_event_unittest.cc
+++ b/base/test/test_waitable_event_unittest.cc
@@ -4,7 +4,7 @@
#include "base/test/test_waitable_event.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/task/thread_pool.h"
#include "base/test/task_environment.h"
#include "base/threading/scoped_blocking_call_internal.h"
diff --git a/base/test/thread_test_helper.cc b/base/test/thread_test_helper.cc
index c635a6c..2e41863 100644
--- a/base/test/thread_test_helper.cc
+++ b/base/test/thread_test_helper.cc
@@ -6,7 +6,7 @@
#include <utility>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/threading/thread_restrictions.h"
diff --git a/base/test/trace_event_analyzer.cc b/base/test/trace_event_analyzer.cc
index 6a91308..d071168 100644
--- a/base/test/trace_event_analyzer.cc
+++ b/base/test/trace_event_analyzer.cc
@@ -9,7 +9,7 @@
#include <algorithm>
#include <set>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
diff --git a/base/test/trace_event_analyzer_unittest.cc b/base/test/trace_event_analyzer_unittest.cc
index 336cb09..fb08cca 100644
--- a/base/test/trace_event_analyzer_unittest.cc
+++ b/base/test/trace_event_analyzer_unittest.cc
@@ -7,7 +7,7 @@
#include <stddef.h>
#include <stdint.h>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/memory/ref_counted_memory.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/platform_thread.h"
@@ -127,18 +127,7 @@
TEST_F(TraceEventAnalyzerTest, QueryEventMember) {
ManualSetUp();
- TraceEvent event;
- event.thread.process_id = 3;
- event.thread.thread_id = 4;
- event.timestamp = 1.5;
- event.phase = TRACE_EVENT_PHASE_BEGIN;
- event.category = "category";
- event.name = "name";
- event.id = "1";
- event.arg_numbers["num"] = 7.0;
- event.arg_strings["str"] = "the string";
-
- // Other event with all different members:
+ // Other event with all different members. Must outlive `event`.
TraceEvent other;
other.thread.process_id = 5;
other.thread.thread_id = 6;
@@ -150,6 +139,16 @@
other.arg_numbers["num2"] = 8.0;
other.arg_strings["str2"] = "the string 2";
+ TraceEvent event;
+ event.thread.process_id = 3;
+ event.thread.thread_id = 4;
+ event.timestamp = 1.5;
+ event.phase = TRACE_EVENT_PHASE_BEGIN;
+ event.category = "category";
+ event.name = "name";
+ event.id = "1";
+ event.arg_numbers["num"] = 7.0;
+ event.arg_strings["str"] = "the string";
event.other_event = &other;
ASSERT_TRUE(event.has_other_event());
double duration = event.GetAbsTimeToOtherEvent();
diff --git a/base/test/trace_to_file.cc b/base/test/trace_to_file.cc
index 69db354..da2fb76 100644
--- a/base/test/trace_to_file.cc
+++ b/base/test/trace_to_file.cc
@@ -5,9 +5,9 @@
#include "base/test/trace_to_file.h"
#include "base/base_switches.h"
-#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
+#include "base/functional/bind.h"
#include "base/memory/ref_counted_memory.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/threading/counter_perftest.cc b/base/threading/counter_perftest.cc
index 5985603..db3b99d 100644
--- a/base/threading/counter_perftest.cc
+++ b/base/threading/counter_perftest.cc
@@ -6,7 +6,7 @@
#include <string>
#include "base/barrier_closure.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
diff --git a/base/threading/hang_watcher.cc b/base/threading/hang_watcher.cc
index 38c60d7..31e0b7d 100644
--- a/base/threading/hang_watcher.cc
+++ b/base/threading/hang_watcher.cc
@@ -7,14 +7,14 @@
#include <atomic>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/containers/flat_map.h"
#include "base/debug/alias.h"
#include "base/debug/crash_logging.h"
#include "base/debug/dump_without_crashing.h"
#include "base/debug/leak_annotations.h"
#include "base/feature_list.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
diff --git a/base/threading/hang_watcher.h b/base/threading/hang_watcher.h
index 2e4afac..902bb2f 100644
--- a/base/threading/hang_watcher.h
+++ b/base/threading/hang_watcher.h
@@ -14,15 +14,16 @@
#include "base/atomicops.h"
#include "base/base_export.h"
#include "base/bits.h"
-#include "base/callback.h"
-#include "base/callback_forward.h"
-#include "base/callback_helpers.h"
#include "base/compiler_specific.h"
#include "base/dcheck_is_on.h"
#include "base/debug/crash_logging.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_forward.h"
+#include "base/functional/callback_helpers.h"
#include "base/gtest_prod_util.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
#include "base/template_util.h"
@@ -98,7 +99,9 @@
#if DCHECK_IS_ON()
// The previous WatchHangsInScope created on this thread.
- WatchHangsInScope* previous_watch_hangs_in_scope_;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION WatchHangsInScope* previous_watch_hangs_in_scope_;
#endif
};
diff --git a/base/threading/hang_watcher_unittest.cc b/base/threading/hang_watcher_unittest.cc
index 065fcdc..960b849 100644
--- a/base/threading/hang_watcher_unittest.cc
+++ b/base/threading/hang_watcher_unittest.cc
@@ -7,9 +7,9 @@
#include <memory>
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
diff --git a/base/threading/platform_thread_unittest.cc b/base/threading/platform_thread_unittest.cc
index 48b558f..a4e34ee 100644
--- a/base/threading/platform_thread_unittest.cc
+++ b/base/threading/platform_thread_unittest.cc
@@ -488,8 +488,13 @@
ThreadPriorityForTest::kBackground);
TestPriorityResultingFromThreadType(ThreadType::kUtility,
ThreadPriorityForTest::kUtility);
+#if BUILDFLAG(IS_APPLE)
+ TestPriorityResultingFromThreadType(ThreadType::kResourceEfficient,
+ ThreadPriorityForTest::kUtility);
+#else
TestPriorityResultingFromThreadType(ThreadType::kResourceEfficient,
ThreadPriorityForTest::kNormal);
+#endif // BUILDFLAG(IS_APPLE)
TestPriorityResultingFromThreadType(ThreadType::kDefault,
ThreadPriorityForTest::kNormal);
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS)
diff --git a/base/threading/post_task_and_reply_impl.cc b/base/threading/post_task_and_reply_impl.cc
index 88e8cff..fb72de3 100644
--- a/base/threading/post_task_and_reply_impl.cc
+++ b/base/threading/post_task_and_reply_impl.cc
@@ -6,9 +6,9 @@
#include <utility>
-#include "base/bind.h"
#include "base/check_op.h"
#include "base/debug/leak_annotations.h"
+#include "base/functional/bind.h"
#include "base/memory/ref_counted.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool/thread_pool_instance.h"
diff --git a/base/threading/post_task_and_reply_impl.h b/base/threading/post_task_and_reply_impl.h
index 8f1a2a7..9e3fda1 100644
--- a/base/threading/post_task_and_reply_impl.h
+++ b/base/threading/post_task_and_reply_impl.h
@@ -8,7 +8,7 @@
#define BASE_THREADING_POST_TASK_AND_REPLY_IMPL_H_
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/location.h"
namespace base {
diff --git a/base/threading/post_task_and_reply_impl_unittest.cc b/base/threading/post_task_and_reply_impl_unittest.cc
index f0f5546..e90ea9f 100644
--- a/base/threading/post_task_and_reply_impl_unittest.cc
+++ b/base/threading/post_task_and_reply_impl_unittest.cc
@@ -7,8 +7,8 @@
#include <utility>
#include "base/auto_reset.h"
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/threading/scoped_blocking_call.h b/base/threading/scoped_blocking_call.h
index 7094096..0242c9a 100644
--- a/base/threading/scoped_blocking_call.h
+++ b/base/threading/scoped_blocking_call.h
@@ -6,7 +6,7 @@
#define BASE_THREADING_SCOPED_BLOCKING_CALL_H_
#include "base/base_export.h"
-#include "base/callback_forward.h"
+#include "base/functional/callback_forward.h"
#include "base/location.h"
#include "base/strings/string_piece.h"
#include "base/threading/scoped_blocking_call_internal.h"
diff --git a/base/threading/scoped_blocking_call_internal.cc b/base/threading/scoped_blocking_call_internal.cc
index d594778..3128c90 100644
--- a/base/threading/scoped_blocking_call_internal.cc
+++ b/base/threading/scoped_blocking_call_internal.cc
@@ -7,9 +7,9 @@
#include <algorithm>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/no_destructor.h"
#include "base/numerics/safe_conversions.h"
diff --git a/base/threading/scoped_blocking_call_internal.h b/base/threading/scoped_blocking_call_internal.h
index 25534ff..99c7ab0 100644
--- a/base/threading/scoped_blocking_call_internal.h
+++ b/base/threading/scoped_blocking_call_internal.h
@@ -6,8 +6,8 @@
#define BASE_THREADING_SCOPED_BLOCKING_CALL_INTERNAL_H_
#include "base/base_export.h"
-#include "base/callback_forward.h"
#include "base/debug/activity_tracker.h"
+#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/lock.h"
diff --git a/base/threading/scoped_blocking_call_unittest.cc b/base/threading/scoped_blocking_call_unittest.cc
index f12e8c8..f4f29c6 100644
--- a/base/threading/scoped_blocking_call_unittest.cc
+++ b/base/threading/scoped_blocking_call_unittest.cc
@@ -9,8 +9,8 @@
#include <vector>
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/task/thread_pool.h"
#include "base/task/thread_pool/environment_config.h"
#include "base/task/thread_pool/thread_pool_impl.h"
diff --git a/base/threading/sequence_bound.h b/base/threading/sequence_bound.h
index e848fff..02380d7 100644
--- a/base/threading/sequence_bound.h
+++ b/base/threading/sequence_bound.h
@@ -52,9 +52,9 @@
// }
// };
//
-// // SequenceBound itself is owned on `SequencedTaskRunnerHandle::Get()`.
-// // The managed Database instance managed by it is constructed and owned on
-// // `GetDBTaskRunner()`.
+// // SequenceBound itself is owned on
+// // `SequencedTaskRunner::GetCurrentDefault()`. The managed Database
+// // instance managed by it is constructed and owned on `GetDBTaskRunner()`.
// base::SequenceBound<Database> db(GetDBTaskRunner());
//
// // `Database::Query()` runs on `GetDBTaskRunner()`, but
diff --git a/base/threading/sequenced_task_runner_handle.cc b/base/threading/sequenced_task_runner_handle.cc
deleted file mode 100644
index 2ab4b64..0000000
--- a/base/threading/sequenced_task_runner_handle.cc
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2015 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/threading/sequenced_task_runner_handle.h"
-
-namespace base {
-
-// DEPRECATED: Use SequencedTaskRunner::GetCurrentDefault instead
-// static
-const scoped_refptr<SequencedTaskRunner>& SequencedTaskRunnerHandle::Get() {
- return SequencedTaskRunner::GetCurrentDefault();
-}
-
-// DEPRECATED: Use SequencedTaskRunner::HasCurrentDefault instead
-// static
-bool SequencedTaskRunnerHandle::IsSet() {
- return SequencedTaskRunner::HasCurrentDefault();
-}
-
-} // namespace base
diff --git a/base/threading/sequenced_task_runner_handle.h b/base/threading/sequenced_task_runner_handle.h
deleted file mode 100644
index 9b555d7..0000000
--- a/base/threading/sequenced_task_runner_handle.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2015 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_THREADING_SEQUENCED_TASK_RUNNER_HANDLE_H_
-#define BASE_THREADING_SEQUENCED_TASK_RUNNER_HANDLE_H_
-
-#include "base/base_export.h"
-#include "base/memory/scoped_refptr.h"
-#include "base/task/sequenced_task_runner.h"
-
-namespace base {
-
-class ThreadTaskRunnerHandle;
-
-class BASE_EXPORT SequencedTaskRunnerHandle {
- public:
- // DEPRECATED: Use SequencedTaskRunner::GetCurrentDefault() instead.
- // Returns a SequencedTaskRunner which guarantees that posted tasks will only
- // run after the current task is finished and will satisfy a SequenceChecker.
- // It should only be called if IsSet() returns true (see the comment there for
- // the requirements).
- [[nodiscard]] static const scoped_refptr<SequencedTaskRunner>& Get();
-
- // DEPRECATED: Use SequencedTaskRunner::HasCurrentDefault() instead.
- // Returns true if one of the following conditions is fulfilled:
- // a) A SequencedTaskRunner has been assigned to the current thread by
- // instantiating a SequencedTaskRunnerHandle.
- // b) The current thread has a ThreadTaskRunnerHandle (which includes any
- // thread that has a MessageLoop associated with it).
- [[nodiscard]] static bool IsSet();
-
- explicit SequencedTaskRunnerHandle(
- scoped_refptr<SequencedTaskRunner> task_runner)
- : contained_current_default_(std::move(task_runner)) {}
-
- SequencedTaskRunnerHandle(const SequencedTaskRunnerHandle&) = delete;
- SequencedTaskRunnerHandle& operator=(const SequencedTaskRunnerHandle&) =
- delete;
-
- ~SequencedTaskRunnerHandle() = default;
-
- private:
- SequencedTaskRunner::CurrentDefaultHandle contained_current_default_;
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_SEQUENCED_TASK_RUNNER_HANDLE_H_
diff --git a/base/threading/sequenced_task_runner_handle_unittest.cc b/base/threading/sequenced_task_runner_handle_unittest.cc
deleted file mode 100644
index 569df19..0000000
--- a/base/threading/sequenced_task_runner_handle_unittest.cc
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright 2015 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/threading/sequenced_task_runner_handle.h"
-
-#include <memory>
-#include <utility>
-
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/location.h"
-#include "base/memory/ref_counted.h"
-#include "base/run_loop.h"
-#include "base/sequence_checker_impl.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/task/sequenced_task_runner.h"
-#include "base/task/thread_pool.h"
-#include "base/test/task_environment.h"
-#include "base/test/test_simple_task_runner.h"
-#include "base/threading/thread_task_runner_handle.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace base {
-namespace {
-
-class SequencedTaskRunnerHandleTest : public ::testing::Test {
- protected:
- // Verifies that the context it runs on has a SequencedTaskRunnerHandle
- // and that posting to it results in the posted task running in that same
- // context (sequence).
- static void VerifyCurrentSequencedTaskRunner() {
- ASSERT_TRUE(SequencedTaskRunnerHandle::IsSet());
- scoped_refptr<SequencedTaskRunner> task_runner =
- SequencedTaskRunnerHandle::Get();
- ASSERT_TRUE(task_runner);
-
- // Use SequenceCheckerImpl to make sure it's not a no-op in Release builds.
- std::unique_ptr<SequenceCheckerImpl> sequence_checker(
- new SequenceCheckerImpl);
- task_runner->PostTask(
- FROM_HERE,
- base::BindOnce(&SequencedTaskRunnerHandleTest::CheckValidSequence,
- std::move(sequence_checker)));
- }
-
- static void CheckValidSequence(
- std::unique_ptr<SequenceCheckerImpl> sequence_checker) {
- EXPECT_TRUE(sequence_checker->CalledOnValidSequence());
- }
-
- base::test::TaskEnvironment task_environment_;
-};
-
-TEST_F(SequencedTaskRunnerHandleTest, FromTaskEnvironment) {
- VerifyCurrentSequencedTaskRunner();
- RunLoop().RunUntilIdle();
-}
-
-TEST_F(SequencedTaskRunnerHandleTest, FromThreadPoolSequencedTask) {
- base::ThreadPool::CreateSequencedTaskRunner({})->PostTask(
- FROM_HERE,
- base::BindOnce(
- &SequencedTaskRunnerHandleTest::VerifyCurrentSequencedTaskRunner));
- task_environment_.RunUntilIdle();
-}
-
-TEST_F(SequencedTaskRunnerHandleTest, NoHandleFromUnsequencedTask) {
- base::ThreadPool::PostTask(base::BindOnce(
- []() { EXPECT_FALSE(SequencedTaskRunnerHandle::IsSet()); }));
- task_environment_.RunUntilIdle();
-}
-
-TEST(SequencedTaskRunnerHandleTestWithoutTaskEnvironment, FromHandleInScope) {
- scoped_refptr<SequencedTaskRunner> test_task_runner(new TestSimpleTaskRunner);
- EXPECT_FALSE(SequencedTaskRunnerHandle::IsSet());
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
- {
- SequencedTaskRunnerHandle handle(test_task_runner);
- EXPECT_TRUE(SequencedTaskRunnerHandle::IsSet());
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(test_task_runner, SequencedTaskRunnerHandle::Get());
- }
- EXPECT_FALSE(SequencedTaskRunnerHandle::IsSet());
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
-}
-
-} // namespace
-} // namespace base
diff --git a/base/threading/thread.cc b/base/threading/thread.cc
index c07e124..174beed 100644
--- a/base/threading/thread.cc
+++ b/base/threading/thread.cc
@@ -8,8 +8,8 @@
#include <type_traits>
#include <utility>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/logging.h"
@@ -376,7 +376,7 @@
// Lazily initialize the |message_loop| so that it can run on this thread.
DCHECK(delegate_);
- // This binds CurrentThread and ThreadTaskRunnerHandle.
+ // This binds CurrentThread and SingleThreadTaskRunner::CurrentDefaultHandle.
delegate_->BindToCurrentThread(timer_slack_);
DCHECK(CurrentThread::Get());
DCHECK(SingleThreadTaskRunner::HasCurrentDefault());
diff --git a/base/threading/thread.h b/base/threading/thread.h
index 6b5768a..06dd702 100644
--- a/base/threading/thread.h
+++ b/base/threading/thread.h
@@ -11,8 +11,9 @@
#include <string>
#include "base/base_export.h"
-#include "base/callback.h"
#include "base/check.h"
+#include "base/functional/callback.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/message_loop/message_pump_type.h"
#include "base/message_loop/timer_slack.h"
#include "base/sequence_checker.h"
@@ -64,9 +65,9 @@
virtual scoped_refptr<SingleThreadTaskRunner> GetDefaultTaskRunner() = 0;
- // Binds a RunLoop::Delegate and TaskRunnerHandle to the thread. The
- // underlying MessagePump will have its |timer_slack| set to the specified
- // amount.
+ // Binds a RunLoop::Delegate and task runner CurrentDefaultHandle to the
+ // thread. The underlying MessagePump will have its |timer_slack| set to the
+ // specified amount.
virtual void BindToCurrentThread(TimerSlack timer_slack) = 0;
};
@@ -321,7 +322,9 @@
// The thread's Delegate and RunLoop are valid only while the thread is
// alive. Set by the created thread.
std::unique_ptr<Delegate> delegate_;
- RunLoop* run_loop_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION RunLoop* run_loop_ = nullptr;
// Stores Options::timer_slack_ until the sequence manager has been bound to
// a thread.
diff --git a/base/threading/thread_checker_impl.cc b/base/threading/thread_checker_impl.cc
index 48adb59..cb7eb30 100644
--- a/base/threading/thread_checker_impl.cc
+++ b/base/threading/thread_checker_impl.cc
@@ -86,8 +86,9 @@
// If this ThreadCheckerImpl is bound to a valid SequenceToken, it must be
// equal to the current SequenceToken and there must be a registered
- // ThreadTaskRunnerHandle. Otherwise, the fact that the current task runs on
- // the thread to which this ThreadCheckerImpl is bound is fortuitous.
+ // SingleThreadTaskRunner::CurrentDefaultHandle. Otherwise, the fact that
+ // the current task runs on the thread to which this ThreadCheckerImpl is
+ // bound is fortuitous.
if (sequence_token_.IsValid() &&
(sequence_token_ != SequenceToken::GetForCurrentThread() ||
!SingleThreadTaskRunner::HasCurrentDefault())) {
diff --git a/base/threading/thread_checker_unittest.cc b/base/threading/thread_checker_unittest.cc
index 38a0eab..b405bd8 100644
--- a/base/threading/thread_checker_unittest.cc
+++ b/base/threading/thread_checker_unittest.cc
@@ -6,8 +6,8 @@
#include <memory>
-#include "base/bind.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/sequence_token.h"
#include "base/task/single_thread_task_runner.h"
diff --git a/base/threading/thread_id_name_manager.h b/base/threading/thread_id_name_manager.h
index 620bb17..85063c8 100644
--- a/base/threading/thread_id_name_manager.h
+++ b/base/threading/thread_id_name_manager.h
@@ -10,7 +10,7 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/lock.h"
#include "base/threading/platform_thread.h"
diff --git a/base/threading/thread_local_storage_perftest.cc b/base/threading/thread_local_storage_perftest.cc
index 5d8f86b..9f5d1c0 100644
--- a/base/threading/thread_local_storage_perftest.cc
+++ b/base/threading/thread_local_storage_perftest.cc
@@ -7,9 +7,9 @@
#include <vector>
#include "base/barrier_closure.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/bind.h"
diff --git a/base/threading/thread_perftest.cc b/base/threading/thread_perftest.cc
index 11ef5e8..3c623f1 100644
--- a/base/threading/thread_perftest.cc
+++ b/base/threading/thread_perftest.cc
@@ -8,8 +8,8 @@
#include <vector>
#include "base/base_switches.h"
-#include "base/bind.h"
#include "base/command_line.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/synchronization/condition_variable.h"
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h
index 493cb7c..f5436c1 100644
--- a/base/threading/thread_restrictions.h
+++ b/base/threading/thread_restrictions.h
@@ -293,10 +293,10 @@
namespace leveldb::port {
class ScopedAllowWait;
} // namespace leveldb::port
-namespace location::nearby::chrome {
+namespace nearby::chrome {
class ScheduledExecutor;
class SubmittableExecutor;
-} // namespace location::nearby::chrome
+} // namespace nearby::chrome
namespace media {
class AudioInputDevice;
class AudioOutputDevice;
@@ -735,8 +735,8 @@
friend class history_report::HistoryReportJniBridge;
friend class internal::TaskTracker;
friend class leveldb::port::ScopedAllowWait;
- friend class location::nearby::chrome::ScheduledExecutor;
- friend class location::nearby::chrome::SubmittableExecutor;
+ friend class nearby::chrome::ScheduledExecutor;
+ friend class nearby::chrome::SubmittableExecutor;
friend class media::AudioOutputDevice;
friend class media::BlockingUrlProtocol;
friend class media::MojoVideoEncodeAccelerator;
diff --git a/base/threading/thread_restrictions_unittest.cc b/base/threading/thread_restrictions_unittest.cc
index 6e1db8d..846a153 100644
--- a/base/threading/thread_restrictions_unittest.cc
+++ b/base/threading/thread_restrictions_unittest.cc
@@ -6,11 +6,11 @@
#include <utility>
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/dcheck_is_on.h"
#include "base/debug/stack_trace.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/test/gtest_util.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
diff --git a/base/threading/thread_task_runner_handle.cc b/base/threading/thread_task_runner_handle.cc
deleted file mode 100644
index 1158eea..0000000
--- a/base/threading/thread_task_runner_handle.cc
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2016 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/threading/thread_task_runner_handle.h"
-
-namespace base {
-
-// DEPRECATED: Use SequencedTaskRunner::GetCurrentDefault instead
-// static
-const scoped_refptr<SingleThreadTaskRunner>& ThreadTaskRunnerHandle::Get() {
- return SingleThreadTaskRunner::GetCurrentDefault();
-}
-
-// DEPRECATED: Use SequencedTaskRunner::HasCurrentDefault instead
-// static
-bool ThreadTaskRunnerHandle::IsSet() {
- return SingleThreadTaskRunner::HasCurrentDefault();
-}
-
-} // namespace base
diff --git a/base/threading/thread_task_runner_handle.h b/base/threading/thread_task_runner_handle.h
deleted file mode 100644
index 5faedf8..0000000
--- a/base/threading/thread_task_runner_handle.h
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2016 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_
-#define BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_
-
-#include "base/base_export.h"
-#include "base/dcheck_is_on.h"
-#include "base/gtest_prod_util.h"
-#include "base/memory/scoped_refptr.h"
-#include "base/task/single_thread_task_runner.h"
-#include "base/threading/sequenced_task_runner_handle.h"
-#include "third_party/abseil-cpp/absl/types/optional.h"
-
-namespace base {
-
-// ThreadTaskRunnerHandle stores a reference to a thread's TaskRunner
-// in thread-local storage. Callers can then retrieve the TaskRunner
-// for the current thread by calling ThreadTaskRunnerHandle::Get().
-// At most one TaskRunner may be bound to each thread at a time.
-// Prefer SequencedTaskRunnerHandle to this unless thread affinity is required.
-class BASE_EXPORT ThreadTaskRunnerHandle {
- public:
- // DEPRECATED: use SingleThreadTaskRunner::GetCurrentDefault instead
- // Gets the SingleThreadTaskRunner for the current thread.
- [[nodiscard]] static const scoped_refptr<SingleThreadTaskRunner>& Get();
-
- // DEPRECATED: Use SingleThreadTaskRunner::HasCurrentDefault
- // Returns true if the SingleThreadTaskRunner is already created for
- // the current thread.
- [[nodiscard]] static bool IsSet();
-
- // Binds |task_runner| to the current thread. |task_runner| must belong
- // to the current thread for this to succeed.
- explicit ThreadTaskRunnerHandle(
- scoped_refptr<SingleThreadTaskRunner> task_runner)
- : contained_current_default_(std::move(task_runner)) {}
-
- ThreadTaskRunnerHandle(const ThreadTaskRunnerHandle&) = delete;
- ThreadTaskRunnerHandle& operator=(const ThreadTaskRunnerHandle&) = delete;
-
- ~ThreadTaskRunnerHandle() = default;
-
- private:
- SingleThreadTaskRunner::CurrentDefaultHandle contained_current_default_;
-};
-
-// DEPRECATED: Use SingleThreadTaskRunner::CurrentHandleOverride instead.
-//
-// ThreadTaskRunnerHandleOverride overrides the task runner returned by
-// |ThreadTaskRunnerHandle::Get()| to point at |overriding_task_runner| until
-// the |ThreadTaskRunnerHandleOverride| goes out of scope.
-// ThreadTaskRunnerHandleOverride instantiates a new ThreadTaskRunnerHandle if
-// ThreadTaskRunnerHandle is not instantiated on the current thread. Nested
-// overrides are allowed but callers must ensure the
-// |ThreadTaskRunnerHandleOverride| expire in LIFO (stack) order.
-//
-// Note: nesting ThreadTaskRunnerHandle is subtle and should be done with care,
-// hence the need to friend and request a //base/OWNERS review for usage outside
-// of tests. Use ThreadTaskRunnerHandleOverrideForTesting to bypass the friend
-// requirement in tests.
-class BASE_EXPORT ThreadTaskRunnerHandleOverride {
- public:
- ThreadTaskRunnerHandleOverride(const ThreadTaskRunnerHandleOverride&) =
- delete;
- ThreadTaskRunnerHandleOverride& operator=(
- const ThreadTaskRunnerHandleOverride&) = delete;
- ~ThreadTaskRunnerHandleOverride() = default;
-
- private:
- friend class ThreadTaskRunnerHandleOverrideForTesting;
- FRIEND_TEST_ALL_PREFIXES(ThreadTaskRunnerHandleTest, NestedRunLoop);
-
- // We expect ThreadTaskRunnerHandleOverride to be only needed under special
- // circumstances. Require them to be enumerated as friends to require
- // //base/OWNERS review. Use ThreadTaskRunnerHandleOverrideForTesting
- // in unit tests to avoid the friend requirement.
-
- friend class blink::scheduler::MainThreadSchedulerImpl;
-
- // Constructs a ThreadTaskRunnerHandleOverride which will make
- // ThreadTaskRunnerHandle::Get() return |overriding_task_runner| for its
- // lifetime. |allow_nested_loop| specifies whether RunLoop::Run() is allowed
- // during this override's lifetime. It's not recommended to allow this unless
- // the current thread's scheduler guarantees that only tasks which pertain to
- // |overriding_task_runner|'s context will be run by nested RunLoops.
- explicit ThreadTaskRunnerHandleOverride(
- scoped_refptr<SingleThreadTaskRunner> overriding_task_runner,
- bool allow_nested_runloop = false)
- : contained_override_(std::move(overriding_task_runner),
- allow_nested_runloop) {}
-
- SingleThreadTaskRunner::CurrentHandleOverride contained_override_;
-};
-
-// Note: nesting ThreadTaskRunnerHandles isn't generally desired but it's useful
-// in some unit tests where multiple task runners share the main thread for
-// simplicity and determinism. Only use this when no other constructs will work
-// (see base/test/task_environment.h and base/test/test_mock_time_task_runner.h
-// for preferred alternatives).
-class ThreadTaskRunnerHandleOverrideForTesting {
- public:
- explicit ThreadTaskRunnerHandleOverrideForTesting(
- scoped_refptr<SingleThreadTaskRunner> overriding_task_runner)
- : contained_override_(std::move(overriding_task_runner)) {}
-
- ~ThreadTaskRunnerHandleOverrideForTesting() = default;
-
- private:
- SingleThreadTaskRunner::CurrentHandleOverrideForTesting contained_override_;
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_THREAD_TASK_RUNNER_HANDLE_H_
diff --git a/base/threading/thread_task_runner_handle_unittest.cc b/base/threading/thread_task_runner_handle_unittest.cc
deleted file mode 100644
index 4e211a6..0000000
--- a/base/threading/thread_task_runner_handle_unittest.cc
+++ /dev/null
@@ -1,141 +0,0 @@
-// Copyright 2017 The Chromium Authors
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/threading/thread_task_runner_handle.h"
-
-#include "base/memory/ref_counted.h"
-#include "base/run_loop.h"
-#include "base/test/gtest_util.h"
-#include "base/test/task_environment.h"
-#include "base/test/test_simple_task_runner.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace base {
-
-TEST(ThreadTaskRunnerHandleTest, Basic) {
- scoped_refptr<SingleThreadTaskRunner> task_runner(new TestSimpleTaskRunner);
-
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
- {
- ThreadTaskRunnerHandle ttrh1(task_runner);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner, ThreadTaskRunnerHandle::Get());
- }
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
-}
-
-TEST(ThreadTaskRunnerHandleTest, DeathOnImplicitOverride) {
- scoped_refptr<SingleThreadTaskRunner> task_runner(new TestSimpleTaskRunner);
- scoped_refptr<SingleThreadTaskRunner> overidding_task_runner(
- new TestSimpleTaskRunner);
-
- ThreadTaskRunnerHandle ttrh(task_runner);
- EXPECT_DCHECK_DEATH(
- { ThreadTaskRunnerHandle overriding_ttrh(overidding_task_runner); });
-}
-
-TEST(ThreadTaskRunnerHandleTest, OverrideExistingTTRH) {
- scoped_refptr<SingleThreadTaskRunner> task_runner_1(new TestSimpleTaskRunner);
- scoped_refptr<SingleThreadTaskRunner> task_runner_2(new TestSimpleTaskRunner);
- scoped_refptr<SingleThreadTaskRunner> task_runner_3(new TestSimpleTaskRunner);
- scoped_refptr<SingleThreadTaskRunner> task_runner_4(new TestSimpleTaskRunner);
-
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
- {
- // TTRH in place prior to override.
- ThreadTaskRunnerHandle ttrh1(task_runner_1);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_1, ThreadTaskRunnerHandle::Get());
-
- {
- // Override.
- ThreadTaskRunnerHandleOverrideForTesting ttrh_override_2(task_runner_2);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_2, ThreadTaskRunnerHandle::Get());
-
- {
- // Nested override.
- ThreadTaskRunnerHandleOverrideForTesting ttrh_override_3(task_runner_3);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_3, ThreadTaskRunnerHandle::Get());
- }
-
- // Back to single override.
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_2, ThreadTaskRunnerHandle::Get());
-
- {
- // Backup to double override with another TTRH.
- ThreadTaskRunnerHandleOverrideForTesting ttrh_override_4(task_runner_4);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_4, ThreadTaskRunnerHandle::Get());
- }
- }
-
- // Back to simple TTRH.
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_1, ThreadTaskRunnerHandle::Get());
- }
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
-}
-
-TEST(ThreadTaskRunnerHandleTest, OverrideNoExistingTTRH) {
- scoped_refptr<SingleThreadTaskRunner> task_runner_1(new TestSimpleTaskRunner);
- scoped_refptr<SingleThreadTaskRunner> task_runner_2(new TestSimpleTaskRunner);
-
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
- {
- // Override with no TTRH in place.
- ThreadTaskRunnerHandleOverrideForTesting ttrh_override_1(task_runner_1);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_1, ThreadTaskRunnerHandle::Get());
-
- {
- // Nested override works the same.
- ThreadTaskRunnerHandleOverrideForTesting ttrh_override_2(task_runner_2);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_2, ThreadTaskRunnerHandle::Get());
- }
-
- // Back to single override.
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner_1, ThreadTaskRunnerHandle::Get());
- }
- EXPECT_FALSE(ThreadTaskRunnerHandle::IsSet());
-}
-
-TEST(ThreadTaskRunnerHandleTest, DeathOnTTRHOverOverride) {
- scoped_refptr<SingleThreadTaskRunner> task_runner(new TestSimpleTaskRunner);
- scoped_refptr<SingleThreadTaskRunner> overidding_task_runner(
- new TestSimpleTaskRunner);
-
- ThreadTaskRunnerHandleOverrideForTesting ttrh_override(task_runner);
- EXPECT_DCHECK_DEATH(
- { ThreadTaskRunnerHandle overriding_ttrh(overidding_task_runner); });
-}
-
-TEST(ThreadTaskRunnerHandleTest, NestedRunLoop) {
- test::SingleThreadTaskEnvironment task_environment;
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- scoped_refptr<SingleThreadTaskRunner> task_runner(new TestSimpleTaskRunner);
- ThreadTaskRunnerHandleOverride ttrh_override(task_runner,
- /*allow_nested_runloop=*/true);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner, ThreadTaskRunnerHandle::Get());
- EXPECT_EQ(task_runner, SequencedTaskRunnerHandle::Get());
- RunLoop().RunUntilIdle();
-}
-
-TEST(ThreadTaskRunnerHandleTest, DeathOnNestedRunLoop) {
- test::SingleThreadTaskEnvironment task_environment;
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- scoped_refptr<SingleThreadTaskRunner> task_runner(new TestSimpleTaskRunner);
- ThreadTaskRunnerHandleOverrideForTesting ttrh_override(task_runner);
- EXPECT_TRUE(ThreadTaskRunnerHandle::IsSet());
- EXPECT_EQ(task_runner, ThreadTaskRunnerHandle::Get());
- EXPECT_EQ(task_runner, SequencedTaskRunnerHandle::Get());
- EXPECT_DCHECK_DEATH({ RunLoop().RunUntilIdle(); });
-}
-
-} // namespace base
diff --git a/base/threading/thread_unittest.cc b/base/threading/thread_unittest.cc
index 387c90a..b3b1154 100644
--- a/base/threading/thread_unittest.cc
+++ b/base/threading/thread_unittest.cc
@@ -10,8 +10,8 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
#include "base/debug/leak_annotations.h"
+#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
diff --git a/base/timer/mock_timer_unittest.cc b/base/timer/mock_timer_unittest.cc
index 24cf688..8524cd6 100644
--- a/base/timer/mock_timer_unittest.cc
+++ b/base/timer/mock_timer_unittest.cc
@@ -4,7 +4,7 @@
#include "base/timer/mock_timer.h"
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
diff --git a/base/timer/timer.h b/base/timer/timer.h
index d78485a..4cd6baa 100644
--- a/base/timer/timer.h
+++ b/base/timer/timer.h
@@ -68,9 +68,9 @@
// should be able to tell the difference.
#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/sequence_checker.h"
diff --git a/base/timer/timer_unittest.cc b/base/timer/timer_unittest.cc
index d401321..63ad63e 100644
--- a/base/timer/timer_unittest.cc
+++ b/base/timer/timer_unittest.cc
@@ -8,9 +8,9 @@
#include <memory>
-#include "base/bind.h"
-#include "base/callback.h"
-#include "base/callback_helpers.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
+#include "base/functional/callback_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/timer/wall_clock_timer.h b/base/timer/wall_clock_timer.h
index 8aa9cb1..eabfe95 100644
--- a/base/timer/wall_clock_timer.h
+++ b/base/timer/wall_clock_timer.h
@@ -6,8 +6,8 @@
#define BASE_TIMER_WALL_CLOCK_TIMER_H_
#include "base/base_export.h"
-#include "base/bind.h"
-#include "base/callback.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/power_monitor/power_observer.h"
diff --git a/base/trace_event/cpufreq_monitor_android.cc b/base/trace_event/cpufreq_monitor_android.cc
index aebba8c..48d773f 100644
--- a/base/trace_event/cpufreq_monitor_android.cc
+++ b/base/trace_event/cpufreq_monitor_android.cc
@@ -6,9 +6,9 @@
#include <fcntl.h>
-#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/files/scoped_file.h"
+#include "base/functional/bind.h"
#include "base/memory/scoped_refptr.h"
#include "base/no_destructor.h"
#include "base/strings/string_number_conversions.h"
diff --git a/base/trace_event/memory_dump_manager_test_utils.h b/base/trace_event/memory_dump_manager_test_utils.h
index d540ef6..9a23195 100644
--- a/base/trace_event/memory_dump_manager_test_utils.h
+++ b/base/trace_event/memory_dump_manager_test_utils.h
@@ -5,7 +5,7 @@
#ifndef BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_TEST_UTILS_H_
#define BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_TEST_UTILS_H_
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/memory_dump_request_args.h"
diff --git a/base/trace_event/memory_dump_manager_unittest.cc b/base/trace_event/memory_dump_manager_unittest.cc
index 6d989f8..348d21f 100644
--- a/base/trace_event/memory_dump_manager_unittest.cc
+++ b/base/trace_event/memory_dump_manager_unittest.cc
@@ -13,9 +13,9 @@
#include "base/allocator/buildflags.h"
#include "base/at_exit.h"
#include "base/base_switches.h"
-#include "base/bind.h"
-#include "base/callback.h"
#include "base/command_line.h"
+#include "base/functional/bind.h"
+#include "base/functional/callback.h"
#include "base/run_loop.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/sequenced_task_runner.h"
diff --git a/base/trace_event/memory_dump_request_args.h b/base/trace_event/memory_dump_request_args.h
index 32d9e3b..4920535 100644
--- a/base/trace_event/memory_dump_request_args.h
+++ b/base/trace_event/memory_dump_request_args.h
@@ -14,7 +14,7 @@
#include <string>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/process/process_handle.h"
namespace base {
diff --git a/base/trace_event/memory_dump_scheduler.cc b/base/trace_event/memory_dump_scheduler.cc
index 77356d5..80d0519 100644
--- a/base/trace_event/memory_dump_scheduler.cc
+++ b/base/trace_event/memory_dump_scheduler.cc
@@ -7,8 +7,8 @@
#include <algorithm>
#include <limits>
-#include "base/bind.h"
#include "base/check_op.h"
+#include "base/functional/bind.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
diff --git a/base/trace_event/memory_dump_scheduler.h b/base/trace_event/memory_dump_scheduler.h
index 73d611c..e480f1f 100644
--- a/base/trace_event/memory_dump_scheduler.h
+++ b/base/trace_event/memory_dump_scheduler.h
@@ -10,7 +10,7 @@
#include <vector>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/trace_event/memory_dump_request_args.h"
namespace base {
diff --git a/base/trace_event/memory_dump_scheduler_unittest.cc b/base/trace_event/memory_dump_scheduler_unittest.cc
index c2854f1..6436513 100644
--- a/base/trace_event/memory_dump_scheduler_unittest.cc
+++ b/base/trace_event/memory_dump_scheduler_unittest.cc
@@ -6,7 +6,7 @@
#include <memory>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread.h"
diff --git a/base/trace_event/trace_arguments.h b/base/trace_event/trace_arguments.h
index fe969b8..f852043 100644
--- a/base/trace_event/trace_arguments.h
+++ b/base/trace_event/trace_arguments.h
@@ -14,6 +14,7 @@
#include <utility>
#include "base/base_export.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/trace_event/common/trace_event_common.h"
#include "base/tracing_buildflags.h"
#include "third_party/perfetto/include/perfetto/protozero/scattered_heap_buffer.h"
@@ -223,10 +224,17 @@
unsigned long long as_uint;
long long as_int;
double as_double;
- const void* as_pointer;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION const void* as_pointer;
const char* as_string;
- ConvertableToTraceFormat* as_convertable;
- protozero::HeapBuffered<perfetto::protos::pbzero::DebugAnnotation>* as_proto;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION ConvertableToTraceFormat* as_convertable;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #union
+ RAW_PTR_EXCLUSION protozero::HeapBuffered<
+ perfetto::protos::pbzero::DebugAnnotation>* as_proto;
// Static method to create a new TraceValue instance from a given
// initialization value. Note that this deduces the TRACE_VALUE_TYPE_XXX
@@ -597,7 +605,9 @@
// enough, but the compiler will then complaing about inlined constructors
// and destructors being too complex (!), resulting in larger code for no
// good reason.
- Data* data_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION Data* data_ = nullptr;
};
// TraceArguments models an array of kMaxSize trace-related items,
diff --git a/base/trace_event/trace_buffer.cc b/base/trace_event/trace_buffer.cc
index 8f8b424..b3b8692 100644
--- a/base/trace_event/trace_buffer.cc
+++ b/base/trace_event/trace_buffer.cc
@@ -8,7 +8,7 @@
#include <utility>
#include <vector>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/trace_event/heap_profiler.h"
#include "base/trace_event/trace_event_impl.h"
diff --git a/base/trace_event/trace_category_unittest.cc b/base/trace_event/trace_category_unittest.cc
index 9305ba3..e7b58ef4 100644
--- a/base/trace_event/trace_category_unittest.cc
+++ b/base/trace_event/trace_category_unittest.cc
@@ -6,7 +6,7 @@
#include <memory>
-#include "base/bind.h"
+#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/synchronization/lock.h"
#include "base/synchronization/waitable_event.h"
diff --git a/base/trace_event/trace_event_android.cc b/base/trace_event/trace_event_android.cc
index e9f3be8..0d0d436 100644
--- a/base/trace_event/trace_event_android.cc
+++ b/base/trace_event/trace_event_android.cc
@@ -8,8 +8,8 @@
#include <stddef.h>
#include <stdint.h>
-#include "base/bind.h"
#include "base/format_macros.h"
+#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/strings/stringprintf.h"
diff --git a/base/trace_event/trace_event_impl.h b/base/trace_event/trace_event_impl.h
index 12e4040..235c3e2 100644
--- a/base/trace_event/trace_event_impl.h
+++ b/base/trace_event/trace_event_impl.h
@@ -12,7 +12,7 @@
#include <string>
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/process/process_handle.h"
#include "base/strings/string_util.h"
#include "base/threading/platform_thread.h"
diff --git a/base/trace_event/trace_event_unittest.cc b/base/trace_event/trace_event_unittest.cc
index 6d4fdf1..004b557 100644
--- a/base/trace_event/trace_event_unittest.cc
+++ b/base/trace_event/trace_event_unittest.cc
@@ -17,9 +17,9 @@
#include <vector>
#include "base/at_exit.h"
-#include "base/bind.h"
#include "base/command_line.h"
#include "base/containers/cxx20_erase_vector.h"
+#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/location.h"
diff --git a/base/trace_event/trace_log.cc b/base/trace_event/trace_log.cc
index f2971ac..6211eec 100644
--- a/base/trace_event/trace_log.cc
+++ b/base/trace_event/trace_log.cc
@@ -11,11 +11,11 @@
#include <utility>
#include "base/base_switches.h"
-#include "base/bind.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/debug/leak_annotations.h"
#include "base/format_macros.h"
+#include "base/functional/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
diff --git a/base/trace_event/traced_value.h b/base/trace_event/traced_value.h
index b111330..beb6343 100644
--- a/base/trace_event/traced_value.h
+++ b/base/trace_event/traced_value.h
@@ -14,6 +14,7 @@
#include "base/base_export.h"
#include "base/memory/raw_ptr.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "base/strings/string_piece.h"
#include "base/trace_event/trace_arguments.h"
@@ -273,7 +274,9 @@
bool bool_value;
base::StringPiece string_piece_value;
std::string std_string_value;
- void* void_ptr_value;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter
+ // for: #union
+ RAW_PTR_EXCLUSION void* void_ptr_value;
Array array_value;
Dictionary dictionary_value;
diff --git a/base/trace_event/tracing_agent.h b/base/trace_event/tracing_agent.h
index 4e1451a..4026e33 100644
--- a/base/trace_event/tracing_agent.h
+++ b/base/trace_event/tracing_agent.h
@@ -6,7 +6,7 @@
#define BASE_TRACE_EVENT_TRACING_AGENT_H_
#include "base/base_export.h"
-#include "base/callback.h"
+#include "base/functional/callback.h"
#include "base/memory/ref_counted_memory.h"
namespace base {
diff --git a/base/tracing/perfetto_task_runner.cc b/base/tracing/perfetto_task_runner.cc
index 5ac8b3b..8022be3 100644
--- a/base/tracing/perfetto_task_runner.cc
+++ b/base/tracing/perfetto_task_runner.cc
@@ -7,8 +7,8 @@
#include <memory>
#include <utility>
-#include "base/bind.h"
#include "base/containers/contains.h"
+#include "base/functional/bind.h"
#include "base/notreached.h"
#include "base/task/common/checked_lock_impl.h"
#include "base/task/common/scoped_defer_task_posting.h"
diff --git a/base/types/optional_ref.h b/base/types/optional_ref.h
index 561e2bd..8ba1ea8 100644
--- a/base/types/optional_ref.h
+++ b/base/types/optional_ref.h
@@ -9,6 +9,7 @@
#include <type_traits>
#include "base/check.h"
+#include "base/memory/raw_ptr_exclusion.h"
#include "third_party/abseil-cpp/absl/base/attributes.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
@@ -183,7 +184,9 @@
}
private:
- T* const ptr_ = nullptr;
+ // This field is not a raw_ptr<> because it was filtered by the rewriter for:
+ // #constexpr-ctor-field-initializer
+ RAW_PTR_EXCLUSION T* const ptr_ = nullptr;
};
template <typename T>
diff --git a/base/values.cc b/base/values.cc
index ae5cbc5..4612da9 100644
--- a/base/values.cc
+++ b/base/values.cc
@@ -133,12 +133,6 @@
return std::make_unique<Value>(std::move(val));
}
-// static
-const DictionaryValue& Value::AsDictionaryValue(const Value& val) {
- CHECK(val.is_dict());
- return static_cast<const DictionaryValue&>(val);
-}
-
Value::Value() noexcept = default;
Value::Value(Value&&) noexcept = default;
@@ -1438,151 +1432,6 @@
}
#endif // BUILDFLAG(ENABLE_BASE_TRACING)
-///////////////////// DictAdapterForMigration ////////////////////
-
-DictAdapterForMigration::DictAdapterForMigration(
- const Value::Dict& dict) noexcept
- : dict_(dict) {}
-
-DictAdapterForMigration::DictAdapterForMigration(
- const DictionaryValue& dict) noexcept
- : dict_(dict.GetDict()) {}
-
-bool DictAdapterForMigration::empty() const {
- return dict_->empty();
-}
-
-size_t DictAdapterForMigration::size() const {
- return dict_->size();
-}
-
-DictAdapterForMigration::const_iterator DictAdapterForMigration::begin() const {
- return dict_->begin();
-}
-
-DictAdapterForMigration::const_iterator DictAdapterForMigration::cbegin()
- const {
- return dict_->cbegin();
-}
-
-DictAdapterForMigration::const_iterator DictAdapterForMigration::end() const {
- return dict_->end();
-}
-
-DictAdapterForMigration::const_iterator DictAdapterForMigration::cend() const {
- return dict_->cend();
-}
-
-bool DictAdapterForMigration::contains(base::StringPiece key) const {
- return dict_->contains(key);
-}
-
-Value::Dict DictAdapterForMigration::Clone() const {
- return dict_->Clone();
-}
-
-const Value* DictAdapterForMigration::Find(StringPiece key) const {
- return dict_->Find(key);
-}
-
-absl::optional<bool> DictAdapterForMigration::FindBool(StringPiece key) const {
- return dict_->FindBool(key);
-}
-
-absl::optional<int> DictAdapterForMigration::FindInt(StringPiece key) const {
- return dict_->FindInt(key);
-}
-
-absl::optional<double> DictAdapterForMigration::FindDouble(
- StringPiece key) const {
- return dict_->FindDouble(key);
-}
-const std::string* DictAdapterForMigration::FindString(StringPiece key) const {
- return dict_->FindString(key);
-}
-
-const Value::BlobStorage* DictAdapterForMigration::FindBlob(
- StringPiece key) const {
- return dict_->FindBlob(key);
-}
-
-const Value::Dict* DictAdapterForMigration::FindDict(StringPiece key) const {
- return dict_->FindDict(key);
-}
-
-const Value::List* DictAdapterForMigration::FindList(StringPiece key) const {
- return dict_->FindList(key);
-}
-
-const Value* DictAdapterForMigration::FindByDottedPath(StringPiece path) const {
- return dict_->FindByDottedPath(path);
-}
-
-absl::optional<bool> DictAdapterForMigration::FindBoolByDottedPath(
- StringPiece path) const {
- return dict_->FindBoolByDottedPath(path);
-}
-
-absl::optional<int> DictAdapterForMigration::FindIntByDottedPath(
- StringPiece path) const {
- return dict_->FindIntByDottedPath(path);
-}
-
-absl::optional<double> DictAdapterForMigration::FindDoubleByDottedPath(
- StringPiece path) const {
- return dict_->FindDoubleByDottedPath(path);
-}
-
-const std::string* DictAdapterForMigration::FindStringByDottedPath(
- StringPiece path) const {
- return dict_->FindStringByDottedPath(path);
-}
-
-const Value::BlobStorage* DictAdapterForMigration::FindBlobByDottedPath(
- StringPiece path) const {
- return dict_->FindBlobByDottedPath(path);
-}
-
-const Value::Dict* DictAdapterForMigration::FindDictByDottedPath(
- StringPiece path) const {
- return dict_->FindDictByDottedPath(path);
-}
-
-const Value::List* DictAdapterForMigration::FindListByDottedPath(
- StringPiece path) const {
- return dict_->FindListByDottedPath(path);
-}
-
-std::string DictAdapterForMigration::DebugString() const {
- return dict_->DebugString();
-}
-
-#if BUILDFLAG(ENABLE_BASE_TRACING)
-void DictAdapterForMigration::WriteIntoTrace(
- perfetto::TracedValue context) const {
- return dict_->WriteIntoTrace(std::move(context));
-}
-#endif // BUILDFLAG(ENABLE_BASE_TRACING)
-
-const Value::Dict& DictAdapterForMigration::dict_for_test() const {
- return *dict_;
-}
-
-///////////////////// DictionaryValue ////////////////////
-
-// static
-std::unique_ptr<DictionaryValue> DictionaryValue::From(
- std::unique_ptr<Value> value) {
- if (!value || !value->is_dict()) {
- return nullptr;
- }
-
- DictionaryValue* out = static_cast<DictionaryValue*>(value.release());
- return WrapUnique(out);
-}
-
-DictionaryValue::DictionaryValue() : Value(Type::DICTIONARY) {}
-
ValueView::ValueView(const Value& value)
: data_view_(
value.Visit([](const auto& member) { return ViewType(member); })) {}
diff --git a/base/values.h b/base/values.h
index 548f534..e72d46d 100644
--- a/base/values.h
+++ b/base/values.h
@@ -33,9 +33,6 @@
namespace base {
-class DictAdapterForMigration;
-class DictionaryValue;
-
// The `Value` class is a variant type can hold one of the following types:
// - null
// - bool
@@ -176,25 +173,6 @@
// return base::Value(std::move(dict));
// }
//
-// To avoid losing type information with the new variant-based design, migration
-// off the deprecated types should use more specific subtypes where possible:
-//
-// OLD WAY:
-//
-// void AlwaysTakesDict(std::unique_ptr<base::DictionaryValue> dict);
-//
-// DEPRECATED (PREVIOUS) WAY:
-//
-// void AlwaysTakesList(std::vector<base::Value> list);
-// void AlwaysTakesListAlterantive3(base::Value::ListStorage);
-// void AlwaysTakesDict(base::flat_map<std::string, base::Value> dict);
-// void AlwaysTakesDictAlternative(base::Value::DictStorage);
-//
-// NEW WAY:
-//
-// void AlwaysTakesList(base::Value::List list);
-// void AlwaysTakesDict(base::Value::Dict dict);
-//
// Migrating code may require conversions on API boundaries. If something seems
// awkward/inefficient, please reach out to #code-health-rotation on Slack for
// consultation: it is entirely possible that certain classes of APIs may be
@@ -227,13 +205,8 @@
};
// Adaptors for converting from the old way to the new way and vice versa.
- // Note: `DictionaryValue` has been deprecated.
- // `AsDictionaryValue()` performs a `static_cast` to these types (as opposed
- // to the preferred `GetDict()` API - which uses a variant lookup
- // `absl::get<>()`).
static Value FromUniquePtrValue(std::unique_ptr<Value> val);
static std::unique_ptr<Value> ToUniquePtrValue(Value val);
- static const DictionaryValue& AsDictionaryValue(const Value& val);
Value() noexcept;
@@ -727,6 +700,7 @@
// a pointer to the element. Otherwise it returns nullptr.
//
// DEPRECATED: prefer `Value::Dict::Find()`.
+ // TODO(https://crbug.com/1406815): Remove this API.
Value* FindKey(StringPiece key);
const Value* FindKey(StringPiece key) const;
@@ -1169,88 +1143,6 @@
data_;
};
-// DictAdapterForMigration is an adapter class to help the migration of
-// base::DictionaryValue to base::Value::Dict.
-//
-// DictAdapterForMigration mirrors the API of base::Value::Dict,
-// and is implicitly constructable from both base::DictionaryValue
-// and base::Value::Dict. Currently this is read-only, similar to StringPiece.
-//
-// To migrate a function that takes a base::DictionaryValue, change the
-// signature to take DictAdapterForMigration instead, and update the
-// function body to use the Dict::Value API.
-// The call sites can be left unchanged and migrated later.
-//
-// Note that DictAdapterForMigration is intended as a shim to help migrations,
-// and will go away with base::DictionaryValue.
-class BASE_EXPORT GSL_POINTER DictAdapterForMigration {
- public:
- using iterator = detail::dict_iterator;
- using const_iterator = detail::const_dict_iterator;
-
- DictAdapterForMigration() = delete;
-
- // NOLINTNEXTLINE(google-explicit-constructor)
- DictAdapterForMigration(const Value::Dict&) noexcept;
- // NOLINTNEXTLINE(google-explicit-constructor)
- DictAdapterForMigration(const DictionaryValue&) noexcept;
-
- bool empty() const;
- size_t size() const;
-
- const_iterator begin() const;
- const_iterator cbegin() const;
- const_iterator end() const;
- const_iterator cend() const;
-
- bool contains(base::StringPiece key) const;
-
- Value::Dict Clone() const;
-
- const Value* Find(StringPiece key) const;
- absl::optional<bool> FindBool(StringPiece key) const;
- absl::optional<int> FindInt(StringPiece key) const;
- absl::optional<double> FindDouble(StringPiece key) const;
- const std::string* FindString(StringPiece key) const;
- const Value::BlobStorage* FindBlob(StringPiece key) const;
- const Value::Dict* FindDict(StringPiece key) const;
- const Value::List* FindList(StringPiece key) const;
-
- const Value* FindByDottedPath(StringPiece path) const;
-
- absl::optional<bool> FindBoolByDottedPath(StringPiece path) const;
- absl::optional<int> FindIntByDottedPath(StringPiece path) const;
- absl::optional<double> FindDoubleByDottedPath(StringPiece path) const;
- const std::string* FindStringByDottedPath(StringPiece path) const;
- const Value::BlobStorage* FindBlobByDottedPath(StringPiece path) const;
- const Value::Dict* FindDictByDottedPath(StringPiece path) const;
- const Value::List* FindListByDottedPath(StringPiece path) const;
-
- std::string DebugString() const;
-
-#if BUILDFLAG(ENABLE_BASE_TRACING)
- void WriteIntoTrace(perfetto::TracedValue) const;
-#endif // BUILDFLAG(ENABLE_BASE_TRACING)
-
- const Value::Dict& dict_for_test() const;
-
- private:
- const raw_ref<const Value::Dict> dict_;
-};
-
-// DictionaryValue provides a key-value dictionary with (optional) "path"
-// parsing for recursive access; see the comment at the top of the file. Keys
-// are std::string's and should be UTF-8 encoded.
-//
-// DEPRECATED: prefer `Value::Dict`.
-class BASE_EXPORT DictionaryValue : public Value {
- public:
- // Returns `value` if it is a dictionary, nullptr otherwise.
- static std::unique_ptr<DictionaryValue> From(std::unique_ptr<Value> value);
-
- DictionaryValue();
-};
-
// Adapter so `Value::Dict` or `Value::List` can be directly passed to JSON
// serialization methods without having to clone the contents and transfer
// ownership of the clone to a `Value` wrapper object.
@@ -1382,13 +1274,6 @@
BASE_EXPORT std::ostream& operator<<(std::ostream& out,
const Value::List& list);
-// Hints for DictionaryValue otherwise, gtest tends to prefer the default
-// template implementation over an upcast to Value.
-BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
- const DictionaryValue& value) {
- return out << static_cast<const Value&>(value);
-}
-
// Stream operator so that enum class Types can be used in log statements.
BASE_EXPORT std::ostream& operator<<(std::ostream& out,
const Value::Type& type);
diff --git a/base/values_unittest.cc b/base/values_unittest.cc
index 42a5b1d..0dafe38 100644
--- a/base/values_unittest.cc
+++ b/base/values_unittest.cc
@@ -2031,20 +2031,19 @@
}
TEST(ValuesTest, DeepCopyCovariantReturnTypes) {
- DictionaryValue original_dict;
- Value* null_weak = original_dict.SetKey("null", Value());
- Value* bool_weak = original_dict.SetKey("bool", Value(true));
- Value* int_weak = original_dict.SetKey("int", Value(42));
- Value* double_weak = original_dict.SetKey("double", Value(3.14));
- Value* string_weak = original_dict.SetKey("string", Value("hello"));
- Value* string16_weak = original_dict.SetKey("string16", Value(u"hello16"));
- Value* binary_weak =
- original_dict.SetKey("binary", Value(Value::BlobStorage(42, '!')));
+ Value::Dict original_dict;
+ Value* null_weak = original_dict.Set("null", Value());
+ Value* bool_weak = original_dict.Set("bool", true);
+ Value* int_weak = original_dict.Set("int", 42);
+ Value* double_weak = original_dict.Set("double", 3.14);
+ Value* string_weak = original_dict.Set("string", "hello");
+ Value* string16_weak = original_dict.Set("string16", u"hello16");
+ Value* binary_weak = original_dict.Set("binary", Value::BlobStorage(42, '!'));
Value::List list;
list.Append(0);
list.Append(1);
- Value* list_weak = original_dict.SetKey("list", Value(std::move(list)));
+ Value* list_weak = original_dict.Set("list", std::move(list));
auto copy_dict = std::make_unique<Value>(original_dict.Clone());
auto copy_null = std::make_unique<Value>(null_weak->Clone());
@@ -2125,25 +2124,25 @@
//
// Just remove this test when the old API is removed.
- std::unique_ptr<DictionaryValue> child(new DictionaryValue);
- child->SetStringKey("test", "value");
- EXPECT_EQ(1U, child->DictSize());
+ Value::Dict child;
+ child.Set("test", "value");
+ EXPECT_EQ(1U, child.size());
- std::string* value = child->GetDict().FindString("test");
+ std::string* value = child.FindString("test");
ASSERT_TRUE(value);
EXPECT_EQ("value", *value);
- std::unique_ptr<DictionaryValue> base(new DictionaryValue);
- base->GetDict().Set("dict", std::move(child->GetDict()));
- EXPECT_EQ(1U, base->DictSize());
+ Value base(Value::Type::DICT);
+ base.GetDict().Set("dict", std::move(child));
+ EXPECT_EQ(1U, base.GetDict().size());
- base::Value::Dict* original_child = base->GetDict().FindDict("dict");
+ base::Value::Dict* original_child = base.GetDict().FindDict("dict");
EXPECT_FALSE(original_child->empty());
- std::unique_ptr<DictionaryValue> merged(new DictionaryValue);
- merged->MergeDictionary(base.get());
- EXPECT_EQ(1U, merged->DictSize());
- base::Value::Dict* ptr = merged->GetDict().FindDict("dict");
+ Value merged(Value::Type::DICT);
+ merged.MergeDictionary(&base);
+ EXPECT_EQ(1U, merged.GetDict().size());
+ base::Value::Dict* ptr = merged.GetDict().FindDict("dict");
EXPECT_FALSE(ptr->empty());
EXPECT_NE(original_child, ptr);
value = ptr->FindString("test");
@@ -2151,7 +2150,6 @@
EXPECT_EQ("value", *value);
original_child->Set("test", "overwrite");
- base.reset();
value = ptr->FindString("test");
ASSERT_TRUE(value);
EXPECT_EQ("value", *value);
@@ -2253,9 +2251,9 @@
}
TEST(ValuesTest, FromToUniquePtrValue) {
- std::unique_ptr<DictionaryValue> dict = std::make_unique<DictionaryValue>();
- dict->SetStringKey("name", "Froogle");
- dict->SetStringKey("url", "http://froogle.com");
+ std::unique_ptr<Value> dict = std::make_unique<Value>(Value::Type::DICT);
+ dict->GetDict().Set("name", "Froogle");
+ dict->GetDict().Set("url", "http://froogle.com");
Value dict_copy = dict->Clone();
Value dict_converted = Value::FromUniquePtrValue(std::move(dict));
@@ -2310,78 +2308,6 @@
}
#endif // BUILDFLAG(ENABLE_BASE_TRACING)
-TEST(DictAdapterForMigrationTest, ImplicitConstruction) {
- {
- Value::Dict dict;
- dict.Set("hello", "world");
- DictAdapterForMigration a = dict;
- EXPECT_EQ(&dict, &a.dict_for_test());
- }
- {
- DictionaryValue dict;
- dict.SetStringKey("hello", "world");
- DictAdapterForMigration v = dict;
- EXPECT_EQ(&dict.GetDict(), &v.dict_for_test());
- }
-}
-
-TEST(DictAdapterForMigrationTest, BasicFunctions) {
- Value::Dict dict;
- DictAdapterForMigration a = dict;
-
- EXPECT_TRUE(a.empty());
- EXPECT_EQ(a.size(), 0u);
-
- dict.Set("hello", "world");
- EXPECT_FALSE(a.empty());
- EXPECT_EQ(a.size(), 1u);
-
- EXPECT_EQ(dict.cbegin(), a.begin());
- EXPECT_EQ(dict.cend(), a.end());
- EXPECT_EQ(dict.cbegin(), a.cbegin());
- EXPECT_EQ(dict.cend(), a.cend());
-
- EXPECT_TRUE(a.contains("hello"));
- EXPECT_FALSE(a.contains("world"));
-
- EXPECT_EQ(a.Clone(), dict);
-
- EXPECT_EQ(a.DebugString(), dict.DebugString());
-}
-
-TEST(DictAdapterForMigrationTest, Find) {
- Value::Dict dict;
- dict.Set("null", Value());
- dict.Set("bool", true);
- dict.Set("int", 2);
- dict.Set("double", 3.0);
- dict.Set("string", std::string("4"));
- dict.Set("blob", Value(Value::BlobStorage()));
- dict.Set("list", Value::List());
- dict.Set("dict", Value::Dict());
- DictAdapterForMigration a = dict;
-
- EXPECT_EQ(a.Find("n/a"), nullptr);
- EXPECT_EQ(*a.Find("null"), Value());
- EXPECT_EQ(a.FindBool("bool"), true);
- EXPECT_EQ(a.FindInt("int"), 2);
- EXPECT_EQ(a.FindDouble("double"), 3.0);
- EXPECT_EQ(*a.FindString("string"), "4");
- EXPECT_EQ(*a.FindBlob("blob"), Value::BlobStorage());
- EXPECT_EQ(*a.FindList("list"), Value::List());
- EXPECT_EQ(*a.FindDict("dict"), Value::Dict());
-
- EXPECT_EQ(a.FindByDottedPath("n/a"), nullptr);
- EXPECT_EQ(*a.FindByDottedPath("null"), Value());
- EXPECT_EQ(a.FindBoolByDottedPath("bool"), true);
- EXPECT_EQ(a.FindIntByDottedPath("int"), 2);
- EXPECT_EQ(a.FindDoubleByDottedPath("double"), 3.0);
- EXPECT_EQ(*a.FindStringByDottedPath("string"), "4");
- EXPECT_EQ(*a.FindBlobByDottedPath("blob"), Value::BlobStorage());
- EXPECT_EQ(*a.FindListByDottedPath("list"), Value::List());
- EXPECT_EQ(*a.FindDictByDottedPath("dict"), Value::Dict());
-}
-
TEST(ValueViewTest, BasicConstruction) {
{
ValueView v = true;
diff --git a/build/add_rts_filters.py b/build/add_rts_filters.py
index 1a53474..94297c5 100755
--- a/build/add_rts_filters.py
+++ b/build/add_rts_filters.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2021 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/android/gyp/util/md5_check.py b/build/android/gyp/util/md5_check.py
index 8a59ba5..8423ac3 100644
--- a/build/android/gyp/util/md5_check.py
+++ b/build/android/gyp/util/md5_check.py
@@ -2,7 +2,6 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-from __future__ import print_function
import difflib
import hashlib
diff --git a/build/check_return_value.py b/build/check_return_value.py
index 56b5fe7..2337e96 100755
--- a/build/check_return_value.py
+++ b/build/check_return_value.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2014 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -6,7 +6,6 @@
"""This program wraps an arbitrary command and prints "1" if the command ran
successfully."""
-from __future__ import print_function
import os
import subprocess
diff --git a/build/clobber.py b/build/clobber.py
index 411bb8d..9192777 100755
--- a/build/clobber.py
+++ b/build/clobber.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2015 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -22,18 +22,17 @@
On error, returns the empty string."""
result = ""
with open(build_ninja_file, 'r') as f:
- # Read until the third blank line. The first thing GN writes to the file
- # is "ninja_required_version = x.y.z", then the "rule gn" and the third
- # is the section for "build build.ninja", separated by blank lines.
- num_blank_lines = 0
- while num_blank_lines < 3:
- line = f.readline()
- if len(line) == 0:
- return '' # Unexpected EOF.
+ # Reads until the first empty line after the "build build.ninja:" target.
+ # We assume everything before it necessary as well (eg the
+ # "ninja_required_version" line).
+ found_build_dot_ninja_target = False
+ for line in f.readlines():
result += line
- if line[0] == '\n':
- num_blank_lines = num_blank_lines + 1
- return result
+ if line.startswith('build build.ninja:'):
+ found_build_dot_ninja_target = True
+ if found_build_dot_ninja_target and line[0] == '\n':
+ return result
+ return '' # We got to EOF and didn't find what we were looking for.
def delete_dir(build_dir):
@@ -68,7 +67,7 @@
except IOError:
args_contents = ''
- e = None
+ exception_during_rm = None
try:
# delete_dir and os.mkdir() may fail, such as when chrome.exe is running,
# and we still want to restore args.gn/build.ninja/build.ninja.d, so catch
@@ -76,7 +75,7 @@
delete_dir(build_dir)
os.mkdir(build_dir)
except Exception as e:
- pass
+ exception_during_rm = e
# Put back the args file (if any).
if args_contents != '':
@@ -105,9 +104,10 @@
with open(build_ninja_d_file, 'w') as f:
f.write('build.ninja: nonexistant_file.gn\n')
- if e:
+ if exception_during_rm:
# Rethrow the exception we caught earlier.
- raise e
+ raise exception_during_rm
+
def clobber(out_dir):
"""Clobber contents of build directory.
diff --git a/build/clobber_unittest.py b/build/clobber_unittest.py
new file mode 100755
index 0000000..bad503b
--- /dev/null
+++ b/build/clobber_unittest.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+# 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.
+
+import os
+import pathlib
+import shutil
+import tempfile
+import textwrap
+import unittest
+from unittest import mock
+
+import clobber
+
+
+class TestExtractBuildCommand(unittest.TestCase):
+ def setUp(self):
+ self.build_ninja_file, self.build_ninja_path = tempfile.mkstemp(text=True)
+
+ def tearDown(self):
+ os.close(self.build_ninja_file)
+ os.remove(self.build_ninja_path)
+
+ def test_normal_extraction(self):
+ build_ninja_file_contents = textwrap.dedent("""
+ ninja_required_version = 1.7.2
+
+ rule gn
+ command = ../../buildtools/gn --root=../.. -q --regeneration gen .
+ pool = console
+ description = Regenerating ninja files
+
+ build build.ninja.stamp: gn
+ generator = 1
+ depfile = build.ninja.d
+
+ build build.ninja: phony build.ninja.stamp
+ generator = 1
+
+ pool build_toolchain_action_pool
+ depth = 72
+
+ pool build_toolchain_link_pool
+ depth = 23
+
+ subninja toolchain.ninja
+ subninja clang_newlib_x64/toolchain.ninja
+ subninja glibc_x64/toolchain.ninja
+ subninja irt_x64/toolchain.ninja
+ subninja nacl_bootstrap_x64/toolchain.ninja
+ subninja newlib_pnacl/toolchain.ninja
+
+ build blink_python_tests: phony obj/blink_python_tests.stamp
+ build blink_tests: phony obj/blink_tests.stamp
+
+ default all
+ """) # Based off of a standard linux build dir.
+ with open(self.build_ninja_path, 'w') as f:
+ f.write(build_ninja_file_contents)
+
+ expected_build_ninja_file_contents = textwrap.dedent("""
+ ninja_required_version = 1.7.2
+
+ rule gn
+ command = ../../buildtools/gn --root=../.. -q --regeneration gen .
+ pool = console
+ description = Regenerating ninja files
+
+ build build.ninja.stamp: gn
+ generator = 1
+ depfile = build.ninja.d
+
+ build build.ninja: phony build.ninja.stamp
+ generator = 1
+
+ """)
+
+ self.assertEqual(clobber.extract_gn_build_commands(self.build_ninja_path),
+ expected_build_ninja_file_contents)
+
+ def test_unexpected_format(self):
+ # No "build build.ninja:" line should make it return an empty string.
+ build_ninja_file_contents = textwrap.dedent("""
+ ninja_required_version = 1.7.2
+
+ rule gn
+ command = ../../buildtools/gn --root=../.. -q --regeneration gen .
+ pool = console
+ description = Regenerating ninja files
+
+ subninja toolchain.ninja
+
+ build blink_python_tests: phony obj/blink_python_tests.stamp
+ build blink_tests: phony obj/blink_tests.stamp
+
+ """)
+ with open(self.build_ninja_path, 'w') as f:
+ f.write(build_ninja_file_contents)
+
+ self.assertEqual(clobber.extract_gn_build_commands(self.build_ninja_path),
+ '')
+
+
+class TestDelete(unittest.TestCase):
+ def setUp(self):
+ self.build_dir = tempfile.mkdtemp()
+
+ pathlib.Path(os.path.join(self.build_dir, 'build.ninja')).touch()
+ pathlib.Path(os.path.join(self.build_dir, 'build.ninja.d')).touch()
+
+ def tearDown(self):
+ shutil.rmtree(self.build_dir)
+
+ def test_delete_build_dir_full(self):
+ # Create a dummy file in the build dir and ensure it gets removed.
+ dummy_file = os.path.join(self.build_dir, 'dummy')
+ pathlib.Path(dummy_file).touch()
+
+ clobber.delete_build_dir(self.build_dir)
+
+ self.assertFalse(os.path.exists(dummy_file))
+
+ def test_delete_build_dir_fail(self):
+ # Make delete_dir() throw to ensure it's handled gracefully.
+
+ with mock.patch('clobber.delete_dir', side_effect=OSError):
+ with self.assertRaises(OSError):
+ clobber.delete_build_dir(self.build_dir)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/build/compute_build_timestamp.py b/build/compute_build_timestamp.py
index ca1cc44..befe844 100755
--- a/build/compute_build_timestamp.py
+++ b/build/compute_build_timestamp.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2018 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -27,7 +27,6 @@
# the symbol server, so rarely changing timestamps can cause conflicts there
# as well. We only upload symbols for official builds to the symbol server.
-from __future__ import print_function
import argparse
import calendar
diff --git a/build/cp.py b/build/cp.py
index 483b274..2bcf55c 100755
--- a/build/cp.py
+++ b/build/cp.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2012 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/detect_host_arch.py b/build/detect_host_arch.py
index 7c7d6d6..c9d47e9 100755
--- a/build/detect_host_arch.py
+++ b/build/detect_host_arch.py
@@ -1,11 +1,10 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2014 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Outputs host CPU architecture in format recognized by gyp."""
-from __future__ import print_function
import platform
import re
diff --git a/build/dir_exists.py b/build/dir_exists.py
index f95a52d..da9813f 100755
--- a/build/dir_exists.py
+++ b/build/dir_exists.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2011 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/env_dump.py b/build/env_dump.py
index 2474b48..1eaf8dc 100755
--- a/build/env_dump.py
+++ b/build/env_dump.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2013 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/extract_from_cab.py b/build/extract_from_cab.py
index 4c003ba..c7ae6d9 100755
--- a/build/extract_from_cab.py
+++ b/build/extract_from_cab.py
@@ -1,11 +1,10 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2012 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Extracts a single file from a CAB archive."""
-from __future__ import print_function
import os
import shutil
diff --git a/build/extract_partition.py b/build/extract_partition.py
index bbe0e70..319ce8f 100755
--- a/build/extract_partition.py
+++ b/build/extract_partition.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2019 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/find_depot_tools.py b/build/find_depot_tools.py
index 94985fe..f891a41 100755
--- a/build/find_depot_tools.py
+++ b/build/find_depot_tools.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2011 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -11,7 +11,6 @@
directory location.
"""
-from __future__ import print_function
import os
import sys
diff --git a/build/fix_gn_headers.py b/build/fix_gn_headers.py
index 7b8086b..5111b5d 100755
--- a/build/fix_gn_headers.py
+++ b/build/fix_gn_headers.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2017 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -10,7 +10,6 @@
Manual cleaning up is likely required afterwards.
"""
-from __future__ import print_function
import argparse
import os
diff --git a/build/get_landmines.py b/build/get_landmines.py
index 311f042..6155d71 100755
--- a/build/get_landmines.py
+++ b/build/get_landmines.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2013 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -8,7 +8,6 @@
(or a list of 'landmines').
"""
-from __future__ import print_function
import sys
@@ -79,6 +78,8 @@
if host_os() == 'linux':
print('Clobber to workaround buggy .ninja_deps cycle (crbug.com/934404)')
print('Clobber to flush stale generated files. See crbug.com/1406628')
+ print('Clobber to flush old .ninja_log files for updating ninja. '
+ 'See crbug.com/1406628#c14')
def main():
diff --git a/build/get_symlink_targets.py b/build/get_symlink_targets.py
index 33362c0..850bbae 100755
--- a/build/get_symlink_targets.py
+++ b/build/get_symlink_targets.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2019 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/gn_run_binary.py b/build/gn_run_binary.py
index 29035e7..414f695 100644
--- a/build/gn_run_binary.py
+++ b/build/gn_run_binary.py
@@ -8,7 +8,6 @@
python gn_run_binary.py <binary_name> [args ...]
"""
-from __future__ import print_function
import os
import subprocess
diff --git a/build/landmines.py b/build/landmines.py
index 2078b24..844ee38 100755
--- a/build/landmines.py
+++ b/build/landmines.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2012 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/locale_tool.py b/build/locale_tool.py
index 8eda9cd..c9fd395 100755
--- a/build/locale_tool.py
+++ b/build/locale_tool.py
@@ -28,7 +28,6 @@
trying to fix it too, but at least the file will not be modified.
"""
-from __future__ import print_function
import argparse
import json
diff --git a/build/protoc_java.py b/build/protoc_java.py
index 3c0b313..28c4200 100755
--- a/build/protoc_java.py
+++ b/build/protoc_java.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2012 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -15,7 +15,6 @@
4. Creates a new stamp file.
"""
-from __future__ import print_function
import argparse
import os
diff --git a/build/redirect_stdout.py b/build/redirect_stdout.py
index eb7d363..16494fa 100644
--- a/build/redirect_stdout.py
+++ b/build/redirect_stdout.py
@@ -2,7 +2,6 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-from __future__ import print_function
import os
import subprocess
diff --git a/build/rm.py b/build/rm.py
index 5f4aea1..11e8a64 100755
--- a/build/rm.py
+++ b/build/rm.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2016 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
@@ -8,7 +8,6 @@
This module works much like the rm posix command.
"""
-from __future__ import print_function
import argparse
import os
diff --git a/build/symlink.py b/build/symlink.py
index 38a6102..44aff0b 100755
--- a/build/symlink.py
+++ b/build/symlink.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2013 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/vs_toolchain.py b/build/vs_toolchain.py
index d426fcd..6ca0be4 100755
--- a/build/vs_toolchain.py
+++ b/build/vs_toolchain.py
@@ -1,9 +1,8 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2014 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
-from __future__ import print_function
import collections
import glob
diff --git a/build/write_build_date_header.py b/build/write_build_date_header.py
index 3b79417..4929e04 100755
--- a/build/write_build_date_header.py
+++ b/build/write_build_date_header.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2016 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/build/write_buildflag_header.py b/build/write_buildflag_header.py
index 44da8a6..89a0737 100755
--- a/build/write_buildflag_header.py
+++ b/build/write_buildflag_header.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
# Copyright 2015 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
diff --git a/components/policy/core/common/policy_map_unittest.cc b/components/policy/core/common/policy_map_unittest.cc
index 7829e97..c8b43c6 100644
--- a/components/policy/core/common/policy_map_unittest.cc
+++ b/components/policy/core/common/policy_map_unittest.cc
@@ -13,6 +13,7 @@
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
+#include "base/values.h"
#include "build/build_config.h"
#include "components/policy/core/common/external_data_manager.h"
#include "components/policy/core/common/policy_details.h"
@@ -720,109 +721,113 @@
}
TEST_F(PolicyMapTest, MergeValuesDictionary) {
- base::Value dict_a(base::Value::Type::DICTIONARY);
- dict_a.SetBoolKey("keyA", true);
+ base::Value::Dict dict_a;
+ dict_a.Set("keyA", true);
- base::Value dict_b(base::Value::Type::DICTIONARY);
- dict_b.SetStringKey("keyB", "ValueB2");
- dict_b.SetStringKey("keyC", "ValueC2");
- dict_b.SetStringKey("keyD", "ValueD2");
+ base::Value::Dict dict_b;
+ dict_b.Set("keyB", "ValueB2");
+ dict_b.Set("keyC", "ValueC2");
+ dict_b.Set("keyD", "ValueD2");
- base::Value dict_c(base::Value::Type::DICTIONARY);
- dict_c.SetStringKey("keyA", "ValueA");
- dict_c.SetStringKey("keyB", "ValueB");
- dict_c.SetStringKey("keyC", "ValueC");
- dict_c.SetStringKey("keyD", "ValueD");
- dict_c.SetStringKey("keyZ", "ValueZ");
+ base::Value::Dict dict_c;
+ dict_c.Set("keyA", "ValueA");
+ dict_c.Set("keyB", "ValueB");
+ dict_c.Set("keyC", "ValueC");
+ dict_c.Set("keyD", "ValueD");
+ dict_c.Set("keyZ", "ValueZ");
- base::Value dict_d(base::Value::Type::DICTIONARY);
- dict_d.SetStringKey("keyC", "ValueC3");
+ base::Value::Dict dict_d;
+ dict_d.Set("keyC", "ValueC3");
- base::Value dict_e(base::Value::Type::DICTIONARY);
- dict_e.SetStringKey("keyD", "ValueD4");
- dict_e.SetIntKey("keyE", 123);
+ base::Value::Dict dict_e;
+ dict_e.Set("keyD", "ValueD4");
+ dict_e.Set("keyE", 123);
- base::Value dict_f(base::Value::Type::DICTIONARY);
- dict_f.SetStringKey("keyX", "ValueX");
- dict_f.SetStringKey("keyE", "ValueE5");
+ base::Value::Dict dict_f;
+ dict_f.Set("keyX", "ValueX");
+ dict_f.Set("keyE", "ValueE5");
// Case 1: kTestPolicyName1 - Merging should only keep keys with the highest
// priority
PolicyMap::Entry case1(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_PLATFORM, dict_a.Clone(), nullptr);
- case1.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_CLOUD, dict_b.Clone(), nullptr));
- case1.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_COMMAND_LINE, dict_c.Clone(), nullptr));
+ POLICY_SOURCE_PLATFORM, base::Value(dict_a.Clone()),
+ nullptr);
+ case1.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
+ base::Value(dict_b.Clone()), nullptr));
+ case1.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_COMMAND_LINE,
+ base::Value(dict_c.Clone()), nullptr));
- base::Value merged_dict_case1(base::Value::Type::DICTIONARY);
- merged_dict_case1.MergeDictionary(&dict_c);
- merged_dict_case1.MergeDictionary(&dict_b);
- merged_dict_case1.MergeDictionary(&dict_a);
+ base::Value::Dict merged_dict_case1;
+ merged_dict_case1.Merge(dict_c.Clone());
+ merged_dict_case1.Merge(dict_b.Clone());
+ merged_dict_case1.Merge(dict_a.Clone());
- PolicyMap::Entry expected_case1(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_MERGED,
- merged_dict_case1.Clone(), nullptr);
+ PolicyMap::Entry expected_case1(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_MERGED,
+ base::Value(merged_dict_case1.Clone()), nullptr);
expected_case1.AddConflictingPolicy(case1.DeepCopy());
// Case 2 - kTestPolicyName2
// Policies should only be merged with other policies with the same target,
// level and scope.
PolicyMap::Entry case2(POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_PLATFORM, dict_e.Clone(), nullptr);
+ POLICY_SOURCE_PLATFORM, base::Value(dict_e.Clone()),
+ nullptr);
- case2.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_CLOUD, dict_f.Clone(), nullptr));
+ case2.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD,
+ base::Value(dict_f.Clone()), nullptr));
- case2.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER,
- POLICY_SOURCE_PLATFORM, dict_a.Clone(), nullptr));
+ case2.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, POLICY_SOURCE_PLATFORM,
+ base::Value(dict_a.Clone()), nullptr));
- base::Value merged_dict_case2(base::Value::Type::DICTIONARY);
- merged_dict_case2.MergeDictionary(&dict_f);
- merged_dict_case2.MergeDictionary(&dict_e);
+ base::Value::Dict merged_dict_case2;
+ merged_dict_case2.Merge(dict_f.Clone());
+ merged_dict_case2.Merge(dict_e.Clone());
- PolicyMap::Entry expected_case2(POLICY_LEVEL_RECOMMENDED,
- POLICY_SCOPE_MACHINE, POLICY_SOURCE_MERGED,
- merged_dict_case2.Clone(), nullptr);
+ PolicyMap::Entry expected_case2(
+ POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_MACHINE, POLICY_SOURCE_MERGED,
+ base::Value(merged_dict_case2.Clone()), nullptr);
expected_case2.AddConflictingPolicy(case2.DeepCopy());
// Case 3 - kTestPolicyName3
// Enterprise default policies should not be merged with other sources.
PolicyMap::Entry case3(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_PLATFORM, dict_a.Clone(), nullptr);
+ POLICY_SOURCE_PLATFORM, base::Value(dict_a.Clone()),
+ nullptr);
- case3.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_COMMAND_LINE, dict_b.Clone(), nullptr));
+ case3.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_COMMAND_LINE,
+ base::Value(dict_b.Clone()), nullptr));
case3.AddConflictingPolicy(PolicyMap::Entry(
POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_ENTERPRISE_DEFAULT, dict_e.Clone(), nullptr));
+ POLICY_SOURCE_ENTERPRISE_DEFAULT, base::Value(dict_e.Clone()), nullptr));
case3.AddConflictingPolicy(PolicyMap::Entry(
POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_ENTERPRISE_DEFAULT, dict_f.Clone(), nullptr));
+ POLICY_SOURCE_ENTERPRISE_DEFAULT, base::Value(dict_f.Clone()), nullptr));
- base::Value merged_dict_case3(base::Value::Type::DICTIONARY);
- merged_dict_case3.MergeDictionary(&dict_b);
- merged_dict_case3.MergeDictionary(&dict_a);
+ base::Value::Dict merged_dict_case3;
+ merged_dict_case3.Merge(dict_b.Clone());
+ merged_dict_case3.Merge(dict_a.Clone());
- PolicyMap::Entry expected_case3(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_MERGED,
- merged_dict_case3.Clone(), nullptr);
+ PolicyMap::Entry expected_case3(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_MERGED,
+ base::Value(merged_dict_case3.Clone()), nullptr);
expected_case3.AddConflictingPolicy(case3.DeepCopy());
// Case 4 - kTestPolicyName4
// Policies with a single source should be merged.
PolicyMap::Entry case4(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_CLOUD, dict_a.Clone(), nullptr);
+ POLICY_SOURCE_CLOUD, base::Value(dict_a.Clone()),
+ nullptr);
PolicyMap::Entry expected_case4(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_MERGED, dict_a.Clone(),
- nullptr);
+ POLICY_SOURCE_MERGED,
+ base::Value(dict_a.Clone()), nullptr);
expected_case4.AddConflictingPolicy(case4.DeepCopy());
// Case 5 - kTestPolicyName5
@@ -843,37 +848,39 @@
// Case 6 - kTestPolicyName6
// User cloud policies should not be merged with other sources.
PolicyMap::Entry case6(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_PLATFORM, dict_a.Clone(), nullptr);
- case6.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_CLOUD, dict_e.Clone(), nullptr));
- case6.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_CLOUD, dict_f.Clone(), nullptr));
+ POLICY_SOURCE_PLATFORM, base::Value(dict_a.Clone()),
+ nullptr);
+ case6.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
+ base::Value(dict_e.Clone()), nullptr));
+ case6.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
+ base::Value(dict_f.Clone()), nullptr));
PolicyMap::Entry expected_case6(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_MERGED, dict_a.Clone(),
- nullptr);
+ POLICY_SOURCE_MERGED,
+ base::Value(dict_a.Clone()), nullptr);
expected_case6.AddConflictingPolicy(case6.DeepCopy());
// Case 7 - kTestPolicyName7
// User platform policies should not be merged under any circumstances.
PolicyMap::Entry case7(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_PLATFORM, dict_a.Clone(), nullptr);
- case7.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_PLATFORM, dict_b.Clone(), nullptr));
- case7.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_CLOUD, dict_c.Clone(), nullptr));
- case7.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_PLATFORM, dict_d.Clone(), nullptr));
- case7.AddConflictingPolicy(
- PolicyMap::Entry(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_COMMAND_LINE, dict_e.Clone(), nullptr));
+ POLICY_SOURCE_PLATFORM, base::Value(dict_a.Clone()),
+ nullptr);
+ case7.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_PLATFORM,
+ base::Value(dict_b.Clone()), nullptr));
+ case7.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
+ base::Value(dict_c.Clone()), nullptr));
+ case7.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE, POLICY_SOURCE_PLATFORM,
+ base::Value(dict_d.Clone()), nullptr));
+ case7.AddConflictingPolicy(PolicyMap::Entry(
+ POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, POLICY_SOURCE_COMMAND_LINE,
+ base::Value(dict_e.Clone()), nullptr));
PolicyMap::Entry expected_case7(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
- POLICY_SOURCE_MERGED, dict_a.Clone(),
- nullptr);
+ POLICY_SOURCE_MERGED,
+ base::Value(dict_a.Clone()), nullptr);
expected_case7.AddConflictingPolicy(case7.DeepCopy());
// Case 8 - kTestPolicyName8
@@ -881,7 +888,8 @@
// If such a policy is explicitly in the list of policies to merge, an error
// is added to the entry and the policy stays intact.
PolicyMap::Entry case8(POLICY_LEVEL_MANDATORY, POLICY_SCOPE_MACHINE,
- POLICY_SOURCE_CLOUD, dict_a.Clone(), nullptr);
+ POLICY_SOURCE_CLOUD, base::Value(dict_a.Clone()),
+ nullptr);
PolicyMap::Entry expected_case8 = case8.DeepCopy();
diff --git a/components/policy/core/common/policy_pref_names.cc b/components/policy/core/common/policy_pref_names.cc
index c2e1122..6d7b5d8 100644
--- a/components/policy/core/common/policy_pref_names.cc
+++ b/components/policy/core/common/policy_pref_names.cc
@@ -5,6 +5,7 @@
#include "components/policy/core/common/policy_pref_names.h"
#include "build/build_config.h"
+#include "policy_pref_names.h"
namespace policy {
namespace policy_prefs {
@@ -136,5 +137,10 @@
const char kPPAPISharedImagesSwapChainAllowed[] =
"policy.ppapi_shared_images_swap_chain_allowed";
+// If true then support for the PPB_VideoDecoder(Dev) API will be enabled;
+// otherwise the browser will decide whether the API is supported.
+const char kForceEnablePepperVideoDecoderDevAPI[] =
+ "policy.force_enable_pepper_video_decoder_dev_api";
+
} // namespace policy_prefs
} // namespace policy
diff --git a/components/policy/core/common/policy_pref_names.h b/components/policy/core/common/policy_pref_names.h
index fe3ff50..2d19167 100644
--- a/components/policy/core/common/policy_pref_names.h
+++ b/components/policy/core/common/policy_pref_names.h
@@ -49,6 +49,7 @@
POLICY_EXPORT extern const char kSendMouseEventsDisabledFormControlsEnabled[];
POLICY_EXPORT extern const char kUseMojoVideoDecoderForPepperAllowed[];
POLICY_EXPORT extern const char kPPAPISharedImagesSwapChainAllowed[];
+POLICY_EXPORT extern const char kForceEnablePepperVideoDecoderDevAPI[];
} // namespace policy_prefs
} // namespace policy
diff --git a/components/policy/core/common/schema.cc b/components/policy/core/common/schema.cc
index 9939c50..479b39e 100644
--- a/components/policy/core/common/schema.cc
+++ b/components/policy/core/common/schema.cc
@@ -394,58 +394,62 @@
// attribute and keys for 'patternProperties' are not checked for valid regulax
// expression syntax. Invalid regular expressions will cause a value validation
// error.
-bool IsValidSchema(const base::Value& dict, int options, std::string* error) {
- DCHECK(dict.is_dict());
+bool IsValidSchema(const base::Value& dict_val,
+ int options,
+ std::string* error) {
+ DCHECK(dict_val.is_dict());
+ const base::Value::Dict& dict = dict_val.GetDict();
// Validate '$ref'.
- const base::Value* ref_id = dict.FindKey(schema::kRef);
- if (ref_id)
- return ValidateAttributesAndTypes(dict, schema::kRef, options, error);
+ if (dict.contains(schema::kRef)) {
+ return ValidateAttributesAndTypes(dict_val, schema::kRef, options, error);
+ }
// Validate 'type'.
- const base::Value* type = dict.FindKey(schema::kType);
- if (!type) {
+ if (!dict.contains(schema::kType)) {
*error = "Each schema must have a 'type' or '$ref'.";
return false;
}
- if (type->type() != base::Value::Type::STRING) {
+
+ const std::string* type = dict.FindString(schema::kType);
+ if (!type) {
*error = "Attribute 'type' must be a string.";
return false;
}
- const std::string type_string = type->GetString();
+ const std::string& type_string = *type;
if (!IsValidType(type_string)) {
*error = base::StringPrintf("Unknown type '%s'.", type_string.c_str());
return false;
}
// Validate attributes and expected types.
- if (!ValidateAttributesAndTypes(dict, type_string, options, error))
+ if (!ValidateAttributesAndTypes(dict_val, type_string, options, error)) {
return false;
+ }
// Validate 'enum' attribute.
if (type_string == schema::kString || type_string == schema::kInteger) {
- const base::Value* enum_list = dict.FindKey(schema::kEnum);
+ const base::Value* enum_list = dict.Find(schema::kEnum);
if (enum_list && !ValidateEnum(enum_list, type_string, error))
return false;
}
if (type_string == schema::kInteger) {
// Validate 'minimum' > 'maximum'.
- const base::Value* minimum_value = dict.FindKey(schema::kMinimum);
- const base::Value* maximum_value = dict.FindKey(schema::kMaximum);
+ const absl::optional<double> minimum_value =
+ dict.FindDouble(schema::kMinimum);
+ const absl::optional<double> maximum_value =
+ dict.FindDouble(schema::kMaximum);
if (minimum_value && maximum_value) {
- double minimum = minimum_value->is_int() ? minimum_value->GetInt()
- : minimum_value->GetDouble();
- double maximum = maximum_value->is_int() ? maximum_value->GetInt()
- : maximum_value->GetDouble();
- if (minimum > maximum) {
- *error = base::StringPrintf("Invalid range specified [%f;%f].", minimum,
- maximum);
+ if (minimum_value.value() > maximum_value.value()) {
+ *error =
+ base::StringPrintf("Invalid range specified [%f;%f].",
+ minimum_value.value(), maximum_value.value());
return false;
}
}
} else if (type_string == schema::kArray) {
// Validate type 'array'.
- const base::Value* items = dict.FindKey(schema::kItems);
+ const base::Value* items = dict.Find(schema::kItems);
if (!items) {
*error = "Schema of type 'array' must have a schema in 'items'.";
return false;
@@ -454,33 +458,33 @@
return false;
} else if (type_string == schema::kObject) {
// Validate type 'object'.
- const base::Value* properties = dict.FindKey(schema::kProperties);
+ const base::Value* properties = dict.Find(schema::kProperties);
if (properties && !ValidateProperties(*properties, options, error))
return false;
const base::Value* pattern_properties =
- dict.FindKey(schema::kPatternProperties);
+ dict.Find(schema::kPatternProperties);
if (pattern_properties &&
!ValidateProperties(*pattern_properties, options, error)) {
return false;
}
const base::Value* additional_properties =
- dict.FindKey(schema::kAdditionalProperties);
+ dict.Find(schema::kAdditionalProperties);
if (additional_properties) {
if (!IsValidSchema(*additional_properties, options, error))
return false;
}
- const base::Value* required = dict.FindKey(schema::kRequired);
+ const base::Value::List* required = dict.FindList(schema::kRequired);
if (required) {
- for (const base::Value& item : required->GetList()) {
+ for (const base::Value& item : *required) {
if (!item.is_string()) {
*error = "Attribute 'required' may only contain strings.";
return false;
}
const std::string property_name = item.GetString();
- if (!properties || !properties->FindKey(property_name)) {
+ if (!properties || !properties->GetDict().contains(property_name)) {
*error = base::StringPrintf(