├── .github └── logo.png ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── RELEASING.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── relinker ├── .gitignore ├── build.gradle └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── getkeepsafe │ │ └── relinker │ │ ├── ApkLibraryInstaller.java │ │ ├── MissingLibraryException.java │ │ ├── ReLinker.java │ │ ├── ReLinkerInstance.java │ │ ├── SystemLibraryLoader.java │ │ ├── TextUtils.java │ │ └── elf │ │ ├── Dynamic32Structure.java │ │ ├── Dynamic64Structure.java │ │ ├── Elf.java │ │ ├── Elf32Header.java │ │ ├── Elf64Header.java │ │ ├── ElfParser.java │ │ ├── Program32Header.java │ │ ├── Program64Header.java │ │ ├── Section32Header.java │ │ └── Section64Header.java │ └── test │ ├── java │ └── com │ │ └── getkeepsafe │ │ └── relinker │ │ ├── ApkLibraryInstallerTest.java │ │ ├── ApkLibraryInstallerWithSplitsTest.java │ │ ├── ReLinkerInstanceTest.java │ │ └── elf │ │ └── ElfParserTest.java │ └── resources │ ├── fake.apk │ ├── libdl.so │ └── robolectric.properties ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── getkeepsafe │ │ │ └── relinker │ │ │ └── sample │ │ │ ├── App.java │ │ │ ├── MainActivity.java │ │ │ └── Native.java │ ├── jni │ │ ├── Android.mk │ │ ├── Application.mk │ │ ├── hello │ │ │ ├── Android.mk │ │ │ ├── hello.cpp │ │ │ └── hello.h │ │ └── hellojni │ │ │ ├── .DS_Store │ │ │ ├── Android.mk │ │ │ └── hellojni.cpp │ ├── libs │ │ ├── armeabi-v7a │ │ │ ├── libhello.so │ │ │ └── libhellojni.so │ │ ├── armeabi │ │ │ ├── libhello.so │ │ │ └── libhellojni.so │ │ └── x86 │ │ │ ├── libhello.so │ │ │ └── libhellojni.so │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── getkeepsafe │ └── relinker │ └── ExampleUnitTest.java └── settings.gradle /.github/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/.github/logo.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | /*/build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | *.iml 30 | .idea/ 31 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | sudo: false 4 | 5 | install: true 6 | 7 | jdk: 8 | - oraclejdk8 9 | 10 | android: 11 | components: 12 | - tools 13 | - platform-tools 14 | 15 | before_install: 16 | - mkdir "$ANDROID_HOME/licenses" || true 17 | - echo "d56f5187479451eabf01fb78af6dfcb131a6481e" > "$ANDROID_HOME/licenses/android-sdk-license" 18 | - echo "24333f8a63b6825ea9c5514f83c2829b004d1fee" >> "$ANDROID_HOME/licenses/android-sdk-license" 19 | 20 | cache: 21 | directories: 22 | - $HOME/.m2 23 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | 11 | 12 | ## [Unreleased] 13 | 14 | ## [1.4.5] - Released July 13, 2022 15 | - Added null check when closing the parser (#99) 16 | 17 | ## [1.4.4] - Released July 9, 2021 18 | - Removed reliance on JCenter (#87) 19 | 20 | ## [1.4.3] - Released March 3, 2021 21 | - Moved artifact publishing from JCenter to Maven Central (#81) -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Guidelines for contributing 2 | 3 | Thank you for your interest in contributing! We're always happy to get the community involved in our projects, however we have just a couple rules that we enforce for any pull requests: 4 | 5 | - You must follow the code style already in place 6 | - You must squash all of your commits into one meaningful commit 7 | 8 | Any pull request that does not meet the above criteria will not be merged. 9 | -------------------------------------------------------------------------------- /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 2015 KeepSafe Software Inc. 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 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | ReLinker
3 | ReLinker 4 |

5 | 6 | [![Build Status](https://travis-ci.org/KeepSafe/ReLinker.svg?branch=master)](https://travis-ci.org/KeepSafe/ReLinker) 7 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.getkeepsafe.relinker/relinker/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.getkeepsafe.relinker/relinker) 8 | [![Release](https://img.shields.io/github/tag/KeepSafe/ReLinker.svg?label=jitpack)](https://jitpack.io/#KeepSafe/ReLinker) 9 | 10 | 11 | A robust native library loader for Android. More information can be found in our [blog post](https://medium.com/keepsafe-engineering/the-perils-of-loading-native-libraries-on-android-befa49dce2db) 12 | 13 | **Min SDK:** 9 14 | 15 | [JavaDoc](https://jitpack.io/com/github/KeepSafe/Relinker/latest/javadoc/) 16 | 17 | ## Overview 18 | 19 | The Android `PackageManager`'s native library loading is unreliable. Occasionally when using native libraries, you will encounter a stack trace like this: 20 | 21 | ``` 22 | java.lang.UnsatisfiedLinkError: Couldn't load stlport_shared from loader dalvik.system.PathClassLoader: findLibrary returned null 23 | at java.lang.Runtime.loadLibrary(Runtime.java:365) 24 | at java.lang.System.loadLibrary(System.java:535) 25 | at com.your.app.NativeClass.(Native.java:16) 26 | ... 63 more 27 | 28 | Caused by: java.lang.UnsatisfiedLinkError: Library stlport_shared not found 29 | at java.lang.Runtime.loadLibrary(Runtime.java:461) 30 | at java.lang.System.loadLibrary(System.java:557) 31 | at com.your.app.NativeClass.(Native.java:16) 32 | ... 5 more 33 | ``` 34 | 35 | ReLinker fixes these issues by replacing the standard `System.loadLibrary` call with a more reliable implementation. 36 | 37 | Note that this library fixes intermittent link errors; if you get an error every time you use your app, you may have a configuration issue. See [this StackOverflow question](http://stackoverflow.com/questions/27421134/system-loadlibrary-couldnt-find-native-library-in-my-case) for more information. 38 | 39 | ## Who needs ReLinker? 40 | 41 | If your app includes native libraries, and your minimum SDK is below API 23 (Marshmallow), you need ReLinker. 42 | 43 | There are a number of different bugs addressed by ReLinker; the last of these was resolved as of Marshmallow. As long as your app's min SDK is at or above it, loading libraries via `System.loadLibrary("foo")` is safe. 44 | 45 | ## Installation 46 | 47 | ReLinker is distributed using [MavenCentral](https://search.maven.org/artifact/com.getkeepsafe.relinker/relinker). 48 | 49 | ```groovy 50 | repositories { 51 | mavenCentral() 52 | } 53 | 54 | dependencies { 55 | compile 'com.getkeepsafe.relinker:relinker:x.x.x' 56 | } 57 | ``` 58 | 59 | If you wish, you may also use ReLinker with [jitpack](https://jitpack.io/#KeepSafe/ReLinker) 60 | 61 | ## Usage 62 | 63 | Simply replace a call to `System.loadLibrary` like this: 64 | 65 | ```java 66 | System.loadLibrary("mylibrary"); 67 | ``` 68 | 69 | With a call to `ReLinker.loadLibrary` like this: 70 | 71 | ```java 72 | ReLinker.loadLibrary(context, "mylibrary"); 73 | ``` 74 | 75 | ## Advanced Usage 76 | 77 | ### Asynchronous loading 78 | 79 | ReLinker can load libraries asynchronously. Simply pass a `LoadListener` instance to the `loadLibrary` call: 80 | ```java 81 | ReLinker.loadLibrary(context, "mylibrary", new ReLinker.LoadListener() { 82 | @Override 83 | public void success() { /* Yay */ } 84 | 85 | @Override 86 | public void failure(Throwable t) { /* Boo */ } 87 | }); 88 | ``` 89 | 90 | ### Recursive loading 91 | 92 | On older versions of Android, the system's library loader may fail to resolve intra-library dependencies. In this instance, ReLinker can resolve those dependencies for you. This will recursively load all libraries defined as "needed" by each library. 93 | 94 | For example, if you have a library `libchild` that relies on `libparent`, then `libchild` will have an entry in its shared object file defining that. ReLinker will parse the shared object file and determine that `libchild` needs `libparent`. ReLinker will then proceed to load `libparent` (and any dependencies it may have) and then `libchild`. 95 | 96 | To allow ReLinker to recursively load and resolve intra-library dependencies simply modify your `loadLibrary` call with the `recursively` modifier, like so: 97 | ```java 98 | ReLinker.recursively().loadLibrary(context, "mylibrary"); 99 | ``` 100 | 101 | ### Logging 102 | 103 | To help facilitate debugging, ReLinker can log messages to a `Logger` instance you provide: 104 | ```java 105 | ReLinker.log(myLogger).loadLibrary(context, "mylibrary"); 106 | ``` 107 | 108 | Which will log the following messages during a normal / successful execution: 109 | ``` 110 | D/ReLinker: Beginning load of mylibrary... 111 | D/ReLinker: mylibrary was not loaded normally, re-linking... 112 | D/ReLinker: Looking for lib/x86/libmylibrary.so in APK... 113 | D/ReLinker: Found lib/x86/libmylibrary.so! Extracting... 114 | D/ReLinker: mylibrary was re-linked! 115 | ``` 116 | 117 | ### Versioning 118 | 119 | In the event that your library's code is changed, it is a good idea to specify a specific version. Doing so will allow ReLinker to update the workaround library file successfully. In the case that the system handles the library loading appropriately, the version specified is not used as all library files are extracted and replaced on update or install. 120 | 121 | To specify a version for your library simply provide it as an additional parameter for `loadLibrary` like: 122 | ```java 123 | ReLinker.loadLibrary(context, "mylibrary", "1.0"); 124 | ``` 125 | 126 | This will cause ReLinker to look for, and load `libmylibrary.so.1.0`. Subsequent version updates will automatically clean up all other library versions. 127 | 128 | ## Sample application 129 | 130 | See the sample application under `sample/` for a quick demo. 131 | 132 | ## Acknowledgements 133 | 134 | Special thanks to [Jeff Young](https://github.com/tenoversix) for the awesome logo! 135 | 136 | ## License 137 | 138 | Copyright 2015 - 2016 Keepsafe Software Inc. 139 | 140 | Licensed under the Apache License, Version 2.0 (the "License"); 141 | you may not use this file except in compliance with the License. 142 | You may obtain a copy of the License at 143 | 144 | http://www.apache.org/licenses/LICENSE-2.0 145 | 146 | Unless required by applicable law or agreed to in writing, software 147 | distributed under the License is distributed on an "AS IS" BASIS, 148 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 149 | See the License for the specific language governing permissions and 150 | limitations under the License. 151 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | How To Release 2 | ============== 3 | 4 | Due to Maven Central's very particular requirements, the release process is a bit 5 | elaborate and requires a good deal of local configuration. This guide should walk 6 | you through it. It won't do anyone outside of KeepSafe any good, but the workflow 7 | is representative of just about any project deploying via Sonatype. 8 | 9 | We currently deploy to Maven Central (via Sonatype's OSS Nexus instance). 10 | 11 | ### Prerequisites 12 | 13 | 1. A *published* GPG code-signing key 14 | 1. A Sonatype Nexus OSS account with permission to publish in com.getkeepsafe 15 | 1. Permission to push directly to https://github.com/KeepSafe/ReLinker 16 | 17 | ### Setup 18 | 19 | 1. Add your GPG key to your github profile - this is required 20 | for github to know that your commits and tags are "verified". 21 | 1. Configure your code-signing key in ~/.gradle/gradle.properties: 22 | ```gradle 23 | signing.keyId= 24 | signing.password= 25 | signing.secretKeyRingFile=/path/to/your/secring.gpg 26 | ``` 27 | 1. Configure your Sonatype credentials in ~/.gradle/gradle.properties: 28 | ```gradle 29 | mavenCentralUsername= 30 | mavenCentralPassword= 31 | SONATYPE_STAGING_PROFILE=com.getkeepsafe 32 | ``` 33 | 1. Configure git with your codesigning key; make sure it's the same as the one 34 | you use to sign binaries (i.e. it's the same one you added to gradle.properties): 35 | ```bash 36 | # Do this for the ReLinker repo only 37 | git config user.email "your@email.com" 38 | git config user.signingKey "your-key-id" 39 | ``` 40 | 41 | ### Pushing a build 42 | 43 | 1. Edit gradle.properties, update the VERSION property for the new version release 44 | 1. Edit changelog, add relevant changes, note the date and new version (follow the existing pattern) 45 | 1. Add new `## [Unreleased]` header for next release 46 | 1. Verify that the everything works: 47 | ```bash 48 | ./gradlew clean check 49 | ``` 50 | 1. Make a *signed* commit: 51 | ```bash 52 | git commit -S -m "Release version X.Y.Z" 53 | ``` 54 | 1. Make a *signed* tag: 55 | ```bash 56 | git tag -s -a X.Y.Z 57 | ``` 58 | 1. Upload binaries to Staging: 59 | ```bash 60 | ./gradlew publish 61 | ``` 62 | 1. Publish to Release: 63 | ```bash 64 | ./gradlew closeAndReleaseRepository 65 | ``` 66 | 1. Wait until that's done. It takes a while to publish and be available in [MavenCentral](https://repo.maven.apache.org/maven2/com/getkeepsafe/). Monitor until the latest published version is visible. 67 | 1. Hooray, we're in Maven Central now! 68 | 1. Push all of our work to Github to make it official. Check previous [releases](https://github.com/KeepSafe/ReLinker/releases) and edit tag release changes: 69 | ```bash 70 | git push --tags origin master 71 | ``` 72 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | wrapper { 2 | gradleVersion = '7.1.1' 3 | distributionType = Wrapper.DistributionType.BIN 4 | } 5 | buildscript { 6 | repositories { 7 | google() 8 | mavenCentral() 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:4.2.2' 12 | classpath 'com.vanniktech:gradle-maven-publish-plugin:0.17.0' 13 | } 14 | } 15 | 16 | allprojects { 17 | repositories { 18 | google() 19 | mavenCentral() 20 | } 21 | } 22 | 23 | task clean(type: Delete) { 24 | delete rootProject.buildDir 25 | } 26 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | android.useAndroidX=true 2 | 3 | GROUP=com.getkeepsafe.relinker 4 | VERSION_NAME=1.4.5 5 | POM_ARTIFACT_ID=relinker 6 | 7 | POM_NAME=ReLinker 8 | POM_PACKAGING=aar 9 | 10 | POM_DESCRIPTION=A robust native library loader for Android 11 | POM_INCEPTION_YEAR=2015 12 | 13 | POM_URL=https://github.com/KeepSafe/ReLinker 14 | POM_SCM_URL=https://github.com/KeepSafe/ReLinker 15 | POM_SCM_CONNECTION=scm:git:git://github.com/KeepSafe/ReLinker.git 16 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/KeepSafe/ReLinker.git 17 | 18 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 19 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 20 | POM_LICENCE_DIST=repo 21 | 22 | POM_DEVELOPER_ID=keepsafe 23 | POM_DEVELOPER_NAME=KeepSafe Software, Inc. 24 | POM_DEVELOPER_URL=https://github.com/KeepSafe/ -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MSYS* | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /relinker/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | *.iml 3 | -------------------------------------------------------------------------------- /relinker/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.vanniktech.maven.publish' 3 | 4 | android { 5 | compileSdkVersion 30 6 | compileOptions { 7 | sourceCompatibility JavaVersion.VERSION_1_8 8 | targetCompatibility JavaVersion.VERSION_1_8 9 | } 10 | 11 | defaultConfig { 12 | //noinspection MinSdkTooLow 13 | minSdkVersion 9 14 | } 15 | testOptions { 16 | unitTests.all { 17 | testLogging { 18 | exceptionFormat 'full' 19 | showStackTraces true 20 | showCauses true 21 | events "passed", "skipped", "failed", "standardOut", "standardError" 22 | } 23 | } 24 | } 25 | } 26 | 27 | dependencies { 28 | testImplementation "org.robolectric:robolectric:4.5.1" 29 | testImplementation 'junit:junit:4.13.2' 30 | testImplementation 'org.mockito:mockito-all:1.10.19' 31 | testImplementation 'org.hamcrest:hamcrest-all:1.3' 32 | } 33 | 34 | // build a jar with source files 35 | task sourcesJar(type: Jar) { 36 | from android.sourceSets.main.java.srcDirs 37 | classifier = 'sources' 38 | } 39 | 40 | task javadoc(type: Javadoc) { 41 | failOnError false 42 | source = android.sourceSets.main.java.sourceFiles 43 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 44 | } 45 | 46 | // build a jar with javadoc 47 | task javadocJar(type: Jar, dependsOn: javadoc) { 48 | classifier = 'javadoc' 49 | from javadoc.destinationDir 50 | } 51 | 52 | artifacts { 53 | archives sourcesJar 54 | archives javadocJar 55 | } 56 | -------------------------------------------------------------------------------- /relinker/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/ApkLibraryInstaller.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker; 17 | 18 | import android.annotation.SuppressLint; 19 | import android.content.Context; 20 | import android.content.pm.ApplicationInfo; 21 | import android.os.Build; 22 | 23 | import java.io.Closeable; 24 | import java.io.File; 25 | import java.io.FileNotFoundException; 26 | import java.io.FileOutputStream; 27 | import java.io.IOException; 28 | import java.io.InputStream; 29 | import java.io.OutputStream; 30 | import java.util.Enumeration; 31 | import java.util.HashSet; 32 | import java.util.Set; 33 | import java.util.regex.Matcher; 34 | import java.util.regex.Pattern; 35 | import java.util.zip.ZipEntry; 36 | import java.util.zip.ZipFile; 37 | 38 | public class ApkLibraryInstaller implements ReLinker.LibraryInstaller { 39 | private static final int MAX_TRIES = 5; 40 | private static final int COPY_BUFFER_SIZE = 4096; 41 | 42 | private String[] sourceDirectories(final Context context) { 43 | final ApplicationInfo appInfo = context.getApplicationInfo(); 44 | 45 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && 46 | appInfo.splitSourceDirs != null && 47 | appInfo.splitSourceDirs.length != 0) { 48 | String[] apks = new String[appInfo.splitSourceDirs.length + 1]; 49 | apks[0] = appInfo.sourceDir; 50 | System.arraycopy(appInfo.splitSourceDirs, 0, apks, 1, appInfo.splitSourceDirs.length); 51 | return apks; 52 | } else { 53 | return new String[] { appInfo.sourceDir }; 54 | } 55 | } 56 | 57 | private static class ZipFileInZipEntry { 58 | public ZipFile zipFile; 59 | public ZipEntry zipEntry; 60 | 61 | public ZipFileInZipEntry(ZipFile zipFile, ZipEntry zipEntry) { 62 | this.zipFile = zipFile; 63 | this.zipEntry = zipEntry; 64 | } 65 | } 66 | 67 | private ZipFileInZipEntry findAPKWithLibrary(final Context context, 68 | final String[] abis, 69 | final String mappedLibraryName, 70 | final ReLinkerInstance instance) { 71 | 72 | for (String sourceDir : sourceDirectories(context)) { 73 | ZipFile zipFile = null; 74 | int tries = 0; 75 | while (tries++ < MAX_TRIES) { 76 | try { 77 | zipFile = new ZipFile(new File(sourceDir), ZipFile.OPEN_READ); 78 | break; 79 | } catch (IOException ignored) { 80 | } 81 | } 82 | 83 | if (zipFile == null) { 84 | continue; 85 | } 86 | 87 | tries = 0; 88 | while (tries++ < MAX_TRIES) { 89 | String jniNameInApk = null; 90 | ZipEntry libraryEntry = null; 91 | 92 | for (final String abi : abis) { 93 | jniNameInApk = "lib" + File.separatorChar + abi + File.separatorChar 94 | + mappedLibraryName; 95 | 96 | instance.log("Looking for %s in APK %s...", jniNameInApk, sourceDir); 97 | 98 | libraryEntry = zipFile.getEntry(jniNameInApk); 99 | 100 | if (libraryEntry != null) { 101 | return new ZipFileInZipEntry(zipFile, libraryEntry); 102 | } 103 | } 104 | } 105 | 106 | try { 107 | zipFile.close(); 108 | } catch (IOException ignored) { 109 | } 110 | } 111 | 112 | return null; 113 | } 114 | 115 | // Loop over all APK's again in order to detect which ABI's are actually supported. 116 | // This second loop is more expensive than trying to find a specific ABI, so it should 117 | // only be ran when no matching libraries are found. This should keep the overhead of 118 | // the happy path to a minimum. 119 | private String[] getSupportedABIs(Context context, String mappedLibraryName) { 120 | String p = "lib" + File.separatorChar + "([^\\" + File.separatorChar + "]*)" + File.separatorChar + mappedLibraryName; 121 | Pattern pattern = Pattern.compile(p); 122 | ZipFile zipFile; 123 | Set supportedABIs = new HashSet(); 124 | for (String sourceDir : sourceDirectories(context)) { 125 | try { 126 | zipFile = new ZipFile(new File(sourceDir), ZipFile.OPEN_READ); 127 | } catch (IOException ignored) { 128 | continue; 129 | } 130 | 131 | Enumeration elements = zipFile.entries(); 132 | while (elements.hasMoreElements()) { 133 | ZipEntry el = elements.nextElement(); 134 | Matcher match = pattern.matcher(el.getName()); 135 | if (match.matches()) { 136 | supportedABIs.add(match.group(1)); 137 | } 138 | } 139 | } 140 | 141 | String[] result = new String[supportedABIs.size()]; 142 | return supportedABIs.toArray(result); 143 | } 144 | 145 | /** 146 | * Attempts to unpack the given library to the given destination. Implements retry logic for 147 | * IO operations to ensure they succeed. 148 | * 149 | * @param context {@link Context} to describe the location of the installed APK file 150 | * @param mappedLibraryName The mapped name of the library file to load 151 | */ 152 | @SuppressLint ("SetWorldReadable") 153 | @SuppressWarnings("ResultOfMethodCallIgnored") 154 | @Override 155 | public void installLibrary(final Context context, 156 | final String[] abis, 157 | final String mappedLibraryName, 158 | final File destination, 159 | final ReLinkerInstance instance) { 160 | ZipFileInZipEntry found = null; 161 | try { 162 | found = findAPKWithLibrary(context, abis, mappedLibraryName, instance); 163 | if (found == null) { 164 | // Does not exist in any APK. Report exactly what ReLinker is looking for and 165 | // what is actually supported by the APK. 166 | String[] supportedABIs; 167 | try { 168 | supportedABIs = getSupportedABIs(context, mappedLibraryName); 169 | } catch (Exception e) { 170 | // Should never happen as this indicates a bug in ReLinker code, but just to be safe. 171 | // User code should only ever crash with a MissingLibraryException if getting this far. 172 | supportedABIs = new String[1]; 173 | supportedABIs[0] = e.toString(); 174 | } 175 | throw new MissingLibraryException(mappedLibraryName, abis, supportedABIs); 176 | } 177 | 178 | int tries = 0; 179 | while (tries++ < MAX_TRIES) { 180 | instance.log("Found %s! Extracting...", mappedLibraryName); 181 | try { 182 | if (!destination.exists() && !destination.createNewFile()) { 183 | continue; 184 | } 185 | } catch (IOException ignored) { 186 | // Try again 187 | continue; 188 | } 189 | 190 | InputStream inputStream = null; 191 | FileOutputStream fileOut = null; 192 | try { 193 | inputStream = found.zipFile.getInputStream(found.zipEntry); 194 | fileOut = new FileOutputStream(destination); 195 | final long written = copy(inputStream, fileOut); 196 | fileOut.getFD().sync(); 197 | if (written != destination.length()) { 198 | // File was not written entirely... Try again 199 | continue; 200 | } 201 | } catch (FileNotFoundException e) { 202 | // Try again 203 | continue; 204 | } catch (IOException e) { 205 | // Try again 206 | continue; 207 | } finally { 208 | closeSilently(inputStream); 209 | closeSilently(fileOut); 210 | } 211 | 212 | // Change permission to rwxr-xr-x 213 | destination.setReadable(true, false); 214 | destination.setExecutable(true, false); 215 | destination.setWritable(true); 216 | return; 217 | } 218 | 219 | instance.log("FATAL! Couldn't extract the library from the APK!"); 220 | } finally { 221 | try { 222 | if (found != null && found.zipFile != null) { 223 | found.zipFile.close(); 224 | } 225 | } catch (IOException ignored) {} 226 | } 227 | } 228 | 229 | /** 230 | * Copies all data from an {@link InputStream} to an {@link OutputStream}. 231 | * 232 | * @param in The stream to read from. 233 | * @param out The stream to write to. 234 | * @throws IOException when a stream operation fails. 235 | * @return The actual number of bytes copied 236 | */ 237 | private long copy(InputStream in, OutputStream out) throws IOException { 238 | long copied = 0; 239 | byte[] buf = new byte[COPY_BUFFER_SIZE]; 240 | while (true) { 241 | int read = in.read(buf); 242 | if (read == -1) { 243 | break; 244 | } 245 | out.write(buf, 0, read); 246 | copied += read; 247 | } 248 | out.flush(); 249 | return copied; 250 | } 251 | 252 | /** 253 | * Closes a {@link Closeable} silently (without throwing or handling any exceptions) 254 | * @param closeable {@link Closeable} to close 255 | */ 256 | private void closeSilently(final Closeable closeable) { 257 | try { 258 | if (closeable != null) { 259 | closeable.close(); 260 | } 261 | } catch (IOException ignored) {} 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/MissingLibraryException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker; 17 | 18 | import java.util.Arrays; 19 | 20 | public class MissingLibraryException extends RuntimeException { 21 | public MissingLibraryException(final String library, final String[] wantedABIs, final String[] supportedABIs) { 22 | super("Could not find '" + library + "'. " + 23 | "Looked for: " + Arrays.toString(wantedABIs) + ", " + 24 | "but only found: " + Arrays.toString(supportedABIs) + "."); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/ReLinker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker; 17 | 18 | import android.content.Context; 19 | 20 | import java.io.File; 21 | 22 | /** 23 | * ReLinker is a small library to help alleviate {@link UnsatisfiedLinkError} exceptions thrown due 24 | * to Android's inability to properly install / load native libraries for Android versions before 25 | * API 23. 26 | */ 27 | public class ReLinker { 28 | public interface LoadListener { 29 | void success(); 30 | void failure(Throwable t); 31 | } 32 | 33 | public interface Logger { 34 | void log(String message); 35 | } 36 | 37 | public interface LibraryLoader { 38 | void loadLibrary(String libraryName); 39 | void loadPath(String libraryPath); 40 | String mapLibraryName(String libraryName); 41 | String unmapLibraryName(String mappedLibraryName); 42 | String[] supportedAbis(); 43 | } 44 | 45 | public interface LibraryInstaller { 46 | void installLibrary(Context context, String[] abis, String mappedLibraryName, 47 | File destination, ReLinkerInstance logger); 48 | } 49 | 50 | public static void loadLibrary(final Context context, final String library) { 51 | loadLibrary(context, library, null, null); 52 | } 53 | 54 | public static void loadLibrary(final Context context, 55 | final String library, 56 | final String version) { 57 | loadLibrary(context, library, version, null); 58 | } 59 | 60 | public static void loadLibrary(final Context context, 61 | final String library, 62 | final LoadListener listener) { 63 | loadLibrary(context, library, null, listener); 64 | } 65 | 66 | public static void loadLibrary(final Context context, 67 | final String library, 68 | final String version, 69 | final ReLinker.LoadListener listener) { 70 | new ReLinkerInstance().loadLibrary(context, library, version, listener); 71 | } 72 | 73 | public static ReLinkerInstance force() { 74 | return new ReLinkerInstance().force(); 75 | } 76 | 77 | public static ReLinkerInstance log(final Logger logger) { 78 | return new ReLinkerInstance().log(logger); 79 | } 80 | 81 | public static ReLinkerInstance recursively() { 82 | return new ReLinkerInstance().recursively(); 83 | } 84 | 85 | private ReLinker() {} 86 | } 87 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/ReLinkerInstance.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker; 17 | 18 | import android.content.Context; 19 | import android.util.Log; 20 | 21 | import com.getkeepsafe.relinker.elf.ElfParser; 22 | 23 | import java.io.File; 24 | import java.io.FilenameFilter; 25 | import java.io.IOException; 26 | import java.util.HashSet; 27 | import java.util.List; 28 | import java.util.Locale; 29 | import java.util.Set; 30 | 31 | public class ReLinkerInstance { 32 | private static final String LIB_DIR = "lib"; 33 | 34 | protected final Set loadedLibraries = new HashSet(); 35 | protected final ReLinker.LibraryLoader libraryLoader; 36 | protected final ReLinker.LibraryInstaller libraryInstaller; 37 | 38 | protected boolean force; 39 | protected boolean recursive; 40 | protected ReLinker.Logger logger; 41 | 42 | protected ReLinkerInstance() { 43 | this(new SystemLibraryLoader(), new ApkLibraryInstaller()); 44 | } 45 | 46 | protected ReLinkerInstance(final ReLinker.LibraryLoader libraryLoader, 47 | final ReLinker.LibraryInstaller libraryInstaller) { 48 | if (libraryLoader == null) { 49 | throw new IllegalArgumentException("Cannot pass null library loader"); 50 | } 51 | 52 | if (libraryInstaller == null) { 53 | throw new IllegalArgumentException("Cannot pass null library installer"); 54 | } 55 | 56 | this.libraryLoader = libraryLoader; 57 | this.libraryInstaller = libraryInstaller; 58 | } 59 | 60 | /** 61 | * Logs debugging related information to the {@link ReLinker.Logger} instance given 62 | */ 63 | public ReLinkerInstance log(final ReLinker.Logger logger) { 64 | this.logger = logger; 65 | return this; 66 | } 67 | 68 | /** 69 | * Forces any previously extracted / re-linked libraries to be cleaned up before loading 70 | */ 71 | public ReLinkerInstance force() { 72 | this.force = true; 73 | return this; 74 | } 75 | 76 | /** 77 | * Enables recursive library loading to resolve and load shared object -> shared object 78 | * defined dependencies 79 | */ 80 | public ReLinkerInstance recursively() { 81 | this.recursive = true; 82 | return this; 83 | } 84 | 85 | /** 86 | * Utilizes the regular system call to attempt to load a native library. If a failure occurs, 87 | * then the function extracts native .so library out of the app's APK and attempts to load it. 88 | *

89 | * Note: This is a synchronous operation 90 | */ 91 | public void loadLibrary(final Context context, final String library) { 92 | loadLibrary(context, library, null, null); 93 | } 94 | 95 | /** 96 | * The same call as {@link #loadLibrary(Context, String)}, however if a {@code version} is 97 | * provided, then that specific version of the given library is loaded. 98 | */ 99 | public void loadLibrary(final Context context, final String library, final String version) { 100 | loadLibrary(context, library, version, null); 101 | } 102 | 103 | /** 104 | * The same call as {@link #loadLibrary(Context, String)}, however if a 105 | * {@link ReLinker.LoadListener} is provided, the function is executed asynchronously. 106 | */ 107 | public void loadLibrary(final Context context, 108 | final String library, 109 | final ReLinker.LoadListener listener) { 110 | loadLibrary(context, library, null, listener); 111 | } 112 | 113 | /** 114 | * Attemps to load the given library normally. If that fails, it loads the library utilizing 115 | * a workaround. 116 | * 117 | * @param context The {@link Context} to get a workaround directory from 118 | * @param library The library you wish to load 119 | * @param version The version of the library you wish to load, or {@code null} 120 | * @param listener {@link ReLinker.LoadListener} to listen for async execution, or {@code null} 121 | */ 122 | public void loadLibrary(final Context context, 123 | final String library, 124 | final String version, 125 | final ReLinker.LoadListener listener) { 126 | if (context == null) { 127 | throw new IllegalArgumentException("Given context is null"); 128 | } 129 | 130 | if (TextUtils.isEmpty(library)) { 131 | throw new IllegalArgumentException("Given library is either null or empty"); 132 | } 133 | 134 | log("Beginning load of %s...", library); 135 | if (listener == null) { 136 | loadLibraryInternal(context, library, version); 137 | } else { 138 | new Thread(new Runnable() { 139 | @Override 140 | public void run() { 141 | try { 142 | loadLibraryInternal(context, library, version); 143 | listener.success(); 144 | } catch (UnsatisfiedLinkError e) { 145 | listener.failure(e); 146 | } catch (MissingLibraryException e) { 147 | listener.failure(e); 148 | } 149 | } 150 | }).start(); 151 | } 152 | } 153 | 154 | private void loadLibraryInternal(final Context context, 155 | final String library, 156 | final String version) { 157 | if (loadedLibraries.contains(library) && !force) { 158 | log("%s already loaded previously!", library); 159 | return; 160 | } 161 | 162 | try { 163 | libraryLoader.loadLibrary(library); 164 | loadedLibraries.add(library); 165 | log("%s (%s) was loaded normally!", library, version); 166 | return; 167 | } catch (final UnsatisfiedLinkError e) { 168 | // :-( 169 | log("Loading the library normally failed: %s", Log.getStackTraceString(e)); 170 | } 171 | 172 | log("%s (%s) was not loaded normally, re-linking...", library, version); 173 | final File workaroundFile = getWorkaroundLibFile(context, library, version); 174 | if (!workaroundFile.exists() || force) { 175 | if (force) { 176 | log("Forcing a re-link of %s (%s)...", library, version); 177 | } 178 | 179 | cleanupOldLibFiles(context, library, version); 180 | libraryInstaller.installLibrary(context, libraryLoader.supportedAbis(), 181 | libraryLoader.mapLibraryName(library), workaroundFile, this); 182 | } 183 | 184 | try { 185 | if (recursive) { 186 | ElfParser parser = null; 187 | final List dependencies; 188 | try { 189 | parser = new ElfParser(workaroundFile); 190 | dependencies = parser.parseNeededDependencies(); 191 | } finally { 192 | if (parser != null) { 193 | parser.close(); 194 | } 195 | } 196 | for (final String dependency : dependencies) { 197 | loadLibrary(context, libraryLoader.unmapLibraryName(dependency)); 198 | } 199 | } 200 | } catch (IOException ignored) { 201 | // This a redundant step of the process, if our library resolving fails, it will likely 202 | // be picked up by the system's resolver, if not, an exception will be thrown by the 203 | // next statement, so its better to try twice. 204 | } 205 | 206 | libraryLoader.loadPath(workaroundFile.getAbsolutePath()); 207 | loadedLibraries.add(library); 208 | log("%s (%s) was re-linked!", library, version); 209 | } 210 | 211 | /** 212 | * @param context {@link Context} to describe the location of it's private directories 213 | * @return A {@link File} locating the directory that can store extracted libraries 214 | * for later use 215 | */ 216 | protected File getWorkaroundLibDir(final Context context) { 217 | return context.getDir(LIB_DIR, Context.MODE_PRIVATE); 218 | } 219 | 220 | /** 221 | * @param context {@link Context} to retrieve the workaround directory from 222 | * @param library The name of the library to load 223 | * @param version The version of the library to load or {@code null} 224 | * @return A {@link File} locating the workaround library file to load 225 | */ 226 | protected File getWorkaroundLibFile(final Context context, 227 | final String library, 228 | final String version) { 229 | final String libName = libraryLoader.mapLibraryName(library); 230 | 231 | if (TextUtils.isEmpty(version)) { 232 | return new File(getWorkaroundLibDir(context), libName); 233 | } 234 | 235 | return new File(getWorkaroundLibDir(context), libName + "." + version); 236 | } 237 | 238 | /** 239 | * Cleans up any other versions of the {@code library}. If {@code force} is used, all 240 | * versions of the {@code library} are deleted 241 | * 242 | * @param context {@link Context} to retrieve the workaround directory from 243 | * @param library The name of the library to load 244 | * @param currentVersion The version of the library to keep, all other versions will be deleted. 245 | * This parameter is ignored if {@code force} is used. 246 | */ 247 | protected void cleanupOldLibFiles(final Context context, 248 | final String library, 249 | final String currentVersion) { 250 | final File workaroundDir = getWorkaroundLibDir(context); 251 | final File workaroundFile = getWorkaroundLibFile(context, library, currentVersion); 252 | final String mappedLibraryName = libraryLoader.mapLibraryName(library); 253 | final File[] existingFiles = workaroundDir.listFiles(new FilenameFilter() { 254 | @Override 255 | public boolean accept(File dir, String filename) { 256 | return filename.startsWith(mappedLibraryName); 257 | } 258 | }); 259 | 260 | if (existingFiles == null) return; 261 | 262 | for (final File file : existingFiles) { 263 | if (force || !file.getAbsolutePath().equals(workaroundFile.getAbsolutePath())) { 264 | file.delete(); 265 | } 266 | } 267 | } 268 | 269 | public void log(final String format, final Object... args) { 270 | log(String.format(Locale.US, format, args)); 271 | } 272 | 273 | public void log(final String message) { 274 | if (logger != null) { 275 | logger.log(message); 276 | } 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/SystemLibraryLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker; 17 | 18 | import android.annotation.SuppressLint; 19 | import android.os.Build; 20 | 21 | @SuppressWarnings("deprecation") 22 | final class SystemLibraryLoader implements ReLinker.LibraryLoader { 23 | @Override 24 | public void loadLibrary(final String libraryName) { 25 | System.loadLibrary(libraryName); 26 | } 27 | 28 | @SuppressLint ("UnsafeDynamicallyLoadedCode") 29 | @Override 30 | public void loadPath(final String libraryPath) { 31 | System.load(libraryPath); 32 | } 33 | 34 | @Override 35 | public String mapLibraryName(final String libraryName) { 36 | if (libraryName.startsWith("lib") && libraryName.endsWith(".so")) { 37 | // Already mapped 38 | return libraryName; 39 | } 40 | 41 | return System.mapLibraryName(libraryName); 42 | } 43 | 44 | @Override 45 | public String unmapLibraryName(String mappedLibraryName) { 46 | // Assuming libname.so 47 | return mappedLibraryName.substring(3, mappedLibraryName.length() - 3); 48 | } 49 | 50 | @Override 51 | public String[] supportedAbis() { 52 | if (Build.VERSION.SDK_INT >= 21 && Build.SUPPORTED_ABIS.length > 0) { 53 | return Build.SUPPORTED_ABIS; 54 | } else if (!TextUtils.isEmpty(Build.CPU_ABI2)) { 55 | return new String[] {Build.CPU_ABI, Build.CPU_ABI2}; 56 | } else { 57 | return new String[] {Build.CPU_ABI}; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/TextUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker; 17 | 18 | /** 19 | * Slimmed down version of https://developer.android.com/reference/android/text/TextUtils.html to 20 | * avoid depending on android.text.TextUtils. 21 | */ 22 | final class TextUtils { 23 | private TextUtils() { 24 | } 25 | 26 | /** 27 | * Returns true if the string is null or 0-length. 28 | * 29 | * @param str the string to be examined 30 | * @return true if str is null or zero length 31 | */ 32 | public static boolean isEmpty(CharSequence str) { 33 | return str == null || str.length() == 0; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Dynamic32Structure.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | import java.nio.ByteBuffer; 20 | import java.nio.ByteOrder; 21 | 22 | public class Dynamic32Structure extends Elf.DynamicStructure { 23 | public Dynamic32Structure(final ElfParser parser, final Elf.Header header, 24 | long baseOffset, final int index) throws IOException { 25 | final ByteBuffer buffer = ByteBuffer.allocate(4); 26 | buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 27 | 28 | baseOffset = baseOffset + (index * 8); 29 | tag = parser.readWord(buffer, baseOffset); 30 | val = parser.readWord(buffer, baseOffset + 0x4); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Dynamic64Structure.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | import java.nio.ByteBuffer; 20 | import java.nio.ByteOrder; 21 | 22 | public class Dynamic64Structure extends Elf.DynamicStructure { 23 | public Dynamic64Structure(final ElfParser parser, final Elf.Header header, 24 | long baseOffset, final int index) throws IOException { 25 | final ByteBuffer buffer = ByteBuffer.allocate(8); 26 | buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 27 | 28 | baseOffset = baseOffset + (index * 16); 29 | tag = parser.readLong(buffer, baseOffset); 30 | val = parser.readLong(buffer, baseOffset + 0x8); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Elf.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | 20 | public interface Elf { 21 | abstract class Header { 22 | public static final int ELFCLASS32 = 1; // 32 Bit ELF 23 | public static final int ELFCLASS64 = 2; // 64 Bit ELF 24 | public static final int ELFDATA2MSB = 2; // Big Endian, 2s complement 25 | 26 | public boolean bigEndian; 27 | public int type; 28 | public long phoff; 29 | public long shoff; 30 | public int phentsize; 31 | public int phnum; 32 | public int shentsize; 33 | public int shnum; 34 | public int shstrndx; 35 | 36 | abstract public Elf.SectionHeader getSectionHeader(int index) throws IOException; 37 | abstract public Elf.ProgramHeader getProgramHeader(long index) throws IOException; 38 | abstract public Elf.DynamicStructure getDynamicStructure(long baseOffset, int index) 39 | throws IOException; 40 | } 41 | 42 | abstract class ProgramHeader { 43 | public static final int PT_LOAD = 1; // Loadable segment 44 | public static final int PT_DYNAMIC = 2; // Dynamic linking information 45 | 46 | public long type; 47 | public long offset; 48 | public long vaddr; 49 | public long memsz; 50 | } 51 | 52 | abstract class SectionHeader { 53 | public long info; 54 | } 55 | 56 | abstract class DynamicStructure { 57 | public static final int DT_NULL = 0; // Marks end of structure list 58 | public static final int DT_NEEDED = 1; // Needed library 59 | public static final int DT_STRTAB = 5; // String table 60 | 61 | public long tag; 62 | public long val; // Union with d_ptr 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Elf32Header.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | import java.nio.ByteBuffer; 20 | import java.nio.ByteOrder; 21 | 22 | public class Elf32Header extends Elf.Header { 23 | private final ElfParser parser; 24 | 25 | public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException { 26 | this.bigEndian = bigEndian; 27 | this.parser = parser; 28 | 29 | final ByteBuffer buffer = ByteBuffer.allocate(4); 30 | buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 31 | 32 | type = parser.readHalf(buffer, 0x10); 33 | phoff = parser.readWord(buffer, 0x1C); 34 | shoff = parser.readWord(buffer, 0x20); 35 | phentsize = parser.readHalf(buffer, 0x2A); 36 | phnum = parser.readHalf(buffer, 0x2C); 37 | shentsize = parser.readHalf(buffer, 0x2E); 38 | shnum = parser.readHalf(buffer, 0x30); 39 | shstrndx = parser.readHalf(buffer, 0x32); 40 | } 41 | 42 | @Override 43 | public Elf.SectionHeader getSectionHeader(final int index) throws IOException { 44 | return new Section32Header(parser, this, index); 45 | } 46 | 47 | @Override 48 | public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { 49 | return new Program32Header(parser, this, index); 50 | } 51 | 52 | @Override 53 | public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) 54 | throws IOException { 55 | return new Dynamic32Structure(parser, this, baseOffset, index); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Elf64Header.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | import java.nio.ByteBuffer; 20 | import java.nio.ByteOrder; 21 | 22 | public class Elf64Header extends Elf.Header { 23 | private final ElfParser parser; 24 | 25 | public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException { 26 | this.bigEndian = bigEndian; 27 | this.parser = parser; 28 | 29 | final ByteBuffer buffer = ByteBuffer.allocate(8); 30 | buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 31 | 32 | type = parser.readHalf(buffer, 0x10); 33 | phoff = parser.readLong(buffer, 0x20); 34 | shoff = parser.readLong(buffer, 0x28); 35 | phentsize = parser.readHalf(buffer, 0x36); 36 | phnum = parser.readHalf(buffer, 0x38); 37 | shentsize = parser.readHalf(buffer, 0x3A); 38 | shnum = parser.readHalf(buffer, 0x3C); 39 | shstrndx = parser.readHalf(buffer, 0x3E); 40 | } 41 | 42 | @Override 43 | public Elf.SectionHeader getSectionHeader(final int index) throws IOException { 44 | return new Section64Header(parser, this, index); 45 | } 46 | 47 | @Override 48 | public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { 49 | return new Program64Header(parser, this, index); 50 | } 51 | 52 | @Override 53 | public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) 54 | throws IOException { 55 | return new Dynamic64Structure(parser, this, baseOffset, index); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/ElfParser.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.Closeable; 19 | import java.io.EOFException; 20 | import java.io.File; 21 | import java.io.FileInputStream; 22 | import java.io.FileNotFoundException; 23 | import java.io.IOException; 24 | import java.nio.ByteBuffer; 25 | import java.nio.ByteOrder; 26 | import java.nio.channels.FileChannel; 27 | import java.util.ArrayList; 28 | import java.util.Collections; 29 | import java.util.List; 30 | 31 | public class ElfParser implements Closeable, Elf { 32 | private final int MAGIC = 0x464C457F; 33 | private final FileChannel channel; 34 | 35 | public ElfParser(final File file) throws FileNotFoundException { 36 | if (file == null || !file.exists()) { 37 | throw new IllegalArgumentException("File is null or does not exist"); 38 | } 39 | 40 | final FileInputStream inputStream = new FileInputStream(file); 41 | this.channel = inputStream.getChannel(); 42 | } 43 | 44 | public Elf.Header parseHeader() throws IOException { 45 | channel.position(0L); 46 | 47 | // Read in ELF identification to determine file class and endianness 48 | final ByteBuffer buffer = ByteBuffer.allocate(8); 49 | buffer.order(ByteOrder.LITTLE_ENDIAN); 50 | if (readWord(buffer, 0) != MAGIC) { 51 | throw new IllegalArgumentException("Invalid ELF Magic!"); 52 | } 53 | 54 | final short fileClass = readByte(buffer, 0x4); 55 | final boolean bigEndian = (readByte(buffer, 0x5) == Header.ELFDATA2MSB); 56 | if (fileClass == Header.ELFCLASS32) { 57 | return new Elf32Header(bigEndian, this); 58 | } else if (fileClass == Header.ELFCLASS64) { 59 | return new Elf64Header(bigEndian, this); 60 | } 61 | 62 | throw new IllegalStateException("Invalid class type!"); 63 | } 64 | 65 | public List parseNeededDependencies() throws IOException { 66 | channel.position(0); 67 | final List dependencies = new ArrayList(); 68 | final Elf.Header header = parseHeader(); 69 | final ByteBuffer buffer = ByteBuffer.allocate(8); 70 | buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 71 | 72 | long numProgramHeaderEntries = header.phnum; 73 | if (numProgramHeaderEntries == 0xFFFF) { 74 | /** 75 | * Extended Numbering 76 | * 77 | * If the real number of program header table entries is larger than 78 | * or equal to PN_XNUM(0xffff), it is set to sh_info field of the 79 | * section header at index 0, and PN_XNUM is set to e_phnum 80 | * field. Otherwise, the section header at index 0 is zero 81 | * initialized, if it exists. 82 | **/ 83 | final Elf.SectionHeader sectionHeader = header.getSectionHeader(0); 84 | numProgramHeaderEntries = sectionHeader.info; 85 | } 86 | 87 | long dynamicSectionOff = 0; 88 | for (long i = 0; i < numProgramHeaderEntries; ++i) { 89 | final Elf.ProgramHeader programHeader = header.getProgramHeader(i); 90 | if (programHeader.type == ProgramHeader.PT_DYNAMIC) { 91 | dynamicSectionOff = programHeader.offset; 92 | break; 93 | } 94 | } 95 | 96 | if (dynamicSectionOff == 0) { 97 | // No dynamic linking info, nothing to load 98 | return Collections.unmodifiableList(dependencies); 99 | } 100 | 101 | int i = 0; 102 | final List neededOffsets = new ArrayList(); 103 | long vStringTableOff = 0; 104 | Elf.DynamicStructure dynStructure; 105 | do { 106 | dynStructure = header.getDynamicStructure(dynamicSectionOff, i); 107 | if (dynStructure.tag == DynamicStructure.DT_NEEDED) { 108 | neededOffsets.add(dynStructure.val); 109 | } else if (dynStructure.tag == DynamicStructure.DT_STRTAB) { 110 | vStringTableOff = dynStructure.val; // d_ptr union 111 | } 112 | ++i; 113 | } while (dynStructure.tag != DynamicStructure.DT_NULL); 114 | 115 | if (vStringTableOff == 0) { 116 | throw new IllegalStateException("String table offset not found!"); 117 | } 118 | 119 | // Map to file offset 120 | final long stringTableOff = offsetFromVma(header, numProgramHeaderEntries, vStringTableOff); 121 | for (final Long strOff : neededOffsets) { 122 | dependencies.add(readString(buffer, stringTableOff + strOff)); 123 | } 124 | 125 | return dependencies; 126 | } 127 | 128 | private long offsetFromVma(final Elf.Header header, final long numEntries, final long vma) 129 | throws IOException { 130 | for (long i = 0; i < numEntries; ++i) { 131 | final Elf.ProgramHeader programHeader = header.getProgramHeader(i); 132 | if (programHeader.type == ProgramHeader.PT_LOAD) { 133 | // Within memsz instead of filesz to be more tolerant 134 | if (programHeader.vaddr <= vma 135 | && vma <= programHeader.vaddr + programHeader.memsz) { 136 | return vma - programHeader.vaddr + programHeader.offset; 137 | } 138 | } 139 | } 140 | 141 | throw new IllegalStateException("Could not map vma to file offset!"); 142 | } 143 | 144 | @Override 145 | public void close() throws IOException { 146 | this.channel.close(); 147 | } 148 | 149 | protected String readString(final ByteBuffer buffer, long offset) throws IOException { 150 | final StringBuilder builder = new StringBuilder(); 151 | short c; 152 | while ((c = readByte(buffer, offset++)) != 0) { 153 | builder.append((char) c); 154 | } 155 | 156 | return builder.toString(); 157 | } 158 | 159 | protected long readLong(final ByteBuffer buffer, final long offset) throws IOException { 160 | read(buffer, offset, 8); 161 | return buffer.getLong(); 162 | } 163 | 164 | protected long readWord(final ByteBuffer buffer, final long offset) throws IOException { 165 | read(buffer, offset, 4); 166 | return buffer.getInt() & 0xFFFFFFFFL; 167 | } 168 | 169 | protected int readHalf(final ByteBuffer buffer, final long offset) throws IOException { 170 | read(buffer, offset, 2); 171 | return buffer.getShort() & 0xFFFF; 172 | } 173 | 174 | protected short readByte(final ByteBuffer buffer, final long offset) throws IOException { 175 | read(buffer, offset, 1); 176 | return (short) (buffer.get() & 0xFF); 177 | } 178 | 179 | protected void read(final ByteBuffer buffer, long offset, final int length) throws IOException { 180 | buffer.position(0); 181 | buffer.limit(length); 182 | long bytesRead = 0; 183 | while (bytesRead < length) { 184 | final int read = channel.read(buffer, offset + bytesRead); 185 | if (read == -1) { 186 | throw new EOFException(); 187 | } 188 | 189 | bytesRead += read; 190 | } 191 | buffer.position(0); 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Program32Header.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | import java.nio.ByteBuffer; 20 | import java.nio.ByteOrder; 21 | 22 | public class Program32Header extends Elf.ProgramHeader { 23 | public Program32Header(final ElfParser parser, final Elf.Header header, final long index) 24 | throws IOException { 25 | final ByteBuffer buffer = ByteBuffer.allocate(4); 26 | buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 27 | 28 | final long baseOffset = header.phoff + (index * header.phentsize); 29 | type = parser.readWord(buffer, baseOffset); 30 | offset = parser.readWord(buffer, baseOffset + 0x4); 31 | vaddr = parser.readWord(buffer, baseOffset + 0x8); 32 | memsz = parser.readWord(buffer, baseOffset + 0x14); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Program64Header.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | import java.nio.ByteBuffer; 20 | import java.nio.ByteOrder; 21 | 22 | public class Program64Header extends Elf.ProgramHeader { 23 | public Program64Header(final ElfParser parser, final Elf.Header header, final long index) 24 | throws IOException { 25 | final ByteBuffer buffer = ByteBuffer.allocate(8); 26 | buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 27 | 28 | final long baseOffset = header.phoff + (index * header.phentsize); 29 | type = parser.readWord(buffer, baseOffset); 30 | offset = parser.readLong(buffer, baseOffset + 0x8); 31 | vaddr = parser.readLong(buffer, baseOffset + 0x10); 32 | memsz = parser.readLong(buffer, baseOffset + 0x28); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Section32Header.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | import java.nio.ByteBuffer; 20 | import java.nio.ByteOrder; 21 | 22 | public class Section32Header extends Elf.SectionHeader { 23 | public Section32Header(final ElfParser parser, final Elf.Header header, final int index) 24 | throws IOException { 25 | final ByteBuffer buffer = ByteBuffer.allocate(4); 26 | buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 27 | 28 | info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /relinker/src/main/java/com/getkeepsafe/relinker/elf/Section64Header.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker.elf; 17 | 18 | import java.io.IOException; 19 | import java.nio.ByteBuffer; 20 | import java.nio.ByteOrder; 21 | 22 | public class Section64Header extends Elf.SectionHeader { 23 | public Section64Header(final ElfParser parser, final Elf.Header header, final int index) 24 | throws IOException { 25 | final ByteBuffer buffer = ByteBuffer.allocate(8); 26 | buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); 27 | 28 | info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /relinker/src/test/java/com/getkeepsafe/relinker/ApkLibraryInstallerTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker; 17 | 18 | import android.content.Context; 19 | import android.content.pm.ApplicationInfo; 20 | 21 | import org.junit.Before; 22 | import org.junit.Rule; 23 | import org.junit.Test; 24 | import org.junit.rules.TemporaryFolder; 25 | 26 | import java.io.EOFException; 27 | import java.io.File; 28 | import java.io.FileInputStream; 29 | import java.io.IOException; 30 | 31 | import static org.hamcrest.MatcherAssert.assertThat; 32 | import static org.hamcrest.core.Is.is; 33 | import static org.junit.Assert.assertEquals; 34 | import static org.mockito.Mockito.mock; 35 | import static org.mockito.Mockito.verify; 36 | import static org.mockito.Mockito.when; 37 | 38 | public class ApkLibraryInstallerTest { 39 | @Rule 40 | public TemporaryFolder tempFolder = new TemporaryFolder(); 41 | 42 | @Before 43 | public void setUp() throws IOException { 44 | tempFolder.create(); 45 | } 46 | 47 | @Test 48 | public void installsCorrectly() throws IOException { 49 | final Context context = mock(Context.class); 50 | final ApplicationInfo appInfo = mock(ApplicationInfo.class); 51 | final ReLinkerInstance instance = mock(ReLinkerInstance.class); 52 | final ApkLibraryInstaller installer = new ApkLibraryInstaller(); 53 | final File destination = tempFolder.newFile("test"); 54 | final String[] abis = new String[] {"x86"}; 55 | 56 | when(context.getApplicationInfo()).thenReturn(appInfo); 57 | appInfo.sourceDir = getClass().getResource("/fake.apk").getFile(); 58 | 59 | installer.installLibrary(context, abis, "libtest.so", destination, instance); 60 | verify(context).getApplicationInfo(); 61 | assertThat(fileToString(destination), is("works!")); 62 | } 63 | 64 | @Test 65 | public void throwsMissingLibraryExceptionWhenABIIsMissing() throws IOException { 66 | final Context context = mock(Context.class); 67 | final ApplicationInfo appInfo = mock(ApplicationInfo.class); 68 | final ReLinkerInstance instance = mock(ReLinkerInstance.class); 69 | final ApkLibraryInstaller installer = new ApkLibraryInstaller(); 70 | final File destination = tempFolder.newFile("test"); 71 | final String[] abis = new String[] {"armeabi-v7a"}; // For unit test running on a developer machine this is normally x86 72 | 73 | when(context.getApplicationInfo()).thenReturn(appInfo); 74 | appInfo.sourceDir = getClass().getResource("/fake.apk").getFile(); 75 | 76 | try { 77 | installer.installLibrary(context, abis, "libtest.so", destination, instance); 78 | } catch (MissingLibraryException e) { 79 | assertEquals("Could not find 'libtest.so'. Looked for: [armeabi-v7a], but only found: [x86].", e.getMessage()); 80 | } 81 | } 82 | 83 | private String fileToString(final File file) throws IOException { 84 | final long size = file.length(); 85 | if (size > Integer.MAX_VALUE) { 86 | throw new IOException("Can't read a file larger than Integer.MAX_VALUE"); 87 | } 88 | 89 | final byte[] data = new byte[(int) size]; 90 | final FileInputStream in = new FileInputStream(file); 91 | try { 92 | int bytesRead = 0; 93 | while (bytesRead < size) { 94 | int read = in.read(data, bytesRead, (int) size - bytesRead); 95 | if (read == -1) { 96 | throw new EOFException(); 97 | } 98 | bytesRead += read; 99 | } 100 | 101 | return new String(data); 102 | } finally { 103 | in.close(); 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /relinker/src/test/java/com/getkeepsafe/relinker/ApkLibraryInstallerWithSplitsTest.java: -------------------------------------------------------------------------------- 1 | package com.getkeepsafe.relinker; 2 | 3 | import android.content.Context; 4 | import android.content.pm.ApplicationInfo; 5 | import android.os.Build; 6 | 7 | import org.junit.Before; 8 | import org.junit.Rule; 9 | import org.junit.Test; 10 | import org.junit.rules.TemporaryFolder; 11 | import org.junit.runner.RunWith; 12 | import org.mockito.Mock; 13 | import org.mockito.MockitoAnnotations; 14 | import org.robolectric.RobolectricTestRunner; 15 | import org.robolectric.annotation.Config; 16 | 17 | import java.io.EOFException; 18 | import java.io.File; 19 | import java.io.FileInputStream; 20 | import java.io.IOException; 21 | 22 | import static org.hamcrest.MatcherAssert.assertThat; 23 | import static org.hamcrest.core.Is.is; 24 | import static org.mockito.Mockito.verify; 25 | import static org.mockito.Mockito.when; 26 | 27 | 28 | @RunWith(RobolectricTestRunner.class) 29 | @Config(sdk = Build.VERSION_CODES.LOLLIPOP) 30 | public class ApkLibraryInstallerWithSplitsTest { 31 | 32 | @Rule 33 | public TemporaryFolder tempFolder = new TemporaryFolder(); 34 | 35 | @Mock Context context; 36 | 37 | @Mock ApplicationInfo applicationInfo; 38 | 39 | @Mock ReLinkerInstance instance; 40 | 41 | private final String[] abis = new String[]{"x86"}; 42 | 43 | private ApkLibraryInstaller subject; 44 | 45 | @Before 46 | public void setUp() throws IOException { 47 | MockitoAnnotations.initMocks(this); 48 | tempFolder.create(); 49 | subject = new ApkLibraryInstaller(); 50 | } 51 | 52 | @Test 53 | public void nullSplitSourceDirInstallCorrectly() throws IOException { 54 | final File destination = tempFolder.newFile("null-test"); 55 | 56 | applicationInfo.sourceDir = getClass().getResource("/fake.apk").getFile(); 57 | applicationInfo.splitSourceDirs = null; 58 | when(context.getApplicationInfo()).thenReturn(applicationInfo); 59 | 60 | subject.installLibrary(context, abis, "libtest.so", destination, instance); 61 | verify(context).getApplicationInfo(); 62 | assertThat(fileToString(destination), is("works!")); 63 | } 64 | 65 | @Test 66 | public void emptySplitSourceDirInstallCorrectly() throws IOException { 67 | final File destination = tempFolder.newFile("empty-test"); 68 | 69 | applicationInfo.sourceDir = getClass().getResource("/fake.apk").getFile(); 70 | applicationInfo.splitSourceDirs = new String[]{}; 71 | when(context.getApplicationInfo()).thenReturn(applicationInfo); 72 | 73 | subject.installLibrary(context, abis, "libtest.so", destination, instance); 74 | verify(context).getApplicationInfo(); 75 | assertThat(fileToString(destination), is("works!")); 76 | } 77 | 78 | @Test 79 | public void apkSplitsInstallCorrectly() throws IOException { 80 | final File destination = tempFolder.newFile("split-test"); 81 | 82 | applicationInfo.sourceDir = "/fake/path/nolib.apk"; 83 | String actualApk = getClass().getResource("/fake.apk").getFile(); 84 | applicationInfo.splitSourceDirs = new String[]{"/another/fake/path/nolib.apk", actualApk}; 85 | when(context.getApplicationInfo()).thenReturn(applicationInfo); 86 | 87 | subject.installLibrary(context, abis, "libtest.so", destination, instance); 88 | verify(context).getApplicationInfo(); 89 | assertThat(fileToString(destination), is("works!")); 90 | } 91 | 92 | private String fileToString(final File file) throws IOException { 93 | final long size = file.length(); 94 | if (size > Integer.MAX_VALUE) { 95 | throw new IOException("Can't read a file larger than Integer.MAX_VALUE"); 96 | } 97 | 98 | final byte[] data = new byte[(int) size]; 99 | final FileInputStream in = new FileInputStream(file); 100 | try { 101 | int bytesRead = 0; 102 | while (bytesRead < size) { 103 | int read = in.read(data, bytesRead, (int) size - bytesRead); 104 | if (read == -1) { 105 | throw new EOFException(); 106 | } 107 | bytesRead += read; 108 | } 109 | 110 | return new String(data); 111 | } finally { 112 | in.close(); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /relinker/src/test/java/com/getkeepsafe/relinker/ReLinkerInstanceTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2015 - 2016 KeepSafe Software, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.getkeepsafe.relinker; 17 | 18 | 19 | import android.content.Context; 20 | 21 | import org.junit.Before; 22 | import org.junit.Rule; 23 | import org.junit.Test; 24 | import org.junit.rules.TemporaryFolder; 25 | import org.junit.runner.RunWith; 26 | import org.mockito.Mock; 27 | import org.robolectric.RobolectricTestRunner; 28 | 29 | import java.io.File; 30 | import java.io.IOException; 31 | 32 | import static org.hamcrest.MatcherAssert.assertThat; 33 | import static org.hamcrest.core.Is.is; 34 | import static org.mockito.Matchers.anyString; 35 | import static org.mockito.Mockito.doThrow; 36 | import static org.mockito.Mockito.times; 37 | import static org.mockito.Mockito.verify; 38 | import static org.mockito.Mockito.when; 39 | import static org.mockito.MockitoAnnotations.initMocks; 40 | 41 | @RunWith(RobolectricTestRunner.class) 42 | public class ReLinkerInstanceTest { 43 | private static final String TEST_LIB = "mylib"; 44 | private static final String TEST_LIB_MAPPED = "libmylib.so"; 45 | private static final String TEST_DIR = "lib"; 46 | 47 | @Mock 48 | Context context; 49 | @Mock 50 | ReLinker.LibraryLoader testLoader; 51 | @Mock 52 | ReLinker.LibraryInstaller testInstaller; 53 | @Rule 54 | public TemporaryFolder tempFolder = new TemporaryFolder(); 55 | 56 | private File libDir; 57 | 58 | @Before 59 | public void setUp() throws IOException { 60 | initMocks(this); 61 | tempFolder.create(); 62 | libDir = tempFolder.getRoot(); 63 | when(context.getDir(TEST_DIR, Context.MODE_PRIVATE)).thenReturn(libDir); 64 | when(testLoader.mapLibraryName(TEST_LIB)).thenReturn(TEST_LIB_MAPPED); 65 | } 66 | 67 | @Test 68 | public void getsCorrectWorkaroundDirectory() { 69 | final ReLinkerInstance instance = new ReLinkerInstance(testLoader, testInstaller); 70 | assertThat(instance.getWorkaroundLibDir(context), is(libDir)); 71 | } 72 | 73 | @Test 74 | public void getsCorrectWorkaroundFile() { 75 | final ReLinkerInstance instance = new ReLinkerInstance(testLoader, testInstaller); 76 | final String libName = testLoader.mapLibraryName(TEST_LIB); 77 | final File libFile = new File(libDir, libName); 78 | assertThat(instance.getWorkaroundLibFile(context, TEST_LIB, null), is(libFile)); 79 | 80 | final File versionedLibFile = new File(libDir, libName + ".2.0"); 81 | assertThat(instance.getWorkaroundLibFile(context, TEST_LIB, "2.0"), is(versionedLibFile)); 82 | } 83 | 84 | @Test 85 | public void cleansupOldLibraryFiles() throws IOException { 86 | final ReLinkerInstance instance = new ReLinkerInstance(testLoader, testInstaller); 87 | final String mappedName = testLoader.mapLibraryName(TEST_LIB); 88 | tempFolder.newFile(mappedName); 89 | tempFolder.newFile(mappedName + ".2.0"); 90 | tempFolder.newFile(mappedName + ".3.4"); 91 | tempFolder.newFile(mappedName + ".4.0"); 92 | 93 | assertThat(libDir.listFiles().length, is(4)); 94 | instance.cleanupOldLibFiles(context, TEST_LIB, "4.0"); 95 | assertThat(libDir.listFiles().length, is(1)); 96 | 97 | tempFolder.newFile(mappedName); 98 | tempFolder.newFile(mappedName + ".2.0"); 99 | tempFolder.newFile(mappedName + ".3.4"); 100 | assertThat(libDir.listFiles().length, is(4)); 101 | instance.cleanupOldLibFiles(context, TEST_LIB, null); 102 | assertThat(libDir.listFiles().length, is(1)); 103 | 104 | tempFolder.newFile(mappedName + ".2.0"); 105 | tempFolder.newFile(mappedName + ".3.4"); 106 | tempFolder.newFile(mappedName + ".4.0"); 107 | assertThat(libDir.listFiles().length, is(4)); 108 | instance.force().cleanupOldLibFiles(context, TEST_LIB, "4.0"); 109 | assertThat(libDir.listFiles().length, is(0)); 110 | } 111 | 112 | @Test 113 | public void loadsLibraryNormally() { 114 | final ReLinkerInstance instance = new ReLinkerInstance(testLoader, testInstaller); 115 | instance.loadLibrary(context, TEST_LIB); 116 | } 117 | 118 | @Test 119 | public void relinksLibrary() { 120 | final ReLinkerInstance instance = new ReLinkerInstance(testLoader, testInstaller); 121 | final File workaroundFile = new File(libDir.getAbsolutePath(), TEST_LIB_MAPPED); 122 | final String[] abis = new String[] {"x86"}; 123 | 124 | doThrow(new UnsatisfiedLinkError("boo")).when(testLoader).loadLibrary(anyString()); 125 | when(testLoader.supportedAbis()).thenReturn(abis); 126 | 127 | instance.loadLibrary(context, TEST_LIB); 128 | verify(testLoader).loadLibrary(TEST_LIB); 129 | verify(testLoader).loadPath(workaroundFile.getAbsolutePath()); 130 | verify(testLoader).supportedAbis(); 131 | verify(testInstaller).installLibrary(context, abis, TEST_LIB_MAPPED, workaroundFile, instance); 132 | 133 | instance.force().loadLibrary(context, TEST_LIB); 134 | verify(testLoader, times(2)).loadLibrary(TEST_LIB); 135 | verify(testLoader, times(2)).loadPath(workaroundFile.getAbsolutePath()); 136 | verify(testLoader, times(2)).supportedAbis(); 137 | verify(testInstaller, times(2)).installLibrary( 138 | context, abis, TEST_LIB_MAPPED, workaroundFile, instance); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /relinker/src/test/java/com/getkeepsafe/relinker/elf/ElfParserTest.java: -------------------------------------------------------------------------------- 1 | package com.getkeepsafe.relinker.elf; 2 | 3 | import org.junit.After; 4 | import org.junit.Test; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | 9 | public class ElfParserTest { 10 | ElfParser elfParser; 11 | 12 | @After 13 | public void tearDown() throws Exception { 14 | if (elfParser != null) 15 | elfParser.close(); 16 | } 17 | 18 | @Test 19 | public void testParseDependenciesDoesNotThrowIllegalArgException() throws IOException { 20 | elfParser = new ElfParser(new File(getClass().getClassLoader().getResource("libdl.so").getFile())); 21 | elfParser.parseNeededDependencies(); 22 | } 23 | } -------------------------------------------------------------------------------- /relinker/src/test/resources/fake.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/relinker/src/test/resources/fake.apk -------------------------------------------------------------------------------- /relinker/src/test/resources/libdl.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/relinker/src/test/resources/libdl.so -------------------------------------------------------------------------------- /relinker/src/test/resources/robolectric.properties: -------------------------------------------------------------------------------- 1 | sdk=16 2 | constants=com.getkeepsafe.relinker.BuildConfig -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /src/main/obj 3 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | repositories { 4 | mavenCentral() 5 | } 6 | 7 | android { 8 | compileSdkVersion 30 9 | 10 | sourceSets { 11 | main { 12 | jniLibs.srcDirs = ['src/main/libs'] 13 | jni.srcDirs = [] 14 | } 15 | } 16 | defaultConfig { 17 | applicationId "com.getkeepsafe.relinker.sample" 18 | //noinspection MinSdkTooLow 19 | minSdkVersion 9 20 | targetSdkVersion 30 21 | versionCode 1 22 | versionName "1.0" 23 | } 24 | buildTypes { 25 | release { 26 | minifyEnabled false 27 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 28 | } 29 | } 30 | } 31 | 32 | dependencies { 33 | implementation project(':relinker') 34 | testImplementation 'junit:junit:4.13.2' 35 | } 36 | 37 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/xiphirx/Documents/dev/android-sdk-macosx/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /sample/src/main/java/com/getkeepsafe/relinker/sample/App.java: -------------------------------------------------------------------------------- 1 | package com.getkeepsafe.relinker.sample; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | 6 | public class App extends Application { 7 | public static Context sContext; 8 | 9 | @Override 10 | public void onCreate() { 11 | super.onCreate(); 12 | sContext = this; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /sample/src/main/java/com/getkeepsafe/relinker/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.getkeepsafe.relinker.sample; 2 | 3 | import android.app.Activity; 4 | import android.content.Context; 5 | import android.os.Bundle; 6 | import android.util.Log; 7 | import android.view.View; 8 | import android.widget.EditText; 9 | import android.widget.TextView; 10 | import android.widget.Toast; 11 | 12 | import com.getkeepsafe.relinker.ReLinker; 13 | import com.getkeepsafe.relinker.elf.Elf; 14 | import com.getkeepsafe.relinker.elf.ElfParser; 15 | 16 | import java.io.DataOutputStream; 17 | import java.io.File; 18 | import java.io.IOException; 19 | import java.util.List; 20 | import java.util.Locale; 21 | 22 | public class MainActivity extends Activity { 23 | private File mLibDir; 24 | private File mWorkaroundDir; 25 | 26 | private EditText version; 27 | 28 | private ReLinker.Logger logcatLogger = new ReLinker.Logger() { 29 | @Override 30 | public void log(String message) { 31 | Log.d("ReLinker", message); 32 | } 33 | }; 34 | 35 | @Override 36 | protected void onCreate(Bundle savedInstanceState) { 37 | super.onCreate(savedInstanceState); 38 | setContentView(R.layout.activity_main); 39 | } 40 | 41 | @Override 42 | protected void onResume() { 43 | super.onResume(); 44 | mLibDir = new File(getApplicationInfo().nativeLibraryDir); 45 | mWorkaroundDir = getDir("lib", Context.MODE_PRIVATE); 46 | updateTree(); 47 | 48 | findViewById(R.id.call).setOnClickListener(new View.OnClickListener() { 49 | @Override 50 | public void onClick(View v) { 51 | call(); 52 | } 53 | }); 54 | 55 | findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() { 56 | @Override 57 | public void onClick(View v) { 58 | try { 59 | final Process process = Runtime.getRuntime().exec("su"); 60 | final DataOutputStream stream = new DataOutputStream(process.getOutputStream()); 61 | stream.writeBytes("rm -r " + mLibDir.getAbsolutePath() + "\n"); 62 | stream.writeBytes("rm -r " + mWorkaroundDir.getAbsolutePath() + "\n"); 63 | stream.writeBytes("exit\n"); 64 | stream.flush(); 65 | process.waitFor(); 66 | 67 | updateTree(); 68 | Runtime.getRuntime().exit(0); 69 | } catch (Throwable e) { 70 | Toast.makeText(MainActivity.this, "You do not have root!", Toast.LENGTH_LONG).show(); 71 | } 72 | } 73 | }); 74 | 75 | version = (EditText) findViewById(R.id.version); 76 | } 77 | 78 | private void call() { 79 | try { 80 | ((TextView) findViewById(R.id.text)).setText(Native.helloJni()); 81 | updateTree(); 82 | } catch (UnsatisfiedLinkError e) { 83 | final String libVersion = version.getText().toString(); 84 | ReLinker.log(logcatLogger) 85 | .force() 86 | .recursively() 87 | .loadLibrary(MainActivity.this, "hellojni", libVersion, 88 | new ReLinker.LoadListener() { 89 | @Override 90 | public void success() { 91 | runOnUiThread(new Runnable() { 92 | @Override 93 | public void run() { 94 | ((TextView) findViewById(R.id.text)).setText(Native.helloJni()); 95 | updateTree(); 96 | } 97 | }); 98 | 99 | new Thread(new Runnable() { 100 | @Override 101 | public void run() { 102 | try { 103 | final String file; 104 | if (libVersion.length() > 0) { 105 | file = "libhellojni.so." + libVersion; 106 | } else { 107 | file = "libhellojni.so"; 108 | } 109 | final File filesDir = getDir("lib", MODE_PRIVATE); 110 | final File lib = new File(filesDir, file); 111 | if (!lib.exists()) return; 112 | 113 | final ElfParser parser = new ElfParser(lib); 114 | final List deps = parser.parseNeededDependencies(); 115 | final StringBuilder builder = new StringBuilder("Library dependencies:\n"); 116 | for (final String str : deps) { 117 | builder.append(str).append(", "); 118 | } 119 | runOnUiThread(new Runnable() { 120 | @Override 121 | public void run() { 122 | ((TextView) findViewById(R.id.deps)).setText(builder.toString()); 123 | } 124 | }); 125 | } catch (IOException e) { 126 | e.printStackTrace(); 127 | } 128 | } 129 | }).start(); 130 | } 131 | 132 | @Override 133 | public void failure(Throwable t) { 134 | runOnUiThread(new Runnable() { 135 | @Override 136 | public void run() { 137 | ((TextView) findViewById(R.id.text)).setText( 138 | "Couldn't load! Report this issue to the github please!"); 139 | } 140 | }); 141 | } 142 | }); 143 | } 144 | } 145 | 146 | private void updateTree() { 147 | final File[] files = mLibDir.listFiles(); 148 | final StringBuilder builder = new StringBuilder(); 149 | builder.append("Current files in the standard lib directory: "); 150 | if (files != null) { 151 | for (final File file : files) { 152 | builder.append(file.getName()).append(", "); 153 | } 154 | } 155 | 156 | builder.append("\n\nCurrent files in the ReLinker lib directory: "); 157 | final File[] relinkerFiles = mWorkaroundDir.listFiles(); 158 | if (relinkerFiles != null) { 159 | for (final File file : relinkerFiles) { 160 | builder.append(file.getName()).append(", "); 161 | } 162 | } 163 | 164 | ((TextView) findViewById(R.id.tree)).setText(builder.toString()); 165 | } 166 | } 167 | -------------------------------------------------------------------------------- /sample/src/main/java/com/getkeepsafe/relinker/sample/Native.java: -------------------------------------------------------------------------------- 1 | package com.getkeepsafe.relinker.sample; 2 | 3 | public class Native { 4 | public static native String helloJni(); 5 | } 6 | -------------------------------------------------------------------------------- /sample/src/main/jni/Android.mk: -------------------------------------------------------------------------------- 1 | include $(call all-subdir-makefiles) 2 | -------------------------------------------------------------------------------- /sample/src/main/jni/Application.mk: -------------------------------------------------------------------------------- 1 | APP_ABI := armeabi armeabi-v7a x86 2 | APP_MODULES := hello hellojni 3 | APP_PLATFORM := android-9 4 | -------------------------------------------------------------------------------- /sample/src/main/jni/hello/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH:= $(call my-dir) 2 | 3 | include $(CLEAR_VARS) 4 | 5 | LOCAL_MODULE := hello 6 | LOCAL_SRC_FILES := hello.cpp 7 | 8 | include $(BUILD_SHARED_LIBRARY) 9 | -------------------------------------------------------------------------------- /sample/src/main/jni/hello/hello.cpp: -------------------------------------------------------------------------------- 1 | extern "C" const char* hello() { 2 | return "Hello from the JNI!"; 3 | } -------------------------------------------------------------------------------- /sample/src/main/jni/hello/hello.h: -------------------------------------------------------------------------------- 1 | extern "C" const char* hello(); 2 | -------------------------------------------------------------------------------- /sample/src/main/jni/hellojni/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/sample/src/main/jni/hellojni/.DS_Store -------------------------------------------------------------------------------- /sample/src/main/jni/hellojni/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH:= $(call my-dir) 2 | 3 | include $(CLEAR_VARS) 4 | 5 | LOCAL_MODULE := hellojni 6 | LOCAL_SRC_FILES := hellojni.cpp 7 | LOCAL_SHARED_LIBRARIES := libhello 8 | 9 | include $(BUILD_SHARED_LIBRARY) 10 | -------------------------------------------------------------------------------- /sample/src/main/jni/hellojni/hellojni.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "../hello/hello.h" 3 | 4 | extern "C" 5 | { 6 | JNIEXPORT jstring 7 | JNICALL Java_com_getkeepsafe_relinker_sample_Native_helloJni(JNIEnv *env, jclass clazz) { 8 | return env->NewStringUTF(hello()); 9 | } 10 | } -------------------------------------------------------------------------------- /sample/src/main/libs/armeabi-v7a/libhello.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/sample/src/main/libs/armeabi-v7a/libhello.so -------------------------------------------------------------------------------- /sample/src/main/libs/armeabi-v7a/libhellojni.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/sample/src/main/libs/armeabi-v7a/libhellojni.so -------------------------------------------------------------------------------- /sample/src/main/libs/armeabi/libhello.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/sample/src/main/libs/armeabi/libhello.so -------------------------------------------------------------------------------- /sample/src/main/libs/armeabi/libhellojni.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/sample/src/main/libs/armeabi/libhellojni.so -------------------------------------------------------------------------------- /sample/src/main/libs/x86/libhello.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/sample/src/main/libs/x86/libhello.so -------------------------------------------------------------------------------- /sample/src/main/libs/x86/libhellojni.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KeepSafe/ReLinker/41a5e0ce54a171b4633380404bb99dece01a6582/sample/src/main/libs/x86/libhellojni.so -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 18 | 19 | 23 | 24 |