惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
J
Java Code Geeks
S
SegmentFault 最新的问题
L
LangChain Blog
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
IT之家
IT之家
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Cloudflare Blog
MongoDB | Blog
MongoDB | Blog
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
H
Help Net Security
阮一峰的网络日志
阮一峰的网络日志
Jina AI
Jina AI
N
Netflix TechBlog - Medium
A
About on SuperTechFans
博客园 - 叶小钗
美团技术团队
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net

ashishb.net

A day in Luxembourg - the richest country in the world I was asked to install malware during a fake interview Book summary: Breakneck - China's quest to engineer the future by Dan Wang Book summary: How to Teach Your Baby to Read Book Summary: The Discontented Little Baby Book by Pamela Douglas Introducing Amazing Sandbox - run third-party tools and AI agents securely on your machine Why software outsourcing gets a bad reputation? Book summary: The Natural Baby Sleep Solution by Polly Moore A day in Antwerp, Belgium Journey of online influencers Two days in Brussels, Belgium Shortcuts - when we love them and when we don't A visit to Rakhigarhi Three days in overhyped Paris Empty Japan, crowded Tokyo The real lock-in in GitHub is not the code, but the stars 11-day Norwegian Breakaway East Caribbean cruise Sanskrit and Sri Lankan Air Force Use REST with Open API The Achilles heel of American capitalism Costa Rica in 4 days At a juice stall in Sri Lanka A short stay at Warsaw, Poland Best practices for using Python & uv inside Docker Two days in Vilnius, Lithuania How IntelliJ IDEs waste disk space Pregnancy Why there aren't many digital nomads from India Two days in Riga, Latvia To keep your machine secure, run third-party tools inside Docker
Android: Catching NDK crashes
Ashish Bhatia · 2021-02-07 · via ashishb.net

On Android catching Java exceptions is easy via UncaughtExceptionHandler. Catching NDK crashes is a bit more convoluted. Since the native stack is probably corrupted, you want the crash handler to run on a separate process. Also, since the system might be in an unstable shape, don’t send the crash report to your web server or do anything fancy. Just write the crash report to a file, and on the next restart of the app, send to your web server and delete it from the disk. I ended up using jndcrash package for this.

  1. Create a new Service that extends ru.ivanarh.jndcrash.NDCrashService

  2. Run this as a sticky service in a separate process by adding the following to the AndroidManifest.xml

    1
    2
    3
    
    <!-- Create a new process to handle native crashes
             https://github.com/ivanarh/jndcrash#out-of-process -->
        <service android:name=".NdkCrashService" android:process=":ndkCrashReportProcess"/>
  3. Override onCrash to read the logcat logs and write a report to a new location. I didn’t care about it overwriting an existing native crash report, but if your app has a million+ installs, you should generate filename patterns for crash reports.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
    @Override
      public void onCrash(String reportPath) {
        String logcatLogs = getLogcatLogs(NUM_LOGCAT_LINES);
        String ndkLogcatLogsReportPath = getNdkCrashLogcatLogsPath(this);
        Log.i(TAG, "onCrash, stack trace in " + reportPath);
        Log.i(TAG, "onCrash, logcat logs are in " + ndkLogcatLogsReportPath);
        Log.d(
          TAG,
          "Logcat logs for the native error (from last " +
          NUM_LOGCAT_LINES +
          " lines): \"" +
          logcatLogs +
          "\""
        );
        try (FileWriter fileWriter = new FileWriter(ndkLogcatLogsReportPath, false/* append */)) {
          for (String line : logcatLogs.split("\n")) {
            // Build fingerprint marks the beginning of native crash dump which is already
            // present in the reportPath file.
            if (line.contains("Build fingerprint")) {
              break;
            }
            fileWriter.write(line);
            fileWriter.write("\n");
          }
          fileWriter.flush();
        } catch (IOException e) {
          Log.e(TAG, "Error writing more logs to native crash report " + reportPath);
        }
      }
  4. In the app’s onCreate, initialize the crash reporter.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    private void initNdkCrashHandler() {
        final String reportPath = NdkCrashService.getNdkCrashLogReportPath(this);
        final NDCrashError error = NDCrash.initializeOutOfProcess(
          this,
          reportPath,
          NDCrashUnwinder.libunwind,
          NdkCrashService.class
        );
        if (error == NDCrashError.ok) {
          Log.i("MainApplication@initJndcrash", "NDK crash handler init successful");
        } else {
          Log.e("MainApplication@initJndcrash", "NDK crash handler init failed: " + error);
        }
      }
  5. It is probably best to read and submit any existing reports in the same initNdkCrashHandler method. Since we were using React Native, we ended up doing it a bit differently. We used Sentry to wrap a native crash and report it as a Java Exception; you can do this for your crash reporting mechanism as well.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    
    const uploadNdkCrashesIfAny = async () => {
      // This file path should be same here and in MainApplication.java
      const ndkCrashLogsFilePath = RNFS.CachesDirectoryPath + '/ndk_crash_logs.txt'
      const ndkCrashLogcatLogsFilePath = RNFS.CachesDirectoryPath + '/ndk_crash_logcat_logs.txt'
    
      if (!(await RNFS.exists(ndkCrashLogsFilePath))) {
        Logger.debug(
          'Sentry@uploadNdkCrashesIfAny',
          `crash log file ${ndkCrashLogsFilePath} not found, no native crashes recorded`
        )
        return
      }
    
      const fileSize = parseInt((await RNFS.stat(ndkCrashLogsFilePath)).size, 10)
      Logger.info(
        'Sentry@uploadNdkCrashesIfAny',
        `crash log file ${ndkCrashLogsFilePath} found (${fileSize} bytes), capturing it via Sentry`
      )
      const msg1 = (await RNFS.exists(ndkCrashLogcatLogsFilePath))
        ? await RNFS.readFile(ndkCrashLogcatLogsFilePath)
        : 'Logcat logs not available'
      const msg2 = await RNFS.readFile(ndkCrashLogsFilePath)
    
      Sentry.captureMessage(`NDK crash\n${msg1}\n${msg2}`)
      await RNFS.unlink(ndkCrashLogsFilePath)
    
      if (!(await RNFS.exists(ndkCrashLogcatLogsFilePath))) {
        await RNFS.unlink(ndkCrashLogcatLogsFilePath)
      }
    }

    And a simple mechanism to handle native crashes would be ready. The best part is that this approach is not tied to your crash reporter, so, you can choose Sentry or Firebase Crashlytics or any other mechanism.