Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix thread race in MTRXPCListenerSampleTests. #26862

Merged
merged 1 commit into from
May 26, 2023
Merged
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
10 changes: 10 additions & 0 deletions src/darwin/Framework/CHIPTests/MTRXPCListenerSampleTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

// system dependencies
#import <XCTest/XCTest.h>
#import <os/lock.h>

static uint16_t kTestVendorId = 0xFFF1u;

Expand Down Expand Up @@ -73,6 +74,8 @@ @interface MTRXPCListenerSample ()
@property (nonatomic, readonly, strong)
NSMutableDictionary<NSNumber *, MTRClusterStateCacheContainer *> * clusterStateCacheDictionary;

// serversLock controls access to _servers.
@property (nonatomic, readonly) os_unfair_lock serversLock;
@end

@implementation MTRXPCListenerSample
Expand All @@ -86,6 +89,7 @@ - (instancetype)init
_clusterStateCacheDictionary = [NSMutableDictionary dictionary];
_xpcListener = [NSXPCListener anonymousListener];
[_xpcListener setDelegate:(id<NSXPCListenerDelegate>) self];
_serversLock = OS_UNFAIR_LOCK_INIT;
}
return self;
}
Expand Down Expand Up @@ -113,10 +117,16 @@ - (BOOL)listener:(NSXPCListener *)listener shouldAcceptNewConnection:(NSXPCConne
__auto_type newServer = [[MTRDeviceControllerServerSample alloc] initWithClientProxy:[newConnection remoteObjectProxy]
clusterStateCacheDictionary:_clusterStateCacheDictionary];
newConnection.exportedObject = newServer;

os_unfair_lock_lock(&_serversLock);
[_servers setObject:newServer forKey:newServer.identifier];
os_unfair_lock_unlock(&_serversLock);

newConnection.invalidationHandler = ^{
NSLog(@"XPC connection disconnected");
os_unfair_lock_lock(&self->_serversLock);
[self.servers removeObjectForKey:newServer.identifier];
os_unfair_lock_unlock(&self->_serversLock);
};
[newConnection resume];
return YES;
Expand Down