[llvm-branch-commits] [compiler-rt] [CopyProf] Add libc interceptors. (PR #232851)

via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Sun Nov 1 11:09:46 PST 2026


https://github.com/newgre updated https://github.com/llvm/llvm-project/pull/232851

>From 3f46fbf33ae33fe6967718733ed1247cecdaad30 Mon Sep 17 00:00:00 2001
From: jannewger <jannewger at gmail.com>
Date: Tue, 20 Oct 2026 22:21:42 +0200
Subject: [PATCH] [CopyProf] Add libc interceptors.

A copy is reported as unnecessary if neither the object nor any memory
it owns is modified before it is destroyed. So far, writes by
uninstrumented code, most importantly library functions (e.g. `memcpy`,
`memset`, etc.), are not accounted for, which leads to false positives.
Interceptors make these writes visible.

Additionally, objects constructed inside a d'tor are now marked as copy,
so that destroying temporaries (e.g. a string built for a log message)
does not suppress reports.

Note that `strndup` and `realpath` are not intercepted yet, as their
interceptors allocate memory via the `malloc` interceptor, which is only
added in a subsequent patch.

RFC:
https://discourse.llvm.org/t/rfc-copysanitizer-csan-detecting-unneccessary-object-copies-at-runtime/91038
Previous PR: #225905
---
 compiler-rt/lib/copyprof/CMakeLists.txt       |   4 +
 compiler-rt/lib/copyprof/copyprof.cpp         |  20 ++-
 .../lib/copyprof/copyprof_interceptors.cpp    |  90 +++++++++++++
 .../lib/copyprof/copyprof_interceptors.h      |  64 +++++++++
 .../copyprof_interceptors_memintrinsics.cpp   |  27 ++++
 compiler-rt/lib/copyprof/copyprof_preinit.cpp |  23 ++++
 compiler-rt/lib/copyprof/copyprof_shadow.cpp  |   6 +-
 compiler-rt/lib/copyprof/copyprof_state.h     |  19 ++-
 compiler-rt/lib/copyprof/tests/CMakeLists.txt |   1 +
 .../tests/copyprof_interceptors_test.cpp      | 121 ++++++++++++++++++
 .../copyprof/tests/copyprof_shadow_test.cpp   |  14 ++
 .../copyprof/tests/copyprof_state_test.cpp    | 105 +++++++++++----
 12 files changed, 461 insertions(+), 33 deletions(-)
 create mode 100644 compiler-rt/lib/copyprof/copyprof_interceptors.cpp
 create mode 100644 compiler-rt/lib/copyprof/copyprof_interceptors.h
 create mode 100644 compiler-rt/lib/copyprof/copyprof_interceptors_memintrinsics.cpp
 create mode 100644 compiler-rt/lib/copyprof/copyprof_preinit.cpp
 create mode 100644 compiler-rt/lib/copyprof/tests/copyprof_interceptors_test.cpp

diff --git a/compiler-rt/lib/copyprof/CMakeLists.txt b/compiler-rt/lib/copyprof/CMakeLists.txt
index 727022db2114a0..da05b8a51c04f5 100644
--- a/compiler-rt/lib/copyprof/CMakeLists.txt
+++ b/compiler-rt/lib/copyprof/CMakeLists.txt
@@ -2,6 +2,9 @@
 
 set(COPYPROF_SOURCES
   copyprof.cpp
+  copyprof_interceptors.cpp
+  copyprof_interceptors_memintrinsics.cpp
+  copyprof_preinit.cpp
   copyprof_reporting.cpp
   copyprof_shadow.cpp
   copyprof_stack.cpp
@@ -9,6 +12,7 @@ set(COPYPROF_SOURCES
 )
 
 set(COPYPROF_HEADERS
+  copyprof_interceptors.h
   copyprof_interface_internal.h
   copyprof_internal.h
   copyprof_reporting.h
diff --git a/compiler-rt/lib/copyprof/copyprof.cpp b/compiler-rt/lib/copyprof/copyprof.cpp
index a272cf83075542..7dd5350440c1d5 100644
--- a/compiler-rt/lib/copyprof/copyprof.cpp
+++ b/compiler-rt/lib/copyprof/copyprof.cpp
@@ -11,6 +11,7 @@
 ///
 //===----------------------------------------------------------------------===//
 
+#include "copyprof_interceptors.h"
 #include "copyprof_interface_internal.h"
 #include "copyprof_reporting.h"
 #include "copyprof_shadow.h"
@@ -38,14 +39,18 @@ static void CheckUnwind() {
 static void Initialize() {
   if (LIKELY(copyprof_is_initialized))
     return;
+  SanitizerToolName = "CopyProf";
   CHECK(!copyprof_init_is_running &&
         "BUG: CopyProf Initialize() must not call itself.");
   copyprof_init_is_running = true;
   CacheBinaryName();
+  // CopyProf uses interception so ensure we're not statically linked.
+  __interception::DoesNotSupportStaticLinking();
   SetCheckUnwindCallback(&CheckUnwind);
   InitializePlatformEarly();
   SetCommonFlagsDefaults();
   InitializeCommonFlags();
+  InitializeInterceptors();
   InitializeShadowMemory();
   copyprof_init_is_running = false;
   copyprof_is_initialized = true;
@@ -74,12 +79,19 @@ static void UpdateShadow(const void* addr, uptr size) {
                         __copyprof_state.smf_context == SmfContext::COPY);
 }
 
+// Marks the shadow memory of an object that is being constructed. Unlike for
+// stores, this also happens in `DTOR` context (see `SmfContext`).
+static void MarkConstructedObject(const void* this_ptr, uptr obj_size) {
+  MarkApplicationMemory(
+      this_ptr, obj_size,
+      ShouldMarkNewMemoryAsCopy(__copyprof_state.smf_context));
+}
+
 static void CopyMemberFunctionEnter(const void* this_ptr, uptr obj_size) {
   MaybeUpdateSmfContext(SmfContext::COPY);
   if (__copyprof_state.copy_nesting_level++ == 0) {
     __copyprof_state.current_this_ptr = this_ptr;
   }
-  UpdateShadow(this_ptr, obj_size);
 }
 
 static void CopyMemberFunctionExit(const void* this_ptr, uptr obj_size) {
@@ -94,7 +106,7 @@ void __copyprof_init_once() { Initialize(); }
 void __copyprof_ctor_enter_callback(const void* this_ptr, uptr obj_size) {
   MaybeUpdateSmfContext(SmfContext::CTOR);
   ++__copyprof_state.construct_nesting_level;
-  UpdateShadow(this_ptr, obj_size);
+  MarkConstructedObject(this_ptr, obj_size);
 }
 
 void __copyprof_ctor_exit_callback(const void* this_ptr, uptr obj_size) {
@@ -105,6 +117,7 @@ void __copyprof_ctor_exit_callback(const void* this_ptr, uptr obj_size) {
 void __copyprof_copy_ctor_enter_callback(const void* this_ptr,
                                          const void* other_ptr, uptr obj_size) {
   CopyMemberFunctionEnter(this_ptr, obj_size);
+  MarkConstructedObject(this_ptr, obj_size);
 }
 
 void __copyprof_copy_ctor_exit_callback(const void* this_ptr,
@@ -116,6 +129,9 @@ void __copyprof_copy_assign_op_enter_callback(const void* this_ptr,
                                               const void* other_ptr,
                                               uptr obj_size) {
   CopyMemberFunctionEnter(this_ptr, obj_size);
+  // Unlike a c'tor, a copy assignment overwrites an existing object, so it is
+  // treated like a store.
+  UpdateShadow(this_ptr, obj_size);
 }
 
 void __copyprof_copy_assign_op_exit_callback(const void* this_ptr,
diff --git a/compiler-rt/lib/copyprof/copyprof_interceptors.cpp b/compiler-rt/lib/copyprof/copyprof_interceptors.cpp
new file mode 100644
index 00000000000000..077c1e096d7b32
--- /dev/null
+++ b/compiler-rt/lib/copyprof/copyprof_interceptors.cpp
@@ -0,0 +1,90 @@
+//===-- copyprof_interceptors.cpp ----------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// This file implements standard library function interceptors for CopyProf,
+/// tracking memory operations across intercepted library calls.
+///
+//===----------------------------------------------------------------------===//
+
+#include "copyprof_interceptors.h"
+
+#include "copyprof/copyprof_interface_internal.h"
+#include "copyprof/copyprof_internal.h"
+#include "interception/interception.h"
+#include "sanitizer_common/sanitizer_common.h"
+#include "sanitizer_common/sanitizer_flags.h"
+#include "sanitizer_common/sanitizer_internal_defs.h"
+
+using namespace __copyprof;
+
+namespace __copyprof {
+
+int CopyProfOnExit() { return 0; }
+
+}  // namespace __copyprof
+
+#define COMMON_INTERCEPTOR_DIR_ACQUIRE(ctx, path) \
+  do {                                            \
+  } while (false)
+
+#define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
+  do {                                         \
+  } while (false)
+
+#define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
+  do {                                         \
+  } while (false)
+
+#define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
+  do {                                                      \
+  } while (false)
+
+#define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
+  do {                                                \
+  } while (false)
+
+#define COMMON_INTERCEPTOR_ON_EXIT(ctx) CopyProfOnExit()
+
+#define COMMON_INTERCEPTOR_SET_PTHREAD_NAME(ctx, thread, name) \
+  do {                                                         \
+  } while (false)
+
+#define COMMON_INTERCEPT_FUNCTION_VER(name, ver)                          \
+  do {                                                                    \
+    if (!INTERCEPT_FUNCTION_VER(name, ver))                               \
+      VReport(1, "CopyProf: failed to intercept '%s@@%s'\n", #name, ver); \
+  } while (0)
+
+#define COMMON_INTERCEPT_FUNCTION_VER_UNVERSIONED_FALLBACK(name, ver)       \
+  do {                                                                      \
+    if (!INTERCEPT_FUNCTION_VER(name, ver) && !INTERCEPT_FUNCTION(name))    \
+      VReport(1, "CopyProf: failed to intercept '%s@@%s' or '%s'\n", #name, \
+              ver, #name);                                                  \
+  } while (0)
+
+#define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name)
+
+#include "sanitizer_common/sanitizer_platform_interceptors.h"
+// These interceptors allocate memory via `WRAP(malloc)`, but heap functions are
+// not intercepted yet.
+#undef SANITIZER_INTERCEPT_STRNDUP
+#undef SANITIZER_INTERCEPT___STRNDUP
+#undef SANITIZER_INTERCEPT_REALPATH
+
+#include "sanitizer_common/sanitizer_common_interceptors.inc"
+
+namespace __copyprof {
+
+void InitializeInterceptors() {
+  static bool initialized;
+  CHECK(!initialized);
+  initialized = true;
+  InitializeCommonInterceptors();
+}
+
+}  // namespace __copyprof
diff --git a/compiler-rt/lib/copyprof/copyprof_interceptors.h b/compiler-rt/lib/copyprof/copyprof_interceptors.h
new file mode 100644
index 00000000000000..c4aa32118a254b
--- /dev/null
+++ b/compiler-rt/lib/copyprof/copyprof_interceptors.h
@@ -0,0 +1,64 @@
+//===-- copyprof_interceptors.h -------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// This file declares the standard library interceptor interface for CopyProf,
+/// defining hooks for intercepted memory and string functions.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef COPYPROF_INTERCEPTORS_H
+#define COPYPROF_INTERCEPTORS_H
+
+#include "copyprof_interface_internal.h"
+#include "copyprof_internal.h"
+#include "interception/interception.h"
+
+// Functions whose interceptor is defined in another TU.
+DECLARE_REAL(void*, memset, void* block, int c, SIZE_T size)
+DECLARE_REAL(void*, memcpy, void* to, const void* from, SIZE_T size)
+
+// The macros below must be defined when using the interceptor infrastructure
+// (i.e. sanitizer_common_interceptors*.inc files).
+#define COPYPROF_INTERCEPT_FUNC(name)                            \
+  do {                                                           \
+    if (!INTERCEPT_FUNCTION(name))                               \
+      VReport(1, "CopyProf: failed to intercept '%s'\n", #name); \
+  } while (0)
+#define COMMON_INTERCEPT_FUNCTION(name) COPYPROF_INTERCEPT_FUNC(name)
+
+#define COMMON_INTERCEPTOR_ENTER(ctx, func, ...) \
+  do {                                           \
+    ctx = 0;                                     \
+    (void)ctx;                                   \
+    if (copyprof_init_is_running)                \
+      return REAL(func)(__VA_ARGS__);            \
+    if (UNLIKELY(!copyprof_is_initialized))      \
+      __copyprof_init_once();                    \
+  } while (false)
+
+#define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
+  do {                                                \
+    (void)(ctx);                                      \
+    (void)(ptr);                                      \
+    (void)(size);                                     \
+  } while (false)
+
+#define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
+  __copyprof_store_callback(ptr, size)
+
+#define COMMON_INTERCEPTOR_NOTHING_IS_INITIALIZED (!copyprof_is_initialized)
+
+namespace __copyprof {
+
+// Initializes the interception infrastructure, s.t. CopyProf can hook into
+// library functions or syscalls. Must be called once during startup.
+void InitializeInterceptors();
+
+}  // namespace __copyprof
+
+#endif  // COPYPROF_INTERCEPTORS_H
diff --git a/compiler-rt/lib/copyprof/copyprof_interceptors_memintrinsics.cpp b/compiler-rt/lib/copyprof/copyprof_interceptors_memintrinsics.cpp
new file mode 100644
index 00000000000000..0794772d4e3933
--- /dev/null
+++ b/compiler-rt/lib/copyprof/copyprof_interceptors_memintrinsics.cpp
@@ -0,0 +1,27 @@
+//===-- copyprof_interceptors_memintrinsics.cpp --------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// This file implements interceptors for memory intrinsic functions (memcpy,
+/// memmove, memset) to correctly maintain shadow memory status.
+///
+//===----------------------------------------------------------------------===//
+
+#define SANITIZER_COMMON_NO_REDEFINE_BUILTINS
+
+#include "copyprof_interceptors.h"
+#include "sanitizer_common/sanitizer_flags.h"
+#include "sanitizer_common/sanitizer_libc.h"
+
+using namespace __copyprof;
+using namespace __sanitizer;
+
+// The default implementations fall back to the internal intrinsics until
+// CopyProf is initialized (they may be called during `__copyprof_init_once`,
+// e.g. from the internals of `Printf`), and only update shadow memory if
+// `intercept_intrin` is set.
+#include "sanitizer_common/sanitizer_common_interceptors_memintrinsics.inc"
diff --git a/compiler-rt/lib/copyprof/copyprof_preinit.cpp b/compiler-rt/lib/copyprof/copyprof_preinit.cpp
new file mode 100644
index 00000000000000..acc6e37d287f8f
--- /dev/null
+++ b/compiler-rt/lib/copyprof/copyprof_preinit.cpp
@@ -0,0 +1,23 @@
+//===-- copyprof_preinit.cpp ---------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// This file sets up early pre-initialization hooks for CopyProf, ensuring the
+/// runtime initializes before any instrumented application code runs.
+///
+//===----------------------------------------------------------------------===//
+
+#include "copyprof_interface_internal.h"
+
+using namespace __copyprof;
+
+// Make sure CopyProf initialization runs as early as possible as some
+// applications use preinit_array on their own.
+#if SANITIZER_CAN_USE_PREINIT_ARRAY
+__attribute__((section(".preinit_array"), used)) static auto preinit =
+    __copyprof_init_once;
+#endif
diff --git a/compiler-rt/lib/copyprof/copyprof_shadow.cpp b/compiler-rt/lib/copyprof/copyprof_shadow.cpp
index e5b52baa8acd88..2e1872f4c50ccf 100644
--- a/compiler-rt/lib/copyprof/copyprof_shadow.cpp
+++ b/compiler-rt/lib/copyprof/copyprof_shadow.cpp
@@ -60,7 +60,8 @@ void InitializeShadowMemory() {
 }
 
 void MarkApplicationMemory(const void* app_addr, uptr num_bytes, bool is_copy) {
-  CHECK_GT(num_bytes, 0);
+  if (UNLIKELY(num_bytes == 0))
+    return;
   const uptr addr = reinterpret_cast<uptr>(app_addr);
   unsigned char* shadow =
       reinterpret_cast<unsigned char*>(g_copy_shadow.MemToShadow(addr));
@@ -85,7 +86,8 @@ void MarkApplicationMemory(const void* app_addr, uptr num_bytes, bool is_copy) {
 }
 
 bool IsMarkedAsCopy(const void* app_addr, uptr num_bytes) {
-  CHECK_GT(num_bytes, 0);
+  if (UNLIKELY(num_bytes == 0))
+    return true;
   const uptr addr = reinterpret_cast<uptr>(app_addr);
   const auto* shadow =
       reinterpret_cast<const unsigned char*>(g_copy_shadow.MemToShadow(addr));
diff --git a/compiler-rt/lib/copyprof/copyprof_state.h b/compiler-rt/lib/copyprof/copyprof_state.h
index 13cb6a94c38ea3..b342f1de7a1c6b 100644
--- a/compiler-rt/lib/copyprof/copyprof_state.h
+++ b/compiler-rt/lib/copyprof/copyprof_state.h
@@ -26,10 +26,15 @@ namespace __copyprof {
 // to `CTOR`, and a d'tor to `DTOR`.
 // In the `COPY` context, shadow memory is marked as copy.
 // In the `CTOR` context, shadow memory is marked as non-copy.
-// In the `DTOR` context, no shadow memory is updated at all (to
-// avoid false negatives during destruction). Once control flow leaves (any
-// nested) special member functions, the context is set to `NONE`. In this
-// state, any stores mark shadow memory as non-copy.
+// In the `DTOR` context, shadow memory is not updated (to avoid false negatives
+// during destruction), except that newly constructed objects are marked as
+// copy, so that destroying temporaries does not cause false negatives either
+// (see TemporaryObjectInDtorDoesNotSuppressReport). Note that newly created
+// temporary objects inside d'tors would still check their shadow memory when
+// destroyed, but if that is never updated when constructed, its state wouldn't
+// be meaningful. That's why shadow memory is marked as copy in d'tors as well.
+// Once control flow leaves (any nested) special member functions, the context
+// is set to `NONE`. In this state, any stores mark shadow memory as non-copy.
 enum class SmfContext : u8 {
   NONE,
   CTOR,
@@ -37,6 +42,12 @@ enum class SmfContext : u8 {
   DTOR,
 };
 
+// Whether memory that is newly constructed in `ctx` is marked as copy (see
+// `SmfContext`).
+inline bool ShouldMarkNewMemoryAsCopy(SmfContext ctx) {
+  return ctx == SmfContext::COPY || ctx == SmfContext::DTOR;
+}
+
 // CopyProf uses per-thread state to figure out whether control flow is
 // currently inside a special member function, and adapts updating of shadow
 // memory accordingly (see SmfContext). Since special member functions can
diff --git a/compiler-rt/lib/copyprof/tests/CMakeLists.txt b/compiler-rt/lib/copyprof/tests/CMakeLists.txt
index 948d7a1cb88a7b..e3042f936b8ac8 100644
--- a/compiler-rt/lib/copyprof/tests/CMakeLists.txt
+++ b/compiler-rt/lib/copyprof/tests/CMakeLists.txt
@@ -19,6 +19,7 @@ file(GLOB COPYPROF_HEADERS ../*.h)
 
 set(COPYPROF_NOINST_TEST_SOURCES
   driver.cpp
+  copyprof_interceptors_test.cpp
   copyprof_shadow_test.cpp
   copyprof_state_test.cpp)
 
diff --git a/compiler-rt/lib/copyprof/tests/copyprof_interceptors_test.cpp b/compiler-rt/lib/copyprof/tests/copyprof_interceptors_test.cpp
new file mode 100644
index 00000000000000..b6d85f279f4f93
--- /dev/null
+++ b/compiler-rt/lib/copyprof/tests/copyprof_interceptors_test.cpp
@@ -0,0 +1,121 @@
+//===-- copyprof_interceptors_test.cpp ------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include <string.h>
+
+#include "copyprof/copyprof_interface_internal.h"
+#include "copyprof/copyprof_shadow.h"
+#include "copyprof/copyprof_state.h"
+#include "gtest/gtest.h"
+
+namespace __copyprof {
+namespace {
+
+// The intercepted functions are called through volatile function pointers, so
+// that the compiler cannot replace the calls with inline stores, which would
+// bypass the interceptors.
+void* (*volatile memset_fn)(void*, int, size_t) = memset;
+void* (*volatile memcpy_fn)(void*, const void*, size_t) = memcpy;
+void* (*volatile memmove_fn)(void*, const void*, size_t) = memmove;
+
+class CopyProfInterceptorsTest : public testing::Test {
+ protected:
+  void SetUp() override {
+    __copyprof_init_once();
+    __copyprof_state = PerThreadState();
+  }
+};
+
+TEST_F(CopyProfInterceptorsTest, MemsetMarksDestinationAsNonCopy) {
+  alignas(8) char buf[32] = {0};
+  MarkApplicationMemory(buf, sizeof(buf), /*is_copy=*/true);
+
+  memset_fn(buf + 8, /*c=*/1, /*size=*/8);
+  EXPECT_TRUE(IsMarkedAsCopy(buf, /*num_bytes=*/8));
+  EXPECT_FALSE(IsMarkedAsCopy(buf + 8, /*num_bytes=*/8));
+  EXPECT_TRUE(IsMarkedAsCopy(buf + 16, /*num_bytes=*/16));
+}
+
+TEST_F(CopyProfInterceptorsTest, MemcpyMarksOnlyDestinationAsNonCopy) {
+  alignas(8) char dst[32] = {0};
+  alignas(8) char src[32] = {0};
+  MarkApplicationMemory(dst, sizeof(dst), /*is_copy=*/true);
+  MarkApplicationMemory(src, sizeof(src), /*is_copy=*/true);
+
+  memcpy_fn(dst, src, sizeof(dst));
+  EXPECT_FALSE(IsMarkedAsCopy(dst, sizeof(dst)));
+  EXPECT_TRUE(IsMarkedAsCopy(src, sizeof(src)));
+}
+
+TEST_F(CopyProfInterceptorsTest, MemmoveMarksOnlyDestinationAsNonCopy) {
+  alignas(8) char buf[32] = {0};
+  MarkApplicationMemory(buf, sizeof(buf), /*is_copy=*/true);
+
+  // Overlapping move of `[0, 16)` to `[8, 24)`.
+  memmove_fn(buf + 8, buf, /*size=*/16);
+  EXPECT_TRUE(IsMarkedAsCopy(buf, /*num_bytes=*/8));
+  EXPECT_FALSE(IsMarkedAsCopy(buf + 8, /*num_bytes=*/16));
+  EXPECT_TRUE(IsMarkedAsCopy(buf + 24, /*num_bytes=*/8));
+}
+
+// Zero-sized writes must not touch shadow memory.
+TEST_F(CopyProfInterceptorsTest, ZeroSizedWriteLeavesShadowUnchanged) {
+  alignas(8) char buf[16] = {0};
+  MarkApplicationMemory(buf, sizeof(buf), /*is_copy=*/true);
+
+  memset_fn(buf + 3, /*c=*/1, /*size=*/0);
+  memcpy_fn(buf + 3, buf, /*size=*/0);
+  EXPECT_TRUE(IsMarkedAsCopy(buf, sizeof(buf)));
+}
+
+// A copy c'tor may copy (trivially copyable) members via `memcpy`, which must
+// mark the copy as such.
+TEST_F(CopyProfInterceptorsTest, WriteDuringCopyMarksAsCopy) {
+  alignas(8) char obj[32] = {0};
+  alignas(8) char other[32] = {0};
+
+  __copyprof_copy_ctor_enter_callback(obj, other, sizeof(obj));
+  memcpy_fn(obj, other, sizeof(obj));
+  __copyprof_copy_ctor_exit_callback(obj, other, sizeof(obj));
+  EXPECT_TRUE(IsMarkedAsCopy(obj, sizeof(obj)));
+}
+
+// Like stores, writes by library functions during destruction must not clear
+// the copy shadow bits.
+TEST_F(CopyProfInterceptorsTest, WriteDuringDtorLeavesShadowUnchanged) {
+  alignas(8) char obj[32] = {0};
+  alignas(8) char other[32] = {0};
+
+  __copyprof_copy_ctor_enter_callback(obj, other, sizeof(obj));
+  __copyprof_copy_ctor_exit_callback(obj, other, sizeof(obj));
+
+  __copyprof_dtor_enter_callback(obj, sizeof(obj));
+  memset_fn(obj, /*c=*/0, sizeof(obj));
+  EXPECT_TRUE(IsMarkedAsCopy(obj, sizeof(obj)));
+  __copyprof_dtor_exit_callback(obj, sizeof(obj));
+  EXPECT_TRUE(__copyprof_state.is_transitive_copy);
+}
+
+// Modifying a copy via a library function makes it a necessary copy.
+TEST_F(CopyProfInterceptorsTest, ModifyingCopyViaLibraryCallClearsCopy) {
+  alignas(8) char obj[32] = {0};
+  alignas(8) char other[32] = {0};
+
+  __copyprof_copy_ctor_enter_callback(obj, other, sizeof(obj));
+  __copyprof_copy_ctor_exit_callback(obj, other, sizeof(obj));
+  ASSERT_TRUE(IsMarkedAsCopy(obj, sizeof(obj)));
+
+  memset_fn(obj + 4, /*c=*/1, /*size=*/1);
+
+  __copyprof_dtor_enter_callback(obj, sizeof(obj));
+  __copyprof_dtor_exit_callback(obj, sizeof(obj));
+  EXPECT_FALSE(__copyprof_state.is_transitive_copy);
+}
+
+}  // namespace
+}  // namespace __copyprof
diff --git a/compiler-rt/lib/copyprof/tests/copyprof_shadow_test.cpp b/compiler-rt/lib/copyprof/tests/copyprof_shadow_test.cpp
index 7a3c4b38c9f33a..1074d2494ae97e 100644
--- a/compiler-rt/lib/copyprof/tests/copyprof_shadow_test.cpp
+++ b/compiler-rt/lib/copyprof/tests/copyprof_shadow_test.cpp
@@ -160,5 +160,19 @@ TEST(CopyProfShadowTest, PartialOverwrite) {
   EXPECT_TRUE(IsMarkedAsCopy(&buf[2], 2 * sizeof(u64)));
 }
 
+TEST(CopyProfShadowTest, ZeroSizedRange) {
+  __copyprof_init_once();
+  alignas(8) unsigned char buf[16] = {0};
+  MarkApplicationMemory(buf, sizeof(buf), /*is_copy=*/false);
+
+  // Zero-byte mark (aligned and unaligned) must be a no-op.
+  MarkApplicationMemory(buf, 0, /*is_copy=*/true);
+  MarkApplicationMemory(buf + 3, 0, /*is_copy=*/true);
+  EXPECT_FALSE(IsMarkedAsCopy(buf, sizeof(buf)));
+
+  EXPECT_TRUE(IsMarkedAsCopy(buf, 0));
+  EXPECT_TRUE(IsMarkedAsCopy(buf + 3, 0));
+}
+
 }  // namespace
 }  // namespace __copyprof
diff --git a/compiler-rt/lib/copyprof/tests/copyprof_state_test.cpp b/compiler-rt/lib/copyprof/tests/copyprof_state_test.cpp
index 4217902307169b..92b4bdceae1db1 100644
--- a/compiler-rt/lib/copyprof/tests/copyprof_state_test.cpp
+++ b/compiler-rt/lib/copyprof/tests/copyprof_state_test.cpp
@@ -107,16 +107,16 @@ TEST_F(CopyProfStateTest, CheckModeIgnoresStores) {
   __copyprof_dtor_exit_callback(obj, sizeof(obj));
 }
 
-// Tests that the `DTOR` context invariant covers every shadow write, not just
-// stores. A temporary object created inside a d'tor must leave shadow memory
-// alone too.
-TEST_F(CopyProfStateTest, CheckModeIgnoresConstruction) {
+// A temporary object created inside a d'tor is marked as copy, so that
+// destroying it does not suppress the report (see
+// TemporaryObjectInDtorDoesNotSuppressReport).
+TEST_F(CopyProfStateTest, ConstructionInDtorMarksAsCopy) {
   char obj[32] = {0};
   char other[32] = {0};
   char scratch[32] = {0};
 
-  // Mark `scratch` as a copy up front so a stray shadow write is observable.
-  MarkApplicationMemory(scratch, sizeof(scratch), /*is_copy=*/true);
+  // Mark `scratch` as non-copy up front so the shadow write is observable.
+  MarkApplicationMemory(scratch, sizeof(scratch), /*is_copy=*/false);
 
   __copyprof_copy_ctor_enter_callback(obj, other, sizeof(obj));
   __copyprof_copy_ctor_exit_callback(obj, other, sizeof(obj));
@@ -125,30 +125,38 @@ TEST_F(CopyProfStateTest, CheckModeIgnoresConstruction) {
   __copyprof_dtor_enter_callback(obj, sizeof(obj));
   __copyprof_ctor_enter_callback(scratch, sizeof(scratch));
   __copyprof_ctor_exit_callback(scratch, sizeof(scratch));
-  // The c'tor must not have modified shadow memory so `scratch` must still be
-  // marked as copy.
   EXPECT_TRUE(IsMarkedAsCopy(scratch, sizeof(scratch)));
   __copyprof_dtor_exit_callback(obj, sizeof(obj));
 }
 
+// Unlike a c'tor, a copy assignment inside a d'tor overwrites an existing
+// object, so it must leave shadow memory alone, just like a store.
+TEST_F(CopyProfStateTest, CheckModeIgnoresCopyAssignment) {
+  char obj[32] = {0};
+  char other[32] = {0};
+  char target[32] = {0};
+
+  // Mark `target` as non-copy up front so a stray shadow write is observable.
+  MarkApplicationMemory(target, sizeof(target), /*is_copy=*/false);
+
+  __copyprof_copy_ctor_enter_callback(obj, other, sizeof(obj));
+  __copyprof_copy_ctor_exit_callback(obj, other, sizeof(obj));
+
+  // Enter the d'tor, then copy-assign to `target`.
+  __copyprof_dtor_enter_callback(obj, sizeof(obj));
+  __copyprof_copy_assign_op_enter_callback(target, other, sizeof(target));
+  __copyprof_copy_assign_op_exit_callback(target, other, sizeof(target));
+  EXPECT_FALSE(IsMarkedAsCopy(target, sizeof(target)));
+  __copyprof_dtor_exit_callback(obj, sizeof(obj));
+}
+
 // A d'tor whose body constructs and destroys an object that the destroyed
-// object does not own must not suppress the report. `is_transitive_copy` is
-// folded with `IsMarkedAsCopy` for every nested d'tor exit, with no check that
-// the nested object is reachable from the top-level one, so any local in the
-// d'tor body (a string built for a log message, a lock guard, an iterator)
-// clears it. Contrast with SimulatedUnnecessaryCopy, which is the same
-// scenario with an empty d'tor body and does report.
-//
-// DISABLED: this is a known limitation of the minimal runtime, not a defect to
-// be fixed in isolation. Telling a temporary created *by* the d'tor apart from
-// a sub-object that the destroyed object *owns* requires per-object state keyed
-// by allocation, which arrives with the malloc/new interceptors in a follow-up
-// patch. Restricting the fold to the top-level object's flat extent does make
-// this test pass, but it then misses heap-owned sub-objects with non-trivial
-// d'tors (`std::vector<std::string>`), turning a false negative into a false
-// positive -- the worse trade for this tool. Re-enable once allocation
-// tracking can supply the ownership predicate.
-TEST_F(CopyProfStateTest, DISABLED_TemporaryObjectInDtorDoesNotSuppressReport) {
+// object does not own (a string built for a log message, a lock guard, an
+// iterator) must not suppress the report. Objects constructed inside a d'tor
+// are marked as copy, so destroying them leaves `is_transitive_copy` unchanged.
+// Contrast with SimulatedUnnecessaryCopy, which is the same scenario with an
+// empty d'tor body.
+TEST_F(CopyProfStateTest, TemporaryObjectInDtorDoesNotSuppressReport) {
   char obj[32] = {0};
   char source_obj[32] = {0};
   char local[32] = {0};
@@ -174,5 +182,52 @@ TEST_F(CopyProfStateTest, DISABLED_TemporaryObjectInDtorDoesNotSuppressReport) {
   EXPECT_TRUE(__copyprof_state.is_transitive_copy);
 }
 
+// Likewise for a temporary that the d'tor copy-constructs, e.g. from a member.
+TEST_F(CopyProfStateTest, CopiedTemporaryInDtorDoesNotSuppressReport) {
+  char obj[32] = {0};
+  char source_obj[32] = {0};
+  char temp[32] = {0};
+
+  __copyprof_copy_ctor_enter_callback(obj, source_obj, sizeof(obj));
+  __copyprof_copy_ctor_exit_callback(obj, source_obj, sizeof(obj));
+  // Memory occupied by `temp` is not a copy.
+  MarkApplicationMemory(temp, sizeof(temp), /*is_copy=*/false);
+
+  __copyprof_dtor_enter_callback(obj, sizeof(obj));
+  __copyprof_copy_ctor_enter_callback(temp, obj, sizeof(temp));
+  __copyprof_copy_ctor_exit_callback(temp, obj, sizeof(temp));
+  __copyprof_dtor_enter_callback(temp, sizeof(temp));
+  __copyprof_dtor_exit_callback(temp, sizeof(temp));
+  __copyprof_dtor_exit_callback(obj, sizeof(obj));
+  EXPECT_TRUE(__copyprof_state.is_transitive_copy);
+}
+
+// A temporary with a trivial c'tor gets no c'tor callback, so it is not marked
+// as copy when a d'tor creates it. If its d'tor is instrumented, destroying it
+// folds whatever shadow its memory had before into `is_transitive_copy`, which
+// may suppress the report.
+//
+// DISABLED: known limitation. Possible fixes are to also instrument trivial
+// construction, or to skip the fold for objects in the stack frames below the
+// top-level d'tor.
+TEST_F(CopyProfStateTest,
+       DISABLED_TriviallyConstructedTemporaryInDtorDoesNotSuppressReport) {
+  char obj[32] = {0};
+  char source_obj[32] = {0};
+  char temp[32] = {0};
+
+  __copyprof_copy_ctor_enter_callback(obj, source_obj, sizeof(obj));
+  __copyprof_copy_ctor_exit_callback(obj, source_obj, sizeof(obj));
+  // Memory occupied by `temp` is not a copy.
+  MarkApplicationMemory(temp, sizeof(temp), /*is_copy=*/false);
+
+  __copyprof_dtor_enter_callback(obj, sizeof(obj));
+  // `temp` is created without a c'tor callback, then destroyed.
+  __copyprof_dtor_enter_callback(temp, sizeof(temp));
+  __copyprof_dtor_exit_callback(temp, sizeof(temp));
+  __copyprof_dtor_exit_callback(obj, sizeof(obj));
+  EXPECT_TRUE(__copyprof_state.is_transitive_copy);
+}
+
 }  // namespace
 }  // namespace __copyprof



More information about the llvm-branch-commits mailing list