代码之家  ›  专栏  ›  技术社区  ›  Piepants

无法确定EXC\u BAD\u ACCESS(在应用程序启动期间发生)的可能原因

  •  6
  • Piepants  · 技术社区  · 6 年前

    特别令人困惑的是,这是在应用程序启动时发生的,而内存不足-令人困惑的是,如果没有足够的内存供应用程序启动,我可能会看到其他类型的崩溃报告,而不是EXC\u BAD\u访问-即,如果EXC\u BAD\u访问是由访问删除的内存引起的,代码中没有任何地方可以删除任何内容,因为崩溃是在创建对象的过程中发生的。

    我尝试过很多方法来重现这种情况——在模拟器中运行并发送内存不足警告消息,在应用程序创建过程中故意使各种对象的初始化失败,在应用程序启动过程中调用calloc以消耗大量内存,在RAM完全耗尽的手机上运行应用程序无数次。我无法重新创建,也无法从代码检查中看出可能出了什么问题。

    Exception Type:  EXC_BAD_ACCESS (SIGSEGV) Exception Subtype:
    KERN_INVALID_ADDRESS at 0x0000000000000000 **(many also at 0x0000000000000008)**
    Thread 0 name:  Dispatch queue: com.apple.main-thread
    Thread 0 Crashed:
    0  The_Name_Of_MyApp             0x000000010268ca94 SearchViewController.init(coder:) + 838292 (SearchViewController.swift:67)
    1  The_Name_Of_MyApp             0x000000010268ca88 SearchViewController.init(coder:) + 838280 (SearchViewController.swift:67)
    2  The_Name_Of_MyApp             0x000000010268cd4c @objc SearchViewController.init(coder:) + 838988 (SearchViewController.swift:0)
    3  UIKitCore                     0x00000001bca63d64 -[UIClassSwapper initWithCoder:] + 248
    4  UIFoundation                  0x000000019a77fe88 UINibDecoderDecodeObjectForValue + 744
    5  UIFoundation                  0x000000019a7800cc UINibDecoderDecodeObjectForValue + 1324
    6  UIFoundation                  0x000000019a71eb3c -[UINibDecoder decodeObjectForKey:] + 320
    7  UIKitCore                     0x00000001bd0a1288 -[UIViewController initWithCoder:] + 1420
    8  UIKitCore                     0x00000001bceb5dcc -[UITabBarController initWithCoder:] + 80
    9  The_Name_Of_MyApp             0x000000010283f658 TabBarViewController.init(coder:) + 2618968 (TabBarViewController.swift:0)
    10 The_Name_Of_MyApp             0x000000010283f70c @objc TabBarViewController.init(coder:) + 2619148 (TabBarViewController.swift:0) 
    11 UIKitCore                     0x00000001bca63d64 -[UIClassSwapper initWithCoder:] + 248 
    12 UIFoundation                  0x000000019a77fe88 UINibDecoderDecodeObjectForValue + 744 
    13 UIFoundation                  0x000000019a71eb3c -[UINibDecoder decodeObjectForKey:] + 320 
    14 UIKitCore                     0x00000001bcd9dcbc -[UIRuntimeConnection initWithCoder:] + 188 
    15 UIFoundation                  0x000000019a77fe88 UINibDecoderDecodeObjectForValue + 744 
    16 UIFoundation                  0x000000019a7800cc UINibDecoderDecodeObjectForValue + 1324 
    17 UIFoundation                  0x000000019a71eb3c -[UINibDecoder decodeObjectForKey:] + 320 
    18 UIKitCore                     0x00000001bccc4a1c -[UINib instantiateWithOwner:options:] + 1124 
    19 UIKitCore                     0x00000001bce92f18 -[UIStoryboard instantiateViewControllerWithIdentifier:] + 196 
    20 The_Name_Of_MyApp             0x000000010266b4dc InitialViewController.start() + 701660 (InitialViewController.swift:118) 
    21 The_Name_Of_MyApp             0x000000010266bba4 @objc InitialViewController.start() + 703396 (InitialViewController.swift:0) 
    22 Foundation                    0x0000000190bff6d0 __NSFireDelayedPerform + 404 
    23 CoreFoundation                0x00000001900f2bf0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 28 
    24 CoreFoundation                0x00000001900f2920 __CFRunLoopDoTimer +864 
    25 CoreFoundation                0x00000001900f2154 __CFRunLoopDoTimers + 248 
    26 CoreFoundation                0x00000001900ed030 __CFRunLoopRun + 1880 
    27 CoreFoundation                0x00000001900ec5b8 CFRunLoopRunSpecific + 436 
    28 GraphicsServices              0x0000000192360584 GSEventRunModal + 100 
    29 UIKitCore                     0x00000001bc9e3558 UIApplicationMain + 212 
    30 The_Name_Of_MyApp             0x00000001026ea6b0 main + 1222320 (AppDelegate.swift:20) 
    31 libdyld.dylib                 0x000000018fbacb94 start + 4
    
    Thread 1: 
    0  libsystem_pthread.dylib       0x000000018fd80cfc start_wqthread + 0
    
    Thread 2 name:  Dispatch queue: com.myQueue.backgroundSerialQueue
    Thread 2: 
    0  libsystem_c.dylib             0x000000018fc60ae4 __v2printf + 616 
    1  libsystem_c.dylib             0x000000018fc60a00 __v2printf + 388 
    2  libsystem_c.dylib             0x000000018fc46ac0 _vsnprintf + 264 
    3  libsystem_c.dylib             0x000000018fc3b9c0 snprintf_l + 28 
    4  CoreFoundation                0x000000019010fa88 __CFStringAppendFormatCore + 8548 
    5  CoreFoundation                0x00000001901111b8 _CFStringCreateWithFormatAndArgumentsAux2 + 136 
    6  Foundation                    0x0000000190afd3ec -[NSString initWithFormat:locale:] + 36 
    7  Foundation                    0x0000000190afd364 -[NSNumber descriptionWithLocale:] + 1044 
    8  CoreFoundation                0x000000019004d9a8 -[__NSCFNumber descriptionWithLocale:] + 72 
    9  CoreFoundation                0x0000000190053268 -[__NSCFNumber stringValue] + 64 
    10 The_Name_Of_MyApp             0x00000001025f6494 -[RobocallerManager readCityAndStateData] + 222356 (RobocallerManager.m:596) 
    11 The_Name_Of_MyApp             0x00000001025f343c __25-[RobocallerManager init]_block_invoke + 209980 (RobocallerManager.m:148) 
    12 libdispatch.dylib             0x000000018fb9b6c8 _dispatch_call_block_and_release + 24 
    13 libdispatch.dylib             0x000000018fb9c484 _dispatch_client_callout + 16 
    14 libdispatch.dylib             0x000000018fb43c18 _dispatch_lane_serial_drain$VARIANT$mp + 592 
    15 libdispatch.dylib             0x000000018fb44760 _dispatch_lane_invoke$VARIANT$mp + 432 
    16 libdispatch.dylib             0x000000018fb4cf00 _dispatch_workloop_worker_thread + 600 
    17 libsystem_pthread.dylib       0x000000018fd7e0f0 _pthread_wqthread + 312 
    18 libsystem_pthread.dylib       0x000000018fd80d00 start_wqthread + 4
    
    Thread 3: 
    0  libsystem_pthread.dylib       0x000000018fd80cfc start_wqthread + 0
    
    Thread 4 name:  com.apple.uikit.eventfetch-thread
    Thread 4: 
    0  libsystem_kernel.dylib        0x000000018fceded0 mach_msg_trap + 8 
    1  libsystem_kernel.dylib        0x000000018fced3a8 mach_msg + 72 
    2  CoreFoundation                0x00000001900f1fb0 __CFRunLoopServiceMachPort + 236 
    3  CoreFoundation                0x00000001900ece4c __CFRunLoopRun + 1396 
    4  CoreFoundation                0x00000001900ec5b8 CFRunLoopRunSpecific + 436 
    5  Foundation                    0x0000000190ae06a4 -[NSRunLoop+ 34468 (NSRunLoop) runMode:beforeDate:] + 300 
    6  Foundation                    0x0000000190ae0514 -[NSRunLoop+ 34068 (NSRunLoop) runUntilDate:] + 88 
    7  UIKitCore                     0x00000001bc940ac0 -[UIEventFetcher threadMain] + 136 
    8  Foundation                    0x0000000190c133b0 __NSThread__start__ + 1040 
    9  libsystem_pthread.dylib       0x000000018fd7d2fc _pthread_body + 128 
    10 libsystem_pthread.dylib       0x000000018fd7d25c _pthread_start + 48 
    11 libsystem_pthread.dylib       0x000000018fd80d08 thread_start + 4
    
    Thread 5 name:  com.twitter.crashlytics.ios.MachExceptionServer
    Thread 5: 
    0  libsystem_kernel.dylib        0x000000018fceded0 mach_msg_trap + 8 
    1  libsystem_kernel.dylib        0x000000018fced3a8 mach_msg + 72 
    2  The_Name_Of_MyApp             0x000000010288d08c CLSMachExceptionServer + 1180 
    3  libsystem_pthread.dylib       0x000000018fd7d2fc _pthread_body + 128 
    4  libsystem_pthread.dylib       0x000000018fd7d25c _pthread_start + 48 
    5  libsystem_pthread.dylib       0x000000018fd80d08 thread_start + 4
    
    Thread 6: 
    0  libsystem_pthread.dylib       0x000000018fd80cfc start_wqthread + 0
    
    Thread 7: 
    0  libsystem_pthread.dylib       0x000000018fd80cfc start_wqthread + 0
    
    Thread 8: 
    0  libsystem_pthread.dylib       0x000000018fd80cfc start_wqthread + 0
    
    Thread 9: 
    0  libsystem_pthread.dylib       0x000000018fd80cfc start_wqthread + 0
    
    Thread 10 name:  com.apple.NSURLConnectionLoader
    Thread 10: 
    0  libsystem_kernel.dylib        0x000000018fceded0 mach_msg_trap + 8 
    1  libsystem_kernel.dylib        0x000000018fced3a8 mach_msg + 72 
    2  CoreFoundation                0x00000001900f1fb0 __CFRunLoopServiceMachPort + 236 
    3  CoreFoundation                0x00000001900ece4c __CFRunLoopRun + 1396 
    4  CoreFoundation                0x00000001900ec5b8 CFRunLoopRunSpecific + 436 
    5  CFNetwork                     0x000000019070ce18 -[__CoreSchedulingSetRunnable runForever] + 212 
    6  Foundation                    0x0000000190c133b0 __NSThread__start__ + 1040 
    7  libsystem_pthread.dylib       0x000000018fd7d2fc _pthread_body + 128 
    8  libsystem_pthread.dylib       0x000000018fd7d25c _pthread_start + 48 
    9  libsystem_pthread.dylib       0x000000018fd80d08 thread_start + 4
    
    Thread 0 crashed with ARM Thread State (64-bit):
        x0: 0x0000000000000000   x1: 0x0000000000000000   x2: 0x0000000282718580   x3: 0x0000000000000000
        x4: 0x0000000104870680   x5: 0x0000000000000000   x6: 0x0000000000000072   x7: 0x00000000000000a0
        x8: 0x0000000103f03650   x9: 0x0000000000000000  x10: 0x000000000000001f  x11: 0x0000000000000005
        x12: 0x0000000000000005  x13: 0x0000000000000000  x14: 0x0000000000000068  x15: 0x00000001ae696425
        x16: 0x000000018f34b858  x17: 0x0000000102601328  x18: 0x0000000000000000  x19: 0x0000000104853200
        x20: 0x00000001048709c8  x21: 0x0000000280b73880  x22: 0x00000001c92684c0  x23: 0x0000000104870600
        x24: 0x0000000281e51ec0  x25: 0x00000001c73e2000  x26: 0x0000000000000002  x27: 0x00000001c73e2000  
        x28: 0x0000000000000171   fp: 0x000000016d83c0b0   lr: 0x000000010268ca88
        sp: 0x000000016d83bcc0   pc: 0x000000010268ca94 cpsr: 0x60000000
    

    下面是一个图表,概述了崩溃报告中显示的对象之间的关系。基本上,在app启动时,AppDelegate会导致licensemanger对象被实例化,这又会导致DatabaseManager和数据库对象被创建,所有这些对象都是模型类型类。 同时,GUI启动时InitialVC是根VC,它实例化了TabBar VC,从而导致SearchVC的实例化。 SearchVC访问DatabaseModel对象,这就是崩溃发生的地方。

    enter image description here

    初始视图控制器

    ////////////////// InitialViewController ////////////////////////////
    class InitialViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            self.perform(#selector(InitialViewController.start), with: nil, afterDelay: 1.5)
        }
    }
    
    @objc func start() {
        let tbvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TabBarViewControllerID") as! TabBarViewController
    navigationController.pushViewController(tbvc, animated: true)
    }
    

    ///////////////////////// SearchViewController ///////////////////////////////
    class SearchViewController: UITableViewController, UISearchBarDelegate {
        var searchResultsList   = DatabaseManager.instance().database.emptyList() /** line 67 **/
    

    程序委托

    ////////////////////// App Delegate ///////////////////////////
    AppDelegate:didFinishLaunchingWithOptions() {
        let _ = LicenseManager.instance
    }
    

    //////////////////////// LicenseManager ////////////////////////
    @objc class LicenseManager : NSObject {
        @objc open static let instance = LicenseManager()
        private let databaseManager = DatabaseManager.instance()
    }
    
    override private init() {
        super.init()
    }
    

    数据库管理器

    ///////////////////// DatabaseManager ////////////////////////
    + (DatabaseManager*) instance {
        static DatabaseManager *theInstance = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^ {
            theInstance = [[DatabaseManager alloc] init];
        });
        return theInstance;
    }
    
    @interface DatabaseManager()
    @property (strong, nonatomic)   Database*  _Nonnull database;
    @property (strong, nonatomic)   NSMutableDictionary* cityAndStateDictionary;
    @end
    
    
    @implementation DatabaseManager
    - (id) init {
        self = [super init];
        if (self)
        {
            _database   = Database.instance;
            [_database openOrCreateDatabase];
    
    
            dispatch_async(robocallerQueue(), ^{
                [self readCityAndStateData];
            });
        }
        return self;
    }
    
    
    //Populates a very large dictionary > 100K entries
    - (void) readCityAndStateData
    {
        NSBundle* bundle = [NSBundle bundleForClass:[DatabaseManager class]];
        NSString *filePath = [bundle pathForResource:@"CityState" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        Assert(data, @"unable to read CityState.json file");
    
        NSError* __autoreleasing  nserror;
        NSDictionary* jsonParser = [NSJSONSerialization JSONObjectWithData: data
                                                                   options: NSJSONReadingAllowFragments
                                                                     error: &nserror];
        if (nserror == nil)
        {
            self.cityAndStateDictionary = [[NSMutableDictionary alloc] init];
            self.stateDictionary = [[NSMutableDictionary alloc] init];
            for (NSDictionary *item in jsonParser)
            {
                NSNumber* num1  = item[@"Code1"];
                NSNumber* num2  = item[@"Code2"];
                NSString* key   = [NSString stringWithFormat:@"%@%@", num1.stringValue, num2.stringValue];
                NSString* city  = item[@"City"];
                NSString* state = item[@"State"];
                NSString* value = [NSString stringWithFormat:@"%@, %@", [city capitalizedString], state];
                (self.cityAndStateDictionary)[key] = value;
    
                NSString* stateKey = [num1 stringValue];
                (self.stateDictionary)[stateKey] = state;
            }
            self.cityAndStateDataLoaded = TRUE;
        }
        else
        {
            Assert(data, @"unable to parse CityState.json file");
        }
    }
    

    数据库

    ////////////////////// Database //////////////////////
    @objcMembers class Database : NSObject {
        open static let instance = Database()
        fileprivate var configuration:Realm.Configuration?    = nil
    
        override init()
        {
        }
    }
    
    
    @objc func openOrCreateDatabase() {
           configuration = Realm.Configuration(encryptionKey: Database.getKey() as Data)
    }
    
    class func getKey() -> NSData {
        let string = "AED16D8B-7762-4CBF-A313-48FDCAD51B9C23456754635498123450ka&9dB6t"
        let data = string.data(using: String.Encoding.utf8)
        return data! as NSData
    }
    
    func emptyList() -> Results<Caller> {        
        let realm = try! Realm(configuration: configuration!)
        let mdn = "DoesNotExist"
        let searchTerm = "number ==  " + "\"" + mdn + "\""
        let results = realm.objects(Caller.self).filter(searchTerm)
        return results
     }
    

    //////////////// Caller ///////////
    @objc public class Caller : Object {
        @objc dynamic var name:String? = nil
        // More simple types, strings, dates, ints etc.
    }
    
    4 回复  |  直到 6 年前
        1
  •  2
  •   Ewan Mellor    6 年前

    在emptyList方法中,您有:

    let realm = try! Realm(configuration: configuration!)
    

    这就要崩溃了 try!

    看到了吗 https://realm.io/docs/swift/latest/#error-handling 对于正确的错误处理(基本上是一个do catch)。

        2
  •  3
  •   ielyamani    6 年前

    僵尸

    这不是强制展开的结果,我猜这是故意的,如果无法创建数据库,就会故意崩溃。 EXC_BAD_ACCESS KERN_INVALID_ADDRESS 当您有僵尸时发生:代码试图访问释放的内存(类似于崩溃消息) here here ).

    以下是消除僵尸的一般建议:

    • 在方案的“诊断”选项卡中的Xcode中启用僵尸对象
    • 使用工具在项目中查找僵尸

    罪魁祸首包括: DatabaseManager.instance().database.emptyList()

    1. DatabaseManager.instance()

      首先在AppDelegate中通过 let _ = LicenseManager.instance . 因为应用程序在调用时崩溃 SearchViewController.init(coder:) ,而不是在AppDelegate中,可以公平地假设 DatabaseManager.instance() , Database.instance 在AppDelegate中是无害的。

    2. DatabaseManager.instance().database

    3. emptyList()

      KERN_INVALID_ADDRESS 消息,如果是发送给僵尸。也就是说 DatabaseManager.instance().database 1.5 第二次延迟 InitialViewController 这还不够 robocallerQueue 返回非零 DatabaseManager.instance().database . 从崩溃报告中可以看到,当主线程(线程0)崩溃时,线程2仍在执行 readCityAndStateData


    解决

    searchResultsList 延迟,或者使用完成处理程序而不是1.5秒的延迟。

        3
  •  0
  •   Augie    6 年前

    • 因为它处理的是ObjC类DataBaseManager,其中nil是 如果允许,则可能某个内容未被展开且为空
    • 可能在emptyList()中强制展开配置
    • 异步调度中指向自身的强指针(robocallerQueue()^{ [自述城市和状态数据];

    还有,这个领域有多大?

        4
  •  -1
  •   Ali Moazenzadeh    6 年前

    基于WWDC18高级调试会话,您可以使用以下解决方法:

    1. 从XCode左侧菜单打开断点导航器选项卡
    2. 单击底部的+按钮
    3. 创建一个新的“异常断点”并选择“Objective-c”异常

    现在重新运行你的应用程序,看看它是否显示正确的崩溃情况