项目常见崩溃(陆续更新)

作者: bigParis | 来源:发表于2017-01-03 11:28 被阅读758次

    项目中有些崩溃很难重现, 甚至开发者自己根本无法重现, 但是又确实崩溃很多, 只见堆栈, 却无法重现, 这种崩溃着实令人抓狂.

    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加锁应该也是可以解决崩溃的.

    相关文章

      网友评论

      本文标题:项目常见崩溃(陆续更新)

      本文链接:https://www.haomeiwen.com/subject/dewgvttx.html