How to call the stack trace and androidstack for Android programs?
You can find out the call stack trace of a program to know who called this interface, and quickly learn the call process of the program, which is very practical. However, it should be noted that it cannot be used in the official code but can only be used for debugging. This is a very resource-consuming situation and causes log flooding.
The following describes how to print the program call trace in the Android Java/C ++/C program. If you want to use the trace in other environments, you must port the corkscrew library in the C ++/C program.
Java
It is very simple to createThrowable
To obtain the current stack trace. The following example shows the calling method.foobar()
Function trace:
1 private void foobar() {2 Throwable t = new Throwable();3 Log.d(TAG, "stack trace is ", t);4 }
C ++
It is also relatively simple to use.utils/Callstack
Class. The header file is located inframeworks/native/include/utils/CallStack.h
Generally, Android. mk can be used directly without modification. The following example shows the calling method.Foo::bar()
Function trace:
1 #include <utils/CallStack.h> 2 3 void Foo::bar() {4 // CallStack::CallStack(const char* logtag, int32_t ignoreDepth, int32_t maxDepth)5 CallStack *t = new CallStack("Trace", 1, 30);6 delete t;7 }
C
It is a little troublesome and needs to be called directlycorkscrew/backtrace
. In factutils/Callstack
Also usedcorkscrew/backtrace
, But the encapsulation is easier to use. ReferCallStack.cpp
Code. The following example shows the calling method.foobar()
Function trace:
NOTE: C ++ Code cannot be called directly, unless the corresponding C wrapper is added to the C ++ class or is dynamically loaded through dlsym.
1 #include <corkscrew/backtrace.h> 2 3 void dumpStackTrace(const char* logtag, int32_t ignoreDepth, int32_t maxDepth) const { 4 static const int MAX_DEPTH = 31; 5 static const int MAX_BACKTRACE_LINE_LENGTH = 800; 6 7 if (maxDepth > MAX_DEPTH) { 8 maxDepth = MAX_DEPTH; 9 }10 backtrace_frame_t mStack[MAX_DEPTH];11 ssize_t count = unwind_backtrace(mStack, ignoreDepth + 1, maxDepth);12 if (count <= 0) {13 LOGE("Can not get stack trace");14 return;15 }16 17 backtrace_symbol_t symbols[count];18 19 get_backtrace_symbols(mStack, count, symbols);20 for (size_t i = 0; i < count; i++) {21 char line[MAX_BACKTRACE_LINE_LENGTH];22 format_backtrace_line(i, &mStack[i], &symbols[i],23 line, MAX_BACKTRACE_LINE_LENGTH);24 ALOG(LOG_DEBUG, logtag, "%s%s",25 "",26 line);27 }28 free_backtrace_symbols(symbols, count);29 }30 31 void foobar() {32 dumpStackTrace("Trace", 1, 30);33 }
The header file is located insystem/core/include/corkscrew/backtrace.h
In Android. mk, you also need to add:
1 LOCAL_SHARED_LIBRARIES += libcorkscrew