Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 30 additions & 33 deletions jre_emul/apple_apsl/objc-sync.m
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@
* @APPLE_LICENSE_HEADER_END@
*/

#include <AssertMacros.h>
#include <dispatch/dispatch.h>
#include <pthread.h>
#include <stdatomic.h>
#include <AssertMacros.h>
#include <libkern/OSAtomic.h>

#include "JreEmulation.h"
#include "java/lang/Thread.h"
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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");

Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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;
}

Expand All @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions jre_emul/constants.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
158 changes: 158 additions & 0 deletions jre_emul/misc_tests/ObjcSyncFirstUseTest.m
Original file line number Diff line number Diff line change
@@ -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 <Foundation/Foundation.h>
#import <XCTest/XCTest.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdint.h>

// 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<NSObject *> *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
Loading