Skip to content

Commit

Permalink
fix(ndk): Switch unwinders based on required async signal-safety
Browse files Browse the repository at this point in the history
When capturing a stacktrace from a signal handler or C++ terminate 
handler different unwinders deadlock on different architectures and/or
Android API levels. This change uses different unwinders based on
whether async signal safety is required or not, by supported API levels.

It introduces libunwindstack as the signal-safe unwinder for API 15+ on
ARM64 and x86/x64 devices. For notify()/C++ exceptions, use libunwind,
nongnu libunwind, or libcorkscrew depending on the API level.

* libcorkscrew hangs when unwinding from a C++ exception on ARM 32-bit.
* libunwind hangs on ARM64 from a signal handler
* nongnu libunwind hangs on ARM32 from a signal handler if raise() is
  called directly
  • Loading branch information
kattrali committed Jan 21, 2019
1 parent bb1a2a6 commit 6ede23a
Show file tree
Hide file tree
Showing 14 changed files with 206 additions and 14 deletions.
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "ndk/src/main/jni/external/libunwindstack"]
path = ndk/src/main/jni/external/libunwindstack
url = https://github.com/ivanarh/libunwindstack-ndk
6 changes: 6 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ installed to `~/.android-sdk`.

## Building the Library

Be sure to clone the repository submodules:

```shell
git submodule update --init --recursive
```

You can build new `.aar` files as follows:

```shell
Expand Down
59 changes: 59 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,62 @@ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

====

The libunwindstack module located in ndk/src/main/jni/external/libunwindstack
is licensed under the Apache Software License, Version 2.0.

http://www.apache.org/licenses/LICENSE-2.0

https://android.googlesource.com/platform/system/core.git

https://source.android.com/setup/start/licenses

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.

You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS
1 change: 1 addition & 0 deletions checkstyle.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ task("checkstyle", type: Checkstyle) {
configFile rootProject.file("config/checkstyle/checkstyle.xml")
source "src/"
include "**/*.java"
exclude "**/external/**/*.java"
classpath = files()
}
4 changes: 4 additions & 0 deletions ndk/src/main/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ add_library( # Specifies the name of the library.
jni/handlers/cpp_handler.cpp
jni/utils/crash_info.c
jni/utils/stack_unwinder.c
jni/utils/stack_unwinder_libunwindstack.cpp
jni/utils/stack_unwinder_libcorkscrew.c
jni/utils/stack_unwinder_libunwind.c
jni/utils/stack_unwinder_simple.c
Expand All @@ -26,6 +27,7 @@ include_directories(
jni/
jni/deps
jni/external/libunwind/include
jni/external/libunwindstack/include
)

target_include_directories(bugsnag-ndk PRIVATE ${BUGSNAG_DIR}/assets/include)
Expand All @@ -49,6 +51,8 @@ set_target_properties(bugsnag-ndk
COMPILE_OPTIONS
-Werror -Wall -pedantic)

add_subdirectory(jni/external/libunwindstack/cmake)
target_link_libraries(bugsnag-ndk unwindstack)
if(${ANDROID_ABI} STREQUAL "armeabi" OR ${ANDROID_ABI} STREQUAL "armeabi-v7a")
add_library(libunwind STATIC IMPORTED)
set_target_properties(libunwind PROPERTIES IMPORTED_LOCATION
Expand Down
4 changes: 3 additions & 1 deletion ndk/src/main/jni/bugsnag_ndk.c
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ JNIEXPORT void JNICALL Java_com_bugsnag_android_ndk_NativeBridge_install(
JNIEnv *env, jobject _this, jstring _report_path, jboolean auto_notify,
jint _api_level, jboolean is32bit) {
bsg_environment *bugsnag_env = calloc(1, sizeof(bsg_environment));
bugsnag_env->unwind_style = bsg_get_unwind_type((int)_api_level, (bool)is32bit);
bsg_set_unwind_types((int)_api_level, (bool)is32bit,
&bugsnag_env->signal_unwind_style,
&bugsnag_env->unwind_style);
bugsnag_env->report_header.big_endian =
htonl(47) == 47; // potentially too clever, see man 3 htonl
bugsnag_env->report_header.version = BUGSNAG_REPORT_VERSION;
Expand Down
7 changes: 7 additions & 0 deletions ndk/src/main/jni/bugsnag_ndk.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ extern "C" {
#endif

typedef struct {
/**
* Unwinding style used for signal-safe handling
*/
bsg_unwinder signal_unwind_style;
/**
* Preferred unwinding style
*/
bsg_unwinder unwind_style;
bsg_report_header report_header;
/**
Expand Down
1 change: 1 addition & 0 deletions ndk/src/main/jni/external/libunwindstack
Submodule libunwindstack added at 0717e9
2 changes: 1 addition & 1 deletion ndk/src/main/jni/handlers/signal_handler.c
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ void bsg_handle_signal(int signum, siginfo_t *info,
bsg_global_env->handling_crash = true;
bsg_populate_report_as(bsg_global_env);
bsg_global_env->next_report.exception.frame_count = bsg_unwind_stack(
bsg_global_env->unwind_style,
bsg_global_env->signal_unwind_style,
bsg_global_env->next_report.exception.stacktrace, info, user_context);

for (int i = 0; i < BSG_HANDLED_SIGNAL_COUNT; i++) {
Expand Down
39 changes: 30 additions & 9 deletions ndk/src/main/jni/utils/stack_unwinder.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "stack_unwinder.h"
#include "stack_unwinder_libcorkscrew.h"
#include "stack_unwinder_libunwind.h"
#include "stack_unwinder_libunwindstack.h"
#include "stack_unwinder_simple.h"
#include "string.h"
#include <asm/siginfo.h>
Expand All @@ -9,18 +10,35 @@
#include <ucontext.h>

#define BSG_LIBUNWIND_LEVEL 21
#define BSG_LIBUNWINDSTACK_LEVEL 15
#define BSG_LIBUNWIND_LEVEL_ARM32 16
#define BSG_LIBCORKSCREW_MIN_LEVEL 16
#define BSG_LIBCORKSCREW_MAX_LEVEL 19

bsg_unwinder bsg_get_unwind_type(int apiLevel, bool is32bit) {
if (apiLevel >= BSG_LIBUNWIND_LEVEL && bsg_configure_libunwind(is32bit)) {
return BSG_LIBUNWIND;
} else if (apiLevel <= BSG_LIBCORKSCREW_MAX_LEVEL &&
apiLevel >= BSG_LIBCORKSCREW_MIN_LEVEL &&
bsg_configure_libcorkscrew()) {
return BSG_LIBCORKSCREW;
void bsg_set_unwind_types(int apiLevel, bool is32bit, bsg_unwinder *signal_type,
bsg_unwinder *other_type) {
#if defined(__arm__)
if (apiLevel >= BSG_LIBUNWIND_LEVEL_ARM32 && is32bit &&
bsg_configure_libunwind(is32bit)) {
if (apiLevel >= BSG_LIBUNWIND_LEVEL) {
*signal_type = BSG_LIBUNWIND;
} else if (bsg_configure_libcorkscrew()) {
*signal_type = BSG_LIBCORKSCREW;
} else {
*signal_type = BSG_CUSTOM_UNWIND;
}
*other_type = BSG_LIBUNWIND;
return;
}
#endif
if (apiLevel >= BSG_LIBUNWINDSTACK_LEVEL) {
bsg_configure_libunwind(is32bit);
*signal_type = BSG_LIBUNWINDSTACK;
*other_type = BSG_LIBUNWIND;
} else {
*signal_type = BSG_CUSTOM_UNWIND;
*other_type = BSG_CUSTOM_UNWIND;
}
return BSG_CUSTOM_UNWIND;
}

void bsg_insert_fileinfo(ssize_t frame_count,
Expand All @@ -46,7 +64,10 @@ ssize_t bsg_unwind_stack(bsg_unwinder unwind_style,
bsg_stackframe stacktrace[BUGSNAG_FRAMES_MAX],
siginfo_t *info, void *user_context) {
ssize_t frame_count = 0;
if (unwind_style == BSG_LIBUNWIND) {
if (unwind_style == BSG_LIBUNWINDSTACK) {
frame_count =
bsg_unwind_stack_libunwindstack(stacktrace, info, user_context);
} else if (unwind_style == BSG_LIBUNWIND) {
frame_count = bsg_unwind_stack_libunwind(stacktrace, info, user_context);
} else if (unwind_style == BSG_LIBCORKSCREW) {
frame_count = bsg_unwind_stack_libcorkscrew(stacktrace, info, user_context);
Expand Down
10 changes: 7 additions & 3 deletions ndk/src/main/jni/utils/stack_unwinder.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,23 @@ extern "C" {

typedef enum {
BSG_LIBUNWIND,
BSG_LIBUNWINDSTACK,
BSG_LIBCORKSCREW,
BSG_CUSTOM_UNWIND,
} bsg_unwinder;


/**
* Based on the current environment, determine what unwinding library to use.
*
* Android API level 21+: libunwind
* Android API level 16-19: libcorkscrew
* Android API level 16-19: libunwind, unless in a signal handler. Then
* libcorkscrew.
* Everything else: custom unwinding logic
* @return the preferred unwind type
*/
bsg_unwinder bsg_get_unwind_type(int apiLevel, bool is32bit);
void bsg_set_unwind_types(int apiLevel, bool is32bit,
bsg_unwinder *signal_type,
bsg_unwinder *other_type);

/**
* Unwind the stack using the preferred tool/style. If info and a user
Expand Down
3 changes: 3 additions & 0 deletions ndk/src/main/jni/utils/stack_unwinder_libunwind.c
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ bsg_unwind_stack_libunwind(bsg_stackframe stacktrace[BUGSNAG_FRAMES_MAX],
return bsg_unwind_stack_libunwind_arm32(stacktrace, info, user_context);
}
#endif
if (bsg_global_libunwind_state == NULL) {
return 0;
}
bsg_global_libunwind_state->frame_count = 0;
// The return value of _Unwind_Backtrace sits on a throne of lies
_Unwind_Backtrace(bsg_libunwind_callback, bsg_global_libunwind_state);
Expand Down
68 changes: 68 additions & 0 deletions ndk/src/main/jni/utils/stack_unwinder_libunwindstack.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include "../utils/string.h"
#include "stack_unwinder_libunwindstack.h"
#include <stdlib.h>
#include <ucontext.h>
#include <unwindstack/Elf.h>
#include <unwindstack/MapInfo.h>
#include <unwindstack/Maps.h>
#include <unwindstack/Memory.h>
#include <unwindstack/Regs.h>

ssize_t
bsg_unwind_stack_libunwindstack(bsg_stackframe stacktrace[BUGSNAG_FRAMES_MAX],
siginfo_t *info, void *user_context) {
if (user_context == NULL) {
return 0; // only handle unwinding from signals
}

const std::unique_ptr<unwindstack::Regs> regs(
unwindstack::Regs::CreateFromUcontext(unwindstack::Regs::CurrentArch(),
user_context));

// if (user_context != NULL) {
// regs = unwindstack::Regs::CreateFromUcontext(
// unwindstack::Regs::CurrentArch(), user_context);
//} else {
// regs = unwindstack::Regs::CreateFromLocal();
//}

std::string unw_function_name;
unwindstack::LocalMaps maps;

if (!maps.Parse()) {
stacktrace[0].frame_address = regs->pc(); // only known frame
return 1;
}

const std::shared_ptr<unwindstack::Memory> memory(
new unwindstack::MemoryLocal);

int frame_count = 0;
for (int i = 0; i < BUGSNAG_FRAMES_MAX; i++) {
unwindstack::MapInfo *const map_info = maps.Find(regs->pc());
unwindstack::Elf *const elf = map_info->GetElf(memory, false);
if (!map_info || !elf) {
stacktrace[frame_count++].frame_address = regs->pc();
break;
}

// Getting value of program counter relative module where a function is
// located.
const uint64_t rel_pc = elf->GetRelPc(regs->pc(), map_info);
uint64_t adjusted_rel_pc = rel_pc;
if (frame_count != 0) {
// If it's not a first frame we need to rewind program counter value to
// previous instruction. For the first frame pc from ucontext points
// exactly to a failed instruction, for other frames rel_pc will contain
// return address after function call instruction.
adjusted_rel_pc -= regs->GetPcAdjustment(rel_pc, elf);
}
stacktrace[frame_count++].frame_address = regs->pc();
bool finished = false;
if (!elf->Step(rel_pc, adjusted_rel_pc, map_info->elf_offset, regs.get(),
memory.get(), &finished)) {
break;
}
}
return frame_count;
}
13 changes: 13 additions & 0 deletions ndk/src/main/jni/utils/stack_unwinder_libunwindstack.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#ifndef BUGSNAG_UTILS_STACK_UNWINDER_LIBUNWINDSTACK_H
#define BUGSNAG_UTILS_STACK_UNWINDER_LIBUNWINDSTACK_H

#include "../report.h"
#include <signal.h>

#ifdef __cplusplus
extern "C"
#endif
ssize_t
bsg_unwind_stack_libunwindstack(bsg_stackframe stacktrace[BUGSNAG_FRAMES_MAX],
siginfo_t *info, void *user_context);
#endif

0 comments on commit 6ede23a

Please sign in to comment.