項目中有些崩潰很難重現, 甚至開發者自己根本無法重現, 但是又確實崩潰很多, 只見堆棧, 卻無法重現, 這種崩潰著實令人抓狂.
1 AFNetworking多線程崩潰
崩潰堆棧
0 CoreFoundation!__exceptionPreprocess + 0x7f
1 libobjc.A.dylib!objc_exception_throw + 0x25
2 CoreFoundation!+[NSException raise:format:] + 0x6f
3 Foundation!_NSMutableDataGrowBytes + 0x2b7
4 Foundation!-[NSConcreteMutableData appendBytes:length:] + 0x137
5 Foundation!-[NSData(NSData) enumerateByteRangesUsingBlock:] + 0x3f
6 Foundation!-[NSConcreteMutableData appendData:] + 0x51
7 MakeFriends!__70-[AFURLSessionManagerTaskDelegate URLSession:dataTask:didReceiveData:]_block_invoke [AFURLSessionManager.m : 337 + 0x13]
8 Foundation!__49-[_NSDispatchData enumerateByteRangesUsingBlock:]_block_invoke + 0x1f
9 Foundation!__49-[_NSDispatchData enumerateByteRangesUsingBlock:]_block_invoke + 0x1f
10 libdispatch.dylib!_dispatch_client_callout3 + 0x25
11 libdispatch.dylib!_dispatch_data_apply + 0x4d
12 libdispatch.dylib!dispatch_data_apply + 0x1b
13 Foundation!-[_NSDispatchData enumerateByteRangesUsingBlock:] + 0x3f
14 MakeFriends!-[AFURLSessionManagerTaskDelegate URLSession:dataTask:didReceiveData:] [AFURLSessionManager.m : 335 + 0x9]
由于使用了第三方庫AFN造成的崩潰, AFN關于類似的崩潰也是有很多issue的, 但都沒有徹底的解決問題, 但是通過issue不難定位問題的原因是多線程訪問數據mutableData并不安全, 在深入學習了AFN3.X之后發現, AFN在發送網絡請求的時候, 實際上是串行的, 因為并發數設置成了1, 但在收到數據時候卻是多線程的, 雖然有些地方AFN使用了隊列來確保線程的安全, 但是有些地方還是忽略了, 舉個例子:
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
__strong AFURLSessionManager *manager = self.manager;
__block id responseObject = nil;
__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
//Performance Improvement from #2672
NSData *data = nil;
if (self.mutableData) {
data = [self.mutableData copy];
//We no longer need the reference, so nil it out to gain back some memory.
//[self.lock lock];
self.mutableData = nil;
// [self.lock unlock];
}
這里mutableData不是線程安全的, 但在給self.mutableData
賦值的時候卻沒加鎖, 這就導致了崩潰, 而且這個崩潰無法重現, 至少我沒重現過. 解決問題的辦法就是加鎖.
@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
@property (readwrite, nonatomic, strong) NSLock *lock;
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.mutableData = [NSMutableData data];
self.uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
self.uploadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown;
self.downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
self.downloadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown;
self.lock = [[NSLock alloc] init];
return self;
}
#pragma mark - NSURLSessionDataTaskDelegate
- (void)URLSession:(__unused NSURLSession *)session
dataTask:(__unused NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
@autoreleasepool {
[data enumerateByteRangesUsingBlock:^(const void * _Nonnull bytes, NSRange byteRange, BOOL * _Nonnull stop) {
NSData *receiveData = [[NSData alloc] initWithBytes:bytes length:byteRange.length];
[self.lock lock];
[self.mutableData appendData:receiveData];
[self.lock unlock];
}];
}
}
- (void)URLSession:(__unused NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
__strong AFURLSessionManager *manager = self.manager;
__block id responseObject = nil;
__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
//Performance Improvement from #2672
NSData *data = nil;
if (self.mutableData) {
data = [self.mutableData copy];
//We no longer need the reference, so nil it out to gain back some memory.
[self.lock lock];
self.mutableData = nil;
[self.lock unlock];
}
AFN issue上其實已經有人給出了加互斥鎖@synchronized的方法, 但是他并沒有給所有使用self.mutableData
的地方加鎖, 所以并沒解決問題. 但按照此方案給所有用到self.mutableData
加鎖應該也是可以解決崩潰的.