diff --git a/jre_emul/apple_apsl/objc-sync.m b/jre_emul/apple_apsl/objc-sync.m index c35bee1bfa..ea3298ea76 100644 --- a/jre_emul/apple_apsl/objc-sync.m +++ b/jre_emul/apple_apsl/objc-sync.m @@ -21,10 +21,10 @@ * @APPLE_LICENSE_HEADER_END@ */ +#include +#include #include #include -#include -#include #include "JreEmulation.h" #include "java/lang/Thread.h" @@ -49,31 +49,26 @@ // Allocate a lock only when needed. Since few locks are needed at any point // in time, keep them on a single list. // -static pthread_mutexattr_t sRecursiveLockAttr; -static bool sRecursiveLockAttrIntialized = false; - - -static pthread_mutexattr_t* recursiveAttributes() -{ - if ( !sRecursiveLockAttrIntialized ) { - int err = pthread_mutexattr_init(&sRecursiveLockAttr); - __Require_noErr_String(err, done, "pthread_mutexattr_init failed"); - - err = pthread_mutexattr_settype(&sRecursiveLockAttr, PTHREAD_MUTEX_RECURSIVE); - __Require_noErr_String(err, done, "pthread_mutexattr_settype failed"); - - sRecursiveLockAttrIntialized = true; - } - -done: - return &sRecursiveLockAttr; +static pthread_mutexattr_t *recursiveAttributes(void) { + static pthread_mutexattr_t sRecursiveLockAttr; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + int err = pthread_mutexattr_init(&sRecursiveLockAttr); + __Require_noErr_String(err, done, "pthread_mutexattr_init failed"); + + err = pthread_mutexattr_settype(&sRecursiveLockAttr, PTHREAD_MUTEX_RECURSIVE); + __Require_noErr_String(err, done, "pthread_mutexattr_settype failed"); + + done: + return; + }); + return &sRecursiveLockAttr; } - typedef struct SyncData { struct SyncData* nextData; id object; - int threadCount; // number of THREADS using this block + atomic_int threadCount; // number of THREADS using this block pthread_mutex_t mutex; pthread_cond_t conditionVariable; } SyncData; @@ -161,7 +156,6 @@ void init_j2objc_thread_data(void) { } -__attribute__((disable_sanitizer_instrumentation)) static SyncCacheItem* id2SyncCacheItem(id object, enum usage why) { J2OBJC_FAST_LOCK_TYPE *lockp = &LOCK_FOR_OBJ(object); @@ -180,8 +174,9 @@ void init_j2objc_thread_data(void) { // Found a match. result = item->data; - __Require_Action_String(result->threadCount > 0, cache_done, - item = NULL, "id2data cache is buggy"); + __Require_Action_String( + atomic_load_explicit(&result->threadCount, memory_order_relaxed) > 0, cache_done, + item = NULL, "id2data cache is buggy"); __Require_Action_String(item->lockCount > 0, cache_done, item = NULL, "id2data cache is buggy"); @@ -194,8 +189,9 @@ void init_j2objc_thread_data(void) { if (item->lockCount == 0) { // remove from per-thread cache cache->list[i] = cache->list[--cache->used]; - // atomic because may collide with concurrent ACQUIRE - OSAtomicDecrement32Barrier(&result->threadCount); + // acq_rel synchronizes prior SyncData::object reads and critical section + // with reuse when threadCount reaches 0 + atomic_fetch_sub_explicit(&result->threadCount, 1, memory_order_acq_rel); } break; case CHECK: @@ -226,12 +222,13 @@ void init_j2objc_thread_data(void) { for (p = *listp; p != NULL; p = p->nextData) { if ( p->object == object ) { result = p; - // atomic because may collide with concurrent RELEASE - OSAtomicIncrement32Barrier(&result->threadCount); + // atomic because may collide with unlocked SyncCache hit/release + atomic_fetch_add_explicit(&result->threadCount, 1, memory_order_relaxed); goto done; } - if ( (firstUnused == NULL) && (p->threadCount == 0) ) - firstUnused = p; + if ((firstUnused == NULL) && + (atomic_load_explicit(&p->threadCount, memory_order_acquire) == 0)) + firstUnused = p; } // no SyncData currently associated with object @@ -242,7 +239,7 @@ void init_j2objc_thread_data(void) { if ( firstUnused != NULL ) { result = firstUnused; result->object = object; - result->threadCount = 1; + atomic_store_explicit(&result->threadCount, 1, memory_order_relaxed); goto done; } @@ -252,7 +249,7 @@ void init_j2objc_thread_data(void) { // But since we never free these guys we won't be stuck in malloc very often. result = (SyncData*)malloc(sizeof(SyncData)); result->object = object; - result->threadCount = 1; + atomic_store_explicit(&result->threadCount, 1, memory_order_relaxed); err = pthread_mutex_init(&result->mutex, recursiveAttributes()); __Require_noErr_String(err, done, "pthread_mutex_init failed"); err = pthread_cond_init(&result->conditionVariable, NULL); diff --git a/jre_emul/constants.bzl b/jre_emul/constants.bzl index 4230dd457e..d402019c7e 100644 --- a/jre_emul/constants.bzl +++ b/jre_emul/constants.bzl @@ -6057,6 +6057,7 @@ TEST_JAVA_SRCS_RELATIVE = [ "com/google/j2objc/ReflectionTest.java", "com/google/j2objc/RetainedWithTest.java", "com/google/j2objc/StringTest.java", + "com/google/j2objc/SynchronizedTest.java", "com/google/j2objc/ThreadTest.java", "com/google/j2objc/ThrowableTest.java", "com/google/j2objc/io/AsyncPipedNSInputStreamAdapterTest.java", @@ -7466,6 +7467,7 @@ TEST_JAVA_SRCS_QUALIFIED = [ "misc_tests/com/google/j2objc/ReflectionTest.java", "misc_tests/com/google/j2objc/RetainedWithTest.java", "misc_tests/com/google/j2objc/StringTest.java", + "misc_tests/com/google/j2objc/SynchronizedTest.java", "misc_tests/com/google/j2objc/ThreadTest.java", "misc_tests/com/google/j2objc/ThrowableTest.java", "misc_tests/com/google/j2objc/io/AsyncPipedNSInputStreamAdapterTest.java", @@ -8652,6 +8654,7 @@ TEST_NAMES = [ "com.google.j2objc.ReflectionTest", "com.google.j2objc.RetainedWithTest", "com.google.j2objc.StringTest", + "com.google.j2objc.SynchronizedTest", "com.google.j2objc.ThreadTest", "com.google.j2objc.ThrowableTest", "com.google.j2objc.io.AsyncPipedNSInputStreamAdapterTest", diff --git a/jre_emul/misc_tests/ObjcSyncFirstUseTest.m b/jre_emul/misc_tests/ObjcSyncFirstUseTest.m new file mode 100644 index 0000000000..00d0f98417 --- /dev/null +++ b/jre_emul/misc_tests/ObjcSyncFirstUseTest.m @@ -0,0 +1,158 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#import +#import +#include +#include +#include + +// Reproduces the process first-use data race inside recursiveAttributes() in +// apple_apsl/objc-sync.m when two threads enter @synchronized on objects that +// hash to different sDataLists buckets before any prior :jre_core +// objc_sync_enter call has initialized sRecursiveLockAttr: +// +// (no prior @synchronized against :jre_core in the test process: +// sRecursiveLockAttrIntialized == false) +// +// Thread A (@synchronized(lockBucketA)) Thread B (@synchronized(lockBucketB)) +// | | +// v (atomic spin barrier: readyCount==2) v +// objc_sync_enter(lockBucketA) objc_sync_enter(lockBucketB) +// | locks sDataLists[bucketA].lock | locks sDataLists[bucketB].lock +// | (bucketA != bucketB -> NO HB edge) | +// v v +// recursiveAttributes() recursiveAttributes() +// if (!sRecursiveLockAttrIntialized) if (!sRecursiveLockAttrIntialized) +// pthread_mutexattr_init(&sRecursiveLockAttr) <=== TSan DATA RACE ===> + +typedef struct { + __unsafe_unretained NSObject *targetObject; + atomic_int *readyCount; + atomic_int *completedCount; + int sink; +} ThreadSyncArgs; + +static BOOL gFoundDistinctBucket = NO; +static int gCreateErrorA = -1; +static int gCreateErrorB = -1; +static int gJoinErrorA = -1; +static int gJoinErrorB = -1; +static int gCompletedCount = 0; +static int gSinkA = 0; +static int gSinkB = 0; +static NSUInteger gRetainedCandidateCount = 0; + +static uintptr_t SyncBucketIndex(NSObject *targetObject) { + // Matches HASH(obj) = ((((uintptr_t)(obj)) >> 5) & (COUNT - 1)) with + // COUNT == 16 in apple_apsl/objc-sync.m. + return (((uintptr_t)(__bridge const void *)targetObject) >> 5) & 15U; +} + +static void *RunSynchronized(void *context) { + @autoreleasepool { + ThreadSyncArgs *threadArgs = (ThreadSyncArgs *)context; + atomic_fetch_add_explicit(threadArgs->readyCount, 1, memory_order_acq_rel); + while (atomic_load_explicit(threadArgs->readyCount, memory_order_acquire) < 2) { + } + @synchronized(threadArgs->targetObject) { + threadArgs->sink += 1; + } + atomic_fetch_add_explicit(threadArgs->completedCount, 1, memory_order_relaxed); + } + return NULL; +} + +@interface ObjcSyncFirstUseTest : XCTestCase +@end + +@implementation ObjcSyncFirstUseTest + ++ (void)load { + // Trigger the two-thread @synchronized race during image load before XCTest + // test discovery or Foundation runtime observers call objc_sync_enter. + @autoreleasepool { + // Keep all candidate allocations alive so addresses cannot be reused, and + // do not invoke @synchronized before spawning the worker pthreads. + NSMutableArray *retainedCandidates = [[NSMutableArray alloc] init]; + NSObject *lockBucketA = [[NSObject alloc] init]; + [retainedCandidates addObject:lockBucketA]; + uintptr_t bucketA = SyncBucketIndex(lockBucketA); + + NSObject *lockBucketB = nil; + for (int attempt = 0; attempt < 4096; ++attempt) { + NSObject *candidate = [[NSObject alloc] init]; + [retainedCandidates addObject:candidate]; + if (SyncBucketIndex(candidate) != bucketA) { + lockBucketB = candidate; + break; + } + } + gFoundDistinctBucket = (lockBucketB != nil); + if (!gFoundDistinctBucket) { + return; + } + + atomic_int readyCount; + atomic_init(&readyCount, 0); + atomic_int completedCount; + atomic_init(&completedCount, 0); + + ThreadSyncArgs argsA = { + .targetObject = lockBucketA, + .readyCount = &readyCount, + .completedCount = &completedCount, + .sink = 0, + }; + ThreadSyncArgs argsB = { + .targetObject = lockBucketB, + .readyCount = &readyCount, + .completedCount = &completedCount, + .sink = 0, + }; + + pthread_t threadA; + pthread_t threadB; + gCreateErrorA = pthread_create(&threadA, NULL, RunSynchronized, &argsA); + if (gCreateErrorA != 0) { + return; + } + gCreateErrorB = pthread_create(&threadB, NULL, RunSynchronized, &argsB); + if (gCreateErrorB != 0) { + // Release threadA from the start barrier before joining so it cannot spin indefinitely. + atomic_fetch_add_explicit(&readyCount, 1, memory_order_acq_rel); + pthread_join(threadA, NULL); + return; + } + + gJoinErrorA = pthread_join(threadA, NULL); + gJoinErrorB = pthread_join(threadB, NULL); + gCompletedCount = atomic_load_explicit(&completedCount, memory_order_relaxed); + gSinkA = argsA.sink; + gSinkB = argsB.sink; + gRetainedCandidateCount = [retainedCandidates count]; + } +} + +- (void)testConcurrentFirstUseAcrossDistinctBuckets { + XCTAssertTrue(gFoundDistinctBucket); + XCTAssertEqual(gCreateErrorA, 0); + XCTAssertEqual(gCreateErrorB, 0); + XCTAssertEqual(gJoinErrorA, 0); + XCTAssertEqual(gJoinErrorB, 0); + XCTAssertEqual(gCompletedCount, 2); + XCTAssertEqual(gSinkA, 1); + XCTAssertEqual(gSinkB, 1); + XCTAssertGreaterThan(gRetainedCandidateCount, (NSUInteger)0); +} + +@end diff --git a/jre_emul/misc_tests/com/google/j2objc/SynchronizedTest.java b/jre_emul/misc_tests/com/google/j2objc/SynchronizedTest.java new file mode 100644 index 0000000000..00b64f0abe --- /dev/null +++ b/jre_emul/misc_tests/com/google/j2objc/SynchronizedTest.java @@ -0,0 +1,214 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.j2objc; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@code synchronized} monitor happens-before semantics across {@code objc-sync}. */ +@RunWith(JUnit4.class) +public class SynchronizedTest { + + // J2ObjC omits weakCompareAndSetPlain; weakCompareAndSet lowers to __ATOMIC_RELAXED. + @SuppressWarnings("deprecation") + private static void advancePhaseRelaxed(AtomicInteger phase, int from, int to) { + while (!phase.weakCompareAndSet(from, to)) { + Thread.onSpinWait(); + } + } + + // J2ObjC omits weakCompareAndSetPlain; weakCompareAndSet lowers to __ATOMIC_RELAXED. + @SuppressWarnings("deprecation") + private static void awaitPhaseRelaxed(AtomicInteger phase, int expected) { + while (!phase.weakCompareAndSet(expected, expected)) { + Thread.onSpinWait(); + } + } + + /** + * White-box regression test for a monitor-recycling happens-before bug in J2ObjC's APSL {@code + * objc-sync} striped {@code SyncData} monitor pool ({@code apple_apsl/objc-sync.m}). + * + *

While the assertion itself checks standard Java Memory Model monitor semantics (unlocking + * {@code lockA} must happen-before any subsequent lock of {@code lockA}, so the test remains + * valid on any JVM or replacement runtime), the object setup white-boxes {@code objc-sync.m}'s + * 16-bucket address hash ({@code (ptr >> 5) & 15}), per-bucket spinlock ({@code lockp}), and + * {@code SyncData} node recycling ({@code threadCount == 0}). Once all three threads pass {@code + * startLatch}, all {@code phase} handoffs use {@code weakCompareAndSet} ({@code + * __ATOMIC_RELAXED}) so {@code phase} adds no side-channel happens-before edges. + * + *

{@code
+   * Setup in bucket B = HASH(lockA) == HASH(lockB) (after startLatch barrier):
+   *   Unused SyncData nodes in bucket B: D1 (mutex M1, count=0) and D2 (mutex M2, count=0)
+   *
+   * Thread t1 (lockA)        Bucket B / D1.threadCount     Thread t2 (lockB) / Thread t3 (lockA)
+   * -----------------        -------------------------     -------------------------------------
+   * enter sync(lockA):
+   *   lock(lockp)   -------> [claim D1: obj=lockA, cnt=1]
+   *   unlock(lockp) <-------
+   *   lock(M1)
+   *   shared[2] = 42
+   * exit sync(lockA):
+   *   D1.cnt: 1 -> 0 ======> (acq_rel release #1)
+   *   unlock(M1)                  |
+   * phase 0 -> 1 (relaxed)        | synchronizes-with
+   *                               v
+   *                          (acquire #1: D1.cnt == 0) <-- t2: await phase == 1 (relaxed)
+   *                                                        t2: enter sync(lockB):
+   *                          [recycle D1: obj=lockB,   <--   lock(lockp)
+   *                           cnt=1]
+   *                          (lockp release #2) <=========   unlock(lockp)  [before lock(M1)!]
+   *                               |                          lock(M1)       [t2 holds D1/M1]
+   *                               | synchronizes-with      t2: phase 1 -> 2 (relaxed)
+   *                               v
+   *                          (lockp acquire #2) <========= t3: await phase == 2 (relaxed)
+   *                                                        t3: enter sync(lockA):
+   *                          [D1 busy on lockB;        <--   lock(lockp)
+   *                           claim D2: obj=lockA, cnt=1]
+   *                                                          unlock(lockp)
+   *                                                          lock(M2)       [M2 != M1]
+   *                                                          shared[2] += 1 [reads 42 -> 43]
+   *                                                        t3: exit sync(lockA)
+   *                                                        t3: phase 2 -> 3 (relaxed)
+   * await phase == 3 (relaxed)                             t2: await phase == 3, exit sync(lockB)
+   * }
+ * + *

In a runtime with dedicated per-object monitors, two {@code synchronized (lockA)} blocks + * always acquire the same underlying lock. In {@code objc-sync}'s pooled {@code SyncData} table, + * however, {@code t2} (synchronizing on a hash-colliding object {@code lockB}) recycles {@code + * t1}'s old mutex ({@code M1}) and keeps holding it, forcing {@code t3} onto a second mutex + * ({@code M2}) for {@code lockA}. Because {@code t1} and {@code t3} never touch the same mutex, + * and {@code t2} releases the bucket spinlock ({@code lockp}) before locking {@code M1}, the + * mutexes alone never connect {@code t1} to {@code t3}. Instead, {@code t1}'s release decrement + * of {@code D1->threadCount} to {@code 0} must synchronize-with {@code t2}'s acquire load during + * recycling under {@code lockp}, which then synchronizes-with {@code t3}'s acquisition of {@code + * lockp}. + */ + @Test + public void testSynchronizedHappensBeforeAcrossBucketCollision() throws Exception { + for (int trial = 0; trial < 10; trial++) { + runBucketCollisionTrial(); + } + } + + private static void runBucketCollisionTrial() throws Exception { + // Find 4 distinct objects that map to the same objc-sync bucket (((ptr >> 5) & 15)). + Object[] bucketMatches = new Object[4]; + List> buckets = new ArrayList<>(16); + for (int i = 0; i < 16; i++) { + buckets.add(new ArrayList<>()); + } + while (true) { + Object candidate = new Object(); + int bucket = (System.identityHashCode(candidate) >>> 5) & 15; + List bucketList = buckets.get(bucket); + bucketList.add(candidate); + if (bucketList.size() == 4) { + for (int i = 0; i < 4; i++) { + bucketMatches[i] = bucketList.get(i); + } + break; + } + } + + final Object lockA = bucketMatches[0]; + final Object lockB = bucketMatches[1]; + final Object warm1 = bucketMatches[2]; + final Object warm2 = bucketMatches[3]; + + // Pre-populate two reusable SyncData nodes in this bucket before starting threads. + synchronized (warm1) { + synchronized (warm2) { + } + } + + // Index 2 sits in its own 8-byte TSan shadow granule (separate from IOSIntArray's size_ + // header). + final int[] sharedProtectedByA = new int[4]; + final CountDownLatch startLatch = new CountDownLatch(3); + final AtomicInteger phase = new AtomicInteger(0); + + Thread t1 = + new Thread(() -> { + try { + // Pre-initialize per-thread SyncCache and wait until all Thread.start() calls + // finish so t2.start()/t3.start() monitors on main cannot bridge t1 -> main -> t3. + synchronized (new Object()) { + } + startLatch.countDown(); + startLatch.await(); + } catch (InterruptedException e) { + throw new AssertionError(e); + } + synchronized (lockA) { + sharedProtectedByA[2] = 42; + } + advancePhaseRelaxed(phase, 0, 1); + // Stay alive until t3 finishes so Thread termination locks cannot add side-channel + // sync. + awaitPhaseRelaxed(phase, 3); + }); + + Thread t2 = + new Thread(() -> { + try { + synchronized (new Object()) { + } + startLatch.countDown(); + startLatch.await(); + } catch (InterruptedException e) { + throw new AssertionError(e); + } + awaitPhaseRelaxed(phase, 1); + synchronized (lockB) { // Recycles lockA's SyncData node D1 and holds it + advancePhaseRelaxed(phase, 1, 2); + awaitPhaseRelaxed(phase, 3); + } + }); + + Thread t3 = + new Thread(() -> { + try { + synchronized (new Object()) { + } + startLatch.countDown(); + startLatch.await(); + } catch (InterruptedException e) { + throw new AssertionError(e); + } + awaitPhaseRelaxed(phase, 2); + synchronized (lockA) { // Forced onto second SyncData node D2 (different mutex) + sharedProtectedByA[2] += 1; + } + advancePhaseRelaxed(phase, 2, 3); + }); + + t1.start(); + t2.start(); + t3.start(); + t1.join(); + t2.join(); + t3.join(); + + assertEquals(43, sharedProtectedByA[2]); + } +} diff --git a/jre_emul/test_sources.mk b/jre_emul/test_sources.mk index 66af7bd359..e326165f23 100644 --- a/jre_emul/test_sources.mk +++ b/jre_emul/test_sources.mk @@ -299,6 +299,7 @@ TEST_SOURCES := \ com/google/j2objc/ReflectionTest.java \ com/google/j2objc/RetainedWithTest.java \ com/google/j2objc/StringTest.java \ + com/google/j2objc/SynchronizedTest.java \ com/google/j2objc/ThreadTest.java \ com/google/j2objc/ThrowableTest.java \ com/google/j2objc/io/AsyncPipedNSInputStreamAdapterTest.java \