将异常一网打尽,爱奇艺开源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架构

283c86b5fef568c64391b164a8ccb4c6.png


3

Xcrash类图

df2d95c96509529d649bbb7d076e5ad5.png

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奔溃

0ba501d476ad8dc347c5902f7a4cbd4c.png

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;
}

e96f9f774fc4f9e04dc5a096bc2769da.png

这个部分是做各种数据的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

3de88c3a76a1152b05b44a1d72027cf6.png

同样在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:欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,欢迎转发分享给更多人。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Conda和venv是两种常用的Python虚拟环境管理工具。Conda是一个开源的跨平台包管理器,可以创建和管理不同版本的Python环境,同时可以安装和管理包。venv是Python自带的一个库,只能在同一个Python版本中创建多个环境。 如果你想使用Conda创建新的环境并安装包,你可以使用以下命令: conda create --name <env_name> <package_names> 例如,使用以下命令创建一个名为ZiDuo的环境,并安装python=3.7.0、requests和PyQt5包: conda create --name ZiDuo python=3.7.0 requests PyQt5 如果你想激活一个Conda环境,在Windows下,你可以使用以下命令: activate <env_name> 例如,激活名为ZiDuo的环境: activate ZiDuo 如果你想退出一个Conda环境,在Windows下,你可以使用以下命令: deactivate 如果你想显示已创建的Conda环境,你可以使用以下命令: conda info --envs 或者 conda env list 如果你想复制一个Conda环境,你可以使用以下命令: conda create --name <new_env_name> --clone <copied_env_name> 例如,复制一个名为ZiDuo的环境到ZiDuo_2: conda create --name ZiDuo_2 --clone ZiDuo 如果你想删除一个Conda环境,你可以使用以下命令: conda remove --name <env_name> --all 例如,删除名为ZiDuo的环境: conda remove --name ZiDuo --all venv是Python自带的库,可以用来创建虚拟环境。但是venv只能在同一个Python版本中创建多个环境。 希望以上内容能够帮助你理解conda和venv在打包和虚拟环境管理方面的作用。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Python虚拟环境(pipenv、venv、conda一网打尽)](https://blog.csdn.net/tangyi2008/article/details/124642238)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [Python 虚拟环境 —— 基于conda、venv的虚拟环境的使用指南](https://blog.csdn.net/weixin_43733831/article/details/125325959)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值