简体   繁体   中英

Print C stack trace on Android 5/Lollipop

I'm trying to debug JNI code written in C running on Android 5. When one of my functions is called, I want to write a stack trace to the adb log so I can see where the function was called from.

The first resources I found indicated I needed to use libcorkscrew, and included complete examples of how to use the library. Unfortunately it seems libcorkscrew is gone from Android 5, and now libunwind is supposed to be used. For my project, there are several problems:

  1. Instructions for getting libunwind into the project are sparse and/or misleading - some resources say to download the project from github and build it (with directions that do not work), others indicate the library is already part of Android 5.

  2. All of the examples are written in C++, and it seems that libunwind only has C++ bindings for the functions within it. Since my code is C, not C++, and writing to a log function rather than through the C++ stdlib, this isn't usable.

Among others, I looked at these pages:

  1. Native Stack Traces on Android Lollipop with libunwind

  2. There's no "libcorkscrew" in Android 5.0...

  3. Android NDK: getting the backtrace

Is there a way to get a stack trace in C code on Android 5 without crashing the program?

Can you use backtrace_symbos_fd at Android? If you can, you could use this one:

void *array[100];
size_t size;

size = backtrace (array, 100);
backtrace_symbols_fd (array, size, STDOUT_FILENO);

Instructions for getting libunwind into the project are sparse and/or misleading

Compiled libunwind is included into modern Android NDKs, such as NDK r16b, at sources/cxx-stl/llvm-libc++/libs/armeabi-v7a/libunwind.a . You will have to provide this file to the linker. You will also need to download matching headers, namely libunwind.h and __libunwind_config.h . For NDK r16b, these headers can be fetched here: https://android.googlesource.com/platform/external/libunwind_llvm/+/ndk-r16/include/ .

it seems that libunwind only has C++ bindings

No, it's not so. Most of libunwind bindings are C bindings.

Here is a sample Android command-line app in pure C that uses libunwind:

https://github.com/alexeikh/android-ndk-backtrace-test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM