Skip to content

Instantly share code, notes, and snippets.

@0x8badf00d
Forked from mikeash/gist:5172803
Last active January 4, 2016 04:09
Show Gist options
  • Save 0x8badf00d/8566650 to your computer and use it in GitHub Desktop.
Save 0x8badf00d/8566650 to your computer and use it in GitHub Desktop.
#import "PLCrashReporterConfig.h"
#import "PLCrashReporter.h"
#import "PLCrashReport.h"
#import "PLCrashReportTextFormatter.h"
- (void)watchdog
{
NSTimeInterval pingInterval = 1.0/60.0;
NSTimeInterval watchdogInterval = 1.0/30.0;
__block NSTimeInterval lastPing = 0;
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, pingInterval * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(timer, ^{
lastPing = CFAbsoluteTimeGetCurrent();
});
dispatch_resume(timer);
dispatch_source_t watchdog = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0));
dispatch_source_set_timer(watchdog, DISPATCH_TIME_NOW, pingInterval * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(watchdog, ^{
// watchdog event handler gets called before timer event handler
if(lastPing > 0)
{
NSTimeInterval delta = CFAbsoluteTimeGetCurrent() - lastPing;
if(delta > watchdogInterval)
{
// Reset lastPing to 0
lastPing = 0;
NSLog(@"Main thread blocked for %f seconds", delta);
[self generateStackTraceReport];
}
}
});
dispatch_resume(watchdog);
}
- (void)generateStackTraceReport
{
PLCrashReporterConfig *config = [[PLCrashReporterConfig alloc] initWithSignalHandlerType:PLCrashReporterSignalHandlerTypeBSD
symbolicationStrategy:PLCrashReporterSymbolicationStrategyNone];
PLCrashReporter *crashReporter = [[PLCrashReporter alloc] initWithConfiguration:config];
NSError *err = nil;
NSData *crashData = [crashReporter generateLiveReportAndReturnError:&err];
if(!err)
{
NSError *crashReportError = nil;
PLCrashReport *report = [[PLCrashReport alloc] initWithData:crashData error:&crashReportError];
if(!crashReportError)
{
NSString *crashReportText = [PLCrashReportTextFormatter stringValueForCrashReport:report withTextFormat:PLCrashReportTextFormatiOS];
saveLiveReportForData(crashReportText);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment