https://github.com/DanBlackwell updated https://github.com/llvm/llvm-project/pull/238426
>From 45cc7b32524d19467a403c997a6fcaf32279adad Mon Sep 17 00:00:00 2001 From: Dan Blackwell <[email protected]> Date: Fri, 30 Oct 2026 10:31:53 -0700 Subject: [PATCH] [TSan][ObjC] Make TSan able to detect races on 'nonatomic, copy' properties Currently TSan is not able to observe the write that occurs when a property marked as copy occurs in Objective-C code, resulting in false negatives. This patch fixes that by modifying the instrumentation pass to insert the required TSan runtime calls before the associated Objective-C runtime calls. Assisted by LLMs rdar://191638298 --- .../sanitize-thread-copy-property.m | 21 +++++ .../tsan/Darwin/objc-copy-property-race.mm | 93 +++++++++++++++++++ .../Instrumentation/ThreadSanitizer.cpp | 76 ++++++++++++++- .../ThreadSanitizer/objc-set-property.ll | 70 ++++++++++++++ 4 files changed, 259 insertions(+), 1 deletion(-) create mode 100644 clang/test/CodeGenObjC/sanitize-thread-copy-property.m create mode 100644 compiler-rt/test/tsan/Darwin/objc-copy-property-race.mm create mode 100644 llvm/test/Instrumentation/ThreadSanitizer/objc-set-property.ll diff --git a/clang/test/CodeGenObjC/sanitize-thread-copy-property.m b/clang/test/CodeGenObjC/sanitize-thread-copy-property.m new file mode 100644 index 00000000000000..72195fb65033f1 --- /dev/null +++ b/clang/test/CodeGenObjC/sanitize-thread-copy-property.m @@ -0,0 +1,21 @@ +// RUN: %clang_cc1 -triple arm64-apple-macosx11.0.0 -fobjc-runtime=macosx-11.0.0 -O0 -emit-llvm -fobjc-arc -fsanitize=thread -o - %s | FileCheck %s +// RUN: %clang_cc1 -triple arm64-apple-macosx11.0.0 -fobjc-runtime=macosx-11.0.0 -O1 -emit-llvm -fobjc-arc -fsanitize=thread -o - %s | FileCheck %s + +__attribute__((objc_root_class)) +@interface CopyContainer { + Class _isa; +} +@property(nonatomic, copy) id nonatomicCopyProp; +@property(atomic, copy) id atomicCopyProp; +@end + +// CHECK-LABEL: define internal void @"\01-[CopyContainer setNonatomicCopyProp:]"( +// CHECK: [[ADDR:%.*]] = getelementptr i8, ptr [[SELF:%.*]], i64 {{.*}} +// CHECK-NEXT: call void @__tsan_write8(ptr [[ADDR]]) +// CHECK-NEXT: {{(tail )?}}call void @objc_setProperty_nonatomic_copy(ptr noundef [[SELF]], ptr noundef {{.*}}, ptr noundef {{.*}}, i64 noundef {{.*}}) + +// CHECK-LABEL: define internal void @"\01-[CopyContainer setAtomicCopyProp:]"( +// CHECK-NOT: call void @__tsan_write8 +// CHECK: {{(tail )?}}call void @objc_setProperty_atomic_copy( +@implementation CopyContainer +@end diff --git a/compiler-rt/test/tsan/Darwin/objc-copy-property-race.mm b/compiler-rt/test/tsan/Darwin/objc-copy-property-race.mm new file mode 100644 index 00000000000000..f11ec45106c1ad --- /dev/null +++ b/compiler-rt/test/tsan/Darwin/objc-copy-property-race.mm @@ -0,0 +1,93 @@ +// Verify that ThreadSanitizer detects data races on Objective-C synthesized +// (nonatomic, copy) properties at both -O0 and -O2, and does not report races +// on (atomic, copy) properties. + +// RUN: %clangxx_tsan %s -o %t_O0 -O0 -fobjc-arc -framework Foundation +// RUN: %deflake %run %t_O0 2>&1 | FileCheck %s + +// RUN: %clangxx_tsan %s -o %t_O2 -O2 -fobjc-arc -framework Foundation +// RUN: %deflake %run %t_O2 2>&1 | FileCheck %s + +#import <Foundation/Foundation.h> +#import "../test.h" + +@interface CopyContainer : NSObject +@property(nonatomic, copy) NSString *text; +@property(nonatomic, copy) NSString *readWriteText; +@property(atomic, copy) NSString *atomicText; +@end + +@implementation CopyContainer +@end + +int main() { + @autoreleasepool { + CopyContainer *c = [CopyContainer new]; + NSString *s1 = [NSString stringWithFormat:@"hello-non-tagged-string-%d", 1]; + NSString *s2 = [NSString stringWithFormat:@"world-non-tagged-string-%d", 2]; + dispatch_queue_t q = + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + // 1. Concurrent access to an (atomic, copy) property must not race. + { + barrier_init(&barrier, 2); + dispatch_group_t group = dispatch_group_create(); + dispatch_group_async(group, q, ^{ + c.atomicText = s1; + barrier_wait(&barrier); + }); + dispatch_group_async(group, q, ^{ + barrier_wait(&barrier); + c.atomicText = s2; + }); + dispatch_group_wait(group, DISPATCH_TIME_FOREVER); + NSLog(@"Atomic write completed."); + } + + // 2. Write-vs-Write race on a (nonatomic, copy) property. + { + barrier_init(&barrier, 2); + dispatch_group_t group = dispatch_group_create(); + dispatch_group_async(group, q, ^{ + c.text = s1; + barrier_wait(&barrier); + }); + dispatch_group_async(group, q, ^{ + barrier_wait(&barrier); + c.text = s2; + }); + dispatch_group_wait(group, DISPATCH_TIME_FOREVER); + } + + // 3. Read-vs-Write race (getter vs setter) on a (nonatomic, copy) property. + { + c.readWriteText = s1; + barrier_init(&barrier, 2); + dispatch_group_t group = dispatch_group_create(); + dispatch_group_async(group, q, ^{ + c.readWriteText = s2; + barrier_wait(&barrier); + }); + dispatch_group_async(group, q, ^{ + barrier_wait(&barrier); + (void)c.readWriteText; + }); + dispatch_group_wait(group, DISPATCH_TIME_FOREVER); + } + } + return 0; +} + +// CHECK-NOT: setAtomicText: +// CHECK: Atomic write completed. +// CHECK: WARNING: ThreadSanitizer: data race +// CHECK: Write of size 8 at {{0x[0-9a-f]+}} by thread T{{[0-9]+}}: +// CHECK: #0 -[CopyContainer setText:] +// CHECK: Previous write of size 8 at {{0x[0-9a-f]+}} by thread T{{[0-9]+}}: +// CHECK: #0 -[CopyContainer setText:] + +// CHECK: WARNING: ThreadSanitizer: data race +// CHECK: Read of size 8 at {{0x[0-9a-f]+}} by thread T{{[0-9]+}}: +// CHECK: #0 -[CopyContainer readWriteText] +// CHECK: Previous write of size 8 at {{0x[0-9a-f]+}} by thread T{{[0-9]+}}: +// CHECK: #0 -[CopyContainer setReadWriteText:] diff --git a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp index a2ea0a011e9399..c1e36511f9c9ab 100644 --- a/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp +++ b/llvm/lib/Transforms/Instrumentation/ThreadSanitizer.cpp @@ -104,6 +104,7 @@ struct ThreadSanitizer { bool instrumentLoadOrStore(const InstructionInfo &II, const DataLayout &DL); bool instrumentAtomic(Instruction *I, const DataLayout &DL); bool instrumentMemIntrinsic(Instruction *I); + bool instrumentObjCSetProperty(CallBase *CB, const DataLayout &DL); void chooseInstructionsToInstrument(SmallVectorImpl<Instruction *> &Local, SmallVectorImpl<InstructionInfo> &All, const DataLayout &DL); @@ -139,6 +140,9 @@ struct ThreadSanitizer { FunctionCallee TsanVptrUpdate; FunctionCallee TsanVptrLoad; FunctionCallee MemmoveFn, MemcpyFn, MemsetFn; + Function *ObjCSetPropertyNonAtomicFn = nullptr; + Function *ObjCSetPropertyNonAtomicCopyFn = nullptr; + Function *ObjCSetPropertyFn = nullptr; }; void insertModuleCtor(Module &M) { @@ -313,6 +317,11 @@ void ThreadSanitizer::initialize(Module &M, const TargetLibraryInfo &TLI) { "__tsan_memset", TLI.getAttrList(&Ctx, {1}, /*Signed=*/true, /*Ret=*/false, Attr), IRB.getPtrTy(), IRB.getPtrTy(), IRB.getInt32Ty(), IntptrTy); + + ObjCSetPropertyNonAtomicFn = M.getFunction("objc_setProperty_nonatomic"); + ObjCSetPropertyNonAtomicCopyFn = + M.getFunction("objc_setProperty_nonatomic_copy"); + ObjCSetPropertyFn = M.getFunction("objc_setProperty"); } static bool isVtableAccess(Instruction *I) { @@ -485,9 +494,13 @@ bool ThreadSanitizer::sanitizeFunction(Function &F, SmallVector<Instruction*, 8> LocalLoadsAndStores; SmallVector<Instruction*, 8> AtomicAccesses; SmallVector<Instruction*, 8> MemIntrinCalls; + SmallVector<CallBase *, 8> ObjCSetPropertyCalls; bool Res = false; bool HasCalls = false; bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeThread); + const bool HasObjCSetProperty = ObjCSetPropertyNonAtomicFn || + ObjCSetPropertyNonAtomicCopyFn || + ObjCSetPropertyFn; const DataLayout &DL = F.getDataLayout(); // Traverse all instructions, collect loads/stores/returns, check for calls. @@ -505,6 +518,14 @@ bool ThreadSanitizer::sanitizeFunction(Function &F, maybeMarkSanitizerLibraryCallNoBuiltin(CI, &TLI); if (isa<MemIntrinsic>(Inst)) MemIntrinCalls.push_back(&Inst); + else if (HasObjCSetProperty) { + auto *CB = cast<CallBase>(&Inst); + Value *Callee = CB->getCalledOperand(); + if (Callee == ObjCSetPropertyNonAtomicFn || + Callee == ObjCSetPropertyNonAtomicCopyFn || + Callee == ObjCSetPropertyFn) + ObjCSetPropertyCalls.push_back(CB); + } HasCalls = true; chooseInstructionsToInstrument(LocalLoadsAndStores, AllLoadsAndStores, DL); @@ -518,10 +539,14 @@ bool ThreadSanitizer::sanitizeFunction(Function &F, // (e.g. variables that do not escape, etc). // Instrument memory accesses only if we want to report bugs in the function. - if (Opts.tsan_instrument_memory_accesses && SanitizeFunction) + if (Opts.tsan_instrument_memory_accesses && SanitizeFunction) { for (const auto &II : AllLoadsAndStores) { Res |= instrumentLoadOrStore(II, DL); } + for (auto *CB : ObjCSetPropertyCalls) { + Res |= instrumentObjCSetProperty(CB, DL); + } + } // Instrument atomic memory accesses in any case (they can be used to // implement synchronization). @@ -681,6 +706,55 @@ bool ThreadSanitizer::instrumentMemIntrinsic(Instruction *I) { return false; } +bool ThreadSanitizer::instrumentObjCSetProperty(CallBase *CB, + const DataLayout &DL) { + Value *Callee = CB->getCalledOperand(); + Value *Self = nullptr; + Value *NewValue = nullptr; + Value *Offset = nullptr; + if (Callee == ObjCSetPropertyNonAtomicFn || + Callee == ObjCSetPropertyNonAtomicCopyFn) { + // void objc_setProperty_nonatomic[_copy](id self, SEL _cmd, id newValue, + // ptrdiff_t offset) + if (CB->arg_size() != 4) + return false; + Self = CB->getArgOperand(0); + NewValue = CB->getArgOperand(2); + Offset = CB->getArgOperand(3); + } else if (Callee == ObjCSetPropertyFn) { + // void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, + // BOOL atomic, BOOL shouldCopy) + if (CB->arg_size() != 6) + return false; + auto *AtomicCI = dyn_cast<ConstantInt>(CB->getArgOperand(4)); + if (!AtomicCI || !AtomicCI->isZero()) + return false; + Self = CB->getArgOperand(0); + Offset = CB->getArgOperand(2); + NewValue = CB->getArgOperand(3); + } else { + return false; + } + + if (!Self->getType()->isPointerTy() || !NewValue->getType()->isPointerTy() || + !Offset->getType()->isIntegerTy()) + return false; + if (!shouldInstrumentReadWriteFromAddress(CB->getModule(), Self)) + return false; + + InstrumentationIRBuilder IRB(CB); + Value *Addr = IRB.CreatePtrAdd(Self, Offset); + int Idx = getMemoryAccessFuncIndex(IRB.getPtrTy(), Addr, DL); + if (Idx < 0) + return false; + + // First the old value at Addr is read, then the new value is stored there; + // TSan only needs to know about the write. + IRB.CreateCall(TsanWrite[Idx], Addr); + NumInstrumentedWrites++; + return true; +} + // Both llvm and ThreadSanitizer atomic operations are based on C++11/C1x // standards. For background see C++11 standard. A slightly older, publicly // available draft of the standard (not entirely up-to-date, but close enough diff --git a/llvm/test/Instrumentation/ThreadSanitizer/objc-set-property.ll b/llvm/test/Instrumentation/ThreadSanitizer/objc-set-property.ll new file mode 100644 index 00000000000000..d622b19c1299b7 --- /dev/null +++ b/llvm/test/Instrumentation/ThreadSanitizer/objc-set-property.ll @@ -0,0 +1,70 @@ +; RUN: opt < %s -passes=tsan -S | FileCheck %s + +target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128" + +declare void @objc_setProperty_nonatomic(ptr, ptr, ptr, i64) nounwind +declare void @objc_setProperty_nonatomic_copy(ptr, ptr, ptr, i64) nounwind +declare void @objc_setProperty_atomic_copy(ptr, ptr, ptr, i64) nounwind +declare void @objc_setProperty(ptr, ptr, i64, ptr, i1, i1) nounwind + +; CHECK-LABEL: define void @test_set_property_nonatomic_copy( +; CHECK: [[ADDR:%.*]] = getelementptr i8, ptr %self, i64 %offset +; CHECK-NEXT: call void @__tsan_write8(ptr [[ADDR]]) +; CHECK-NEXT: call void @objc_setProperty_nonatomic_copy(ptr %self, ptr %cmd, ptr %val, i64 %offset) +define void @test_set_property_nonatomic_copy(ptr %self, ptr %cmd, ptr %val, i64 %offset) nounwind sanitize_thread { + call void @objc_setProperty_nonatomic_copy(ptr %self, ptr %cmd, ptr %val, i64 %offset) + ret void +} + +; CHECK-LABEL: define void @test_set_property_nonatomic( +; CHECK: [[ADDR:%.*]] = getelementptr i8, ptr %self, i64 %offset +; CHECK-NEXT: call void @__tsan_write8(ptr [[ADDR]]) +; CHECK-NEXT: call void @objc_setProperty_nonatomic(ptr %self, ptr %cmd, ptr %val, i64 %offset) +define void @test_set_property_nonatomic(ptr %self, ptr %cmd, ptr %val, i64 %offset) nounwind sanitize_thread { + call void @objc_setProperty_nonatomic(ptr %self, ptr %cmd, ptr %val, i64 %offset) + ret void +} + +; CHECK-LABEL: define void @test_set_property_generic_nonatomic( +; CHECK: [[ADDR:%.*]] = getelementptr i8, ptr %self, i64 %offset +; CHECK-NEXT: call void @__tsan_write8(ptr [[ADDR]]) +; CHECK-NEXT: call void @objc_setProperty(ptr %self, ptr %cmd, i64 %offset, ptr %val, i1 false, i1 true) +define void @test_set_property_generic_nonatomic(ptr %self, ptr %cmd, i64 %offset, ptr %val) nounwind sanitize_thread { + call void @objc_setProperty(ptr %self, ptr %cmd, i64 %offset, ptr %val, i1 false, i1 true) + ret void +} + +; CHECK-LABEL: define void @test_set_property_generic_atomic( +; CHECK-NOT: __tsan_write8 +; CHECK: call void @objc_setProperty(ptr %self, ptr %cmd, i64 %offset, ptr %val, i1 true, i1 true) +define void @test_set_property_generic_atomic(ptr %self, ptr %cmd, i64 %offset, ptr %val) nounwind sanitize_thread { + call void @objc_setProperty(ptr %self, ptr %cmd, i64 %offset, ptr %val, i1 true, i1 true) + ret void +} + +; Clang never emits a non-constant 'atomic' argument for synthesized setters, +; but user code could theoretically call objc_setProperty directly with a +; runtime boolean. +; CHECK-LABEL: define void @test_set_property_generic_nonconstant_atomic( +; CHECK-NOT: __tsan_write8 +; CHECK: call void @objc_setProperty(ptr %self, ptr %cmd, i64 %offset, ptr %val, i1 %atomic, i1 true) +define void @test_set_property_generic_nonconstant_atomic(ptr %self, ptr %cmd, i64 %offset, ptr %val, i1 %atomic) nounwind sanitize_thread { + call void @objc_setProperty(ptr %self, ptr %cmd, i64 %offset, ptr %val, i1 %atomic, i1 true) + ret void +} + +; CHECK-LABEL: define void @test_set_property_atomic_copy( +; CHECK-NOT: __tsan_write8 +; CHECK: call void @objc_setProperty_atomic_copy(ptr %self, ptr %cmd, ptr %val, i64 %offset) +define void @test_set_property_atomic_copy(ptr %self, ptr %cmd, ptr %val, i64 %offset) nounwind sanitize_thread { + call void @objc_setProperty_atomic_copy(ptr %self, ptr %cmd, ptr %val, i64 %offset) + ret void +} + +; CHECK-LABEL: define void @test_no_sanitize_thread( +; CHECK-NOT: __tsan_write8 +; CHECK: call void @objc_setProperty_nonatomic_copy(ptr %self, ptr %cmd, ptr %val, i64 %offset) +define void @test_no_sanitize_thread(ptr %self, ptr %cmd, ptr %val, i64 %offset) nounwind { + call void @objc_setProperty_nonatomic_copy(ptr %self, ptr %cmd, ptr %val, i64 %offset) + ret void +} _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
