Skip to content

Commit

Permalink
iOS: Fix an image loader crash
Browse files Browse the repository at this point in the history
Summary:
Fixes #10433

The code didn't account for the fact that cancelLoad is set by two different threads. It gets set on the URL request queue when the request completes successfully and it gets set on the UI queue during cancelation. This oversight lead to a couple of different kinds of crashes.

1. Attempt to invoke a nil function -- We check that cancelLoad is non-nil and on the next line we call it. However, cancelLoad could have been set to nil by the other thread between the time it was verified to be non-nil and the time it was called. Consequently, the program will attempt to call nil and crash.

2. Block deallocated while it's executing -- Suppose cancelLoad points to a block, it is verified to be non-nil, and it is successfully invoked. In the middle of executing the block, cancelLoad, the last reference to the block, is set to nil. This causes the block to be deallocated and its captured values to be freed. However, the block continues executing and the next time it attempts to use a captured value
Closes #11145

Differential Revision: D4261499

Pulled By: javache

fbshipit-source-id: 46424c6dd8cfa085cef32d945308de07798040bc
  • Loading branch information
rigdern authored and Facebook Github Bot committed Dec 2, 2016
1 parent 9646358 commit 2342377
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions Libraries/Image/RCTImageLoader.m
Original file line number Diff line number Diff line change
Expand Up @@ -381,9 +381,10 @@ - (RCTImageLoaderCancellationBlock)_loadImageOrDataWithURLRequest:(NSURLRequest
});

return ^{
if (cancelLoad && !cancelled) {
cancelLoad();
cancelLoad = nil;
dispatch_block_t cancelLoadLocal = cancelLoad;
cancelLoad = nil;
if (cancelLoadLocal && !cancelled) {
cancelLoadLocal();
}
OSAtomicOr32Barrier(1, &cancelled);
};
Expand Down Expand Up @@ -515,8 +516,9 @@ - (RCTImageLoaderCancellationBlock)loadImageWithURLRequest:(NSURLRequest *)image
__block volatile uint32_t cancelled = 0;
__block dispatch_block_t cancelLoad = nil;
dispatch_block_t cancellationBlock = ^{
if (cancelLoad && !cancelled) {
cancelLoad();
dispatch_block_t cancelLoadLocal = cancelLoad;
if (cancelLoadLocal && !cancelled) {
cancelLoadLocal();
}
OSAtomicOr32Barrier(1, &cancelled);
};
Expand Down

1 comment on commit 2342377

@XHTeng
Copy link

@XHTeng XHTeng commented on 2342377 Dec 6, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you ! I finally a solution the crash!!!

Please sign in to comment.