Skip to content

Commit 13bb12f

Browse files
ckennellycopybara-github
authored andcommitted
Check against reentrancy in debug builds.
PiperOrigin-RevId: 768944793 Change-Id: Iab1db90c1e7a1c65134400206929942eecb76443
1 parent 2a9b30a commit 13bb12f

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

tcmalloc/internal/BUILD

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ cc_library(
6363
],
6464
deps = [
6565
":config",
66+
"//tcmalloc:malloc_hook",
6667
"@com_google_absl//absl/base",
6768
"@com_google_absl//absl/base:core_headers",
6869
],

tcmalloc/internal/allocation_guard.cc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,7 @@
2020
GOOGLE_MALLOC_SECTION_BEGIN
2121
namespace tcmalloc::tcmalloc_internal {
2222

23+
ABSL_CONST_INIT thread_local int AllocationGuard::disallowed_ = 0;
24+
2325
} // namespace tcmalloc::tcmalloc_internal
2426
GOOGLE_MALLOC_SECTION_END

tcmalloc/internal/allocation_guard.h

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,38 @@
1919
#include "absl/base/internal/spinlock.h"
2020
#include "absl/base/thread_annotations.h"
2121
#include "tcmalloc/internal/config.h"
22+
#include "tcmalloc/malloc_hook.h"
2223

2324
GOOGLE_MALLOC_SECTION_BEGIN
2425
namespace tcmalloc::tcmalloc_internal {
2526

26-
// TODO(b/143069684): actually ensure no allocations in debug mode here.
27-
struct AllocationGuard {
28-
AllocationGuard() {}
27+
// In debug mode, ensures that no allocations will occur on the current thread
28+
// while this class is in scope.
29+
class AllocationGuard {
30+
public:
31+
AllocationGuard() {
32+
#ifndef NDEBUG
33+
if (disallowed_ == 0) {
34+
(void)MallocHook::AddNewHook(Hook);
35+
}
36+
++disallowed_;
37+
#endif
38+
}
39+
~AllocationGuard() {
40+
#ifndef NDEBUG
41+
--disallowed_;
42+
if (disallowed_ == 0) {
43+
(void)MallocHook::RemoveNewHook(Hook);
44+
}
45+
#endif
46+
}
47+
48+
private:
49+
static void Hook(const MallocHook::NewInfo& info) {
50+
if (disallowed_ > 0) abort();
51+
}
52+
53+
ABSL_CONST_INIT static thread_local int disallowed_;
2954
};
3055

3156
// A SpinLockHolder that also enforces no allocations while the lock is held in

0 commit comments

Comments
 (0)