Crash监控的简单实现方案
个人博客
Crash监控的简单实现方案
前言
本文从Java层及Native展开,简单记录Android中的Crash监控方案。
Java层Crash
Java层的crash监控,可以通过实现Thread.UncaughtExceptionHandler
接口,重写uncaughtException
方法来实现,简单示意代码如下:
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;
private static Context mContext;
private static String mPath;
public static void init(Context context, String path) {
mContext = context.getApplicationContext();
mPath = path;
defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
}
@Override
public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
File dir = new File(mContext.getExternalCacheDir(), mPath);
if (!dir.exists()) {
dir.mkdirs();
}
long l = System.currentTimeMillis();
File file = new File(dir, l + ".txt");
try {
PrintWriter pw = new PrintWriter(new FileWriter(file));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
pw.println("time: " + sdf.format(new Date()));
pw.println("thread: " + thread.getName());
throwable.printStackTrace(pw);
pw.flush();
pw.close();
} catch (Exception ioException) {
ioException.printStackTrace();
} finally {
if (defaultUncaughtExceptionHandler != null) {
defaultUncaughtExceptionHandler.uncaughtException(thread, throwable);
}
}
}
}
新建一个CrashUtil
类,封装CrashHandler
public class CrashUtil {
//Java层Crash信息保存目录
public static final String JAVA_CRASH_DIR = "java_crash";
public static void init(Context context) {
//初始化Java层CrashHandler
Context applicationContext = context.getApplicationContext();
CrashHandler.init(applicationContext, JAVA_CRASH_DIR);
}
}
在Application的onCreate方法中,初始化CrashHandler
public class AppInit extends Application {
@Override
public void onCreate() {
super.onCreate();
CrashUtil.init(this);
}
}
在AndroidManifest
中配置Application
的name
属性
<application
android:name=".AppInit"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--省略其它代码-->
</application>
Native层Crash
Native层crash监控,可以采用Google的BreakPad开源框架。开源地址:https://github.com/google/breakpad
BreakPad需要编译后才能使用。
-
新建一个module,专门编译BreakPad。
-
要新建的breakpadlib的src/main目录下,新建cpp目录,这个目录名称随意。
-
在cpp目录下新建breakpad目录,这个目录名称随意。
-
将下载回来的BreakPad代码解压后,将里面的src目录都复制到刚才新建的breakpad目录下。
-
在breakpad目录下新建CMakeLists.txt文件,在里面配置如下
cmake_minimum_required(VERSION 3.4.1) include_directories(src src/common/android/include) enable_language(ASM) add_library(breakpad STATIC src/client/linux/crash_generation/crash_generation_client.cc src/client/linux/dump_writer_common/thread_info.cc src/client/linux/dump_writer_common/ucontext_reader.cc src/client/linux/handler/exception_handler.cc src/client/linux/handler/minidump_descriptor.cc src/client/linux/log/log.cc src/client/linux/microdump_writer/microdump_writer.cc src/client/linux/minidump_writer/linux_dumper.cc src/client/linux/minidump_writer/linux_ptrace_dumper.cc src/client/linux/minidump_writer/minidump_writer.cc src/client/minidump_file_writer.cc src/common/convert_UTF.cc src/common/md5.cc src/common/string_conversion.cc src/common/linux/breakpad_getcontext.S src/common/linux/elfutils.cc src/common/linux/file_id.cc src/common/linux/guid_creator.cc src/common/linux/linux_libc_support.cc src/common/linux/memory_mapped_file.cc src/common/linux/safe_readlink.cc) target_link_libraries(breakpad log)
-
在breakpadlib模块的src/main/java/包名/目录下,创建NativeCrash.java文件,在这里声明Native方法,方便其它模块调用
public class NativeCrash { static { System.loadLibrary("breakpad_lib"); } public static void init(String path) { initNativeCrash(path); } /** * 初始化NativeCrash * * @param path */ private static native void initNativeCrash(String path); }
-
在cpp目录下,新建breakpad_lib.cpp文件,实现native方法,并配置Native层crash的监听
#include <jni.h> #include <android/log.h> #include "client/linux/handler/minidump_descriptor.h" #include "client/linux/handler/exception_handler.h" #define TAG "breakpad_lib" bool DumpCallback(const google_breakpad::MinidumpDescriptor &descriptor, void *context, bool succeeded) { __android_log_print(ANDROID_LOG_ERROR, TAG, "native crash:%s", descriptor.path()); return false; } extern "C" JNIEXPORT void JNICALL Java_com_wangyz_breadpadlib_NativeCrash_initNativeCrash(JNIEnv *env, jclass clazz, jstring path_) { const char *path = env->GetStringUTFChars(path_, 0); __android_log_print(ANDROID_LOG_INFO, TAG, "initNativeCrash,dmp path:%s", path); google_breakpad::MinidumpDescriptor descriptor(path); static google_breakpad::ExceptionHandler eh(descriptor, NULL, DumpCallback, NULL, true, -1); env->ReleaseStringUTFChars(path_, path); }
-
在cpp目录下创建CMakeLists.txt文件
cmake_minimum_required(VERSION 3.4.1) include_directories(breakpad/src breakpad/src/common/android/include) add_library(breakpad_lib SHARED breakpad_lib.cpp) add_subdirectory(breakpad) target_link_libraries(breakpad_lib breakpad log)
-
在breakpadlib的build.gradle文件中配置ndk
android { //... defaultConfig { //... // 要编译哪些CPU架构 externalNativeBuild { cmake { abiFilters 'armeabi-v7a', 'x86' } } // 把哪些CPU架构打包进去 ndk { abiFilters 'armeabi-v7a', 'x86' } } externalNativeBuild { cmake { path 'src/main/cpp/CMakeLists.txt' } } //... }
-
build这个module,就会生成包含so的aar,可以给其它模块引用,这样就可以为Native层的Crash增加监控。
breakpadlib目录结构如图
注意事项
在编译时,一般会报错。这是由于缺少相应的文件导致的。将linux_syscall_support.h
文件放到cpp/breakpad/src/third_part/lss目录下,再编译就可以了。
app模块引用breakpad编译出来的aar
将编译出来的aar放到app模块的libs目录下,并配置app的build.gradle文件
android {
//...
sourceSets {
main {
jniLibs.srcDir(['libs'])
}
}
repositories {
flatDir {
dirs 'libs'
}
}
}
dependencies {
//...
api(name: 'breadpadlib-release', ext: 'aar')
}
同步工程,然后在前面创建的CrashUtil中增加对Native的Crash的初始化。
public class CrashUtil {
//Java层Crash信息保存目录
public static final String JAVA_CRASH_DIR = "java_crash";
//Native层Crash信息保存目录
public static final String NATIVE_CRASH_DIR = "native_crash";
public static void init(Context context) {
//初始化Java层CrashHandler
Context applicationContext = context.getApplicationContext();
CrashHandler.init(applicationContext, JAVA_CRASH_DIR);
//初始化Native层CrashHandler
File file = new File(context.getExternalCacheDir(), NATIVE_CRASH_DIR);
if (!file.exists()) {
file.mkdirs();
}
NativeCrash.init(file.getAbsolutePath());
}
}
模拟Native层Crash
-
新建一个module:crash,用于生成演示Native层Crash所用的so。
-
在crash模块下的src/main/java/目录下创建CrashTest.java,声明native方法
public class CrashTest { static { System.loadLibrary("crash_test"); } public static void testCrash() { test(); } private static native void test(); }
-
在crash模块下的src/main/目录下,新建jni目录
-
在jni目录下新建cpp目录,在cpp目录下创建crash_test.cpp
#include <jni.h> extern "C" JNIEXPORT void JNICALL Java_com_wangyz_crash_CrashTest_test(JNIEnv* env,jclass clazz) { int * i = NULL; *i = 0; }
-
生成so
可以通过ndk-build直接生成so文件。在jni目录下创建Android.mk
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := crash_test LOCAL_SRC_FILES := cpp/crash_test.cpp include $(BUILD_SHARED_LIBRARY)
然后在jni的目录下,执行cmd命令ndk-build。如果没有在系统环境变量中配置ndk,一般会报
'ndk-build' 不是内部或外部命令,也不是可运行的程序
。通过Android Studio下载的ndk,一般在Android Studio配置的SDK目录下。进入SDK目录下的ndk目录,选择一个版本的ndk,将这个路径配置到环境变量中。重新打开CMD窗口,并定位到jni目录下,重新执行ndk-build,就会在jni目录下生成libs和obj目录。也可以在crash模块的build.gradle中配置来生成aar
android { //... defaultConfig { //... // 要编译哪些CPU架构 externalNativeBuild { cmake { abiFilters 'armeabi-v7a', 'x86' } } // 把哪些CPU架构打包进去 ndk { abiFilters 'armeabi-v7a', 'x86' } } externalNativeBuild { cmake { path 'src/main/jni/CMakeLists.txt' } } //... }
在jni目录下创建CMakeLists.txt
# CMake方式需要在build.grale中配置其它信息,但可以build生成aar # 采用Android.mk配置,不需要再额外配置信息 cmake_minimum_required(VERSION 3.4.1) include_directories(cpp/) add_library(crash_test SHARED cpp/crash_test.cpp) target_link_libraries(crash_test)
build后,就可以生成包含so的aar文件
crash模块的目录结构
-
将aar放到app模块的libs目录,并在build.gradle中增加对新加入的aar的引用
api(name: 'crash-release', ext: 'aar')## 测试Crash
测试Crash
Java Crash
在Activity的onCreate中加入以下代码
//模拟java crash
int i = 1 / 0;
打包APK,安装到手机,运行APK,程序Crash。查看/sdcard/Android/data/包名/,发现在java_crash目录,生成了记录crash信息的文件。
Native Crash
在Activity的onCreate中加入以下代码
//模拟native crash
CrashTest.testCrash();
打包APK,安装到手机,运行APK,程序Crash。查看/sdcard/Android/data/包名/,发现在native_crash目录,生成了记录crash信息的文件xxx.dmp。
将dmp文件导出到电脑。然后在Android Studio的安装目录/bin/lldb/bin中,执行CMD命令
minidump_stackwalk D:\15d05b74-5316-4082-cb24cda2-80f355e4.dmp > crash.txt
在当前目录下会生成crash.txt文件
Operating system: Android
0.0.0 Linux 4.4.23+ #1 SMP PREEMPT Wed Sep 30 13:40:36 CST 2020 armv7l
CPU: arm
ARMv1 ARM part(0x4100d0b0) features: half,thumb,fastmult,vfpv2,edsp,neon,vfpv3,tls,vfpv4,idiva,idivt
8 CPUs
GPU: UNKNOWN
Crash reason: SIGILL
Crash address: 0xcb13875c
Process uptime: not available
Thread 0 (crashed)
0 libcrash_test.so + 0x75c
r0 = 0xed7b1230 r1 = 0xffc18d0c r2 = 0x00430000 r3 = 0xffc18ec8
r4 = 0xef0c35f4 r5 = 0x00000000 r6 = 0x00000000 r7 = 0xffc18fc8
r8 = 0x00000056 r9 = 0xed7cb000 r10 = 0x00000000 r12 = 0xcb13875d
fp = 0xffc18d74 sp = 0xffc18d00 lr = 0xcb2d3519 pc = 0xcb13875c
Found by: given as instruction pointer in context
1 dalvik-LinearAlloc (deleted) + 0xe5f2
sp = 0xffc18d04 pc = 0xef0c35f4
Found by: stack scanning
2 dalvik-main space (region space) (deleted) + 0xc909ce
sp = 0xffc18d10 pc = 0x138909d0
Found by: stack scanning
3 libart.so + 0x3e0931
sp = 0xffc18d70 pc = 0xeb2a0933
Found by: stack scanning
4 base.vdex + 0x1d521f
sp = 0xffc18d78 pc = 0xcb519221
Found by: stack scanning
这个文件列出了操作系统、CPU等信息。
在ndk目录下,找到ndk\21.0.6113669\toolchains\arm-linux-androideabi-4.9\prebuilt\windows-x86_64\bin\目录,这里的arm-linux-androideabi-4.9具体以手机的CPU架构为准。
执行CMD
arm-linux-androideabi-addr2line.exe -f -C -e D:\libcrash_test.so 0x75c
这里的libcrash_text.so就是发生crash的so文件,0x75c为上面转换出来的crash.txt中发生crash的地址。通过addr2line工具,可以看到发生crash的具体行数。
后记
关于crash监控方案,本文记录得比较浅显的,可以查阅其它更详细的资料。
源码
https://github.com/milovetingting/Samples/tree/master/BreakPad
个人主页:http://www.milovetingting.cn