211 Commits

Author SHA1 Message Date
ThePedroo
f35680837e remove: non-working info in zygisk-ptraceXX info response
This commit removes information given in the response of info command of "zygisk-ptrace64" or "zygisk-ptrace32" that leads to failing builds, as it is not exported from monitor.cpp.
2024-11-10 23:28:33 -03:00
ThePedroo
b1d118d120 fix: missing pid and running in zygote_info structure
This commit fixes the issue where the commit that added "pid" (pid_t) and "running" (bool) members to the "zygote_info" structure, a structure that stores the response given by Zygiskd about its state, wasn't added, leading to failing buildings.
2024-11-10 23:19:21 -03:00
ThePedroo
97af7fe2da merge: add/zygiskd-c99 branch
This commit merges the Zygiskd C99 branch, which not only adds the re-written Zygisk daemon, but also implement fixes in the ptrace command.
2024-11-10 23:14:05 -03:00
ThePedroo
519d1db6a0 fix: space indentation in macros
This commit fixes the space indentation done in the "ASSURE_*" macros.
2024-11-10 23:11:50 -03:00
ThePedroo
ba7d044611 fix: additional new line in some logs
This commit fixes the issue where some loggings would add an additional new line.
2024-11-10 23:11:49 -03:00
ThePedroo
2c74ee3877 improve: module.prop parsing code; fix: deferecing a NULL pointer
This commit both improves the code that parses "module.prop" file of ReZygisk, reducing its complexity greatly and also making it smaller, and also fixes an issue where ReZygisk would deference a NULL pointer, leading to crashes in Zygiskd crash.
2024-11-10 23:11:46 -03:00
ThePedroo
66e98cf007 fix: possible out-of-bounds write; remove: unnecessary logging
This commit both fixes a possible out-of-bounds write by using "snprintf" over "sprintf" and also removes a unnecessary logging which was meant to be removed commits ago.
2024-11-10 23:09:51 -03:00
ThePedroo
47d46e305c fix: fd leak and out-of-bounds access in exec_command
This commit fixes both fd leak and out-of-bounds access in the "exec_command" function, which can happen when execution of the command fails, leading to crashes on Magisk-rooted devices, and possibly APatch-rooted devices too.
2024-11-10 23:09:50 -03:00
ThePedroo
8892eca4a7 fix: wrong longest root implementation name macro value
This commit fixes the value of the macro that defines the size of the longest root implementation name, leading to Zygiskd crashes on Magisk Official.
2024-11-10 23:09:49 -03:00
ThePedroo
a6124a6a5e improve: Zygiskd Magisk code
This commit improves the Zygiskd Magisk code by avoiding redundant code and reducing complexity.
2024-11-10 23:09:47 -03:00
ThePedroo
3265bcb581 fix: module name in Zygiskd log
This commit fixes the module name in Zygiskd log which would only show a letter.
2024-11-10 23:09:46 -03:00
ThePedroo
c4ab77ed9e fix: memory leak and use-after-free in APatch Zygiskd code
This commit fixes a memory leak and a user-after-free vulnerability in APatch code of Zygiskd.
2024-11-10 23:09:45 -03:00
ThePedroo
135ebbb9ba add: Magisk variant status; improve: KSU detection
This commit adds the Magisk variant to module description, and also improves KernelSU detection by requiring the userspace part of it to be installed, AKA "ksud".
2024-11-10 23:09:44 -03:00
ThePedroo
380ef011a1 improve: status description spacing
This commit improves the spacing of the module status description.
2024-11-10 23:09:42 -03:00
ThePedroo
e0d0bd0d76 fix: Zygiskd C99 not properly detecting Magisk DenyList
This commit fixes the Magisk part of Zygiskd C99 which used to mark all apps as outside DenyList.
2024-11-10 23:09:41 -03:00
ThePedroo
e23d1a53d0 remove: debug log
This commit removes logging used in development, which is not needed anymore.
2024-11-10 23:09:39 -03:00
ThePedroo
182c0293ca fix: compiling errors
This commit fixes compiling errors from missing declaration of variables and missing macros.
2024-11-10 23:09:38 -03:00
ThePedroo
ab7de49e4c improve: code robustness
This commit improves the robustness of the code by removing debug logs, fixing a memory leak, and adding missing error handling.
2024-11-10 23:09:36 -03:00
ThePedroo
980bf2ab4c improve: Zygiskd build.gradle.kts
This commit improves Zygisk's build gradle file by avoiding the repetition of compiler flags.
2024-11-10 23:09:35 -03:00
ThePedroo
0352d9378b fix: few UBs; fix: missing error handler for malloc
This commit fixes some few UBs (Undefined Behaviors) based on numerous sanitizers, and also adds the missing error handling for a "malloc" call.
2024-11-10 23:09:33 -03:00
ThePedroo
e11db94002 remove: logging to zygiskd.log file
This commit removes the logging made to the zygiskd.log file.
2024-11-10 23:09:32 -03:00
ThePedroo
d4ce0916f6 update: Zygiskd C99 LICENSE
This commit updates the LICENSE for Zygiskd C99, using a LICENSE that doesn't allow the code to be used for closed source projects, and with more restrictions while allowing other people to fork, modify as much as wanted as long as it remains open source.
2024-11-10 23:09:31 -03:00
ThePedroo
6ca4b72762 improve: zygisk-ptrace speed by modifying compiler flags
This commit improves the "zygisk-ptrace" command speed by changing the compiler flags to use more brutal optimizations.
2024-11-10 23:08:41 -03:00
ThePedroo
b252056ca0 fix: zygiskd building NDK version selection
This commit fixes the code that selects which NDK to use.
2024-11-10 23:08:40 -03:00
ThePedroo
6cc01fb548 improve: zygisk-ptrace's event parsing
This commit improves ptrace's event parsing by converting more C++ code to C.
2024-11-10 23:08:39 -03:00
ThePedroo
e31f9b3d85 remove: unused Zygiskd Makefile
This commit removes the unused Zygiskd Makefile, superseeded by CMake file.
2024-11-10 23:08:37 -03:00
ThePedroo
4d267aa719 fix: sending 32-bit int instead of 8-bit; fix: fd leak
This commit fixes the issue where a 32-bit (int) number was sent instead of a 8-bit (uint8_t) number. Also fixes a fd leak when connecting to the companion.
2024-11-10 23:08:36 -03:00
ThePedroo
7a6ca482f0 fix: close client in RequestLogcatFd; fix: not closing client in error cases
This commit fixes the case where Zygiskd would close the client in "RequestLogcatFd" action, and also fixes the leak of closes for client when handling errors.
2024-11-10 23:08:35 -03:00
ThePedroo
b392730366 improve: APatch detection; fix: Magisk detection and Magisk manager detection; fix: fd leak
This commit both improves the APatch detection, making it more stricter, and fixes Magisk detection, together with its manager detection, allowing it to successfully boot. Also fixes a fd leak which makes it better at a long run.
2024-11-10 23:08:34 -03:00
ThePedroo
05ae6941ba fix: Zygiskd APatch code
This commit fixes the code that handles APatch based devices to allow them to boot successfully with ReZygisk.
2024-11-10 23:08:32 -03:00
ThePedroo
c2abef8826 fix: zygiskd companion, companion responses, write fd function and early client close
This commit fixes numerous issues in zygiskd code: The zygiskd companion code not loading the right entry, the companion not sending the correct responses, the write fd function not working properly and early client close when connecting to the companion.
2024-11-10 23:08:30 -03:00
ThePedroo
a549f0e5ae add: Magisk support; fix: (some) zygiskd code issues
This commit adds Magisk support to Zygiskd C99, and also fixes some code issues of it.
2024-11-10 23:05:37 -03:00
ThePedroo
c1e45e9af6 add: zygiskd C99 APatch support
This commit adds support for zygiskd C99 to recognize APatch rooted devices.
2024-11-10 23:05:36 -03:00
ThePedroo
19d2a1758e fix: segmentation fault in write
This commit fixes the segmentation fault when trying to write to /proc/.../sockcreate.
2024-11-10 23:05:35 -03:00
ThePedroo
2ab6542a9a fix: zygiskd building
This commit fixes the building of zygiskd.
2024-11-10 23:05:34 -03:00
ThePedroo
c981907f36 fix: using fgets in a file descriptor
This commit fixes the use of fgets in a file descriptor, which would make it easier to use fopen instead of using fdopen.
2024-11-10 23:05:33 -03:00
ThePedroo
b1e217b665 improve: compiler calling code
This commit improves the code that calls the compiler to compile zygiskd.
2024-11-10 23:05:32 -03:00
ThePedroo
c852a2c146 fix: not properly switching mount ns
This commit corrects mount namespace code.
2024-11-10 23:05:31 -03:00
ThePedroo
37a667ce2a improve: compilation commands
This commit improves the compilation commands resulting in even better sized releases.
2024-11-10 23:05:30 -03:00
ThePedroo
41e83aec52 remove: Rust from CI
This commit removes the setup of Rust in the CI.
2024-11-10 23:05:29 -03:00
ThePedroo
7d29fd821f fix: zygiskd c99 building process
This commit fixes building process of new zygiskd.
2024-11-10 23:05:28 -03:00
ThePedroo
42a5ab989f add: base for CMake building (non-working)
This commit will have a rebase soon.
2024-11-10 23:05:25 -03:00
ThePedroo
5d0adacf4a improve: code readability; fix: not properly starting up companions
This commit both improves the code readability and also fixes a bug that wouln't start companions properly.
2024-11-10 23:03:27 -03:00
ThePedroo
da68db8a9a add: base for C99 zygiskd
This commit adds the first base for C99 zygiskd, that is not fully working or code-ready.
2024-11-10 23:03:26 -03:00
ThePedroo
5635c9f7c5 add: Zygiskd C99 re-write
This commit re-writes Zygiskd to be C99.
2024-11-10 23:03:25 -03:00
ThePedroo
3d2125d6c0 improve: ReZygisk status saving
This commit improves how ReZygisk saves its status.
2024-11-10 23:01:54 -03:00
ThePedroo
6187f34837 fix: code spacing
This commit fixes a minor spacing issue in the code.
2024-11-10 23:01:52 -03:00
SheepChef
7027e8147f add: Chinese README (#68)
This commit adds Chinese translation for the "README.md" file.

Signed-off-by: SheepChef <50871867+SheepChef@users.noreply.github.com>
2024-11-02 11:05:43 -03:00
WinCS
f1ba34fd29 improve: README.md grammar and information (#37)
This commit improves "README.md" grammar and adds more information to it.

Signed-off-by: WinCS <94188592+Meltartica@users.noreply.github.com>
2024-08-16 19:17:39 -03:00
ThePedroo
763e94b9b6 fix: Magisk app marking Zygisk as disabled
This commit fixes the regression added (by me) that doesn't set "ZYGISK_ENABLED" environment variable, making it mark Zygisk as disabled.
2024-08-15 00:38:25 -03:00
ThePedroo
75a004f9d5 add: additional information to ptrace command
This commit adds more information to the ptrace command to allow better integration with external features.
2024-08-10 13:43:14 -03:00
Pedro.js
88f1b7fdb9 fix: permission loophole
This commit tights the permissions for `tmpfs`, removing the permission loophole.

Signed-off-by: Pedro.js <pedroolimpioguerra@gmail.com>
2024-08-05 12:40:50 -03:00
ThePedroo
fedf7f1c40 remove: duplicated logs
This commit removes duplication of logs in ptrace binaries.
2024-07-25 03:13:15 -03:00
ThePedroo
d53e2af6a7 fix: memory leak in dlerror error log
This commit fixes an memory leak when ReZygisk logs errors for "dlerror".
2024-07-25 03:10:39 -03:00
Emmanuel Lobo
954c3a9cc5 update: GH Actions (#32)
This commit updates GH(GitHub) Actions to its latest possible major Versions to avoid [warning or deprecation of them](https://github.blog/changelog/2023-09-22-github-actions-transitioning-from-node-16-to-node-20/), Updated ones Are:

`@actions/checkout`
`@actions/setup-java`
`@gradle/gradle-build-action -> @gradle/actions/setup-gradle (was delegated/replaced)`
`@actions/upload-artifact`

Signed-off-by: Emmanuel Lobo <76094069+UnschooledGamer@users.noreply.github.com>
2024-07-14 14:01:12 -03:00
Captain Throwback
f1fe6b4435 add: support for APatch reset su path (#26)
This commit allows proper root detection when using multiple root solutions.

Co-authored-by: Admire <43035036+Admirepowered@users.noreply.github.com>
2024-07-13 15:43:24 -03:00
Captain Throwback
4b7178f1ea improve: genericize partition variable name (#25)
Since we use the same partition list for both KSU and AP,
make the vector name more generic.

Also rename the loop variable in ap function from ksu to ap
for consistency
2024-07-13 15:42:55 -03:00
Pedro.js
22e09d41bc fix: PerformanC telegram chat URL
This commit fixes the URL for PerformanC telegram chat and channel.

Signed-off-by: Pedro.js <pedroolimpioguerra@gmail.com>
2024-07-02 13:11:25 -03:00
ThePedroo
1f6f45d9ce fix: GitHub issue and FR templates
This commit fixes the templates of the repository to follow the standard and not have duplicated templates.
2024-07-01 20:48:38 -03:00
ThePedroo
4873560420 add: Telegram chat URLs
This commit adds the URLs for the Telegrams channels of the org and ReZygisk.
2024-07-01 20:31:29 -03:00
ThePedroo
f68385be5d fix: ReZygisk break after first boot
This commit fixes the issue where ReZygisk would break after rebooting after first boot after flash.
2024-07-01 00:48:39 -03:00
ThePedroo
7399ae417d fix: Apatch -> APatch
This commit fixes the name of APatch in "build.gradle.kts" and "customize.sh" files.
2024-06-30 23:22:40 -03:00
ThePedroo
c9c15bf120 update: LSPlt
This commit updates LSPlt submodule.
2024-06-30 23:05:39 -03:00
ThePedroo
1a82399e86 improve: hiding
This commit improves hiding by moving monitor related files to /data/adb/rezygisk, where it's not accessable without root.
2024-06-30 23:04:45 -03:00
ThePedroo
df0f2ce5a2 update: LSPlt
This commit updates the LSPlt submodule.
2024-06-30 19:27:32 -03:00
ThePedroo
3451057d17 add: ignore modules in manager process
This commit adds the code to ignore running modules in the manager process.
2024-06-30 19:26:55 -03:00
ThePedroo
80c873c8a4 improve: TMP_PATH related code
This commit improves the code that decides which path will be for "TMP_PATH" variable.
2024-06-30 19:25:52 -03:00
ThePedroo
5da73dd053 fix: not umounting properly module.prop
This commit fixes the issue where module.prop wouldn't be umounted properly.
2024-06-30 19:25:24 -03:00
ThePedroo
c2cb29b717 fix: APatch missing in GetInfo daemon action
This commit fixes the missing APatch root implementation detection in "GetInfo" daemon action, causing it to return none.
2024-06-29 08:49:23 -03:00
ThePedroo
2be1ccc48e fix: README.md word
This commit fixes a word in README.md file.
2024-06-27 22:34:36 -03:00
ThePedroo
af23710782 update: module.prop information
This commit updates information in module.prop.
2024-06-26 19:52:50 -03:00
ThePedroo
51507e8627 update: README.md with more info
This commit updates the README.md to contain more info about the existence of the project and Rust libraries used.
2024-06-26 19:43:38 -03:00
Pedro.js
af96b85a91 add: maps hiding (#13)
This commit adds maps hiding. This commit is taken from Reveny's PR, for more information, see #9.

solves #9
2024-06-26 19:38:34 -03:00
Pedro.js
4aa8b2f828 fix: description changer (#11)
This commit fixes the code that changes the description of the module.

fixes #10
2024-06-24 20:33:08 -03:00
rainy w/rain
7d83bb311a update: project name from issue template
This commit will replace the old project name from issue template to ReZygisk

Signed-off-by: rainy w/rain <minh15052008@gmail.com>
2024-06-23 23:59:17 +07:00
ThePedroo
2017140e0e update: AppSpecializeArgs
This commit updates the AppSpecializeArgs to match newest one.
2024-06-22 23:19:37 -03:00
Matt
2047bdb1bf add: APatch support (#4)
This commit adds support for APatch.
2024-06-22 23:13:29 -03:00
Pedro.js
678d886343 improve: CLI and code (#3)
This commit improves the CLI of ReZygisk, allowing the use of important information like PID of the daemons. Also improves the code of the loaders ptracer.
2024-06-20 22:53:13 -03:00
ThePedroo
39788a9ec2 improve: README.md to be more informative
This commit improves the README.md file with more informations and proper use of words.
2024-06-20 20:18:51 -03:00
ThePedroo
19952e6d03 remove: telegram script for releases
This commit removes the telegram script that sends a message in a telegram repository every release.
2024-06-20 19:59:13 -03:00
rainy w/rain
0987e401da add: issue, FR and PR template (#2)
This commit adds the templates for issues, feature requests and pull requests.

Signed-off-by: rainy w/rain <minh15052008@gmail.com>
2024-06-20 19:59:00 -03:00
ThePedroo
446b475333 improve: README.md
This commit improves the README.md file by adding dependencies information.
2024-06-18 17:21:13 -03:00
rainy w/rain
a22c40d618 add: note about project state
Signed-off-by: rainy w/rain <minh15052008@gmail.com>
2024-06-18 17:19:50 -03:00
ThePedroo
47f230d0c2 update: workflows
This commit updates the workflows for the repository.
2024-06-16 21:24:27 -03:00
ThePedroo
d0da6efd79 update: some loader/ code to C
This commit changes some code from "loader" folder to use C keywords and not C++ only keywords.
2024-06-16 21:13:44 -03:00
ThePedroo
c50d89e28e update: Zygisk Next -> ReZygisk
This commit changes the name of the project to not be the same as the original one, Zygisk Next.
2024-06-16 15:32:24 -03:00
ThePedroo
b7adea736a fix: compiling with modern Rust
This commit fixes compiling errors with modern Rust.
2024-06-16 15:27:05 -03:00
ThePedroo
41414c7d71 improve: README
This commit improves the README of the project.
2024-06-16 15:26:41 -03:00
Ylarod
338d306501 update for version too old issue (#85) 2024-01-06 21:27:39 +08:00
5ec1cff
7979cb4b25 suppress stopping signal properly 2024-01-06 15:54:37 +08:00
5ec1cff
505e5dc4ba fix typo 2024-01-06 10:02:29 +08:00
5ec1cff
420e93f8ed fix install magisk module task 2024-01-06 09:57:34 +08:00
5ec1cff
eee424f11c make ksud more understandable 2024-01-06 09:57:31 +08:00
Nullptr
698e6e6624 Bump to 0.9.1.1 2024-01-05 17:50:37 +08:00
Nullptr
fbb792ef13 Minor changes 2024-01-05 17:11:50 +08:00
Nullptr
381abc99d5 Bump to 0.9.1 2024-01-05 16:48:10 +08:00
Nullptr
fd603982e8 Refine uid_is_manager 2024-01-05 16:43:04 +08:00
Nullptr
2d384685e7 No hardcode ksu tmp path 2024-01-05 14:30:07 +08:00
5ec1cff
675febfd14 refine code 2024-01-05 13:57:18 +08:00
5ec1cff
ad32c4efb0 reformat code 2024-01-05 13:10:10 +08:00
5ec1cff
331b01b0f4 recognize magisk variants correctly 2024-01-05 13:00:01 +08:00
5ec1cff
8079123e43 Refine gradle 2024-01-05 11:11:42 +08:00
5ec1cff
9a95377d7b fix injector cannot get tmp path 2024-01-05 10:37:48 +08:00
Nullptr
043cfd93d6 No hardcode temp dir 2024-01-04 03:44:57 +08:00
Nullptr
32931cf3a8 Bump to 0.9.0 2024-01-03 21:48:42 +08:00
5ec1cff
9a649e0f00 remove redundant sepolicy 2024-01-03 16:10:33 +08:00
5ec1cff
ded1af2757 fix unmount module.prop 2024-01-02 23:53:42 +08:00
5ec1cff
7e1f85caf5 change minimal version codes 2024-01-02 23:49:31 +08:00
5ec1cff
711a3e98d0 no need to unshare 2024-01-02 23:49:19 +08:00
5ec1cff
cbd0f0f0c3 refine mount prop 2024-01-02 23:39:26 +08:00
5ec1cff
977bd7753d write empty machikado if no key available 2024-01-02 19:51:29 +08:00
5ec1cff
b041a4fca0 always use memfd for lib 2024-01-02 19:34:34 +08:00
5ec1cff
d5c896e966 check manager app 2024-01-02 19:33:27 +08:00
5ec1cff
5c8a67657c use /debug_ramdisk 2024-01-02 18:03:17 +08:00
5ec1cff
28f77fa5e2 machikado mazoku 2024-01-02 15:10:03 +08:00
5ec1cff
914c54cdd0 extract both 64 and 32 2024-01-02 11:13:52 +08:00
5ec1cff
8463574e2d temporary move magic to /data/adb/zygisksu 2024-01-02 00:46:30 +08:00
5ec1cff
07c29016a5 unmount ksu tmpfs 2024-01-01 00:12:54 +08:00
5ec1cff
cd714527e9 remove unnecessary jni hook logs 2023-12-31 14:27:19 +08:00
5ec1cff
0741a35c8f Update monitor.cpp 2023-12-22 09:28:40 +08:00
5ec1cff
dce2937ba0 don't panic in handle_daemon_action 2023-12-20 11:47:43 +08:00
Nullptr
92ac6d4f1a Update README.md 2023-12-14 15:44:38 +08:00
Nullptr
535379fe45 Merge pull request #73 from 5ec1cff/master 2023-12-12 16:01:56 +08:00
5ec1cff
1999ef734c fix ci upload (https://core.telegram.org/bots/api#markdownv2-style) test \_*[]()~`>#+-=|{}.! 2023-12-12 13:20:25 +08:00
5ec1cff
12f57d6e8c log if jni hook failed 2023-12-12 13:12:58 +08:00
5ec1cff
49886d9485 Fixes for Android 14 QPR2 B2 (https://github.com/topjohnwu/Magisk/pull/7620) 2023-12-12 13:05:10 +08:00
5ec1cff
056900406e separate error info and normal info of daemons 2023-12-12 12:35:13 +08:00
5ec1cff
370bb0863b Indicate root implementation 2023-12-12 12:18:32 +08:00
5ec1cff
75495dee38 Indicate wrong root implementation 2023-12-12 12:18:19 +08:00
5ec1cff
feb34c701d show loaded modules 2023-12-12 12:12:42 +08:00
5ec1cff
483987b7e6 fix companion exec failed 2023-12-12 11:24:53 +08:00
5ec1cff
b45d55e83d change some logs level to V 2023-12-12 10:50:11 +08:00
5ec1cff
f101ffb95f add emoji to status 2023-12-12 10:35:26 +08:00
5ec1cff
faf074b990 don't show inject status if not tracing 2023-12-12 00:50:49 +08:00
5ec1cff
db60c3185e show injection status 2023-12-12 00:43:30 +08:00
5ec1cff
993b18752b daemon launched by monitor & show daemon status in module.prop 2023-12-11 23:43:32 +08:00
5ec1cff
ad8510dee0 show root impl 2023-12-11 20:24:50 +08:00
5ec1cff
5d95f627bf don't use Result on handle_daemon_action 2023-12-11 20:10:28 +08:00
5ec1cff
99048699fc rename uploaded symbol filename 2023-12-11 16:13:33 +08:00
5ec1cff
ba1f90cba8 Upload CI builds to telegram 2023-12-11 15:42:26 +08:00
5ec1cff
0e2bc75966 Add version info to logs 2023-12-11 11:40:19 +08:00
5ec1cff
a88d7a5bb8 fix CI 2023-12-08 20:40:32 +08:00
5ec1cff
d66dba265c upload zygiskd debug symbols 2023-12-08 20:32:40 +08:00
5ec1cff
4f81f09a67 randomize init control socket & add shortcut (/data/adb/modules/zygisksu/bin/zygisk-ctl) 2023-12-08 20:20:59 +08:00
5ec1cff
c4163c91b9 generate debug info for release 2023-12-08 19:53:38 +08:00
5ec1cff
0254623166 fix check_unix_socket 2023-12-08 19:47:06 +08:00
5ec1cff
b34015b5f0 strip by ourselves 2023-12-08 19:46:40 +08:00
5ec1cff
bcb65c4bd9 run companion in standalone process 2023-12-08 17:19:26 +08:00
5ec1cff
9c34c671fa restart zygiskd when zygote restart 2023-12-08 11:41:40 +08:00
5ec1cff
9e48f18247 Randomize tmp path 2023-11-27 10:23:03 +08:00
5ec1cff
c205893dd2 set max retry count to 5 2023-11-14 00:10:20 +08:00
5ec1cff
5aea51ce03 Revert "run zygisk-cp on post-fs-data"
This reverts commit 47a17d2079.
2023-11-13 22:15:20 +08:00
5ec1cff
c59a7887ca refine tracing logic 2023-11-13 21:59:12 +08:00
5ec1cff
47a17d2079 run zygisk-cp on post-fs-data 2023-11-13 21:51:51 +08:00
5ec1cff
fd9f8799a1 refine tracing logic 2023-11-13 21:51:37 +08:00
5ec1cff
fd6a454275 fix compatibility on lower android version 2023-11-13 15:04:23 +08:00
5ec1cff
3e541ece3a prevent from bootloop 2023-11-12 21:38:45 +08:00
5ec1cff
36dcec0264 fix wrong entry break addr on arm32 2023-11-12 21:27:40 +08:00
5ec1cff
889a44cd0d inject non-stop signal by default 2023-11-12 21:10:40 +08:00
5ec1cff
0ac9bb819b add controller command 2023-11-12 21:00:18 +08:00
5ec1cff
040643337d init monitor 2023-11-12 20:34:45 +08:00
5ec1cff
ba8c313122 Merge branch 'art2' into new-pt
# Conflicts:
#	loader/src/Android.mk
#	loader/src/external/Android.mk
#	loader/src/injector/hook.cpp
#	module/src/customize.sh
#	zygiskd/Cargo.toml
#	zygiskd/src/utils.rs
#	zygiskd/src/watchdog.rs
2023-11-08 15:33:15 +08:00
5ec1cff
070aa5f1a1 fix pure 64 bit support 2023-11-06 10:05:41 +08:00
5ec1cff
add1c65626 make compiler happy 2023-11-04 16:39:21 +08:00
5ec1cff
ac53ef11a3 refactor jni hooks 2023-11-04 16:39:10 +08:00
5ec1cff
1c79932cae comment out useless code 2023-11-03 18:20:52 +08:00
5ec1cff
5e2a211ca4 min api is 26 2023-11-03 18:19:04 +08:00
5ec1cff
f958e57af6 Get rid of binder-rs & Refine watchdog 2023-11-03 18:12:50 +08:00
5ec1cff
f5e0a418c9 WIP 2023-11-03 11:41:28 +08:00
5ec1cff
f78c217552 init-sigstop-based ptrace zygisk 2023-10-31 18:36:01 +08:00
5ec1cff
c249ebe22c use cmake instead of ndk-build 2023-10-30 21:25:04 +08:00
Nullptr
47e515e2fc Update CI 2023-10-24 17:22:34 +08:00
Nullptr
44918d332e Rename project to Zygisk Next 2023-10-24 17:18:59 +08:00
Nullptr
cbf5920d02 Bump to 0.8.1 2023-10-24 16:07:21 +08:00
5ec1cff
a2af28dc6f add 32 bit support back & fix x86-64 support & fix jni hook restore (#59)
* Add back 32 bit support & some fix

* fix system server crash on android 10

* Refine code

---------

Co-authored-by: Nullptr <noreply@nullptr.icu>
2023-10-24 15:27:21 +08:00
Nullptr
a956dba77d Show crash info correctly 2023-10-23 22:23:25 +08:00
Nullptr
abbca19c82 Implement uid_should_umount for magisk 2023-10-22 00:23:12 +08:00
Nullptr
4587e39964 Bump to 0.8.0 2023-10-21 16:26:54 +08:00
Nullptr
9df4fb64cd Fix magisk unmount 2023-10-21 16:25:00 +08:00
Nullptr
9f28e0a7ad Update CI and README.md 2023-10-21 16:08:35 +08:00
Nullptr
8a80586fb8 Fix magisk loading 2023-10-21 13:51:01 +08:00
Nullptr
218659dcbf Fix module loading 2023-10-20 23:27:40 +08:00
Nullptr
8c0d5b5395 Drop 32 bit support 2023-10-20 19:23:40 +08:00
Nullptr
9051f59bf6 Fix hook 2023-10-20 15:24:42 +08:00
Nullptr
5f2dd50703 Replace native bridge with fuse + ptrace 2023-10-20 14:04:44 +08:00
5ec1cff
77cb323506 remove dead code (#53) 2023-10-19 01:47:53 +08:00
Nullptr
2b41a8336c Use rustix to replace nix 2023-10-19 01:33:47 +08:00
Nullptr
e730ccd9b2 Update deps 2023-10-19 01:20:50 +08:00
LoveSy
db47f03728 New way to unload zygisk (#51)
* use old binder_rs

* New way to unload zygisk (3a4fe53)

Co-authored-by: LoveSy <shana@zju.edu.cn>
Co-authored-by: 残页 <31466456+canyie@users.noreply.github.com>

---------

Co-authored-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>
Co-authored-by: 残页 <31466456+canyie@users.noreply.github.com>
2023-10-15 11:11:05 +08:00
Nullptr
42503e7cfe Update issue template 2023-08-13 09:54:50 +08:00
Nullptr
14c920c553 Update dependencies 2023-08-02 08:24:07 +08:00
Nullptr
ceaa2d431c Add updateJson 2023-06-27 16:18:52 +08:00
5ec1cff
ccb5764b72 Receive the reply_ok to prevent from dmesg flooding (#35) 2023-06-21 23:06:47 +08:00
Nullptr
e8958e94b6 Bump to 0.7.1 2023-06-19 11:08:41 +08:00
5ec1cff
0338cdb0ed Update kernelsu.rs (#34) 2023-06-18 16:42:54 +08:00
Nullptr
99e653c576 Revert "Fix #27: bool on kernel is 4 bytes, while rust's is 1 byte. This causes the stack to be covered, triggering a ub."
This reverts commit 7c27c32861.
2023-06-18 15:47:12 +08:00
Nullptr
7c27c32861 Fix #27: bool on kernel is 4 bytes, while rust's is 1 byte. This causes the stack to be covered, triggering a ub. 2023-06-13 23:32:43 +08:00
Nullptr
bea5ed47b8 Bump to 0.7.0 2023-06-04 11:16:03 +08:00
Nullptr
954a712089 Use app profile 2023-06-04 01:31:12 +08:00
Nullptr
f6195ddb43 Don't spawn new process for companion 2023-05-21 20:14:36 +08:00
Nullptr
8b5e9db347 Make watchdog async 2023-05-21 19:38:24 +08:00
Nullptr
a04f636ac4 Refine code 2023-05-19 19:14:54 +08:00
5ec1cff
00f0a6e3fa several changes (#21)
* umount for ksu 10763

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

* Add crashdump sepolicy

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

* Add more information about debug

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

* daemonize zygiskd companion

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

* create zygiskd if crash

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

* injector: use ANDROID_DLEXT_USE_LIBRARY_FD to load module

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

* zygiskd: use file as module fd instead of memfd on debug build

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

* use OwnedFd

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

* dlopen: no need to create ns

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>

---------

Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>
2023-05-19 18:28:56 +08:00
Nullptr
f5bf82fa93 Set memfd name to module name on debug 2023-04-23 09:15:53 +08:00
Nullptr
33c4ea3c62 Bump to 0.6.5 2023-04-21 16:19:12 +08:00
Nullptr
3eee57eb8f Fix incorrect ksu denylist meaning 2023-04-21 08:40:11 +08:00
5ec1cff
250b4b2f8c umount for ksu 10763 (#20)
Signed-off-by: 5ec1cff <ewtqyqyewtqyqy@gmail.com>
2023-04-20 13:36:08 +08:00
Howard Wu
3772e23473 Add issue templates (#19) 2023-04-16 14:41:56 +08:00
Nullptr
8c5acf1ebe Always add sepolicy 2023-04-14 10:43:18 +08:00
Nullptr
9d0858be7c Bump to 0.6.4 2023-03-23 19:55:15 +08:00
Nullptr
b7bed4ad35 Fix pltHookCommit 2023-03-23 19:54:45 +08:00
98 changed files with 8628 additions and 2128 deletions

1
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1 @@
blank_issues_enabled: false

View File

@@ -0,0 +1,65 @@
name: Issue report
description: Report an issue
title: "[BUG]: "
labels: ["bug", "not confirmed"]
body:
- type: input
id: version
attributes:
label: Version
description: The version of the ReZygisk you're using.
validations:
required: true
- type: textarea
id: modules
attributes:
label: Modules
description: "The modules you're using following the format: moduleName by authorName version x.x.x"
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: Steps to reproduce the behavior.
validations:
required: true
- type: textarea
id: logs
attributes:
label: Logs
description: If applicable, add logs AS A FILE to help solve the issue. Most of the time it will be from logcat on boot.
validations:
required: false
- type: checkboxes
id: terms
attributes:
label: Confirmations
description: The following confirmations are required to open a bug report.
options:
- label: My environment meets the minimum requirements.
required: true
- label: I have verified that this is not a duplicate issue.
required: true
- type: checkboxes
id: code_of_conduct
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/PerformanC/voice/blob/main/CODE_OF_CONDUCT.md)
options:
- label: I agree to follow this project's Code of Conduct
required: true

41
.github/ISSUE_TEMPLATE/pull_request.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: Feature request
description: Ask for a new feature to be added
title: "[FR]: "
labels: ["enhancement", "not confirmed"]
body:
- type: textarea
id: description
attributes:
label: Description
description: A clear and concise description of what the feature is.
validations:
required: true
- type: textarea
id: reason
attributes:
label: Reason
description: Why should this feature be added?
validations:
required: true
- type: checkboxes
id: terms
attributes:
label: Confirmations
description: The following confirmations are required to open a feature request.
options:
- label: This feature is not already implemented.
required: true
- label: I have verified that this is not a duplicate feature request.
required: true
- type: checkboxes
id: code_of_conduct
attributes:
label: Code of Conduct
description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/PerformanC/voice/blob/main/CODE_OF_CONDUCT.md)
options:
- label: I agree to follow this project's Code of Conduct
required: true

17
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,17 @@
## Changes
Write here about the changes you've made
## Why
Write here why you think this should be merged
## Checkmarks
- [ ] The modified functions have been tested.
- [ ] Used the same indentation as the rest of the project.
- [ ] Updated documentation (changelog).
## Additional information
If you have any additional information, write it here

View File

@@ -1,10 +1,9 @@
name: CI
on:
workflow_dispatch:
push:
branches: [ master ]
tags: [ v* ]
branches: [ main ]
pull_request:
merge_group:
@@ -19,35 +18,22 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
submodules: "recursive"
fetch-depth: 0
- name: Setup Java
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "17"
- name: Setup Gradle
uses: gradle/gradle-build-action@v2
uses: gradle/actions/setup-gradle@v3
with:
gradle-home-cache-cleanup: true
- name: Setup rust-cache
uses: Swatinem/rust-cache@v2
with:
workspaces: zygiskd/src -> ../build/intermediates/rust
cache-targets: false
- name: Setup Rust
run: |
rustup target add armv7-linux-androideabi
rustup target add aarch64-linux-android
rustup target add x86_64-linux-android
rustup target add i686-linux-android
- name: Set up ccache
uses: hendrikmuhs/ccache-action@v1.2
with:
@@ -70,19 +56,19 @@ jobs:
if: success()
id: prepareArtifact
run: |
releaseName=`ls module/build/outputs/release/Zygisk-on-KernelSU-v*-release.zip | awk -F '(/|.zip)' '{print $5}'` && echo "releaseName=$releaseName" >> $GITHUB_OUTPUT
debugName=`ls module/build/outputs/release/Zygisk-on-KernelSU-v*-debug.zip | awk -F '(/|.zip)' '{print $5}'` && echo "debugName=$debugName" >> $GITHUB_OUTPUT
unzip module/build/outputs/release/Zygisk-on-KernelSU-v*-release.zip -d zksu-release
unzip module/build/outputs/release/Zygisk-on-KernelSU-v*-debug.zip -d zksu-debug
releaseName=`ls module/build/outputs/release/ReZygisk-v*-release.zip | awk -F '(/|.zip)' '{print $5}'` && echo "releaseName=$releaseName" >> $GITHUB_OUTPUT
debugName=`ls module/build/outputs/release/ReZygisk-v*-debug.zip | awk -F '(/|.zip)' '{print $5}'` && echo "debugName=$debugName" >> $GITHUB_OUTPUT
unzip module/build/outputs/release/ReZygisk-v*-release.zip -d zksu-release
unzip module/build/outputs/release/ReZygisk-v*-debug.zip -d zksu-debug
- name: Upload release
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: ${{ steps.prepareArtifact.outputs.releaseName }}
path: "./zksu-release/*"
- name: Upload debug
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: ${{ steps.prepareArtifact.outputs.debugName }}
path: "./zksu-debug/*"

1
.gitignore vendored
View File

@@ -1,6 +1,7 @@
.gradle
.idea
.cxx
.vscode
build
local.properties
Cargo.lock

3
.gitmodules vendored
View File

@@ -1,6 +1,3 @@
[submodule "loader/src/external/lsplt"]
path = loader/src/external/lsplt
url = https://github.com/LSPosed/lsplt
[submodule "loader/src/external/parallel-hashmap"]
path = loader/src/external/parallel-hashmap
url = https://github.com/greg7mdp/parallel-hashmap

View File

@@ -1,26 +1,80 @@
# Zygisk on KernelSU
# ReZygisk
Zygisk loader for KernelSU, allowing Zygisk modules to run without Magisk environment.
[中文](https://github.com/PerformanC/ReZygisk/blob/main/README_CN.md)
Also works as standalone loader for Magisk on purpose of getting rid of LD_PRELOAD.
ReZygisk is a fork of Zygisk Next, a standalone implementation of Zygisk, providing Zygisk API support for KernelSU, Magisk (besides built-in), and APatch (Work In Progress).
## Requirements
It aims to modernize and re-write the codebase to C (from C++ and Rust), allowing a more efficient and faster implementation of the Zygisk API with a more permissive license.
### General
> [!NOTE]
> This module/fork is WIP (Work In Progress); only use .zip from the Releases.
>
> Although you may install the .zip from the [Actions](https://github.com/PerformanC/ReZygisk/actions) page, it is only at your discretion to install it since your device might enter bootloop.
+ No multiple root implementation installed
## Why?
### KernelSU
The latest releases of Zygisk Next are not open-source, reserving entirely the code for its developers. Not only does that limit our ability to contribute to the project, but also impossibilities the audit of the code, which is a major security concern, as Zygisk Next is a module that runs with superuser (root) privileges, having access to the entire system.
+ Minimal KernelSU version: 10654
+ Minimal ksud version: 10670
+ Kernel has full SELinux patch support
The Zygisk Next developers are famous and trusted in the Android community, however, this doesn't mean that the code is not malicious or vulnerable. We (PerformanC) understand they have their reasons to keep the code closed-source, but we believe the contrary.
### Magisk
## Advantages
+ Minimal version: 25208
+ Original Zygisk turned off
- FOSS (Forever)
## Compatibility
## Dependencies
Should work with everything except those rely on Magisk internal behaviors.
| Tool | Description |
|-----------------|----------------------------------------|
| `rustc` | The Rust compiler |
| `Android NDK` | Native Development Kit for Android |
### Rust Dependencies
| Dependency | Description |
|------------------|---------------------------------------------------------------|
| `android_logger` | Logger for Android platform |
| `anyhow` | Error handling library |
| `bitflags` | Macro to generate structures for bitwise operations |
| `const_format` | Compile-time string formatting |
| `futures` | Abstractions for asynchronous programming |
| `konst` | Compile-time constant evaluation |
| `lazy_static` | Macro for declaring lazily evaluated static variables |
| `libc` | FFI bindings to native C libraries |
| `log` | Logging facade |
| `memfd` | Memory file descriptor utilities |
| `num_enum` | Derive macros to convert between numbers and enums |
| `passfd` | Passing file descriptors over Unix sockets |
| `proc-maps` | Parse and analyze process memory maps |
### C++ Dependencies
| Dependency | Description |
|------------|-------------------------------|
| `lsplt` | Simple PLT Hook for Android |
## Usage
We're currently in the process of cooking. (Coming Soon)
## Installation
There are currently no available stable releases. (Coming Soon)
## Translation
As of now, we don't have integration with another platform for translations but you may contribute to the [add/webui](https://github.com/PerformanC/ReZygisk/tree/add/webui) branch. Please don't forget to include your GitHub profile in [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/webui/TRANSLATOR.md) so that people can see your contribution.
## Support
For any question related to ReZygisk or other PerformanC projects, feel free to join any of the following channels below:
- Discord Channel: [PerformanC](https://discord.gg/uPveNfTuCJ)
- ReZygisk Telegram Channel: [@rezygiskchat](https://t.me/rezygiskchat)
- PerformanC Telegram Channel: [@performancorg](https://t.me/performancorg)
## Contribution
It is mandatory to follow PerformanC's [Contribution Guidelines](https://github.com/PerformanC/contributing) to contribute to ReZygisk. Following its Security Policy, Code of Conduct, and syntax standard.
## License
ReZygisk is licensed majoritaly under GPL, by Dr-TSNG, but also AGPL 3.0, by The PerformanC Organization, for re-written code. You can read more about it on [Open Source Initiative](https://opensource.org/licenses/AGPL-3.0).

87
README_CN.md Normal file
View File

@@ -0,0 +1,87 @@
# ReZygisk
[English](https://github.com/PerformanC/ReZygisk/blob/main/README.md)
ReZygisk 是 Zygisk 的另一个独立实现,从 Zygisk Next 分叉而来,为 KernelSU、Magisk 和 APatch 提供 Zygisk API 支持(目前处于测试阶段)。
项目致力于使用 C 语言重写原本的 C++ 和 Rust 代码,从而更加现代、高效地实现 Zygisk API并使用更宽松的开源许可证。
> [!NOTE]
> 此模块还在测试阶段,请仅安装正式版本的压缩包。
>
> 您可以从 [Actions](https://github.com/PerformanC/ReZygisk/actions) 页面下载自动构建包,但要注意自负风险。使用不稳定的版本时,设备可能会陷入启动循环(Bootloop)。
## 为什么要ReZygisk
最新版本的 Zygisk Next 并不开源仅其核心开发者有权查阅全部源代码。这不仅阻止了其他开发者贡献代码还阻止了他们对项目代码进行审计。Zygisk Next 是一个以超级用户(root)权限运行的模块,可以访问整个系统,闭源后存在重大安全隐患。
Zygisk Next 的开发者们在Android社区享有盛誉备受信任。但这并不意味着他们的项目就一定没有任何恶意代码和漏洞。我们(PerformanC)理解他们出于某些原因不愿保持开源,但我们坚信,开源是更好的选择。
## 优点
- 永远保持开源
## 依赖
| 工具 | 简介 |
|---------------|------------------------------------|
| `rustc` | Rust 编译器 |
| `Android NDK` | Android 本地开发工具包 |
### Rust 依赖
| 依赖 | 简介 |
|------------------|-------------------------------------------------------|
| `android_logger` | Android 日志记录工具 |
| `anyhow` | 错误处理库 |
| `bitflags` | 用于生成位操作结构的宏 |
| `const_format` | 编译时字符串格式化 |
| `futures` | 异步编程的抽象实现 |
| `konst` | 编译时常量比较 |
| `lazy_static` | 用于声明静态延迟比较变量的宏 |
| `libc` | 对各平台系统C语言库的原始 FFI 绑定 |
| `log` | 日志外观框架 |
| `memfd` | 内存文件描述符实用程序 |
| `num_enum` | 在数字类型和枚举类型之间进行转换的衍生宏 |
| `passfd` | 通过Unix套接字传递文件描述符 |
| `proc-maps` | 解析和分析进程内存映射 |
### C++ 依赖
| 依赖 | 简介 |
|---------|-----------------------------|
| `lsplt` | Android 程序链接表钩子 |
## 用法
目前正在编写中 (敬请期待)
## 安装
目前还没有发布正式版本 (敬请期待)
## 翻译
您可以向 [add/webui](https://github.com/PerformanC/ReZygisk/tree/add/webui) 分支贡献翻译。
请不要忘记在 [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/webui/TRANSLATOR.md) 中添加您的 GitHub 账号信息,以便人们看到您的贡献。
## 支持
如果您有任何关于 ReZygisk 或者其他 PerformanC 项目的问题,可以随时加入以下群组:
- Discord 服务器: [PerformanC](https://discord.gg/uPveNfTuCJ)
- ReZygisk Telegram 群组: [@rezygiskchat](https://t.me/rezygiskchat)
- PerformanC Telegram 群组: [@performancorg](https://t.me/performancorg)
## 贡献
要对 ReZygisk 做出贡献,请遵守 PerformanC 的 [贡献指南](https://github.com/PerformanC/contributing) 。
请遵循其安全政策、行为准则和语法标准。
## 开源许可证
ReZygisk 项目中,旧的 Zygisk Next 部分采用 GPL 许可证,但重写的代码将采用 BSD 2-Clause 许可证。
您可以在 [Open Source Initiative](https://opensource.org/licenses/BSD-2-Clause) 上了解更多信息。

View File

@@ -2,18 +2,7 @@ import com.android.build.gradle.LibraryExtension
import java.io.ByteArrayOutputStream
plugins {
id("com.android.application") apply false
id("com.android.library") apply false
}
buildscript {
repositories {
maven("https://plugins.gradle.org/m2/")
}
dependencies {
classpath("org.eclipse.jgit:org.eclipse.jgit:6.4.0.202211300538-r")
classpath("org.mozilla.rust-android-gradle:plugin:0.9.3")
}
alias(libs.plugins.agp.lib) apply false
}
fun String.execute(currentWorkingDir: File = file("./")): String {
@@ -30,19 +19,21 @@ val gitCommitCount = "git rev-list HEAD --count".execute().toInt()
val gitCommitHash = "git rev-parse --verify --short HEAD".execute()
val moduleId by extra("zygisksu")
val moduleName by extra("Zygisk on KernelSU")
val verName by extra("v4-0.6.3")
val moduleName by extra("ReZygisk")
val verName by extra("v1.0.0")
val verCode by extra(gitCommitCount)
val minKsuVersion by extra(10654)
val minKsudVersion by extra(10670)
val commitHash by extra(gitCommitHash)
val minAPatchVersion by extra(10655)
val minKsuVersion by extra(10940)
val minKsudVersion by extra(11425)
val maxKsuVersion by extra(20000)
val minMagiskVersion by extra(25208)
val minMagiskVersion by extra(26402)
val androidMinSdkVersion by extra(29)
val androidTargetSdkVersion by extra(33)
val androidCompileSdkVersion by extra(33)
val androidBuildToolsVersion by extra("33.0.2")
val androidCompileNdkVersion by extra("25.2.9519653")
val androidMinSdkVersion by extra(26)
val androidTargetSdkVersion by extra(34)
val androidCompileSdkVersion by extra(34)
val androidBuildToolsVersion by extra("34.0.0")
val androidCompileNdkVersion by extra("26.0.10792818")
val androidSourceCompatibility by extra(JavaVersion.VERSION_11)
val androidTargetCompatibility by extra(JavaVersion.VERSION_11)
@@ -52,7 +43,7 @@ tasks.register("Delete", Delete::class) {
fun Project.configureBaseExtension() {
extensions.findByType(LibraryExtension::class)?.run {
namespace = "icu.nullptr.zygisksu"
namespace = "icu.nullptr.zygisk.next"
compileSdk = androidCompileSdkVersion
ndkVersion = androidCompileNdkVersion
buildToolsVersion = androidBuildToolsVersion

View File

@@ -1,23 +1 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.useAndroidX=false

View File

@@ -0,0 +1,9 @@
[versions]
agp = "8.2.0"
kotlin = "1.9.22"
[plugins]
agp-lib = { id = "com.android.library", version.ref = "agp" }
kotlin = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
lsplugin-jgit = { id = "org.lsposed.lsplugin.jgit", version = "1.1" }
rust-android = { id = "org.mozilla.rust-android-gradle.rust-android", version = "0.9.3" }

Binary file not shown.

View File

@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -2,9 +2,13 @@ import java.nio.file.Paths
import org.gradle.internal.os.OperatingSystem
plugins {
id("com.android.library")
alias(libs.plugins.agp.lib)
}
val verCode: Int by rootProject.extra
val verName: String by rootProject.extra
val commitHash: String by rootProject.extra
fun Project.findInPath(executable: String, property: String): String? {
val pathEnv = System.getenv("PATH")
return pathEnv.split(File.pathSeparator).map { folder ->
@@ -15,12 +19,27 @@ fun Project.findInPath(executable: String, property: String): String? {
}?.absolutePath ?: properties.getOrDefault(property, null) as? String?
}
val ccachePatch by lazy {
val ccachePath by lazy {
project.findInPath("ccache", "ccache.path")?.also {
println("loader: Use ccache: $it")
}
}
val defaultCFlags = arrayOf(
"-Wall", "-Wextra",
"-fno-rtti", "-fno-exceptions",
"-fno-stack-protector", "-fomit-frame-pointer",
"-Wno-builtin-macro-redefined", "-D__FILE__=__FILE_NAME__"
)
val releaseFlags = arrayOf(
"-Ofast", "-flto=thin",
"-Wno-unused", "-Wno-unused-parameter",
"-fvisibility=hidden", "-fvisibility-inlines-hidden",
"-fno-unwind-tables", "-fno-asynchronous-unwind-tables",
"-Wl,--exclude-libs,ALL", "-Wl,--gc-sections", "-Wl,--strip-all"
)
android {
buildFeatures {
androidResources = false
@@ -28,16 +47,33 @@ android {
prefab = true
}
externalNativeBuild.ndkBuild {
path("src/Android.mk")
externalNativeBuild.cmake {
path("src/CMakeLists.txt")
}
defaultConfig {
externalNativeBuild {
ndkBuild {
ccachePatch?.let {
arguments += "NDK_CCACHE=$it"
}
externalNativeBuild.cmake {
arguments += "-DANDROID_STL=none"
arguments += "-DLSPLT_STANDALONE=ON"
cFlags("-std=c18", *defaultCFlags)
cppFlags("-std=c++20", *defaultCFlags)
ccachePath?.let {
arguments += "-DNDK_CCACHE=$it"
}
}
}
buildTypes {
debug {
externalNativeBuild.cmake {
arguments += "-DZKSU_VERSION=$verName-$verCode-$commitHash-debug"
}
}
release {
externalNativeBuild.cmake {
cFlags += releaseFlags
cppFlags += releaseFlags
arguments += "-DZKSU_VERSION=$verName-$verCode-$commitHash-release"
}
}
}

View File

@@ -1,35 +0,0 @@
LOCAL_PATH := $(call my-dir)
define walk
$(wildcard $(1)) $(foreach e, $(wildcard $(1)/*), $(call walk, $(e)))
endef
include $(CLEAR_VARS)
LOCAL_MODULE := common
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
FILE_LIST := $(filter %.cpp, $(call walk, $(LOCAL_PATH)/common))
LOCAL_SRC_FILES := $(FILE_LIST:COMMON_FILE_LIST:$(LOCAL_PATH)/%=%)
LOCAL_STATIC_LIBRARIES := cxx
LOCAL_LDLIBS := -llog
include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := zygisk_loader
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
FILE_LIST := $(filter %.cpp, $(call walk, $(LOCAL_PATH)/loader))
LOCAL_SRC_FILES := $(FILE_LIST:COMMON_FILE_LIST:$(LOCAL_PATH)/%=%)
LOCAL_STATIC_LIBRARIES := cxx common
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := zygisk_injector
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
FILE_LIST := $(filter %.cpp, $(call walk, $(LOCAL_PATH)/injector))
LOCAL_SRC_FILES := $(FILE_LIST:COMMON_FILE_LIST:$(LOCAL_PATH)/%=%)
LOCAL_STATIC_LIBRARIES := cxx common liblsplt libphmap
LOCAL_LDLIBS := -llog
include $(BUILD_SHARED_LIBRARY)
$(call import-module,prefab/cxx)
include src/external/Android.mk

View File

@@ -1,14 +0,0 @@
APP_CFLAGS := -Wall -Wextra
APP_CFLAGS += -fno-stack-protector -fomit-frame-pointer
APP_CFLAGS += -Wno-builtin-macro-redefined -D__FILE__=__FILE_NAME__
APP_CPPFLAGS := -std=c++20
APP_CONLYFLAGS := -std=c18
APP_STL := none
ifneq ($(NDK_DEBUG),1)
APP_CFLAGS += -Oz -flto
APP_CFLAGS += -Wno-unused -Wno-unused-parameter
APP_CFLAGS += -fvisibility=hidden -fvisibility-inlines-hidden
APP_CFLAGS += -fno-unwind-tables -fno-asynchronous-unwind-tables
APP_LDFLAGS += -Wl,--exclude-libs,ALL -flto -Wl,--gc-sections -Wl,--strip-all
endif

23
loader/src/CMakeLists.txt Normal file
View File

@@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.22.1)
project("loader")
find_package(cxx REQUIRED CONFIG)
add_definitions(-DZKSU_VERSION=\"${ZKSU_VERSION}\")
aux_source_directory(common COMMON_SRC_LIST)
add_library(common STATIC ${COMMON_SRC_LIST})
target_include_directories(common PRIVATE include)
target_link_libraries(common cxx::cxx log)
aux_source_directory(injector INJECTOR_SRC_LIST)
add_library(zygisk SHARED ${INJECTOR_SRC_LIST})
target_include_directories(zygisk PRIVATE include)
target_link_libraries(zygisk cxx::cxx log common lsplt_static phmap)
aux_source_directory(ptracer PTRACER_SRC_LIST)
add_executable(libzygisk_ptrace.so ${PTRACER_SRC_LIST})
target_include_directories(libzygisk_ptrace.so PRIVATE include)
target_link_libraries(libzygisk_ptrace.so cxx::cxx log common)
add_subdirectory(external)

View File

@@ -1,132 +1,263 @@
#include <linux/un.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include "daemon.h"
#include "dl.h"
#include "socket_utils.h"
namespace zygiskd {
static std::string TMP_PATH;
void Init(const char *path) {
TMP_PATH = path;
}
bool sMagicRead = false;
static std::string sSocketName;
std::string GetTmpPath() {
return TMP_PATH;
}
void ReadMagic() {
sMagicRead = true;
char magic[PATH_MAX]{0};
auto fp = fopen(kZygiskMagic, "r");
if (fp == nullptr) {
PLOGE("Open magic file");
return;
}
fgets(magic, PATH_MAX, fp);
fclose(fp);
sSocketName.append(LP_SELECT("zygiskd32", "zygiskd64")).append(magic);
LOGD("Socket name: %s", sSocketName.data());
int Connect(uint8_t retry) {
retry++;
int fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
struct sockaddr_un addr = {
.sun_family = AF_UNIX,
.sun_path = { 0 }
};
auto socket_path = TMP_PATH + kCPSocketName;
strcpy(addr.sun_path, socket_path.c_str());
socklen_t socklen = sizeof(addr);
while (--retry) {
int r = connect(fd, (struct sockaddr *)&addr, socklen);
if (r == 0) return fd;
if (retry) {
PLOGE("Retrying to connect to zygiskd, sleep 1s");
sleep(1);
}
}
int Connect(uint8_t retry) {
if (!sMagicRead) ReadMagic();
int fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
struct sockaddr_un addr{
.sun_family = AF_UNIX,
.sun_path={0},
};
strcpy(addr.sun_path + 1, sSocketName.data());
socklen_t socklen = sizeof(sa_family_t) + strlen(addr.sun_path + 1) + 1;
close(fd);
while (retry--) {
int r = connect(fd, reinterpret_cast<struct sockaddr*>(&addr), socklen);
if (r == 0) return fd;
LOGW("Retrying to connect to zygiskd, sleep 1s");
sleep(1);
}
return -1;
}
bool PingHeartbeat() {
int fd = Connect(5);
if (fd == -1) {
PLOGE("Connect to zygiskd");
return false;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::PingHeartBeat);
close(fd);
return true;
}
int RequestLogcatFd() {
int fd = Connect(1);
if (fd == -1) {
PLOGE("RequestLogcatFd");
return -1;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::RequestLogcatFd);
return fd;
}
uint32_t GetProcessFlags(uid_t uid) {
int fd = Connect(1);
if (fd == -1) {
PLOGE("GetProcessFlags");
return 0;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::GetProcessFlags);
socket_utils::write_u32(fd, uid);
uint32_t res = socket_utils::read_u32(fd);
close(fd);
return res;
}
std::vector<Module> ReadModules() {
std::vector<Module> modules;
int fd = Connect(1);
if (fd == -1) {
PLOGE("ReadModules");
return modules;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::ReadModules);
size_t len = socket_utils::read_usize(fd);
for (size_t i = 0; i < len; i++) {
std::string name = socket_utils::read_string(fd);
int module_fd = socket_utils::recv_fd(fd);
modules.emplace_back(name, module_fd);
}
close(fd);
return modules;
}
int ConnectCompanion(size_t index) {
int fd = Connect(1);
if (fd == -1) {
PLOGE("ConnectCompanion");
return -1;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::RequestCompanionSocket);
socket_utils::write_usize(fd, index);
uint8_t res = socket_utils::read_u8(fd);
if (res == 1) return fd;
else {
close(fd);
return -1;
}
}
int GetModuleDir(size_t index) {
int fd = Connect(1);
if (fd == -1) {
PLOGE("GetModuleDir");
return -1;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::GetModuleDir);
socket_utils::write_usize(fd, index);
int nfd = socket_utils::recv_fd(fd);
close(fd);
return nfd;
}
void ZygoteRestart() {
int fd = Connect(1);
if (fd == -1) {
if (errno == ENOENT) LOGD("Could not notify ZygoteRestart (maybe it hasn't been created)");
else PLOGE("Could not notify ZygoteRestart");
return;
}
if (!socket_utils::write_u8(fd, (uint8_t) SocketAction::ZygoteRestart))
PLOGE("Failed to request ZygoteRestart");
close(fd);
}
void SystemServerStarted() {
int fd = Connect(1);
if (fd == -1) PLOGE("Failed to report system server started");
else {
if (!socket_utils::write_u8(fd, (uint8_t) SocketAction::SystemServerStarted))
PLOGE("Failed to report system server started");
}
close(fd);
}
void GetInfo(struct zygote_info *info) {
/* TODO: Optimize and avoid re-connect twice here */
int fd = Connect(1);
if (fd != -1) {
info->running = true;
socket_utils::write_u8(fd, (uint8_t) SocketAction::GetInfo);
int flags = socket_utils::read_u32(fd);
if (flags & (1 << 27)) {
info->root_impl = ZYGOTE_ROOT_IMPL_APATCH;
} else if (flags & (1 << 29)) {
info->root_impl = ZYGOTE_ROOT_IMPL_KERNELSU;
} else if (flags & (1 << 30)) {
info->root_impl = ZYGOTE_ROOT_IMPL_MAGISK;
} else {
info->root_impl = ZYGOTE_ROOT_IMPL_NONE;
}
info->pid = socket_utils::read_u32(fd);
info->modules = (struct zygote_modules *)malloc(sizeof(struct zygote_modules));
if (info->modules == NULL) {
info->modules->modules_count = 0;
close(fd);
return -1;
}
bool PingHeartbeat() {
UniqueFd fd = Connect(5);
if (fd == -1) {
PLOGE("Connect to zygiskd");
return false;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::PingHeartBeat);
return true;
}
return;
}
int RequestLogcatFd() {
int fd = Connect(1);
if (fd == -1) {
PLOGE("RequestLogcatFd");
return -1;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::RequestLogcatFd);
return fd;
}
info->modules->modules_count = socket_utils::read_usize(fd);
std::string ReadNativeBridge() {
UniqueFd fd = Connect(1);
if (fd == -1) {
PLOGE("ReadNativeBridge");
return "";
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::ReadNativeBridge);
return socket_utils::read_string(fd);
}
if (info->modules->modules_count == 0) {
info->modules->modules = NULL;
uint32_t GetProcessFlags(uid_t uid) {
UniqueFd fd = Connect(1);
if (fd == -1) {
PLOGE("GetProcessFlags");
return 0;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::GetProcessFlags);
socket_utils::write_u32(fd, uid);
return socket_utils::read_u32(fd);
}
close(fd);
std::vector<Module> ReadModules() {
std::vector<Module> modules;
UniqueFd fd = Connect(1);
if (fd == -1) {
PLOGE("ReadModules");
return modules;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::ReadModules);
size_t len = socket_utils::read_usize(fd);
for (size_t i = 0; i < len; i++) {
std::string name = socket_utils::read_string(fd);
int module_fd = socket_utils::recv_fd(fd);
modules.emplace_back(name, module_fd);
}
return modules;
}
return;
}
int ConnectCompanion(size_t index) {
int fd = Connect(1);
if (fd == -1) {
PLOGE("ConnectCompanion");
return -1;
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::RequestCompanionSocket);
socket_utils::write_usize(fd, index);
if (socket_utils::read_u8(fd) == 1) {
return fd;
info->modules->modules = (char **)malloc(sizeof(char *) * info->modules->modules_count);
if (info->modules->modules == NULL) {
free(info->modules);
info->modules = NULL;
info->modules->modules_count = 0;
close(fd);
return;
}
for (size_t i = 0; i < info->modules->modules_count; i++) {
/* INFO by ThePedroo: Ugly solution to read with std::string existance (temporary) */
std::string name = socket_utils::read_string(fd);
char module_path[PATH_MAX];
snprintf(module_path, sizeof(module_path), "/data/adb/modules/%s/module.prop", name.c_str());
FILE *module_prop = fopen(module_path, "r");
if (module_prop == NULL) {
info->modules->modules[i] = strdup(name.c_str());
} else {
return -1;
}
}
char line[1024];
while (fgets(line, sizeof(line), module_prop) != NULL) {
if (strncmp(line, "name=", 5) == 0) {
info->modules->modules[i] = strndup(line + 5, strlen(line) - 6);
int GetModuleDir(size_t index) {
int fd = Connect(1);
if (fd == -1) {
PLOGE("GetModuleDir");
return -1;
break;
}
}
fclose(module_prop);
}
socket_utils::write_u8(fd, (uint8_t) SocketAction::GetModuleDir);
socket_utils::write_usize(fd, index);
return socket_utils::recv_fd(fd);
}
}
close(fd);
} else info->running = false;
}
}

View File

@@ -44,8 +44,17 @@ void* DlopenExt(const char* path, int flags) {
return handle;
}
void* DlopenMem(int memfd, int flags) {
char path[PATH_MAX];
sprintf(path, "/proc/self/fd/%d", memfd);
return DlopenExt(path, flags);
void* DlopenMem(int fd, int flags) {
auto info = android_dlextinfo{
.flags = ANDROID_DLEXT_USE_LIBRARY_FD,
.library_fd = fd
};
auto* handle = android_dlopen_ext("/jit-cache-zygisk", flags, &info);
if (handle) {
LOGV("dlopen fd %d: %p", fd, handle);
} else {
LOGE("dlopen fd %d: %s", fd, dlerror());
}
return handle;
}

View File

@@ -0,0 +1,235 @@
/*
* This file is part of LSPosed.
*
* LSPosed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LSPosed is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LSPosed. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright (C) 2019 Swift Gan
* Copyright (C) 2021 LSPosed Contributors
*/
#include <malloc.h>
#include <cstring>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <cassert>
#include <sys/stat.h>
#include "elf_util.h"
using namespace SandHook;
template<typename T>
inline constexpr auto offsetOf(ElfW(Ehdr) *head, ElfW(Off) off) {
return reinterpret_cast<std::conditional_t<std::is_pointer_v<T>, T, T *>>(
reinterpret_cast<uintptr_t>(head) + off);
}
ElfImg::ElfImg(std::string_view base_name) : elf(base_name) {
if (!findModuleBase()) {
base = nullptr;
return;
}
//load elf
int fd = open(elf.data(), O_RDONLY);
if (fd < 0) {
// LOGE("failed to open %s", elf.data());
return;
}
size = lseek(fd, 0, SEEK_END);
if (size <= 0) {
// LOGE("lseek() failed for %s", elf.data());
}
header = reinterpret_cast<decltype(header)>(mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0));
close(fd);
section_header = offsetOf<decltype(section_header)>(header, header->e_shoff);
auto shoff = reinterpret_cast<uintptr_t>(section_header);
char *section_str = offsetOf<char *>(header, section_header[header->e_shstrndx].sh_offset);
for (int i = 0; i < header->e_shnum; i++, shoff += header->e_shentsize) {
auto *section_h = (ElfW(Shdr) *) shoff;
char *sname = section_h->sh_name + section_str;
auto entsize = section_h->sh_entsize;
switch (section_h->sh_type) {
case SHT_DYNSYM: {
if (bias == -4396) {
dynsym = section_h;
dynsym_offset = section_h->sh_offset;
dynsym_start = offsetOf<decltype(dynsym_start)>(header, dynsym_offset);
}
break;
}
case SHT_SYMTAB: {
if (strcmp(sname, ".symtab") == 0) {
symtab = section_h;
symtab_offset = section_h->sh_offset;
symtab_size = section_h->sh_size;
symtab_count = symtab_size / entsize;
symtab_start = offsetOf<decltype(symtab_start)>(header, symtab_offset);
}
break;
}
case SHT_STRTAB: {
if (bias == -4396) {
strtab = section_h;
symstr_offset = section_h->sh_offset;
strtab_start = offsetOf<decltype(strtab_start)>(header, symstr_offset);
}
if (strcmp(sname, ".strtab") == 0) {
symstr_offset_for_symtab = section_h->sh_offset;
}
break;
}
case SHT_PROGBITS: {
if (strtab == nullptr || dynsym == nullptr) break;
if (bias == -4396) {
bias = (off_t) section_h->sh_addr - (off_t) section_h->sh_offset;
}
break;
}
case SHT_HASH: {
auto *d_un = offsetOf<ElfW(Word)>(header, section_h->sh_offset);
nbucket_ = d_un[0];
bucket_ = d_un + 2;
chain_ = bucket_ + nbucket_;
break;
}
case SHT_GNU_HASH: {
auto *d_buf = reinterpret_cast<ElfW(Word) *>(((size_t) header) +
section_h->sh_offset);
gnu_nbucket_ = d_buf[0];
gnu_symndx_ = d_buf[1];
gnu_bloom_size_ = d_buf[2];
gnu_shift2_ = d_buf[3];
gnu_bloom_filter_ = reinterpret_cast<decltype(gnu_bloom_filter_)>(d_buf + 4);
gnu_bucket_ = reinterpret_cast<decltype(gnu_bucket_)>(gnu_bloom_filter_ +
gnu_bloom_size_);
gnu_chain_ = gnu_bucket_ + gnu_nbucket_ - gnu_symndx_;
break;
}
}
}
}
ElfW(Addr) ElfImg::ElfLookup(std::string_view name, uint32_t hash) const {
if (nbucket_ == 0) return 0;
char *strings = (char *) strtab_start;
for (auto n = bucket_[hash % nbucket_]; n != 0; n = chain_[n]) {
auto *sym = dynsym_start + n;
if (name == strings + sym->st_name) {
return sym->st_value;
}
}
return 0;
}
ElfW(Addr) ElfImg::GnuLookup(std::string_view name, uint32_t hash) const {
static constexpr auto bloom_mask_bits = sizeof(ElfW(Addr)) * 8;
if (gnu_nbucket_ == 0 || gnu_bloom_size_ == 0) return 0;
auto bloom_word = gnu_bloom_filter_[(hash / bloom_mask_bits) % gnu_bloom_size_];
uintptr_t mask = 0
| (uintptr_t) 1 << (hash % bloom_mask_bits)
| (uintptr_t) 1 << ((hash >> gnu_shift2_) % bloom_mask_bits);
if ((mask & bloom_word) == mask) {
auto sym_index = gnu_bucket_[hash % gnu_nbucket_];
if (sym_index >= gnu_symndx_) {
char *strings = (char *) strtab_start;
do {
auto *sym = dynsym_start + sym_index;
if (((gnu_chain_[sym_index] ^ hash) >> 1) == 0
&& name == strings + sym->st_name) {
return sym->st_value;
}
} while ((gnu_chain_[sym_index++] & 1) == 0);
}
}
return 0;
}
ElfW(Addr) ElfImg::LinearLookup(std::string_view name) const {
if (symtabs_.empty()) {
symtabs_.reserve(symtab_count);
if (symtab_start != nullptr && symstr_offset_for_symtab != 0) {
for (ElfW(Off) i = 0; i < symtab_count; i++) {
unsigned int st_type = ELF_ST_TYPE(symtab_start[i].st_info);
const char *st_name = offsetOf<const char *>(header, symstr_offset_for_symtab +
symtab_start[i].st_name);
if ((st_type == STT_FUNC || st_type == STT_OBJECT) && symtab_start[i].st_size) {
symtabs_.emplace(st_name, &symtab_start[i]);
}
}
}
}
if (auto i = symtabs_.find(name); i != symtabs_.end()) {
return i->second->st_value;
} else {
return 0;
}
}
ElfImg::~ElfImg() {
//open elf file local
if (buffer) {
free(buffer);
buffer = nullptr;
}
//use mmap
if (header) {
munmap(header, size);
}
}
ElfW(Addr) ElfImg::getSymbOffset(std::string_view name, uint32_t gnu_hash, uint32_t elf_hash) const {
if (auto offset = GnuLookup(name, gnu_hash); offset > 0) {
// LOGD("found %s %p in %s in dynsym by gnuhash", name.data(), reinterpret_cast<void *>(offset), elf.data());
return offset;
} else if (offset = ElfLookup(name, elf_hash); offset > 0) {
// LOGD("found %s %p in %s in dynsym by elfhash", name.data(), reinterpret_cast<void *>(offset), elf.data());
return offset;
} else if (offset = LinearLookup(name); offset > 0) {
// LOGD("found %s %p in %s in symtab by linear lookup", name.data(), reinterpret_cast<void *>(offset), elf.data());
return offset;
} else {
return 0;
}
}
bool ElfImg::findModuleBase() {
dl_iterate_phdr([](struct dl_phdr_info *info, size_t size, void *data) -> int {
(void) size;
if ((info)->dlpi_name == nullptr) {
return 0;
}
auto *self = reinterpret_cast<ElfImg *>(data);
if (strstr(info->dlpi_name, self->elf.data())) {
self->elf = info->dlpi_name;
self->base = reinterpret_cast<void *>(info->dlpi_addr);
return 1;
}
return 0;
}, this);
return base != 0;
}

View File

@@ -5,131 +5,133 @@
#include "socket_utils.h"
namespace socket_utils {
ssize_t xread(int fd, void* buf, size_t count) {
size_t read_sz = 0;
ssize_t ret;
do {
ret = read(fd, (std::byte*) buf + read_sz, count - read_sz);
if (ret < 0) {
if (errno == EINTR) continue;
PLOGE("read");
return ret;
}
read_sz += ret;
} while (read_sz != count && ret != 0);
if (read_sz != count) {
PLOGE("read (%zu != %zu)", count, read_sz);
}
return read_sz;
}
ssize_t xread(int fd, void* buf, size_t count) {
size_t read_sz = 0;
ssize_t ret;
do {
ret = read(fd, (std::byte*) buf + read_sz, count - read_sz);
if (ret < 0) {
if (errno == EINTR) continue;
PLOGE("read");
return ret;
}
read_sz += ret;
} while (read_sz != count && ret != 0);
if (read_sz != count) {
PLOGE("read (%d != %d)", count, read_sz);
size_t xwrite(int fd, const void* buf, size_t count) {
size_t write_sz = 0;
ssize_t ret;
do {
ret = write(fd, (std::byte*) buf + write_sz, count - write_sz);
if (ret < 0) {
if (errno == EINTR) continue;
PLOGE("write");
return write_sz;
}
return read_sz;
write_sz += ret;
} while (write_sz != count && ret != 0);
if (write_sz != count) {
PLOGE("write (%zu != %zu)", count, write_sz);
}
return write_sz;
}
ssize_t xwrite(int fd, const void* buf, size_t count) {
size_t write_sz = 0;
ssize_t ret;
do {
ret = write(fd, (std::byte*) buf + write_sz, count - write_sz);
if (ret < 0) {
if (errno == EINTR) continue;
PLOGE("write");
return ret;
}
write_sz += ret;
} while (write_sz != count && ret != 0);
if (write_sz != count) {
PLOGE("write (%d != %d)", count, write_sz);
}
return write_sz;
}
ssize_t xrecvmsg(int sockfd, struct msghdr* msg, int flags) {
int rec = recvmsg(sockfd, msg, flags);
if (rec < 0) PLOGE("recvmsg");
return rec;
}
ssize_t xrecvmsg(int sockfd, struct msghdr* msg, int flags) {
int rec = recvmsg(sockfd, msg, flags);
if (rec < 0) PLOGE("recvmsg");
return rec;
}
template<typename T>
inline T read_exact_or(int fd, T fail) {
T res;
return sizeof(T) == xread(fd, &res, sizeof(T)) ? res : fail;
}
void* recv_fds(int sockfd, char* cmsgbuf, size_t bufsz, int cnt) {
iovec iov = {
.iov_base = &cnt,
.iov_len = sizeof(cnt),
};
msghdr msg = {
.msg_iov = &iov,
.msg_iovlen = 1,
.msg_control = cmsgbuf,
.msg_controllen = bufsz
};
template<typename T>
inline bool write_exact(int fd, T val) {
return sizeof(T) == xwrite(fd, &val, sizeof(T));
}
xrecvmsg(sockfd, &msg, MSG_WAITALL);
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
uint8_t read_u8(int fd) {
return read_exact_or<uint8_t>(fd, 0);
}
if (msg.msg_controllen != bufsz ||
cmsg == nullptr ||
// TODO: pass from rust: 20, expected: 16
// cmsg->cmsg_len != CMSG_LEN(sizeof(int) * cnt) ||
cmsg->cmsg_level != SOL_SOCKET ||
cmsg->cmsg_type != SCM_RIGHTS) {
return nullptr;
}
uint32_t read_u32(int fd) {
return read_exact_or<uint32_t>(fd, 0);
}
return CMSG_DATA(cmsg);
}
size_t read_usize(int fd) {
return read_exact_or<size_t>(fd, 0);
}
template<typename T>
inline T read_exact_or(int fd, T fail) {
T res;
return sizeof(T) == xread(fd, &res, sizeof(T)) ? res : fail;
}
bool write_usize(int fd, size_t val) {
return write_exact<size_t>(fd, val);
}
template<typename T>
inline bool write_exact(int fd, T val) {
return sizeof(T) == xwrite(fd, &val, sizeof(T));
}
std::string read_string(int fd) {
size_t len = read_usize(fd);
uint8_t read_u8(int fd) {
return read_exact_or<uint8_t>(fd, 0);
}
char buf[len + 1];
xread(fd, buf, len);
uint32_t read_u32(int fd) {
return read_exact_or<uint32_t>(fd, 0);
}
buf[len] = '\0';
size_t read_usize(int fd) {
return read_exact_or<size_t>(fd, 0);
}
return buf;
}
bool write_usize(int fd, size_t val) {
return write_exact<size_t>(fd, val);
}
bool write_u8(int fd, uint8_t val) {
return write_exact<uint8_t>(fd, val);
}
std::string read_string(int fd) {
auto len = read_usize(fd);
char buf[len + 1];
buf[len] = '\0';
xread(fd, buf, len);
return buf;
}
void* recv_fds(int sockfd, char* cmsgbuf, size_t bufsz, int cnt) {
iovec iov = {
.iov_base = &cnt,
.iov_len = sizeof(cnt),
};
msghdr msg = {
.msg_iov = &iov,
.msg_iovlen = 1,
.msg_control = cmsgbuf,
.msg_controllen = bufsz
};
bool write_u8(int fd, uint8_t val) {
return write_exact<uint8_t>(fd, val);
}
xrecvmsg(sockfd, &msg, MSG_WAITALL);
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
bool write_u32(int fd, uint32_t val) {
return write_exact<uint32_t>(fd, val);
}
if (msg.msg_controllen != bufsz ||
cmsg == nullptr ||
// TODO: pass from rust: 20, expected: 16
// cmsg->cmsg_len != CMSG_LEN(sizeof(int) * cnt) ||
cmsg->cmsg_level != SOL_SOCKET ||
cmsg->cmsg_type != SCM_RIGHTS) {
return nullptr;
}
bool write_string(int fd, std::string_view str) {
return write_usize(fd, str.size()) && str.size() == xwrite(fd, str.data(), str.size());
}
return CMSG_DATA(cmsg);
}
int recv_fd(int sockfd) {
char cmsgbuf[CMSG_SPACE(sizeof(int))];
char cmsgbuf[CMSG_SPACE(sizeof(int))];
void* data = recv_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), 1);
if (data == nullptr) return -1;
void* data = recv_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), 1);
if (data == nullptr) return -1;
int result;
memcpy(&result, data, sizeof(int));
return result;
}
int result;
memcpy(&result, data, sizeof(int));
return result;
}
bool write_u32(int fd, uint32_t val) {
return write_exact<uint32_t>(fd, val);
}
bool write_string(int fd, std::string_view str) {
return write_usize(fd, str.size()) && str.size() == xwrite(fd, str.data(), str.size());
}
}

View File

@@ -1,21 +0,0 @@
LOCAL_PATH := $(call my-dir)
# liblsplt.a
include $(CLEAR_VARS)
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 -DLOG_DISABLED
LOCAL_CPPFLAGS := -std=c++20
LOCAL_STATIC_LIBRARIES := libcxx
LOCAL_SRC_FILES := \
lsplt/lsplt/src/main/jni/elf_util.cc \
lsplt/lsplt/src/main/jni/lsplt.cc
include $(BUILD_STATIC_LIBRARY)
# Header only library
include $(CLEAR_VARS)
LOCAL_MODULE:= libphmap
LOCAL_CFLAGS := -Wno-unused-value
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/parallel-hashmap
include $(BUILD_STATIC_LIBRARY)

8
loader/src/external/CMakeLists.txt vendored Normal file
View File

@@ -0,0 +1,8 @@
project(external)
OPTION(LSPLT_BUILD_SHARED OFF)
add_subdirectory(lsplt/lsplt/src/main/jni)
add_library(phmap INTERFACE)
target_include_directories(phmap INTERFACE parallel-hashmap)
target_compile_options(phmap INTERFACE -Wno-unused-value)

View File

@@ -26,14 +26,40 @@
#define ZYGISK_API_VERSION 4
/*
***************
* Introduction
***************
On Android, all app processes are forked from a special daemon called "Zygote".
For each new app process, zygote will fork a new process and perform "specialization".
This specialization operation enforces the Android security sandbox on the newly forked
process to make sure that 3rd party application code is only loaded after it is being
restricted within a sandbox.
On Android, there is also this special process called "system_server". This single
process hosts a significant portion of system services, which controls how the
Android operating system and apps interact with each other.
The Zygisk framework provides a way to allow developers to build modules and run custom
code before and after system_server and any app processes' specialization.
This enable developers to inject code and alter the behavior of system_server and app processes.
Please note that modules will only be loaded after zygote has forked the child process.
THIS MEANS ALL OF YOUR CODE RUNS IN THE APP/SYSTEM_SERVER PROCESS, NOT THE ZYGOTE DAEMON!
*********************
* Development Guide
*********************
Define a class and inherit zygisk::ModuleBase to implement the functionality of your module.
Use the macro REGISTER_ZYGISK_MODULE(className) to register that class to Zygisk.
Please note that modules will only be loaded after zygote has forked the child process.
THIS MEANS ALL OF YOUR CODE RUNS IN THE APP/SYSTEM SERVER PROCESS, NOT THE ZYGOTE DAEMON!
Example code:
static jint (*orig_logger_entry_max)(JNIEnv *env);
static jint my_logger_entry_max(JNIEnv *env) { return orig_logger_entry_max(env); }
static void example_handler(int socket) { ... }
class ExampleModule : public zygisk::ModuleBase {
public:
void onLoad(zygisk::Api *api, JNIEnv *env) override {
@@ -51,8 +77,26 @@ private:
zygisk::Api *api;
JNIEnv *env;
};
REGISTER_ZYGISK_MODULE(ExampleModule)
-----------------------------------------------------------------------------------------
Since your module class's code runs with either Zygote's privilege in pre[XXX]Specialize,
or runs in the sandbox of the target process in post[XXX]Specialize, the code in your class
never runs in a true superuser environment.
If your module require access to superuser permissions, you can create and register
a root companion handler function. This function runs in a separate root companion
daemon process, and an Unix domain socket is provided to allow you to perform IPC between
your target process and the root companion process.
Example code:
static void example_handler(int socket) { ... }
REGISTER_ZYGISK_COMPANION(example_handler)
*/
namespace zygisk {
@@ -84,7 +128,7 @@ namespace zygisk {
// This method is called after the app process is specialized.
// At this point, the process has all sandbox restrictions enabled for this application.
// This means that this method runs as the same privilege of the app's own code.
// This means that this method runs with the same privilege of the app's own code.
virtual void postAppSpecialize([[maybe_unused]] const AppSpecializeArgs *args) {}
// This method is called before the system server process is specialized.
@@ -117,6 +161,7 @@ namespace zygisk {
jobjectArray *const whitelisted_data_info_list;
jboolean *const mount_data_dirs;
jboolean *const mount_storage_dirs;
jboolean *const mount_sysprop_overrides;
AppSpecializeArgs() = delete;
};
@@ -219,7 +264,16 @@ namespace zygisk {
// will be set to nullptr.
void hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods);
// For ELFs loaded in memory matching `inode`, replace function `symbol` with `newFunc`.
// Hook functions in the PLT (Procedure Linkage Table) of ELFs loaded in memory.
//
// Parsing /proc/[PID]/maps will give you the memory map of a process. As an example:
//
// <address> <perms> <offset> <dev> <inode> <pathname>
// 56b4346000-56b4347000 r-xp 00002000 fe:00 235 /system/bin/app_process64
// (More details: https://man7.org/linux/man-pages/man5/proc.5.html)
//
// The `dev` and `inode` pair uniquely identifies a file being mapped into memory.
// For matching ELFs loaded in memory, replace function `symbol` with `newFunc`.
// If `oldFunc` is not nullptr, the original function pointer will be saved to `oldFunc`.
void pltHookRegister(dev_t dev, ino_t inode, const char *symbol, void *newFunc, void **oldFunc);
@@ -243,11 +297,11 @@ void zygisk_module_entry(zygisk::internal::api_table *table, JNIEnv *env) { \
//
// The function runs in a superuser daemon process and handles a root companion request from
// your module running in a target process. The function has to accept an integer value,
// which is a socket that is connected to the target process.
// which is a Unix domain socket that is connected to the target process.
// See Api::connectCompanion() for more info.
//
// NOTE: the function can run concurrently on multiple threads.
// Be aware of race conditions if you have a globally shared resource.
// Be aware of race conditions if you have globally shared resources.
#define REGISTER_ZYGISK_COMPANION(func) \
void zygisk_companion_entry(int client) { func(client); }

View File

@@ -11,7 +11,7 @@
# define LP_SELECT(lp32, lp64) lp32
#endif
constexpr auto kZygiskMagic = "/system/zygisk_magic";
constexpr auto kCPSocketName = "/" LP_SELECT("cp32", "cp64") ".sock";
class UniqueFd {
using Fd = int;
@@ -20,7 +20,7 @@ public:
UniqueFd(Fd fd) : fd_(fd) {}
~UniqueFd() { close(fd_); }
~UniqueFd() { if (fd_ >= 0) close(fd_); }
// Disallow copy
UniqueFd(const UniqueFd&) = delete;
@@ -42,6 +42,25 @@ private:
Fd fd_ = -1;
};
struct zygote_modules {
char **modules;
size_t modules_count;
};
enum zygote_root_impl {
ZYGOTE_ROOT_IMPL_NONE,
ZYGOTE_ROOT_IMPL_APATCH,
ZYGOTE_ROOT_IMPL_KERNELSU,
ZYGOTE_ROOT_IMPL_MAGISK
};
struct zygote_info {
struct zygote_modules *modules;
enum zygote_root_impl root_impl;
pid_t pid;
bool running;
};
namespace zygiskd {
struct Module {
@@ -54,19 +73,23 @@ namespace zygiskd {
enum class SocketAction {
PingHeartBeat,
RequestLogcatFd,
ReadNativeBridge,
GetProcessFlags,
GetInfo,
ReadModules,
RequestCompanionSocket,
GetModuleDir,
ZygoteRestart,
SystemServerStarted,
};
void Init(const char *path);
std::string GetTmpPath();
bool PingHeartbeat();
int RequestLogcatFd();
std::string ReadNativeBridge();
std::vector<Module> ReadModules();
uint32_t GetProcessFlags(uid_t uid);
@@ -74,4 +97,10 @@ namespace zygiskd {
int ConnectCompanion(size_t index);
int GetModuleDir(size_t index);
void ZygoteRestart();
void SystemServerStarted();
void GetInfo(struct zygote_info *info);
}

View File

@@ -0,0 +1,136 @@
/*
* This file is part of LSPosed.
*
* LSPosed is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LSPosed is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LSPosed. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright (C) 2019 Swift Gan
* Copyright (C) 2021 LSPosed Contributors
*/
#ifndef SANDHOOK_ELF_UTIL_H
#define SANDHOOK_ELF_UTIL_H
#include <string_view>
#include <unordered_map>
#include <linux/elf.h>
#include <sys/types.h>
#include <link.h>
#include <string>
#define SHT_GNU_HASH 0x6ffffff6
namespace SandHook {
class ElfImg {
public:
ElfImg(std::string_view elf);
constexpr ElfW(Addr) getSymbOffset(std::string_view name) const {
return getSymbOffset(name, GnuHash(name), ElfHash(name));
}
constexpr ElfW(Addr) getSymbAddress(std::string_view name) const {
ElfW(Addr) offset = getSymbOffset(name);
if (offset > 0 && base != nullptr) {
return static_cast<ElfW(Addr)>((uintptr_t) base + offset - bias);
} else {
return 0;
}
}
template<typename T>
constexpr T getSymbAddress(std::string_view name) const {
return reinterpret_cast<T>(getSymbAddress(name));
}
bool isValid() const {
return base != nullptr;
}
const std::string name() const {
return elf;
}
~ElfImg();
private:
ElfW(Addr) getSymbOffset(std::string_view name, uint32_t gnu_hash, uint32_t elf_hash) const;
ElfW(Addr) ElfLookup(std::string_view name, uint32_t hash) const;
ElfW(Addr) GnuLookup(std::string_view name, uint32_t hash) const;
ElfW(Addr) LinearLookup(std::string_view name) const;
constexpr static uint32_t ElfHash(std::string_view name);
constexpr static uint32_t GnuHash(std::string_view name);
bool findModuleBase();
std::string elf;
void *base = nullptr;
char *buffer = nullptr;
off_t size = 0;
off_t bias = -4396;
ElfW(Ehdr) *header = nullptr;
ElfW(Shdr) *section_header = nullptr;
ElfW(Shdr) *symtab = nullptr;
ElfW(Shdr) *strtab = nullptr;
ElfW(Shdr) *dynsym = nullptr;
ElfW(Sym) *symtab_start = nullptr;
ElfW(Sym) *dynsym_start = nullptr;
ElfW(Sym) *strtab_start = nullptr;
ElfW(Off) symtab_count = 0;
ElfW(Off) symstr_offset = 0;
ElfW(Off) symstr_offset_for_symtab = 0;
ElfW(Off) symtab_offset = 0;
ElfW(Off) dynsym_offset = 0;
ElfW(Off) symtab_size = 0;
uint32_t nbucket_{};
uint32_t *bucket_ = nullptr;
uint32_t *chain_ = nullptr;
uint32_t gnu_nbucket_{};
uint32_t gnu_symndx_{};
uint32_t gnu_bloom_size_;
uint32_t gnu_shift2_;
uintptr_t *gnu_bloom_filter_;
uint32_t *gnu_bucket_;
uint32_t *gnu_chain_;
mutable std::unordered_map<std::string_view, ElfW(Sym) *> symtabs_;
};
constexpr uint32_t ElfImg::ElfHash(std::string_view name) {
uint32_t h = 0, g = 0;
for (unsigned char p: name) {
h = (h << 4) + p;
g = h & 0xf0000000;
h ^= g;
h ^= g >> 24;
}
return h;
}
constexpr uint32_t ElfImg::GnuHash(std::string_view name) {
uint32_t h = 5381;
for (unsigned char p: name) {
h += (h << 5) + p;
}
return h;
}
}
#endif //SANDHOOK_ELF_UTIL_H

View File

@@ -6,19 +6,12 @@
#ifndef LOG_TAG
#if defined(__LP64__)
# define LOG_TAG "zygisksu64"
# define LOG_TAG "zygisk-core64"
#else
# define LOG_TAG "zygisksu32"
# define LOG_TAG "zygisk-core32"
#endif
#endif
#ifdef LOG_DISABLED
#define LOGD(...)
#define LOGV(...)
#define LOGI(...)
#define LOGW(...)
#define LOGE(...)
#else
#ifndef NDEBUG
#define LOGD(...) logging::log(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGV(...) logging::log(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
@@ -31,7 +24,6 @@
#define LOGE(...) logging::log(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGF(...) logging::log(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__)
#define PLOGE(fmt, args...) LOGE(fmt " failed with %d: %s", ##args, errno, strerror(errno))
#endif
namespace logging {
void setfd(int fd);

View File

@@ -9,7 +9,7 @@ namespace socket_utils {
ssize_t xread(int fd, void *buf, size_t count);
ssize_t xwrite(int fd, const void *buf, size_t count);
size_t xwrite(int fd, const void *buf, size_t count);
uint8_t read_u8(int fd);

View File

@@ -0,0 +1,103 @@
//
// Original from https://github.com/LSPosed/NativeDetector/blob/master/app/src/main/jni/solist.cpp
//
#pragma once
#include <string>
#include "elf_util.h"
namespace SoList
{
class SoInfo {
public:
#ifdef __LP64__
inline static size_t solist_next_offset = 0x30;
constexpr static size_t solist_realpath_offset = 0x1a8;
#else
inline static size_t solist_next_offset = 0xa4;
constexpr static size_t solist_realpath_offset = 0x174;
#endif
inline static const char *(*get_realpath_sym)(SoInfo *) = nullptr;
inline static const char *(*get_soname_sym)(SoInfo *) = nullptr;
inline SoInfo *get_next() {
return *(SoInfo **) ((uintptr_t) this + solist_next_offset);
}
inline const char *get_path() {
return get_realpath_sym ? get_realpath_sym(this) : ((std::string *) ((uintptr_t) this + solist_realpath_offset))->c_str();
}
inline const char *get_name() {
return get_soname_sym ? get_soname_sym(this) : *((const char **) ((uintptr_t) this + solist_realpath_offset - sizeof(void *)));
}
void nullify_name() {
const char** name = (const char**)get_soname_sym(this);
static const char* empty_string = "";
*name = reinterpret_cast<const char *>(&empty_string);
}
void nullify_path() {
const char** name = (const char**)get_realpath_sym(this);
static const char* empty_string = "";
*name = reinterpret_cast<const char *>(&empty_string);
}
};
static SoInfo *solist = nullptr;
static SoInfo *somain = nullptr;
template<typename T>
inline T *getStaticPointer(const SandHook::ElfImg &linker, const char* name)
{
auto *addr = reinterpret_cast<T **>(linker.getSymbAddress(name));
return addr == nullptr ? nullptr : *addr;
}
static void NullifySoName(const char* target_name) {
for (auto *iter = solist; iter; iter = iter->get_next()) {
if (iter->get_name() && iter->get_path() && strstr(iter->get_path(), target_name)) {
iter->nullify_path();
LOGI("Cleared SOList entry for %s", target_name);
}
}
for (auto *iter = somain; iter; iter = iter->get_next()) {
if (iter->get_name() && iter->get_path() && strstr(iter->get_path(), target_name)) {
iter->nullify_path();
break;
}
}
}
static bool Initialize() {
SandHook::ElfImg linker("/linker");
solist = getStaticPointer<SoInfo>(linker, "__dl__ZL6solist");
somain = getStaticPointer<SoInfo>(linker, "__dl__ZL6somain");
if (solist != nullptr && somain != nullptr)
{
SoInfo::get_realpath_sym = reinterpret_cast<decltype(SoInfo::get_realpath_sym)>(linker.getSymbAddress("__dl__ZNK6soinfo12get_realpathEv"));
SoInfo::get_soname_sym = reinterpret_cast<decltype(SoInfo::get_soname_sym)>(linker.getSymbAddress("__dl__ZNK6soinfo10get_sonameEv"));
auto vsdo = getStaticPointer<SoInfo>(linker, "__dl__ZL4vdso");
for (size_t i = 0; i < 1024 / sizeof(void *); i++)
{
auto *possible_next = *(void **) ((uintptr_t) solist + i * sizeof(void *));
if (possible_next == somain || (vsdo != nullptr && possible_next == vsdo))
{
SoInfo::solist_next_offset = i * sizeof(void *);
break;
}
}
return (SoInfo::get_realpath_sym != nullptr && SoInfo::get_soname_sym != nullptr);
}
return false;
}
}

View File

@@ -0,0 +1,82 @@
#pragma once
#include "jni_helper.hpp"
template <typename T>
constexpr inline auto RoundUpTo(T v, size_t size) {
return v + size - 1 - ((v + size - 1) & (size - 1));
}
inline static constexpr auto kPointerSize = sizeof(void *);
namespace lsplant::art {
class ArtMethod {
public:
void *GetData() {
return *reinterpret_cast<void **>(reinterpret_cast<uintptr_t>(this) + data_offset);
}
static art::ArtMethod *FromReflectedMethod(JNIEnv *env, jobject method) {
if (art_method_field) [[likely]] {
return reinterpret_cast<art::ArtMethod *>(
JNI_GetLongField(env, method, art_method_field));
} else {
return reinterpret_cast<art::ArtMethod *>(env->FromReflectedMethod(method));
}
}
static bool Init(JNIEnv *env) {
ScopedLocalRef<jclass> executable{env, nullptr};
executable = JNI_FindClass(env, "java/lang/reflect/Executable");
if (!executable) {
LOGE("Failed to found Executable");
return false;
}
if (art_method_field = JNI_GetFieldID(env, executable, "artMethod", "J");
!art_method_field) {
LOGE("Failed to find artMethod field");
return false;
}
auto throwable = JNI_FindClass(env, "java/lang/Throwable");
if (!throwable) {
LOGE("Failed to found Executable");
return false;
}
auto clazz = JNI_FindClass(env, "java/lang/Class");
static_assert(std::is_same_v<decltype(clazz)::BaseType, jclass>);
jmethodID get_declared_constructors = JNI_GetMethodID(env, clazz, "getDeclaredConstructors",
"()[Ljava/lang/reflect/Constructor;");
const auto constructors =
JNI_Cast<jobjectArray>(JNI_CallObjectMethod(env, throwable, get_declared_constructors));
if (constructors.size() < 2) {
LOGE("Throwable has less than 2 constructors");
return false;
}
auto &first_ctor = constructors[0];
auto &second_ctor = constructors[1];
auto *first = FromReflectedMethod(env, first_ctor.get());
auto *second = FromReflectedMethod(env, second_ctor.get());
art_method_size = reinterpret_cast<uintptr_t>(second) - reinterpret_cast<uintptr_t>(first);
LOGD("ArtMethod size: %zu", art_method_size);
if (RoundUpTo(4 * 9, kPointerSize) + kPointerSize * 3 < art_method_size) [[unlikely]] {
LOGW("ArtMethod size exceeds maximum assume. There may be something wrong.");
}
entry_point_offset = art_method_size - kPointerSize;
data_offset = entry_point_offset - kPointerSize;
LOGD("ArtMethod::entrypoint offset: %zu", entry_point_offset);
LOGD("ArtMethod::data offset: %zu", data_offset);
return true;
}
private:
inline static jfieldID art_method_field = nullptr;
inline static size_t art_method_size = 0;
inline static size_t entry_point_offset = 0;
inline static size_t data_offset = 0;
};
} // namespace lsplant::art

View File

@@ -7,22 +7,21 @@ using namespace std;
void *self_handle = nullptr;
[[gnu::destructor]] [[maybe_unused]]
static void zygisk_cleanup_wait() {
if (self_handle) {
// Wait 10us to make sure none of our code is executing
timespec ts = { .tv_sec = 0, .tv_nsec = 10000L };
nanosleep(&ts, nullptr);
}
}
extern "C" [[gnu::visibility("default")]]
void entry(void *handle) {
void entry(void* handle, const char* path) {
LOGI("Zygisk library injected, version %s", ZKSU_VERSION);
self_handle = handle;
zygiskd::Init(path);
if (!zygiskd::PingHeartbeat()) {
LOGE("Zygisk daemon is not running");
return;
}
#ifdef NDEBUG
logging::setfd(zygiskd::RequestLogcatFd());
#endif
self_handle = handle;
LOGD("Load injector successfully");
LOGI("Start hooking");
hook_functions();
}

View File

@@ -0,0 +1,290 @@
#!/usr/bin/env python3
primitives = ['jint', 'jboolean', 'jlong']
class JType:
def __init__(self, cpp, jni):
self.cpp = cpp
self.jni = jni
class JArray(JType):
def __init__(self, type):
if type.cpp in primitives:
name = type.cpp + 'Array'
else:
name = 'jobjectArray'
super().__init__(name, '[' + type.jni)
class Argument:
def __init__(self, name, type, set_arg = False):
self.name = name
self.type = type
self.set_arg = set_arg
def cpp(self):
return f'{self.type.cpp} {self.name}'
# Args we don't care, give it an auto generated name
class Anon(Argument):
cnt = 0
def __init__(self, type):
super().__init__(f'_{Anon.cnt}', type)
Anon.cnt += 1
class Return:
def __init__(self, value, type):
self.value = value
self.type = type
class Method:
def __init__(self, name, ret, args):
self.name = name
self.ret = ret
self.args = args
def cpp(self):
return ', '.join(map(lambda x: x.cpp(), self.args))
def name_list(self):
return ', '.join(map(lambda x: x.name, self.args))
def jni(self):
args = ''.join(map(lambda x: x.type.jni, self.args))
return f'({args}){self.ret.type.jni}'
def body(self):
return ''
class JNIHook(Method):
def __init__(self, ver, ret, args):
name = f'{self.base_name()}_{ver}'
super().__init__(name, ret, args)
def base_name(self):
return ''
def orig_method(self):
return f'reinterpret_cast<decltype(&{self.name})>({self.base_name()}_orig)'
def ind(i):
return '\n' + ' ' * i
# Common types
jint = JType('jint', 'I')
jintArray = JArray(jint)
jstring = JType('jstring', 'Ljava/lang/String;')
jboolean = JType('jboolean', 'Z')
jlong = JType('jlong', 'J')
void = JType('void', 'V')
class ForkAndSpec(JNIHook):
def __init__(self, ver, args):
super().__init__(ver, Return('ctx.pid', jint), args)
def base_name(self):
return 'nativeForkAndSpecialize'
def init_args(self):
return 'AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);'
def body(self):
decl = ''
decl += ind(1) + self.init_args()
for a in self.args:
if a.set_arg:
decl += ind(1) + f'args.{a.name} = &{a.name};'
decl += ind(1) + 'ZygiskContext ctx(env, &args);'
decl += ind(1) + f'ctx.{self.base_name()}_pre();'
decl += ind(1) + self.orig_method() + '('
decl += ind(2) + f'env, clazz, {self.name_list()}'
decl += ind(1) + ');'
decl += ind(1) + f'ctx.{self.base_name()}_post();'
return decl
class SpecApp(ForkAndSpec):
def __init__(self, ver, args):
super().__init__(ver, args)
self.ret = Return('', void)
def base_name(self):
return 'nativeSpecializeAppProcess'
class ForkServer(ForkAndSpec):
def base_name(self):
return 'nativeForkSystemServer'
def init_args(self):
return 'ServerSpecializeArgs_v1 args(uid, gid, gids, runtime_flags, permitted_capabilities, effective_capabilities);'
# Common args
uid = Argument('uid', jint)
gid = Argument('gid', jint)
gids = Argument('gids', jintArray)
runtime_flags = Argument('runtime_flags', jint)
rlimits = Argument('rlimits', JArray(jintArray))
mount_external = Argument('mount_external', jint)
se_info = Argument('se_info', jstring)
nice_name = Argument('nice_name', jstring)
fds_to_close = Argument('fds_to_close', jintArray)
instruction_set = Argument('instruction_set', jstring)
app_data_dir = Argument('app_data_dir', jstring)
# o
fds_to_ignore = Argument('fds_to_ignore', jintArray, True)
# p
is_child_zygote = Argument('is_child_zygote', jboolean, True)
# q_alt
is_top_app = Argument('is_top_app', jboolean, True)
# r
pkg_data_info_list = Argument('pkg_data_info_list', JArray(jstring), True)
whitelisted_data_info_list = Argument('whitelisted_data_info_list', JArray(jstring), True)
mount_data_dirs = Argument('mount_data_dirs', jboolean, True)
mount_storage_dirs = Argument('mount_storage_dirs', jboolean, True)
# u
mount_sysprop_overrides = Argument('mount_sysprop_overrides', jboolean, True)
# server
permitted_capabilities = Argument('permitted_capabilities', jlong)
effective_capabilities = Argument('effective_capabilities', jlong)
# Method definitions
fas_l = ForkAndSpec('l', [uid, gid, gids, runtime_flags, rlimits, mount_external,
se_info, nice_name, fds_to_close, instruction_set, app_data_dir])
fas_o = ForkAndSpec('o', [uid, gid, gids, runtime_flags, rlimits, mount_external,
se_info, nice_name, fds_to_close, fds_to_ignore, instruction_set, app_data_dir])
fas_p = ForkAndSpec('p', [uid, gid, gids, runtime_flags, rlimits, mount_external, se_info,
nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir])
fas_q_alt = ForkAndSpec('q_alt', [uid, gid, gids, runtime_flags, rlimits, mount_external, se_info,
nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app])
fas_r = ForkAndSpec('r', [uid, gid, gids, runtime_flags, rlimits, mount_external, se_info,
nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app,
pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs])
fas_u = ForkAndSpec('u', [uid, gid, gids, runtime_flags, rlimits, mount_external, se_info,
nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app,
pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs, mount_sysprop_overrides])
fas_samsung_m = ForkAndSpec('samsung_m', [uid, gid, gids, runtime_flags, rlimits, mount_external,
se_info, Anon(jint), Anon(jint), nice_name, fds_to_close, instruction_set, app_data_dir])
fas_samsung_n = ForkAndSpec('samsung_n', [uid, gid, gids, runtime_flags, rlimits, mount_external,
se_info, Anon(jint), Anon(jint), nice_name, fds_to_close, instruction_set, app_data_dir, Anon(jint)])
fas_samsung_o = ForkAndSpec('samsung_o', [uid, gid, gids, runtime_flags, rlimits, mount_external,
se_info, Anon(jint), Anon(jint), nice_name, fds_to_close, fds_to_ignore, instruction_set, app_data_dir])
fas_samsung_p = ForkAndSpec('samsung_p', [uid, gid, gids, runtime_flags, rlimits, mount_external,
se_info, Anon(jint), Anon(jint), nice_name, fds_to_close, fds_to_ignore, is_child_zygote,
instruction_set, app_data_dir])
spec_q = SpecApp('q', [uid, gid, gids, runtime_flags, rlimits, mount_external, se_info,
nice_name, is_child_zygote, instruction_set, app_data_dir])
spec_q_alt = SpecApp('q_alt', [uid, gid, gids, runtime_flags, rlimits, mount_external, se_info,
nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app])
spec_r = SpecApp('r', [uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name,
is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list,
whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs])
spec_u = SpecApp('u', [uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name,
is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list,
whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs, mount_sysprop_overrides])
spec_samsung_q = SpecApp('samsung_q', [uid, gid, gids, runtime_flags, rlimits, mount_external,
se_info, Anon(jint), Anon(jint), nice_name, is_child_zygote, instruction_set, app_data_dir])
server_l = ForkServer('l', [uid, gid, gids, runtime_flags, rlimits,
permitted_capabilities, effective_capabilities])
server_samsung_q = ForkServer('samsung_q', [uid, gid, gids, runtime_flags, Anon(jint), Anon(jint), rlimits,
permitted_capabilities, effective_capabilities])
hook_map = {}
def gen_jni_def(clz, methods):
if clz not in hook_map:
hook_map[clz] = []
decl = ''
for m in methods:
decl += ind(0) + f'[[clang::no_stack_protector]] {m.ret.type.cpp} {m.name}(JNIEnv *env, jclass clazz, {m.cpp()}) {{'
decl += m.body()
if m.ret.value:
decl += ind(1) + f'return {m.ret.value};'
decl += ind(0) + '}'
decl += ind(0) + f'std::array {m.base_name()}_methods = {{'
for m in methods:
decl += ind(1) + 'JNINativeMethod {'
decl += ind(2) + f'"{m.base_name()}",'
decl += ind(2) + f'"{m.jni()}",'
decl += ind(2) + f'(void *) &{m.name}'
decl += ind(1) + '},'
decl += ind(0) + '};'
decl = ind(0) + f'void *{m.base_name()}_orig = nullptr;' + decl
decl += ind(0)
hook_map[clz].append(m.base_name())
return decl
with open('jni_hooks.hpp', 'w') as f:
f.write('// Generated by gen_jni_hooks.py\n')
f.write('\nnamespace {\n')
zygote = 'com/android/internal/os/Zygote'
methods = [fas_l, fas_o, fas_p, fas_q_alt, fas_r, fas_u, fas_samsung_m, fas_samsung_n, fas_samsung_o, fas_samsung_p]
f.write(gen_jni_def(zygote, methods))
methods = [spec_q, spec_q_alt, spec_r, spec_u, spec_samsung_q]
f.write(gen_jni_def(zygote, methods))
methods = [server_l, server_samsung_q]
f.write(gen_jni_def(zygote, methods))
f.write('\n} // namespace\n')
f.write("""
static void do_hook_zygote(JNIEnv *env) {
vector<JNINativeMethod> hooks;
const char *clz;
clz = "com/android/internal/os/Zygote";
hookJniNativeMethods(env, clz, nativeForkAndSpecialize_methods.data(), nativeForkAndSpecialize_methods.size());
for (auto &method : nativeForkAndSpecialize_methods) {
if (method.fnPtr) {
nativeForkAndSpecialize_orig = method.fnPtr;
hooks.emplace_back(method);
break;
}
}
hookJniNativeMethods(env, clz, nativeSpecializeAppProcess_methods.data(), nativeSpecializeAppProcess_methods.size());
for (auto &method : nativeSpecializeAppProcess_methods) {
if (method.fnPtr) {
nativeSpecializeAppProcess_orig = method.fnPtr;
hooks.emplace_back(method);
break;
}
}
hookJniNativeMethods(env, clz, nativeForkSystemServer_methods.data(), nativeForkSystemServer_methods.size());
for (auto &method : nativeForkSystemServer_methods) {
if (method.fnPtr) {
nativeForkSystemServer_orig = method.fnPtr;
hooks.emplace_back(method);
break;
}
}
jni_hook_list->emplace(clz, std::move(hooks));
}
""")

View File

@@ -4,27 +4,32 @@
#include <regex.h>
#include <bitset>
#include <list>
#include <map>
#include <array>
#include <lsplt.hpp>
#include <fcntl.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include "dl.h"
#include "daemon.h"
#include "zygisk.hpp"
#include "memory.hpp"
#include "module.hpp"
#include "files.hpp"
#include "misc.hpp"
#include "solist.hpp"
#include "art_method.hpp"
using namespace std;
using jni_hook::hash_map;
using jni_hook::tree_map;
using xstring = jni_hook::string;
static bool unhook_functions();
static void hook_unloader();
static void unhook_functions();
namespace {
@@ -34,7 +39,6 @@ enum {
APP_SPECIALIZE,
SERVER_FORK_AND_SPECIALIZE,
DO_REVERT_UNMOUNT,
CAN_UNLOAD_ZYGISK,
SKIP_FD_SANITIZATION,
FLAG_MAX
@@ -46,11 +50,16 @@ void name##_post();
#define MAX_FD_SIZE 1024
struct HookContext {
struct ZygiskContext;
// Current context
ZygiskContext *g_ctx;
struct ZygiskContext {
JNIEnv *env;
union {
void *ptr;
AppSpecializeArgs_v3 *app;
AppSpecializeArgs_v5 *app;
ServerSpecializeArgs_v1 *server;
} args;
@@ -79,8 +88,12 @@ struct HookContext {
vector<RegisterInfo> register_info;
vector<IgnoreInfo> ignore_info;
HookContext() : env(nullptr), args{nullptr}, process(nullptr), pid(-1), info_flags(0),
hook_info_lock(PTHREAD_MUTEX_INITIALIZER) {}
ZygiskContext(JNIEnv *env, void *args) :
env(env), args{args}, process(nullptr), pid(-1), info_flags(0),
hook_info_lock(PTHREAD_MUTEX_INITIALIZER) {
g_ctx = this;
}
~ZygiskContext();
/* Zygisksu changed: Load module fds */
void run_modules_pre();
@@ -91,9 +104,9 @@ struct HookContext {
DCL_PRE_POST(nativeSpecializeAppProcess)
DCL_PRE_POST(nativeForkSystemServer)
void unload_zygisk();
void sanitize_fds();
bool exempt_fd(int fd);
bool is_child() const { return pid <= 0; }
// Compatibility shim
void plt_hook_register(const char *regex, const char *symbol, void *fn, void **backup);
@@ -108,103 +121,16 @@ struct HookContext {
// Global variables
vector<tuple<dev_t, ino_t, const char *, void **>> *plt_hook_list;
map<string, vector<JNINativeMethod>, StringCmp> *jni_hook_list;
hash_map<xstring, tree_map<xstring, tree_map<xstring, void *>>> *jni_method_map;
// Current context
HookContext *g_ctx;
const JNINativeInterface *old_functions = nullptr;
JNINativeInterface *new_functions = nullptr;
bool should_unmap_zygisk = false;
} // namespace
#define HOOK_JNI(method) \
if (methods[i].name == #method##sv) { \
int j = 0; \
for (; j < method##_methods_num; ++j) { \
if (strcmp(methods[i].signature, method##_methods[j].signature) == 0) { \
jni_hook_list->try_emplace(className).first->second.push_back(methods[i]); \
method##_orig = methods[i].fnPtr; \
newMethods[i] = method##_methods[j]; \
LOGI("replaced %s#" #method "\n", className); \
--hook_cnt; \
break; \
} \
} \
if (j == method##_methods_num) { \
LOGE("unknown signature of %s#" #method ": %s\n", className, methods[i].signature); \
} \
continue; \
}
// JNI method hook definitions, auto generated
#include "jni_hooks.hpp"
#undef HOOK_JNI
namespace {
string get_class_name(JNIEnv *env, jclass clazz) {
static auto class_getName = env->GetMethodID(env->FindClass("java/lang/Class"), "getName", "()Ljava/lang/String;");
auto nameRef = (jstring) env->CallObjectMethod(clazz, class_getName);
const char *name = env->GetStringUTFChars(nameRef, nullptr);
string className(name);
env->ReleaseStringUTFChars(nameRef, name);
std::replace(className.begin(), className.end(), '.', '/');
return className;
}
#define DCL_HOOK_FUNC(ret, func, ...) \
ret (*old_##func)(__VA_ARGS__); \
ret new_##func(__VA_ARGS__)
jint env_RegisterNatives(
JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint numMethods) {
auto className = get_class_name(env, clazz);
LOGV("JNIEnv->RegisterNatives [%s]\n", className.data());
auto newMethods = hookAndSaveJNIMethods(className.data(), methods, numMethods);
return old_functions->RegisterNatives(env, clazz, newMethods.get() ?: methods, numMethods);
}
DCL_HOOK_FUNC(void, androidSetCreateThreadFunc, void* func) {
LOGD("androidSetCreateThreadFunc\n");
do {
auto get_created_java_vms = reinterpret_cast<jint (*)(JavaVM **, jsize, jsize *)>(
dlsym(RTLD_DEFAULT, "JNI_GetCreatedJavaVMs"));
if (!get_created_java_vms) {
for (auto &map: lsplt::MapInfo::Scan()) {
if (!map.path.ends_with("/libnativehelper.so")) continue;
void *h = dlopen(map.path.data(), RTLD_LAZY);
if (!h) {
LOGW("cannot dlopen libnativehelper.so: %s\n", dlerror());
break;
}
get_created_java_vms = reinterpret_cast<decltype(get_created_java_vms)>(dlsym(h, "JNI_GetCreatedJavaVMs"));
dlclose(h);
break;
}
if (!get_created_java_vms) {
LOGW("JNI_GetCreatedJavaVMs not found\n");
break;
}
}
JavaVM *vm = nullptr;
jsize num = 0;
jint res = get_created_java_vms(&vm, 1, &num);
if (res != JNI_OK || vm == nullptr) break;
JNIEnv *env = nullptr;
res = vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6);
if (res != JNI_OK || env == nullptr) break;
default_new(new_functions);
memcpy(new_functions, env->functions, sizeof(*new_functions));
new_functions->RegisterNatives = &env_RegisterNatives;
// Replace the function table in JNIEnv to hook RegisterNatives
old_functions = env->functions;
env->functions = new_functions;
} while (false);
old_androidSetCreateThreadFunc(func);
}
// Skip actual fork and return cached result if applicable
DCL_HOOK_FUNC(int, fork) {
return (g_ctx && g_ctx->pid >= 0) ? g_ctx->pid : old_fork();
@@ -221,6 +147,8 @@ DCL_HOOK_FUNC(int, unshare, int flags) {
if (g_ctx->flags[DO_REVERT_UNMOUNT]) {
if (g_ctx->info_flags & PROCESS_ROOT_IS_KSU) {
revert_unmount_ksu();
} else if (g_ctx->info_flags & PROCESS_ROOT_IS_APATCH){
revert_unmount_apatch();
} else if (g_ctx->info_flags & PROCESS_ROOT_IS_MAGISK) {
revert_unmount_magisk();
}
@@ -246,53 +174,142 @@ DCL_HOOK_FUNC(void, android_log_close) {
old_android_log_close();
}
// Last point before process secontext changes
DCL_HOOK_FUNC(int, selinux_android_setcontext,
uid_t uid, int isSystemServer, const char *seinfo, const char *pkgname) {
if (g_ctx) {
g_ctx->flags[CAN_UNLOAD_ZYGISK] = unhook_functions();
// We cannot directly call `dlclose` to unload ourselves, otherwise when `dlclose` returns,
// it will return to our code which has been unmapped, causing segmentation fault.
// Instead, we hook `pthread_attr_destroy` which will be called when VM daemon threads start.
DCL_HOOK_FUNC(int, pthread_attr_destroy, void *target) {
int res = old_pthread_attr_destroy((pthread_attr_t *)target);
// Only perform unloading on the main thread
if (gettid() != getpid())
return res;
LOGV("pthread_attr_destroy");
if (should_unmap_zygisk) {
unhook_functions();
if (should_unmap_zygisk) {
// Because both `pthread_attr_destroy` and `dlclose` have the same function signature,
// we can use `musttail` to let the compiler reuse our stack frame and thus
// `dlclose` will directly return to the caller of `pthread_attr_destroy`.
[[clang::musttail]] return dlclose(self_handle);
}
}
return old_selinux_android_setcontext(uid, isSystemServer, seinfo, pkgname);
return res;
}
void initialize_jni_hook();
DCL_HOOK_FUNC(char *, strdup, const char *s) {
if (strcmp(s, "com.android.internal.os.ZygoteInit") == 0) {
LOGV("strdup %s", s);
initialize_jni_hook();
}
return old_strdup(s);
}
#undef DCL_HOOK_FUNC
// -----------------------------------------------------------------
static bool can_hook_jni = false;
static jint MODIFIER_NATIVE = 0;
static jmethodID member_getModifiers = nullptr;
void hookJniNativeMethods(JNIEnv *env, const char *clz, JNINativeMethod *methods, int numMethods) {
auto class_map = jni_method_map->find(clz);
if (class_map == jni_method_map->end()) {
for (int i = 0; i < numMethods; ++i) {
if (!can_hook_jni) return;
auto clazz = env->FindClass(clz);
if (clazz == nullptr) {
env->ExceptionClear();
for (int i = 0; i < numMethods; i++) {
methods[i].fnPtr = nullptr;
}
return;
}
vector<JNINativeMethod> hooks;
for (int i = 0; i < numMethods; ++i) {
auto method_map = class_map->second.find(methods[i].name);
if (method_map != class_map->second.end()) {
auto it = method_map->second.find(methods[i].signature);
if (it != method_map->second.end()) {
// Copy the JNINativeMethod
hooks.push_back(methods[i]);
// Save the original function pointer
methods[i].fnPtr = it->second;
// Do not allow double hook, remove method from map
method_map->second.erase(it);
continue;
}
for (int i = 0; i < numMethods; i++) {
auto &nm = methods[i];
auto mid = env->GetMethodID(clazz, nm.name, nm.signature);
bool is_static = false;
if (mid == nullptr) {
env->ExceptionClear();
mid = env->GetStaticMethodID(clazz, nm.name, nm.signature);
is_static = true;
}
// No matching method found, set fnPtr to null
methods[i].fnPtr = nullptr;
if (mid == nullptr) {
env->ExceptionClear();
nm.fnPtr = nullptr;
continue;
}
auto method = lsplant::JNI_ToReflectedMethod(env, clazz, mid, is_static);
auto modifier = lsplant::JNI_CallIntMethod(env, method, member_getModifiers);
if ((modifier & MODIFIER_NATIVE) == 0) {
nm.fnPtr = nullptr;
continue;
}
auto artMethod = lsplant::art::ArtMethod::FromReflectedMethod(env, method);
hooks.push_back(nm);
auto orig = artMethod->GetData();
LOGV("replaced %s %s orig %p", clz, nm.name, orig);
nm.fnPtr = orig;
}
if (hooks.empty())
return;
old_functions->RegisterNatives(env, env->FindClass(clz), hooks.data(), static_cast<int>(hooks.size()));
if (hooks.empty()) return;
env->RegisterNatives(clazz, hooks.data(), hooks.size());
}
// JNI method hook definitions, auto generated
#include "jni_hooks.hpp"
void initialize_jni_hook() {
auto get_created_java_vms = reinterpret_cast<jint (*)(JavaVM **, jsize, jsize *)>(
dlsym(RTLD_DEFAULT, "JNI_GetCreatedJavaVMs"));
if (!get_created_java_vms) {
for (auto &map: lsplt::MapInfo::Scan()) {
if (!map.path.ends_with("/libnativehelper.so")) continue;
void *h = dlopen(map.path.data(), RTLD_LAZY);
if (!h) {
LOGW("cannot dlopen libnativehelper.so: %s", dlerror());
break;
}
get_created_java_vms = reinterpret_cast<decltype(get_created_java_vms)>(dlsym(h, "JNI_GetCreatedJavaVMs"));
dlclose(h);
break;
}
if (!get_created_java_vms) {
LOGW("JNI_GetCreatedJavaVMs not found");
return;
}
}
JavaVM *vm = nullptr;
jsize num = 0;
jint res = get_created_java_vms(&vm, 1, &num);
if (res != JNI_OK || vm == nullptr) return;
JNIEnv *env = nullptr;
res = vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6);
if (res != JNI_OK || env == nullptr) return;
auto classMember = lsplant::JNI_FindClass(env, "java/lang/reflect/Member");
if (classMember != nullptr) member_getModifiers = lsplant::JNI_GetMethodID(env, classMember, "getModifiers", "()I");
auto classModifier = lsplant::JNI_FindClass(env, "java/lang/reflect/Modifier");
if (classModifier != nullptr) {
auto fieldId = lsplant::JNI_GetStaticFieldID(env, classModifier, "NATIVE", "I");
if (fieldId != nullptr) MODIFIER_NATIVE = lsplant::JNI_GetStaticIntField(env, classModifier, fieldId);
}
if (member_getModifiers == nullptr || MODIFIER_NATIVE == 0) return;
if (!lsplant::art::ArtMethod::Init(env)) {
LOGE("failed to init ArtMethod");
return;
}
can_hook_jni = true;
do_hook_zygote(env);
}
// -----------------------------------------------------------------
ZygiskModule::ZygiskModule(int id, void *handle, void *entry)
: id(id), handle(handle), entry{entry}, api{}, mod{nullptr} {
// Make sure all pointers are null
@@ -331,6 +348,7 @@ bool ZygiskModule::RegisterModuleImpl(ApiTable *api, long *module) {
api->v2.getFlags = [](auto) { return ZygiskModule::getFlags(); };
}
if (api_version >= 4) {
api->v4.pltHookCommit = lsplt::CommitHook;
api->v4.pltHookRegister = [](dev_t dev, ino_t inode, const char *symbol, void *fn, void **backup) {
if (dev == 0 || inode == 0 || symbol == nullptr || fn == nullptr)
return;
@@ -342,7 +360,7 @@ bool ZygiskModule::RegisterModuleImpl(ApiTable *api, long *module) {
return true;
}
void HookContext::plt_hook_register(const char *regex, const char *symbol, void *fn, void **backup) {
void ZygiskContext::plt_hook_register(const char *regex, const char *symbol, void *fn, void **backup) {
if (regex == nullptr || symbol == nullptr || fn == nullptr)
return;
regex_t re;
@@ -352,7 +370,7 @@ void HookContext::plt_hook_register(const char *regex, const char *symbol, void
register_info.emplace_back(RegisterInfo{re, symbol, fn, backup});
}
void HookContext::plt_hook_exclude(const char *regex, const char *symbol) {
void ZygiskContext::plt_hook_exclude(const char *regex, const char *symbol) {
if (!regex) return;
regex_t re;
if (regcomp(&re, regex, REG_NOSUB) != 0)
@@ -361,7 +379,7 @@ void HookContext::plt_hook_exclude(const char *regex, const char *symbol) {
ignore_info.emplace_back(IgnoreInfo{re, symbol ?: ""});
}
void HookContext::plt_hook_process_regex() {
void ZygiskContext::plt_hook_process_regex() {
if (register_info.empty())
return;
for (auto &map : lsplt::MapInfo::Scan()) {
@@ -385,7 +403,7 @@ void HookContext::plt_hook_process_regex() {
}
}
bool HookContext::plt_hook_commit() {
bool ZygiskContext::plt_hook_commit() {
{
mutex_guard lock(hook_info_lock);
plt_hook_process_regex();
@@ -447,8 +465,7 @@ int sigmask(int how, int signum) {
return sigprocmask(how, &set, nullptr);
}
void HookContext::fork_pre() {
g_ctx = this;
void ZygiskContext::fork_pre() {
// Do our own fork before loading any 3rd party code
// First block SIGCHLD, unblock after original fork is done
sigmask(SIG_BLOCK, SIGCHLD);
@@ -470,7 +487,7 @@ void HookContext::fork_pre() {
allowed_fds[dirfd(dir.get())] = false;
}
void HookContext::sanitize_fds() {
void ZygiskContext::sanitize_fds() {
if (flags[SKIP_FD_SANITIZATION])
return;
@@ -526,15 +543,14 @@ void HookContext::sanitize_fds() {
}
}
void HookContext::fork_post() {
void ZygiskContext::fork_post() {
// Unblock SIGCHLD in case the original method didn't
sigmask(SIG_UNBLOCK, SIGCHLD);
g_ctx = nullptr;
unload_zygisk();
}
/* Zygisksu changed: Load module fds */
void HookContext::run_modules_pre() {
void ZygiskContext::run_modules_pre() {
auto ms = zygiskd::ReadModules();
auto size = ms.size();
for (size_t i = 0; i < size; i++) {
@@ -555,7 +571,7 @@ void HookContext::run_modules_pre() {
}
}
void HookContext::run_modules_post() {
void ZygiskContext::run_modules_post() {
flags[POST_SPECIALIZE] = true;
for (const auto &m : modules) {
if (flags[APP_SPECIALIZE]) {
@@ -565,17 +581,109 @@ void HookContext::run_modules_post() {
}
m.tryUnload();
}
// Remove from SoList to avoid detection
bool solist_res = SoList::Initialize();
if (!solist_res) {
LOGE("Failed to initialize SoList");
} else {
SoList::NullifySoName("jit-cache");
}
// Remap as well to avoid checking of /memfd:jit-cache
for (auto &info : lsplt::MapInfo::Scan()) {
if (strstr(info.path.c_str(), "jit-cache-zygisk"))
{
void *addr = (void *)info.start;
size_t size = info.end - info.start;
// MAP_SHARED should fix the suspicious mapping.
void *copy = mmap(nullptr, size, PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (copy == MAP_FAILED) {
LOGE("Failed to mmap jit-cache-zygisk");
continue;
}
if ((info.perms & PROT_READ) == 0) {
mprotect(addr, size, PROT_READ);
}
memcpy(copy, addr, size);
mremap(copy, size, size, MREMAP_MAYMOVE | MREMAP_FIXED, addr);
mprotect(addr, size, info.perms);
}
}
// Don't know if there's a header for things like this
// so I just put it into a lambda
auto generateRandomString = [](char *str, int length) {
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
srand(time(NULL));
for (int i = 0; i < length; i++) {
int key = rand() % (sizeof(charset) - 1);
str[i] = charset[key];
}
str[length] = '\0';
};
// Randomize name of anonymous mappings
// We don't run this in the previous loop because LSPosed might also add
// mappings that are not related to /memfd:jit-zygisk-cache
//
// Since we changed to MAP_SHARED, I don't think this is still needed but let's
// leave it here just in case.
for (auto info : lsplt::MapInfo::Scan()) {
// I had some problems with info.perms & PROT_EXEC so I had to change lsplt source a bit.
// If that problem occurs here, do strchr(info.perms_str.c_str(), 'x') instead and add perms_str
// to the lsplt MapInfo struct and set it to the raw perms string in Scan();
if (info.perms & PROT_EXEC && info.path.empty()) {
// Generate Random Name
char randomString[11];
generateRandomString(randomString, 10);
LOGI("Randomized Memory map name: %s", randomString);
// Memory address of random string
uintptr_t strAddr = (uintptr_t)&randomString;
// https://lore.kernel.org/lkml/1383170047-21074-2-git-send-email-ccross@android.com/
prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, info.start, info.end - info.start, strAddr);
}
// Remap as MAP_SHARED
if (info.perms & PROT_EXEC && info.dev == 0 && info.path.find("anon") != std::string::npos) {
void *addr = reinterpret_cast<void *>(info.start);
size_t size = info.end - info.start;
void *copy = mmap(nullptr, size, PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if ((info.perms & PROT_READ) == 0) {
mprotect(addr, size, PROT_READ);
}
memcpy(copy, addr, size);
mremap(copy, size, size, MREMAP_MAYMOVE | MREMAP_FIXED, addr);
mprotect(addr, size, info.perms);
}
}
}
/* Zygisksu changed: Load module fds */
void HookContext::app_specialize_pre() {
void ZygiskContext::app_specialize_pre() {
flags[APP_SPECIALIZE] = true;
info_flags = zygiskd::GetProcessFlags(g_ctx->args.app->uid);
run_modules_pre();
if ((info_flags & PROCESS_ON_DENYLIST) == PROCESS_ON_DENYLIST) {
flags[DO_REVERT_UNMOUNT] = true;
}
if ((info_flags & (PROCESS_IS_MANAGER | PROCESS_ROOT_IS_MAGISK)) == (PROCESS_IS_MANAGER | PROCESS_ROOT_IS_MAGISK)) {
LOGI("Manager process detected. Notifying that Zygisk has been enabled.");
setenv("ZYGISK_ENABLED", "1", 1);
} else {
run_modules_pre();
}
}
void HookContext::app_specialize_post() {
void ZygiskContext::app_specialize_post() {
run_modules_post();
// Cleanups
@@ -584,23 +692,7 @@ void HookContext::app_specialize_post() {
logging::setfd(-1);
}
void HookContext::unload_zygisk() {
if (flags[CAN_UNLOAD_ZYGISK]) {
// Do NOT call the destructor
operator delete(jni_method_map);
// Directly unmap the whole memory block
jni_hook::memory_block::release();
// Strip out all API function pointers
for (auto &m : modules) {
m.clearApi();
}
new_daemon_thread(reinterpret_cast<thread_entry>(&dlclose), self_handle);
}
}
bool HookContext::exempt_fd(int fd) {
bool ZygiskContext::exempt_fd(int fd) {
if (flags[POST_SPECIALIZE] || flags[SKIP_FD_SANITIZATION])
return true;
if (!flags[APP_FORK_AND_SPECIALIZE])
@@ -611,24 +703,22 @@ bool HookContext::exempt_fd(int fd) {
// -----------------------------------------------------------------
void HookContext::nativeSpecializeAppProcess_pre() {
void ZygiskContext::nativeSpecializeAppProcess_pre() {
process = env->GetStringUTFChars(args.app->nice_name, nullptr);
LOGV("pre specialize [%s]\n", process);
g_ctx = this;
LOGV("pre specialize [%s]", process);
// App specialize does not check FD
flags[SKIP_FD_SANITIZATION] = true;
app_specialize_pre();
}
void HookContext::nativeSpecializeAppProcess_post() {
LOGV("post specialize [%s]\n", process);
void ZygiskContext::nativeSpecializeAppProcess_post() {
LOGV("post specialize [%s]", process);
app_specialize_post();
unload_zygisk();
}
/* Zygisksu changed: No system_server status write back */
void HookContext::nativeForkSystemServer_pre() {
LOGV("pre forkSystemServer\n");
void ZygiskContext::nativeForkSystemServer_pre() {
LOGV("pre forkSystemServer");
flags[SERVER_FORK_AND_SPECIALIZE] = true;
fork_pre();
@@ -636,21 +726,22 @@ void HookContext::nativeForkSystemServer_pre() {
return;
run_modules_pre();
zygiskd::SystemServerStarted();
sanitize_fds();
}
void HookContext::nativeForkSystemServer_post() {
void ZygiskContext::nativeForkSystemServer_post() {
if (pid == 0) {
LOGV("post forkSystemServer\n");
LOGV("post forkSystemServer");
run_modules_post();
}
fork_post();
}
void HookContext::nativeForkAndSpecialize_pre() {
void ZygiskContext::nativeForkAndSpecialize_pre() {
process = env->GetStringUTFChars(args.app->nice_name, nullptr);
LOGV("pre forkAndSpecialize [%s]\n", process);
LOGV("pre forkAndSpecialize [%s]", process);
flags[APP_FORK_AND_SPECIALIZE] = true;
/* Zygisksu changed: No args.app->fds_to_ignore check since we are Android 10+ */
@@ -665,28 +756,59 @@ void HookContext::nativeForkAndSpecialize_pre() {
sanitize_fds();
}
void HookContext::nativeForkAndSpecialize_post() {
void ZygiskContext::nativeForkAndSpecialize_post() {
if (pid == 0) {
LOGV("post forkAndSpecialize [%s]\n", process);
LOGV("post forkAndSpecialize [%s]", process);
app_specialize_post();
}
fork_post();
}
ZygiskContext::~ZygiskContext() {
// This global pointer points to a variable on the stack.
// Set this to nullptr to prevent leaking local variable.
// This also disables most plt hooked functions.
g_ctx = nullptr;
if (!is_child())
return;
should_unmap_zygisk = true;
// Unhook JNI methods
for (const auto &[clz, methods] : *jni_hook_list) {
if (!methods.empty() && env->RegisterNatives(
env->FindClass(clz.data()), methods.data(),
static_cast<int>(methods.size())) != 0) {
LOGE("Failed to restore JNI hook of class [%s]", clz.data());
should_unmap_zygisk = false;
}
}
delete jni_hook_list;
jni_hook_list = nullptr;
// Strip out all API function pointers
for (auto &m : modules) {
m.clearApi();
}
hook_unloader();
}
} // namespace
static bool hook_commit() {
if (lsplt::CommitHook()) {
return true;
} else {
LOGE("plt_hook failed\n");
LOGE("plt_hook failed");
return false;
}
}
static void hook_register(dev_t dev, ino_t inode, const char *symbol, void *new_func, void **old_func) {
if (!lsplt::RegisterHook(dev, inode, symbol, new_func, old_func)) {
LOGE("Failed to register plt_hook \"%s\"\n", symbol);
LOGE("Failed to register plt_hook \"%s\"", symbol);
return;
}
plt_hook_list->emplace_back(dev, inode, symbol, old_func);
@@ -701,22 +823,25 @@ static void hook_register(dev_t dev, ino_t inode, const char *symbol, void *new_
void hook_functions() {
default_new(plt_hook_list);
default_new(jni_hook_list);
default_new(jni_method_map);
ino_t android_runtime_inode = 0;
dev_t android_runtime_dev = 0;
/* TODO by ThePedroo: Implement injection via native bridge */
// ino_t native_bridge_inode = 0;
// dev_t native_bridge_dev = 0;
for (auto &map : lsplt::MapInfo::Scan()) {
if (map.path.ends_with("libandroid_runtime.so")) {
android_runtime_inode = map.inode;
android_runtime_dev = map.dev;
break;
}
}
PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, fork);
PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, unshare);
PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, selinux_android_setcontext);
PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, androidSetCreateThreadFunc);
PLT_HOOK_REGISTER(android_runtime_dev, android_runtime_inode, strdup);
PLT_HOOK_REGISTER_SYM(android_runtime_dev, android_runtime_inode, "__android_log_close", android_log_close);
hook_commit();
@@ -727,38 +852,32 @@ void hook_functions() {
plt_hook_list->end());
}
static bool unhook_functions() {
bool success = true;
static void hook_unloader() {
ino_t art_inode = 0;
dev_t art_dev = 0;
// Restore JNIEnv
if (g_ctx->env->functions == new_functions) {
g_ctx->env->functions = old_functions;
delete new_functions;
}
// Unhook JNI methods
for (const auto &[clz, methods] : *jni_hook_list) {
if (!methods.empty() && g_ctx->env->RegisterNatives(
g_ctx->env->FindClass(clz.data()), methods.data(),
static_cast<int>(methods.size())) != 0) {
LOGE("Failed to restore JNI hook of class [%s]\n", clz.data());
success = false;
for (auto &map : lsplt::MapInfo::Scan()) {
if (map.path.ends_with("/libart.so")) {
art_inode = map.inode;
art_dev = map.dev;
break;
}
}
delete jni_hook_list;
PLT_HOOK_REGISTER(art_dev, art_inode, pthread_attr_destroy);
hook_commit();
}
static void unhook_functions() {
// Unhook plt_hook
for (const auto &[dev, inode, sym, old_func] : *plt_hook_list) {
if (!lsplt::RegisterHook(dev, inode, sym, *old_func, nullptr)) {
LOGE("Failed to register plt_hook [%s]\n", sym);
success = false;
LOGE("Failed to register plt_hook [%s]", sym);
}
}
delete plt_hook_list;
if (!hook_commit()) {
LOGE("Failed to restore plt_hook\n");
success = false;
LOGE("Failed to restore plt_hook");
should_unmap_zygisk = false;
}
return success;
}

File diff suppressed because it is too large Load Diff

View File

@@ -4,10 +4,8 @@ namespace {
void *nativeForkAndSpecialize_orig = nullptr;
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_l(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_l)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, instruction_set, app_data_dir
@@ -16,11 +14,9 @@ void *nativeForkAndSpecialize_orig = nullptr;
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_o(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.fds_to_ignore = &fds_to_ignore;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_o)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, instruction_set, app_data_dir
@@ -29,12 +25,10 @@ void *nativeForkAndSpecialize_orig = nullptr;
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_p(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.fds_to_ignore = &fds_to_ignore;
args.is_child_zygote = &is_child_zygote;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_p)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir
@@ -43,13 +37,11 @@ void *nativeForkAndSpecialize_orig = nullptr;
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_q_alt(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.fds_to_ignore = &fds_to_ignore;
args.is_child_zygote = &is_child_zygote;
args.is_top_app = &is_top_app;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_q_alt)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app
@@ -58,7 +50,7 @@ void *nativeForkAndSpecialize_orig = nullptr;
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_r(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.fds_to_ignore = &fds_to_ignore;
args.is_child_zygote = &is_child_zygote;
args.is_top_app = &is_top_app;
@@ -66,9 +58,7 @@ void *nativeForkAndSpecialize_orig = nullptr;
args.whitelisted_data_info_list = &whitelisted_data_info_list;
args.mount_data_dirs = &mount_data_dirs;
args.mount_storage_dirs = &mount_storage_dirs;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_r)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs
@@ -76,11 +66,27 @@ void *nativeForkAndSpecialize_orig = nullptr;
ctx.nativeForkAndSpecialize_post();
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_u(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs, jboolean mount_sysprop_overrides) {
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.fds_to_ignore = &fds_to_ignore;
args.is_child_zygote = &is_child_zygote;
args.is_top_app = &is_top_app;
args.pkg_data_info_list = &pkg_data_info_list;
args.whitelisted_data_info_list = &whitelisted_data_info_list;
args.mount_data_dirs = &mount_data_dirs;
args.mount_storage_dirs = &mount_storage_dirs;
args.mount_sysprop_overrides = &mount_sysprop_overrides;
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_u)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs, mount_sysprop_overrides
);
ctx.nativeForkAndSpecialize_post();
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_samsung_m(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _0, jint _1, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_samsung_m)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _0, _1, nice_name, fds_to_close, instruction_set, app_data_dir
@@ -89,10 +95,8 @@ void *nativeForkAndSpecialize_orig = nullptr;
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_samsung_n(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _2, jint _3, jstring nice_name, jintArray fds_to_close, jstring instruction_set, jstring app_data_dir, jint _4) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_samsung_n)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _2, _3, nice_name, fds_to_close, instruction_set, app_data_dir, _4
@@ -101,11 +105,9 @@ void *nativeForkAndSpecialize_orig = nullptr;
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_samsung_o(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _5, jint _6, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.fds_to_ignore = &fds_to_ignore;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_samsung_o)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _5, _6, nice_name, fds_to_close, fds_to_ignore, instruction_set, app_data_dir
@@ -114,12 +116,10 @@ void *nativeForkAndSpecialize_orig = nullptr;
return ctx.pid;
}
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_samsung_p(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _7, jint _8, jstring nice_name, jintArray fds_to_close, jintArray fds_to_ignore, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.fds_to_ignore = &fds_to_ignore;
args.is_child_zygote = &is_child_zygote;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeForkAndSpecialize_pre();
reinterpret_cast<decltype(&nativeForkAndSpecialize_samsung_p)>(nativeForkAndSpecialize_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _7, _8, nice_name, fds_to_close, fds_to_ignore, is_child_zygote, instruction_set, app_data_dir
@@ -127,62 +127,64 @@ void *nativeForkAndSpecialize_orig = nullptr;
ctx.nativeForkAndSpecialize_post();
return ctx.pid;
}
const JNINativeMethod nativeForkAndSpecialize_methods[] = {
{
std::array nativeForkAndSpecialize_methods = {
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;Ljava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
(void *) &nativeForkAndSpecialize_l
},
{
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;Ljava/lang/String;[I[ILjava/lang/String;Ljava/lang/String;)I",
(void *) &nativeForkAndSpecialize_o
},
{
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
(void *) &nativeForkAndSpecialize_p
},
{
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z)I",
(void *) &nativeForkAndSpecialize_q_alt
},
{
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZ)I",
(void *) &nativeForkAndSpecialize_r
},
{
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;Ljava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZZ)I",
(void *) &nativeForkAndSpecialize_u
},
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;IILjava/lang/String;[ILjava/lang/String;Ljava/lang/String;)I",
(void *) &nativeForkAndSpecialize_samsung_m
},
{
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;IILjava/lang/String;[ILjava/lang/String;Ljava/lang/String;I)I",
(void *) &nativeForkAndSpecialize_samsung_n
},
{
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;IILjava/lang/String;[I[ILjava/lang/String;Ljava/lang/String;)I",
(void *) &nativeForkAndSpecialize_samsung_o
},
{
JNINativeMethod {
"nativeForkAndSpecialize",
"(II[II[[IILjava/lang/String;IILjava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
(void *) &nativeForkAndSpecialize_samsung_p
},
};
constexpr int nativeForkAndSpecialize_methods_num = std::size(nativeForkAndSpecialize_methods);
void *nativeSpecializeAppProcess_orig = nullptr;
[[clang::no_stack_protector]] void nativeSpecializeAppProcess_q(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.is_child_zygote = &is_child_zygote;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeSpecializeAppProcess_pre();
reinterpret_cast<decltype(&nativeSpecializeAppProcess_q)>(nativeSpecializeAppProcess_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir
@@ -190,12 +192,10 @@ void *nativeSpecializeAppProcess_orig = nullptr;
ctx.nativeSpecializeAppProcess_post();
}
[[clang::no_stack_protector]] void nativeSpecializeAppProcess_q_alt(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.is_child_zygote = &is_child_zygote;
args.is_top_app = &is_top_app;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeSpecializeAppProcess_pre();
reinterpret_cast<decltype(&nativeSpecializeAppProcess_q_alt)>(nativeSpecializeAppProcess_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app
@@ -203,64 +203,78 @@ void *nativeSpecializeAppProcess_orig = nullptr;
ctx.nativeSpecializeAppProcess_post();
}
[[clang::no_stack_protector]] void nativeSpecializeAppProcess_r(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.is_child_zygote = &is_child_zygote;
args.is_top_app = &is_top_app;
args.pkg_data_info_list = &pkg_data_info_list;
args.whitelisted_data_info_list = &whitelisted_data_info_list;
args.mount_data_dirs = &mount_data_dirs;
args.mount_storage_dirs = &mount_storage_dirs;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeSpecializeAppProcess_pre();
reinterpret_cast<decltype(&nativeSpecializeAppProcess_r)>(nativeSpecializeAppProcess_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs
);
ctx.nativeSpecializeAppProcess_post();
}
[[clang::no_stack_protector]] void nativeSpecializeAppProcess_samsung_q(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _9, jint _10, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v3 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
[[clang::no_stack_protector]] void nativeSpecializeAppProcess_u(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir, jboolean is_top_app, jobjectArray pkg_data_info_list, jobjectArray whitelisted_data_info_list, jboolean mount_data_dirs, jboolean mount_storage_dirs, jboolean mount_sysprop_overrides) {
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.is_child_zygote = &is_child_zygote;
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
args.is_top_app = &is_top_app;
args.pkg_data_info_list = &pkg_data_info_list;
args.whitelisted_data_info_list = &whitelisted_data_info_list;
args.mount_data_dirs = &mount_data_dirs;
args.mount_storage_dirs = &mount_storage_dirs;
args.mount_sysprop_overrides = &mount_sysprop_overrides;
ZygiskContext ctx(env, &args);
ctx.nativeSpecializeAppProcess_pre();
reinterpret_cast<decltype(&nativeSpecializeAppProcess_u)>(nativeSpecializeAppProcess_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, is_child_zygote, instruction_set, app_data_dir, is_top_app, pkg_data_info_list, whitelisted_data_info_list, mount_data_dirs, mount_storage_dirs, mount_sysprop_overrides
);
ctx.nativeSpecializeAppProcess_post();
}
[[clang::no_stack_protector]] void nativeSpecializeAppProcess_samsung_q(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jint mount_external, jstring se_info, jint _9, jint _10, jstring nice_name, jboolean is_child_zygote, jstring instruction_set, jstring app_data_dir) {
AppSpecializeArgs_v5 args(uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, nice_name, instruction_set, app_data_dir);
args.is_child_zygote = &is_child_zygote;
ZygiskContext ctx(env, &args);
ctx.nativeSpecializeAppProcess_pre();
reinterpret_cast<decltype(&nativeSpecializeAppProcess_samsung_q)>(nativeSpecializeAppProcess_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, mount_external, se_info, _9, _10, nice_name, is_child_zygote, instruction_set, app_data_dir
);
ctx.nativeSpecializeAppProcess_post();
}
const JNINativeMethod nativeSpecializeAppProcess_methods[] = {
{
std::array nativeSpecializeAppProcess_methods = {
JNINativeMethod {
"nativeSpecializeAppProcess",
"(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V",
(void *) &nativeSpecializeAppProcess_q
},
{
JNINativeMethod {
"nativeSpecializeAppProcess",
"(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z)V",
(void *) &nativeSpecializeAppProcess_q_alt
},
{
JNINativeMethod {
"nativeSpecializeAppProcess",
"(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZ)V",
(void *) &nativeSpecializeAppProcess_r
},
{
JNINativeMethod {
"nativeSpecializeAppProcess",
"(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZZ)V",
(void *) &nativeSpecializeAppProcess_u
},
JNINativeMethod {
"nativeSpecializeAppProcess",
"(II[II[[IILjava/lang/String;IILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V",
(void *) &nativeSpecializeAppProcess_samsung_q
},
};
constexpr int nativeSpecializeAppProcess_methods_num = std::size(nativeSpecializeAppProcess_methods);
void *nativeForkSystemServer_orig = nullptr;
[[clang::no_stack_protector]] jint nativeForkSystemServer_l(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities) {
ServerSpecializeArgs_v1 args(uid, gid, gids, runtime_flags, permitted_capabilities, effective_capabilities);
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeForkSystemServer_pre();
reinterpret_cast<decltype(&nativeForkSystemServer_l)>(nativeForkSystemServer_orig)(
env, clazz, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities, effective_capabilities
@@ -270,9 +284,7 @@ void *nativeForkSystemServer_orig = nullptr;
}
[[clang::no_stack_protector]] jint nativeForkSystemServer_samsung_q(JNIEnv *env, jclass clazz, jint uid, jint gid, jintArray gids, jint runtime_flags, jint _11, jint _12, jobjectArray rlimits, jlong permitted_capabilities, jlong effective_capabilities) {
ServerSpecializeArgs_v1 args(uid, gid, gids, runtime_flags, permitted_capabilities, effective_capabilities);
HookContext ctx;
ctx.env = env;
ctx.args = { &args };
ZygiskContext ctx(env, &args);
ctx.nativeForkSystemServer_pre();
reinterpret_cast<decltype(&nativeForkSystemServer_samsung_q)>(nativeForkSystemServer_orig)(
env, clazz, uid, gid, gids, runtime_flags, _11, _12, rlimits, permitted_capabilities, effective_capabilities
@@ -280,45 +292,48 @@ void *nativeForkSystemServer_orig = nullptr;
ctx.nativeForkSystemServer_post();
return ctx.pid;
}
const JNINativeMethod nativeForkSystemServer_methods[] = {
{
std::array nativeForkSystemServer_methods = {
JNINativeMethod {
"nativeForkSystemServer",
"(II[II[[IJJ)I",
(void *) &nativeForkSystemServer_l
},
{
JNINativeMethod {
"nativeForkSystemServer",
"(II[IIII[[IJJ)I",
(void *) &nativeForkSystemServer_samsung_q
},
};
constexpr int nativeForkSystemServer_methods_num = std::size(nativeForkSystemServer_methods);
unique_ptr<JNINativeMethod[]> hookAndSaveJNIMethods(const char *className, const JNINativeMethod *methods, int numMethods) {
unique_ptr<JNINativeMethod[]> newMethods;
int clz_id = -1;
int hook_cnt = 0;
do {
if (className == "com/android/internal/os/Zygote"sv) {
clz_id = 0;
hook_cnt = 3;
break;
}
} while (false);
if (hook_cnt) {
newMethods = make_unique<JNINativeMethod[]>(numMethods);
memcpy(newMethods.get(), methods, sizeof(JNINativeMethod) * numMethods);
}
auto &class_map = (*jni_method_map)[className];
for (int i = 0; i < numMethods; ++i) {
if (hook_cnt && clz_id == 0) {
HOOK_JNI(nativeForkAndSpecialize)
HOOK_JNI(nativeSpecializeAppProcess)
HOOK_JNI(nativeForkSystemServer)
}
class_map[methods[i].name][methods[i].signature] = methods[i].fnPtr;
}
return newMethods;
}
} // namespace
static void do_hook_zygote(JNIEnv *env) {
vector<JNINativeMethod> hooks;
const char *clz;
clz = "com/android/internal/os/Zygote";
hookJniNativeMethods(env, clz, nativeForkAndSpecialize_methods.data(), nativeForkAndSpecialize_methods.size());
for (auto &method : nativeForkAndSpecialize_methods) {
if (method.fnPtr) {
nativeForkAndSpecialize_orig = method.fnPtr;
hooks.emplace_back(method);
break;
}
}
hookJniNativeMethods(env, clz, nativeSpecializeAppProcess_methods.data(), nativeSpecializeAppProcess_methods.size());
for (auto &method : nativeSpecializeAppProcess_methods) {
if (method.fnPtr) {
nativeSpecializeAppProcess_orig = method.fnPtr;
hooks.emplace_back(method);
break;
}
}
hookJniNativeMethods(env, clz, nativeForkSystemServer_methods.data(), nativeForkSystemServer_methods.size());
for (auto &method : nativeForkSystemServer_methods) {
if (method.fnPtr) {
nativeForkSystemServer_orig = method.fnPtr;
hooks.emplace_back(method);
break;
}
}
jni_hook_list->emplace(clz, std::move(hooks));
}

View File

@@ -1,31 +0,0 @@
#include "memory.hpp"
namespace jni_hook {
// We know our minimum alignment is WORD size (size of pointer)
static constexpr size_t ALIGN = sizeof(long);
// 4MB is more than enough
static constexpr size_t CAPACITY = (1 << 22);
// No need to be thread safe as the initial mmap always happens on the main thread
static uint8_t *_area = nullptr;
static std::atomic<uint8_t *> _curr = nullptr;
void *memory_block::allocate(size_t sz) {
if (!_area) {
// Memory will not actually be allocated because physical pages are mapped in on-demand
_area = static_cast<uint8_t *>(mmap(
nullptr, CAPACITY, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
_curr = _area;
}
return _curr.fetch_add(align_to(sz, ALIGN));
}
void memory_block::release() {
if (_area)
munmap(_area, CAPACITY);
}
} // namespace jni_hook

View File

@@ -1,44 +0,0 @@
#pragma once
#include <map>
#include <sys/mman.h>
#pragma clang diagnostic push
#include <parallel_hashmap/phmap.h>
#pragma clang diagnostic pop
#include "misc.hpp"
namespace jni_hook {
struct memory_block {
static void *allocate(size_t sz);
static void deallocate(void *, size_t) { /* Monotonic increase */ }
static void release();
};
template<class T>
using allocator = stateless_allocator<T, memory_block>;
using string = std::basic_string<char, std::char_traits<char>, allocator<char>>;
// Use node_hash_map since it will use less memory because we are using a monotonic allocator
template<class K, class V>
using hash_map = phmap::node_hash_map<K, V,
phmap::priv::hash_default_hash<K>,
phmap::priv::hash_default_eq<K>,
allocator<std::pair<const K, V>>
>;
template<class K, class V>
using tree_map = std::map<K, V,
std::less<K>,
allocator<std::pair<const K, V>>
>;
} // namespace jni_hook
// Provide heterogeneous lookup for jni_hook::string
namespace phmap::priv {
template <> struct HashEq<jni_hook::string> : StringHashEqT<char> {};
} // namespace phmap::priv

View File

@@ -5,23 +5,26 @@
namespace {
struct HookContext;
struct ZygiskContext;
struct ZygiskModule;
struct AppSpecializeArgs_v1;
using AppSpecializeArgs_v2 = AppSpecializeArgs_v1;
struct AppSpecializeArgs_v3;
using AppSpecializeArgs_v4 = AppSpecializeArgs_v3;
struct AppSpecializeArgs_v5;
struct module_abi_v1;
using module_abi_v2 = module_abi_v1;
using module_abi_v3 = module_abi_v1;
using module_abi_v4 = module_abi_v1;
using module_abi_v5 = module_abi_v1;
struct api_abi_v1;
struct api_abi_v2;
using api_abi_v3 = api_abi_v2;
struct api_abi_v4;
using api_abi_v5 = api_abi_v4;
union ApiTable;
@@ -54,6 +57,17 @@ namespace {
instruction_set(instruction_set), app_data_dir(app_data_dir) {}
};
struct AppSpecializeArgs_v5 : public AppSpecializeArgs_v3 {
jboolean *mount_sysprop_overrides = nullptr;
AppSpecializeArgs_v5(
jint &uid, jint &gid, jintArray &gids, jint &runtime_flags,
jobjectArray &rlimits, jint &mount_external, jstring &se_info, jstring &nice_name,
jstring &instruction_set, jstring &app_data_dir) : AppSpecializeArgs_v3(
uid, gid, gids, runtime_flags, rlimits, mount_external,
se_info, nice_name, instruction_set, app_data_dir) {}
};
struct AppSpecializeArgs_v1 {
jint &uid;
jint &gid;
@@ -72,14 +86,14 @@ namespace {
jboolean *const mount_data_dirs;
jboolean *const mount_storage_dirs;
AppSpecializeArgs_v1(const AppSpecializeArgs_v3 *v3) :
uid(v3->uid), gid(v3->gid), gids(v3->gids), runtime_flags(v3->runtime_flags),
mount_external(v3->mount_external), se_info(v3->se_info), nice_name(v3->nice_name),
instruction_set(v3->instruction_set), app_data_dir(v3->app_data_dir),
is_child_zygote(v3->is_child_zygote), is_top_app(v3->is_top_app),
pkg_data_info_list(v3->pkg_data_info_list),
whitelisted_data_info_list(v3->whitelisted_data_info_list),
mount_data_dirs(v3->mount_data_dirs), mount_storage_dirs(v3->mount_storage_dirs) {}
AppSpecializeArgs_v1(const AppSpecializeArgs_v5 *a) :
uid(a->uid), gid(a->gid), gids(a->gids), runtime_flags(a->runtime_flags),
mount_external(a->mount_external), se_info(a->se_info), nice_name(a->nice_name),
instruction_set(a->instruction_set), app_data_dir(a->app_data_dir),
is_child_zygote(a->is_child_zygote), is_top_app(a->is_top_app),
pkg_data_info_list(a->pkg_data_info_list),
whitelisted_data_info_list(a->whitelisted_data_info_list),
mount_data_dirs(a->mount_data_dirs), mount_storage_dirs(a->mount_storage_dirs) {}
};
struct ServerSpecializeArgs_v1 {
@@ -111,6 +125,8 @@ namespace {
PROCESS_GRANTED_ROOT = zygisk::StateFlag::PROCESS_GRANTED_ROOT,
PROCESS_ON_DENYLIST = zygisk::StateFlag::PROCESS_ON_DENYLIST,
PROCESS_IS_MANAGER = (1u << 28),
PROCESS_ROOT_IS_APATCH = (1u << 27),
PROCESS_ROOT_IS_KSU = (1u << 29),
PROCESS_ROOT_IS_MAGISK = (1u << 30),
PROCESS_IS_SYS_UI = (1u << 31),
@@ -165,6 +181,7 @@ case 2: { \
} \
case 3: \
case 4: \
case 5: \
mod.v1->method(mod.v1->impl, args);\
break; \
}
@@ -174,10 +191,10 @@ case 4: \
void onLoad(void *env) {
entry.fn(&api, env);
}
void preAppSpecialize(AppSpecializeArgs_v3 *args) const {
void preAppSpecialize(AppSpecializeArgs_v5 *args) const {
call_app(preAppSpecialize)
}
void postAppSpecialize(const AppSpecializeArgs_v3 *args) const {
void postAppSpecialize(const AppSpecializeArgs_v5 *args) const {
call_app(postAppSpecialize)
}
void preServerSpecialize(ServerSpecializeArgs_v1 *args) const {

View File

@@ -10,32 +10,24 @@ using namespace std::string_view_literals;
namespace {
constexpr auto MODULE_DIR = "/data/adb/modules";
struct overlay_backup {
std::string target;
std::string vfs_option;
std::string fs_option;
};
constexpr auto KSU_OVERLAY_SOURCE = "KSU";
constexpr auto AP_OVERLAY_SOURCE = "APatch";
const std::vector<std::string> DEVICE_PARTITIONS{"/system", "/vendor", "/product", "/system_ext", "/odm", "/oem"};
void lazy_unmount(const char* mountpoint) {
if (umount2(mountpoint, MNT_DETACH) != -1) {
LOGD("Unmounted (%s)", mountpoint);
} else {
#ifndef NDEBUG
PLOGE("Unmount (%s)", mountpoint);
#endif
}
}
}
#define PARSE_OPT(name, flag) \
if (opt == (name)) { \
flags |= (flag); \
return true; \
}
void revert_unmount_ksu() {
std::string ksu_loop;
std::vector<std::string> targets;
std::list<overlay_backup> backups;
// Unmount ksu module dir last
targets.emplace_back(MODULE_DIR);
@@ -45,22 +37,19 @@ void revert_unmount_ksu() {
ksu_loop = info.source;
continue;
}
// Unmount everything on /data/adb except ksu module dir
// Unmount everything mounted to /data/adb
if (info.target.starts_with("/data/adb")) {
targets.emplace_back(info.target);
}
// Unmount ksu overlays
if (info.type == "overlay") {
if (str_contains(info.fs_option, MODULE_DIR)) {
targets.emplace_back(info.target);
} else {
auto backup = overlay_backup{
.target = info.target,
.vfs_option = info.vfs_option,
.fs_option = info.fs_option,
};
backups.emplace_back(backup);
}
if (info.type == "overlay"
&& info.source == KSU_OVERLAY_SOURCE
&& std::find(DEVICE_PARTITIONS.begin(), DEVICE_PARTITIONS.end(), info.target) != DEVICE_PARTITIONS.end()) {
targets.emplace_back(info.target);
}
// Unmount temp dir
if (info.type == "tmpfs" && info.source == KSU_OVERLAY_SOURCE) {
targets.emplace_back(info.target);
}
}
for (auto& info: parse_mount_info("self")) {
@@ -74,34 +63,6 @@ void revert_unmount_ksu() {
for (auto& s: reversed(targets)) {
lazy_unmount(s.data());
}
// Affirm unmounted system overlays
for (auto& info: parse_mount_info("self")) {
if (info.type == "overlay") {
backups.remove_if([&](overlay_backup& mnt) {
return mnt.target == info.target && mnt.fs_option == info.fs_option;
});
}
}
// Restore system overlays
for (auto& mnt: backups) {
auto opts = split_str(mnt.vfs_option, ",");
opts.splice(opts.end(), split_str(mnt.fs_option, ","));
unsigned long flags = 0;
opts.remove_if([&](auto& opt) {
PARSE_OPT(MNTOPT_RO, MS_RDONLY)
PARSE_OPT(MNTOPT_NOSUID, MS_NOSUID)
PARSE_OPT("relatime", MS_RELATIME)
return false;
});
auto mnt_data = join_str(opts, ",");
if (mount("overlay", mnt.target.data(), "overlay", flags, mnt_data.data()) != -1) {
LOGD("Remounted (%s)", mnt.target.data());
} else {
PLOGE("Remount (%s, %s)", mnt.target.data(), mnt.fs_option.data());
}
}
}
void revert_unmount_magisk() {
@@ -114,9 +75,53 @@ void revert_unmount_magisk() {
info.root.starts_with("/adb/modules")) { // bind mount from data partition
targets.push_back(info.target);
}
// Unmount everything mounted to /data/adb
if (info.target.starts_with("/data/adb")) {
targets.emplace_back(info.target);
}
}
for (auto& s: reversed(targets)) {
lazy_unmount(s.data());
}
}
void revert_unmount_apatch() {
std::string ap_loop;
std::vector<std::string> targets;
// Unmount ksu module dir last
targets.emplace_back(MODULE_DIR);
for (auto& info: parse_mount_info("self")) {
if (info.target == MODULE_DIR) {
ap_loop = info.source;
continue;
}
// Unmount everything mounted to /data/adb
if (info.target.starts_with("/data/adb")) {
targets.emplace_back(info.target);
}
// Unmount ksu overlays
if (info.type == "overlay"
&& info.source == AP_OVERLAY_SOURCE
&& std::find(DEVICE_PARTITIONS.begin(), DEVICE_PARTITIONS.end(), info.target) != DEVICE_PARTITIONS.end()) {
targets.emplace_back(info.target);
}
// Unmount temp dir
if (info.type == "tmpfs" && info.source == AP_OVERLAY_SOURCE) {
targets.emplace_back(info.target);
}
}
for (auto& info: parse_mount_info("self")) {
// Unmount everything from ksu loop except ksu module dir
if (info.source == ap_loop && info.target != MODULE_DIR) {
targets.emplace_back(info.target);
}
}
// Do unmount
for (auto& s: reversed(targets)) {
lazy_unmount(s.data());
}
}

View File

@@ -12,3 +12,4 @@ void revert_unmount_ksu();
void revert_unmount_magisk();
void revert_unmount_apatch();

View File

@@ -1,100 +0,0 @@
#include <string_view>
#include <sys/system_properties.h>
#include <unistd.h>
#include <array>
#include "daemon.h"
#include "dl.h"
#include "logging.h"
#include "native_bridge_callbacks.h"
extern "C" [[gnu::visibility("default")]]
uint8_t NativeBridgeItf[sizeof(NativeBridgeCallbacks<__ANDROID_API_R__>) * 2]{0};
namespace {
constexpr auto kZygoteProcesses = {"zygote", "zygote32", "zygote64", "usap32", "usap64"};
constexpr auto kInjector = "/system/" LP_SELECT("lib", "lib64") "/libzygisk_injector.so";
void* sOriginalBridge = nullptr;
}
__used __attribute__((destructor))
void Destructor() {
if (sOriginalBridge) {
dlclose(sOriginalBridge);
}
}
__used __attribute__((constructor))
void Constructor() {
if (getuid() != 0) {
return;
}
std::string_view cmdline = getprogname();
if (std::none_of(
kZygoteProcesses.begin(), kZygoteProcesses.end(),
[&](const char* p) { return cmdline == p; }
)) {
LOGW("Not started as zygote (cmdline=%s)", cmdline.data());
return;
}
std::string native_bridge;
do {
if (!zygiskd::PingHeartbeat()) break;
#ifdef NDEBUG
logging::setfd(zygiskd::RequestLogcatFd());
#endif
LOGI("Read native bridge");
native_bridge = zygiskd::ReadNativeBridge();
LOGI("Load injector");
auto handle = DlopenExt(kInjector, RTLD_NOW);
if (handle == nullptr) {
LOGE("Failed to dlopen injector: %s", dlerror());
break;
}
auto entry = dlsym(handle, "entry");
if (entry == nullptr) {
LOGE("Failed to dlsym injector entry: %s", dlerror());
dlclose(handle);
break;
}
reinterpret_cast<void (*)(void*)>(entry)(handle);
} while (false);
do {
if (native_bridge.empty() || native_bridge == "0") break;
LOGI("Load original native bridge: %s", native_bridge.data());
sOriginalBridge = dlopen(native_bridge.data(), RTLD_NOW);
if (sOriginalBridge == nullptr) {
LOGE("%s", dlerror());
break;
}
auto* original_native_bridge_itf = dlsym(sOriginalBridge, "NativeBridgeItf");
if (original_native_bridge_itf == nullptr) {
LOGE("%s", dlerror());
break;
}
long sdk = 0;
char value[PROP_VALUE_MAX + 1];
if (__system_property_get("ro.build.version.sdk", value) > 0) {
sdk = strtol(value, nullptr, 10);
}
auto callbacks_size = 0;
if (sdk >= __ANDROID_API_R__) {
callbacks_size = sizeof(NativeBridgeCallbacks<__ANDROID_API_R__>);
} else if (sdk == __ANDROID_API_Q__) {
callbacks_size = sizeof(NativeBridgeCallbacks<__ANDROID_API_Q__>);
}
memcpy(NativeBridgeItf, original_native_bridge_itf, callbacks_size);
} while (false);
logging::setfd(-1);
}

114
loader/src/ptracer/main.cpp Normal file
View File

@@ -0,0 +1,114 @@
#include <stdio.h>
#include "monitor.h"
#include "utils.hpp"
#include "daemon.h"
int main(int argc, char **argv) {
zygiskd::Init("/data/adb/rezygisk");
printf("The ReZygisk Tracer %s\n\n", ZKSU_VERSION);
if (argc >= 2 && strcmp(argv[1], "monitor") == 0) {
init_monitor();
printf("[ReZygisk]: Started monitoring...\n");
return 0;
} else if (argc >= 3 && strcmp(argv[1], "trace") == 0) {
if (argc >= 4 && strcmp(argv[3], "--restart") == 0) zygiskd::ZygoteRestart();
long pid = strtol(argv[2], 0, 0);
if (!trace_zygote(pid)) {
kill(pid, SIGKILL);
return 1;
}
printf("[ReZygisk]: Tracing %ld...\n", pid);
return 0;
} else if (argc >= 2 && strcmp(argv[1], "ctl") == 0) {
enum Command command;
if (strcmp(argv[2], "start") == 0) command = START;
else if (strcmp(argv[2], "stop") == 0) command = STOP;
else if (strcmp(argv[2], "exit") == 0) command = EXIT;
else {
printf("[ReZygisk]: Usage: %s ctl <start|stop|exit>\n", argv[0]);
return 1;
}
if (send_control_command(command) == -1) {
printf("[ReZygisk]: Failed to send the command, is the daemon running?\n");
return 1;
}
printf("[ReZygisk]: command sent\n");
return 0;
} else if (argc >= 2 && strcmp(argv[1], "version") == 0) {
/* INFO: Noop*/
return 0;
} else if (argc >= 2 && strcmp(argv[1], "info") == 0) {
struct zygote_info info;
zygiskd::GetInfo(&info);
printf("Daemon process PID: %d\n", info.pid);
switch (info.root_impl) {
case ZYGOTE_ROOT_IMPL_NONE: {
printf("Root implementation: none\n");
break;
}
case ZYGOTE_ROOT_IMPL_APATCH: {
printf("Root implementation: APatch\n");
break;
}
case ZYGOTE_ROOT_IMPL_KERNELSU: {
printf("Root implementation: KernelSU\n");
break;
}
case ZYGOTE_ROOT_IMPL_MAGISK: {
printf("Root implementation: Magisk\n");
break;
}
}
if (info.modules->modules_count != 0) {
printf("Modules: %zu\n", info.modules->modules_count);
for (size_t i = 0; i < info.modules->modules_count; i++) {
printf(" - %s\n", info.modules->modules[i]);
free(info.modules->modules[i]);
}
free(info.modules->modules);
} else {
printf("Modules: N/A\n");
}
return 0;
} else {
printf(
"Available commands:\n"
" - monitor\n"
" - trace <pid> [--restart]\n"
" - ctl <start|stop|exit>\n"
" - version: Shows the version of ReZygisk.\n"
" - info: Shows information about the created daemon/injection.\n"
"\n"
"<...>: Obligatory\n"
"[...]: Optional\n");
return 1;
}
}

View File

@@ -0,0 +1,829 @@
#include <stdlib.h>
#include <sys/system_properties.h>
#include <unistd.h>
#include <set>
#include <sys/signalfd.h>
#include <err.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/epoll.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <fcntl.h>
#include "monitor.h"
#include "utils.hpp"
#include "files.hpp"
#include "misc.hpp"
#define STOPPED_WITH(sig, event) WIFSTOPPED(status) && (status >> 8 == ((sig) | (event << 8)))
static void updateStatus();
char monitor_stop_reason[32];
constexpr char SOCKET_NAME[] = "init_monitor";
struct EventLoop;
struct EventHandler {
virtual int GetFd() = 0;
virtual void HandleEvent(EventLoop& loop, uint32_t event) = 0;
};
struct EventLoop {
private:
int epoll_fd_;
bool running = false;
public:
bool Init() {
epoll_fd_ = epoll_create(1);
if (epoll_fd_ == -1) {
PLOGE("failed to create");
return false;
}
return true;
}
void Stop() {
running = false;
}
void Loop() {
running = true;
constexpr auto MAX_EVENTS = 2;
struct epoll_event events[MAX_EVENTS];
while (running) {
int nfds = epoll_wait(epoll_fd_, events, MAX_EVENTS, -1);
if (nfds == -1) {
if (errno != EINTR) PLOGE("epoll_wait");
continue;
}
for (int i = 0; i < nfds; i++) {
reinterpret_cast<EventHandler *>(events[i].data.ptr)->HandleEvent(*this,
events[i].events);
if (!running) break;
}
}
}
bool RegisterHandler(EventHandler &handler, uint32_t events) {
struct epoll_event ev{};
ev.events = events;
ev.data.ptr = &handler;
if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, handler.GetFd(), &ev) == -1) {
PLOGE("failed to add event handler");
return false;
}
return true;
}
bool UnregisterHandler(EventHandler &handler) {
if (epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, handler.GetFd(), NULL) == -1) {
PLOGE("failed to del event handler");
return false;
}
return true;
}
~EventLoop() {
if (epoll_fd_ >= 0) close(epoll_fd_);
}
};
enum TracingState {
TRACING = 1,
STOPPING,
STOPPED,
EXITING
};
TracingState tracing_state = TRACING;
static char prop_path[PATH_MAX];
struct Status {
bool supported = false;
bool zygote_injected = false;
bool daemon_running = false;
pid_t daemon_pid = -1;
char *daemon_info;
char *daemon_error_info;
};
Status status64;
Status status32;
struct SocketHandler : public EventHandler {
int sock_fd_;
bool Init() {
sock_fd_ = socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
if (sock_fd_ == -1) {
PLOGE("socket create");
return false;
}
struct sockaddr_un addr = {
.sun_family = AF_UNIX,
.sun_path = { 0 }
};
size_t sun_path_len = sprintf(addr.sun_path, "%s/%s", zygiskd::GetTmpPath().c_str(), SOCKET_NAME);
socklen_t socklen = sizeof(sa_family_t) + sun_path_len;
if (bind(sock_fd_, (struct sockaddr *)&addr, socklen) == -1) {
PLOGE("bind socket");
return false;
}
return true;
}
int GetFd() override {
return sock_fd_;
}
void HandleEvent(EventLoop &loop, uint32_t) override {
struct [[gnu::packed]] MsgHead {
enum Command cmd;
int length;
char data[0];
};
while (1) {
struct MsgHead *msg = (struct MsgHead *)malloc(sizeof(struct MsgHead));
ssize_t real_size;
ssize_t nread = recv(sock_fd_, msg, sizeof(struct MsgHead), MSG_PEEK);
if (nread == -1) {
if (errno == EAGAIN) break;
PLOGE("read socket");
}
if ((size_t)nread < sizeof(Command)) {
LOGE("read %zu < %zu", nread, sizeof(Command));
continue;
}
if (msg->cmd >= Command::DAEMON64_SET_INFO && msg->cmd != Command::SYSTEM_SERVER_STARTED) {
if (nread != sizeof(msg)) {
LOGE("cmd %d size %zu != %zu", msg->cmd, nread, sizeof(MsgHead));
continue;
}
real_size = sizeof(MsgHead) + msg->length;
} else {
if (nread != sizeof(Command)) {
LOGE("cmd %d size %zu != %zu", msg->cmd, nread, sizeof(Command));
continue;
}
real_size = sizeof(Command);
}
msg = (struct MsgHead *)realloc(msg, real_size);
nread = recv(sock_fd_, msg, real_size, 0);
if (nread == -1) {
if (errno == EAGAIN) break;
PLOGE("recv");
continue;
}
if (nread != real_size) {
LOGE("real size %zu != %zu", real_size, nread);
continue;
}
switch (msg->cmd) {
case START: {
if (tracing_state == STOPPING) tracing_state = TRACING;
else if (tracing_state == STOPPED) {
ptrace(PTRACE_SEIZE, 1, 0, PTRACE_O_TRACEFORK);
LOGI("start tracing init");
tracing_state = TRACING;
}
updateStatus();
break;
}
case STOP: {
if (tracing_state == TRACING) {
LOGI("stop tracing requested");
tracing_state = STOPPING;
strcpy(monitor_stop_reason, "user requested");
ptrace(PTRACE_INTERRUPT, 1, 0, 0);
updateStatus();
}
break;
}
case EXIT: {
LOGI("prepare for exit ...");
tracing_state = EXITING;
strcpy(monitor_stop_reason, "user requested");
updateStatus();
loop.Stop();
break;
}
case ZYGOTE64_INJECTED: {
status64.zygote_injected = true;
updateStatus();
break;
}
case ZYGOTE32_INJECTED: {
status32.zygote_injected = true;
updateStatus();
break;
}
case DAEMON64_SET_INFO: {
LOGD("received daemon64 info %s", msg->data);
/* Will only happen if somehow the daemon restarts */
if (status64.daemon_info != NULL) {
free(status64.daemon_info);
status64.daemon_info = NULL;
}
status64.daemon_info = (char *)malloc(msg->length);
if (status64.daemon_info == NULL) {
PLOGE("malloc daemon64 info");
break;
}
strcpy(status64.daemon_info, msg->data);
updateStatus();
break;
}
case DAEMON32_SET_INFO: {
LOGD("received daemon32 info %s", msg->data);
if (status32.daemon_info != NULL) {
free(status32.daemon_info);
status32.daemon_info = NULL;
}
status32.daemon_info = (char *)malloc(msg->length);
if (status32.daemon_info == NULL) {
PLOGE("malloc daemon32 info");
break;
}
strcpy(status32.daemon_info, msg->data);
updateStatus();
break;
}
case DAEMON64_SET_ERROR_INFO: {
LOGD("received daemon64 error info %s", msg->data);
status64.daemon_running = false;
if (status64.daemon_error_info != NULL) {
free(status64.daemon_error_info);
status64.daemon_error_info = NULL;
}
status64.daemon_error_info = (char *)malloc(msg->length);
if (status64.daemon_error_info == NULL) {
PLOGE("malloc daemon64 error info");
break;
}
strcpy(status64.daemon_error_info, msg->data);
updateStatus();
break;
}
case DAEMON32_SET_ERROR_INFO: {
LOGD("received daemon32 error info %s", msg->data);
status32.daemon_running = false;
if (status32.daemon_error_info != NULL) {
free(status32.daemon_error_info);
status32.daemon_error_info = NULL;
}
status32.daemon_error_info = (char *)malloc(msg->length);
if (status32.daemon_error_info == NULL) {
PLOGE("malloc daemon32 error info");
break;
}
strcpy(status32.daemon_error_info, msg->data);
updateStatus();
break;
}
case SYSTEM_SERVER_STARTED: {
LOGD("system server started, mounting prop");
if (mount(prop_path, "/data/adb/modules/zygisksu/module.prop", NULL, MS_BIND, NULL) == -1) {
PLOGE("failed to mount prop");
}
break;
}
}
free(msg);
}
}
~SocketHandler() {
if (sock_fd_ >= 0) close(sock_fd_);
}
};
constexpr int MAX_RETRY_COUNT = 5;
#define CREATE_ZYGOTE_START_COUNTER(abi) \
struct timespec last_zygote##abi = { \
.tv_sec = 0, \
.tv_nsec = 0 \
}; \
\
int count_zygote ## abi = 0; \
bool should_stop_inject ## abi() { \
struct timespec now = {}; \
clock_gettime(CLOCK_MONOTONIC, &now); \
if (now.tv_sec - last_zygote ## abi.tv_sec < 30) \
count_zygote ## abi++; \
else \
count_zygote ## abi = 0; \
\
last_zygote##abi = now; \
\
return count_zygote##abi >= MAX_RETRY_COUNT; \
}
CREATE_ZYGOTE_START_COUNTER(64)
CREATE_ZYGOTE_START_COUNTER(32)
static bool ensure_daemon_created(bool is_64bit) {
Status *status = is_64bit ? &status64 : &status32;
if (is_64bit) {
LOGD("new zygote started.");
umount2("/data/adb/modules/zygisksu/module.prop", MNT_DETACH);
}
status->zygote_injected = false;
if (status->daemon_pid == -1) {
pid_t pid = fork();
if (pid < 0) {
PLOGE("create daemon%s", is_64bit ? "64" : "32");
return false;
} else if (pid == 0) {
char daemon_name[PATH_MAX] = "./bin/zygiskd";
strcat(daemon_name, is_64bit ? "64" : "32");
execl(daemon_name, daemon_name, NULL);
PLOGE("exec daemon %s failed", daemon_name);
exit(1);
} else {
status->supported = true;
status->daemon_pid = pid;
status->daemon_running = true;
return true;
}
} else {
return status->daemon_running;
}
}
#define CHECK_DAEMON_EXIT(abi) \
if (status##abi.supported && pid == status64.daemon_pid) { \
char status_str[64]; \
parse_status(status, status_str, sizeof(status_str)); \
\
LOGW("daemon" #abi " pid %d exited: %s", pid, status_str); \
status##abi.daemon_running = false; \
\
if (!status##abi.daemon_error_info) { \
status##abi.daemon_error_info = (char *)malloc(strlen(status_str) + 1); \
if (status##abi.daemon_error_info) { \
LOGE("malloc daemon" #abi " error info failed"); \
\
return; \
} \
\
memcpy(status##abi.daemon_error_info, status_str, strlen(status_str) + 1); \
} \
\
updateStatus(); \
continue; \
}
#define PRE_INJECT(abi, is_64) \
if (strcmp(program, "/system/bin/app_process" # abi) == 0) { \
tracer = "./bin/zygisk-ptrace" # abi; \
\
if (should_stop_inject ## abi()) { \
LOGW("zygote" # abi " restart too much times, stop injecting"); \
\
tracing_state = STOPPING; \
memcpy(monitor_stop_reason, "zygote crashed", sizeof("zygote crashed")); \
ptrace(PTRACE_INTERRUPT, 1, 0, 0); \
\
break; \
} \
if (!ensure_daemon_created(is_64)) { \
LOGW("daemon" #abi " not running, stop injecting"); \
\
tracing_state = STOPPING; \
memcpy(monitor_stop_reason, "daemon not running", sizeof("daemon not running")); \
ptrace(PTRACE_INTERRUPT, 1, 0, 0); \
\
break; \
} \
}
struct SigChldHandler : public EventHandler {
private:
int signal_fd_;
struct signalfd_siginfo fdsi;
int status;
std::set<pid_t> process;
public:
bool Init() {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) {
PLOGE("set sigprocmask");
return false;
}
signal_fd_ = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC);
if (signal_fd_ == -1) {
PLOGE("create signalfd");
return false;
}
ptrace(PTRACE_SEIZE, 1, 0, PTRACE_O_TRACEFORK);
return true;
}
int GetFd() override {
return signal_fd_;
}
void HandleEvent(EventLoop &, uint32_t) override {
while (1) {
ssize_t s = read(signal_fd_, &fdsi, sizeof(fdsi));
if (s == -1) {
if (errno == EAGAIN) break;
PLOGE("read signalfd");
continue;
}
if (s != sizeof(fdsi)) {
LOGW("read %zu != %zu", s, sizeof(fdsi));
continue;
}
if (fdsi.ssi_signo != SIGCHLD) {
LOGW("no sigchld received");
continue;
}
int pid;
while ((pid = waitpid(-1, &status, __WALL | WNOHANG)) != 0) {
if (pid == -1) {
if (tracing_state == STOPPED && errno == ECHILD) break;
PLOGE("waitpid");
}
if (pid == 1) {
if (STOPPED_WITH(SIGTRAP, PTRACE_EVENT_FORK)) {
long child_pid;
ptrace(PTRACE_GETEVENTMSG, pid, 0, &child_pid);
LOGV("forked %ld", child_pid);
} else if (STOPPED_WITH(SIGTRAP, PTRACE_EVENT_STOP) && tracing_state == STOPPING) {
if (ptrace(PTRACE_DETACH, 1, 0, 0) == -1) PLOGE("failed to detach init");
tracing_state = STOPPED;
LOGI("stop tracing init");
continue;
}
if (WIFSTOPPED(status)) {
if (WPTEVENT(status) == 0) {
if (WSTOPSIG(status) != SIGSTOP && WSTOPSIG(status) != SIGTSTP && WSTOPSIG(status) != SIGTTIN && WSTOPSIG(status) != SIGTTOU) {
LOGW("inject signal sent to init: %s %d", sigabbrev_np(WSTOPSIG(status)), WSTOPSIG(status));
ptrace(PTRACE_CONT, pid, 0, WSTOPSIG(status));
continue;
} else {
LOGW("suppress stopping signal sent to init: %s %d", sigabbrev_np(WSTOPSIG(status)), WSTOPSIG(status));
}
}
ptrace(PTRACE_CONT, pid, 0, 0);
}
continue;
}
CHECK_DAEMON_EXIT(64)
CHECK_DAEMON_EXIT(32)
auto state = process.find(pid);
if (state == process.end()) {
LOGV("new process %d attached", pid);
process.emplace(pid);
ptrace(PTRACE_SETOPTIONS, pid, 0, PTRACE_O_TRACEEXEC);
ptrace(PTRACE_CONT, pid, 0, 0);
continue;
} else {
if (STOPPED_WITH(SIGTRAP, PTRACE_EVENT_EXEC)) {
char program[PATH_MAX];
if (get_program(pid, program, sizeof(program)) == -1) {
LOGW("failed to get program %d", pid);
continue;
}
LOGV("%d program %s", pid, program);
const char* tracer = NULL;
do {
if (tracing_state != TRACING) {
LOGW("stop injecting %d because not tracing", pid);
break;
}
PRE_INJECT(64, true)
PRE_INJECT(32, false)
if (tracer != NULL) {
LOGD("stopping %d", pid);
kill(pid, SIGSTOP);
ptrace(PTRACE_CONT, pid, 0, 0);
waitpid(pid, &status, __WALL);
if (STOPPED_WITH(SIGSTOP, 0)) {
LOGD("detaching %d", pid);
ptrace(PTRACE_DETACH, pid, 0, SIGSTOP);
status = 0;
auto p = fork_dont_care();
if (p == 0) {
char pid_str[32];
sprintf(pid_str, "%d", pid);
execl(tracer, basename(tracer), "trace", pid_str, "--restart", NULL);
PLOGE("failed to exec, kill");
kill(pid, SIGKILL);
exit(1);
} else if (p == -1) {
PLOGE("failed to fork, kill");
kill(pid, SIGKILL);
}
}
}
} while (false);
updateStatus();
} else {
char status_str[64];
parse_status(status, status_str, sizeof(status_str));
LOGW("process %d received unknown status %s", pid, status_str);
}
process.erase(state);
if (WIFSTOPPED(status)) {
LOGV("detach process %d", pid);
ptrace(PTRACE_DETACH, pid, 0, 0);
}
}
}
}
}
~SigChldHandler() {
if (signal_fd_ >= 0) close(signal_fd_);
}
};
static char pre_section[1024];
static char post_section[1024];
#define WRITE_STATUS_ABI(suffix) \
if (status ## suffix.supported) { \
strcat(status_text, " zygote" # suffix ": "); \
if (tracing_state != TRACING) strcat(status_text, "❓ unknown, "); \
else if (status ## suffix.zygote_injected) strcat(status_text, "😋 injected, "); \
else strcat(status_text, "❌ not injected, "); \
\
strcat(status_text, "daemon" # suffix ": "); \
if (status ## suffix.daemon_running) { \
strcat(status_text, "😋 running "); \
\
if (status ## suffix.daemon_info != NULL) { \
strcat(status_text, "("); \
strcat(status_text, status ## suffix.daemon_info); \
strcat(status_text, ")"); \
} \
} else { \
strcat(status_text, "❌ crashed "); \
\
if (status ## suffix.daemon_error_info != NULL) { \
strcat(status_text, "("); \
strcat(status_text, status ## suffix.daemon_error_info); \
strcat(status_text, ")"); \
} \
} \
}
static void updateStatus() {
FILE *prop = fopen(prop_path, "w");
char status_text[1024] = "monitor: ";
switch (tracing_state) {
case TRACING: {
strcat(status_text, "😋 tracing");
break;
}
case STOPPING: [[fallthrough]];
case STOPPED: {
strcat(status_text, "❌ stopped");
break;
}
case EXITING: {
strcat(status_text, "❌ exited");
break;
}
}
if (tracing_state != TRACING && monitor_stop_reason[0] != '\0') {
strcat(status_text, " (");
strcat(status_text, monitor_stop_reason);
strcat(status_text, ")");
}
strcat(status_text, ",");
WRITE_STATUS_ABI(64)
WRITE_STATUS_ABI(32)
fprintf(prop, "%s[%s] %s", pre_section, status_text, post_section);
fclose(prop);
}
static bool prepare_environment() {
strcat(prop_path, zygiskd::GetTmpPath().c_str());
strcat(prop_path, "/module.prop");
close(open(prop_path, O_WRONLY | O_CREAT | O_TRUNC, 0644));
FILE *orig_prop = fopen("./module.prop", "r");
if (orig_prop == NULL) {
PLOGE("failed to open orig prop");
return false;
}
bool after_description = false;
char line[1024];
while (fgets(line, sizeof(line), orig_prop) != NULL) {
if (strncmp(line, "description=", strlen("description=")) == 0) {
strcat(pre_section, "description=");
strcat(post_section, line + strlen("description="));
after_description = true;
continue;
}
if (after_description) strcat(post_section, line);
else strcat(pre_section, line);
}
fclose(orig_prop);
/* TODO: See if ZYGISK_ENABLED flag is already set,
if so, set a status saying to disable built-in Zygisk. */
updateStatus();
return true;
}
void init_monitor() {
LOGI("ReZygisk %s", ZKSU_VERSION);
if (!prepare_environment()) exit(1);
SocketHandler socketHandler{};
socketHandler.Init();
SigChldHandler ptraceHandler{};
ptraceHandler.Init();
EventLoop looper;
looper.Init();
looper.RegisterHandler(socketHandler, EPOLLIN | EPOLLET);
looper.RegisterHandler(ptraceHandler, EPOLLIN | EPOLLET);
looper.Loop();
if (status64.daemon_info != NULL) free(status64.daemon_info);
if (status64.daemon_error_info != NULL) free(status64.daemon_error_info);
if (status32.daemon_info != NULL) free(status32.daemon_info);
if (status32.daemon_error_info != NULL) free(status32.daemon_error_info);
LOGI("exit");
}
int send_control_command(enum Command cmd) {
int sockfd = socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
if (sockfd == -1) return -1;
struct sockaddr_un addr = {
.sun_family = AF_UNIX,
.sun_path = { 0 }
};
size_t sun_path_len = snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/%s", zygiskd::GetTmpPath().c_str(), SOCKET_NAME);
socklen_t socklen = sizeof(sa_family_t) + sun_path_len;
ssize_t nsend = sendto(sockfd, (void *)&cmd, sizeof(cmd), 0, (sockaddr *)&addr, socklen);
/* TODO: Should we close even when it fails? */
close(sockfd);
return nsend != sizeof(cmd) ? -1 : 0;
}

View File

@@ -0,0 +1,27 @@
#ifndef MAIN_HPP
#define MAIN_HPP
#include <stdbool.h>
void init_monitor();
bool trace_zygote(int pid);
enum Command {
START = 1,
STOP = 2,
EXIT = 3,
/* sent from daemon */
ZYGOTE64_INJECTED = 4,
ZYGOTE32_INJECTED = 5,
DAEMON64_SET_INFO = 6,
DAEMON32_SET_INFO = 7,
DAEMON64_SET_ERROR_INFO = 8,
DAEMON32_SET_ERROR_INFO = 9,
SYSTEM_SERVER_STARTED = 10
};
int send_control_command(enum Command cmd);
#endif /* MAIN_HPP */

View File

@@ -0,0 +1,326 @@
#include <sys/ptrace.h>
#include <unistd.h>
#include <sys/uio.h>
#include <sys/auxv.h>
#include <elf.h>
#include <link.h>
#include <vector>
#include <string>
#include <sys/mman.h>
#include <sys/wait.h>
#include <dlfcn.h>
#include <signal.h>
#include <sys/system_properties.h>
#include <string>
#include <cinttypes>
#include "utils.hpp"
bool inject_on_main(int pid, const char *lib_path) {
LOGI("injecting %s to zygote %d", lib_path, pid);
/*
parsing KernelArgumentBlock
https://cs.android.com/android/platform/superproject/main/+/main:bionic/libc/private/KernelArgumentBlock.h;l=30;drc=6d1ee77ee32220e4202c3066f7e1f69572967ad8
*/
struct user_regs_struct regs {},
backup {};
/* WARNING: C++ keyword */
std::vector<MapInfo> map = MapInfo::Scan(std::to_string(pid));
if (!get_regs(pid, regs)) return false;
uintptr_t arg = (uintptr_t)regs.REG_SP;
LOGV("kernel argument %" PRIxPTR " %s", arg, get_addr_mem_region(map, arg).c_str());
int argc;
char **argv = (char **)((uintptr_t *)arg + 1);
LOGV("argv %p", (void *)argv);
read_proc(pid, arg, &argc, sizeof(argc));
LOGV("argc %d", argc);
/* WARNING: C++ keyword */
auto envp = argv + argc + 1;
LOGV("envp %p", (void *)envp);
/* WARNING: C++ keyword */
auto p = envp;
while (1) {
uintptr_t *buf;
read_proc(pid, (uintptr_t)p, &buf, sizeof(buf));
if (buf == NULL) break;
/* TODO: Why ++p? */
p++;
}
/* TODO: Why ++p? */
p++;
ElfW(auxv_t) *auxv = (ElfW(auxv_t) *)p;
LOGV("auxv %p %s", auxv, get_addr_mem_region(map, (uintptr_t) auxv).c_str());
ElfW(auxv_t) *v = auxv;
uintptr_t entry_addr = 0;
uintptr_t addr_of_entry_addr = 0;
while (1) {
ElfW(auxv_t) buf;
read_proc(pid, (uintptr_t)v, &buf, sizeof(buf));
if (buf.a_type == AT_ENTRY) {
entry_addr = (uintptr_t)buf.a_un.a_val;
addr_of_entry_addr = (uintptr_t)v + offsetof(ElfW(auxv_t), a_un);
LOGV("entry address %" PRIxPTR " %s (entry=%" PRIxPTR ", entry_addr=%" PRIxPTR ")", entry_addr,
get_addr_mem_region(map, entry_addr).c_str(), (uintptr_t)v, addr_of_entry_addr);
break;
}
if (buf.a_type == AT_NULL) break;
v++;
}
if (entry_addr == 0) {
LOGE("failed to get entry");
return false;
}
/*
Replace the program entry with an invalid address
For arm32 compatibility, we set the last bit to the same as the entry address
*/
/* INFO: (-0x0F & ~1) is a value below zero, while the one after "|"
is an unsigned (must be 0 or greater) value, so we must
cast the second value to signed long (intptr_t) to avoid
undefined behavior.
*/
uintptr_t break_addr = (uintptr_t)((intptr_t)(-0x0F & ~1) | (intptr_t)((uintptr_t)entry_addr & 1));
if (!write_proc(pid, (uintptr_t)addr_of_entry_addr, &break_addr, sizeof(break_addr))) return false;
ptrace(PTRACE_CONT, pid, 0, 0);
int status;
wait_for_trace(pid, &status, __WALL);
if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGSEGV) {
if (!get_regs(pid, regs)) return false;
if (((int)regs.REG_IP & ~1) != ((int)break_addr & ~1)) {
LOGE("stopped at unknown addr %p", (void *) regs.REG_IP);
return false;
}
/* The linker has been initialized now, we can do dlopen */
LOGD("stopped at entry");
/* restore entry address */
if (!write_proc(pid, (uintptr_t) addr_of_entry_addr, &entry_addr, sizeof(entry_addr))) return false;
/* backup registers */
memcpy(&backup, &regs, sizeof(regs));
/* WARNING: C++ keyword */
map = MapInfo::Scan(std::to_string(pid));
/* WARNING: C++ keyword */
std::vector<MapInfo> local_map = MapInfo::Scan();
void *libc_return_addr = find_module_return_addr(map, "libc.so");
LOGD("libc return addr %p", libc_return_addr);
/* call dlopen */
void *dlopen_addr = find_func_addr(local_map, map, "libdl.so", "dlopen");
if (dlopen_addr == NULL) return false;
/* WARNING: C++ keyword */
std::vector<long> args;
/* WARNING: C++ keyword */
uintptr_t str = push_string(pid, regs, lib_path);
args.clear();
args.push_back((long) str);
args.push_back((long) RTLD_NOW);
uintptr_t remote_handle = remote_call(pid, regs, (uintptr_t)dlopen_addr, (uintptr_t)libc_return_addr, args);
LOGD("remote handle %p", (void *)remote_handle);
if (remote_handle == 0) {
LOGE("handle is null");
/* call dlerror */
void *dlerror_addr = find_func_addr(local_map, map, "libdl.so", "dlerror");
if (dlerror_addr == NULL) {
LOGE("find dlerror");
return false;
}
args.clear();
uintptr_t dlerror_str_addr = remote_call(pid, regs, (uintptr_t)dlerror_addr, (uintptr_t)libc_return_addr, args);
LOGD("dlerror str %p", (void*) dlerror_str_addr);
if (dlerror_str_addr == 0) return false;
void *strlen_addr = find_func_addr(local_map, map, "libc.so", "strlen");
if (strlen_addr == NULL) {
LOGE("find strlen");
return false;
}
args.clear();
args.push_back(dlerror_str_addr);
uintptr_t dlerror_len = remote_call(pid, regs, (uintptr_t)strlen_addr, (uintptr_t)libc_return_addr, args);
if (dlerror_len <= 0) {
LOGE("dlerror len <= 0");
return false;
}
/* NOTICE: C++ -> C */
char *err = (char *)malloc((dlerror_len + 1) * sizeof(char));
if (err == NULL) {
LOGE("malloc err");
return false;
}
read_proc(pid, dlerror_str_addr, err, dlerror_len + 1);
LOGE("dlerror info %s", err);
free(err);
return false;
}
/* call dlsym(handle, "entry") */
void *dlsym_addr = find_func_addr(local_map, map, "libdl.so", "dlsym");
if (dlsym_addr == NULL) return false;
args.clear();
str = push_string(pid, regs, "entry");
args.push_back(remote_handle);
args.push_back((long) str);
uintptr_t injector_entry = remote_call(pid, regs, (uintptr_t)dlsym_addr, (uintptr_t)libc_return_addr, args);
LOGD("injector entry %p", (void *)injector_entry);
if (injector_entry == 0) {
LOGE("injector entry is null");
return false;
}
/* call injector entry(handle, path) */
args.clear();
args.push_back(remote_handle);
str = push_string(pid, regs, zygiskd::GetTmpPath().c_str());
args.push_back((long) str);
remote_call(pid, regs, injector_entry, (uintptr_t)libc_return_addr, args);
/* reset pc to entry */
backup.REG_IP = (long) entry_addr;
LOGD("invoke entry");
/* restore registers */
if (!set_regs(pid, backup)) return false;
return true;
} else {
char status_str[64];
parse_status(status, status_str, sizeof(status_str));
LOGE("stopped by other reason: %s", status_str);
}
return false;
}
#define STOPPED_WITH(sig, event) (WIFSTOPPED(status) && WSTOPSIG(status) == (sig) && (status >> 16) == (event))
#define WAIT_OR_DIE wait_for_trace(pid, &status, __WALL);
#define CONT_OR_DIE \
if (ptrace(PTRACE_CONT, pid, 0, 0) == -1) { \
PLOGE("cont"); \
\
return false; \
}
bool trace_zygote(int pid) {
LOGI("start tracing %d (tracer %d)", pid, getpid());
int status;
if (ptrace(PTRACE_SEIZE, pid, 0, PTRACE_O_EXITKILL) == -1) {
PLOGE("seize");
return false;
}
WAIT_OR_DIE
if (STOPPED_WITH(SIGSTOP, PTRACE_EVENT_STOP)) {
/* WARNING: C++ keyword */
std::string lib_path = zygiskd::GetTmpPath();
lib_path += "/lib" LP_SELECT("", "64") "/libzygisk.so";
if (!inject_on_main(pid, lib_path.c_str())) {
LOGE("failed to inject");
return false;
}
LOGD("inject done, continue process");
if (kill(pid, SIGCONT)) {
PLOGE("kill");
return false;
}
CONT_OR_DIE
WAIT_OR_DIE
if (STOPPED_WITH(SIGTRAP, PTRACE_EVENT_STOP)) {
CONT_OR_DIE
WAIT_OR_DIE
if (STOPPED_WITH(SIGCONT, 0)) {
LOGD("received SIGCONT");
ptrace(PTRACE_DETACH, pid, 0, SIGCONT);
}
} else {
char status_str[64];
parse_status(status, status_str, sizeof(status_str));
LOGE("unknown state %s, not SIGTRAP + EVENT_STOP", status_str);
ptrace(PTRACE_DETACH, pid, 0, 0);
return false;
}
} else {
char status_str[64];
parse_status(status, status_str, sizeof(status_str));
LOGE("unknown state %s, not SIGSTOP + EVENT_STOP", status_str);
ptrace(PTRACE_DETACH, pid, 0, 0);
return false;
}
return true;
}

View File

@@ -0,0 +1,528 @@
#include <linux/limits.h>
#include <vector>
#include <sys/mman.h>
#include <sys/sysmacros.h>
#include <array>
#include <cinttypes>
#include <sys/ptrace.h>
#include <unistd.h>
#include <sys/uio.h>
#include <sys/auxv.h>
#include <elf.h>
#include <link.h>
#include <vector>
#include <string>
#include <sys/mman.h>
#include <sys/wait.h>
#include <cstdlib>
#include <cstdio>
#include <dlfcn.h>
#include <signal.h>
#include <sstream>
#include <ios>
#include <cstring>
#include <sys/stat.h>
#include <sched.h>
#include <fcntl.h>
#include "utils.hpp"
#include "logging.h"
bool switch_mnt_ns(int pid, int *fd) {
int nsfd, old_nsfd = -1;
/* WARNING: C++ keyword */
char path[PATH_MAX];
if (pid == 0) {
if (fd != NULL) {
nsfd = *fd;
*fd = -1;
} else return false;
snprintf(path, sizeof(path), "/proc/self/fd/%d", nsfd);
} else {
if (fd != NULL) {
old_nsfd = open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC);
if (old_nsfd == -1) {
PLOGE("get old nsfd");
return false;
}
*fd = old_nsfd;
}
snprintf(path, sizeof(path), "/proc/%d/ns/mnt", pid);
nsfd = open(path, O_RDONLY | O_CLOEXEC);
if (nsfd == -1) {
PLOGE("open nsfd %s", path);
close(old_nsfd);
return false;
}
}
if (setns(nsfd, CLONE_NEWNS) == -1) {
PLOGE("set ns to %s", path);
close(nsfd);
close(old_nsfd);
return false;
}
close(nsfd);
return true;
}
/* WARNING: C++ keyword */
std::vector<MapInfo> MapInfo::Scan(const std::string &pid) {
constexpr static auto kPermLength = 5;
constexpr static auto kMapEntry = 7;
/* WARNING: C++ keyword */
std::vector<MapInfo> info;
char file_name[NAME_MAX];
snprintf(file_name, sizeof(file_name), "/proc/%s/maps", pid.c_str());
/* WARNING: C++ keyword */
auto maps = std::unique_ptr<FILE, decltype(&fclose)>{fopen(file_name, "r"), &fclose};
if (maps) {
char *line = NULL;
size_t len = 0;
ssize_t read;
/* WARNING: C++ keyword */
while ((read = getline(&line, &len, maps.get())) > 0) {
line[read - 1] = '\0';
uintptr_t start = 0;
uintptr_t end = 0;
uintptr_t off = 0;
ino_t inode = 0;
unsigned int dev_major = 0;
unsigned int dev_minor = 0;
/* WARNING: C++ keyword */
std::array<char, kPermLength> perm {'\0'};
int path_off;
if (sscanf(line, "%" PRIxPTR "-%" PRIxPTR " %4s %" PRIxPTR " %x:%x %lu %n%*s", &start,
&end, perm.data(), &off, &dev_major, &dev_minor, &inode,
&path_off) != kMapEntry) continue;
while (path_off < read && isspace(line[path_off])) path_off++;
/* WARNING: C++ keyword */
MapInfo &ref = info.emplace_back(MapInfo{
start,
end,
0,
perm[3] == 'p',
off,
static_cast<dev_t>(makedev(dev_major, dev_minor)),
inode,
line + path_off
});
if (perm[0] == 'r') ref.perms |= PROT_READ;
if (perm[1] == 'w') ref.perms |= PROT_WRITE;
if (perm[2] == 'x') ref.perms |= PROT_EXEC;
}
free(line);
}
return info;
}
ssize_t write_proc(int pid, uintptr_t remote_addr, const void *buf, size_t len) {
LOGV("write to remote addr %" PRIxPTR " size %zu", remote_addr, len);
struct iovec local = {
.iov_base = (void *)buf,
.iov_len = len
};
struct iovec remote = {
.iov_base = (void *)remote_addr,
.iov_len = len
};
ssize_t l = process_vm_writev(pid, &local, 1, &remote, 1, 0);
if (l == -1) PLOGE("process_vm_writev");
else if ((size_t)l != len) LOGW("not fully written: %zu, excepted %zu", l, len);
return l;
}
ssize_t read_proc(int pid, uintptr_t remote_addr, void *buf, size_t len) {
struct iovec local = {
.iov_base = (void *)buf,
.iov_len = len
};
struct iovec remote = {
.iov_base = (void *)remote_addr,
.iov_len = len
};
ssize_t l = process_vm_readv(pid, &local, 1, &remote, 1, 0);
if (l == -1) PLOGE("process_vm_readv");
else if ((size_t)l != len) LOGW("not fully read: %zu, excepted %zu", l, len);
return l;
}
bool get_regs(int pid, struct user_regs_struct &regs) {
#if defined(__x86_64__) || defined(__i386__)
if (ptrace(PTRACE_GETREGS, pid, 0, &regs) == -1) {
PLOGE("getregs");
return false;
}
#elif defined(__aarch64__) || defined(__arm__)
struct iovec iov = {
.iov_base = &regs,
.iov_len = sizeof(struct user_regs_struct),
};
if (ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &iov) == -1) {
PLOGE("getregs");
return false;
}
#endif
return true;
}
bool set_regs(int pid, struct user_regs_struct &regs) {
#if defined(__x86_64__) || defined(__i386__)
if (ptrace(PTRACE_SETREGS, pid, 0, &regs) == -1) {
PLOGE("setregs");
return false;
}
#elif defined(__aarch64__) || defined(__arm__)
struct iovec iov = {
.iov_base = &regs,
.iov_len = sizeof(struct user_regs_struct),
};
if (ptrace(PTRACE_SETREGSET, pid, NT_PRSTATUS, &iov) == -1) {
PLOGE("setregs");
return false;
}
#endif
return true;
}
/* WARNING: C++ keyword */
std::string get_addr_mem_region(std::vector<MapInfo> &info, uintptr_t addr) {
/* WARNING: C++ keyword */
for (auto &map: info) {
if (map.start <= addr && map.end > addr) {
/* WARNING: C++ keyword */
auto s = std::string(map.path);
s += ' ';
s += map.perms & PROT_READ ? 'r' : '-';
s += map.perms & PROT_WRITE ? 'w' : '-';
s += map.perms & PROT_EXEC ? 'x' : '-';
return s;
}
}
return "<unknown>";
}
/* WARNING: C++ keyword */
void *find_module_return_addr(std::vector<MapInfo> &info, std::string_view suffix) {
/* WARNING: C++ keyword */
for (auto &map: info) {
/* WARNING: C++ keyword */
if ((map.perms & PROT_EXEC) == 0 && map.path.ends_with(suffix)) return (void *)map.start;
}
return NULL;
}
/* WARNING: C++ keyword */
void *find_module_base(std::vector<MapInfo> &info, std::string_view suffix) {
/* WARNING: C++ keyword */
for (auto &map: info) {
/* WARNING: C++ keyword */
if (map.offset == 0 && map.path.ends_with(suffix)) return (void *)map.start;
}
return NULL;
}
/* WARNING: C++ keyword */
void *find_func_addr(std::vector<MapInfo> &local_info, std::vector<MapInfo> &remote_info, std::string_view module, std::string_view func) {
void *lib = dlopen(module.data(), RTLD_NOW);
if (lib == NULL) {
LOGE("failed to open lib %s: %s", module.data(), dlerror());
return NULL;
}
uint8_t *sym = (uint8_t *)dlsym(lib, func.data());
if (sym == NULL) {
LOGE("failed to find sym %s in %s: %s", func.data(), module.data(), dlerror());
dlclose(lib);
return NULL;
}
LOGD("sym %s: %p", func.data(), sym);
dlclose(lib);
uint8_t *local_base = (uint8_t *)find_module_base(local_info, module);
if (local_base == NULL) {
LOGE("failed to find local base for module %s", module.data());
return NULL;
}
uint8_t *remote_base = (uint8_t *)find_module_base(remote_info, module);
if (remote_base == NULL) {
LOGE("failed to find remote base for module %s", module.data());
return NULL;
}
LOGD("found local base %p remote base %p", local_base, remote_base);
uint8_t *addr = (sym - local_base) + remote_base;
LOGD("addr %p", addr);
return addr;
}
/* WARNING: C++ keyword */
void align_stack(struct user_regs_struct &regs, long preserve) {
/* INFO: ~0xf is a negative value, and REG_SP is unsigned,
so we must cast REG_SP to signed type before subtracting
then cast back to unsigned type.
*/
regs.REG_SP = (uintptr_t)((intptr_t)(regs.REG_SP - preserve) & ~0xf);
}
/* WARNING: C++ keyword */
uintptr_t push_string(int pid, struct user_regs_struct &regs, const char *str) {
size_t len = strlen(str) + 1;
regs.REG_SP -= len;
align_stack(regs);
uintptr_t addr = (uintptr_t)regs.REG_SP;
if (!write_proc(pid, addr, str, len)) LOGE("failed to write string %s", str);
LOGD("pushed string %" PRIxPTR, addr);
return addr;
}
/* WARNING: C++ keyword */
uintptr_t remote_call(int pid, struct user_regs_struct &regs, uintptr_t func_addr, uintptr_t return_addr, std::vector<long> &args) {
align_stack(regs);
/* WARNING: C++ keyword */
LOGV("calling remote function %" PRIxPTR " args %zu", func_addr, args.size());
/* WARNING: C++ keyword */
for (auto &a: args) {
LOGV("arg %p", (void *) a);
}
#if defined(__x86_64__)
if (args.size() >= 1) regs.rdi = args[0];
if (args.size() >= 2) regs.rsi = args[1];
if (args.size() >= 3) regs.rdx = args[2];
if (args.size() >= 4) regs.rcx = args[3];
if (args.size() >= 5) regs.r8 = args[4];
if (args.size() >= 6) regs.r9 = args[5];
if (args.size() > 6) {
long remain = (args.size() - 6L) * sizeof(long);
align_stack(regs, remain);
if (!write_proc(pid, (uintptr_t) regs.REG_SP, args.data(), remain)) LOGE("failed to push arguments");
}
regs.REG_SP -= sizeof(long);
if (!write_proc(pid, (uintptr_t) regs.REG_SP, &return_addr, sizeof(return_addr))) LOGE("failed to write return addr");
regs.REG_IP = func_addr;
#elif defined(__i386__)
if (args.size() > 0) {
long remain = (args.size()) * sizeof(long);
align_stack(regs, remain);
if (!write_proc(pid, (uintptr_t) regs.REG_SP, args.data(), remain)) LOGE("failed to push arguments");
}
regs.REG_SP -= sizeof(long);
if (!write_proc(pid, (uintptr_t) regs.REG_SP, &return_addr, sizeof(return_addr))) LOGE("failed to write return addr");
regs.REG_IP = func_addr;
#elif defined(__aarch64__)
for (size_t i = 0; i < args.size() && i < 8; i++) {
regs.regs[i] = args[i];
}
if (args.size() > 8) {
long remain = (args.size() - 8) * sizeof(long);
align_stack(regs, remain);
write_proc(pid, (uintptr_t)regs.REG_SP, args.data(), remain);
}
regs.regs[30] = return_addr;
regs.REG_IP = func_addr;
#elif defined(__arm__)
for (size_t i = 0; i < args.size() && i < 4; i++) {
regs.uregs[i] = args[i];
}
if (args.size() > 4) {
long remain = (args.size() - 4) * sizeof(long);
align_stack(regs, remain);
write_proc(pid, (uintptr_t)regs.REG_SP, args.data(), remain);
}
regs.uregs[14] = return_addr;
regs.REG_IP = func_addr;
constexpr auto CPSR_T_MASK = 1lu << 5;
if ((regs.REG_IP & 1) != 0) {
regs.REG_IP = regs.REG_IP & ~1;
regs.uregs[16] = regs.uregs[16] | CPSR_T_MASK;
} else {
regs.uregs[16] = regs.uregs[16] & ~CPSR_T_MASK;
}
#endif
if (!set_regs(pid, regs)) {
LOGE("failed to set regs");
return 0;
}
ptrace(PTRACE_CONT, pid, 0, 0);
int status;
wait_for_trace(pid, &status, __WALL);
if (!get_regs(pid, regs)) {
LOGE("failed to get regs after call");
return 0;
}
if (WSTOPSIG(status) == SIGSEGV) {
if ((uintptr_t)regs.REG_IP != return_addr) {
LOGE("wrong return addr %p", (void *) regs.REG_IP);
return 0;
}
return regs.REG_RET;
} else {
char status_str[64];
parse_status(status, status_str, sizeof(status_str));
LOGE("stopped by other reason %s at addr %p", status_str, (void *)regs.REG_IP);
}
return 0;
}
int fork_dont_care() {
pid_t pid = fork();
if (pid < 0) PLOGE("fork 1");
else if (pid == 0) {
pid = fork();
if (pid < 0) PLOGE("fork 2");
else if (pid > 0) exit(0);
} else {
int status;
waitpid(pid, &status, __WALL);
}
return pid;
}
void wait_for_trace(int pid, int *status, int flags) {
while (1) {
pid_t result = waitpid(pid, status, flags);
if (result == -1) {
if (errno == EINTR) continue;
PLOGE("wait %d failed", pid);
exit(1);
}
if (!WIFSTOPPED(*status)) {
char status_str[64];
parse_status(*status, status_str, sizeof(status_str));
LOGE("process %d not stopped for trace: %s, exit", pid, status_str);
exit(1);
}
return;
}
}
void parse_status(int status, char *buf, size_t len) {
snprintf(buf, len, "0x%x ", status);
if (WIFEXITED(status)) {
snprintf(buf + strlen(buf), len - strlen(buf), "exited with %d", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
snprintf(buf + strlen(buf), len - strlen(buf), "signaled with %s(%d)", sigabbrev_np(WTERMSIG(status)), WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
snprintf(buf + strlen(buf), len - strlen(buf), "stopped by ");
int stop_sig = WSTOPSIG(status);
snprintf(buf + strlen(buf), len - strlen(buf), "signal=%s(%d),", sigabbrev_np(stop_sig), stop_sig);
snprintf(buf + strlen(buf), len - strlen(buf), "event=%s", parse_ptrace_event(status));
} else {
snprintf(buf + strlen(buf), len - strlen(buf), "unknown");
}
}
int get_program(int pid, char *buf, size_t size) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "/proc/%d/exe", pid);
ssize_t sz = readlink(path, buf, size);
if (sz == -1) {
PLOGE("readlink /proc/%d/exe", pid);
return -1;
}
buf[sz] = 0;
return 0;
}

View File

@@ -0,0 +1,125 @@
#pragma once
#include <string>
#include <sys/ptrace.h>
#include <map>
#include "daemon.h"
#ifdef __LP64__
#define LOG_TAG "zygisk-ptrace64"
#else
#define LOG_TAG "zygisk-ptrace32"
#endif
#include "logging.h"
struct MapInfo {
/// \brief The start address of the memory region.
uintptr_t start;
/// \brief The end address of the memory region.
uintptr_t end;
/// \brief The permissions of the memory region. This is a bit mask of the following values:
/// - PROT_READ
/// - PROT_WRITE
/// - PROT_EXEC
uint8_t perms;
/// \brief Whether the memory region is private.
bool is_private;
/// \brief The offset of the memory region.
uintptr_t offset;
/// \brief The device number of the memory region.
/// Major can be obtained by #major()
/// Minor can be obtained by #minor()
dev_t dev;
/// \brief The inode number of the memory region.
ino_t inode;
/// \brief The path of the memory region.
std::string path;
/// \brief Scans /proc/self/maps and returns a list of \ref MapInfo entries.
/// This is useful to find out the inode of the library to hook.
/// \return A list of \ref MapInfo entries.
static std::vector<MapInfo> Scan(const std::string& pid = "self");
};
#if defined(__x86_64__)
#define REG_SP rsp
#define REG_IP rip
#define REG_RET rax
#elif defined(__i386__)
#define REG_SP esp
#define REG_IP eip
#define REG_RET eax
#elif defined(__aarch64__)
#define REG_SP sp
#define REG_IP pc
#define REG_RET regs[0]
#elif defined(__arm__)
#define REG_SP uregs[13]
#define REG_IP uregs[15]
#define REG_RET uregs[0]
#define user_regs_struct user_regs
#endif
ssize_t write_proc(int pid, uintptr_t remote_addr, const void *buf, size_t len);
ssize_t read_proc(int pid, uintptr_t remote_addr, void *buf, size_t len);
bool get_regs(int pid, struct user_regs_struct &regs);
bool set_regs(int pid, struct user_regs_struct &regs);
std::string get_addr_mem_region(std::vector<MapInfo> &info, uintptr_t addr);
void *find_module_base(std::vector<MapInfo> &info, std::string_view suffix);
void *find_func_addr(
std::vector<MapInfo> &local_info,
std::vector<MapInfo> &remote_info,
std::string_view module,
std::string_view func);
void align_stack(struct user_regs_struct &regs, long preserve = 0);
uintptr_t push_string(int pid, struct user_regs_struct &regs, const char *str);
uintptr_t remote_call(int pid, struct user_regs_struct &regs, uintptr_t func_addr, uintptr_t return_addr,
std::vector<long> &args);
int fork_dont_care();
void wait_for_trace(int pid, int* status, int flags);
void parse_status(int status, char *buf, size_t len);
#define WPTEVENT(x) (x >> 16)
#define CASE_CONST_RETURN(x) case x: return #x;
inline const char* parse_ptrace_event(int status) {
status = status >> 16;
switch (status) {
CASE_CONST_RETURN(PTRACE_EVENT_FORK)
CASE_CONST_RETURN(PTRACE_EVENT_VFORK)
CASE_CONST_RETURN(PTRACE_EVENT_CLONE)
CASE_CONST_RETURN(PTRACE_EVENT_EXEC)
CASE_CONST_RETURN(PTRACE_EVENT_VFORK_DONE)
CASE_CONST_RETURN(PTRACE_EVENT_EXIT)
CASE_CONST_RETURN(PTRACE_EVENT_SECCOMP)
CASE_CONST_RETURN(PTRACE_EVENT_STOP)
default:
return "(no event)";
}
}
inline const char* sigabbrev_np(int sig) {
if (sig > 0 && sig < NSIG) return sys_signame[sig];
return "(unknown)";
}
int get_program(int pid, char *buf, size_t size);
void *find_module_return_addr(std::vector<MapInfo> &info, std::string_view suffix);
// pid = 0, fd != nullptr -> set to fd
// pid != 0, fd != nullptr -> set to pid ns, give orig ns in fd
bool switch_mnt_ns(int pid, int *fd);

2
module/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
public_key
private_key

View File

@@ -1,20 +1,35 @@
import android.databinding.tool.ext.capitalizeUS
import java.security.MessageDigest
import org.apache.tools.ant.filters.ReplaceTokens
import org.apache.tools.ant.filters.FixCrLfFilter
import org.apache.commons.codec.binary.Hex
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.security.KeyFactory
import java.security.KeyPairGenerator
import java.security.Signature
import java.security.interfaces.EdECPrivateKey
import java.security.interfaces.EdECPublicKey
import java.security.spec.EdECPrivateKeySpec
import java.security.spec.NamedParameterSpec
import java.util.TreeSet
plugins {
id("com.android.library")
alias(libs.plugins.agp.lib)
}
val moduleId: String by rootProject.extra
val moduleName: String by rootProject.extra
val verCode: Int by rootProject.extra
val verName: String by rootProject.extra
val minAPatchVersion: Int by rootProject.extra
val minKsuVersion: Int by rootProject.extra
val minKsudVersion: Int by rootProject.extra
val maxKsuVersion: Int by rootProject.extra
val minMagiskVersion: Int by rootProject.extra
val commitHash: String by rootProject.extra
android.buildFeatures {
androidResources = false
@@ -22,23 +37,23 @@ android.buildFeatures {
}
androidComponents.onVariants { variant ->
val variantLowered = variant.name.toLowerCase()
val variantCapped = variant.name.capitalize()
val buildTypeLowered = variant.buildType?.toLowerCase()
val variantLowered = variant.name.lowercase()
val variantCapped = variant.name.capitalizeUS()
val buildTypeLowered = variant.buildType?.lowercase()
val moduleDir = "$buildDir/outputs/module/$variantLowered"
val zipFileName = "$moduleName-$verName-$verCode-$buildTypeLowered.zip".replace(' ', '-')
val moduleDir = layout.buildDirectory.dir("outputs/module/$variantLowered")
val zipFileName = "$moduleName-$verName-$verCode-$commitHash-$buildTypeLowered.zip".replace(' ', '-')
val prepareModuleFilesTask = task<Sync>("prepareModuleFiles$variantCapped") {
group = "module"
dependsOn(
":loader:assemble$variantCapped",
":zygiskd:cargoBuild",
":zygiskd:buildAndStrip",
)
into(moduleDir)
from("${rootProject.projectDir}/README.md")
from("$projectDir/src") {
exclude("module.prop", "customize.sh", "service.sh")
exclude("module.prop", "customize.sh", "post-fs-data.sh", "service.sh", "uninstall.sh", "mazoku")
filter<FixCrLfFilter>("eol" to FixCrLfFilter.CrLf.newInstance("lf"))
}
from("$projectDir/src") {
@@ -46,14 +61,16 @@ androidComponents.onVariants { variant ->
expand(
"moduleId" to moduleId,
"moduleName" to moduleName,
"versionName" to "$verName ($verCode)",
"versionCode" to verCode,
"versionName" to "$verName ($verCode-$commitHash-$variantLowered)",
"versionCode" to verCode
)
}
from("$projectDir/src/mazoku")
from("$projectDir/src") {
include("customize.sh", "service.sh")
include("customize.sh", "post-fs-data.sh", "service.sh", "uninstall.sh")
val tokens = mapOf(
"DEBUG" to if (buildTypeLowered == "debug") "true" else "false",
"MIN_APATCH_VERSION" to "$minAPatchVersion",
"MIN_KSU_VERSION" to "$minKsuVersion",
"MIN_KSUD_VERSION" to "$minKsudVersion",
"MAX_KSU_VERSION" to "$maxKsuVersion",
@@ -63,20 +80,107 @@ androidComponents.onVariants { variant ->
filter<FixCrLfFilter>("eol" to FixCrLfFilter.CrLf.newInstance("lf"))
}
into("bin") {
from(project(":zygiskd").buildDir.path + "/rustJniLibs/android")
from(project(":zygiskd").layout.buildDirectory.getAsFile().get())
include("**/zygiskd")
}
into("lib") {
from("${project(":loader").buildDir}/intermediates/stripped_native_libs/$variantLowered/out/lib")
from(project(":loader").layout.buildDirectory.file("intermediates/stripped_native_libs/$variantLowered/out/lib"))
}
val root = moduleDir.get()
doLast {
if (file("private_key").exists()) {
println("=== Guards the peace of Machikado ===")
val privateKey = file("private_key").readBytes()
val publicKey = file("public_key").readBytes()
val namedSpec = NamedParameterSpec("ed25519")
val privKeySpec = EdECPrivateKeySpec(namedSpec, privateKey)
val kf = KeyFactory.getInstance("ed25519")
val privKey = kf.generatePrivate(privKeySpec);
val sig = Signature.getInstance("ed25519")
fun File.sha(realFile: File? = null) {
sig.update(this.name.toByteArray())
sig.update(0) // null-terminated string
val real = realFile ?: this
val buffer = ByteBuffer.allocate(8)
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(real.length())
.array()
sig.update(buffer)
real.forEachBlock { bytes, size ->
sig.update(bytes, 0, size)
}
}
fun getSign(name: String, abi32: String, abi64: String) {
val set = TreeSet<Pair<File, File?>> { o1, o2 ->
o1.first.path.replace("\\", "/")
.compareTo(o2.first.path.replace("\\", "/"))
}
set.add(Pair(root.file("module.prop").asFile, null))
set.add(Pair(root.file("sepolicy.rule").asFile, null))
set.add(Pair(root.file("post-fs-data.sh").asFile, null))
set.add(Pair(root.file("service.sh").asFile, null))
set.add(Pair(root.file("mazoku").asFile, null))
set.add(
Pair(
root.file("lib/libzygisk.so").asFile,
root.file("lib/$abi32/libzygisk.so").asFile
)
)
set.add(
Pair(
root.file("lib64/libzygisk.so").asFile,
root.file("lib/$abi64/libzygisk.so").asFile
)
)
set.add(
Pair(
root.file("bin/zygisk-ptrace32").asFile,
root.file("lib/$abi32/libzygisk_ptrace.so").asFile
)
)
set.add(
Pair(
root.file("bin/zygisk-ptrace64").asFile,
root.file("lib/$abi64/libzygisk_ptrace.so").asFile
)
)
set.add(
Pair(
root.file("bin/zygiskd32").asFile,
root.file("bin/$abi32/zygiskd").asFile
)
)
set.add(
Pair(
root.file("bin/zygiskd64").asFile,
root.file("bin/$abi64/zygiskd").asFile
)
)
sig.initSign(privKey)
set.forEach { it.first.sha(it.second) }
val signFile = root.file(name).asFile
signFile.writeBytes(sig.sign())
signFile.appendBytes(publicKey)
}
getSign("machikado.arm", "armeabi-v7a", "arm64-v8a")
getSign("machikado.x86", "x86", "x86_64")
} else {
println("no private_key found, this build will not be signed")
root.file("machikado.arm").asFile.createNewFile()
root.file("machikado.x86").asFile.createNewFile()
}
fileTree(moduleDir).visit {
if (isDirectory) return@visit
val md = MessageDigest.getInstance("SHA-256")
file.forEachBlock(4096) { bytes, size ->
md.update(bytes, 0, size)
}
file(file.path + ".sha256").writeText(org.apache.commons.codec.binary.Hex.encodeHexString(md.digest()))
file(file.path + ".sha256").writeText(Hex.encodeHexString(md.digest()))
}
}
}
@@ -85,7 +189,7 @@ androidComponents.onVariants { variant ->
group = "module"
dependsOn(prepareModuleFilesTask)
archiveFileName.set(zipFileName)
destinationDirectory.set(file("$buildDir/outputs/release"))
destinationDirectory.set(layout.buildDirectory.file("outputs/release").get().asFile)
from(moduleDir)
}
@@ -111,10 +215,22 @@ androidComponents.onVariants { variant ->
}
}
val installAPatchTask = task<Exec>("installAPatch$variantCapped") {
group = "module"
dependsOn(pushTask)
commandLine("adb", "shell", "su", "-c", "/data/adb/apd module install /data/local/tmp/$zipFileName")
}
val installMagiskTask = task<Exec>("installMagisk$variantCapped") {
group = "module"
dependsOn(pushTask)
commandLine("adb", "shell", "su", "-c", "magisk --install-module /data/local/tmp/$zipFileName")
commandLine("adb", "shell", "su", "-M", "-c", "magisk --install-module /data/local/tmp/$zipFileName")
}
task<Exec>("installAPatchAndReboot$variantCapped") {
group = "module"
dependsOn(installAPatchTask)
commandLine("adb", "reboot")
}
task<Exec>("installKsuAndReboot$variantCapped") {

View File

@@ -6,6 +6,7 @@ MIN_KSU_VERSION=@MIN_KSU_VERSION@
MIN_KSUD_VERSION=@MIN_KSUD_VERSION@
MAX_KSU_VERSION=@MAX_KSU_VERSION@
MIN_MAGISK_VERSION=@MIN_MAGISK_VERSION@
MIN_APATCH_VERSION=@MIN_APATCH_VERSION@
if [ "$BOOTMODE" ] && [ "$KSU" ]; then
ui_print "- Installing from KernelSU app"
@@ -31,9 +32,17 @@ if [ "$BOOTMODE" ] && [ "$KSU" ]; then
if [ "$(which magisk)" ]; then
ui_print "*********************************************************"
ui_print "! Multiple root implementation is NOT supported!"
ui_print "! Please uninstall Magisk before installing Zygisksu"
ui_print "! Please uninstall Magisk before installing ReZygisk"
abort "*********************************************************"
fi
elif [ "$BOOTMODE" ] && [ "$APATCH" ]; then
ui_print "- Installing from APatch app"
if ! [ "$APATCH_VER_CODE" ] || [ "$APATCH_VER_CODE" -lt "$MIN_APATCH_VERSION" ]; then
ui_print "*********************************************************"
ui_print "! APatch version is too old!"
ui_print "! Please update APatch to latest version"
abort "*********************************************************"
fi
elif [ "$BOOTMODE" ] && [ "$MAGISK_VER_CODE" ]; then
ui_print "- Installing from Magisk app"
if [ "$MAGISK_VER_CODE" -lt "$MIN_MAGISK_VERSION" ]; then
@@ -50,12 +59,12 @@ else
fi
VERSION=$(grep_prop version "${TMPDIR}/module.prop")
ui_print "- Installing Zygisksu $VERSION"
ui_print "- Installing ReZygisk $VERSION"
# check android
if [ "$API" -lt 29 ]; then
if [ "$API" -lt 26 ]; then
ui_print "! Unsupported sdk: $API"
abort "! Minimal supported sdk is 29 (Android 10)"
abort "! Minimal supported sdk is 26 (Android 8.0)"
else
ui_print "- Device sdk: $API"
fi
@@ -82,10 +91,6 @@ extract "$ZIPFILE" 'sepolicy.rule' "$TMPDIR"
if [ "$KSU" ]; then
ui_print "- Checking SELinux patches"
if [ "$(getprop ro.product.first_api_level)" -lt 31 ]; then
echo "allow zygote appdomain_tmpfs file *" >> "$TMPDIR/sepolicy.rule"
echo "allow zygote appdomain_tmpfs dir *" >> "$TMPDIR/sepolicy.rule"
fi
if ! check_sepolicy "$TMPDIR/sepolicy.rule"; then
ui_print "*********************************************************"
ui_print "! Unable to apply SELinux patches!"
@@ -98,63 +103,54 @@ ui_print "- Extracting module files"
extract "$ZIPFILE" 'module.prop' "$MODPATH"
extract "$ZIPFILE" 'post-fs-data.sh' "$MODPATH"
extract "$ZIPFILE" 'service.sh' "$MODPATH"
extract "$ZIPFILE" 'uninstall.sh' "$MODPATH"
extract "$ZIPFILE" 'mazoku' "$MODPATH"
mv "$TMPDIR/sepolicy.rule" "$MODPATH"
HAS32BIT=false && [ -d "/system/lib" ] && HAS32BIT=true
HAS64BIT=false && [ -d "/system/lib64" ] && HAS64BIT=true
mkdir "$MODPATH/bin"
mkdir "$MODPATH/system"
[ "$HAS32BIT" = true ] && mkdir "$MODPATH/system/lib"
[ "$HAS64BIT" = true ] && mkdir "$MODPATH/system/lib64"
mkdir "$MODPATH/lib"
mkdir "$MODPATH/lib64"
if [ "$ARCH" = "x86" ] || [ "$ARCH" = "x64" ]; then
if [ "$HAS32BIT" = true ]; then
ui_print "- Extracting x86 libraries"
extract "$ZIPFILE" 'bin/x86/zygiskd' "$MODPATH/bin" true
mv "$MODPATH/bin/zygiskd" "$MODPATH/bin/zygiskd32"
extract "$ZIPFILE" 'lib/x86/libzygisk_injector.so' "$MODPATH/system/lib" true
extract "$ZIPFILE" 'lib/x86/libzygisk_loader.so' "$MODPATH/system/lib" true
ln -sf "zygiskd32" "$MODPATH/bin/zygiskwd"
fi
ui_print "- Extracting x86 libraries"
extract "$ZIPFILE" 'bin/x86/zygiskd' "$MODPATH/bin" true
mv "$MODPATH/bin/zygiskd" "$MODPATH/bin/zygiskd32"
extract "$ZIPFILE" 'lib/x86/libzygisk.so' "$MODPATH/lib" true
extract "$ZIPFILE" 'lib/x86/libzygisk_ptrace.so' "$MODPATH/bin" true
mv "$MODPATH/bin/libzygisk_ptrace.so" "$MODPATH/bin/zygisk-ptrace32"
if [ "$HAS64BIT" = true ]; then
ui_print "- Extracting x64 libraries"
extract "$ZIPFILE" 'bin/x86_64/zygiskd' "$MODPATH/bin" true
mv "$MODPATH/bin/zygiskd" "$MODPATH/bin/zygiskd64"
extract "$ZIPFILE" 'lib/x86_64/libzygisk_injector.so' "$MODPATH/system/lib64" true
extract "$ZIPFILE" 'lib/x86_64/libzygisk_loader.so' "$MODPATH/system/lib64" true
ln -sf "zygiskd64" "$MODPATH/bin/zygiskwd"
fi
ui_print "- Extracting x64 libraries"
extract "$ZIPFILE" 'bin/x86_64/zygiskd' "$MODPATH/bin" true
mv "$MODPATH/bin/zygiskd" "$MODPATH/bin/zygiskd64"
extract "$ZIPFILE" 'lib/x86_64/libzygisk.so' "$MODPATH/lib64" true
extract "$ZIPFILE" 'lib/x86_64/libzygisk_ptrace.so' "$MODPATH/bin" true
mv "$MODPATH/bin/libzygisk_ptrace.so" "$MODPATH/bin/zygisk-ptrace64"
extract "$ZIPFILE" 'machikado.x86' "$MODPATH" true
mv "$MODPATH/machikado.x86" "$MODPATH/machikado"
else
if [ "$HAS32BIT" = true ]; then
ui_print "- Extracting arm libraries"
extract "$ZIPFILE" 'bin/armeabi-v7a/zygiskd' "$MODPATH/bin" true
mv "$MODPATH/bin/zygiskd" "$MODPATH/bin/zygiskd32"
extract "$ZIPFILE" 'lib/armeabi-v7a/libzygisk_injector.so' "$MODPATH/system/lib" true
extract "$ZIPFILE" 'lib/armeabi-v7a/libzygisk_loader.so' "$MODPATH/system/lib" true
ln -sf "zygiskd32" "$MODPATH/bin/zygiskwd"
fi
ui_print "- Extracting arm libraries"
extract "$ZIPFILE" 'bin/armeabi-v7a/zygiskd' "$MODPATH/bin" true
mv "$MODPATH/bin/zygiskd" "$MODPATH/bin/zygiskd32"
extract "$ZIPFILE" 'lib/armeabi-v7a/libzygisk.so' "$MODPATH/lib" true
extract "$ZIPFILE" 'lib/armeabi-v7a/libzygisk_ptrace.so' "$MODPATH/bin" true
mv "$MODPATH/bin/libzygisk_ptrace.so" "$MODPATH/bin/zygisk-ptrace32"
if [ "$HAS64BIT" = true ]; then
ui_print "- Extracting arm64 libraries"
extract "$ZIPFILE" 'bin/arm64-v8a/zygiskd' "$MODPATH/bin" true
mv "$MODPATH/bin/zygiskd" "$MODPATH/bin/zygiskd64"
extract "$ZIPFILE" 'lib/arm64-v8a/libzygisk_injector.so' "$MODPATH/system/lib64" true
extract "$ZIPFILE" 'lib/arm64-v8a/libzygisk_loader.so' "$MODPATH/system/lib64" true
ln -sf "zygiskd64" "$MODPATH/bin/zygiskwd"
fi
ui_print "- Extracting arm64 libraries"
extract "$ZIPFILE" 'bin/arm64-v8a/zygiskd' "$MODPATH/bin" true
mv "$MODPATH/bin/zygiskd" "$MODPATH/bin/zygiskd64"
extract "$ZIPFILE" 'lib/arm64-v8a/libzygisk.so' "$MODPATH/lib64" true
extract "$ZIPFILE" 'lib/arm64-v8a/libzygisk_ptrace.so' "$MODPATH/bin" true
mv "$MODPATH/bin/libzygisk_ptrace.so" "$MODPATH/bin/zygisk-ptrace64"
extract "$ZIPFILE" 'machikado.arm' "$MODPATH" true
mv "$MODPATH/machikado.arm" "$MODPATH/machikado"
fi
ui_print "- Generating magic"
MAGIC=$(tr -dc 'a-f0-9' </dev/urandom | head -c 18)
echo -n "$MAGIC" > "$MODPATH/system/zygisk_magic"
ui_print "- Setting permissions"
chmod 0744 "$MODPATH/daemon.sh"
set_perm_recursive "$MODPATH/bin" 0 2000 0755 0755
set_perm_recursive "$MODPATH/system/lib" 0 0 0755 0644 u:object_r:system_lib_file:s0
set_perm_recursive "$MODPATH/system/lib64" 0 0 0755 0644 u:object_r:system_lib_file:s0
set_perm_recursive "$MODPATH/bin" 0 0 0755 0755
set_perm_recursive "$MODPATH/lib" 0 0 0755 0644 u:object_r:system_lib_file:s0
set_perm_recursive "$MODPATH/lib64" 0 0 0755 0644 u:object_r:system_lib_file:s0
# If Huawei's Maple is enabled, system_server is created with a special way which is out of Zygisk's control
HUAWEI_MAPLE_ENABLED=$(grep_prop ro.maple.enable)

1
module/src/mazoku Normal file
View File

@@ -0,0 +1 @@
c<EFBFBD><EFBFBD><EFBFBD>]<5D><> <20>[<11>B<EFBFBD>u<EFBFBD>5=<3D>rEU<45>Z<>ʿ<EFBFBD><CABF><<3C>5<EFBFBD>_o<><6F>M<>L<>l<EFBFBD><6C><EFBFBD>Q#<23><><EFBFBD>C<EFBFBD>}<7D> e<><65>fjق/<2F>7<EFBFBD><11><>(<28><>g<b<>Rg<07>m<EFBFBD>d

View File

@@ -2,5 +2,5 @@ id=${moduleId}
name=${moduleName}
version=${versionName}
versionCode=${versionCode}
author=Nullptr, 5ec1cff
description=Run Zygisk on KernelSU.
author=The PerformanC Organization
description=Standalone implementation of Zygisk.

View File

@@ -6,18 +6,45 @@ if [ "$ZYGISK_ENABLED" ]; then
fi
cd "$MODDIR"
getprop ro.dalvik.vm.native.bridge > /dev/.native_bridge
resetprop ro.dalvik.vm.native.bridge libzygisk_loader.so
if [ "$(which magisk)" ]; then
for file in ../*; do
if [ -d "$file" ] && [ -d "$file/zygisk" ] && ! [ -f "$file/disable" ]; then
if [ -f "$file/post-fs-data.sh" ]; then
cd "$file"
log -p i -t "zygisksu" "Manually trigger post-fs-data.sh for $file"
log -p i -t "zygisk-sh" "Manually trigger post-fs-data.sh for $file"
sh "$(realpath ./post-fs-data.sh)"
cd "$MODDIR"
fi
fi
done
fi
create_sys_perm() {
mkdir -p $1
chmod 555 $1
chcon u:object_r:system_file:s0 $1
}
export TMP_PATH=/data/adb/rezygisk
if [ -d $TMP_PATH ]; then
rm -rf $TMP_PATH
fi
create_sys_perm $TMP_PATH
if [ -f $MODDIR/lib64/libzygisk.so ];then
create_sys_perm $TMP_PATH/lib64
cp $MODDIR/lib64/libzygisk.so $TMP_PATH/lib64/libzygisk.so
chcon u:object_r:system_file:s0 $TMP_PATH/lib64/libzygisk.so
fi
if [ -f $MODDIR/lib/libzygisk.so ];then
create_sys_perm $TMP_PATH/lib
cp $MODDIR/lib/libzygisk.so $TMP_PATH/lib/libzygisk.so
chcon u:object_r:system_file:s0 $TMP_PATH/lib/libzygisk.so
fi
[ "$DEBUG" = true ] && export RUST_BACKTRACE=1
./bin/zygisk-ptrace64 monitor &

View File

@@ -1,7 +1,9 @@
allow * tmpfs * *
allow zygote tmpfs file *
allow zygote appdomain_tmpfs file *
type magisk_file file_type
typeattribute magisk_file mlstrustedobject
allow * magisk_file file *
allow * magisk_file dir *
allow * magisk_file fifo_file *
@@ -10,6 +12,8 @@ allow * magisk_file lnk_file *
allow * magisk_file sock_file *
allow system_server system_server process execmem
allow zygote zygote process execmem
allow zygote adb_data_file dir search
allow zygote mnt_vendor_file dir search
allow zygote system_file dir mounton

View File

@@ -8,22 +8,16 @@ if [ "$ZYGISK_ENABLED" ]; then
fi
cd "$MODDIR"
export NATIVE_BRIDGE=$(cat /dev/.native_bridge)
rm /dev/.native_bridge
if [ "$(which magisk)" ]; then
for file in ../*; do
if [ -d "$file" ] && [ -d "$file/zygisk" ] && ! [ -f "$file/disable" ]; then
if [ -f "$file/service.sh" ]; then
cd "$file"
log -p i -t "zygisksu" "Manually trigger service.sh for $file"
log -p i -t "zygisk-sh" "Manually trigger service.sh for $file"
sh "$(realpath ./service.sh)"
cd "$MODDIR"
fi
fi
done
fi
log -p i -t "zygisksu" "Start watchdog"
[ "$DEBUG" = true ] && export RUST_BACKTRACE=1
exec "bin/zygiskwd" "watchdog" >/dev/null 2>&1

5
module/src/uninstall.sh Normal file
View File

@@ -0,0 +1,5 @@
#!/system/bin/sh
export TMP_PATH=/data/adb/rezygisk
rm -rf $TMP_PATH

View File

@@ -6,10 +6,6 @@ pluginManagement {
mavenCentral()
gradlePluginPortal()
}
plugins {
id("com.android.library") version "7.4.2"
id("com.android.application") version "7.4.2"
}
}
dependencyResolutionManagement {
@@ -20,7 +16,7 @@ dependencyResolutionManagement {
}
}
rootProject.name = "ZygiskOnKernelSU"
rootProject.name = "ReZygisk"
include(
":loader",
":module",

View File

@@ -1,2 +0,0 @@
[build]
target-dir = "build/intermediates/rust"

View File

@@ -1,28 +0,0 @@
[package]
name = "zygiskd"
authors = ["Nullptr"]
version = "1.0.0"
edition = "2021"
rust-version = "1.67"
[dependencies]
android_logger = "0.13.0"
anyhow = { version = "1.0.68", features = ["backtrace"] }
clap = { version = "4.1.4", features = ["derive"] }
const_format = "0.2.5"
konst = "0.3.4"
lazy_static = "1.4.0"
log = "0.4.17"
memfd = "0.6.2"
nix = "0.26.2"
num_enum = "0.5.9"
once_cell = "1.17.1"
passfd = "0.1.5"
rand = "0.8.5"
binder = { git = "https://github.com/Kernel-SU/binder_rs" }
[profile.release]
strip = true
opt-level = "z"
lto = true

View File

@@ -1,33 +1,120 @@
plugins {
id("com.android.library")
id("org.mozilla.rust-android-gradle.rust-android")
import java.nio.file.Paths
import org.gradle.internal.os.OperatingSystem
fun getLatestNDKPath(): String {
val android_home = System.getenv("ANDROID_HOME")
if (android_home == null) {
throw Exception("ANDROID_HOME not set")
}
val ndkPath = android_home + "/ndk"
val ndkDir = Paths.get(ndkPath)
if (!ndkDir.toFile().exists()) {
throw Exception("NDK not found at $ndkPath")
}
val ndkVersion = ndkDir.toFile().listFiles().filter { it.isDirectory }.map { it.name }.sorted().last()
return ndkPath + "/" + ndkVersion
}
val verName: String by rootProject.extra
val verCode: Int by rootProject.extra
val minAPatchVersion: Int by rootProject.extra
val minKsuVersion: Int by rootProject.extra
val maxKsuVersion: Int by rootProject.extra
val minMagiskVersion: Int by rootProject.extra
val verCode: Int by rootProject.extra
val verName: String by rootProject.extra
val commitHash: String by rootProject.extra
android.buildFeatures {
androidResources = false
buildConfig = false
}
val CStandardFlags = arrayOf(
"-D_GNU_SOURCE", "-std=c99", "-Wpedantic", "-Wall", "-Wextra", "-Werror",
"-Wformat", "-Wuninitialized", "-Wshadow", "-Wno-zero-length-array",
"-Wno-fixed-enum-extension", "-Iroot_impl", "-llog",
"-DMIN_APATCH_VERSION=$minAPatchVersion",
"-DMIN_KSU_VERSION=$minKsuVersion",
"-DMAX_KSU_VERSION=$maxKsuVersion",
"-DMIN_MAGISK_VERSION=$minMagiskVersion",
"-DZKSU_VERSION=\"$verName\""
)
cargo {
module = "."
libname = "zygiskd"
targetIncludes = arrayOf("zygiskd")
targets = listOf("arm64", "arm", "x86", "x86_64")
targetDirectory = "build/intermediates/rust"
val isDebug = gradle.startParameter.taskNames.any { it.toLowerCase().contains("debug") }
profile = if (isDebug) "debug" else "release"
exec = { spec, _ ->
spec.environment("ANDROID_NDK_HOME", android.ndkDirectory.path)
spec.environment("VERSION_CODE", verCode)
spec.environment("VERSION_NAME", verName)
spec.environment("MIN_KSU_VERSION", minKsuVersion)
spec.environment("MAX_KSU_VERSION", maxKsuVersion)
spec.environment("MIN_MAGISK_VERSION", minMagiskVersion)
val CFlagsRelease = arrayOf(
"-Wl,--strip-all", "-flto=thin", "-Ofast"
)
val CFlagsDebug = arrayOf(
"-g", "-O0"
)
val Files = arrayOf(
"root_impl/apatch.c",
"root_impl/common.c",
"root_impl/kernelsu.c",
"root_impl/magisk.c",
"companion.c",
"dl.c",
"main.c",
"utils.c",
"zygiskd.c"
)
task("buildAndStrip") {
group = "build"
description = "Build the native library and strip the debug symbols."
val isDebug = gradle.startParameter.taskNames.any { it.lowercase().contains("debug") }
doLast {
val ndkPath = getLatestNDKPath()
val aarch64Compiler = Paths.get(ndkPath, "toolchains", "llvm", "prebuilt", "linux-x86_64", "bin", "aarch64-linux-android34-clang").toString()
val armv7aCompiler = Paths.get(ndkPath, "toolchains", "llvm", "prebuilt", "linux-x86_64", "bin", "armv7a-linux-androideabi34-clang").toString()
val x86Compiler = Paths.get(ndkPath, "toolchains", "llvm", "prebuilt", "linux-x86_64", "bin", "i686-linux-android34-clang").toString()
val x86_64Compiler = Paths.get(ndkPath, "toolchains", "llvm", "prebuilt", "linux-x86_64", "bin", "x86_64-linux-android34-clang").toString()
if (!Paths.get(aarch64Compiler).toFile().exists()) {
throw Exception("aarch64 compiler not found at $aarch64Compiler")
}
if (!Paths.get(armv7aCompiler).toFile().exists()) {
throw Exception("armv7a compiler not found at $armv7aCompiler")
}
if (!Paths.get(x86Compiler).toFile().exists()) {
throw Exception("x86 compiler not found at $x86Compiler")
}
if (!Paths.get(x86_64Compiler).toFile().exists()) {
throw Exception("x86_64 compiler not found at $x86_64Compiler")
}
val Files = Files.map { Paths.get(project.projectDir.toString(), "src", it).toString() }.toTypedArray()
val buildDir = getLayout().getBuildDirectory().getAsFile().get()
buildDir.mkdirs()
val aarch64OutputDir = Paths.get(buildDir.toString(), "arm64-v8a").toFile()
val armv7aOutputDir = Paths.get(buildDir.toString(), "armeabi-v7a").toFile()
val x86OutputDir = Paths.get(buildDir.toString(), "x86").toFile()
val x86_64OutputDir = Paths.get(buildDir.toString(), "x86_64").toFile()
aarch64OutputDir.mkdirs()
armv7aOutputDir.mkdirs()
x86OutputDir.mkdirs()
x86_64OutputDir.mkdirs()
val compileArgs = (if (isDebug) CFlagsDebug else CFlagsRelease) + CStandardFlags
exec {
commandLine(aarch64Compiler, "-o", Paths.get(aarch64OutputDir.toString(), "zygiskd").toString(), *compileArgs, *Files)
}
exec {
commandLine(armv7aCompiler, "-o", Paths.get(armv7aOutputDir.toString(), "zygiskd").toString(), *compileArgs, *Files)
}
exec {
commandLine(x86Compiler, "-o", Paths.get(x86OutputDir.toString(), "zygiskd").toString(), *compileArgs, *Files)
}
exec {
commandLine(x86_64Compiler, "-o", Paths.get(x86_64OutputDir.toString(), "zygiskd").toString(), *compileArgs, *Files)
}
}
}

2
zygiskd/src/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
zygiskd64
zygiskd32

661
zygiskd/src/LICENSE Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

134
zygiskd/src/companion.c Normal file
View File

@@ -0,0 +1,134 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/limits.h>
#include <pthread.h>
#include <android/log.h>
#include "companion.h"
#include "dl.h"
#include "utils.h"
typedef void (*zygisk_companion_entry_func)(int);
struct companion_module_thread_args {
int fd;
zygisk_companion_entry_func entry;
};
zygisk_companion_entry_func load_module(int fd) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
void *handle = android_dlopen(path, RTLD_NOW);
void *entry = dlsym(handle, "zygisk_companion_entry");
if (entry == NULL) return NULL;
return (zygisk_companion_entry_func)entry;
}
void *entry_thread(void *arg) {
struct companion_module_thread_args *args = (struct companion_module_thread_args *)arg;
int fd = args->fd;
zygisk_companion_entry_func module_entry = args->entry;
module_entry(fd);
close(fd);
free(args);
pthread_exit(NULL);
}
/* WARNING: Dynamic memory based */
void companion_entry(int fd) {
LOGI("New companion entry.\n - Client fd: %d\n", fd);
/* TODO: Use non-NULL string termination */
char name[256 + 1];
ssize_t name_length = read_string(fd, name, sizeof(name) - 1);
if (name_length == -1) {
LOGE("Failed to read module name\n");
ssize_t ret = write_uint8_t(fd, 2);
ASSURE_SIZE_WRITE("ZygiskdCompanion", "name", ret, sizeof(uint8_t));
exit(0);
}
name[name_length] = '\0';
LOGI(" - Module name: `%.*s`\n", (int)name_length, name);
int library_fd = read_fd(fd);
ssize_t ret = 0;
if (library_fd == -1) {
LOGE("Failed to receive library fd\n");
ret = write_uint8_t(fd, 2);
ASSURE_SIZE_WRITE("ZygiskdCompanion", "library_fd", ret, sizeof(uint8_t));
exit(0);
}
LOGI(" - Library fd: %d\n", library_fd);
zygisk_companion_entry_func module_entry = load_module(library_fd);
close(library_fd);
if (module_entry == NULL) {
LOGI("No companion module entry for module: %.*s\n", (int)name_length, name);
ret = write_uint8_t(fd, 0);
ASSURE_SIZE_WRITE("ZygiskdCompanion", "module_entry", ret, sizeof(uint8_t));
exit(0);
} else {
ret = write_uint8_t(fd, 1);
ASSURE_SIZE_WRITE("ZygiskdCompanion", "module_entry", ret, sizeof(uint8_t));
}
while (1) {
if (!check_unix_socket(fd, true)) {
LOGI("Something went wrong in companion. Bye!\n");
exit(0);
break;
}
int client_fd = read_fd(fd);
if (fd == -1) {
LOGE("Failed to receive client fd\n");
exit(0);
}
struct companion_module_thread_args *args = malloc(sizeof(struct companion_module_thread_args));
if (args == NULL) {
LOGE("Failed to allocate memory for thread args\n");
exit(0);
}
args->fd = client_fd;
args->entry = module_entry;
LOGI("New companion request.\n - Module name: %.*s\n - Client fd: %d\n", (int)name_length, name, args->fd);
ret = write_uint8_t(args->fd, 1);
ASSURE_SIZE_WRITE("ZygiskdCompanion", "client_fd", ret, sizeof(uint8_t));
pthread_t thread;
pthread_create(&thread, NULL, entry_thread, args);
}
}

6
zygiskd/src/companion.h Normal file
View File

@@ -0,0 +1,6 @@
#ifndef COMPANION_H
#define COMPANION_H
void companion_entry(int fd);
#endif /* COMPANION_H */

View File

@@ -1,61 +0,0 @@
use std::ffi::c_void;
use std::os::fd::{FromRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::thread;
use anyhow::Result;
use nix::libc;
use passfd::FdPassingExt;
use crate::utils::UnixStreamExt;
use crate::dl;
type ZygiskCompanionEntryFn = unsafe extern "C" fn(i32);
pub fn entry(fd: i32) -> Result<()> {
unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) };
let mut stream = unsafe { UnixStream::from_raw_fd(fd) };
let name = stream.read_string()?;
let library = stream.recv_fd()?;
let entry = load_module(library)?;
unsafe { libc::close(library) };
let entry = match entry {
Some(entry) => {
log::debug!("Companion process created for `{name}`");
stream.write_u8(1)?;
entry
}
None => {
log::debug!("No companion entry for `{name}`");
stream.write_u8(0)?;
return Ok(());
}
};
loop {
let fd = stream.recv_fd()?;
log::trace!("New companion request from module `{name}`");
thread::spawn(move || {
unsafe {
let mut s = UnixStream::from_raw_fd(fd);
match s.write_u8(1) { // Ack
Ok(_) => entry(fd),
Err(_) => log::warn!("Ack failed?"),
}
};
});
}
}
fn load_module(fd: RawFd) -> Result<Option<ZygiskCompanionEntryFn>> {
unsafe {
let path = format!("/proc/self/fd/{fd}");
let handle = dl::dlopen(&path, libc::RTLD_NOW)?;
let symbol = std::ffi::CString::new("zygisk_companion_entry")?;
let entry = libc::dlsym(handle, symbol.as_ptr());
if entry.is_null() {
return Ok(None);
}
let fnptr = std::mem::transmute::<*mut c_void, ZygiskCompanionEntryFn>(entry);
Ok(Some(fnptr))
}
}

57
zygiskd/src/constants.h Normal file
View File

@@ -0,0 +1,57 @@
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <android/log.h>
#define bool _Bool
#define true 1
#define false 0
#if DEBUG == false
#define MAX_LOG_LEVEL ANDROID_LOG_VERBOSE
#else
#define MAX_LOG_LEVEL ANDROID_LOG_INFO
#endif
#if (defined(__LP64__) || defined(_LP64))
#define lp_select(a, b) b
#else
#define lp_select(a, b) a
#endif
#define ZYGOTE_INJECTED lp_select(5, 4)
#define DAEMON_SET_INFO lp_select(7, 6)
#define DAEMON_SET_ERROR_INFO lp_select(9, 8)
#define SYSTEM_SERVER_STARTED 10
enum DaemonSocketAction {
PingHeartbeat,
RequestLogcatFd,
GetProcessFlags,
GetInfo,
ReadModules,
RequestCompanionSocket,
GetModuleDir,
ZygoteRestart,
SystemServerStarted
};
enum ProcessFlags: uint32_t {
PROCESS_GRANTED_ROOT = (1u << 0),
PROCESS_ON_DENYLIST = (1u << 1),
PROCESS_IS_MANAGER = (1u << 28),
PROCESS_ROOT_IS_APATCH = (1u << 27),
PROCESS_ROOT_IS_KSU = (1u << 29),
PROCESS_ROOT_IS_MAGISK = (1u << 30),
PROCESS_IS_SYS_UI = (1u << 31),
PROCESS_IS_SYSUI = (1u << 31)
};
enum RootImplState {
Supported,
TooOld,
Inexistent,
Abnormal
};
#endif /* CONSTANTS_H */

View File

@@ -1,53 +0,0 @@
use const_format::concatcp;
use konst::primitive::parse_i32;
use konst::unwrap_ctx;
use log::LevelFilter;
use num_enum::TryFromPrimitive;
pub const VERSION_NAME: &str = env!("VERSION_NAME");
pub const VERSION_CODE: &str = env!("VERSION_CODE");
pub const VERSION_FULL: &str = concatcp!(VERSION_NAME, " (", VERSION_CODE, ")");
pub const MIN_KSU_VERSION: i32 = unwrap_ctx!(parse_i32(env!("MIN_KSU_VERSION")));
pub const MAX_KSU_VERSION: i32 = unwrap_ctx!(parse_i32(env!("MAX_KSU_VERSION")));
pub const MIN_MAGISK_VERSION: i32 = unwrap_ctx!(parse_i32(env!("MIN_MAGISK_VERSION")));
#[cfg(debug_assertions)]
pub const MAX_LOG_LEVEL: LevelFilter = LevelFilter::Trace;
#[cfg(not(debug_assertions))]
pub const MAX_LOG_LEVEL: LevelFilter = LevelFilter::Info;
pub const PROP_NATIVE_BRIDGE: &str = "ro.dalvik.vm.native.bridge";
pub const PROP_CTL_RESTART: &str = "ctl.restart";
pub const ZYGISK_LOADER: &str = "libzygisk_loader.so";
pub const ZYGISK_MAGIC: &str = "/system/zygisk_magic";
pub const PATH_MODULES_DIR: &str = "..";
pub const PATH_MODULE_PROP: &str = "module.prop";
pub const PATH_ZYGISKD32: &str = "bin/zygiskd32";
pub const PATH_ZYGISKD64: &str = "bin/zygiskd64";
pub const STATUS_LOADED: &str = "😋 Zygisksu is loaded";
pub const STATUS_CRASHED: &str = "❌ Zygiskd has crashed";
pub const STATUS_ROOT_IMPL_NONE: &str = "❌ Unknown root implementation";
pub const STATUS_ROOT_IMPL_TOO_OLD: &str = "❌ Root implementation version too old";
pub const STATUS_ROOT_IMPL_ABNORMAL: &str = "❌ Abnormal root implementation version";
pub const STATUS_ROOT_IMPL_MULTIPLE: &str = "❌ Multiple root implementations installed";
#[derive(Debug, Eq, PartialEq, TryFromPrimitive)]
#[repr(u8)]
pub enum DaemonSocketAction {
PingHeartbeat,
RequestLogcatFd,
ReadNativeBridge,
GetProcessFlags,
ReadModules,
RequestCompanionSocket,
GetModuleDir,
}
// Zygisk process flags
pub const PROCESS_GRANTED_ROOT: u32 = 1 << 0;
pub const PROCESS_ON_DENYLIST: u32 = 1 << 1;
pub const PROCESS_ROOT_IS_KSU: u32 = 1 << 29;
pub const PROCESS_ROOT_IS_MAGISK: u32 = 1 << 30;
pub const PROCESS_IS_SYSUI: u32 = 1 << 31;

88
zygiskd/src/dl.c Normal file
View File

@@ -0,0 +1,88 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <errno.h>
#include <libgen.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <android/log.h>
#include "companion.h"
#include "dl.h"
#include "utils.h"
#define ANDROID_NAMESPACE_TYPE_SHARED 0x2
#define ANDROID_DLEXT_USE_NAMESPACE 0x200
typedef struct AndroidNamespace {
unsigned char _unused[0];
} AndroidNamespace;
typedef struct AndroidDlextinfo {
uint64_t flags;
void *reserved_addr;
size_t reserved_size;
int relro_fd;
int library_fd;
off64_t library_fd_offset;
AndroidNamespace *library_namespace;
} AndroidDlextinfo;
typedef AndroidNamespace *(*AndroidCreateNamespaceFn)(
const char *name,
const char *ld_library_path,
const char *default_library_path,
uint64_t type,
const char *permitted_when_isolated_path,
AndroidNamespace *parent,
const void *caller_addr
);
extern void *android_dlopen_ext(const char *filename, int flags, const AndroidDlextinfo *extinfo);
void *android_dlopen(char *path, int flags) {
char *dir = dirname(path);
struct AndroidDlextinfo info = {
.flags = 0,
.reserved_addr = NULL,
.reserved_size = 0,
.relro_fd = 0,
.library_fd = 0,
.library_fd_offset = 0,
.library_namespace = NULL,
};
void *handle = dlsym(RTLD_DEFAULT, "__loader_android_create_namespace");
AndroidCreateNamespaceFn android_create_namespace_fn = (AndroidCreateNamespaceFn)handle;
AndroidNamespace *ns = android_create_namespace_fn(
path,
dir,
NULL,
ANDROID_NAMESPACE_TYPE_SHARED,
NULL,
NULL,
(const void *)&android_dlopen
);
if (ns != NULL) {
info.flags = ANDROID_DLEXT_USE_NAMESPACE;
info.library_namespace = ns;
LOGI("Open %s with namespace %p\n", path, (void *)ns);
} else {
LOGI("Cannot create namespace for %s\n", path);
}
void *result = android_dlopen_ext(path, flags, &info);
if (result == NULL) {
LOGE("Failed to dlopen %s: %s\n", path, dlerror());
}
return result;
}

6
zygiskd/src/dl.h Normal file
View File

@@ -0,0 +1,6 @@
#ifndef DL_H
#define DL_H
void *android_dlopen(char *path, int flags);
#endif /* DL_H */

View File

@@ -1,82 +0,0 @@
use anyhow::{bail, Result};
use std::ffi::{c_char, c_void};
use nix::libc;
const ANDROID_NAMESPACE_TYPE_SHARED: u64 = 0x2;
const ANDROID_DLEXT_USE_NAMESPACE: u64 = 0x200;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
struct AndroidNamespace {
_unused: [u8; 0],
}
#[repr(C)]
struct AndroidDlextinfo {
pub flags: u64,
pub reserved_addr: *mut c_void,
pub reserved_size: libc::size_t,
pub relro_fd: libc::c_int,
pub library_fd: libc::c_int,
pub library_fd_offset: libc::off64_t,
pub library_namespace: *mut AndroidNamespace,
}
extern "C" {
fn android_dlopen_ext(
filename: *const c_char,
flags: libc::c_int,
extinfo: *const AndroidDlextinfo,
) -> *mut c_void;
}
type AndroidCreateNamespaceFn = unsafe extern "C" fn(
*const c_char, // name
*const c_char, // ld_library_path
*const c_char, // default_library_path
u64, // type
*const c_char, // permitted_when_isolated_path
*mut AndroidNamespace, // parent
*const c_void, // caller_addr
) -> *mut AndroidNamespace;
pub unsafe fn dlopen(path: &str, flags: i32) -> Result<*mut c_void> {
let filename = std::ffi::CString::new(path)?;
let filename = filename.as_ptr() as *mut _;
let dir = libc::dirname(filename);
let mut info = AndroidDlextinfo {
flags: 0,
reserved_addr: std::ptr::null_mut(),
reserved_size: 0,
relro_fd: 0,
library_fd: 0,
library_fd_offset: 0,
library_namespace: std::ptr::null_mut(),
};
let android_create_namespace_fn = libc::dlsym(
libc::RTLD_DEFAULT,
std::ffi::CString::new("__loader_android_create_namespace")?.as_ptr(),
);
let android_create_namespace_fn: AndroidCreateNamespaceFn = std::mem::transmute(android_create_namespace_fn);
let ns = android_create_namespace_fn(
filename, dir, std::ptr::null(),
ANDROID_NAMESPACE_TYPE_SHARED,
std::ptr::null(), std::ptr::null_mut(),
&dlopen as *const _ as *const c_void,
);
if ns != std::ptr::null_mut() {
info.flags = ANDROID_DLEXT_USE_NAMESPACE;
info.library_namespace = ns;
log::debug!("Open {} with namespace {:p}", path, ns);
} else {
log::debug!("Cannot create namespace for {}", path);
};
let result = android_dlopen_ext(filename, flags, &info);
if result.is_null() {
let e = std::ffi::CStr::from_ptr(libc::dlerror()).to_string_lossy();
bail!(e);
}
Ok(result)
}

View File

@@ -1,19 +0,0 @@
use std::fs;
use anyhow::Result;
use crate::constants;
use crate::utils::LateInit;
pub static MAGIC: LateInit<String> = LateInit::new();
pub static PATH_TMP_DIR: LateInit<String> = LateInit::new();
pub static PATH_TMP_PROP: LateInit<String> = LateInit::new();
pub fn setup() -> Result<()> {
let name = fs::read_to_string(constants::ZYGISK_MAGIC)?;
let path_tmp_dir = format!("/dev/{}", name);
let path_tmp_prop = format!("{}/module.prop", path_tmp_dir);
MAGIC.init(name);
PATH_TMP_DIR.init(path_tmp_dir);
PATH_TMP_PROP.init(path_tmp_prop);
Ok(())
}

73
zygiskd/src/main.c Normal file
View File

@@ -0,0 +1,73 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <android/log.h>
#include "root_impl/common.h"
#include "companion.h"
#include "zygiskd.h"
#include "utils.h"
int __android_log_print(int prio, const char *tag, const char *fmt, ...);
int main(int argc, char *argv[]) {
#ifdef __LP64__
LOGI("Welcome to ReZygisk %s Zygiskd64!\n", ZKSU_VERSION);
#else
LOGI("Welcome to ReZygisk %s Zygiskd32!\n", ZKSU_VERSION);
#endif
if (argc > 1) {
if (strcmp(argv[1], "companion") == 0) {
if (argc < 3) {
LOGI("Usage: zygiskd companion <fd>\n");
return 1;
}
int fd = atoi(argv[2]);
companion_entry(fd);
return 0;
}
else if (strcmp(argv[1], "version") == 0) {
LOGI("ReZygisk Daemon %s\n", ZKSU_VERSION);
return 0;
}
else if (strcmp(argv[1], "root") == 0) {
root_impls_setup();
struct root_impl impl;
get_impl(&impl);
char impl_name[LONGEST_ROOT_IMPL_NAME];
stringify_root_impl_name(impl, impl_name);
LOGI("Root implementation: %s\n", impl_name);
return 0;
}
else {
LOGI("Usage: zygiskd [companion|version|root]\n");
return 0;
}
}
if (switch_mount_namespace((pid_t)1) == false) {
LOGE("Failed to switch mount namespace\n");
return 1;
}
root_impls_setup();
zygiskd_start(argv);
return 0;
}

View File

@@ -1,61 +0,0 @@
#![allow(dead_code)]
mod companion;
mod constants;
mod dl;
mod magic;
mod root_impl;
mod utils;
mod watchdog;
mod zygiskd;
use anyhow::Result;
use clap::{Subcommand, Parser};
#[derive(Parser, Debug)]
#[command(author, version = constants::VERSION_FULL, about, long_about = None)]
struct Args {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Start zygisk watchdog
Watchdog,
/// Start zygisk daemon
Daemon,
/// Start zygisk companion
Companion { fd: i32 },
}
fn init_android_logger(tag: &str) {
android_logger::init_once(
android_logger::Config::default()
.with_max_level(constants::MAX_LOG_LEVEL)
.with_tag(tag),
);
}
fn start() -> Result<()> {
root_impl::setup();
magic::setup()?;
let cli = Args::parse();
match cli.command {
Commands::Watchdog => watchdog::entry()?,
Commands::Daemon => zygiskd::entry()?,
Commands::Companion { fd } => companion::entry(fd)?,
};
Ok(())
}
fn main() {
let process = std::env::args().next().unwrap();
let nice_name = process.split('/').last().unwrap();
init_android_logger(nice_name);
if let Err(e) = start() {
log::error!("Crashed: {}\n{}", e, e.backtrace());
}
}

View File

@@ -0,0 +1,194 @@
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include "../constants.h"
#include "../utils.h"
#include "common.h"
#include "apatch.h"
void apatch_get_existence(struct root_impl_state *state) {
struct stat s;
if (stat("/data/adb/apd", &s) != 0) {
if (errno != ENOENT) {
LOGE("Failed to stat APatch apd binary: %s\n", strerror(errno));
}
errno = 0;
state->state = Inexistent;
return;
}
char *PATH = getenv("PATH");
if (PATH == NULL) {
LOGE("Failed to get PATH environment variable: %s\n", strerror(errno));
errno = 0;
state->state = Inexistent;
return;
}
if (strstr(PATH, "/data/adb/ap/bin") == NULL) {
LOGE("APatch's APD binary is not in PATH\n");
state->state = Inexistent;
return;
}
char apatch_version[32];
char *const argv[] = { "apd", "-V", NULL };
if (!exec_command(apatch_version, sizeof(apatch_version), "/data/adb/apd", argv)) {
LOGE("Failed to execute apd binary: %s\n", strerror(errno));
errno = 0;
state->state = Inexistent;
return;
}
int version = atoi(apatch_version + strlen("apd "));
if (version == 0) state->state = Abnormal;
else if (version >= MIN_APATCH_VERSION && version <= 999999) state->state = Supported;
else if (version >= 1 && version <= MIN_APATCH_VERSION - 1) state->state = TooOld;
else state->state = Abnormal;
}
struct package_config {
uid_t uid;
bool root_granted;
bool umount_needed;
};
struct packages_config {
struct package_config *configs;
size_t size;
};
/* WARNING: Dynamic memory based */
bool _apatch_get_package_config(struct packages_config *restrict config) {
config->configs = NULL;
config->size = 0;
FILE *fp = fopen("/data/adb/ap/package_config", "r");
if (fp == NULL) {
LOGE("Failed to open APatch's package_config: %s\n", strerror(errno));
return false;
}
char line[1048];
/* INFO: Skip the CSV header */
if (fgets(line, sizeof(line), fp) == NULL) {
LOGE("Failed to read APatch's package_config header: %s\n", strerror(errno));
fclose(fp);
return false;
}
while (fgets(line, sizeof(line), fp) != NULL) {
config->configs = realloc(config->configs, (config->size + 1) * sizeof(struct package_config));
if (config->configs == NULL) {
LOGE("Failed to realloc APatch config struct: %s\n", strerror(errno));
fclose(fp);
return false;
}
strtok(line, ",");
char *exclude_str = strtok(NULL, ",");
if (exclude_str == NULL) continue;
char *allow_str = strtok(NULL, ",");
if (allow_str == NULL) continue;
char *uid_str = strtok(NULL, ",");
if (uid_str == NULL) continue;
config->configs[config->size].uid = atoi(uid_str);
config->configs[config->size].root_granted = strcmp(allow_str, "1") == 0;
config->configs[config->size].umount_needed = strcmp(exclude_str, "1") == 0;
config->size++;
}
fclose(fp);
return true;
}
void _apatch_free_package_config(struct packages_config *restrict config) {
free(config->configs);
}
bool apatch_uid_granted_root(uid_t uid) {
struct packages_config config;
if (!_apatch_get_package_config(&config)) {
_apatch_free_package_config(&config);
return false;
}
for (size_t i = 0; i < config.size; i++) {
if (config.configs[i].uid != uid) continue;
/* INFO: This allow us to copy the information to avoid use-after-free */
bool root_granted = config.configs[i].root_granted;
_apatch_free_package_config(&config);
return root_granted;
}
_apatch_free_package_config(&config);
return false;
}
bool apatch_uid_should_umount(uid_t uid) {
struct packages_config config;
if (!_apatch_get_package_config(&config)) {
_apatch_free_package_config(&config);
return false;
}
for (size_t i = 0; i < config.size; i++) {
if (config.configs[i].uid != uid) continue;
/* INFO: This allow us to copy the information to avoid use-after-free */
bool umount_needed = config.configs[i].umount_needed;
_apatch_free_package_config(&config);
return umount_needed;
}
_apatch_free_package_config(&config);
return false;
}
bool apatch_uid_is_manager(uid_t uid) {
struct stat s;
if (stat("/data/user_de/0/me.bmax.apatch", &s) == -1) {
if (errno != ENOENT) {
LOGE("Failed to stat APatch manager data directory: %s\n", strerror(errno));
}
errno = 0;
return false;
}
return s.st_uid == uid;
}

View File

@@ -0,0 +1,14 @@
#ifndef APATCH_H
#define APATCH_H
#include "../constants.h"
void apatch_get_existence(struct root_impl_state *state);
bool apatch_uid_granted_root(uid_t uid);
bool apatch_uid_should_umount(uid_t uid);
bool apatch_uid_is_manager(uid_t uid);
#endif

View File

@@ -0,0 +1,126 @@
#include <stdio.h>
#include <sys/types.h>
#include "../utils.h"
#include "kernelsu.h"
#include "apatch.h"
#include "magisk.h"
#include "common.h"
static struct root_impl impl;
void root_impls_setup(void) {
struct root_impl_state state_ksu;
ksu_get_existence(&state_ksu);
struct root_impl_state state_apatch;
apatch_get_existence(&state_apatch);
struct root_impl_state state_magisk;
magisk_get_existence(&state_magisk);
/* INFO: Check if it's only one supported, if not, it's multile and that's bad.
Remember that true here is equal to the integer 1. */
if ((state_ksu.state == Supported ? 1 : 0) + (state_apatch.state == Supported ? 1 : 0) + (state_magisk.state == Supported ? 1 : 0) >= 2) {
impl.impl = Multiple;
} else if (state_ksu.state == Supported) {
impl.impl = KernelSU;
} else if (state_apatch.state == Supported) {
impl.impl = APatch;
} else if (state_magisk.state == Supported) {
impl.impl = Magisk;
impl.variant = state_magisk.variant;
} else {
impl.impl = None;
}
switch (impl.impl) {
case None: {
LOGI("No root implementation found.\n");
break;
}
case Multiple: {
LOGI("Multiple root implementations found.\n");
break;
}
case KernelSU: {
LOGI("KernelSU root implementation found.\n");
break;
}
case APatch: {
LOGI("APatch root implementation found.\n");
break;
}
case Magisk: {
if (state_magisk.variant == 0) {
LOGI("Magisk Official root implementation found.\n");
} else {
LOGI("Magisk Kitsune root implementation found.\n");
}
break;
}
}
}
void get_impl(struct root_impl *uimpl) {
uimpl->impl = impl.impl;
uimpl->variant = impl.variant;
}
bool uid_granted_root(uid_t uid) {
switch (impl.impl) {
case KernelSU: {
return ksu_uid_granted_root(uid);
}
case APatch: {
return apatch_uid_granted_root(uid);
}
case Magisk: {
return magisk_uid_granted_root(uid);
}
default: {
return false;
}
}
}
bool uid_should_umount(uid_t uid) {
switch (impl.impl) {
case KernelSU: {
return ksu_uid_should_umount(uid);
}
case APatch: {
return apatch_uid_should_umount(uid);
}
case Magisk: {
return magisk_uid_should_umount(uid);
}
default: {
return false;
}
}
}
bool uid_is_manager(uid_t uid) {
switch (impl.impl) {
case KernelSU: {
return ksu_uid_is_manager(uid);
}
case APatch: {
return apatch_uid_is_manager(uid);
}
case Magisk: {
return magisk_uid_is_manager(uid);
}
default: {
return false;
}
}
}

View File

@@ -0,0 +1,38 @@
#ifndef COMMON_H
#define COMMON_H
#include <stdint.h>
#include "../constants.h"
enum root_impls {
None,
Multiple,
KernelSU,
APatch,
Magisk
};
struct root_impl_state {
enum RootImplState state;
uint8_t variant;
};
struct root_impl {
enum root_impls impl;
uint8_t variant;
};
#define LONGEST_ROOT_IMPL_NAME sizeof("Magisk Official")
void root_impls_setup(void);
void get_impl(struct root_impl *uimpl);
bool uid_granted_root(uid_t uid);
bool uid_should_umount(uid_t uid);
bool uid_is_manager(uid_t uid);
#endif /* COMMON_H */

View File

@@ -0,0 +1,82 @@
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#include <errno.h>
#include "../constants.h"
#include "../utils.h"
#include "common.h"
#include "kernelsu.h"
/* INFO: It would be presumed it is a unsigned int,
so we need to cast it to signed int to
avoid any potential UB.
*/
#define KERNEL_SU_OPTION 0xdeadbeef
#define CMD_GET_VERSION 2
#define CMD_UID_GRANTED_ROOT 12
#define CMD_UID_SHOULD_UMOUNT 13
void ksu_get_existence(struct root_impl_state *state) {
int version = 0;
prctl((signed int)KERNEL_SU_OPTION, CMD_GET_VERSION, &version, 0, 0);
if (version == 0) state->state = Abnormal;
else if (version >= MIN_KSU_VERSION && version <= MAX_KSU_VERSION) {
/* INFO: Some custom kernels for custom ROMs have pre-installed KernelSU.
Some users don't want to use KernelSU, but, for example, Magisk.
This if allows this to happen, as it checks if "ksud" exists,
which in case it doesn't, it won't be considered as supported. */
struct stat s;
if (stat("/data/adb/ksud", &s) == -1) {
if (errno != ENOENT) {
LOGE("Failed to stat KSU daemon: %s\n", strerror(errno));
}
errno = 0;
state->state = Abnormal;
return;
}
state->state = Supported;
}
else if (version >= 1 && version <= MIN_KSU_VERSION - 1) state->state = TooOld;
else state->state = Abnormal;
}
bool ksu_uid_granted_root(uid_t uid) {
uint32_t result = 0;
bool granted = false;
prctl(KERNEL_SU_OPTION, CMD_UID_GRANTED_ROOT, uid, &granted, &result);
if (result != KERNEL_SU_OPTION) return false;
return granted;
}
bool ksu_uid_should_umount(uid_t uid) {
uint32_t result = 0;
bool umount = false;
prctl(KERNEL_SU_OPTION, CMD_UID_SHOULD_UMOUNT, uid, &umount, &result);
if (result != KERNEL_SU_OPTION) return false;
return umount;
}
bool ksu_uid_is_manager(uid_t uid) {
struct stat s;
if (stat("/data/user_de/0/me.weishu.kernelsu", &s) == -1) {
if (errno != ENOENT) {
LOGE("Failed to stat KSU manager data directory: %s\n", strerror(errno));
}
errno = 0;
return false;
}
return s.st_uid == uid;
}

View File

@@ -0,0 +1,14 @@
#ifndef KERNELSU_H
#define KERNELSU_H
#include "../constants.h"
void ksu_get_existence(struct root_impl_state *state);
bool ksu_uid_granted_root(uid_t uid);
bool ksu_uid_should_umount(uid_t uid);
bool ksu_uid_is_manager(uid_t uid);
#endif

View File

@@ -1,43 +0,0 @@
use nix::libc::prctl;
use crate::constants::{MIN_KSU_VERSION, MAX_KSU_VERSION};
const KERNEL_SU_OPTION: i32 = 0xdeadbeefu32 as i32;
const CMD_GET_VERSION: usize = 2;
const CMD_GET_ALLOW_LIST: usize = 5;
const CMD_GET_DENY_LIST: usize = 6;
pub enum Version {
Supported,
TooOld,
Abnormal,
}
pub fn get_kernel_su() -> Option<Version> {
let mut version = 0;
unsafe { prctl(KERNEL_SU_OPTION, CMD_GET_VERSION, &mut version as *mut i32) };
match version {
0 => None,
MIN_KSU_VERSION..=MAX_KSU_VERSION => Some(Version::Supported),
1..=MIN_KSU_VERSION => Some(Version::TooOld),
_ => Some(Version::Abnormal)
}
}
#[inline(never)]
pub fn uid_on_allowlist(uid: i32) -> bool {
let mut size = 1024u32;
let mut uids = vec![0; size as usize];
unsafe { prctl(KERNEL_SU_OPTION, CMD_GET_ALLOW_LIST, uids.as_mut_ptr(), &mut size as *mut u32) };
uids.resize(size as usize, 0);
uids.contains(&uid)
}
#[inline(never)]
pub fn uid_on_denylist(uid: i32) -> bool {
let mut size = 1024u32;
let mut uids = vec![0; size as usize];
unsafe { prctl(KERNEL_SU_OPTION, CMD_GET_DENY_LIST, uids.as_mut_ptr(), &mut size as *mut u32) };
uids.resize(size as usize, 0);
uids.contains(&uid)
}

View File

@@ -0,0 +1,190 @@
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#include <errno.h>
#include <unistd.h>
#include "../constants.h"
#include "../utils.h"
#include "common.h"
#include "magisk.h"
char *supported_variants[] = {
"kitsune"
};
char *magisk_managers[] = {
"com.topjohnwu.magisk",
"io.github.huskydg.magisk"
};
#define SBIN_MAGISK lp_select("/sbin/magisk32", "/sbin/magisk64")
#define DEBUG_RAMDISK_MAGISK lp_select("/debug_ramdisk/magisk32", "/debug_ramdisk/magisk64")
#define BITLESS_DEBUG_RAMDISK_MAGISK "/debug_ramdisk/magisk"
enum magisk_variants variant = Official;
/* INFO: Longest path */
static char path_to_magisk[sizeof(DEBUG_RAMDISK_MAGISK)];
void magisk_get_existence(struct root_impl_state *state) {
struct stat s;
if (stat(SBIN_MAGISK, &s) != 0) {
if (errno != ENOENT) {
LOGE("Failed to stat Magisk /sbin/magisk binary: %s\n", strerror(errno));
}
errno = 0;
if (stat(DEBUG_RAMDISK_MAGISK, &s) != 0) {
if (errno != ENOENT) {
LOGE("Failed to stat Magisk %s binary: %s\n", DEBUG_RAMDISK_MAGISK, strerror(errno));
}
errno = 0;
if (stat(BITLESS_DEBUG_RAMDISK_MAGISK, &s) != 0) {
if (errno != ENOENT) {
LOGE("Failed to stat Magisk /debug_ramdisk/magisk binary: %s\n", strerror(errno));
}
errno = 0;
state->state = Inexistent;
return;
}
/* INFO: /debug_ramdisk/magisk64 (or 32) doesn't exist but /debug_ramdisk/magisk does */
strcpy(path_to_magisk, BITLESS_DEBUG_RAMDISK_MAGISK);
} else {
/* INFO: /sbin/magisk doesn't exist but /debug_ramdisk/magisk does */
strcpy(path_to_magisk, DEBUG_RAMDISK_MAGISK);
}
} else {
/* INFO: /sbin/magisk exists */
strcpy(path_to_magisk, SBIN_MAGISK);
}
char *argv[] = { "magisk", "-v", NULL };
char magisk_info[128];
if (!exec_command(magisk_info, sizeof(magisk_info), (const char *)path_to_magisk, argv)) {
LOGE("Failed to execute magisk binary: %s\n", strerror(errno));
errno = 0;
state->state = Abnormal;
return;
}
state->variant = (uint8_t)Official;
for (unsigned long i = 0; i < sizeof(supported_variants) / sizeof(supported_variants[0]); i++) {
if (strstr(magisk_info, supported_variants[i])) {
variant = (enum magisk_variants)(i + 1);
state->variant = (uint8_t)variant;
break;
}
}
argv[1] = "-V";
char magisk_version[32];
if (!exec_command(magisk_version, sizeof(magisk_version), (const char *)path_to_magisk, argv)) {
LOGE("Failed to execute magisk binary: %s\n", strerror(errno));
errno = 0;
state->state = Abnormal;
return;
}
if (atoi(magisk_version) >= MIN_MAGISK_VERSION) state->state = Supported;
else state->state = TooOld;
}
bool magisk_uid_granted_root(uid_t uid) {
char sqlite_cmd[256];
snprintf(sqlite_cmd, sizeof(sqlite_cmd), "select 1 from policies where uid=%d and policy=2 limit 1", uid);
char *const argv[] = { "magisk", "--sqlite", sqlite_cmd, NULL };
char result[32];
if (!exec_command(result, sizeof(result), (const char *)path_to_magisk, argv)) {
LOGE("Failed to execute magisk binary: %s\n", strerror(errno));
errno = 0;
return false;
}
return result[0] != '\0';
}
bool magisk_uid_should_umount(uid_t uid) {
char uid_str[16];
snprintf(uid_str, sizeof(uid_str), "%d", uid);
char *const argv_pm[] = { "pm", "list", "packages", "--uid", uid_str, NULL };
char result[256];
if (!exec_command(result, sizeof(result), "/system/bin/pm", argv_pm)) {
LOGE("Failed to execute pm binary: %s\n", strerror(errno));
errno = 0;
/* INFO: It's better if we do NOT umount than the opposite */
return false;
}
if (result[0] == '\0') {
LOGE("Failed to get package name from UID %d\n", uid);
return false;
}
char *package_name = strtok(result + strlen("package:"), " ");
char sqlite_cmd[256];
snprintf(sqlite_cmd, sizeof(sqlite_cmd), "select 1 from denylist where package_name=\"%s\" limit 1", package_name);
char *const argv[] = { "magisk", "--sqlite", sqlite_cmd, NULL };
if (!exec_command(result, sizeof(result), (const char *)path_to_magisk, argv)) {
LOGE("Failed to execute magisk binary: %s\n", strerror(errno));
errno = 0;
return false;
}
return result[0] != '\0';
}
bool magisk_uid_is_manager(uid_t uid) {
char *const argv[] = { "magisk", "--sqlite", "select value from strings where key=\"requester\" limit 1", NULL };
char output[128];
if (!exec_command(output, sizeof(output), (const char *)path_to_magisk, argv)) {
LOGE("Failed to execute magisk binary: %s\n", strerror(errno));
errno = 0;
return false;
}
char stat_path[PATH_MAX];
if (output[0] == '\0')
snprintf(stat_path, sizeof(stat_path), "/data/user_de/0/%s", magisk_managers[(int)variant]);
else
snprintf(stat_path, sizeof(stat_path), "/data/user_de/0/%s", output + strlen("value="));
struct stat s;
if (stat(stat_path, &s) == -1) {
LOGE("Failed to stat %s: %s\n", stat_path, strerror(errno));
errno = 0;
return false;
}
return s.st_uid == uid;
}

View File

@@ -0,0 +1,19 @@
#ifndef MAGISK_H
#define MAGISK_H
#include "../constants.h"
enum magisk_variants {
Official,
Kitsune
};
void magisk_get_existence(struct root_impl_state *state);
bool magisk_uid_granted_root(uid_t uid);
bool magisk_uid_should_umount(uid_t uid);
bool magisk_uid_is_manager(uid_t uid);
#endif

View File

@@ -1,48 +0,0 @@
use std::process::{Command, Stdio};
use crate::constants::MIN_MAGISK_VERSION;
pub enum Version {
Supported,
TooOld,
}
pub fn get_magisk() -> Option<Version> {
let version: Option<i32> = Command::new("magisk")
.arg("-V")
.stdout(Stdio::piped())
.spawn().ok()
.and_then(|child| child.wait_with_output().ok())
.and_then(|output| String::from_utf8(output.stdout).ok())
.and_then(|output| output.trim().parse().ok());
version.map(|version| {
if version >= MIN_MAGISK_VERSION {
Version::Supported
} else {
Version::TooOld
}
})
}
#[inline(never)]
pub fn uid_on_allowlist(uid: i32) -> bool {
let output: Option<String> = Command::new("magisk")
.arg("--sqlite")
.arg("select uid from policies where policy=2")
.stdout(Stdio::piped())
.spawn().ok()
.and_then(|child| child.wait_with_output().ok())
.and_then(|output| String::from_utf8(output.stdout).ok());
let lines = match &output {
Some(output) => output.lines(),
None => return false,
};
lines.into_iter().any(|line| {
line.trim().strip_prefix("uid=").and_then(|uid| uid.parse().ok()) == Some(uid)
})
}
#[inline(never)]
pub fn uid_on_denylist(uid: i32) -> bool {
// TODO: uid_on_denylist
return false;
}

View File

@@ -1,61 +0,0 @@
mod kernelsu;
mod magisk;
pub enum RootImpl {
None,
TooOld,
Abnormal,
Multiple,
KernelSU,
Magisk,
}
// FIXME: OnceCell bugs on 32 bit
static mut ROOT_IMPL: RootImpl = RootImpl::None;
pub fn setup() {
let ksu_version = kernelsu::get_kernel_su();
let magisk_version = magisk::get_magisk();
let impl_ = match (ksu_version, magisk_version) {
(None, None) => RootImpl::None,
(Some(_), Some(_)) => RootImpl::Multiple,
(Some(ksu_version), None) => {
match ksu_version {
kernelsu::Version::Supported => RootImpl::KernelSU,
kernelsu::Version::TooOld => RootImpl::TooOld,
kernelsu::Version::Abnormal => RootImpl::Abnormal,
}
}
(None, Some(magisk_version)) => {
match magisk_version {
magisk::Version::Supported => RootImpl::Magisk,
magisk::Version::TooOld => RootImpl::TooOld,
}
}
};
unsafe { ROOT_IMPL = impl_; }
}
pub fn get_impl() -> &'static RootImpl {
unsafe { &ROOT_IMPL }
}
// FIXME: Without #[inline(never)], this function will lag forever
#[inline(never)]
pub fn uid_on_allowlist(uid: i32) -> bool {
match get_impl() {
RootImpl::KernelSU => kernelsu::uid_on_allowlist(uid),
RootImpl::Magisk => magisk::uid_on_allowlist(uid),
_ => unreachable!(),
}
}
#[inline(never)]
pub fn uid_on_denylist(uid: i32) -> bool {
match get_impl() {
RootImpl::KernelSU => kernelsu::uid_on_denylist(uid),
RootImpl::Magisk => magisk::uid_on_denylist(uid),
_ => unreachable!(),
}
}

458
zygiskd/src/utils.c Normal file
View File

@@ -0,0 +1,458 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <errno.h>
#include <unistd.h>
#include <linux/limits.h>
#include <sched.h>
#include <pthread.h>
#include <android/log.h>
#include "utils.h"
#include "root_impl/common.h"
bool switch_mount_namespace(pid_t pid) {
char path[PATH_MAX];
snprintf(path, sizeof(path), "/proc/%d/ns/mnt", pid);
int nsfd = open(path, O_RDONLY | O_CLOEXEC);
if (nsfd == -1) {
LOGE("Failed to open nsfd: %s\n", strerror(errno));
return false;
}
if (setns(nsfd, CLONE_NEWNS) == -1) {
LOGE("Failed to setns: %s\n", strerror(errno));
close(nsfd);
return false;
}
close(nsfd);
return true;
}
int __system_property_get(const char *, char *);
void get_property(const char *restrict name, char *restrict output) {
__system_property_get(name, output);
}
void set_socket_create_context(const char *restrict context) {
char path[PATH_MAX];
snprintf(path, PATH_MAX, "/proc/thread-self/attr/sockcreate");
FILE *sockcreate = fopen(path, "w");
if (sockcreate == NULL) {
LOGE("Failed to open /proc/thread-self/attr/sockcreate: %s Now trying to via gettid().\n", strerror(errno));
goto fail;
}
if (fwrite(context, 1, strlen(context), sockcreate) != strlen(context)) {
LOGE("Failed to write to /proc/thread-self/attr/sockcreate: %s Now trying to via gettid().\n", strerror(errno));
fclose(sockcreate);
goto fail;
}
fclose(sockcreate);
return;
fail:
snprintf(path, PATH_MAX, "/proc/self/task/%d/attr/sockcreate", gettid());
sockcreate = fopen(path, "w");
if (sockcreate == NULL) {
LOGE("Failed to open %s: %s\n", path, strerror(errno));
return;
}
if (fwrite(context, 1, strlen(context), sockcreate) != strlen(context)) {
LOGE("Failed to write to %s: %s\n", path, strerror(errno));
return;
}
fclose(sockcreate);
}
static void get_current_attr(char *restrict output, size_t size) {
char path[PATH_MAX];
snprintf(path, PATH_MAX, "/proc/self/attr/current");
FILE *current = fopen(path, "r");
if (current == NULL) {
LOGE("fopen: %s\n", strerror(errno));
return;
}
if (fread(output, 1, size, current) == 0) {
LOGE("fread: %s\n", strerror(errno));
return;
}
fclose(current);
}
void unix_datagram_sendto(const char *restrict path, void *restrict buf, size_t len) {
char current_attr[PATH_MAX];
get_current_attr(current_attr, sizeof(current_attr));
set_socket_create_context(current_attr);
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
int socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (socket_fd == -1) {
LOGE("socket: %s\n", strerror(errno));
return;
}
if (connect(socket_fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOGE("connect: %s\n", strerror(errno));
return;
}
if (sendto(socket_fd, buf, len, 0, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOGE("sendto: %s\n", strerror(errno));
return;
}
set_socket_create_context("u:r:zygote:s0");
close(socket_fd);
}
int chcon(const char *restrict path, const char *context) {
char command[PATH_MAX];
snprintf(command, PATH_MAX, "chcon %s %s", context, path);
return system(command);
}
int unix_listener_from_path(char *restrict path) {
if (remove(path) == -1 && errno != ENOENT) {
LOGE("remove: %s\n", strerror(errno));
return -1;
}
int socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (socket_fd == -1) {
LOGE("socket: %s\n", strerror(errno));
return -1;
}
struct sockaddr_un addr = {
.sun_family = AF_UNIX
};
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
if (bind(socket_fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) {
LOGE("bind: %s\n", strerror(errno));
return -1;
}
if (listen(socket_fd, 2) == -1) {
LOGE("listen: %s\n", strerror(errno));
return -1;
}
if (chcon(path, "u:object_r:magisk_file:s0") == -1) {
LOGE("chcon: %s\n", strerror(errno));
return -1;
}
return socket_fd;
}
ssize_t write_fd(int fd, int sendfd) {
char cmsgbuf[CMSG_SPACE(sizeof(int))];
char buf[1] = { 0 };
struct iovec iov = {
.iov_base = buf,
.iov_len = 1
};
struct msghdr msg = {
.msg_iov = &iov,
.msg_iovlen = 1,
.msg_control = cmsgbuf,
.msg_controllen = sizeof(cmsgbuf)
};
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
memcpy(CMSG_DATA(cmsg), &sendfd, sizeof(int));
ssize_t ret = sendmsg(fd, &msg, 0);
if (ret == -1) {
LOGE("sendmsg: %s\n", strerror(errno));
return -1;
}
return ret;
}
int read_fd(int fd) {
char cmsgbuf[CMSG_SPACE(sizeof(int))];
char buf[1] = { 0 };
struct iovec iov = {
.iov_base = buf,
.iov_len = 1
};
struct msghdr msg = {
.msg_iov = &iov,
.msg_iovlen = 1,
.msg_control = cmsgbuf,
.msg_controllen = sizeof(cmsgbuf)
};
ssize_t ret = recvmsg(fd, &msg, 0);
if (ret == -1) {
LOGE("recvmsg: %s\n", strerror(errno));
return -1;
}
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
if (cmsg == NULL) {
LOGE("CMSG_FIRSTHDR: %s\n", strerror(errno));
return -1;
}
int sendfd;
memcpy(&sendfd, CMSG_DATA(cmsg), sizeof(int));
return sendfd;
}
#define write_func(type) \
ssize_t write_## type(int fd, type val) { \
return write(fd, &val, sizeof(type)); \
}
#define read_func(type) \
ssize_t read_## type(int fd, type *val) { \
return read(fd, val, sizeof(type)); \
}
write_func(int)
read_func(int)
write_func(size_t)
read_func(size_t)
write_func(uint32_t)
read_func(uint32_t)
write_func(uint8_t)
read_func(uint8_t)
ssize_t write_string(int fd, const char *restrict str) {
size_t len[1];
len[0] = strlen(str);
ssize_t written_bytes = write(fd, &len, sizeof(size_t));
if (written_bytes != sizeof(size_t)) {
LOGE("Failed to write string length: Not all bytes were written (%zd != %zu).\n", written_bytes, sizeof(size_t));
return -1;
}
written_bytes = write(fd, str, len[0]);
if ((size_t)written_bytes != len[0]) {
LOGE("Failed to write string: Not all bytes were written.\n");
return -1;
}
return written_bytes;
}
ssize_t read_string(int fd, char *restrict str, size_t len) {
size_t str_len_buf[1];
ssize_t read_bytes = read(fd, &str_len_buf, sizeof(size_t));
if (read_bytes != (ssize_t)sizeof(size_t)) {
LOGE("Failed to read string length: Not all bytes were read (%zd != %zu).\n", read_bytes, sizeof(size_t));
return -1;
}
size_t str_len = str_len_buf[0];
if (str_len > len) {
LOGE("Failed to read string: Buffer is too small (%zu > %zu).\n", str_len, len);
return -1;
}
read_bytes = read(fd, str, str_len);
if (read_bytes != (ssize_t)str_len) {
LOGE("Failed to read string: Promised bytes doesn't exist (%zd != %zu).\n", read_bytes, str_len);
return -1;
}
return read_bytes;
}
/* INFO: Cannot use restrict here as execv does not have restrict */
bool exec_command(char *restrict buf, size_t len, const char *restrict file, char *const argv[]) {
int link[2];
pid_t pid;
if (pipe(link) == -1) {
LOGE("pipe: %s\n", strerror(errno));
return false;
}
if ((pid = fork()) == -1) {
LOGE("fork: %s\n", strerror(errno));
close(link[0]);
close(link[1]);
return false;
}
if (pid == 0) {
dup2(link[1], STDOUT_FILENO);
close(link[0]);
close(link[1]);
execv(file, argv);
LOGE("execv failed: %s\n", strerror(errno));
_exit(1);
} else {
close(link[1]);
int nbytes = read(link[0], buf, len);
if (nbytes > 0) buf[nbytes - 1] = '\0';
/* INFO: If something went wrong, at least we must ensure it is NULL-terminated */
else buf[0] = '\0';
wait(NULL);
close(link[0]);
}
return true;
}
bool check_unix_socket(int fd, bool block) {
struct pollfd pfd = {
.fd = fd,
.events = POLLIN,
.revents = 0
};
int timeout = block ? -1 : 0;
poll(&pfd, 1, timeout);
return pfd.revents & ~POLLIN ? false : true;
}
/* INFO: Cannot use restrict here as execv does not have restrict */
int non_blocking_execv(const char *restrict file, char *const argv[]) {
int link[2];
pid_t pid;
if (pipe(link) == -1) {
LOGE("pipe: %s\n", strerror(errno));
return -1;
}
if ((pid = fork()) == -1) {
LOGE("fork: %s\n", strerror(errno));
return -1;
}
if (pid == 0) {
dup2(link[1], STDOUT_FILENO);
close(link[0]);
close(link[1]);
execv(file, argv);
} else {
close(link[1]);
return link[0];
}
return -1;
}
void stringify_root_impl_name(struct root_impl impl, char *restrict output) {
switch (impl.impl) {
case None: {
strcpy(output, "None");
break;
}
case Multiple: {
strcpy(output, "Multiple");
break;
}
case KernelSU: {
strcpy(output, "KernelSU");
break;
}
case APatch: {
strcpy(output, "APatch");
break;
}
case Magisk: {
if (impl.variant == 0) {
strcpy(output, "Magisk Official");
} else {
strcpy(output, "Magisk Kitsune");
}
break;
}
}
}

107
zygiskd/src/utils.h Normal file
View File

@@ -0,0 +1,107 @@
#ifndef UTILS_H
#define UTILS_H
#include <sys/types.h>
#include "constants.h"
#include "root_impl/common.h"
#define CONCAT_(x,y) x##y
#define CONCAT(x,y) CONCAT_(x,y)
#define LOGI(...) \
__android_log_print(ANDROID_LOG_INFO, lp_select("zygiskd32", "zygiskd64"), __VA_ARGS__); \
printf(__VA_ARGS__);
#define LOGE(...) \
__android_log_print(ANDROID_LOG_ERROR , lp_select("zygiskd32", "zygiskd64"), __VA_ARGS__); \
printf(__VA_ARGS__);
#define ASSURE_SIZE_WRITE(area_name, subarea_name, sent_size, expected_size) \
if (sent_size != (ssize_t)(expected_size)) { \
LOGE("Failed to sent " subarea_name " in " area_name ": Expected %zu, got %zd\n", expected_size, sent_size); \
\
return; \
}
#define ASSURE_SIZE_READ(area_name, subarea_name, sent_size, expected_size) \
if (sent_size != (ssize_t)(expected_size)) { \
LOGE("Failed to read " subarea_name " in " area_name ": Expected %zu, got %zd\n", expected_size, sent_size); \
\
return; \
}
#define ASSURE_SIZE_WRITE_BREAK(area_name, subarea_name, sent_size, expected_size) \
if (sent_size != (ssize_t)(expected_size)) { \
LOGE("Failed to sent " subarea_name " in " area_name ": Expected %zu, got %zd\n", expected_size, sent_size); \
\
break; \
}
#define ASSURE_SIZE_READ_BREAK(area_name, subarea_name, sent_size, expected_size) \
if (sent_size != (ssize_t)(expected_size)) { \
LOGE("Failed to read " subarea_name " in " area_name ": Expected %zu, got %zd\n", expected_size, sent_size); \
\
break; \
}
#define ASSURE_SIZE_WRITE_WR(area_name, subarea_name, sent_size, expected_size) \
if (sent_size != (ssize_t)(expected_size)) { \
LOGE("Failed to sent " subarea_name " in " area_name ": Expected %zu, got %zd\n", expected_size, sent_size); \
\
return -1; \
}
#define ASSURE_SIZE_READ_WR(area_name, subarea_name, sent_size, expected_size) \
if (sent_size != (ssize_t)(expected_size)) { \
LOGE("Failed to read " subarea_name " in " area_name ": Expected %zu, got %zd\n", expected_size, sent_size); \
\
return -1; \
}
#define write_func_def(type) \
ssize_t write_## type(int fd, type val)
#define read_func_def(type) \
ssize_t read_## type(int fd, type *val)
bool switch_mount_namespace(pid_t pid);
void get_property(const char *name, char *restrict output);
void set_socket_create_context(const char *restrict context);
void unix_datagram_sendto(const char *restrict path, void *restrict buf, size_t len);
int chcon(const char *path, const char *restrict context);
int unix_listener_from_path(char *path);
ssize_t write_fd(int fd, int sendfd);
int read_fd(int fd);
write_func_def(int);
read_func_def(int);
write_func_def(size_t);
read_func_def(size_t);
write_func_def(uint32_t);
read_func_def(uint32_t);
write_func_def(uint8_t);
read_func_def(uint8_t);
ssize_t write_string(int fd, const char *restrict str);
ssize_t read_string(int fd, char *restrict str, size_t len);
bool exec_command(char *restrict buf, size_t len, const char *restrict file, char *const argv[]);
bool check_unix_socket(int fd, bool block);
int non_blocking_execv(const char *restrict file, char *const argv[]);
void stringify_root_impl_name(struct root_impl impl, char *restrict output);
#endif /* UTILS_H */

View File

@@ -1,161 +0,0 @@
use anyhow::Result;
use nix::unistd::gettid;
use std::{fs, io::{Read, Write}, os::unix::net::UnixStream, process::Command};
use std::ffi::c_char;
use std::os::fd::FromRawFd;
use std::os::unix::net::UnixListener;
use nix::sys::socket::{AddressFamily, SockFlag, SockType, UnixAddr};
use once_cell::sync::OnceCell;
use rand::distributions::{Alphanumeric, DistString};
#[cfg(target_pointer_width = "64")]
#[macro_export]
macro_rules! lp_select {
($lp32:expr, $lp64:expr) => { $lp64 };
}
#[cfg(target_pointer_width = "32")]
#[macro_export]
macro_rules! lp_select {
($lp32:expr, $lp64:expr) => { $lp32 };
}
pub struct LateInit<T> {
cell: OnceCell<T>,
}
impl<T> LateInit<T> {
pub const fn new() -> Self {
LateInit { cell: OnceCell::new() }
}
pub fn init(&self, value: T) {
assert!(self.cell.set(value).is_ok())
}
}
impl<T> std::ops::Deref for LateInit<T> {
type Target = T;
fn deref(&self) -> &T {
self.cell.get().unwrap()
}
}
pub fn random_string() -> String {
Alphanumeric.sample_string(&mut rand::thread_rng(), 8)
}
pub fn set_socket_create_context(context: &str) -> Result<()> {
let path = "/proc/thread-self/attr/sockcreate";
match fs::write(path, context) {
Ok(_) => Ok(()),
Err(_) => {
let path = format!("/proc/self/task/{}/attr/sockcreate", gettid().as_raw());
fs::write(path, context)?;
Ok(())
}
}
}
pub fn get_native_bridge() -> String {
std::env::var("NATIVE_BRIDGE").unwrap_or_default()
}
pub fn log_raw(level: i32, tag: &str, message: &str) -> Result<()> {
let tag = std::ffi::CString::new(tag)?;
let message = std::ffi::CString::new(message)?;
unsafe {
__android_log_print(level as i32, tag.as_ptr(), message.as_ptr());
}
Ok(())
}
pub fn get_property(name: &str) -> Result<String> {
let name = std::ffi::CString::new(name)?;
let mut buf = vec![0u8; 92];
unsafe {
__system_property_get(name.as_ptr(), buf.as_mut_ptr() as *mut c_char);
}
Ok(String::from_utf8(buf)?)
}
pub fn set_property(name: &str, value: &str) -> Result<()> {
Command::new("resetprop")
.arg(name)
.arg(value)
.spawn()?.wait()?;
Ok(())
}
pub trait UnixStreamExt {
fn read_u8(&mut self) -> Result<u8>;
fn read_u32(&mut self) -> Result<u32>;
fn read_usize(&mut self) -> Result<usize>;
fn read_string(&mut self) -> Result<String>;
fn write_u8(&mut self, value: u8) -> Result<()>;
fn write_u32(&mut self, value: u32) -> Result<()>;
fn write_usize(&mut self, value: usize) -> Result<()>;
fn write_string(&mut self, value: &str) -> Result<()>;
}
impl UnixStreamExt for UnixStream {
fn read_u8(&mut self) -> Result<u8> {
let mut buf = [0u8; 1];
self.read_exact(&mut buf)?;
Ok(buf[0])
}
fn read_u32(&mut self) -> Result<u32> {
let mut buf = [0u8; 4];
self.read_exact(&mut buf)?;
Ok(u32::from_ne_bytes(buf))
}
fn read_usize(&mut self) -> Result<usize> {
let mut buf = [0u8; std::mem::size_of::<usize>()];
self.read_exact(&mut buf)?;
Ok(usize::from_ne_bytes(buf))
}
fn read_string(&mut self) -> Result<String> {
let len = self.read_usize()?;
let mut buf = vec![0u8; len];
self.read_exact(&mut buf)?;
Ok(String::from_utf8(buf)?)
}
fn write_u8(&mut self, value: u8) -> Result<()> {
self.write_all(&value.to_ne_bytes())?;
Ok(())
}
fn write_u32(&mut self, value: u32) -> Result<()> {
self.write_all(&value.to_ne_bytes())?;
Ok(())
}
fn write_usize(&mut self, value: usize) -> Result<()> {
self.write_all(&value.to_ne_bytes())?;
Ok(())
}
fn write_string(&mut self, value: &str) -> Result<()> {
self.write_usize(value.len())?;
self.write_all(value.as_bytes())?;
Ok(())
}
}
// TODO: Replace with SockAddrExt::from_abstract_name when it's stable
pub fn abstract_namespace_socket(name: &str) -> Result<UnixListener> {
let addr = UnixAddr::new_abstract(name.as_bytes())?;
let socket = nix::sys::socket::socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), None)?;
nix::sys::socket::bind(socket, &addr)?;
nix::sys::socket::listen(socket, 2)?;
let listener = unsafe { UnixListener::from_raw_fd(socket) };
Ok(listener)
}
extern "C" {
fn __android_log_print(prio: i32, tag: *const c_char, fmt: *const c_char, ...) -> i32;
fn __system_property_get(name: *const c_char, value: *mut c_char) -> u32;
}

View File

@@ -1,191 +0,0 @@
use crate::{constants, magic, root_impl, utils};
use anyhow::{bail, Result};
use nix::unistd::{getgid, getuid, Pid};
use std::process::{Child, Command};
use std::sync::mpsc;
use std::{fs, io, thread};
use std::ffi::CString;
use std::io::{BufRead, Write};
use std::os::unix::net::UnixListener;
use std::time::Duration;
use binder::IBinder;
use nix::errno::Errno;
use nix::libc;
use nix::sys::signal::{kill, Signal};
use crate::utils::LateInit;
static LOCK: LateInit<UnixListener> = LateInit::new();
static PROP_SECTIONS: LateInit<[String; 2]> = LateInit::new();
pub fn entry() -> Result<()> {
log::info!("Start zygisksu watchdog");
check_permission()?;
ensure_single_instance()?;
mount_prop()?;
if check_and_set_hint()? == false {
log::warn!("Requirements not met, exiting");
utils::set_property(constants::PROP_NATIVE_BRIDGE, &utils::get_native_bridge())?;
return Ok(());
}
let end = spawn_daemon();
set_prop_hint(constants::STATUS_CRASHED)?;
end
}
fn check_permission() -> Result<()> {
log::info!("Check permission");
let uid = getuid();
if uid.as_raw() != 0 {
bail!("UID is not 0");
}
let gid = getgid();
if gid.as_raw() != 0 {
bail!("GID is not 0");
}
let context = fs::read_to_string("/proc/self/attr/current")?;
let context = context.trim_end_matches('\0');
if context != "u:r:su:s0" && context != "u:r:magisk:s0" {
bail!("SELinux context incorrect: {context}");
}
Ok(())
}
fn ensure_single_instance() -> Result<()> {
log::info!("Ensure single instance");
let name = format!("zygiskwd{}", magic::MAGIC.as_str());
match utils::abstract_namespace_socket(&name) {
Ok(socket) => LOCK.init(socket),
Err(e) => bail!("Failed to acquire lock: {e}. Maybe another instance is running?")
}
Ok(())
}
fn mount_prop() -> Result<()> {
let module_prop = if let root_impl::RootImpl::Magisk = root_impl::get_impl() {
let magisk_path = Command::new("magisk").arg("--path").output()?;
let mut magisk_path = String::from_utf8(magisk_path.stdout)?;
magisk_path.pop(); // Removing '\n'
let cwd = std::env::current_dir()?;
let dir = cwd.file_name().unwrap().to_string_lossy();
format!("{magisk_path}/.magisk/modules/{dir}/{}", constants::PATH_MODULE_PROP)
} else {
constants::PATH_MODULE_PROP.to_string()
};
log::info!("Mount {module_prop}");
let module_prop_file = fs::File::open(&module_prop)?;
let mut section = 0;
let mut sections: [String; 2] = [String::new(), String::new()];
let lines = io::BufReader::new(module_prop_file).lines();
for line in lines {
let line = line?;
if line.starts_with("description=") {
sections[0].push_str("description=");
sections[1].push_str(line.trim_start_matches("description="));
sections[1].push('\n');
section = 1;
} else {
sections[section].push_str(&line);
sections[section].push('\n');
}
}
PROP_SECTIONS.init(sections);
fs::create_dir(magic::PATH_TMP_DIR.as_str())?;
fs::File::create(magic::PATH_TMP_PROP.as_str())?;
// FIXME: sys_mount cannot be compiled on 32 bit
unsafe {
let r = libc::mount(
CString::new(magic::PATH_TMP_PROP.as_str())?.as_ptr(),
CString::new(module_prop)?.as_ptr(),
std::ptr::null(),
libc::MS_BIND,
std::ptr::null(),
);
Errno::result(r)?;
}
Ok(())
}
fn set_prop_hint(hint: &str) -> Result<()> {
let mut file = fs::File::create(magic::PATH_TMP_PROP.as_str())?;
file.write_all(PROP_SECTIONS[0].as_bytes())?;
file.write_all(b"[")?;
file.write_all(hint.as_bytes())?;
file.write_all(b"] ")?;
file.write_all(PROP_SECTIONS[1].as_bytes())?;
Ok(())
}
fn check_and_set_hint() -> Result<bool> {
let root_impl = root_impl::get_impl();
match root_impl {
root_impl::RootImpl::None => set_prop_hint(constants::STATUS_ROOT_IMPL_NONE)?,
root_impl::RootImpl::TooOld => set_prop_hint(constants::STATUS_ROOT_IMPL_TOO_OLD)?,
root_impl::RootImpl::Abnormal => set_prop_hint(constants::STATUS_ROOT_IMPL_ABNORMAL)?,
root_impl::RootImpl::Multiple => set_prop_hint(constants::STATUS_ROOT_IMPL_MULTIPLE)?,
_ => {
set_prop_hint(constants::STATUS_LOADED)?;
return Ok(true);
}
}
Ok(false)
}
fn spawn_daemon() -> Result<()> {
let mut lives = 5;
loop {
let daemon32 = Command::new(constants::PATH_ZYGISKD32).arg("daemon").spawn();
let daemon64 = Command::new(constants::PATH_ZYGISKD64).arg("daemon").spawn();
let mut child_ids = vec![];
let (sender, receiver) = mpsc::channel();
let mut spawn = |mut daemon: Child| {
child_ids.push(daemon.id());
let sender = sender.clone();
thread::spawn(move || {
let result = daemon.wait().unwrap();
log::error!("Daemon process {} died: {}", daemon.id(), result);
drop(daemon);
let _ = sender.send(());
});
};
if let Ok(it) = daemon32 { spawn(it) }
if let Ok(it) = daemon64 { spawn(it) }
let mut binder = loop {
if receiver.try_recv().is_ok() {
bail!("Daemon died before system server ready");
}
match binder::get_service("activity") {
Some(binder) => break binder,
None => {
log::trace!("System server not ready, wait for 1s...");
thread::sleep(Duration::from_secs(1));
}
};
};
log::info!("System server ready, restore native bridge");
utils::set_property(constants::PROP_NATIVE_BRIDGE, &utils::get_native_bridge())?;
loop {
if receiver.try_recv().is_ok() || binder.ping_binder().is_err() { break; }
thread::sleep(Duration::from_secs(1))
}
for child in child_ids {
let _ = kill(Pid::from_raw(child as i32), Signal::SIGKILL);
}
lives -= 1;
if lives == 0 {
bail!("Too many crashes, abort");
}
log::error!("Restarting zygote...");
utils::set_property(constants::PROP_NATIVE_BRIDGE, constants::ZYGISK_LOADER)?;
utils::set_property(constants::PROP_CTL_RESTART, "zygote")?;
}
}

713
zygiskd/src/zygiskd.c Normal file
View File

@@ -0,0 +1,713 @@
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/sendfile.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <linux/limits.h>
#include <sys/syscall.h>
#include <linux/memfd.h>
#include <pthread.h>
#include "root_impl/common.h"
#include "constants.h"
#include "utils.h"
struct Module {
char *name;
int lib_fd;
int companion;
};
struct Context {
struct Module *modules;
int len;
};
enum Architecture {
ARM32,
ARM64,
X86,
X86_64,
};
#define PATH_MODULES_DIR "/data/adb/modules"
#define TMP_PATH "/data/adb/rezygisk"
#define CONTROLLER_SOCKET TMP_PATH "/init_monitor"
#define PATH_CP_NAME TMP_PATH "/" lp_select("cp32.sock", "cp64.sock")
#define ZYGISKD_FILE PATH_MODULES_DIR "/zygisksu/bin/zygiskd" lp_select("32", "64")
#define ZYGISKD_PATH "/data/adb/modules/zygisksu/bin/zygiskd" lp_select("32", "64")
static enum Architecture get_arch(void) {
char system_arch[32];
get_property("ro.product.cpu.abi", system_arch);
if (strstr(system_arch, "arm") != NULL) return lp_select(ARM32, ARM64);
if (strstr(system_arch, "x86") != NULL) return lp_select(X86, X86_64);
LOGE("Unsupported system architecture: %s\n", system_arch);
exit(1);
}
int create_library_fd(const char *restrict so_path) {
int so_fd = open(so_path, O_RDONLY);
if (so_fd == -1) {
LOGE("Failed opening so file: %s\n", strerror(errno));
return -1;
}
off_t so_size = lseek(so_fd, 0, SEEK_END);
if (so_size == -1) {
LOGE("Failed getting so file size: %s\n", strerror(errno));
close(so_fd);
return -1;
}
if (lseek(so_fd, 0, SEEK_SET) == -1) {
LOGE("Failed seeking so file: %s\n", strerror(errno));
close(so_fd);
return -1;
}
/* INFO: This is required as older implementations of glibc may not
have the memfd_create function call, causing a crash. */
int memfd = syscall(SYS_memfd_create, "jit-cache-zygisk", MFD_ALLOW_SEALING);
if (memfd == -1) {
LOGE("Failed creating memfd: %s\n", strerror(errno));
return -1;
}
if (sendfile(memfd, so_fd, NULL, so_size) == -1) {
LOGE("Failed copying so file to memfd: %s\n", strerror(errno));
close(so_fd);
close(memfd);
return -1;
}
close(so_fd);
if (fcntl(memfd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL) == -1) {
LOGE("Failed sealing memfd: %s\n", strerror(errno));
close(memfd);
return -1;
}
return memfd;
}
/* WARNING: Dynamic memory based */
static void load_modules(enum Architecture arch, struct Context *restrict context) {
context->len = 0;
context->modules = NULL;
DIR *dir = opendir(PATH_MODULES_DIR);
if (dir == NULL) {
LOGE("Failed opening modules directory: %s.", PATH_MODULES_DIR);
return;
}
char arch_str[32];
switch (arch) {
case ARM64: { strcpy(arch_str, "arm64-v8a"); break; }
case X86_64: { strcpy(arch_str, "x86_64"); break; }
case ARM32: { strcpy(arch_str, "armeabi-v7a"); break; }
case X86: { strcpy(arch_str, "x86"); break; }
}
LOGI("Loading modules for architecture: %s\n", arch_str);
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type != DT_DIR) continue; /* INFO: Only directories */
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0 || strcmp(entry->d_name, "zygisksu") == 0) continue;
char *name = entry->d_name;
char so_path[PATH_MAX];
snprintf(so_path, PATH_MAX, "/data/adb/modules/%s/zygisk/%s.so", name, arch_str);
struct stat st;
if (stat(so_path, &st) == -1) {
errno = 0;
continue;
}
char disabled[PATH_MAX];
snprintf(disabled, PATH_MAX, "/data/adb/modules/%s/disable", name);
if (stat(disabled, &st) == -1) {
if (errno != ENOENT) {
LOGE("Failed checking if module `%s` is disabled: %s\n", name, strerror(errno));
errno = 0;
continue;
}
errno = 0;
} else continue;
int lib_fd = create_library_fd(so_path);
if (lib_fd == -1) {
LOGE("Failed loading module `%s`\n", name);
continue;
}
context->modules = realloc(context->modules, ((context->len + 1) * sizeof(struct Module)));
if (context->modules == NULL) {
LOGE("Failed reallocating memory for modules.\n");
return;
}
context->modules[context->len].name = strdup(name);
context->modules[context->len].lib_fd = lib_fd;
context->modules[context->len].companion = -1;
context->len++;
}
}
static void free_modules(struct Context *restrict context) {
for (int i = 0; i < context->len; i++) {
free(context->modules[i].name);
if (context->modules[i].companion != -1) close(context->modules[i].companion);
}
}
static int create_daemon_socket(void) {
set_socket_create_context("u:r:zygote:s0");
return unix_listener_from_path(PATH_CP_NAME);
}
static int spawn_companion(char *restrict argv[], char *restrict name, int lib_fd) {
int sockets[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
LOGE("Failed creating socket pair.\n");
return -1;
}
int daemon_fd = sockets[0];
int companion_fd = sockets[1];
pid_t pid = fork();
if (pid < 0) {
LOGE("Failed forking companion: %s\n", strerror(errno));
close(companion_fd);
close(daemon_fd);
exit(1);
} else if (pid > 0) {
close(companion_fd);
int status = 0;
waitpid(pid, &status, 0);
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
if (write_string(daemon_fd, name) == -1) {
LOGE("Failed writing module name.\n");
close(daemon_fd);
return -1;
}
if (write_fd(daemon_fd, lib_fd) == -1) {
LOGE("Failed sending library fd.\n");
close(daemon_fd);
return -1;
}
uint8_t response = 0;
ssize_t ret = read_uint8_t(daemon_fd, &response);
if (ret <= 0) {
LOGE("Failed reading companion response.\n");
close(daemon_fd);
return -1;
}
switch (response) {
/* INFO: Even without any entry, we should still just deal with it */
case 0: { return -2; }
case 1: { return daemon_fd; }
/* TODO: Should we be closing daemon socket here? (in non-0-and-1 case) */
default: {
return -1;
}
}
/* TODO: Should we be closing daemon socket here? */
} else {
LOGE("Exited with status %d\n", status);
return -1;
}
/* INFO: if pid == 0: */
} else {
/* INFO: There is no case where this will fail with a valid fd. */
/* INFO: Remove FD_CLOEXEC flag to avoid closing upon exec */
if (fcntl(companion_fd, F_SETFD, 0) == -1) {
LOGE("Failed removing FD_CLOEXEC flag: %s\n", strerror(errno));
close(companion_fd);
close(daemon_fd);
exit(1);
}
}
char *process = argv[0];
char nice_name[256];
char *last = strrchr(process, '/');
if (last == NULL) {
snprintf(nice_name, sizeof(nice_name), "%s", process);
} else {
snprintf(nice_name, sizeof(nice_name), "%s", last + 1);
}
char process_name[256];
snprintf(process_name, sizeof(process_name), "%s-%s", nice_name, name);
char companion_fd_str[32];
snprintf(companion_fd_str, sizeof(companion_fd_str), "%d", companion_fd);
char *eargv[] = { process_name, "companion", companion_fd_str, NULL };
if (non_blocking_execv(ZYGISKD_PATH, eargv) == -1) {
LOGE("Failed executing companion: %s\n", strerror(errno));
close(companion_fd);
exit(1);
}
exit(0);
}
struct __attribute__((__packed__)) MsgHead {
unsigned int cmd;
int length;
char data[0];
};
/* WARNING: Dynamic memory based */
void zygiskd_start(char *restrict argv[]) {
/* INFO: When implementation is None or Multiple, it won't set the values
for the context, causing it to have garbage values. In response
to that, "= { 0 }" is used to ensure that the values are clean. */
struct Context context = { 0 };
struct root_impl impl;
get_impl(&impl);
if (impl.impl == None || impl.impl == Multiple) {
struct MsgHead *msg = NULL;
if (impl.impl == None) {
msg = malloc(sizeof(struct MsgHead) + strlen("Unsupported environment: Unknown root implementation") + 1);
} else {
msg = malloc(sizeof(struct MsgHead) + strlen("Unsupported environment: Multiple root implementations found") + 1);
}
if (msg == NULL) {
LOGE("Failed allocating memory for message.\n");
return;
}
msg->cmd = DAEMON_SET_ERROR_INFO;
if (impl.impl == None) {
msg->length = sprintf(msg->data, "Unsupported environment: Unknown root implementation");
} else {
msg->length = sprintf(msg->data, "Unsupported environment: Multiple root implementations found");
}
unix_datagram_sendto(CONTROLLER_SOCKET, (void *)msg, sizeof(struct MsgHead) + msg->length);
free(msg);
} else {
enum Architecture arch = get_arch();
load_modules(arch, &context);
char *module_list = NULL;
size_t module_list_len = 0;
if (context.len == 0) {
module_list = strdup("None");
module_list_len = strlen("None");
} else {
for (int i = 0; i < context.len; i++) {
if (i != context.len - 1) {
module_list = realloc(module_list, module_list_len + strlen(context.modules[i].name) + strlen(", ") + 1);
if (module_list == NULL) {
LOGE("Failed reallocating memory for module list.\n");
return;
}
strcpy(module_list + module_list_len, context.modules[i].name);
module_list_len += strlen(context.modules[i].name);
strcpy(module_list + module_list_len, ", ");
module_list_len += strlen(", ");
} else {
module_list = realloc(module_list, module_list_len + strlen(context.modules[i].name) + 1);
if (module_list == NULL) {
LOGE("Failed reallocating memory for module list.\n");
return;
}
strcpy(module_list + module_list_len, context.modules[i].name);
module_list_len += strlen(context.modules[i].name);
}
}
}
char impl_name[LONGEST_ROOT_IMPL_NAME];
stringify_root_impl_name(impl, impl_name);
size_t msg_length = strlen("Root: , Modules: ") + strlen(impl_name) + module_list_len + 1;
struct MsgHead *msg = malloc(sizeof(struct MsgHead) + msg_length);
msg->length = snprintf(msg->data, msg_length, "Root: %s, Modules: %s", impl_name, module_list);
msg->cmd = DAEMON_SET_INFO;
unix_datagram_sendto(CONTROLLER_SOCKET, (void *)msg, sizeof(struct MsgHead) + msg->length);
free(msg);
free(module_list);
}
int socket_fd = create_daemon_socket();
if (socket_fd == -1) {
LOGE("Failed creating daemon socket\n");
return;
}
while (1) {
int client_fd = accept(socket_fd, NULL, NULL);
if (client_fd == -1) {
LOGE("accept: %s\n", strerror(errno));
return;
}
uint8_t action8 = 0;
ssize_t len = read_uint8_t(client_fd, &action8);
if (len == -1) {
LOGE("read: %s\n", strerror(errno));
return;
} else if (len == 0) {
LOGI("Client disconnected\n");
return;
}
enum DaemonSocketAction action = (enum DaemonSocketAction)action8;
switch (action) {
case PingHeartbeat: {
enum DaemonSocketAction msgr = ZYGOTE_INJECTED;
unix_datagram_sendto(CONTROLLER_SOCKET, &msgr, sizeof(enum DaemonSocketAction));
break;
}
case ZygoteRestart: {
for (int i = 0; i < context.len; i++) {
if (context.modules[i].companion != -1) {
close(context.modules[i].companion);
context.modules[i].companion = -1;
}
}
break;
}
case SystemServerStarted: {
enum DaemonSocketAction msgr = SYSTEM_SERVER_STARTED;
unix_datagram_sendto(CONTROLLER_SOCKET, &msgr, sizeof(enum DaemonSocketAction));
if (impl.impl == None || impl.impl == Multiple) {
LOGI("Unsupported environment detected. Exiting.\n");
close(client_fd);
close(socket_fd);
free_modules(&context);
exit(1);
}
break;
}
case RequestLogcatFd: {
uint8_t level = 0;
ssize_t ret = read_uint8_t(client_fd, &level);
ASSURE_SIZE_READ_BREAK("RequestLogcatFd", "level", ret, sizeof(level));
char tag[128 + 1];
ret = read_string(client_fd, tag, sizeof(tag) - 1);
if (ret == -1) {
LOGE("Failed reading logcat tag.\n");
close(client_fd);
break;
}
tag[ret] = '\0';
/* INFO: Non-NULL terminated */
char message[1024];
ret = read_string(client_fd, message, sizeof(message));
if (ret == -1) {
LOGE("Failed reading logcat message.\n");
close(client_fd);
break;
}
__android_log_print(level, tag, "%.*s", (int)ret, message);
break;
}
case GetProcessFlags: {
uint32_t uid = 0;
ssize_t ret = read_uint32_t(client_fd, &uid);
ASSURE_SIZE_READ_BREAK("GetProcessFlags", "uid", ret, sizeof(uid));
uint32_t flags = 0;
if (uid_is_manager(uid)) {
flags |= PROCESS_IS_MANAGER;
} else {
if (uid_granted_root(uid)) {
flags |= PROCESS_GRANTED_ROOT;
}
if (uid_should_umount(uid)) {
flags |= PROCESS_ON_DENYLIST;
}
}
switch (impl.impl) {
case None: { break; }
case Multiple: { break; }
case KernelSU: {
flags |= PROCESS_ROOT_IS_KSU;
break;
}
case APatch: {
flags |= PROCESS_ROOT_IS_APATCH;
break;
}
case Magisk: {
flags |= PROCESS_ROOT_IS_MAGISK;
break;
}
}
ret = write_int(client_fd, flags);
ASSURE_SIZE_WRITE_BREAK("GetProcessFlags", "flags", ret, sizeof(flags));
break;
}
case GetInfo: {
uint32_t flags = 0;
switch (impl.impl) {
case None: { break; }
case Multiple: { break; }
case KernelSU: {
flags |= PROCESS_ROOT_IS_KSU;
break;
}
case APatch: {
flags |= PROCESS_ROOT_IS_APATCH;
break;
}
case Magisk: {
flags |= PROCESS_ROOT_IS_MAGISK;
break;
}
}
ssize_t ret = write_size_t(client_fd, flags);
ASSURE_SIZE_WRITE_BREAK("GetInfo", "flags", ret, sizeof(flags));
uint32_t pid = getpid();
ret = write_uint32_t(client_fd, pid);
ASSURE_SIZE_WRITE_BREAK("GetInfo", "pid", ret, sizeof(pid));
size_t modules_len = context.len;
ret = write_size_t(client_fd, modules_len);
ASSURE_SIZE_WRITE_BREAK("GetInfo", "modules_len", ret, sizeof(modules_len));
for (size_t i = 0; i < modules_len; i++) {
ret = write_string(client_fd, context.modules[i].name);
if (ret == -1) {
LOGE("Failed writing module name.\n");
break;
}
}
break;
}
case ReadModules: {
size_t clen = context.len;
ssize_t ret = write_size_t(client_fd, clen);
ASSURE_SIZE_WRITE_BREAK("ReadModules", "len", ret, sizeof(clen));
for (size_t i = 0; i < clen; i++) {
if (write_string(client_fd, context.modules[i].name) == -1) {
LOGE("Failed writing module name.\n");
break;
}
if (write_fd(client_fd, context.modules[i].lib_fd) == -1) {
LOGE("Failed writing module fd.\n");
break;
}
}
break;
}
case RequestCompanionSocket: {
size_t index = 0;
ssize_t ret = read_size_t(client_fd, &index);
ASSURE_SIZE_READ_BREAK("RequestCompanionSocket", "index", ret, sizeof(index));
struct Module *module = &context.modules[index];
if (module->companion != -1) {
LOGI(" - Polling companion for module \"%s\"\n", module->name);
if (!check_unix_socket(module->companion, false)) {
LOGE(" - Poll companion for module \"%s\" crashed\n", module->name);
close(module->companion);
module->companion = -1;
}
}
if (module->companion == -1) {
module->companion = spawn_companion(argv, module->name, module->lib_fd);
if (module->companion > 0) {
LOGI(" - Spawned companion for \"%s\"\n", module->name);
} else {
if (module->companion == -2) {
LOGE(" - No companion spawned for \"%s\" because it has no entry.\n", module->name);
} else {
LOGE(" - Failed to spawn companion for \"%s\": %s\n", module->name, strerror(errno));
}
}
}
/*
INFO: Companion already exists or was created. In any way,
it should be in the while loop to receive fds now,
so just sending the file descriptor of the client is
safe.
*/
if (module->companion != -1) {
LOGI(" - Sending companion fd socket of module \"%s\"\n", module->name);
if (write_fd(module->companion, client_fd) == -1) {
LOGE(" - Failed to send companion fd socket of module \"%s\"\n", module->name);
ret = write_uint8_t(client_fd, 0);
ASSURE_SIZE_WRITE_BREAK("RequestCompanionSocket", "response", ret, sizeof(int));
close(module->companion);
module->companion = -1;
/* INFO: RequestCompanionSocket by defailt doesn't close the client_fd */
close(client_fd);
}
} else {
ret = write_uint8_t(client_fd, 0);
ASSURE_SIZE_WRITE_BREAK("RequestCompanionSocket", "response", ret, sizeof(int));
/* INFO: RequestCompanionSocket by defailt doesn't close the client_fd */
close(client_fd);
}
break;
}
case GetModuleDir: {
size_t index = 0;
ssize_t ret = read_size_t(client_fd, &index);
ASSURE_SIZE_READ_BREAK("GetModuleDir", "index", ret, sizeof(index));
char module_dir[PATH_MAX];
snprintf(module_dir, PATH_MAX, "%s/%s", PATH_MODULES_DIR, context.modules[index].name);
int fd = open(module_dir, O_RDONLY);
if (fd == -1) {
LOGE("Failed opening module directory \"%s\": %s\n", module_dir, strerror(errno));
break;
}
struct stat st;
if (fstat(fd, &st) == -1) {
LOGE("Failed getting module directory \"%s\" stats: %s\n", module_dir, strerror(errno));
close(fd);
break;
}
if (write_fd(client_fd, fd) == -1) {
LOGE("Failed sending module directory \"%s\" fd: %s\n", module_dir, strerror(errno));
close(fd);
break;
}
break;
}
}
if (action != RequestCompanionSocket && action != RequestLogcatFd) close(client_fd);
continue;
}
close(socket_fd);
free_modules(&context);
}

6
zygiskd/src/zygiskd.h Normal file
View File

@@ -0,0 +1,6 @@
#ifndef ZYGISKD_H
#define ZYGISKD_H
void zygiskd_start(char *restrict argv[]);
#endif /* ZYGISKD_H */

View File

@@ -1,240 +0,0 @@
use crate::constants::DaemonSocketAction;
use crate::utils::UnixStreamExt;
use crate::{constants, lp_select, magic, root_impl, utils};
use anyhow::{bail, Result};
use memfd::Memfd;
use nix::{
fcntl::{fcntl, FcntlArg, FdFlag},
libc::self,
};
use passfd::FdPassingExt;
use std::sync::{Arc, Mutex};
use std::thread;
use std::fs;
use std::os::unix::{
net::{UnixListener, UnixStream},
prelude::AsRawFd,
};
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::Command;
struct Module {
name: String,
memfd: Memfd,
companion: Mutex<Option<UnixStream>>,
}
struct Context {
native_bridge: String,
modules: Vec<Module>,
}
pub fn entry() -> Result<()> {
unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) };
let arch = get_arch()?;
log::debug!("Daemon architecture: {arch}");
log::info!("Load modules");
let modules = load_modules(arch)?;
let context = Context {
native_bridge: utils::get_native_bridge(),
modules,
};
let context = Arc::new(context);
log::info!("Create socket");
let listener = create_daemon_socket()?;
log::info!("Handle zygote connections");
for stream in listener.incoming() {
let stream = stream?;
let context = Arc::clone(&context);
thread::spawn(move || {
if let Err(e) = handle_daemon_action(stream, &context) {
log::warn!("Error handling daemon action: {}\n{}", e, e.backtrace());
}
});
}
Ok(())
}
fn get_arch() -> Result<&'static str> {
let system_arch = utils::get_property("ro.product.cpu.abi")?;
if system_arch.contains("arm") {
return Ok(lp_select!("armeabi-v7a", "arm64-v8a"));
}
if system_arch.contains("x86") {
return Ok(lp_select!("x86", "x86_64"));
}
bail!("Unsupported system architecture: {}", system_arch);
}
fn load_modules(arch: &str) -> Result<Vec<Module>> {
let mut modules = Vec::new();
let dir = match fs::read_dir(constants::PATH_MODULES_DIR) {
Ok(dir) => dir,
Err(e) => {
log::warn!("Failed reading modules directory: {}", e);
return Ok(modules);
}
};
for entry_result in dir.into_iter() {
let entry = entry_result?;
let name = entry.file_name().into_string().unwrap();
let so_path = entry.path().join(format!("zygisk/{arch}.so"));
let disabled = entry.path().join("disable");
if !so_path.exists() || disabled.exists() {
continue;
}
log::info!(" Loading module `{name}`...");
let memfd = match create_memfd(&so_path) {
Ok(memfd) => memfd,
Err(e) => {
log::warn!(" Failed to create memfd for `{name}`: {e}");
continue;
}
};
let companion = match spawn_companion(&name, &memfd) {
Ok(companion) => companion,
Err(e) => {
log::warn!(" Failed to spawn companion for `{name}`: {e}");
continue;
}
};
let companion = Mutex::new(companion);
let module = Module { name, memfd, companion };
modules.push(module);
}
Ok(modules)
}
fn create_memfd(so_path: &PathBuf) -> Result<Memfd> {
let opts = memfd::MemfdOptions::default().allow_sealing(true);
let memfd = opts.create("jit-cache")?;
let file = fs::File::open(so_path)?;
let mut reader = std::io::BufReader::new(file);
let mut writer = memfd.as_file();
std::io::copy(&mut reader, &mut writer)?;
let mut seals = memfd::SealsHashSet::new();
seals.insert(memfd::FileSeal::SealShrink);
seals.insert(memfd::FileSeal::SealGrow);
seals.insert(memfd::FileSeal::SealWrite);
seals.insert(memfd::FileSeal::SealSeal);
memfd.add_seals(&seals)?;
Ok(memfd)
}
fn create_daemon_socket() -> Result<UnixListener> {
utils::set_socket_create_context("u:r:zygote:s0")?;
let prefix = lp_select!("zygiskd32", "zygiskd64");
let name = format!("{}{}", prefix, magic::MAGIC.as_str());
let listener = utils::abstract_namespace_socket(&name)?;
log::debug!("Daemon socket: {name}");
Ok(listener)
}
fn spawn_companion(name: &str, memfd: &Memfd) -> Result<Option<UnixStream>> {
let (mut daemon, companion) = UnixStream::pair()?;
// Remove FD_CLOEXEC flag
fcntl(companion.as_raw_fd(), FcntlArg::F_SETFD(FdFlag::empty()))?;
let process = std::env::args().next().unwrap();
let nice_name = process.split('/').last().unwrap();
Command::new(&process)
.arg0(format!("{}-{}", nice_name, name))
.arg("companion")
.arg(format!("{}", companion.as_raw_fd()))
.spawn()?;
drop(companion);
daemon.write_string(name)?;
daemon.send_fd(memfd.as_raw_fd())?;
match daemon.read_u8()? {
0 => Ok(None),
1 => Ok(Some(daemon)),
_ => bail!("Invalid companion response"),
}
}
fn handle_daemon_action(mut stream: UnixStream, context: &Context) -> Result<()> {
let action = stream.read_u8()?;
let action = DaemonSocketAction::try_from(action)?;
log::trace!("New daemon action {:?}", action);
match action {
DaemonSocketAction::PingHeartbeat => {
// Do nothing
}
DaemonSocketAction::RequestLogcatFd => {
loop {
let level = match stream.read_u8() {
Ok(level) => level,
Err(_) => break,
};
let tag = stream.read_string()?;
let message = stream.read_string()?;
utils::log_raw(level as i32, &tag, &message)?;
}
}
DaemonSocketAction::ReadNativeBridge => {
stream.write_string(&context.native_bridge)?;
}
DaemonSocketAction::GetProcessFlags => {
let uid = stream.read_u32()? as i32;
let mut flags = 0u32;
if root_impl::uid_on_allowlist(uid) {
flags |= constants::PROCESS_GRANTED_ROOT;
}
if root_impl::uid_on_denylist(uid) {
flags |= constants::PROCESS_ON_DENYLIST;
}
match root_impl::get_impl() {
root_impl::RootImpl::KernelSU => flags |= constants::PROCESS_ROOT_IS_KSU,
root_impl::RootImpl::Magisk => flags |= constants::PROCESS_ROOT_IS_MAGISK,
_ => unreachable!(),
}
// TODO: PROCESS_IS_SYSUI?
stream.write_u32(flags)?;
}
DaemonSocketAction::ReadModules => {
stream.write_usize(context.modules.len())?;
for module in context.modules.iter() {
stream.write_string(&module.name)?;
stream.send_fd(module.memfd.as_raw_fd())?;
}
}
DaemonSocketAction::RequestCompanionSocket => {
let index = stream.read_usize()?;
let module = &context.modules[index];
let mut companion = module.companion.lock().unwrap();
match companion.as_ref() {
Some(sock) => {
if let Err(_) = sock.send_fd(stream.as_raw_fd()) {
log::error!("Companion of module `{}` crashed", module.name);
companion.take();
stream.write_u8(0)?;
}
// Ok: Send by companion
}
None => {
stream.write_u8(0)?;
}
}
}
DaemonSocketAction::GetModuleDir => {
let index = stream.read_usize()?;
let module = &context.modules[index];
let dir = format!("{}/{}", constants::PATH_MODULES_DIR, module.name);
let dir = fs::File::open(dir)?;
stream.send_fd(dir.as_raw_fd())?;
}
}
Ok(())
}