将异常一网打尽,爱奇艺开源xCrash是如何做的?
Posted xhmj12
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将异常一网打尽,爱奇艺开源xCrash是如何做的?相关的知识,希望对你有一定的参考价值。
链接:https://juejin.cn/post/6991356414069309477
需要注意一点,因为开源项目一直在更新,文章和最新项目可能有些许变化,但基本不影响学习~
1
Xcrash简介Xcrash是爱奇艺在2019年4月开源在GitHub上的稳定性日志收集框架,它能为android收集java crash、native crash、anr日志。不需要root权限和系统权限。支持 Android 4.1 - 11(API level 16- 30),支持 armeabi,armeabi-v7a,arm64-v8a,x86 和 x86_64。
项目地址:
https://github.com/iqiyi/xCrash
分析版本: v2.5.7
2
Xcrash架构3
Xcrash类图xcrash作为门面模式的入口,client调用通过配置InitParameter来进行初始化。Xcrash分别关联三种类型Handler来处理对应的奔溃监听和日志收集,通过FileManager和TombstoneManager对奔溃日志进行tombstone文件管理。client调用TombstoneParser来解析本地生成的对应tombstone文件,获取数据。
4
捕获Java奔溃Java层的崩溃可以直接交给JVM的崩溃捕获机制去处理。这个非常简单,不赘述。
Thread.setDefaultUncaughtExceptionHandler(this);
如果有java crash发生,会回调uncaughtException,执行handleException收集相关log信息。
private void handleException(Thread thread, Throwable throwable) {
...
//notify the java crash
NativeHandler.getInstance().notifyJavaCrashed();
AnrHandler.getInstance().notifyJavaCrashed();
//create log file data/data/packageName/files/tombstones
logFile = FileManager.getInstance().createLogFile(logPath);
...
//write info to log file
if (logFile != null) {
…
// write java stacktrace
raf.write(emergency.getBytes("UTF-8"));
//write logcat日志 logcat -b main;logcat -b system; logcat -b event;
raf.write(Util.getLogcat(logcatMainLines, logcatSystemLines, logcatEventsLines).getBytes("UTF-8"));
//write fds
raf.write(Util.getFds().getBytes("UTF-8"));
//write network info
raf.write(Util.getNetworkInfo().getBytes("UTF-8"));
//write memory info
raf.write(Util.getMemoryInfo().getBytes("UTF-8"));
//write background / foreground
raf.write(("foreground:\\n" + (ActivityMonitor.getInstance().isApplicationForeground() ? "yes" : "no") + "\\n\\n").getBytes("UTF-8"));
//write other threads info
if (dumpAllThreads) {
raf.write(getOtherThreadsInfo(thread).getBytes("UTF-8"));
}
}
//callback 回调ICrashCallback onCrash
if (callback != null) {
try {
callback.onCrash(logFile == null ? null : logFile.getAbsolutePath(), emergency);
} catch (Exception ignored) {
}
}
}
5捕获Native奔溃
Crash.java
public static synchronized int init(Context ctx, InitParameters params) {
…
NativeHandler.getInstance().initialize(...)
...
}
NativeHandler.java
int initialize(...) {
//load lib
System.loadLibrary("xcrash");
...
//init native lib
try {
int r = nativeInit(...);
}
...
}
NativeHandler在Xcrash init时会执行initialize方法进行初始化,初始化过程首先通过System.loadLibrary("xcrash”)注册native函数,其次就是调用nativeInit。
执行System.loadLibrary("xcrash”),JNI_OnLoad会被回调,这里是动态注册玩法。
xc_jni.c
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
...
if((*env)->RegisterNatives(env, cls, xc_jni_methods, sizeof(xc_jni_methods) / sizeof(xc_jni_methods[0]))) return -1;
...
return XC_JNI_VERSION;
}
数组0元素对应:
static JNINativeMethod xc_jni_methods[] = {
{
"nativeInit",
"("
"I"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Ljava/lang/String;"
"Z"
"Z"
"I"
"I"
"I"
"Z"
"Z"
"Z"
"Z"
"Z"
"I"
"[Ljava/lang/String;"
"Z"
"Z"
"I"
"I"
"I"
"Z"
"Z"
")"
"I",
(void *)xc_jni_init
},
…
}
java层调用nativeInit,native xc_jni_init会被调用。接着看nativeInit逻辑 xc_jni.c。
static jint xc_jni_init(...)
{
...
//common init
xc_common_init(…);//通用信息初始化,包括系统信息、应用信息、进程信息等。
...
//crash init 捕获crash日志
r_crash = xc_crash_init(…);
...
//trace init 捕获anr日志
r_trace = xc_trace_init(...);
}
...
return (0 == r_crash && 0 == r_trace) ? 0 : XCC_ERRNO_JNI;
}
先看xc_crash_init
int xc_crash_init(){
…
//init for JNI callback
xc_crash_init_callback(env);//1设置信号native 信号回调 jni到java
…
//register signal handler
return xcc_signal_crash_register(xc_crash_signal_handler);//2注册信号handler,能回调处理对应的信号
}
1)设置callback:
xc_crash_init_callback最终回调的是NativeHandler的crashCallback。
private static void crashCallback(String logPath, String emergency, boolean dumpJavaStacktrace, boolean isMainThread, String threadName) {
if (!TextUtils.isEmpty(logPath)) {
//append java stacktrace
TombstoneManager.appendSection(logPath, "java stacktrace", stacktrace);
...
//append memory info
TombstoneManager.appendSection(logPath, "memory info", Util.getProcessMemoryInfo());
//append background / foreground
TombstoneManager.appendSection(logPath, "foreground", ActivityMonitor.getInstance().isApplicationForeground() ? "yes" : "no");
}
//最后回调到client注册的ICrashCallback.onCrash
ICrashCallback callback = NativeHandler.getInstance().crashCallback;
if (callback != null) {
callback.onCrash(logPath, emergency);
}
...
}
2)信号注册:
static xcc_signal_crash_info_t xcc_signal_crash_info[] =
{
{.signum = SIGABRT},//调用abort函数生成的信号,表示程序异常
{.signum = SIGBUS},// 非法地址,包括内存地址对齐出错
{.signum = SIGFPE},// 计算错误,比如除0、溢出
{.signum = SIGILL},// 强制结束程序
{.signum = SIGSEGV},// 非法内存操作
{.signum = SIGTRAP},// 断点时产生,由debugger使用
{.signum = SIGSYS},// 非法的系统调用
{.signum = SIGSTKFLT}// 协处理器堆栈错误
};
int xcc_signal_crash_register(void (*handler)(int, siginfo_t *, void *))
{
stack_t ss;
if(NULL == (ss.ss_sp = calloc(1, XCC_SIGNAL_CRASH_STACK_SIZE))) return XCC_ERRNO_NOMEM;
ss.ss_size = XCC_SIGNAL_CRASH_STACK_SIZE;
ss.ss_flags = 0;
if(0 != sigaltstack(&ss, NULL)) return XCC_ERRNO_SYS;
struct sigaction act;
memset(&act, 0, sizeof(act));
sigfillset(&act.sa_mask);
act.sa_sigaction = handler;//设置信号回调handler
act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
size_t i;
//通过sigaction注册上述信号组
for(i = 0; i < sizeof(xcc_signal_crash_info) / sizeof(xcc_signal_crash_info[0]); i++)
if(0 != sigaction(xcc_signal_crash_info[i].signum, &act, &(xcc_signal_crash_info[i].oldact)))
return XCC_ERRNO_SYS;
return 0;
}
注册的是指针函数:xc_crash_signal_handler,追过去看看:
static void xc_crash_signal_handler(int sig, siginfo_t *si, void *uc
{
...
//create and open log file 打开log文件
if((xc_crash_log_fd = xc_common_open_crash_log(xc_crash_log_pathname, sizeof(xc_crash_log_pathname), &xc_crash_log_from_placeholder)) < 0) goto end;
...
//spawn crash dumper process 起一个进程来处理dump
pid_t dumper_pid = xc_crash_fork(xc_crash_exec_dumper);
...
//JNI callback 完成之后jni到java的callback回调
xc_crash_callback();
...
}
进入xc_crash_exec_dumper指针函数,看看进程dump操作:
static int xc_crash_exec_dumper(void *arg)
{
…
//这里执行的是#define XCC_UTIL_XCRASH_DUMPER_FILENAME "libxcrash_dumper.so"
execl(xc_crash_dumper_pathname, XCC_UTIL_XCRASH_DUMPER_FILENAME, NULL);
return 100 + errno;
}
这个部分是做各种数据的dump。简单找下main方法:
xcd_core.c
int main(int argc, char** argv)
{
...
//read args from stdin
if(0 != xcd_core_read_args()) exit(1);
//open log file
if(0 > (xcd_core_log_fd = XCC_UTIL_TEMP_FAILURE_RETRY(open(xcd_core_log_pathname, O_WRONLY | O_CLOEXEC)))) exit(2);
//register signal handler for catching self-crashing
xcc_unwind_init(xcd_core_spot.api_level);
xcc_signal_crash_register(xcd_core_signal_handler);
//create process object
if(0 != xcd_process_create())) exit(3);
//suspend all threads in the process
xcd_process_suspend_threads(xcd_core_proc);
//load process info
if(0 != xcd_process_load_info(xcd_core_proc)) exit(4);
//record system info
if(0 != xcd_sys_record(...)) exit(5);
//record process info
if(0 != xcd_process_record(...)) exit(6);
//resume all threads in the process
xcd_process_resume_threads(xcd_core_proc);
...
}
不细看了,整个过程先是挂起crash进程的所以线程,然后收集相关log,最后resume所有线程。
xc_trace_init部分不分析了,与xc_jni_init分析方法一致。这里也就简单分析了个大脉络。
Native崩溃处理步骤总结:
注册信号处理函数(signal handler)。
崩溃发生时创建子进程收集信息(避免在崩溃进程调用函数的系统限制)。
suspend崩溃进程中所有的线程,暂停logcat输出,收集logcat。
收集backtrace等信息。
收集内存数据。
完成后恢复线程。
6
捕获ANR同样在Xcrash init时初始化
Crash.java
public static synchronized int init(Context ctx, InitParameters params) {
//init ANR handler (API level < 21)
if (params.enableAnrHandler && Build.VERSION.SDK_INT < 21) {
AnrHandler.getInstance().initialize(...);
}
}
这里有个限制,是sdk <21的版本才抓取。
AnrHandler.java
void initialize(Context ctx, int pid, String processName, String appId, String appVersion, String logDir,
boolean checkProcessState, int logcatSystemLines, int logcatEventsLines, int logcatMainLines,
boolean dumpFds, boolean dumpNetworkInfo, ICrashCallback callback) {
//check API level
if (Build.VERSION.SDK_INT >= 21) {
return;
}
...
//FileObserver是用来监控文件系统,这里监听/data/anr/trace.txt
fileObserver = new FileObserver("/data/anr/", CLOSE_WRITE) {
public void onEvent(int event, String path) {
try {
if (path != null) {
String filepath = "/data/anr/" + path;
if (filepath.contains("trace")) {
//监听回调,处理anr
handleAnr(filepath);
}
}
} catch (Exception e) {
XCrash.getLogger().e(Util.TAG, "AnrHandler fileObserver onEvent failed", e);
}
}
};
try {
//启动监听
fileObserver.startWatching();
} catch (Exception e) {
fileObserver = null;
XCrash.getLogger().e(Util.TAG, "AnrHandler fileObserver startWatching failed", e);
}
}
高版本系统已经没有读取/data/anr/的权限了,因此FileObserver监听/data/anr/的方案只能支持<21的版本,而目前xcrash对>21的版本无法获取anr日志。
然后看看handleAnr收集了哪些数据:
private void handleAnr(String filepath) {
Date anrTime = new Date();
//check ANR time interval
if (anrTime.getTime() - lastTime < anrTimeoutMs) {
return;
}
//check process error state
if (this.checkProcessState) {
if (!Util.checkProcessAnrState(this.ctx, anrTimeoutMs)) {
return;
}
}
//create log file
logFile = FileManager.getInstance().createLogFile(logPath);
//write info to log file
//write emergency info
raf.write(emergency.getBytes("UTF-8"));
//write logcat
raf.write(Util.getLogcat(logcatMainLines, logcatSystemLines, logcatEventsLines).getBytes("UTF-8"));
//write fds
raf.write(Util.getFds().getBytes("UTF-8"));
//write network info
raf.write(Util.getNetworkInfo().getBytes("UTF-8"));
//write memory info
raf.write(Util.getMemoryInfo().getBytes("UTF-8"));
//callback
if (callback != null) {
try {
callback.onCrash(logFile == null ? null : logFile.getAbsolutePath(), emergency);
} catch (Exception ignored) {
}
}
}
这里重点关注checkProcessAnrState,它是AMS对外暴露的api,从AMS的mLruProcesses中过滤出crash和anr异常的进程,返回对应的错误信息。补充cause reason部分,也就是ANR in。
static boolean checkProcessAnrState(Context ctx, long timeoutMs) {
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) return false;
int pid = android.os.Process.myPid();
long poll = timeoutMs / 500;
for (int i = 0; i < poll; i++) {
List<ActivityManager.ProcessErrorStateInfo> processErrorList = am.getProcessesInErrorState();
if (processErrorList != null) {
for (ActivityManager.ProcessErrorStateInfo errorStateInfo : processErrorList) {
if (errorStateInfo.pid == pid && errorStateInfo.condition == ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING) {
return true;
}
}
}
try {
Thread.sleep(500);
} catch (Exception ignored) {
}
}
return false;
}
那么>21版本的anr如何抓取?//init native crash handler / ANR handler (API level >= 21) int r = Errno.OK; if (params.enableNativeCrashHandler || (params.enableAnrHandler && Build.VERSION.SDK_INT >= 21)) { r = NativeHandler.getInstance().initialize(...); } 是通过nativeHandler来抓的。也就是前面提到的。
//trace init 捕获anr日志
r_trace = xc_trace_init(...);
它是native 注册 SIGNAL_QUIT 信号,ANR发生时接收回调去收集ANR信息。
int xc_trace_init(...)
{
int r;
pthread_t thd;
//capture SIGQUIT only for ART
if(xc_common_api_level < 21) return 0;
...
//init for JNI callback
xc_trace_init_callback(env);
//create event FD
if(0 > (xc_trace_notifier = eventfd(0, EFD_CLOEXEC))) return XCC_ERRNO_SYS;
//register signal handler
if(0 != (r = xcc_signal_trace_register(xc_trace_handler))) goto err2;
//create thread for dump trace
if(0 != (r = pthread_create(&thd, NULL, xc_trace_dumper, NULL))) goto err1;
...
return r;
}
这里xc_trace_notifier是一个eventfd ,在handler接收信号回调时被写。
static void xc_trace_handler(int sig, siginfo_t *si, void *uc)
{
uint64_t data;
(void)sig;
(void)si;
(void)uc;
if(xc_trace_notifier >= 0)
{
data = 1;
XCC_UTIL_TEMP_FAILURE_RETRY(write(xc_trace_notifier, &data, sizeof(data)));
}
}
然后xc_trace_dumper线程会解除阻塞状态开始执行dump任务。
static void *xc_trace_dumper(void *arg)
{
JNIEnv *env = NULL;
uint64_t data;
uint64_t trace_time;
int fd;
struct timeval tv;
char pathname[1024];
jstring j_pathname;
(void)arg;
pthread_detach(pthread_self());
JavaVMAttachArgs attach_args = {
.version = XC_JNI_VERSION,
.name = "xcrash_trace_dp",
.group = NULL
};
if(JNI_OK != (*xc_common_vm)->AttachCurrentThread(xc_common_vm, &env, &attach_args)) goto exit;
while(1)
{
//block here, waiting for sigquit
XCC_UTIL_TEMP_FAILURE_RETRY(read(xc_trace_notifier, &data, sizeof(data)));
//check if process already crashed
if(xc_common_native_crashed || xc_common_java_crashed) break;
//trace time
if(0 != gettimeofday(&tv, NULL)) break;
trace_time = (uint64_t)(tv.tv_sec) * 1000 * 1000 + (uint64_t)tv.tv_usec;
//Keep only one current trace.
if(0 != xc_trace_logs_clean()) continue;
//create and open log file
if((fd = xc_common_open_trace_log(pathname, sizeof(pathname), trace_time)) < 0) continue;
//write header info
if(0 != xc_trace_write_header(fd, trace_time)) goto end;
//write trace info from ART runtime
if(0 != xcc_util_write_format(fd, XCC_UTIL_THREAD_SEP"Cmd line: %s\\n", xc_common_process_name)) goto end;
if(0 != xcc_util_write_str(fd, "Mode: ART DumpForSigQuit\\n")) goto end;
if(0 != xc_trace_load_symbols())
{
if(0 != xcc_util_write_str(fd, "Failed to load symbols.\\n")) goto end;
goto skip;
}
if(0 != xc_trace_check_address_valid())
{
if(0 != xcc_util_write_str(fd, "Failed to check runtime address.\\n")) goto end;
goto skip;
}
if(dup2(fd, STDERR_FILENO) < 0)
{
if(0 != xcc_util_write_str(fd, "Failed to duplicate FD.\\n")) goto end;
goto skip;
}
xc_trace_dump_status = XC_TRACE_DUMP_ON_GOING;
if(sigsetjmp(jmpenv, 1) == 0)
{
if(xc_trace_is_lollipop)
xc_trace_libart_dbg_suspend();
xc_trace_libart_runtime_dump(*xc_trace_libart_runtime_instance, xc_trace_libcpp_cerr);
if(xc_trace_is_lollipop)
xc_trace_libart_dbg_resume();
}
else
{
fflush(NULL);
XCD_LOG_WARN("longjmp to skip dumping trace\\n");
}
dup2(xc_common_fd_null, STDERR_FILENO);
skip:
if(0 != xcc_util_write_str(fd, "\\n"XCC_UTIL_THREAD_END"\\n")) goto end;
//write other info
if(0 != xcc_util_record_logcat(fd, xc_common_process_id, xc_common_api_level, xc_trace_logcat_system_lines, xc_trace_logcat_events_lines, xc_trace_logcat_main_lines)) goto end;
if(xc_trace_dump_fds)
if(0 != xcc_util_record_fds(fd, xc_common_process_id)) goto end;
if(xc_trace_dump_network_info)
if(0 != xcc_util_record_network_info(fd, xc_common_process_id, xc_common_api_level)) goto end;
if(0 != xcc_meminfo_record(fd, xc_common_process_id)) goto end;
end:
//close log file
xc_common_close_trace_log(fd);
//rethrow SIGQUIT to ART Signal Catcher
if(xc_trace_rethrow && (XC_TRACE_DUMP_ART_CRASH != xc_trace_dump_status)) xc_trace_send_sigquit();
xc_trace_dump_status = XC_TRACE_DUMP_END;
//JNI callback
//Do we need to implement an emergency buffer for disk exhausted?
if(NULL == xc_trace_cb_method) continue;
if(NULL == (j_pathname = (*env)->NewStringUTF(env, pathname))) continue;
(*env)->CallStaticVoidMethod(env, xc_common_cb_class, xc_trace_cb_method, j_pathname, NULL);
XC_JNI_IGNORE_PENDING_EXCEPTION();
(*env)->DeleteLocalRef(env, j_pathname);
}
(*xc_common_vm)->DetachCurrentThread(xc_common_vm);
exit:
xc_trace_notifier = -1;
close(xc_trace_notifier);
return NULL;
}
PS:如果觉得我的分享不错,欢迎大家随手点赞、转发、在看。
PS:欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,欢迎转发分享给更多人。
以上是关于将异常一网打尽,爱奇艺开源xCrash是如何做的?的主要内容,如果未能解决你的问题,请参考以下文章