Android

Android平台Native奔溃捕获机制及实现

2021-08-21  本文已影响0人  Peakmain

前言

native异常捕获其实一直是个难点,也是一个大头,在现在已有的方案呢,有的代码量太大,有的存在兼容性问题等。腾讯bugly文章其实写的已经很明白了,一些东西知识我就拿过来用了,大家主要看代码。

信号机制

信号机制
函数运行在用户态,当遇到系统调用、中断或是异常的情况时,程序会进入内核态。信号涉及到了这两种状态之间的转换

image.png

常见信号类型

image.png
所以我们可以列出所有异常信号量
// 异常信号量
const int exceptionSignals[] = {SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, SIGTRAP};
const int exceptionSignalsNumber = sizeof(exceptionSignals)/ sizeof(exceptionSignals[0]);
//旧信号量 NSIG数量是65
static struct sigaction oldHandlers[NSIG];

捕捉信号量

 int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact));
void signalPass(int code, siginfo_t *si, void *sc) {
    LOGE("监听到了native异常");
    // 这里要考虑非信号方式防止死锁
    signal(code, SIG_DFL);
    signal(SIGALRM, SIG_DFL);
    (void) alarm(8);
    // 解析栈信息,回调给 java 层,上报到后台或者保存本地文件
    notifyCaughtSignal(code, si, sc);
    // 给系统原来默认的处理,否则就会进入死循环
    oldHandlers[code].sa_sigaction(code, si, sc);
}

/**
 * 安装信号捕获到native crash
 */
bool installSignalHandlers() {
    //保存原来的信号处理
    for (int i = 0; i < exceptionSignalsNumber; i++) {
        // signum:代表信号编码,可以是除SIGKILL及SIGSTOP外的任何一个特定有效的信号,如果为这两个信号定义自己的处理函数,将导致信号安装错误。
        // act:指向结构体sigaction的一个实例的指针,该实例指定了对特定信号的处理,如果设置为空,进程会执行默认处理。
        // oldact:和参数act类似,只不过保存的是原来对相应信号的处理,也可设置为NULL。
        // int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact));
        if (sigaction(exceptionSignals[i], NULL, &oldHandlers[exceptionSignals[i]]) == -1) {
            return false;
        }
    }
    struct sigaction sa{};
    memset(&sa, 0, sizeof(sa));
    //不同堆栈处理并且可将参数传递下去
    sa.sa_flags = SA_ONSTACK | SA_SIGINFO;
    // 指定信号处理的回调函数
    sa.sa_sigaction = signalPass;
    //处理当前信号量的时候不考虑其他的
    for (int i = 0; i < exceptionSignalsNumber; ++i) {
        //阻塞其他信号的
        sigaddset(&sa.sa_mask, exceptionSignals[i]);
    }
    for (int i = 0; i < exceptionSignalsNumber; ++i) {
        //处理自己的信号,如果成功返回0,失败返回-1
        if (sigaction(exceptionSignals[i], &sa, NULL) == -1) {
            // 可以输出一个警告
        }
    }
    return true;
}

signalPass是我们自己指定的信号量去处理的回调函数。在这里我们需要注意防止信号死循环的状态或者死锁

  signal(code, SIG_DFL);
    signal(SIGALRM, SIG_DFL);
    (void) alarm(8);

设置额外的栈空间

int sigaltstack(const stack_t* __new_signal_stack, stack_t* __old_signal_stack);
void installAlternateStack() {
    stack_t newStack;
    stack_t oldStack;
    memset(&newStack, 0, sizeof(newStack));
    memset(&oldStack, 0, sizeof(oldStack));
    static const unsigned sigaltstackSize = std::max(16384, SIGSTKSZ);
    if (sigaltstack(NULL, &oldStack) == -1
        || !oldStack.ss_sp
        || oldStack.ss_size < sigaltstackSize) {
        newStack.ss_sp = calloc(1, sigaltstackSize);
        newStack.ss_size = sigaltstackSize;
        if (sigaltstack(&newStack, NULL) == -1) {
            free(newStack.ss_sp);
        }
    }
}

分析堆栈

  //获取全局的jvm
    JavaVM *javaVm;
    env->GetJavaVM(&javaVm);
    //生成全局对象
    callback = env->NewGlobalRef(callback);
    jclass nativeCrashMonitorClass = env->GetObjectClass(nativeCrashMonitor);
    nativeCrashMonitorClass = (jclass) env->NewGlobalRef(nativeCrashMonitorClass);
    auto *jniBridge = new JNIBridge(javaVm, callback, nativeCrashMonitorClass);
    pthread_t pthread;
    //创建一个线程
    initCondition();
    //ret=0代表创建成功
    int ret = pthread_create(&pthread, NULL, threadCrashMonitor, jniBridge);
    if (ret < 0) {
        LOGE("%s", "pthread_create error");
    }
//锁的条件变量
pthread_cond_t signalCond;
pthread_mutex_t signalLock;
pthread_cond_t exceptionCond;
pthread_mutex_t exceptionLock;

void initCondition() {
    handlerContext = (native_handler_context *) malloc(sizeof(native_handler_context_struct));
    pthread_mutex_init(&signalLock, NULL);
    pthread_cond_init(&signalCond, NULL);
    pthread_mutex_init(&exceptionLock, NULL);
    pthread_cond_init(&exceptionCond, NULL);
}
void *threadCrashMonitor(void *argv) {
    JNIBridge *jniBridge = static_cast<JNIBridge *>(argv);

    while (true) {
        //等待信号处理函数唤醒
        waitForSignal();
        //唤醒之后,分析native堆栈
        analysisNativeException();

        //抛给java
        jniBridge->throwException2Java(handlerContext);
    }
}
//等待信号
void waitForSignal() {
    pthread_mutex_lock(&signalLock);
    LOGE("waitForSignal start.");
    pthread_cond_wait(&signalCond, &signalLock);
    LOGE("waitForSignal finish.");
    pthread_mutex_unlock(&signalLock);

}
void notifyCaughtSignal(int code, siginfo_t *si, void *sc) {
    copyInfo2Context(code, si, sc);
    pthread_mutex_lock(&signalLock);
    pthread_cond_signal(&signalCond);
    pthread_mutex_unlock(&signalLock);
}
//保存唤醒后的信息
void copyInfo2Context(int code, siginfo_t *si, void *sc) {
    handlerContext->code = code;
    handlerContext->si = si;
    handlerContext->sc = sc;
    handlerContext->pid = getpid();
    handlerContext->tid = gettid();
    handlerContext->processName = getProcessName(handlerContext->pid);
    if (handlerContext->pid == handlerContext->tid) {
        handlerContext->threadName = "main";
    } else {
        handlerContext->threadName = getThreadName(handlerContext->tid);
    }
    handlerContext->frame_size = 0;
    //捕获c/c++的堆栈信息
    _Unwind_Backtrace(unwind_callback, handlerContext);
}
//分析native的异常
void analysisNativeException() {
    const char *posixDesc = desc_sig(handlerContext->si->si_signo, handlerContext->si->si_code);
    LOGD("posixDesc -> %s", posixDesc);
    LOGD("signal -> %d", handlerContext->si->si_signo);
    LOGD("address -> %p", handlerContext->si->si_addr);
    LOGD("processName -> %s", handlerContext->processName);
    LOGD("threadName -> %s", handlerContext->threadName);
    LOGD("pid -> %d", handlerContext->pid);
    LOGD("tid -> %d", handlerContext->tid);
}
_Unwind_Backtrace(unwind_callback, handlerContext);
_Unwind_Reason_Code unwind_callback(struct _Unwind_Context *context, void *arg) {
    native_handler_context *const s = static_cast<native_handler_context *const>(arg);
    //pc是每个堆栈的栈顶
    const uintptr_t pc = _Unwind_GetIP(context);
    if (pc != 0x0) {
        // 把 pc 值保存到 native_handler_context
        s->frames[s->frame_size++] = pc;
    }
    if (s->frame_size == BACKTRACE_FRAMES_MAX) {
        return _URC_END_OF_STACK;
    } else {
        return _URC_NO_REASON;
    }
}

pc值是程序加载到内存中的绝对地址

将native信息抛给Java

我们需要拿到奔溃代码相对于共享库的相对偏移地址。这时候通过dladdr()可以获得共享库加载到内存的起始地址,和pc值相减就可以获得相对偏移地址,并且可以获得共享库的名字。

Dl_info info;  
if (dladdr(addr, &info) != 0 && info.dli_fname != NULL) {  
  void * const nearest = info.dli_saddr;  
  //相对偏移地址
  const uintptr_t addr_relative =  
    ((uintptr_t) addr - (uintptr_t) info.dli_fbase);  
}

完整代码

void JNIBridge::throwException2Java(native_handler_context *handlerContext) {
    LOGE("throwException2Java");
    //子线程获取env
    JNIEnv *env = NULL;
    if (this->javaVm->AttachCurrentThread(&env, NULL) != JNI_OK) {
        LOGE("AttachCurrentThread failed");
    }
    const char *sig = "(Ljava/lang/String;)Ljava/lang/String;";
    jmethodID getStackInfoByThreadNameMid = env->GetStaticMethodID(this->nativeCrashMonitorClass,
                                                                   "getStackInfoByThreadName", sig);
    //private stifatic String getStackInfoByThreadName(String threadName)
    jstring jThreadName = env->NewStringUTF(handlerContext->threadName);
    jobject javaStackInfo = env->CallStaticObjectMethod(this->nativeCrashMonitorClass,
                                                        getStackInfoByThreadNameMid, jThreadName);
    //java的String->native的string
    const char *javaExceptionStackInfo = env->GetStringUTFChars((jstring) javaStackInfo, JNI_FALSE);
    //获取c++堆栈信息
    int frame_size = handlerContext->frame_size;
    string result;
    for (int index = 0; index < frame_size; ++index) {
        uintptr_t pc = handlerContext->frames[index];
        //获取到加载的内存的起始地址
        Dl_info stack_info;
        void *const addr = (void *) pc;
        if (dladdr(addr, &stack_info) != 0 && stack_info.dli_fname != NULL) {

            if (stack_info.dli_fbase == 0) {
                // No valid map associated with this frame.
                result += "  <unknown>";
            } else if (stack_info.dli_fname) {
                std::string so_name = std::string(stack_info.dli_fname);
                result += "  " + so_name;
            } else {
                result += android::base::StringPrintf("  <anonymous:%" PRIx64 ">",
                                                      (uint64_t) stack_info.dli_fbase);
            }
            if (stack_info.dli_sname) {
                char *demangled_name = abi::__cxa_demangle(stack_info.dli_sname, nullptr, nullptr,
                                                           nullptr);
                if (demangled_name == nullptr) {
                    result += " (";
                    result += stack_info.dli_sname;
                } else {
                    result += " (";
                    result += demangled_name;
                    free(demangled_name);
                }
                if (stack_info.dli_saddr != 0) {
                    uintptr_t offset = pc - (uintptr_t) stack_info.dli_saddr;
                    result += android::base::StringPrintf("+%" PRId64, (uint64_t) offset);
                }
                result += ')';
            }
            result += '\n';
        }
    }
    //回掉Java的接口
    jclass crashClass = env->GetObjectClass(this->callbackObj);
    jmethodID crashMethod = env->GetMethodID(crashClass, "onCrash",
                                             "(Ljava/lang/String;Ljava/lang/Error;)V");
    jclass jErrorClass = env->FindClass("java/lang/Error");
    jmethodID jErrorInitMethod = env->GetMethodID(jErrorClass, "<init>", "(Ljava/lang/String;)V");
    result = result += javaExceptionStackInfo;
    jstring errorMessage = env->NewStringUTF(result.c_str());
    //错误信息给Error
    jobject errorObject = env->NewObject(jErrorClass, jErrorInitMethod, errorMessage);
    env->CallVoidMethod(this->callbackObj, crashMethod, jThreadName, errorObject);
    if (this->javaVm->DetachCurrentThread() != JNI_OK) {
        LOGE("DetachCurrentThread failed!");
    }
}

结果展示

image.png

java回调接口

public interface CrashListener {
    void onCrash(String threadName, Error error);
}

使用方法

CrashUtils.init(CrashListener { threadName, error ->
            LogUtils.e("threadName:$threadName,error info : $error")
        })
上一篇下一篇

猜你喜欢

热点阅读