IOS Boot continuous Flash protection scheme

Source: Internet
Author: User
Tags signal handler

Introduction

"If an entity shows any of the following characteristics, it has autonomy: self-healing, self-protection, self-maintenance, self-control of goals, self-improvement." "--Kevin Kelly

IOS apps can sometimes encounter the desperate need to start crash: Every time the app is turned off, the app doesn't work.

To try to solve this problem, reading has developed IOS continuous flash Protection tool: Gybootingprotection, detect continuous flash, in the continuous flash exit now, try to self-repair App:


This paper discusses the causes, detection and repair mechanisms of continuous flash-back problems, and how to introduce, test and use gybootingprotection in your project.

Continuous Flash detection

First of all to detect the user App has a continuous flash, there are two detection methods, catch exceptions and timers.

1. Catching Exceptions

Detection of continuous flash can be achieved by catching exceptions with the following types of exceptions:

    • Mach Exception: Exc_crash

    • UNIX Signal: SIGABRT

    • NSException Exception: Application layer, captured by Nsuncaughtexceptionhandler

In a ramble about the IOS Crash Collection framework, the mechanism of Mach anomaly and Unix signal capture Crash is described in detail. In short, exceptions typically result from the micro-core Mach from IOS, which is then converted to a UNIX SIGABRT signal in the BSD layer and provided to the user in the form of a standard POSIX signal. NSException is a programmatic way for users to handle App logic.

How to catch exceptions

The exception is caught by the following methods:

    • Using the Mach API to capture Mach anomalies

    • Registering signal (Sigsegv,signalhandler) with the POSIX API to capture UNIX anomaly signals

    • Registering Nsuncaughtexceptionhandler to capture application-level exceptions

Crash escalation tool such as plcrashreporter by registering Mach anomaly + UNIX signal handler to achieve the purpose of detection, the user is provided with an interface to handle the exception.

How to detect

You can use tools such as plcrashreporter to detect continuous flash-back:

    1. First, maintain a count variable that indicates the number of consecutive flashes

    2. Add logic in Plcrashreporter's crash handler: If you start the 5s inside the crash the counter adds a

    3. Continuous flash detection If continuous flash count > n at each start

    4. After startup, perform a timed task to reset the count after 5s (if the APP continues to flash it will not reset)

Flowchart

Pros and cons

With Mach anomaly, Unix signal, nsexception anomaly to detect the flashback, more crash contexts can be obtained, but as the crash collection framework uses these methods more, there may be a risk that a collision with a third-party crash collection framework leads to leak detection. In addition, it may be coupled with the exception handling code that the APP already has.

2. Timer Method

In addition to detecting continuous flash by catching an exception, you can also detect by means of a counter method:

    1. Maintains a count variable that represents the number of consecutive flashes

    2. After starting the application:didfinishlaunchingwithoptions: Add a Count to the

    3. Then use the Dispatch_after method in the 5s after the 0 count, if the APP can not live 5 seconds count will not be zeroed

    4. If a count variable > n is found, it indicates that the APP continuously flashes n consecutive times, initiates the protection process, resets the count.

    5. When the protection process is complete, go to the App normal START process

Flowchart

Pros and cons

But the counter method logic is simple, and the original code coupling is small. Although the error may be (killed immediately after launch, mistaken for crash), the false positives can be reduced by setting a threshold value.

In the balance, we use the Timer method to detect continuous flash-back.

continuous flash back repair

A continuous flash is detected, and the next step is to try to fix the flashback, which first analyzes the possible causes of the flashback, and then combines the example of a reading to illustrate the repair process.

reasons for Flash back

A continuous flashback may be the code that executes the required crash in the APP startup critical path, possibly for the following reasons:

    1. Database corruption: In daily use such as abnormal exit, power outage, or incorrect operation (refer to: sqlite corruption causes).

    2. File corruption: If no file is processed @try...catch , the corrupted file will be thrown to NSException cause crash

    3. The network returns data processing exceptions: For example, an array is expected to be returned, but the dictionary is actually returned, the method of executing the Dictionary object -objectAtIndex is generated crash: unknow selector send to object; , or the damaged Tar package is returned, causing crash in the decompression failure.

    4. Code bug: When the required crash code appears in the startup critical path, it causes a continuous flash.

For 1, you can repair the database through the tool, or delete the db. For 2, you can delete files to fix them. For 3 and 4, we need to specifically analyze crash cases and fix them through Jspatch.

the repair process of reading

In order to deal with the reasons for the above-mentioned continuous flashback, the repair process of reading is:

  1. Check for continuous flash when entering didfinishlaunch, no execution 5

  2. Flick Toast to prompt the user whether to repair, tap "repair" to perform 2, otherwise perform 5

  3. Try to download and execute the Jspatch patch

    This is to resolve the flash-off caused by the above 4th-code bug, which can be thermally repaired using jspatch [GitHub]. When didfinishlaunching, the interface will be stuck to request check whether there is an available Jspatch script, if any, load execution, to resolve the code bug caused by the flash back.

  4. Try to Documents delete Library Caches all files in//directory

    All user data is deleted directly, and all data is available in the cloud, and can be recovered completely from the cloud after deletion. If your App is not part of this scenario, you should customize the fix logic in Repairblock, such as:

    A. Do not delete files, only repair the database
    B. Back up user data to the cloud before repair
    C. Collection of crash samples, identification of causes, custom Jspatch repair patches and issued

  5. Quit Reading Login Status

  6. Enter the original Didfinishlaunch

Continuous flash detection + protection process:

Implement

There are several ways to detect and continuously crash and fix the original logic that needs to be modified -application:didFinishLaunchingWithOptions: :

    1. Modify the -application:didFinishLaunchingWithOptions: method directly.

    2. Create a new SubAppDelegate class to inherit AppDelegate , overwrite the -application:didFinishLaunchingWithOptions: method, and main() AppDelegate replace the function with theSubAppDelegate

    3. Create a new AppDelegate extension, and then replace the method with method Swizzle -application:didFinishLaunchingWithOptions: .

For the above three scenarios, the cost of changes to existing projects is 1 > 2 > 3. Therefore, we use a scheme that minimizes the cost of modifying the source code to replace it -application:didFinishLaunchingWithOptions: .

The detected logic gybootingprotection has been processed, the processing of the repair has reserved the interface, can be customized by the user, the custom repair process into the repairblock can be.

UseIntroduction of Projects
  1. Download (github) source, drag and drop src all files from the directory to your Xcode project

  2. AppDelegate+GYBootingProtection.m onBeforeBootingProtection Add code that needs to be executed before detection in the method, such as setting the crash escalation:

    - (void)onBeforeBootingProtection { [GYBootingProtection setLogger:^(NSString *msg) {     // setup logger     NSLog(@"%@", msg); }]; [GYBootingProtection setReportBlock:^(NSInteger crashCounts) {     // setup crash report }];}
  3. onBootingProtectionAdd repair logic to the method, such as deleting a file:

     - (void)onBootingProtection {     // 检查 JSPatch 更新     ...     // 删除 Documents Library Caches 目录下所有文件     [GYBootingProtection deleteAllFilesUnderDocumentsLibraryCaches];     ... }

    To perform asynchronous repair logic, onBootingProtectionWithCompletion: add the repair logic in the method and call completion after the repair is complete:

     - (void)onBootingProtectionWithCompletion:(BoolCompletionBlock)completion {        [self onBootingProtection];     // 异步修复        [self asyncRepairWithCompletion:^(void) {         // 正常启动流程            if (completion) completion();        }]; }
    Testing and use
  4. Create a continuous flashback scenario first:

    Within 5 Seconds of startup, double-click Home to kill the App repeatedly by using the swipe gesture. (You can also make crash in code)

  5. When there are more than 5 consecutive flashes, the user is prompted to fix:



  6. The user taps The fix, the APP resets the initial state, and the continuous flashback problem is resolved:



Source Code

Https://github.com/liuslevis/GYBootingProtection

IOS Boot continuous Flash protection scheme

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.