美文网首页
crash之野指针

crash之野指针

作者: 梁炜东 | 来源:发表于2021-07-28 14:14 被阅读0次

    例子一

    堆栈信息

    image.png

    根据堆栈分析:
    1,野指针
    2,有对应的堆栈
    查看堆栈代码,看那些有可能野指针:

    + (NSURLSessionDataTask *)httpAsyncPostWithUrl:(NSString *)urlHost
                                        dictionary:(NSDictionary *)dictionary
                                         userAgent:(NSString *)userAgent
                                   completionBlock:(BDHKNetworkServiceResponse)block {
        
        [self setupNetworkService];
        
        // 检查网络
        if ([BDHKNetworkInfoManager currentNetworkStatus] == BDHKNetworkInfoStatusNotReachable) {
            if (block) {
                NSError *error = [NSError errorWithDomain:kBDHKNetworkingErrorDomain
                                                     code:kBDHKNetworkingUnreachableCode
                                                 userInfo:nil];
    //            [BDHKCoreDataCheck apiErrorCheckApi:urlHost tab:@"haokan" tag:@"haokan" videoType:@"video" vid:@"" error:error extraDict:@{}];
                block(nil, error);
            }
            return nil;
        }
        
        if ([Pyramid.bdhk_commonParams boolUploadZid]) {
            [Pyramid.bdhk_commonParams zid];   //更新zid
        }
        
        NSTimeInterval startTime = [[NSDate date] timeIntervalSince1970];
        __block NSDictionary *timeDic = nil;
        BDHKNetworkingResult resultBlock = ^(NSURLSessionTask * _Nullable task,
                                             NSDictionary * _Nullable response,
                                             NSError * _Nullable error) {
            // passposrt下沉后已修改
            if (!HK_isEmptyDictionary(response)) {
                [[BDHKCorePassportService sharedInstance] updatePassportStatusWithLoginInfo:response];
            }
           
    //        if (!HK_isEmptyDictionary(response)) {
    //            @try {
    //                id obj = [NSClassFromString(@"BDHKPassportService") performSelector:@selector(sharedInstance)];
    //                [obj performSelector:@selector(updatePassportStatusWithLoginInfo:) withObject:response afterDelay:0];
    //            } @catch (NSException *exception) {
    //
    //            }
    //        }
            if (error.code == kBDHKNetworkingUntrustCerErrorCode) {
                bdhk_toast(@"检测到代理连接,关闭代理后可正常使用");
                NSDictionary *errorInfo = @{@"k": @"hk_stability",
                                            @"v": @"untrust_user_cer",
                                            @"url": urlHost};
                [BDHKNewLogService send760PackLogWithLogExtra:@{@"extra": errorInfo}];
                NSString * apiName = [dictionary.allKeys objectAtIndexCheck:0];
                [BDHKCoreDataCheck apiErrorCheckApi:apiName?:urlHost tab:@"haokan" tag:@"haokan" videoType:@"video" vid:@"" error:error extraDict:errorInfo];
            }
            
            if (block) {
                block(response, error);
            }
            
            // 打点
            NSTimeInterval responseTime = [[NSDate date] timeIntervalSince1970];
            BOOL isTurbo = [BDHKNetworking isTurboSession:task.bdhkSession];
            NSInteger errorCode = error ? error.code : 0;
            
            [BDHKNetWorkService apiRequestTime:startTime
                      type:isTurbo ? @"turbo" : @"native"
                      code:errorCode
                   message:error.description
                  response:task.response
                dictionary:dictionary
            responseObject:response
                   timeDic:timeDic
                       url:urlHost
              responseTime:responseTime];
            
            if (error && error.code != NSURLErrorCancelled) {
                BOOL isEmpty = HK_isEmptyDictionary(response);
                [BDHKNetWorkService pageErrorLogDic:dictionary
                                               type:isEmpty ? @"2" : @"0"
                                              error:error];
                NSString * apiName = [dictionary.allKeys objectAtIndexCheck:0];
                [BDHKCoreDataCheck apiErrorCheckApi:apiName?:urlHost tab:@"haokan" tag:@"haokan" videoType:@"video" vid:@"" error:error extraDict:@{}];
            }
        };
        
        NSURLSessionDataTask *dataTask = nil;
        if (@available(iOS 10.0, *)) {
            dataTask = [BDHKNetworking postHost:urlHost
                               apiAndParameters:dictionary
                                      userAgent:userAgent
                                completionBlock:[resultBlock copy]
                                   metricsBlock:^(NSURLSessionTask * _Nullable task,
                                                  NSURLSessionTaskMetrics * _Nullable metrics) {
                    timeDic = [self dicFromMetrics:metrics];
            }];
        } else {
            dataTask = [BDHKNetworking postHost:urlHost
                               apiAndParameters:dictionary
                                      userAgent:userAgent
                                completionBlock:[resultBlock copy]];
        }
        if ([dictionary objectForKey:@"feed"] != nil) {
            dataTask.priority = NSURLSessionTaskPriorityHigh; // 将feed请求调为最高优先级
        }
        return dataTask;
    }
    

    分析所有参数:
    urlHost,dictionary,userAgent, block, startTime, timeDic,dataTask
    以上所有参数,除了timeDic,其他的都不存在多线程读写安全的问题,因为他们要不就是个真正的局部变量,或者不存在一个线程在读另一个线程在写的可能
    只有timeDic,在当前函数的下方有赋值的写操作,但是在block里面有读操作,并且不能保证当前函数的线程和block回调的线程是在同一个线程,所以是有造成多线程读写crash的

    解决方案

    对timeDic 读写进行加锁操作

    @synchronized (self) {
            timeDic = [self dicFromMetrics:metrics];
      }
    

    读操作这里用了copy,因为这个方法调用用到了timeDic,没法直接加锁
    如果强行加锁只能把整个方法加锁

    @synchronized (self) {
                [BDHKNetWorkService apiRequestTime:startTime
                          type:isTurbo ? @"turbo" : @"native"
                          code:errorCode
                       message:error.description
                      response:task.response
                    dictionary:dictionary
                responseObject:response
                       timeDic:tmpTimeDic
                           url:urlHost
                  responseTime:responseTime];
            }
    

    这种加锁方式风险极高,因为你不知道这个方法实现内部是否有耗时操作,如果有,这里就会造成阻塞,所以把timeDic直接加锁拷贝,因为方法内部没有对timeDic修改,只是获取内容,没有修改的操作,所以copy也不影响,最终修改方案如下:

    NSDictionary *tmpTimeDic = nil;
            @synchronized (self) {
                tmpTimeDic = [timeDic copy];
            }
            [BDHKNetWorkService apiRequestTime:startTime
                      type:isTurbo ? @"turbo" : @"native"
                      code:errorCode
                   message:error.description
                  response:task.response
                dictionary:dictionary
            responseObject:response
                   timeDic:tmpTimeDic
                       url:urlHost
              responseTime:responseTime];
    

    Q&A

    多线程同时读写为什么会造成crash:
    1,基本数据类型(非指针类型):不会造成crash,就是读取到的数据可能不对,不一致
    2,指针类型:由于指针类型是直接赋值的操作,多线程多写,a线程读的时候,b线程可能刚好给重新赋值,因此a线程拿到的指针就指向了一个异常内存,造成crash

    相关文章

      网友评论

          本文标题:crash之野指针

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