fix(image): fix data race in imageURLLoaderForURL: and imageDataDecoderForData: (#57297)

Summary:
`imageURLLoaderForURL:` had a broken double-checked lock on `_loaders`: the outer `if (!_loaders)` guard and the `for` loop iteration both ran without `_loadersMutex`, while the assignment ran inside it. `imageDataDecoderForData:` had no lock at all on `_decoders`. Both methods write the ivar in two steps (raw list then sorted), so a concurrent reader could observe the intermediate value and iterate a concurrently-released array, crashing with `EXC_BAD_ACCESS` in `objc_release` on a GCD worker thread.

Verified with a reproducer — crashes 5/5 without the fix, 0/10 with it: https://github.com/mfazekas/rn-rctimageloader-dcl-repro

## Fix

Build the loader and decoder lists once in `setUp` (alongside the URL request queue), under `_setupLock` and gated by the existing `_didSetup` atomic flag. Every entry point calls `setUp` before reading the now write-once `_loaders` and `_decoders`, so a reader can never observe a half-built or concurrently-released array.

This replaces the broken double-checked lock where the outer `if (!_loaders)` guard and the `for` loop iteration ran outside the mutex.

## Changelog:

[iOS] [Fixed] - Fix a data race in `RCTImageLoader` loader and decoder lazy initialization that could crash with `EXC_BAD_ACCESS`

## Related

Fixes https://github.com/react/react-native/issues/57296
See also https://github.com/react/react-native/issues/46115, https://github.com/react/react-native/issues/46153

Pull Request resolved: https://github.com/react/react-native/pull/57297

Reviewed By: javache

Differential Revision: D109404243

Pulled By: fabriziocucci

fbshipit-source-id: 359d4c70e2cbe1bc70a7e6a1dadc3e3b89c59ff4
This commit is contained in:
Miklós Fazekas authored and meta-codesync[bot] committed 2026-06-23 10:21:37 -07:00
1 parent 10ec4ad01a
commit 7ed17c9d09
1 file changed
+60 -63
@@ -68,8 +68,8 @@ static NSError *addResponseHeadersToError(NSError *originalError, NSHTTPURLRespo
@end
@implementation RCTImageLoader {
std::atomic<BOOL> _isLoaderSetup;
std::mutex _loaderSetupLock;
std::atomic<BOOL> _didSetup;
std::mutex _setupLock;
NSArray<id<RCTImageURLLoader>> * (^_loadersProvider)(RCTModuleRegistry *);
NSArray<id<RCTImageDataDecoder>> * (^_decodersProvider)(RCTModuleRegistry *);
NSArray<id<RCTImageURLLoader>> *_loaders;
@@ -82,7 +82,6 @@ static NSError *addResponseHeadersToError(NSError *originalError, NSHTTPURLRespo
NSMutableArray *_pendingDecodes;
NSInteger _scheduledDecodes;
NSUInteger _activeBytes;
std::mutex _loadersMutex;
__weak id<RCTImageRedirectProtocol> _redirectDelegate;
}
@@ -108,7 +107,7 @@ RCT_EXPORT_MODULE()
{
if (self = [super init]) {
_redirectDelegate = redirectDelegate;
_isLoaderSetup = NO;
_didSetup = NO;
}
return self;
}
@@ -126,15 +125,56 @@ RCT_EXPORT_MODULE()
- (void)setUp
{
std::lock_guard<std::mutex> guard(_loaderSetupLock);
if (!_isLoaderSetup) {
std::lock_guard<std::mutex> guard(_setupLock);
if (!_didSetup) {
// Set defaults
_maxConcurrentLoadingTasks = _maxConcurrentLoadingTasks ?: 4;
_maxConcurrentDecodingTasks = _maxConcurrentDecodingTasks ?: 2;
_maxConcurrentDecodingBytes = _maxConcurrentDecodingBytes ?: 30 * 1024 * 1024; // 30MB
_URLRequestQueue = dispatch_queue_create("com.facebook.react.ImageLoaderURLRequestQueue", DISPATCH_QUEUE_SERIAL);
_isLoaderSetup = YES;
// Get loaders, sorted in reverse priority order (highest priority first)
if (_loadersProvider != nil) {
_loaders = _loadersProvider(self.moduleRegistry);
} else {
RCTAssert(_bridge, @"Trying to find RCTImageURLLoaders and bridge not set.");
_loaders = [_bridge modulesConformingToProtocol:@protocol(RCTImageURLLoader)];
}
_loaders =
[_loaders sortedArrayUsingComparator:^NSComparisonResult(id<RCTImageURLLoader> a, id<RCTImageURLLoader> b) {
float priorityA = [a respondsToSelector:@selector(loaderPriority)] ? [a loaderPriority] : 0;
float priorityB = [b respondsToSelector:@selector(loaderPriority)] ? [b loaderPriority] : 0;
if (priorityA > priorityB) {
return NSOrderedAscending;
} else if (priorityA < priorityB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
// Get decoders, sorted in reverse priority order (highest priority first)
if (_decodersProvider != nil) {
_decoders = _decodersProvider(self.moduleRegistry);
} else {
RCTAssert(_bridge, @"Trying to find RCTImageDataDecoders and bridge not set.");
_decoders = [_bridge modulesConformingToProtocol:@protocol(RCTImageDataDecoder)];
}
_decoders = [_decoders
sortedArrayUsingComparator:^NSComparisonResult(id<RCTImageDataDecoder> a, id<RCTImageDataDecoder> b) {
float priorityA = [a respondsToSelector:@selector(decoderPriority)] ? [a decoderPriority] : 0;
float priorityB = [b respondsToSelector:@selector(decoderPriority)] ? [b decoderPriority] : 0;
if (priorityA > priorityB) {
return NSOrderedAscending;
} else if (priorityA < priorityB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
_didSetup = YES;
}
}
@@ -163,41 +203,17 @@ RCT_EXPORT_MODULE()
- (id<RCTImageURLLoader>)imageURLLoaderForURL:(NSURL *)URL
{
if (!_isLoaderSetup) {
if (!_didSetup) {
[self setUp];
}
if (!_loaders) {
std::unique_lock<std::mutex> guard(_loadersMutex);
if (!_loaders) {
// Get loaders, sorted in reverse priority order (highest priority first)
if (_loadersProvider) {
_loaders = _loadersProvider(self.moduleRegistry);
} else {
RCTAssert(_bridge, @"Trying to find RCTImageURLLoaders and bridge not set.");
_loaders = [_bridge modulesConformingToProtocol:@protocol(RCTImageURLLoader)];
}
_loaders =
[_loaders sortedArrayUsingComparator:^NSComparisonResult(id<RCTImageURLLoader> a, id<RCTImageURLLoader> b) {
float priorityA = [a respondsToSelector:@selector(loaderPriority)] ? [a loaderPriority] : 0;
float priorityB = [b respondsToSelector:@selector(loaderPriority)] ? [b loaderPriority] : 0;
if (priorityA > priorityB) {
return NSOrderedAscending;
} else if (priorityA < priorityB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
}
}
NSArray<id<RCTImageURLLoader>> *loaders = _loaders;
if (RCT_DEBUG) {
// Check for handler conflicts
float previousPriority = 0;
id<RCTImageURLLoader> previousLoader = nil;
for (id<RCTImageURLLoader> loader in _loaders) {
for (id<RCTImageURLLoader> loader in loaders) {
float priority = [loader respondsToSelector:@selector(loaderPriority)] ? [loader loaderPriority] : 0;
if (previousLoader && priority < previousPriority) {
return previousLoader;
@@ -224,7 +240,7 @@ RCT_EXPORT_MODULE()
}
// Normal code path
for (id<RCTImageURLLoader> loader in _loaders) {
for (id<RCTImageURLLoader> loader in loaders) {
if ([loader canLoadImageURL:URL]) {
return loader;
}
@@ -236,39 +252,17 @@ RCT_EXPORT_MODULE()
- (id<RCTImageDataDecoder>)imageDataDecoderForData:(NSData *)data
{
if (!_isLoaderSetup) {
if (!_didSetup) {
[self setUp];
}
if (!_decoders) {
// Get decoders, sorted in reverse priority order (highest priority first)
if (_decodersProvider) {
_decoders = _decodersProvider(self.moduleRegistry);
} else {
RCTAssert(_bridge, @"Trying to find RCTImageDataDecoders and bridge not set.");
_decoders = [_bridge modulesConformingToProtocol:@protocol(RCTImageDataDecoder)];
}
_decoders = [_decoders
sortedArrayUsingComparator:^NSComparisonResult(id<RCTImageDataDecoder> a, id<RCTImageDataDecoder> b) {
float priorityA = [a respondsToSelector:@selector(decoderPriority)] ? [a decoderPriority] : 0;
float priorityB = [b respondsToSelector:@selector(decoderPriority)] ? [b decoderPriority] : 0;
if (priorityA > priorityB) {
return NSOrderedAscending;
} else if (priorityA < priorityB) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}];
}
NSArray<id<RCTImageDataDecoder>> *decoders = _decoders;
if (RCT_DEBUG) {
// Check for handler conflicts
float previousPriority = 0;
id<RCTImageDataDecoder> previousDecoder = nil;
for (id<RCTImageDataDecoder> decoder in _decoders) {
for (id<RCTImageDataDecoder> decoder in decoders) {
float priority = [decoder respondsToSelector:@selector(decoderPriority)] ? [decoder decoderPriority] : 0;
if (previousDecoder && priority < previousPriority) {
return previousDecoder;
@@ -297,7 +291,7 @@ RCT_EXPORT_MODULE()
}
// Normal code path
for (id<RCTImageDataDecoder> decoder in _decoders) {
for (id<RCTImageDataDecoder> decoder in decoders) {
if ([decoder canDecodeImageData:data]) {
return decoder;
}
@@ -621,7 +615,7 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
}
// All access to URL cache must be serialized
if (!_isLoaderSetup) {
if (!_didSetup) {
[self setUp];
}
@@ -1040,7 +1034,7 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
});
};
if (!_isLoaderSetup) {
if (!_didSetup) {
[self setUp];
}
dispatch_async(_URLRequestQueue, ^{
@@ -1173,6 +1167,9 @@ static RCTImageLoaderCancellationBlock RCTLoadImageURLFromLoader(
return NO;
}
if (!_didSetup) {
[self setUp];
}
for (id<RCTImageURLLoader> loader in _loaders) {
// Don't use RCTImageURLLoader protocol for modules that already conform to
// RCTURLRequestHandler as it's inefficient to decode an image and then