├── .gitignore ├── .gitmodules ├── CMakeLists.txt ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── proguard-rules.pro └── src ├── androidTest └── java │ └── ru │ └── ivanarh │ └── jndcrash │ └── ExampleInstrumentedTest.java ├── main ├── AndroidManifest.xml ├── java │ └── ru │ │ └── ivanarh │ │ └── jndcrash │ │ ├── NDCrash.java │ │ ├── NDCrashError.java │ │ ├── NDCrashService.java │ │ ├── NDCrashUnwinder.java │ │ └── NDCrashUtils.java ├── jni │ └── jndcrash.c └── res │ └── values │ └── strings.xml └── test └── java └── ru └── ivanarh └── jndcrash └── ExampleUnitTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /.externalNativeBuild 3 | *.iml 4 | .gradle 5 | .idea 6 | local.properties 7 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libndcrash"] 2 | path = libndcrash 3 | url = https://github.com/ivanarh/ndcrash.git 4 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.4.1) 2 | project(jndcrash) 3 | 4 | # Setting default configuration parameters values. Everything is ON. 5 | set(ENABLE_INPROCESS ON) 6 | set(ENABLE_OUTOFPROCESS ON) 7 | set(ENABLE_OUTOFPROCESS_ALL_THREADS ON) 8 | set(ENABLE_LIBCORKSCREW ON) 9 | set(ENABLE_LIBUNWIND ON) 10 | set(ENABLE_LIBUNWINDSTACK ON) 11 | set(ENABLE_CXXABI ON) 12 | set(ENABLE_STACKSCAN ON) 13 | 14 | # Optional JNDCrash build config. 15 | include(${CMAKE_SOURCE_DIR}/../jndcrash.cmake OPTIONAL) 16 | 17 | # Adding NDCrash submodule subdirectory 18 | add_subdirectory(libndcrash) 19 | 20 | # Setting up definitions. The same as used for NDCrash. 21 | if (${ENABLE_INPROCESS}) 22 | add_definitions(-DENABLE_INPROCESS) 23 | endif() 24 | if (${ENABLE_OUTOFPROCESS}) 25 | add_definitions(-DENABLE_OUTOFPROCESS) 26 | endif() 27 | 28 | # NDCrash submodule include path. 29 | include_directories(${CMAKE_SOURCE_DIR}/libndcrash/include) 30 | 31 | # JNDCrash source code. 32 | file(GLOB JNDCRASH_SOURCES ${CMAKE_SOURCE_DIR}/src/main/jni/*.c) 33 | 34 | # Adding dynamic library and linking it with log and NDCrash. 35 | add_library(jndcrash SHARED ${JNDCRASH_SOURCES}) 36 | find_library(LOG_LIB log) 37 | target_link_libraries(jndcrash ndcrash ${LOG_LIB}) 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 Ivan Ponomarev 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JNDCrash # 2 | 3 | **JNDCrash** is a Java wrapper over [NDCrash C library](https://github.com/ivanarh/ndcrash) which significantly simplifies its usage. It includes **NDCrash** library as a submodule. See key concepts here https://github.com/ivanarh/ndcrash documentation. Minimum Android version is 4.0.3. 4 | 5 | ## Integration ## 6 | 7 | ### Quick integration ### 8 | 9 | **JNDCrash** is currently published to [bintray repository](https://bintray.com/ivanarh/ndcrash/jndcrash-libunwind) and accessible in jcenter. Currently only one version with *libunwind* unwinder is accessible, it means other unwinders are disabled during compilation and can't be used. You should initialize a library with `NDCrashUnwinder.libunwind` argument, otherwise it will return an error. This is done for optimization purposes, this unwinder is a good choice for majority of users and it's recommended to use. If you need another unwinder please go to "Advanced integration" and "Customization" sections. 10 | 11 | To add a library to a project please add this line to your application's build.gradle, `dependencies` section: 12 | 13 | ``` 14 | compile 'ru.ivanarh.ndcrash:jndcrash-libunwind:0.8' 15 | ``` 16 | 17 | Also make sure that `jcenter()` is included to `repositories` section (it's already done in default project template). Run "Sync" operation and verify that no error has occured. 18 | 19 | ### Advanced integration ### 20 | 21 | A more advanced way to include it to a project is to a project hierarchy. Please note that gradle version 3 is used. It's integrated to a project as a usual library, see [documentation](https://developer.android.com/studio/projects/android-library.html) For example integraion you can take a look at [ndcrashdemo application](https://github.com/ivanarh/ndcrashdemo). The following instructions assume that you use a default project template provided by Android Studio. A fresh version of Android NDK with clang toolchain should be installed. 22 | 23 | First you need to add **JNDCrash** to a project root. If you use **git** in your project it's a good idea integrate **JNDCrash** as a submodule. To do this please run a following console command in a project root: 24 | 25 | ``` 26 | git submodule add git@github.com:ivanarh/jndcrash.git jndcrash 27 | cd jndcrash 28 | git submodule update --init --recursive 29 | ``` 30 | 31 | If you don't use git please replace `git submodule add` command by `git clone` with the same arguments. Verify that no error has occured. After that please change `settings.gradle` file, replace a line: 32 | 33 | ``` 34 | include ':app' 35 | ``` 36 | 37 | to 38 | 39 | ``` 40 | include ':app', ':jndcrash' 41 | ``` 42 | 43 | After that please add this line to your application's build.gradle, `dependencies` section: 44 | 45 | ``` 46 | implementation project(':jndcrash') 47 | ``` 48 | 49 | Run "Sync" operation and verify that no error has occured. 50 | 51 | ## Usage ## 52 | 53 | All **JNDCrash** method are wrappers over corresponding **NDCrash** functions. 54 | 55 | ### In-process ### 56 | 57 | To initialize in-process signal handler you need to call `NDCrash.initializeInProcess` method. A good place to do this is `onCreate` method of Application subclass. Example with *libunwind* unwinder and crash report path inside getAbsolutePath() result: 58 | 59 | ``` 60 | @Override 61 | public void onCreate() { 62 | super.onCreate(); 63 | ... 64 | final String reportPath = getFilesDir().getAbsolutePath() + "/crash.txt"; // Example. 65 | final NDCrashError error = NDCrash.initializeInProcess(reportPath, NDCrashUnwinder.libunwind); 66 | if (error == NDCrashError.ok) { 67 | // Initialization is successful. 68 | } else { 69 | // Initialization failed, check error value. 70 | } 71 | ... 72 | } 73 | ``` 74 | 75 | ### Out-of-process ### 76 | 77 | First you need to declare a new service that will work in a parallel process, please add a following line to your AndroidManifest.xml, application element: 78 | 79 | ``` 80 | 82 | ... 83 | 84 | ... 85 | 86 | ``` 87 | 88 | Note that ":reportprocess" is just string used for a process name, it doesn't affect library work but should be set. 89 | 90 | Next you need to add some code that initializes a signal handler and starts a service. You should add this code to `onCreate` method of your Application subclass. It will register a signal handler and will start a background service that will use specified unwinder and report path. A class of starting background service should be provided in this point (it should be the same with declared in AndroidManifest.xml). This is an example: 91 | 92 | ``` 93 | @Override 94 | public void onCreate() { 95 | super.onCreate(); 96 | final String reportPath = getFilesDir().getAbsolutePath() + "/crash.txt"; // Example. 97 | final NDCrashError error = NDCrash.initializeOutOfProcess( 98 | this, 99 | reportPath, 100 | NDCrashUnwinder.libunwind, 101 | NDCrashService.class); 102 | if (error == NDCrashError.ok) { 103 | // Initialization is successful. 104 | } else { 105 | // Initialization failed, check error value. 106 | } 107 | } 108 | ``` 109 | 110 | Some important details: `onCreate()` method is run for all processes of an application including background crash service process. The `NDCrash.initializeOutOfProcess` method checks if it's run from crash service process. If yes it doesn't do anything and return NDCrashError.ok value, we don't need to register a signal handler for background process. 111 | 112 | If your application has a lot of processes you can add additional check and initialize a library only for processes that use NDK code (for optimization). But keep in mind that a library must be initialized from main process of an application anyway. It should be done because a service is started only from the main process of an application. You can use `NDCrashUtils.isMainProcess` to check this situation. 113 | 114 | ### Immediate crash handling ### 115 | 116 | You can access a crash report immediately, for example you can send it to your server straight after it's generated. It's supported **only in Out-of-process mode**. To do this you need to subclass `NDCrashService` class and override `onCrash` method: 117 | 118 | ``` 119 | public class CrashService extends NDCrashService { 120 | @Override 121 | public void onCrash(String reportPath) { 122 | // Read a file at reportPath. 123 | } 124 | ``` 125 | 126 | Also a service declaration in AndroidManifest.xml should be updated: 127 | 128 | ``` 129 | 130 | ``` 131 | 132 | And, or course, you need to update a library initialization code, it should provide actual `serviceClass` argument: 133 | 134 | ``` 135 | final NDCrashError error = NDCrash.initializeOutOfProcess( 136 | ... 137 | CrashService.class); 138 | ``` 139 | 140 | Please keep in mind that onCrash is run from background thread created by *pthread*. It means it doesn't have a Looper instance. Also note that when `onCrash` method is running other crash report can't be created, it means a very long blocking operation in it is unwanted. 141 | 142 | ## Customization ## 143 | 144 | For optimization purposes you can customize **NDCrash** library, see *Customization* section in [NDCrash docs](https://github.com/ivanarh/ndcrash) 145 | Since **JNDCrash** is a wrapper, it's customized along with underlying library with the same parameters passed by CMake variables. You always can create a fork of these libraries and set parameters, for example, to build.gradle file of **JNDCrash**: 146 | 147 | ``` 148 | android { 149 | ... 150 | defaultConfig { 151 | ... 152 | externalNativeBuild { 153 | cmake { 154 | arguments "-DANDROID_STL=c++_static", "-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON" 155 | } 156 | } 157 | } 158 | } 159 | ``` 160 | 161 | If you don't wish to create a fork you can use a following ability to customize enabled modules set of **JNDCrash**: You can create `jndcrash.cmake` file in the same directory where **JNDCrash** submodule is cloned, for example see this file in [demo application](https://github.com/ivanarh/ndcrashdemo). Here is example contents of this file: 162 | 163 | ``` 164 | # Modes. 165 | set(ENABLE_INPROCESS ON) 166 | set(ENABLE_OUTOFPROCESS ON) 167 | set(ENABLE_OUTOFPROCESS_ALL_THREADS ON) 168 | 169 | # Unwinders. 170 | set(ENABLE_LIBCORKSCREW ON) 171 | set(ENABLE_LIBUNWIND ON) 172 | set(ENABLE_LIBUNWINDSTACK ON) 173 | set(ENABLE_CXXABI ON) 174 | set(ENABLE_STACKSCAN ON) 175 | ``` 176 | 177 | By default, if this file is absent, all modes all modes and unwinders are switched on. Don't forget that you should initialize crash reporting library with supported mode and supported unwinder, otherwise an initialization will fail. 178 | 179 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 28 5 | defaultConfig { 6 | minSdkVersion 15 7 | targetSdkVersion 28 8 | versionCode 1 9 | versionName "1.0" 10 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 11 | externalNativeBuild { 12 | cmake { 13 | arguments "-DANDROID_STL=c++_static", "-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON" 14 | } 15 | } 16 | ndk { 17 | abiFilters "x86", "armeabi-v7a", "x86_64", "arm64-v8a" 18 | } 19 | } 20 | 21 | buildTypes { 22 | release { 23 | minifyEnabled false 24 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 25 | } 26 | } 27 | 28 | externalNativeBuild { 29 | cmake { 30 | path "CMakeLists.txt" 31 | } 32 | } 33 | } 34 | 35 | buildscript { 36 | repositories { 37 | google() 38 | jcenter() 39 | } 40 | dependencies { 41 | classpath 'com.android.tools.build:gradle:3.4.1' 42 | } 43 | } 44 | 45 | repositories { 46 | google() 47 | jcenter() 48 | } 49 | 50 | dependencies { 51 | implementation fileTree(dir: 'libs', include: ['*.jar']) 52 | 53 | testImplementation 'junit:junit:4.12' 54 | androidTestImplementation 'com.android.support.test:runner:1.0.2' 55 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' 56 | implementation 'com.android.support:support-annotations:28.0.0' 57 | } 58 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ivanarh/jndcrash/a283eb10fae54b01b084b4b8691fcb1deec9c03d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Apr 14 14:35:54 MSK 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /src/androidTest/java/ru/ivanarh/jndcrash/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package ru.ivanarh.jndcrash; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("ru.ivanarh.jndcrash.test", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /src/main/java/ru/ivanarh/jndcrash/NDCrash.java: -------------------------------------------------------------------------------- 1 | package ru.ivanarh.jndcrash; 2 | 3 | import android.content.Context; 4 | import android.content.Intent; 5 | import android.support.annotation.NonNull; 6 | import android.support.annotation.Nullable; 7 | 8 | /** 9 | * Main binding class for NDCrash functionality. 10 | */ 11 | public class NDCrash { 12 | 13 | /** 14 | * Initializes NDCrash library signal handler using in-process mode. 15 | * 16 | * @param crashReportPath Path where a crash report is saved. 17 | * @param unwinder Used unwinder. See ndcrash_unwinder type in ndcrash.h. 18 | * @return Error status. 19 | */ 20 | public static NDCrashError initializeInProcess(@Nullable String crashReportPath, NDCrashUnwinder unwinder) { 21 | return NDCrashError.values()[nativeInitializeInProcess(crashReportPath, unwinder.ordinal())]; 22 | } 23 | 24 | /// Native implementation method. 25 | private static native int nativeInitializeInProcess(@Nullable String crashReportPath, int unwinder); 26 | 27 | /** 28 | * De-initializes NDCrash library signal handler using in-process mode. 29 | * 30 | * @return Flag whether de-initialization was successful. 31 | */ 32 | public static boolean deInitializeInProcess() { 33 | return nativeDeInitializeInProcess(); 34 | } 35 | 36 | /// Native implementation method. 37 | private static native boolean nativeDeInitializeInProcess(); 38 | 39 | /** 40 | * Initializes NDCrash library signal handler using out-of-process mode. Should be called from 41 | * onCreate() method of your subclass of Application. 42 | * 43 | * @param context Context instance. Used to determine a socket name and start a service. 44 | * @param crashReportPath Path where a crash report is saved. 45 | * @param unwinder Used unwinder. See ndcrash_unwinder type in ndcrash.h. 46 | * @param serviceClass Class of background service. Used when we need to use a custom subclass 47 | * of NDCrashUnwinder to use as a background service. If you didn't subclass 48 | * NDCrashUnwinder, please pass NDCrashUnwinder.class. 49 | * @return Error status. 50 | */ 51 | public static NDCrashError initializeOutOfProcess( 52 | @NonNull Context context, 53 | @Nullable String crashReportPath, 54 | @NonNull NDCrashUnwinder unwinder, 55 | @NonNull Class serviceClass) { 56 | if (NDCrashUtils.isCrashServiceProcess(context, serviceClass)) { 57 | // If it's a background crash service process we don't need to initialize anything, 58 | // we treat this situation as no error because this method is designed to call from 59 | // Application.onCreate(). 60 | return NDCrashError.ok; 61 | } 62 | // Saving service class, we should be able to stop it on de-initialization. 63 | mServiceClass = serviceClass; 64 | // Starting crash reporting service. Only from main process. 65 | if (NDCrashUtils.isMainProcess(context)) { 66 | final Intent serviceIntent = new Intent(context, serviceClass); 67 | serviceIntent.putExtra(NDCrashService.EXTRA_REPORT_FILE, crashReportPath); 68 | serviceIntent.putExtra(NDCrashService.EXTRA_UNWINDER, unwinder.ordinal()); 69 | try { 70 | context.startService(serviceIntent); 71 | } catch (RuntimeException e) { 72 | return NDCrashError.error_service_start_failed; 73 | } 74 | } 75 | // Initializing signal handler. 76 | return NDCrashError.values()[nativeInitializeOutOfProcess(getSocketName(context))]; 77 | } 78 | 79 | /// Native implementation method. 80 | private static native int nativeInitializeOutOfProcess(@NonNull String socketName); 81 | 82 | /** 83 | * De-initializes NDCrash library signal handler using out-of-process mode. 84 | * 85 | * @param context Context instance. Used to stop a service. 86 | * @return Flag whether de-initialization was successful. 87 | */ 88 | public static boolean deInitializeOutOfProcess(@NonNull Context context) { 89 | if (mServiceClass != null) { 90 | context.stopService(new Intent(context, mServiceClass)); 91 | mServiceClass = null; 92 | } 93 | return nativeDeInitializeOutOfProcess(); 94 | } 95 | 96 | /// Native implementation method. 97 | private static native boolean nativeDeInitializeOutOfProcess(); 98 | 99 | /** 100 | * Starts NDCrash out-of-process unwinding daemon. This is necessary for out of process crash 101 | * handling. This method is run from a service that works in separate process. 102 | * 103 | * @param context Context instance. Used to determine a socket name. 104 | * @param crashReportPath Path where to save a crash report. 105 | * @param unwinder Unwinder to use. 106 | * @param callback Callback to execute when a crash has occurred. 107 | * @return Error status. 108 | */ 109 | static NDCrashError startOutOfProcessDaemon( 110 | @NonNull Context context, 111 | @Nullable String crashReportPath, 112 | @NonNull NDCrashUnwinder unwinder, 113 | @Nullable OnCrashCallback callback) { 114 | if (NDCrashUtils.isMainProcess(context)) { 115 | return NDCrashError.error_wrong_process; 116 | } 117 | mOnCrashCallback = callback; 118 | final NDCrashError result = NDCrashError.values()[nativeStartOutOfProcessDaemon(getSocketName(context), crashReportPath, unwinder.ordinal())]; 119 | if (result != NDCrashError.ok) { 120 | mOnCrashCallback = null; 121 | } 122 | return result; 123 | } 124 | 125 | /// Native implementation method. 126 | private static native int nativeStartOutOfProcessDaemon( 127 | @NonNull String socketName, 128 | @Nullable String crashReportPath, 129 | int unwinder); 130 | 131 | /** 132 | * Stops NDCrash out-of-process unwinding daemon. 133 | * 134 | * @return Flag whether daemon stopping was successful. 135 | */ 136 | static boolean stopOutOfProcessDaemon() { 137 | final boolean result = nativeStopOutOfProcessDaemon(); 138 | mOnCrashCallback = null; 139 | return result; 140 | } 141 | 142 | /// Native implementation method. 143 | private static native boolean nativeStopOutOfProcessDaemon(); 144 | 145 | /** 146 | * Instance of crash callback. 147 | */ 148 | @Nullable 149 | private static volatile OnCrashCallback mOnCrashCallback = null; 150 | 151 | /** 152 | * Background service class for out-of-process mode. 153 | */ 154 | @Nullable 155 | private static Class mServiceClass = null; 156 | 157 | /** 158 | * Runs on crash callback if it was set. This method is called from native code. 159 | * 160 | * @param reportPath Path to file containing crash report. 161 | */ 162 | private static void runOnCrashCallback(String reportPath) { 163 | final OnCrashCallback callback = mOnCrashCallback; 164 | if (callback != null) { 165 | callback.onCrash(reportPath); 166 | } 167 | } 168 | 169 | /** 170 | * Retrieves a socket name from Context instance. We use a package name with additional suffix 171 | * to make sure that socket name doesn't intersect with another application. 172 | * 173 | * @param context Context to use. 174 | * @return Socket name. 175 | */ 176 | private static String getSocketName(@NonNull Context context) { 177 | return context.getPackageName() + ".ndcrash"; 178 | } 179 | 180 | /** 181 | * Crash callback that allows to process a report immediately after crash. Works only in out of 182 | * process mode. 183 | */ 184 | public interface OnCrashCallback { 185 | 186 | /** 187 | * Runs when crash is detected. This method is run from background (daemon) thread. 188 | * This method allows to process a report immediately after crash. 189 | * 190 | * @param reportPath Path to file containing crash report. 191 | */ 192 | void onCrash(String reportPath); 193 | 194 | } 195 | 196 | static { 197 | System.loadLibrary("jndcrash"); 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /src/main/java/ru/ivanarh/jndcrash/NDCrashError.java: -------------------------------------------------------------------------------- 1 | package ru.ivanarh.jndcrash; 2 | 3 | /** 4 | * Error status. Matches ndcrash_error enum values in ndcrash.h. 5 | */ 6 | public enum NDCrashError { 7 | /// No error, everything is ok. 8 | ok, 9 | 10 | /// NDCrash has already been initialized. 11 | error_already_initialized, 12 | 13 | /// A selected working mode or unwinder is not supported. 14 | error_not_supported, 15 | 16 | /// Error during registering a signal handler. 17 | error_signal, 18 | 19 | /// Error during pipe creation. Pipes are used internally in out-of-process mode. 20 | error_pipe, 21 | 22 | /// Error during thread creation for out-of-process daemon. 23 | error_thread, 24 | 25 | /// Wrong socket name error. 26 | error_socket_name, 27 | 28 | /// Wron process error. Happens if we try to initialize an out-of-process daemon from a main process. 29 | error_wrong_process, 30 | 31 | /// A background out-of-process service has failed to start. 32 | error_service_start_failed, 33 | } -------------------------------------------------------------------------------- /src/main/java/ru/ivanarh/jndcrash/NDCrashService.java: -------------------------------------------------------------------------------- 1 | package ru.ivanarh.jndcrash; 2 | 3 | import android.app.Service; 4 | import android.content.Intent; 5 | import android.content.SharedPreferences; 6 | import android.os.IBinder; 7 | import android.support.annotation.CallSuper; 8 | import android.util.Log; 9 | 10 | /** 11 | * Service for out-of-process crash handling daemon. Should be run from a separate process. 12 | */ 13 | public class NDCrashService extends Service implements NDCrash.OnCrashCallback 14 | { 15 | /** 16 | * Log tag. 17 | */ 18 | private static final String TAG = "JNDCRASH"; 19 | 20 | /** 21 | * Indicates if a daemon was started. 22 | */ 23 | private static boolean mDaemonStarted = false; 24 | 25 | /** 26 | * A name for shared preferences. 27 | */ 28 | private static final String PREFS_NAME = "NDCrashService"; 29 | 30 | /** 31 | * Key for report file in arguments. 32 | */ 33 | public static final String EXTRA_REPORT_FILE = "report_file"; 34 | 35 | /** 36 | * Key for unwinder in arguments. Ordinal value is saved as integer. 37 | */ 38 | public static final String EXTRA_UNWINDER = "unwinder"; 39 | 40 | @Override 41 | public int onStartCommand(Intent intent, int flags, int startId) { 42 | final SharedPreferences preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); 43 | NDCrashUnwinder unwinder = null; 44 | String reportPath = null; 45 | if (intent != null) { 46 | unwinder = NDCrashUnwinder.values()[intent.getIntExtra(EXTRA_UNWINDER, NDCrashUnwinder.libunwind.ordinal())]; 47 | reportPath = intent.getStringExtra(EXTRA_REPORT_FILE); 48 | // Using the same keys as extras. 49 | final SharedPreferences.Editor editor = preferences.edit(); 50 | if (unwinder != null) { 51 | editor.putInt(EXTRA_UNWINDER, unwinder.ordinal()); 52 | } else { 53 | editor.remove(EXTRA_UNWINDER); 54 | } 55 | if (reportPath != null) { 56 | editor.putString(EXTRA_REPORT_FILE, reportPath); 57 | } else { 58 | editor.remove(EXTRA_REPORT_FILE); 59 | } 60 | editor.apply(); 61 | } else { 62 | unwinder = NDCrashUnwinder.values()[preferences.getInt(EXTRA_UNWINDER, NDCrashUnwinder.libunwind.ordinal())]; 63 | reportPath = preferences.getString(EXTRA_REPORT_FILE, null); 64 | } 65 | if (!mDaemonStarted) { 66 | if (unwinder != null) { 67 | mDaemonStarted = true; 68 | final NDCrashError initResult = NDCrash.startOutOfProcessDaemon(this, reportPath, unwinder, this); 69 | if (initResult != NDCrashError.ok) { 70 | Log.e(TAG, "Couldn't start NDCrash out-of-process daemon with unwinder: " + unwinder + ", error: " + initResult); 71 | } else { 72 | Log.i(TAG, "Out-of-process unwinding daemon is started with unwinder: " + unwinder + " report path: " + 73 | (reportPath != null ? reportPath : "null")); 74 | onDaemonStart(unwinder, reportPath, initResult); 75 | } 76 | } else { 77 | Log.e(TAG, "Couldn't start NDCrash out-of-process daemon: unwinder is unknown."); 78 | } 79 | } else { 80 | Log.i(TAG, "NDCrash out-of-process daemon is already started."); 81 | } 82 | // START_REDELIVER_INTENT may seem better but found by experimental way that when we return 83 | // this value a service is restarted significantly slower (with a longer delay) after its 84 | // process is killed. So a workaround is used: Saving initialization parameters to shared 85 | // preferences and reading them when intent is null. 86 | return Service.START_STICKY; 87 | } 88 | 89 | @Override @CallSuper 90 | public void onDestroy() { 91 | if (mDaemonStarted) { 92 | mDaemonStarted = false; 93 | final boolean stoppedSuccessfully = NDCrash.stopOutOfProcessDaemon(); 94 | Log.i(TAG, "Out-of-process daemon " + (stoppedSuccessfully ? "is successfully stopped." : "failed to stop.")); 95 | } 96 | super.onDestroy(); 97 | } 98 | 99 | @Override 100 | public IBinder onBind(Intent intent) { 101 | // Service doesn't support to be bound. 102 | return null; 103 | } 104 | 105 | @Override 106 | public void onCrash(String reportPath) { 107 | } 108 | 109 | /** 110 | * Called on daemon start attempt, both on success and failed. 111 | * 112 | * @param unwinder Unwinder that is used. 113 | * @param reportPath Path to crash report file. 114 | * @param result Start result. 115 | */ 116 | protected void onDaemonStart(NDCrashUnwinder unwinder, String reportPath, NDCrashError result) { 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/ru/ivanarh/jndcrash/NDCrashUnwinder.java: -------------------------------------------------------------------------------- 1 | package ru.ivanarh.jndcrash; 2 | 3 | /** 4 | * Unwinder type. Matches ndcrash_unwinder values in ndcrash.h. 5 | */ 6 | public enum NDCrashUnwinder { 7 | libcorkscrew, 8 | libunwind, 9 | libunwindstack, 10 | cxxabi, 11 | stackscan, 12 | } -------------------------------------------------------------------------------- /src/main/java/ru/ivanarh/jndcrash/NDCrashUtils.java: -------------------------------------------------------------------------------- 1 | package ru.ivanarh.jndcrash; 2 | 3 | import android.app.ActivityManager; 4 | import android.content.ComponentName; 5 | import android.content.Context; 6 | import android.content.pm.PackageManager; 7 | import android.content.pm.ServiceInfo; 8 | import android.os.Process; 9 | import android.support.annotation.NonNull; 10 | 11 | /** 12 | * Contains some utility code. 13 | */ 14 | public class NDCrashUtils { 15 | 16 | /** 17 | * Checks if a current process is a main process of application. 18 | * 19 | * @param context Current context. 20 | * @return Flag whether it's a main process. 21 | */ 22 | public static boolean isMainProcess(@NonNull Context context) { 23 | final int pid = Process.myPid(); 24 | final String packageName = context.getPackageName(); 25 | final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 26 | if (manager != null) { 27 | for (final ActivityManager.RunningAppProcessInfo info : manager.getRunningAppProcesses()) { 28 | if (info.pid == pid) { 29 | return packageName.equals(info.processName); 30 | } 31 | } 32 | } 33 | return true; 34 | } 35 | 36 | /** 37 | * Checks if a current process is a background crash service process. 38 | * 39 | * @param context Current context. 40 | * @param serviceClass Class of background crash reporting service. 41 | * @return Flag whether a current process is a background crash service process. 42 | */ 43 | public static boolean isCrashServiceProcess(@NonNull Context context, @NonNull Class serviceClass) { 44 | final ServiceInfo serviceInfo; 45 | try { 46 | serviceInfo = context.getPackageManager().getServiceInfo(new ComponentName(context, serviceClass), 0); 47 | } catch (PackageManager.NameNotFoundException ignored) { 48 | return false; 49 | } 50 | final int pid = Process.myPid(); 51 | final ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); 52 | if (manager != null) { 53 | for (final ActivityManager.RunningAppProcessInfo info : manager.getRunningAppProcesses()) { 54 | if (info.pid == pid) { 55 | return serviceInfo.processName.equals(info.processName); 56 | } 57 | } 58 | } 59 | return false; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/jni/jndcrash.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // NDCrash.java methods 6 | 7 | JNIEXPORT jint JNICALL Java_ru_ivanarh_jndcrash_NDCrash_nativeInitializeInProcess( 8 | JNIEnv *env, 9 | jclass type, 10 | jstring jCrashReportPath, 11 | jint unwinder) { 12 | #ifdef ENABLE_INPROCESS 13 | const char *crashReportPath = NULL; 14 | if (jCrashReportPath) { 15 | crashReportPath = (*env)->GetStringUTFChars(env, jCrashReportPath, NULL); 16 | } 17 | const enum ndcrash_error error = ndcrash_in_init((enum ndcrash_unwinder) unwinder, crashReportPath); 18 | if (jCrashReportPath) { 19 | (*env)->ReleaseStringUTFChars(env, jCrashReportPath, crashReportPath); 20 | } 21 | return (jint) error; 22 | #else 23 | return (jint) ndcrash_error_not_supported; 24 | #endif 25 | } 26 | 27 | JNIEXPORT jboolean JNICALL Java_ru_ivanarh_jndcrash_NDCrash_nativeDeInitializeInProcess( 28 | JNIEnv *env, 29 | jclass type) { 30 | #ifdef ENABLE_INPROCESS 31 | return (jboolean) ndcrash_in_deinit(); 32 | #else 33 | return (jboolean) false; 34 | #endif 35 | } 36 | 37 | JNIEXPORT jint JNICALL Java_ru_ivanarh_jndcrash_NDCrash_nativeInitializeOutOfProcess( 38 | JNIEnv *env, 39 | jclass type, 40 | jstring jSocketName) { 41 | #ifdef ENABLE_OUTOFPROCESS 42 | const char *socket_name = jSocketName ? (*env)->GetStringUTFChars(env, jSocketName, NULL) : NULL; 43 | const enum ndcrash_error error = ndcrash_out_init(socket_name); 44 | if (socket_name) { 45 | (*env)->ReleaseStringUTFChars(env, jSocketName, socket_name); 46 | } 47 | return (jint) error; 48 | #else 49 | return (jint) ndcrash_error_not_supported; 50 | #endif 51 | } 52 | 53 | JNIEXPORT jboolean JNICALL Java_ru_ivanarh_jndcrash_NDCrash_nativeDeInitializeOutOfProcess( 54 | JNIEnv *env, 55 | jclass type) { 56 | #ifdef ENABLE_OUTOFPROCESS 57 | return (jboolean) ndcrash_out_deinit(); 58 | #else 59 | return (jboolean) false; 60 | #endif 61 | } 62 | 63 | #ifdef ENABLE_OUTOFPROCESS 64 | 65 | /// JavaVM instance. We use it to run. 66 | JavaVM * jndcrash_javavm = NULL; 67 | 68 | /// Called when a native library is loaded. 69 | JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { 70 | jndcrash_javavm = vm; 71 | return JNI_VERSION_1_4; 72 | } 73 | 74 | /// Called when a native library is unloaded. 75 | JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) { 76 | jndcrash_javavm = NULL; 77 | } 78 | 79 | // Special struct where we save values that we need to run a crash callback. 80 | typedef struct { 81 | 82 | /// Global reference to NDCrash class. 83 | jclass jc_NDCrash; 84 | 85 | /// Method ID of runOnCrashCallback. 86 | jmethodID jm_runOnCrashCallback; 87 | 88 | /// JNI environment for daemon background thread. 89 | JNIEnv *daemon_thread_env; 90 | 91 | } jndcrash_callback_arg_t; 92 | 93 | /// Called on daemon start from its background thread. 94 | static void jndcrash_daemon_start(void *argvoid) { 95 | jndcrash_callback_arg_t * const arg = (jndcrash_callback_arg_t *) argvoid; 96 | (*jndcrash_javavm)->AttachCurrentThread(jndcrash_javavm, &arg->daemon_thread_env, NULL); 97 | } 98 | 99 | /// Called when a crash report is generated. From background thread. 100 | static void jndcrash_on_crash(const char *report_file, void *argvoid) { 101 | jndcrash_callback_arg_t * const arg = (jndcrash_callback_arg_t *) argvoid; 102 | const jstring j_report_file = (*arg->daemon_thread_env)->NewStringUTF(arg->daemon_thread_env, report_file); 103 | (*arg->daemon_thread_env)->CallStaticVoidMethod( 104 | arg->daemon_thread_env, arg->jc_NDCrash, arg->jm_runOnCrashCallback, j_report_file); 105 | (*arg->daemon_thread_env)->DeleteLocalRef(arg->daemon_thread_env, j_report_file); 106 | } 107 | 108 | /// Called on daemon stop from its background thread. 109 | static void jndcrash_daemon_stop(void *argvoid) { 110 | jndcrash_callback_arg_t * const arg = (jndcrash_callback_arg_t *) argvoid; 111 | (*jndcrash_javavm)->DetachCurrentThread(jndcrash_javavm); 112 | } 113 | 114 | #endif //ENABLE_OUTOFPROCESS 115 | 116 | JNIEXPORT jint JNICALL Java_ru_ivanarh_jndcrash_NDCrash_nativeStartOutOfProcessDaemon( 117 | JNIEnv *env, 118 | jclass type, 119 | jstring jSocketName, 120 | jstring jCrashReportPath, 121 | jint unwinder) { 122 | #ifdef ENABLE_OUTOFPROCESS 123 | const char *crashReportPath = NULL; 124 | if (jCrashReportPath) { 125 | crashReportPath = (*env)->GetStringUTFChars(env, jCrashReportPath, 0); 126 | } 127 | const char *socket_name = jSocketName ? (*env)->GetStringUTFChars(env, jSocketName, NULL) : NULL; 128 | 129 | jndcrash_callback_arg_t * const arg = calloc(1, sizeof(jndcrash_callback_arg_t)); 130 | arg->jc_NDCrash = (*env)->NewGlobalRef(env, type); 131 | arg->jm_runOnCrashCallback = (*env)->GetStaticMethodID(env, arg->jc_NDCrash, "runOnCrashCallback", "(Ljava/lang/String;)V"); 132 | 133 | const enum ndcrash_error error = ndcrash_out_start_daemon( 134 | socket_name, 135 | (enum ndcrash_unwinder) unwinder, 136 | crashReportPath, 137 | &jndcrash_daemon_start, 138 | &jndcrash_on_crash, 139 | &jndcrash_daemon_stop, 140 | arg); 141 | 142 | if (crashReportPath) { 143 | (*env)->ReleaseStringUTFChars(env, jCrashReportPath, crashReportPath); 144 | } 145 | if (socket_name) { 146 | (*env)->ReleaseStringUTFChars(env, jSocketName, socket_name); 147 | } 148 | 149 | return (jint) error; 150 | #else 151 | return (jint) ndcrash_error_not_supported; 152 | #endif //ENABLE_OUTOFPROCESS 153 | } 154 | 155 | JNIEXPORT jboolean JNICALL Java_ru_ivanarh_jndcrash_NDCrash_nativeStopOutOfProcessDaemon(JNIEnv *env, jclass type) { 156 | #ifdef ENABLE_OUTOFPROCESS 157 | jndcrash_callback_arg_t * const arg = (jndcrash_callback_arg_t *) ndcrash_out_get_daemon_callbacks_arg(); 158 | if (arg) { 159 | (*env)->DeleteGlobalRef(env, arg->jc_NDCrash); 160 | free(arg); 161 | } 162 | return (jboolean) ndcrash_out_stop_daemon(); 163 | #else 164 | return (jboolean) false; 165 | #endif //ENABLE_OUTOFPROCESS 166 | } -------------------------------------------------------------------------------- /src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | jndcrash 3 | 4 | -------------------------------------------------------------------------------- /src/test/java/ru/ivanarh/jndcrash/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package ru.ivanarh.jndcrash; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } --------------------------------------------------------------------------------