在平时的开发调试的时候,经常碰到需要打印JAVA、Native C++、kernel的代码调用关系。这里做一下记录
Jave堆栈打印
使用android.util.Log类进行打印
/**
* Send a {@link #DEBUG} log message and log the exception.
* @param tag Used to identify the source of a log message. It usually identifies
* the class or activity where the log call occurs.
* @param msg The message you would like logged.
* @param tr An exception to log
*/
public static int d(@Nullable String tag, @Nullable String msg, @Nullable Throwable tr) {
return printlns(LOG_ID_MAIN, DEBUG, tag, msg, tr);
}
eg:
android.util.Log.d("test","xxx",new Exception());
kernel 堆栈打印
内核中打印堆栈比较简单,使用下面的函数即可
dump_stack();
Native 堆栈打印
借助libutilscallstack库进行打印。源码路径system\core\libutils\CallStack.cpp
//system\core\libutils\Android.bp
cc_library {
name: "libutilscallstack",
defaults: ["libutils_defaults"],
// TODO(b/153609531): remove when no longer needed.
native_bridge_supported: true,
srcs: [
"CallStack.cpp",
],
//system\core\libutils\CallStack.cpp
CallStack::CallStack(const char* logtag, int32_t ignoreDepth) {
this->update(ignoreDepth+1);
this->log(logtag);
}
可以看出CallStack.cpp编译成libutilscallstack库。使用之前,一定要先将这个库包含进来
(1)包含libutilscallstack库
shared_libs:[
"libutilscallstack",
]
(2)包含头文件
#include<utils/CallStack.h>
(3)使用
CallStack stack("xxx");
注意,低版本的Andorid,CallStack.cpp是编译成libutils
cc_library {
name: "libutils",
vendor_available: true,
vndk: {
enabled: true,
support_system_process: true,
},
host_supported: true,
srcs: [
"CallStack.cpp",
//......
参考链接:Android 打印native堆栈