Commit aa0a2f77 authored by LoveSy's avatar LoveSy Committed by John Wu

Add inode plt hook APIs

parent e38f35ea
......@@ -40,6 +40,9 @@
[submodule "cxx-rs"]
path = native/src/external/cxx-rs
url = https://github.com/topjohnwu/cxx.git
[submodule "lsplt"]
path = native/src/external/lsplt
url = https://github.com/LSPosed/LSPlt.git
[submodule "termux-elf-cleaner"]
path = tools/termux-elf-cleaner
url = https://github.com/termux/termux-elf-cleaner.git
......@@ -13,7 +13,7 @@ LOCAL_STATIC_LIBRARIES := \
libnanopb \
libsystemproperties \
libphmap \
libxhook \
liblsplt \
libmincrypt \
libmagisk-rs
......
......@@ -361,21 +361,17 @@ LOCAL_SRC_FILES := \
pcre2_workaround.c
include $(BUILD_STATIC_LIBRARY)
# libxhook.a
# liblsplt.a
include $(CLEAR_VARS)
LOCAL_MODULE:= libxhook
LOCAL_C_INCLUDES := $(LOCAL_PATH)/libxhook
LOCAL_MODULE:= liblsplt
LOCAL_C_INCLUDES := $(LOCAL_PATH)/lsplt/lsplt/src/main/jni/include
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_C_INCLUDES)
LOCAL_CFLAGS := -Wall -Wextra -Werror -fvisibility=hidden -D__android_log_print=magisk_log_print
LOCAL_CONLYFLAGS := -std=c11
LOCAL_CPPFLAGS := -std=c++20
LOCAL_STATIC_LIBRARIES := libcxx
LOCAL_SRC_FILES := \
libxhook/xh_log.c \
libxhook/xh_version.c \
libxhook/xh_jni.c \
libxhook/xhook.c \
libxhook/xh_core.c \
libxhook/xh_util.c \
libxhook/xh_elf.c
lsplt/lsplt/src/main/jni/elf_util.cc \
lsplt/lsplt/src/main/jni/lsplt.cc
include $(BUILD_STATIC_LIBRARY)
# libz.a
......
.DS_Store
libxhook/libs/
libxhook/obj/
libbiz/libs/
libbiz/obj/
libtest/libs/
libtest/obj/
#for xhookwrapper
build/
.gradle/
.idea/
local.properties
*.iml
*.log
*.so
xhookwrapper/xhook/libs/
Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
Most source code in xhook are MIT licensed. Some other source code
have BSD-style licenses.
A copy of the MIT License is included in this file.
Source code Licensed under the BSD 2-Clause License
===================================================
tree.h
Copyright 2002 Niels Provos <provos@citi.umich.edu>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Source code Licensed under the BSD 3-Clause License
===================================================
queue.h
Copyright (c) 1991, 1993 The Regents of the University of California.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Terms of the MIT License
========================
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This diff is collapsed.
<p align="center"><img src="https://github.com/iqiyi/xHook/blob/master/docs/xhooklogo.png?raw=true" alt="xhook" width="50%"></p>
# xHook
![](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)
![](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat)
![](https://img.shields.io/badge/release-1.2.0-red.svg?style=flat)
![](https://img.shields.io/badge/Android-4.0%20--%2010-blue.svg?style=flat)
![](https://img.shields.io/badge/arch-armeabi%20%7C%20armeabi--v7a%20%7C%20arm64--v8a%20%7C%20x86%20%7C%20x86__64-blue.svg?style=flat)
[README 中文版](README.zh-CN.md)
[Android PLT hook 概述 中文版](docs/overview/android_plt_hook_overview.zh-CN.md)
xHook is a PLT (Procedure Linkage Table) hook library for Android native ELF (executable and shared libraries).
xHook has been keeping optimized for stability and compatibility.
## Features
* Support Android 4.0 - 10 (API level 14 - 29).
* Support armeabi, armeabi-v7a, arm64-v8a, x86 and x86_64.
* Support **ELF HASH** and **GNU HASH** indexed symbols.
* Support **SLEB128** encoded relocation info.
* Support setting hook info via regular expressions.
* Do not require root permission or any system permissions.
* Do not depends on any third-party shared libraries.
## Build
* Download [Android NDK r16b](https://developer.android.com/ndk/downloads/revision_history.html), set environment PATH. (support for armeabi has been removed since r17)
* Build and install the native libraries.
```
./build_libs.sh
./install_libs.sh
```
## Demo
```
cd ./xhookwrapper/
./gradlew assembleDebug
adb install ./app/build/outputs/apk/debug/app-debug.apk
```
## API
External API header file: `libxhook/jni/xhook.h`
### 1. Register hook info
```c
int xhook_register(const char *pathname_regex_str,
const char *symbol,
void *new_func,
void **old_func);
```
In current process's memory space, in every loaded ELF which pathname matches regular expression `pathname_regex_str`, every PLT entries to `symbol` will be **replaced with** `new_func`. The original one will be saved in `old_func`.
The `new_func` **must** have the same function declaration as the original one.
Return zero if successful, non-zero otherwise.
The regular expression for `pathname_regex_str` only support **POSIX BRE (Basic Regular Expression)**.
### 2. Ignore some hook info
```c
int xhook_ignore(const char *pathname_regex_str,
const char *symbol);
```
Ignore some hook info according to `pathname_regex_str` and `symbol`, from registered hooks by `xhook_register`. If `symbol` is `NULL`, xhook will ignore all symbols from ELF which pathname matches `pathname_regex_str`.
Return zero if successful, non-zero otherwise.
The regular expression for `pathname_regex_str` only support **POSIX BRE**.
### 3. Do hook
```c
int xhook_refresh(int async);
```
Do the real hook operations according to the registered hook info.
Pass `1` to `async` for asynchronous hook. Pass `0` to `async` for synchronous hook.
Return zero if successful, non-zero otherwise.
xhook will keep a global cache for saving the last ELF loading info from `/proc/self/maps`. This cache will also be updated in `xhook_refresh`. With this cache, `xhook_refresh` can determine which ELF is newly loaded. We only need to do hook in these newly loaded ELF.
### 4. Clear cache
```c
void xhook_clear();
```
Clear all cache owned by xhook, reset all global flags to default value.
If you confirm that all PLT entries you want have been hooked, you could call this function to save some memory.
### 5. Enable/Disable debug info
```c
void xhook_enable_debug(int flag);
```
Pass `1` to `flag` for enable debug info. Pass `0` to `flag` for disable. (**disabled** by default)
Debug info will be sent to logcat with tag `xhook`.
### 6. Enable/Disable SFP (segmentation fault protection)
```c
void xhook_enable_sigsegv_protection(int flag);
```
Pass `1` to `flag` for enable SFP. Pass `0` to `flag` for disable. (**enabled** by default)
xhook is NOT a compliant business layer library. We have to calculate the value of some pointers directly. Reading or writing the memory pointed to by these pointers will cause a segmentation fault in some unusual situations and environment. The APP crash rate increased which caused by xhook is about one ten-millionth (0.0000001) according to our test. (The increased crash rate is also related to the ELFs and symbols you need to hook). Finally, we have to use some trick to prevent this harmless crashing. We called it SFP (segmentation fault protection) which consists of: `sigaction()`, `SIGSEGV`, `siglongjmp()` and `sigsetjmp()`.
**You should always enable SFP for release-APP, this will prevent your app from crashing. On the other hand, you should always disable SFP for debug-APP, so you can't miss any common coding mistakes that should be fixed.**
## Examples
```c
//detect memory leaks
xhook_register(".*\\.so$", "malloc", my_malloc, NULL);
xhook_register(".*\\.so$", "calloc", my_calloc, NULL);
xhook_register(".*\\.so$", "realloc", my_realloc, NULL);
xhook_register(".*\\.so$", "free", my_free, NULL);
//inspect sockets lifecycle
xhook_register(".*\\.so$", "getaddrinfo", my_getaddrinfo, NULL);
xhook_register(".*\\.so$", "socket", my_socket, NULL);
xhook_register(".*\\.so$", "setsockopt" my_setsockopt, NULL);
xhook_register(".*\\.so$", "bind", my_bind, NULL);
xhook_register(".*\\.so$", "listen", my_listen, NULL);
xhook_register(".*\\.so$", "connect", my_connect, NULL);
xhook_register(".*\\.so$", "shutdown", my_shutdown, NULL);
xhook_register(".*\\.so$", "close", my_close, NULL);
//filter off and save some android log to local file
xhook_register(".*\\.so$", "__android_log_write", my_log_write, NULL);
xhook_register(".*\\.so$", "__android_log_print", my_log_print, NULL);
xhook_register(".*\\.so$", "__android_log_vprint", my_log_vprint, NULL);
xhook_register(".*\\.so$", "__android_log_assert", my_log_assert, NULL);
//tracking (ignore linker and linker64)
xhook_register("^/system/.*$", "mmap", my_mmap, NULL);
xhook_register("^/vendor/.*$", "munmap", my_munmap, NULL);
xhook_ignore (".*/linker$", "mmap");
xhook_ignore (".*/linker$", "munmap");
xhook_ignore (".*/linker64$", "mmap");
xhook_ignore (".*/linker64$", "munmap");
//defense to some injection attacks
xhook_register(".*com\\.hacker.*\\.so$", "malloc", my_malloc_always_return_NULL, NULL);
xhook_register(".*/libhacker\\.so$", "connect", my_connect_with_recorder, NULL);
//fix some system bug
xhook_register(".*some_vendor.*/libvictim\\.so$", "bad_func", my_nice_func, NULL);
//ignore all hooks in libwebviewchromium.so
xhook_ignore(".*/libwebviewchromium.so$", NULL);
//hook now!
xhook_refresh(1);
```
## Support
1. Check the [xhook-sample](libbiz/jni).
2. Communicate on [GitHub issues](https://github.com/iqiyi/xHook/issues).
3. Mail: <a href="mailto:caikelun@gmail.com">caikelun@gmail.com</a>
4. QQ group: 603635869. QR code:
<p align="left"><img src="docs/qq_group.jpg" alt="qq group" width="300px"></p>
## Contributing
See [xHook Contributing Guide](CONTRIBUTING.md).
## License
xHook is MIT licensed, as found in the [LICENSE](LICENSE) file.
xHook documentation is Creative Commons licensed, as found in the [LICENSE-docs](LICENSE-docs) file.
<p align="center"><img src="https://github.com/iqiyi/xHook/blob/master/docs/xhooklogo.png?raw=true" alt="xhook" width="50%"></p>
# xHook
![](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)
![](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat)
![](https://img.shields.io/badge/release-1.2.0-red.svg?style=flat)
![](https://img.shields.io/badge/Android-4.0%20--%2010-blue.svg?style=flat)
![](https://img.shields.io/badge/arch-armeabi%20%7C%20armeabi--v7a%20%7C%20arm64--v8a%20%7C%20x86%20%7C%20x86__64-blue.svg?style=flat)
[README English Version](README.md)
[Android PLT hook 概述 中文版](docs/overview/android_plt_hook_overview.zh-CN.md)
xHook 是一个针对 Android 平台 ELF (可执行文件和动态库) 的 PLT (Procedure Linkage Table) hook 库。
xHook 一直在稳定性和兼容性方面做着持续的优化。
## 特征
* 支持 Android 4.0 - 10(API level 14 - 29)。
* 支持 armeabi,armeabi-v7a,arm64-v8a,x86 和 x86_64。
* 支持 **ELF HASH****GNU HASH** 索引的符号。
* 支持 **SLEB128** 编码的重定位信息。
* 支持通过正则表达式批量设置 hook 信息。
* 不需要 root 权限或任何系统权限。
* 不依赖于任何的第三方动态库。
## 编译
* 下载 [Android NDK r16b](https://developer.android.com/ndk/downloads/revision_history.html),设置 PATH 环境变量。(对 armeabi 的支持,从 r17 版本开始被移除了)
* 编译和安装 native 库。
```
./build_libs.sh
./install_libs.sh
```
## Demo
```
cd ./xhookwrapper/
./gradlew assembleDebug
adb install ./app/build/outputs/apk/debug/app-debug.apk
```
## API
外部 API 头文件: `libxhook/jni/xhook.h`
### 1. 注册 hook 信息
```c
int xhook_register(const char *pathname_regex_str,
const char *symbol,
void *new_func,
void **old_func);
```
在当前进程的内存空间中,在每一个符合正则表达式 `pathname_regex_str` 的已加载ELF中,每一个调用 `symbol` 的 PLT 入口点的地址值都将给替换成 `new_func`。之前的 PLT 入口点的地址值将被保存在 `old_func` 中。
`new_func` 必须具有和原函数同样的函数声明。
成功返回 0,失败返回 非0。
`pathname_regex_str` 只支持 **POSIX BRE (Basic Regular Expression)** 定义的正则表达式语法。
### 2. 忽略部分 hook 信息
```c
int xhook_ignore(const char *pathname_regex_str,
const char *symbol);
```
根据 `pathname_regex_str``symbol`,从已经通过 `xhook_register` 注册的 hook 信息中,忽略一部分 hook 信息。如果 `symbol``NULL`,xhook 将忽略所有路径名符合正则表达式 `pathname_regex_str` 的 ELF。
成功返回 0,失败返回 非0。
`pathname_regex_str` 只支持 **POSIX BRE** 定义的正则表达式语法。
### 3. 执行 hook
```c
int xhook_refresh(int async);
```
根据前面注册的 hook 信息,执行真正的 hook 操作。
`async` 参数传 `1` 表示执行异步的 hook 操作,传 `0` 表示执行同步的 hook 操作。
成功返回 0,失败返回 非0。
xhook 在内部维护了一个全局的缓存,用于保存最后一次从 `/proc/self/maps` 读取到的 ELF 加载信息。每次一调用 `xhook_refresh` 函数,这个缓存都将被更新。xhook 使用这个缓存来判断哪些 ELF 是这次新被加载到内存中的。我们每次只需要针对这些新加载的 ELF 做 hook 就可以了。
### 4. 清除缓存
```c
void xhook_clear();
```
清除 xhook 的缓存,重置所有的全局标示。
如果你确定你需要的所有 PLT 入口点都已经被替换了,你可以调用这个函数来释放和节省一些内存空间。
### 5. 启用/禁用 调试信息
```c
void xhook_enable_debug(int flag);
```
`flag` 参数传 `1` 表示启用调试信息,传 `0` 表示禁用调试信息。 (默认为:**禁用**)
调试信息将被输出到 logcat,对应的 TAG 为:`xhook`
### 6. 启用/禁用 SFP (段错误保护)
```c
void xhook_enable_sigsegv_protection(int flag);
```
`flag` 参数传 `1` 表示启用 SFP,传 `0` 表示禁用 SFP。 (默认为:**启用**)
xhook 并不是一个常规的业务层的动态库。在 xhook 中,我们不得不直接计算一些内存指针的值。在一些极端的情况和环境下,读或者写这些指针指向的内存会发生段错误。根据我们的测试,xhook 的行为将导致 APP 崩溃率增加 “一千万分之一” (0.0000001)。(具体崩溃率可能会增加多少,也和你想要 hook 的库和符号有关)。最终,我们不得不使用某些方法来防止这些无害的崩溃。我们叫它SFP (段错误保护),它是由这些调用和值组成的:`sigaction()``SIGSEGV``siglongjmp()``sigsetjmp()`
**在 release 版本的 APP 中,你应该始终启用 SFP,这能防止你的 APP 因为 xhook 而崩溃。在 debug 版本的 APP 中,你应该始终禁用 SFP,这样你就不会丢失那些一般性的编码失误导致的段错误,这些段错误是应该被修复的。**
## 例子
```c
//监测内存泄露
xhook_register(".*\\.so$", "malloc", my_malloc, NULL);
xhook_register(".*\\.so$", "calloc", my_calloc, NULL);
xhook_register(".*\\.so$", "realloc", my_realloc, NULL);
xhook_register(".*\\.so$", "free", my_free, NULL);
//监控 sockets 生命周期
xhook_register(".*\\.so$", "getaddrinfo", my_getaddrinfo, NULL);
xhook_register(".*\\.so$", "socket", my_socket, NULL);
xhook_register(".*\\.so$", "setsockopt" my_setsockopt, NULL);
xhook_register(".*\\.so$", "bind", my_bind, NULL);
xhook_register(".*\\.so$", "listen", my_listen, NULL);
xhook_register(".*\\.so$", "connect", my_connect, NULL);
xhook_register(".*\\.so$", "shutdown", my_shutdown, NULL);
xhook_register(".*\\.so$", "close", my_close, NULL);
//过滤出和保存部分安卓 log 到本地文件
xhook_register(".*\\.so$", "__android_log_write", my_log_write, NULL);
xhook_register(".*\\.so$", "__android_log_print", my_log_print, NULL);
xhook_register(".*\\.so$", "__android_log_vprint", my_log_vprint, NULL);
xhook_register(".*\\.so$", "__android_log_assert", my_log_assert, NULL);
//追踪某些调用 (忽略 linker 和 linker64)
xhook_register("^/system/.*$", "mmap", my_mmap, NULL);
xhook_register("^/vendor/.*$", "munmap", my_munmap, NULL);
xhook_ignore (".*/linker$", "mmap");
xhook_ignore (".*/linker$", "munmap");
xhook_ignore (".*/linker64$", "mmap");
xhook_ignore (".*/linker64$", "munmap");
//防御某些注入攻击
xhook_register(".*com\\.hacker.*\\.so$", "malloc", my_malloc_always_return_NULL, NULL);
xhook_register(".*/libhacker\\.so$", "connect", my_connect_with_recorder, NULL);
//修复某些系统 bug
xhook_register(".*some_vendor.*/libvictim\\.so$", "bad_func", my_nice_func, NULL);
//忽略 libwebviewchromium.so 的所有 hook 信息
xhook_ignore(".*/libwebviewchromium.so$", NULL);
//现在执行 hook!
xhook_refresh(1);
```
## 技术支持
1. 查看 [xhook-sample](libbiz/jni)
2.[GitHub issues](https://github.com/iqiyi/xHook/issues) 交流。
3. 邮件: <a href="mailto:caikelun@gmail.com">caikelun@gmail.com</a>
5. QQ 群: 603635869。二维码:
<p align="left"><img src="docs/qq_group.jpg" alt="qq group" width="320px"></p>
## 贡献
请阅读 [xHook Contributing Guide](CONTRIBUTING.md)
## 许可证
xHook 使用 [MIT 许可证](LICENSE)
xHook 的文档使用 [Creative Commons 许可证](LICENSE-docs)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#ifndef XH_CORE_H
#define XH_CORE_H 1
#ifdef __cplusplus
extern "C" {
#endif
int xh_core_register(const char *pathname_regex_str, const char *symbol,
void *new_func, void **old_func);
int xh_core_ignore(const char *pathname_regex_str, const char *symbol);
int xh_core_refresh(int async);
void xh_core_clear();
void xh_core_enable_debug(int flag);
void xh_core_enable_sigsegv_protection(int flag);
#ifdef __cplusplus
}
#endif
#endif
This diff is collapsed.
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#ifndef XH_ELF_H
#define XH_ELF_H 1
#include <stdint.h>
#include <elf.h>
#include <link.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
const char *pathname;
ElfW(Addr) base_addr;
ElfW(Addr) bias_addr;
ElfW(Ehdr) *ehdr;
ElfW(Phdr) *phdr;
ElfW(Dyn) *dyn; //.dynamic
ElfW(Word) dyn_sz;
const char *strtab; //.dynstr (string-table)
ElfW(Sym) *symtab; //.dynsym (symbol-index to string-table's offset)
ElfW(Addr) relplt; //.rel.plt or .rela.plt
ElfW(Word) relplt_sz;
ElfW(Addr) reldyn; //.rel.dyn or .rela.dyn
ElfW(Word) reldyn_sz;
ElfW(Addr) relandroid; //android compressed rel or rela
ElfW(Word) relandroid_sz;
//for ELF hash
uint32_t *bucket;
uint32_t bucket_cnt;
uint32_t *chain;
uint32_t chain_cnt; //invalid for GNU hash
//append for GNU hash
uint32_t symoffset;
ElfW(Addr) *bloom;
uint32_t bloom_sz;
uint32_t bloom_shift;
int is_use_rela;
int is_use_gnu_hash;
} xh_elf_t;
int xh_elf_init(xh_elf_t *self, uintptr_t base_addr, const char *pathname);
int xh_elf_hook(xh_elf_t *self, const char *symbol, void *new_func, void **old_func);
int xh_elf_check_elfheader(uintptr_t base_addr);
#ifdef __cplusplus
}
#endif
#endif
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#ifndef XH_ERRNO_H
#define XH_ERRNO_H 1
#define XH_ERRNO_UNKNOWN 1001
#define XH_ERRNO_INVAL 1002
#define XH_ERRNO_NOMEM 1003
#define XH_ERRNO_REPEAT 1004
#define XH_ERRNO_NOTFND 1005
#define XH_ERRNO_BADMAPS 1006
#define XH_ERRNO_FORMAT 1007
#define XH_ERRNO_ELFINIT 1008
#define XH_ERRNO_SEGVERR 1009
#endif
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#include <jni.h>
#include "xhook.h"
#define JNI_API_DEF(f) Java_com_qiyi_xhook_NativeHandler_##f
JNIEXPORT jint JNI_API_DEF(refresh)(JNIEnv *env, jobject obj, jboolean async)
{
(void)env;
(void)obj;
return xhook_refresh(async ? 1 : 0);
}
JNIEXPORT void JNI_API_DEF(clear)(JNIEnv *env, jobject obj)
{
(void)env;
(void)obj;
xhook_clear();
}
JNIEXPORT void JNI_API_DEF(enableDebug)(JNIEnv *env, jobject obj, jboolean flag)
{
(void)env;
(void)obj;
xhook_enable_debug(flag ? 1 : 0);
}
JNIEXPORT void JNI_API_DEF(enableSigSegvProtection)(JNIEnv *env, jobject obj, jboolean flag)
{
(void)env;
(void)obj;
xhook_enable_sigsegv_protection(flag ? 1 : 0);
}
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#include <android/log.h>
#include "xh_log.h"
android_LogPriority xh_log_priority = ANDROID_LOG_WARN;
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#ifndef XH_LOG_H
#define XH_LOG_H 1
#include <android/log.h>
#ifdef __cplusplus
extern "C" {
#endif
extern android_LogPriority xh_log_priority;
#define XH_LOG_TAG "xhook"
#define XH_LOG_DEBUG(fmt, ...) do{if(xh_log_priority <= ANDROID_LOG_DEBUG) __android_log_print(ANDROID_LOG_DEBUG, XH_LOG_TAG, fmt, ##__VA_ARGS__);}while(0)
#define XH_LOG_INFO(fmt, ...) do{if(xh_log_priority <= ANDROID_LOG_INFO) __android_log_print(ANDROID_LOG_INFO, XH_LOG_TAG, fmt, ##__VA_ARGS__);}while(0)
#define XH_LOG_WARN(fmt, ...) do{if(xh_log_priority <= ANDROID_LOG_WARN) __android_log_print(ANDROID_LOG_WARN, XH_LOG_TAG, fmt, ##__VA_ARGS__);}while(0)
#define XH_LOG_ERROR(fmt, ...) do{if(xh_log_priority <= ANDROID_LOG_ERROR) __android_log_print(ANDROID_LOG_ERROR, XH_LOG_TAG, fmt, ##__VA_ARGS__);}while(0)
#ifdef __cplusplus
}
#endif
#endif
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#include <unistd.h>
#include <stdint.h>
#include <inttypes.h>
#include <elf.h>
#include <link.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include "xh_util.h"
#include "xh_errno.h"
#include "xh_log.h"
#define PAGE_START(addr) ((addr) & PAGE_MASK)
#define PAGE_END(addr) (PAGE_START(addr + sizeof(uintptr_t) - 1) + PAGE_SIZE)
#define PAGE_COVER(addr) (PAGE_END(addr) - PAGE_START(addr))
int xh_util_get_mem_protect(uintptr_t addr, size_t len, const char *pathname, unsigned int *prot)
{
uintptr_t start_addr = addr;
uintptr_t end_addr = addr + len;
FILE *fp;
char line[512];
uintptr_t start, end;
char perm[5];
int load0 = 1;
int found_all = 0;
*prot = 0;
if(NULL == (fp = fopen("/proc/self/maps", "r"))) return XH_ERRNO_BADMAPS;
while(fgets(line, sizeof(line), fp))
{
if(NULL != pathname)
if(NULL == strstr(line, pathname)) continue;
if(sscanf(line, "%"PRIxPTR"-%"PRIxPTR" %4s ", &start, &end, perm) != 3) continue;
if(perm[3] != 'p') continue;
if(start_addr >= start && start_addr < end)
{
if(load0)
{
//first load segment
if(perm[0] == 'r') *prot |= PROT_READ;
if(perm[1] == 'w') *prot |= PROT_WRITE;
if(perm[2] == 'x') *prot |= PROT_EXEC;
load0 = 0;
}
else
{
//others
if(perm[0] != 'r') *prot &= ~PROT_READ;
if(perm[1] != 'w') *prot &= ~PROT_WRITE;
if(perm[2] != 'x') *prot &= ~PROT_EXEC;
}
if(end_addr <= end)
{
found_all = 1;
break; //finished
}
else
{
start_addr = end; //try to find the next load segment
}
}
}
fclose(fp);
if(!found_all) return XH_ERRNO_SEGVERR;
return 0;
}
int xh_util_get_addr_protect(uintptr_t addr, const char *pathname, unsigned int *prot)
{
return xh_util_get_mem_protect(addr, sizeof(addr), pathname, prot);
}
int xh_util_set_addr_protect(uintptr_t addr, unsigned int prot)
{
if(0 != mprotect((void *)PAGE_START(addr), PAGE_COVER(addr), (int)prot))
return 0 == errno ? XH_ERRNO_UNKNOWN : errno;
return 0;
}
void xh_util_flush_instruction_cache(uintptr_t addr)
{
__builtin___clear_cache((void *)PAGE_START(addr), (void *)PAGE_END(addr));
}
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#ifndef XH_UTILS_H
#define XH_UTILS_H 1
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__LP64__)
#define XH_UTIL_FMT_LEN "16"
#define XH_UTIL_FMT_X "llx"
#else
#define XH_UTIL_FMT_LEN "8"
#define XH_UTIL_FMT_X "x"
#endif
#define XH_UTIL_FMT_FIXED_X XH_UTIL_FMT_LEN XH_UTIL_FMT_X
#define XH_UTIL_FMT_FIXED_S XH_UTIL_FMT_LEN "s"
int xh_util_get_mem_protect(uintptr_t addr, size_t len, const char *pathname, unsigned int *prot);
int xh_util_get_addr_protect(uintptr_t addr, const char *pathname, unsigned int *prot);
int xh_util_set_addr_protect(uintptr_t addr, unsigned int prot);
void xh_util_flush_instruction_cache(uintptr_t addr);
#ifdef __cplusplus
}
#endif
#endif
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#include "xh_version.h"
#define XH_VERSION_MAJOR 1
#define XH_VERSION_MINOR 2
#define XH_VERSION_EXTRA 0
#define XH_VERSION ((XH_VERSION_MAJOR << 16) | (XH_VERSION_MINOR << 8) | (XH_VERSION_EXTRA))
#define XH_VERSION_TO_STR_HELPER(x) #x
#define XH_VERSION_TO_STR(x) XH_VERSION_TO_STR_HELPER(x)
#define XH_VERSION_STR XH_VERSION_TO_STR(XH_VERSION_MAJOR) "." \
XH_VERSION_TO_STR(XH_VERSION_MINOR) "." \
XH_VERSION_TO_STR(XH_VERSION_EXTRA)
#if defined(__arm__)
#define XH_VERSION_ARCH "arm"
#elif defined(__aarch64__)
#define XH_VERSION_ARCH "aarch64"
#elif defined(__i386__)
#define XH_VERSION_ARCH "x86"
#elif defined(__x86_64__)
#define XH_VERSION_ARCH "x86_64"
#else
#define XH_VERSION_ARCH "unknown"
#endif
#define XH_VERSION_STR_FULL "libxhook "XH_VERSION_STR" ("XH_VERSION_ARCH")"
unsigned int xh_version()
{
return XH_VERSION;
}
const char *xh_version_str()
{
return XH_VERSION_STR;
}
const char *xh_version_str_full()
{
return XH_VERSION_STR_FULL;
}
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#ifndef XH_VERSION_H
#define XH_VERSION_H 1
#ifdef __cplusplus
extern "C" {
#endif
unsigned int xh_version();
const char *xh_version_str();
const char *xh_version_str_full();
#ifdef __cplusplus
}
#endif
#endif
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#include "xh_core.h"
#include "xhook.h"
int xhook_register(const char *pathname_regex_str, const char *symbol,
void *new_func, void **old_func)
{
return xh_core_register(pathname_regex_str, symbol, new_func, old_func);
}
int xhook_ignore(const char *pathname_regex_str, const char *symbol)
{
return xh_core_ignore(pathname_regex_str, symbol);
}
int xhook_refresh(int async)
{
return xh_core_refresh(async);
}
void xhook_clear()
{
return xh_core_clear();
}
void xhook_enable_debug(int flag)
{
return xh_core_enable_debug(flag);
}
void xhook_enable_sigsegv_protection(int flag)
{
return xh_core_enable_sigsegv_protection(flag);
}
// Copyright (c) 2018-present, iQIYI, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Created by caikelun on 2018-04-11.
#ifndef XHOOK_H
#define XHOOK_H 1
#ifdef __cplusplus
extern "C" {
#endif
#define XHOOK_EXPORT __attribute__((visibility("default")))
int xhook_register(const char *pathname_regex_str, const char *symbol,
void *new_func, void **old_func) XHOOK_EXPORT;
int xhook_ignore(const char *pathname_regex_str, const char *symbol) XHOOK_EXPORT;
int xhook_refresh(int async) XHOOK_EXPORT;
void xhook_clear() XHOOK_EXPORT;
void xhook_enable_debug(int flag) XHOOK_EXPORT;
void xhook_enable_sigsegv_protection(int flag) XHOOK_EXPORT;
#ifdef __cplusplus
}
#endif
#endif
Subproject commit d935c30d149f1d5cf934505c37bfdb5f5601572d
......@@ -236,6 +236,14 @@ struct Api {
// If `symbol` is nullptr, then all symbols will be excluded.
void pltHookExclude(const char *regex, const char *symbol);
// For ELFs loaded in memory matching `inode`, replace function `symbol` with `newFunc`.
// If `oldFunc` is not nullptr, the original function pointer will be saved to `oldFunc`.
void pltHookRegisterInode(ino_t inode, const char *symbol, void *newFunc, void **oldFunc);
// For ELFs loaded in memory matching `inode`, exclude hooks registered for `symbol`.
// If `symbol` is nullptr, then all symbols will be excluded.
void pltHookExcludeInode(ino_t inode, const char *symbol);
// Commit all the hooks that was previously registered.
// Returns false if an error occurred.
bool pltHookCommit();
......@@ -303,6 +311,8 @@ struct api_table {
int (*getModuleDir)(void * /* impl */);
uint32_t (*getFlags)(void * /* impl */);
bool (*exemptFd)(int);
void (*pltHookRegisterInode)(ino_t, const char *, void *, void **);
void (*pltHookExcludeInode)(ino_t, const char *);
};
template <class T>
......@@ -332,6 +342,12 @@ inline uint32_t Api::getFlags() {
inline bool Api::exemptFd(int fd) {
return tbl->exemptFd != nullptr && tbl->exemptFd(fd);
}
inline void Api::pltHookRegisterInode(ino_t inode, const char *symbol, void *newFunc, void **oldFunc) {
if (tbl->pltHookExcludeInode) tbl->pltHookRegisterInode(inode, symbol, newFunc, oldFunc);
}
inline void Api::pltHookExcludeInode(ino_t inode, const char *symbol) {
if (tbl->pltHookExcludeInode) tbl->pltHookExcludeInode(inode, symbol);
}
inline void Api::hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods) {
if (tbl->hookJniNativeMethods) tbl->hookJniNativeMethods(env, className, methods, numMethods);
}
......
......@@ -4,7 +4,7 @@
#include <bitset>
#include <list>
#include <xhook.h>
#include <lsplt.hpp>
#include <base.hpp>
#include <flags.h>
......@@ -22,7 +22,7 @@ using xstring = jni_hook::string;
// Extreme verbose logging
//#define ZLOGV(...) ZLOGD(__VA_ARGS__)
#define ZLOGV(...)
#define ZLOGV(...) (void*)0
static bool unhook_functions();
......@@ -81,7 +81,7 @@ struct HookContext {
#undef DCL_PRE_POST
// Global variables
vector<tuple<const char *, const char *, void **>> *xhook_list;
vector<tuple<ino_t, const char *, void **>> *xhook_list;
map<string, vector<JNINativeMethod>, StringCmp> *jni_hook_list;
hash_map<xstring, tree_map<xstring, tree_map<xstring, void *>>> *jni_method_map;
......@@ -328,25 +328,19 @@ bool ZygiskModule::RegisterModuleImpl(ApiTable *api, long *module) {
switch (api_version) {
case 4:
api->v4.exemptFd = [](int fd) { return g_ctx != nullptr && g_ctx->exempt_fd(fd); };
// fallthrough
api->v4.pltHookRegisterInode = PltHookRegister;
api->v4.pltHookExcludeInode = PltHookExclude;
[[fallthrough]];
case 3:
case 2:
api->v2.getModuleDir = [](ZygiskModule *m) { return m->getModuleDir(); };
api->v2.getFlags = [](auto) { return ZygiskModule::getFlags(); };
// fallthrough
[[fallthrough]];
case 1:
api->v1.hookJniNativeMethods = &hookJniNativeMethods;
api->v1.pltHookRegister = [](const char *p, const char *s, void *n, void **o) {
xhook_register(p, s, n, o);
};
api->v1.pltHookExclude = [](const char *p, const char *s) {
xhook_ignore(p, s);
};
api->v1.pltHookCommit = [] {
bool r = xhook_refresh(0) == 0;
xhook_clear();
return r;
};
api->v1.hookJniNativeMethods = hookJniNativeMethods;
api->v1.pltHookRegister = PltHookRegister;
api->v1.pltHookExclude = PltHookExclude;
api->v1.pltHookCommit = CommitPltHook;
api->v1.connectCompanion = [](ZygiskModule *m) { return m->connectCompanion(); };
api->v1.setOption = [](ZygiskModule *m, auto opt) { m->setOption(opt); };
break;
......@@ -358,16 +352,74 @@ bool ZygiskModule::RegisterModuleImpl(ApiTable *api, long *module) {
return true;
}
void ZygiskModule::PltHookRegister(const char* regex, const char *symbol, void *callback, void **backup) {
if (regex == nullptr || symbol == nullptr || callback == nullptr)
return;
regex_t re;
if (regcomp(&re, regex, REG_NOSUB) != 0)
return;
mutex_guard lock(hook_lock);
register_info.emplace_back(RegisterInfo{re, 0, symbol, callback, backup});
}
void ZygiskModule::PltHookRegister(ino_t inode, const char *symbol, void *callback, void **backup) {
if (inode == 0 || symbol == nullptr || callback == nullptr)
return;
mutex_guard lock(hook_lock);
register_info.emplace_back(RegisterInfo{{}, inode, symbol, callback, backup});
}
void ZygiskModule::PltHookExclude(const char* regex, const char *symbol) {
if (!regex) return;
regex_t re;
if (regcomp(&re, regex, REG_NOSUB) != 0)
return;
mutex_guard lock(hook_lock);
ignore_info.emplace_back(IgnoreInfo{re, 0, symbol ? symbol : ""});
}
void ZygiskModule::PltHookExclude(ino_t inode, const char *symbol) {
if (inode == 0) return;
mutex_guard lock(hook_lock);
ignore_info.emplace_back(IgnoreInfo{{}, inode, symbol ? symbol : ""});
}
bool ZygiskModule::CommitPltHook() {
mutex_guard lock(hook_lock);
for (auto &map: lsplt::MapInfo::Scan()) {
if (map.offset != 0 || !map.is_private || !(map.perms & PROT_READ)) continue;
for (auto &reg: register_info) {
if ((reg.inode != 0 && reg.inode != map.inode)||
(reg.inode == 0 && regexec(&reg.regex, map.path.c_str(), 0, nullptr, 0) != 0))
continue;
bool ignored = false;
for (auto &ign: ignore_info) {
if ((ign.inode != 0 && ign.inode != map.inode) ||
(ign.inode == 0 && regexec(&ign.regex, map.path.c_str(), 0, nullptr, 0) != 0))
continue;
if (ign.symbol.empty() || ign.symbol == reg.symbol) {
ignored = true;
break;
}
}
if (!ignored) {
lsplt::RegisterHook(map.inode, reg.symbol, reg.callback, reg.backup);
}
}
}
register_info.clear();
ignore_info.clear();
return lsplt::CommitHook();
}
bool ZygiskModule::valid() const {
if (mod.api_version == nullptr)
return false;
switch (*mod.api_version) {
case 4:
// fallthrough
case 3:
// fallthrough
case 2:
// fallthrough
case 1:
return mod.v1->impl && mod.v1->preAppSpecialize && mod.v1->postAppSpecialize &&
mod.v1->preServerSpecialize && mod.v1->postServerSpecialize;
......@@ -697,8 +749,7 @@ void HookContext::nativeForkAndSpecialize_post() {
} // namespace
static bool hook_refresh() {
if (xhook_refresh(0) == 0) {
xhook_clear();
if (lsplt::CommitHook()) {
return true;
} else {
ZLOGE("xhook failed\n");
......@@ -706,14 +757,12 @@ static bool hook_refresh() {
}
}
static int hook_register(const char *path, const char *symbol, void *new_func, void **old_func) {
int ret = xhook_register(path, symbol, new_func, old_func);
if (ret != 0) {
static void hook_register(ino_t inode, const char *symbol, void *new_func, void **old_func) {
if (!lsplt::RegisterHook(inode, symbol, new_func, old_func)) {
ZLOGE("Failed to register hook \"%s\"\n", symbol);
return ret;
return;
}
xhook_list->emplace_back(path, symbol, old_func);
return 0;
xhook_list->emplace_back(inode, symbol, old_func);
}
#define XHOOK_REGISTER_SYM(PATH_REGEX, SYM, NAME) \
......@@ -722,23 +771,24 @@ static int hook_register(const char *path, const char *symbol, void *new_func, v
#define XHOOK_REGISTER(PATH_REGEX, NAME) \
XHOOK_REGISTER_SYM(PATH_REGEX, #NAME, NAME)
#define ANDROID_RUNTIME ".*/libandroid_runtime.so$"
#define APP_PROCESS "^/system/bin/app_process.*"
void hook_functions() {
#if MAGISK_DEBUG
// xhook_enable_debug(1);
xhook_enable_sigsegv_protection(0);
#endif
default_new(xhook_list);
default_new(jni_hook_list);
default_new(jni_method_map);
XHOOK_REGISTER(ANDROID_RUNTIME, fork);
XHOOK_REGISTER(ANDROID_RUNTIME, unshare);
XHOOK_REGISTER(ANDROID_RUNTIME, jniRegisterNativeMethods);
XHOOK_REGISTER(ANDROID_RUNTIME, selinux_android_setcontext);
XHOOK_REGISTER_SYM(ANDROID_RUNTIME, "__android_log_close", android_log_close);
ino_t android_runtime_inode = 0;
for (auto &map : lsplt::MapInfo::Scan()) {
if (map.path.ends_with("libandroid_runtime.so")) {
android_runtime_inode = map.inode;
break;
}
}
XHOOK_REGISTER(android_runtime_inode, fork);
XHOOK_REGISTER(android_runtime_inode, unshare);
XHOOK_REGISTER(android_runtime_inode, jniRegisterNativeMethods);
XHOOK_REGISTER(android_runtime_inode, selinux_android_setcontext);
XHOOK_REGISTER_SYM(android_runtime_inode, "__android_log_close", android_log_close);
hook_refresh();
// Remove unhooked methods
......@@ -749,9 +799,10 @@ void hook_functions() {
if (old_jniRegisterNativeMethods == nullptr) {
ZLOGD("jniRegisterNativeMethods not hooked, using fallback\n");
struct stat self_stat{};
stat("/proc/self/exe", &self_stat);
// android::AndroidRuntime::setArgv0(const char*, bool)
XHOOK_REGISTER_SYM(APP_PROCESS, "_ZN7android14AndroidRuntime8setArgv0EPKcb", setArgv0);
XHOOK_REGISTER_SYM(self_stat.st_ino, "_ZN7android14AndroidRuntime8setArgv0EPKcb", setArgv0);
hook_refresh();
// We still need old_jniRegisterNativeMethods as other code uses it
......@@ -785,8 +836,8 @@ static bool unhook_functions() {
delete jni_hook_list;
// Unhook xhook
for (const auto &[path, sym, old_func] : *xhook_list) {
if (xhook_register(path, sym, *old_func, nullptr) != 0) {
for (const auto &[inode, sym, old_func] : *xhook_list) {
if (!lsplt::RegisterHook(inode, sym, *old_func, nullptr)) {
ZLOGE("Failed to register xhook [%s]\n", sym);
success = false;
}
......
#pragma once
#include "api.hpp"
#include <list>
#include <regex.h>
namespace {
......@@ -140,6 +142,8 @@ struct api_abi_v2 : public api_abi_v1 {
struct api_abi_v4 : public api_abi_v2 {
bool (*exemptFd)(int);
void (*pltHookRegisterInode)(ino_t, const char *, void *, void **);
void (*pltHookExcludeInode)(ino_t, const char *);
};
union ApiTable {
......@@ -210,6 +214,29 @@ private:
long *api_version;
module_abi_v1 *v1;
} mod;
struct RegisterInfo {
regex_t regex;
ino_t inode;
std::string symbol;
void *callback;
void **backup;
};
struct IgnoreInfo {
regex_t regex;
ino_t inode;
std::string symbol;
};
inline static pthread_mutex_t hook_lock = PTHREAD_MUTEX_INITIALIZER;
inline static std::list<RegisterInfo> register_info {};
inline static std::list<IgnoreInfo> ignore_info {};
static void PltHookRegister(const char *lib, const char *symbol, void *callback, void **backup);
static void PltHookRegister(ino_t inode, const char *symbol, void *callback, void **backup);
static void PltHookExclude(const char *lib, const char *symbol);
static void PltHookExclude(ino_t inode, const char *symbol);
static bool CommitPltHook();
};
} // namespace
This diff is collapsed.
......@@ -84,3 +84,4 @@ export KEEPFORCEENCRYPT=true
rm -f ramdisk.cpio.orig config magisk*.xz stub.xz
./magiskboot compress=gzip ramdisk.cpio ramdisk.cpio.gz
pm install magisk.apk || true
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment