You've already forked ReZygisk
mirror of
https://github.com/PerformanC/ReZygisk.git
synced 2025-09-06 06:37:01 +00:00
fix: merge conflicts
This commit fixes merge conflicts while merging to main.
This commit is contained in:
20
.github/workflows/ci.yml
vendored
20
.github/workflows/ci.yml
vendored
@@ -6,16 +6,11 @@ on:
|
||||
|
||||
pull_request:
|
||||
merge_group:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CCACHE_COMPILERCHECK: "%compiler% -dumpmachine; %compiler% -dumpversion"
|
||||
CCACHE_NOHASHDIR: "true"
|
||||
CCACHE_HARDLINK: "true"
|
||||
CCACHE_BASEDIR: "${{ github.workspace }}"
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -30,24 +25,13 @@ jobs:
|
||||
java-version: "17"
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v3
|
||||
with:
|
||||
gradle-home-cache-cleanup: true
|
||||
|
||||
- name: Set up ccache
|
||||
uses: hendrikmuhs/ccache-action@v1.2
|
||||
with:
|
||||
max-size: 2G
|
||||
key: ${{ runner.os }}
|
||||
restore-keys: ${{ runner.os }}
|
||||
save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
uses: gradle/actions/setup-gradle@v4.2.1
|
||||
|
||||
- name: Build with Gradle
|
||||
run: |
|
||||
echo 'org.gradle.parallel=true' >> gradle.properties
|
||||
echo 'org.gradle.vfs.watch=true' >> gradle.properties
|
||||
echo 'org.gradle.jvmargs=-Xmx2048m' >> gradle.properties
|
||||
echo 'android.native.buildOutput=verbose' >> gradle.properties
|
||||
sed -i 's/org.gradle.unsafe.configuration-cache=true//g' gradle.properties
|
||||
./gradlew zipRelease
|
||||
./gradlew zipDebug
|
||||
|
||||
2
.gitmodules
vendored
2
.gitmodules
vendored
@@ -1,3 +1,3 @@
|
||||
[submodule "loader/src/external/lsplt"]
|
||||
path = loader/src/external/lsplt
|
||||
url = https://github.com/LSPosed/lsplt
|
||||
url = https://github.com/JingMatrix/LSPlt
|
||||
|
||||
23
README.md
23
README.md
@@ -1,6 +1,6 @@
|
||||
# ReZygisk
|
||||
|
||||
[中文](https://github.com/PerformanC/ReZygisk/blob/main/README_CN.md)
|
||||
[简体中文](/READMEs/README_zh-CN.md)|[繁體中文](/READMEs/README_zh-TW.md)|[Bahasa Indonesia](/READMEs/README_id-ID.md)|[Tiếng Việt](/READMEs/README_vi-VN.md)|[Português Brasileiro](/READMEs/README_pt-BR.md)|[Türkçe](/READMEs/README_tr-TR.md)|[French](/READMEs/README_fr-FR.md)
|
||||
|
||||
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).
|
||||
|
||||
@@ -25,27 +25,8 @@ The Zygisk Next developers are famous and trusted in the Android community, howe
|
||||
|
||||
| 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 |
|
||||
@@ -62,7 +43,7 @@ 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.
|
||||
As of now, we don't have integration with another platform for translations but you may contribute to the [add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui) branch. Please don't forget to include your GitHub profile in [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-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:
|
||||
|
||||
61
READMEs/README_fr-FR.md
Normal file
61
READMEs/README_fr-FR.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# ReZygisk
|
||||
|
||||
[English](../README.md)
|
||||
|
||||
ReZygisk est un fork de Zygisk Next, une implémentation autonome de Zygisk. Il vise à fournir un support de l'API Zygisk pour KernelSU, Magisk (en plus de l'intégration existante), et pour Apatch (encore en cours de développement).
|
||||
|
||||
L'objectif est de moderniser et de réécrire la base du code, initialement en C, vers du C++ et du Rust. Cela permettra une meilleure efficacité et une implémentation plus rapide de l'API Zygisk, le tout sous une licence plus permissive.
|
||||
|
||||
> [!NOTE]
|
||||
> Ce module/fork est en cours de développement ; n'utilisez que les fichiers .zip provenant des 'Releases'.
|
||||
>
|
||||
>Bien que vous puissiez installer les fichiers .zip provenant de la page [Actions](https://github.com/PerformanC/ReZygisk/actions), cela vous regarde et peut faire entrer votre téléphone en boucle de redémarrage (bootloop).
|
||||
## Pourquoi ?
|
||||
|
||||
La dernière release de Zygisk Next n'est pas open source, le code est donc accessible uniquement à ses développeurs. Non seulement cela limite notre capacité à contribuer au projet, mais cela rend également impossible la vérification du code, ce qui constitue une préoccupation majeure en matière de sécurité. Zygisk Next est un module fonctionnant avec les permissions administrateur (root) et a donc accès à l'entièreté du système.
|
||||
|
||||
Les développeurs de Zygisk Next sont connus et reconnus dans la communauté Android. Toutefois, cela ne signifie pas que du code malveillant ou des vulnérabilités ne se cachent pas dans le code. Nous (PerfomanC) comprenons qu'ils aient des raisons de garder leur code en source fermée, mais nous pensons qu'avoir un code open source est mieux.
|
||||
|
||||
## Avantages
|
||||
|
||||
- FOSS (Pour toujours !)
|
||||
|
||||
## Dépendances
|
||||
|
||||
| Outil | Description |
|
||||
|-----------------|----------------------------------------|
|
||||
| `Android NDK` | Kit de développement natif d'Android |
|
||||
|
||||
### Dépendances C++
|
||||
|
||||
| Dépendance | Description |
|
||||
|------------|-------------------------------|
|
||||
| `lsplt` | Simple PLT Hook pour Android |
|
||||
|
||||
## Utilisation
|
||||
|
||||
Nous sommes actuellement en train de préparer cela. (Pour bientôt)
|
||||
|
||||
## Installation
|
||||
|
||||
Il n'y a actuellement pas de version (releases) stable (Pour bientôt)
|
||||
|
||||
## Traduction
|
||||
|
||||
À ce jour, nous n'avons pas d'intégration avec d'autres plateformes pour traduire, mais vous pouvez contribuer à la branche [add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui). Merci de ne pas oublier d'inclure votre profil GitHub dans le fichier [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-webui/TRANSLATOR.md) afin que les autres puissent voir votre contribution.
|
||||
|
||||
## Support
|
||||
|
||||
Pour toutes questions relatives a ReZygisk ou d'autres projets de PerformanC, n'hésitez pas à nous rejoindre via les différents moyens disponibles:
|
||||
|
||||
- Notre Discord: [PerformanC](https://discord.gg/uPveNfTuCJ)
|
||||
- Le Telegram relatif a ReZygisk: [@rezygiskchat](https://t.me/rezygiskchat)
|
||||
- Notre Telegram: [@performancorg](https://t.me/performancorg)
|
||||
|
||||
## Contribution
|
||||
|
||||
Il est obligatoire de lire les instructions de PerformanC dans les [Contribution Guidelines](https://github.com/PerformanC/contributing) afin de contribuer au projet ReZygisk. Suivez la politique de sécurité, le code de conduite et les standards relatif à la syntaxe.
|
||||
|
||||
## License
|
||||
|
||||
ReZygisk est majoritairement sous la licence GPL pour la partie de Dr-TSNG, mais sous licence AGPL 3.0 pour la partie réécrite du code par PerformanC. Vous pouvez trouver plus d'information sur le lien suivant : [Open Source Initiative](https://opensource.org/licenses/AGPL-3.0).
|
||||
63
READMEs/README_id-ID.md
Normal file
63
READMEs/README_id-ID.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# ReZygisk
|
||||
|
||||
[English](https://github.com/PerformanC/ReZygisk)
|
||||
|
||||
ReZygisk adalah turunan dari Zygisk Next, sebuah implementasi mandiri Zygisk, yang mendukung API Zygisk untuk KernelSU, Magisk (selain versi bawaan), dan APatch (dalam tahap pengembangan).
|
||||
|
||||
Proyek ini bertujuan untuk memodernisasi dan menulis ulang basis kode ke dalam bahasa pemorgraman C (dari C++ dan Rust), memungkinkan implementasi API Zygisk yang lebih efisien dan cepat dengan lisensi yang lebih permisif.
|
||||
|
||||
> [!NOTE]
|
||||
> [CATATAN]
|
||||
>
|
||||
> Modul/turunan ini sedang dalam tahap pengembangan. gunakan hanya file .zip dari halaman Rilis.
|
||||
>
|
||||
> Anda dapat menginstal file .zip dari halaman [Actions](https://github.com/PerformanC/ReZygisk/actions), namun instalan ini sepenuhnya menjadi tanggung jawab Anda karena perangkat dapat mengalami bootloop.
|
||||
|
||||
## Mengapa?
|
||||
|
||||
Rilisan terbaru dari Zygisk Next tidak bersifat open-source, dengan kode yang sepenuhnya dikendalikan oleh developernya. Hal ini tidak hanya membatasi kemampuan kami untuk berkontribusi pada proyek ini, tetapi juga membuat kode tidak dapat diaudit, yang menjadi masalah utama keamanan karena Zygisk Next adalah modul yang berjalan dengan hak superuser (root), yang memiliki akses ke seluruh sistem.
|
||||
|
||||
Meskipun developer Zygisk Next terkenal dan dipercaya dalam komunitas Android, hal ini tidak menjamin bahwa kode tersebut bebas dari bahaya atau kerentanan. Kami (PerformanC) memahami alasan mereka untuk menjaga kode tetap tertutup, tetapi kami memiliki pandangan yang berbeda.
|
||||
|
||||
## Kelebihan
|
||||
|
||||
- FOSS (Free and Open Source Software) Selamanya.
|
||||
|
||||
## Komponen Pendukung
|
||||
|
||||
| Alat | Deskripsi |
|
||||
|-----------------|------------------------------------------|
|
||||
| `Android NDK` | Native Development Kit untuk Android |
|
||||
|
||||
### Komponen Pendukung C++
|
||||
|
||||
| Komponen | Deskripsi |
|
||||
|------------|---------------------------------|
|
||||
| `lsplt` | Simple PLT Hook untuk Android |
|
||||
|
||||
## Penggunaan
|
||||
|
||||
Kami saat ini sedang dalam tahap pengembangan. (Segera Hadir)
|
||||
|
||||
## Instalasi
|
||||
|
||||
Saat ini belum tersedia rilisan yang stabil. (Segera Hadir)
|
||||
|
||||
## Terjemahan
|
||||
|
||||
Saat ini, kami belum terintegrasi dengan platform lain untuk penerjemahan, tetapi Anda dapat berkontribusi pada cabang [add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui). Jangan lupa untuk menyertakan profil GitHub Anda di [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-webui/TRANSLATOR.md) agar orang lain dapat melihat kontribusi Anda.
|
||||
|
||||
## Dukungan
|
||||
Untuk pertanyaan terkait ReZygisk atau proyek PerformanC lainnya, silakan bergabung ke salah satu saluran berikut:
|
||||
|
||||
- Saluran Discord: [PerformanC](https://discord.gg/uPveNfTuCJ)
|
||||
- Saluran Telegram ReZygisk: [@rezygiskchat](https://t.me/rezygiskchat)
|
||||
- Saluran Telegram PerformanC: [@performancorg](https://t.me/performancorg)
|
||||
|
||||
## Kontribusi
|
||||
|
||||
Wajib mengikuti [Pedoman Kontribusi](https://github.com/PerformanC/contributing) PerformanC untuk berkontribusi pada ReZygisk. Sesuai dengan Kebijakan Keamanan, Kode Etik, dan standar struktur dan format yang berlaku.
|
||||
|
||||
## Lisensi
|
||||
|
||||
ReZygisk sebagian besar berlisensi di bawah GPL, oleh Dr-TSNG, tetapi juga AGPL 3.0, oleh The PerformanC Organization, untuk kode yang ditulis ulang. Anda dapat juga membaca lebih lanjut di [Open Source Initiative](https://opensource.org/licenses/AGPL-3.0).
|
||||
73
READMEs/README_ja-JP.md
Normal file
73
READMEs/README_ja-JP.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# ReZygisk
|
||||
|
||||
[English](https://github.com/PerformanC/ReZygisk/blob/main/README.md)|[简体中文](/READMEs/README_zh-CN.md)|[繁體中文](/READMEs/README_zh-TW.md)
|
||||
|
||||
ReZygiskはkernelSU、Magisk、APatchにZygiskのAPIサポートを提供するスタンドアローンZygiskであるZygisk Nextのフォークです。
|
||||
|
||||
ReZygiskは更に高速かつ効率的なZygisk APIとより寛容なライセンスを、コードベースをC(もともとはC++とRustでした)でアップデート/書き直すことで実現することを目標としています。
|
||||
|
||||
> [!NOTE]
|
||||
> このモジュール/フォークはWIP(Work in Progress、すべての作業が進行中であることを意味します): ReleasesタブのZipのみを使用するようにしてください。
|
||||
>
|
||||
> GitHub [Actions](https://github.com/PerformanC/ReZygisk/actions) よりZipをダウンロードして使用することも可能ですが、デバイスがブートループなどの不具合が起きる可能性があります。ユーザー自身の裁量にて使用してください。
|
||||
|
||||
## ReZygiskを使う理由
|
||||
|
||||
Zygisk Nextの最新リリースはクローズドソースであり、コードはプロジェクトの開発者のみアクセスできるものです。これはコミュニティがコードに貢献することを妨げるだけではなく、コード監査をも難しくしています。これはZygisk Nextがルート権限で作動するアプリであるため、セキュリティ上深刻な問題です。
|
||||
|
||||
Zygisk Nextの開発者はAndroid Communityにて有名かつ信用されています。が、これはコード自体が悪意の無いこと/脆弱でないことを証明するものではありません。
|
||||
|
||||
我々(PerformanC)はZygisk Nextの開発者らがコードをクローズドに保つ重要な理由があることは承知していますが、我々はオープンソース/コミュニティドリブンにすることが重要だと考えています。
|
||||
|
||||
## メリット
|
||||
|
||||
- オープンソース、Free to Use、FOSS (永続的)
|
||||
|
||||
## 依存関係
|
||||
|
||||
| ツール | 説明 |
|
||||
|-----------------|----------------------------------------|
|
||||
| `Android NDK` | Androidのネイティブ開発環境キット |
|
||||
|
||||
### C++ 依存関係
|
||||
|
||||
| 依存 | 説明 |
|
||||
|------------|-------------------------------|
|
||||
| `lsplt` | シンプルなAndroidのPLTフック |
|
||||
|
||||
## 使い方
|
||||
|
||||
ただいま調理中です、しばらくお待ち下さい!(できるだけ早くお届けします)
|
||||
|
||||
## インストール
|
||||
|
||||
現状、ステーブルリリースはありません。(できるだけ早くお届けします)
|
||||
|
||||
## 翻訳
|
||||
|
||||
現状では、翻訳を他のプラットフォーム上で展開することはしていません。
|
||||
|
||||
が、[add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui) ブランチにて翻訳作業に参加していただくことができます。
|
||||
|
||||
他の開発者さんたちがあなたの貢献を確認できるように、 [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-webui/TRANSLATOR.md) にあなたのプロフィールを追加することを忘れないでください!
|
||||
|
||||
## サポート
|
||||
For any question related to ReZygisk or other PerformanC projects, feel free to join any of the following channels below:
|
||||
ReZygisk/他のPerformanCのプロジェクトに対する質問がある場合は、以下のどれかに参加してください!
|
||||
|
||||
- Discord チャンネル: [PerformanC](https://discord.gg/uPveNfTuCJ)
|
||||
- ReZygisk Telegram チャンネル: [@rezygiskchat](https://t.me/rezygiskchat)
|
||||
- PerformanC Telegram チャンネル: [@performancorg](https://t.me/performancorg)
|
||||
|
||||
## 貢献
|
||||
|
||||
貢献をしたい場合、PerformanCの[Contribution Guidelines](https://github.com/PerformanC/contributing)に従うことが必要になります。
|
||||
|
||||
セキュリティーポリシー、行動規範、シンタックススタンダードを採用してください。
|
||||
|
||||
## ライセンス
|
||||
|
||||
ReZygiskは基本的にDr-TSNGによるGPLライセンス下にてライセンスされています。
|
||||
|
||||
ただし、書き直しされたコードに関してはPerformanCによるAGPL3.0ライセンスにてライセンスされています。
|
||||
詳細については [Open Source Initiative](https://opensource.org/licenses/AGPL-3.0) を参照してください。
|
||||
62
READMEs/README_pt-BR.md
Normal file
62
READMEs/README_pt-BR.md
Normal file
@@ -0,0 +1,62 @@
|
||||
# ReZygisk
|
||||
|
||||
[English](../README.md)
|
||||
|
||||
ReZygisk é uma fork do Zygisk Next, uma implementação do Zygisk independente, fornecendo a API do Zygisk para o kernelSU, Magisk (além do embutido) e APatch (a ser desenvolvido).
|
||||
|
||||
Ele foca em modernizar e re-escrever o código fonte para C (de C++ e Rust), permitindo uma implementação da API do Zygisk com uma licença mais permissiva.
|
||||
|
||||
> [!NOTE]
|
||||
> Este módulo/fork ainda está em processo de desenvolvimento; apenas use .zip da aba Releases.
|
||||
>
|
||||
> Apesar de você poder instalar um .zip da aba [Actions](https://github.com/PerformanC/ReZygisk/actions), é de sua conta e risco, já que pode acarretar em um bootloop.
|
||||
|
||||
## Por quê?
|
||||
|
||||
Os últimos lançamentos do Zygisk Next não possuem código aberto, reservando-o para os seus desenvolvedores. Isso não só limita nossa capacidade de contribuir com o projeto, mas também impossibilita a auditoria do código, uma preocupação grave de segurança, já que o Zygisk Next é um módulo que roda como superuser (super usuário/root), tendo acesso a todo o sistema.
|
||||
|
||||
Os desenvolvedores do Zygisk Next são famosos e confiados pela comunidade Android, mas isso não significa que o código não seja nem malicioso nem vulnerável. Nós (PerformanC) reconhecemos seus motivos de manterem o código recluso a eles, mas a gente acredita no contrário.
|
||||
|
||||
## Vantagens
|
||||
|
||||
- FOSS (Pra sempre)
|
||||
|
||||
## Dependências
|
||||
|
||||
| Ferramenta | Descrição |
|
||||
|-----------------|--------------------------------------------|
|
||||
| `Android NDK` | Kit de Desenvolvimento Nativo para Android |
|
||||
|
||||
### Dependências C++
|
||||
|
||||
| Dependência | Descrição |
|
||||
|-------------|-------------------------------|
|
||||
| `lsplt` | PLT Hook simples para Android |
|
||||
|
||||
## Forma de uso
|
||||
|
||||
Estamos ainda em processo de desenvolvimento desta aba. (Em breve)
|
||||
|
||||
## Processo de instalação
|
||||
|
||||
Estamos ainda em processo de desenvolvimento desta aba. (Em breve)
|
||||
|
||||
## Tradução
|
||||
|
||||
Até agora, a gente não possui uma plataforma para traduções, mas você pode contribuir para a branch [add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui). Por favor, não esqueça de incluir seu perfil do GitHub no [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-webui/TRANSLATOR.md) para que assim outras pessoas vejam sua contribuição.
|
||||
|
||||
## Suporte
|
||||
|
||||
Para quaisquer problemas no ReZygisk ou qualquer projeto da PerformanC, sinta-se livre para entrar em qualquer canal abaixo:
|
||||
|
||||
- Server do Discord: [PerformanC](https://discord.gg/uPveNfTuCJ)
|
||||
- Canal do Telegram ReZygisk: [@rezygiskchat](https://t.me/rezygiskchat)
|
||||
- Canal do Telegram PerformanC: [@performancorg](https://t.me/performancorg)
|
||||
|
||||
## Contribuição
|
||||
|
||||
É obrigatório seguir as [Regras de Contribuição](https://github.com/PerformanC/contributing) da PerformanC para contribuir ao ReZygisk, seguindo sua Política de Segurança, Código de Conduta, e padronização de sintaxe.
|
||||
|
||||
## Licença
|
||||
|
||||
ReZygisk é majoritamente licenciado em GPL, por Dr-TSNG, mas também em AGPL 3.0, pela A Organização PerformanC (The PerformanC Organization) para código re-escrito. Você pode ler mais em [Open Source Initiative](https://opensource.org/licenses/AGPL-3.0).
|
||||
61
READMEs/README_tr-TR.md
Normal file
61
READMEs/README_tr-TR.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# ReZygisk
|
||||
|
||||
[English](../README.md)
|
||||
|
||||
ReZygisk, Zygisk Next'in bir forkudur ve Zygisk'in bağımsız bir uygulamasıdır. KernelSU, Magisk (yerleşik olanın dışında) ve APatch (Çalışmalar Devam Ediyor) için Zygisk API desteği sağlar.
|
||||
|
||||
Amacı, C++ ve Rust'tan C diline geçerek kod tabanını modernize etmek ve yeniden yazmaktır. Bu, daha verimli ve hızlı bir Zygisk API uygulaması sağlarken daha esnek bir lisans sunar.
|
||||
|
||||
> [!NOT]
|
||||
> Bu modül/fork şu anda geliştirme aşamasındadır (WIP - Work In Progress); yalnızca Release'deki .zip dosyasını kullanın.
|
||||
>
|
||||
> [Actions](https://github.com/PerformanC/ReZygisk/actions) sayfasındaki .zip dosyasını yüklemek tamamen sizin sorumluluğunuzdadır; cihazınız bootloop'a girebilir.
|
||||
|
||||
## Neden?
|
||||
|
||||
Zygisk Next'in son sürümleri açık kaynaklı değildir ve tamamen geliştiricilerine ayrılmıştır. Bu durum, projeye katkıda bulunma yeteneğimizi sınırlamakla kalmaz, aynı zamanda kodun denetlenmesini imkansız hale getirir. Bu, Zygisk Next'in süper kullanıcı (root) ayrıcalıklarıyla çalışması ve tüm sisteme erişimi olması nedeniyle büyük bir güvenlik sorunudur.
|
||||
|
||||
Zygisk Next geliştiricileri, Android topluluğunda tanınmış ve güvenilir kişilerdir, ancak bu, kodun kötü niyetli veya hassas olmadığını garanti etmez. PerformanC olarak, kodu kapalı kaynaklı tutma nedenlerini anlasak da, bunun tersini savunuyoruz.
|
||||
|
||||
## Avantajlar
|
||||
|
||||
- Sonsuza kadar açık kaynak (FOSS)
|
||||
|
||||
## Bağımlılıklar
|
||||
|
||||
| Araç | Açıklama |
|
||||
|------------------|--------------------------------------|
|
||||
| `Android NDK` | Android için Yerel Geliştirme Kiti |
|
||||
|
||||
### C++ Bağımlılıkları
|
||||
|
||||
| Bağımlılık | Açıklama |
|
||||
|------------|---------------------------------|
|
||||
| `lsplt` | Android için Basit PLT Hook |
|
||||
|
||||
## Kullanım
|
||||
|
||||
Şu anda geliştirme aşamasındayız. (Yakında)
|
||||
|
||||
## Kurulum
|
||||
|
||||
Şu anda mevcut kararlı sürüm yoktur. (Yakında)
|
||||
|
||||
## Çeviri
|
||||
|
||||
Şu anda başka bir platformla entegre bir çeviri sistemimiz bulunmuyor, ancak [add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui) branch'ine katkıda bulunabilirsiniz. Lütfen GitHub profilinizi [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-webui/TRANSLATOR.md) dosyasına eklemeyi unutmayın, böylece katkılarınız görülebilir.
|
||||
|
||||
## Destek
|
||||
ReZygisk veya diğer PerformanC projeleriyle ilgili herhangi bir soru için aşağıdaki kanallardan herhangi birine katılabilirsiniz:
|
||||
|
||||
- Discord Kanalı: [PerformanC](https://discord.gg/uPveNfTuCJ)
|
||||
- ReZygisk Telegram Kanalı: [@rezygiskchat](https://t.me/rezygiskchat)
|
||||
- PerformanC Telegram Kanalı: [@performancorg](https://t.me/performancorg)
|
||||
|
||||
## Katkıda Bulunma
|
||||
|
||||
ReZygisk'e katkıda bulunmak için PerformanC'nin [Katkı Yönergeleri](https://github.com/PerformanC/contributing)'ni takip etmek zorunludur. Güvenlik Politikası, Davranış Kuralları ve sözdizimi standartlarına uyulmalıdır.
|
||||
|
||||
## Lisans
|
||||
|
||||
ReZygisk, büyük ölçüde Dr-TSNG tarafından GPL lisansı altında, ancak yeniden yazılmış kodlar için The PerformanC Organization tarafından AGPL 3.0 lisansı altında lisanslanmıştır. Daha fazla bilgi için [Open Source Initiative](https://opensource.org/licenses/AGPL-3.0)'e göz atabilirsiniz.
|
||||
61
READMEs/README_vi-VN.md
Normal file
61
READMEs/README_vi-VN.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# ReZygisk
|
||||
|
||||
[English](../README.md)
|
||||
|
||||
ReZygisk làm một nhánh phát triển lấy từ ZygiskNext, một triển khai độc lập của Zygisk, cung cấp và hỗ trợ Zygisk API cho KernelSU, Magisk (bên cạnh tích hợp) và APatch (Đang trong quá trình phát triển).
|
||||
|
||||
Mục tiêu của ReZygisk là mô-đun hoá và viết lại toàn bộ codebase từ C++/Rust sang C, cho phép triển khai API Zygisk hiệu quả hơn và nhanh hơn với giấy phép dễ dàng tái sử dụng hơn.
|
||||
|
||||
> [!NOTE]
|
||||
> Mô-đun này đang trong quá trình phát triển; chỉ nên sử dụng file .zip từ các bản phát hành.
|
||||
>
|
||||
> Mạc dù bạn có thể cài đặt mô-đun được lấy từ trang [Actions](https://github.com/PerformanC/ReZygisk/actions), nhưng sẽ chỉ phụ thuộc vào bạn có chấp nhận rủi ro hay không vì các mô-đun này có thể gây lỗi cho hệ điều hành. Ví dụ: Bootloop (Lỗi liên tục khởi động lại máy)
|
||||
|
||||
## Tại sao nhánh phát triển này lại xuất hiện?
|
||||
|
||||
Bản ra mắt mới nhất của Zygisk Next không còn là mã nguồn mở, dành toàn bộ quyền phát triển phần mềm cho những nhà phát triển gốc. Không chỉ giới hạn chúng ta đóng gốp cho dự án, mà còn bất khả thi trong việc kiểm trả độ đảm bảo của mã, điều mà có thể coi là mối quan tâm lớn về tính bảo mật và độ an toàn, bởi Zygisk Next là mô-đun chạy dưới quyền quản trị (root), có khả năng truy cập vào toàn bộ hệ thống trong thiết bị của bạn.
|
||||
|
||||
Các nhà phát triển Zygisk Next đều là những người nổi tiếng và được tin tưởng bởi cộng đồng sử dụng Android, tuy nhiên, điều đó không có nghĩa là mã nguồn của họ không có lỗ hổng hoặc có nguy cơ bị tấn công. Chúng tôi (PerformanC) thông cảm được lý do mà học đóng mã nguồn của họ vào, tuy nhiễn chúng tôi tin vào điều ngược lại.
|
||||
|
||||
## Ưu điểm
|
||||
|
||||
- Mã nguồn mở (Vĩnh Viễn)
|
||||
|
||||
## Các công cụ/thư viện được sử dụng
|
||||
|
||||
| Công cụ | Mô tả |
|
||||
|-----------------|-------------------------------------------|
|
||||
| `Android NDK` | Bộ công cụ phát triển cốt lõi cho Android |
|
||||
|
||||
### Các công cụ/thư viện của C++ được sử dụng
|
||||
|
||||
| Thư Viện | Mô Tả |
|
||||
|------------|----------------------------------------------|
|
||||
| `lsplt` | Công cụ **móc** vào PLT đơn giản cho Android |
|
||||
|
||||
## Các sử dụng
|
||||
|
||||
Chúng tôi đang trong quá trình phát triển (Sắp ra mắt)
|
||||
|
||||
## Cài Đặt
|
||||
|
||||
Hiện chưa có bản ra mắt ổn định (Sắp ra mắt)
|
||||
|
||||
## Dịch WebUI cho mô-đun
|
||||
|
||||
Hiện tai, chúng tôi chưa tích hợp nền táng dịch nào để dịch một cách thuận tiện nhưng bạn có thể đóng góp vào nhánh [add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui). Đừng quên thêm trang cá nhân Github của bạn vào [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-webui/TRANSLATOR.md) để mọi người thâys được đóng góp của bạn
|
||||
|
||||
## Hỗ trợ
|
||||
Nếu bạn có những câu hỏi nào dành cho ReZygisk hoặc bất kì một dự án nào của PerformanC, hãy tự nhiên tham gia các kênh trò chuyện dưới đây:
|
||||
|
||||
- Discord: [PerformanC](https://discord.gg/uPveNfTuCJ)
|
||||
- Telegram [ReZygisk]: [@rezygiskchat](https://t.me/rezygiskchat)
|
||||
- Telegram [PerformanC]: [@performancorg](https://t.me/performancorg)
|
||||
|
||||
## Đóng góp cho dự án này
|
||||
|
||||
Tuân theo [hướng dẫn đóng góp](https://github.com/PerformanC/contributing) của PerformanC là một điều tất yếu mà bạn bắt buộc phải làm. Hãy tuân theo chính sách bảo mật, quy tắc ứng xử/đóng góp mã nguồn và tiêu chuẩn cú pháp riêng.
|
||||
|
||||
## Bản quyền
|
||||
|
||||
Hầu hết các thành phần của ReZygisk để dưới bản quyền GPL (bởi Dr-TSNG) và AGPL 3.0 (bởiThe PerformanC Organization) cho những phần được viết lại. Bạn có thể xem thêm trong trang [Open Source Initiative](https://opensource.org/licenses/AGPL-3.0).
|
||||
@@ -11,9 +11,9 @@ ReZygisk 是 Zygisk 的另一个独立实现,从 Zygisk Next 分叉而来,
|
||||
>
|
||||
> 您可以从 [Actions](https://github.com/PerformanC/ReZygisk/actions) 页面下载自动构建包,但要注意自负风险。使用不稳定的版本时,设备可能会陷入启动循环(Bootloop)。
|
||||
|
||||
## 为什么要ReZygisk?
|
||||
## 为什么要选择 ReZygisk?
|
||||
|
||||
最新版本的 Zygisk Next 并不开源,仅其核心开发者有权查阅全部源代码。这不仅阻止了其他开发者贡献代码,还阻止了他们对项目代码进行审计。Zygisk Next 是一个以超级用户(root)权限运行的模块,可以访问整个系统,闭源后存在重大安全隐患。
|
||||
最新版本的 Zygisk Next 并不开源,仅其核心开发者有权查阅全部源代码。这不仅阻止了其他开发者贡献代码,还阻止了他人对项目代码进行审计。Zygisk Next 是一个以超级用户(root)权限运行的模块,可以访问整个系统,闭源后存在重大安全隐患。
|
||||
|
||||
Zygisk Next 的开发者们在Android社区享有盛誉,备受信任。但这并不意味着他们的项目就一定没有任何恶意代码和漏洞。我们(PerformanC)理解他们出于某些原因不愿保持开源,但我们坚信,开源是更好的选择。
|
||||
|
||||
@@ -23,34 +23,15 @@ Zygisk Next 的开发者们在Android社区享有盛誉,备受信任。但这
|
||||
|
||||
## 依赖
|
||||
|
||||
| 工具 | 简介 |
|
||||
| 工具 | 简介 |
|
||||
|---------------|------------------------------------|
|
||||
| `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` | 解析和分析进程内存映射 |
|
||||
| `Android NDK` | Android 本地开发工具包 |
|
||||
|
||||
### C++ 依赖
|
||||
|
||||
| 依赖 | 简介 |
|
||||
| 依赖 | 简介 |
|
||||
|---------|-----------------------------|
|
||||
| `lsplt` | Android 程序链接表钩子 |
|
||||
| `lsplt` | Android 程序链接表钩子 |
|
||||
|
||||
## 用法
|
||||
|
||||
@@ -62,9 +43,9 @@ Zygisk Next 的开发者们在Android社区享有盛誉,备受信任。但这
|
||||
|
||||
## 翻译
|
||||
|
||||
您可以向 [add/webui](https://github.com/PerformanC/ReZygisk/tree/add/webui) 分支贡献翻译。
|
||||
您可以向 [add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui) 分支贡献翻译。
|
||||
|
||||
请不要忘记在 [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/webui/TRANSLATOR.md) 中添加您的 GitHub 账号信息,以便人们看到您的贡献。
|
||||
请不要忘记在 [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-webui/TRANSLATOR.md) 中添加您的 GitHub 账号信息,以便人们看到您的贡献。
|
||||
|
||||
## 支持
|
||||
|
||||
62
READMEs/README_zh-TW.md
Normal file
62
READMEs/README_zh-TW.md
Normal file
@@ -0,0 +1,62 @@
|
||||
# ReZygisk
|
||||
> 繁體中文(README_zh-TW.md)是根據[英文版自述檔案(README.md)](https://github.com/PerformanC/ReZygisk/blob/main/README.md)翻譯,僅供參考以便理解英文內容,翻譯可能滯後。
|
||||
|
||||
ReZygisk 是 Zygisk Next 的一個分支,這是一個獨立實現的 Zygisk,為 KernelSU、Magisk(除了內建支援外)和 APatch(開發中)提供 Zygisk API 支援。
|
||||
|
||||
此專案致力於用 C 語言重寫原有的 C++ 和 Rust 代碼,藉此以更現代且高效的方式實現 Zygisk API,並採用更寬鬆的授權條款。
|
||||
|
||||
> [!NOTE]
|
||||
> 此模組/分支仍在開發中(WIP);請僅安裝正式版本的壓縮包。
|
||||
>
|
||||
> 雖然你可以從 [Actions](https://github.com/PerformanC/ReZygisk/actions) 頁面安裝 .zip 檔,但若因此導致裝置進入開機循環(Bootloop),後果須自行承擔。
|
||||
|
||||
## 為什麼選擇ReZygisk?
|
||||
|
||||
最新版本的 Zygisk Next 已轉為閉源,只有核心開發者能查閱完整的原始碼。這不僅限制了其他開發者的貢獻,也無法進行代碼審計。由於 Zygisk Next 是一個以超級使用者(root)權限運行的模組,能夠存取整個系統,若閉源將帶來重大的安全風險。
|
||||
|
||||
雖然 Zygisk Next 的開發者在 Android 社群中享有盛譽,並且備受信任,但這並不代表他們的專案就完全沒有任何惡意程式碼或漏洞。我們(PerformanC)理解他們因某些原因選擇保持閉源,但我們堅信開源才是更好的選擇。
|
||||
|
||||
## 優勢
|
||||
|
||||
- 永遠是自由及開放原始碼軟體(FOSS)
|
||||
|
||||
## 依賴項
|
||||
|
||||
| 工具 | 說明 |
|
||||
|-----------------|---------------------------------------|
|
||||
| `Android NDK` | Android 原生開發工具包 |
|
||||
|
||||
### C++ 依賴項
|
||||
|
||||
| 依賴 | 說明 |
|
||||
|----------|----------------------------------------------|
|
||||
| `lsplt` | Android 的簡單 PLT(程式連結表) 勾取 |
|
||||
|
||||
## 用法
|
||||
|
||||
我們目前正在開發中。(敬請期待)
|
||||
|
||||
## 安裝
|
||||
|
||||
目前沒有穩定版本可供下載。(敬請期待)
|
||||
|
||||
## 翻譯
|
||||
|
||||
目前我們尚未與其他平台整合進行翻譯,但您可以為 [add/new-webui](https://github.com/PerformanC/ReZygisk/tree/add/new-webui)分支做出貢獻。請別忘了在 [TRANSLATOR.md](https://github.com/PerformanC/ReZygisk/blob/add/new-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 授權,而由 PerformanC 組織重寫的程式碼則採用 AGPL 3.0 授權。
|
||||
|
||||
您可以在[開放原始碼倡議(Open Source Initiative)](https://opensource.org/licenses/AGPL-3.0)上閱讀更多相關資訊。
|
||||
@@ -33,7 +33,7 @@ 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 androidCompileNdkVersion by extra("27.2.12479018")
|
||||
val androidSourceCompatibility by extra(JavaVersion.VERSION_11)
|
||||
val androidTargetCompatibility by extra(JavaVersion.VERSION_11)
|
||||
|
||||
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
2
gradle/wrapper/gradle-wrapper.properties
vendored
2
gradle/wrapper/gradle-wrapper.properties
vendored
@@ -1,6 +1,6 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
297
gradlew
vendored
297
gradlew
vendored
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env sh
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
@@ -15,69 +15,104 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||
' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
@@ -87,9 +122,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
@@ -98,88 +133,120 @@ Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
|
||||
183
gradlew.bat
vendored
183
gradlew.bat
vendored
@@ -1,89 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
|
||||
@@ -26,6 +26,8 @@ val ccachePath by lazy {
|
||||
}
|
||||
|
||||
val defaultCFlags = arrayOf(
|
||||
"-D_GNU_SOURCE",
|
||||
|
||||
"-Wall", "-Wextra",
|
||||
"-fno-rtti", "-fno-exceptions",
|
||||
"-fno-stack-protector", "-fomit-frame-pointer",
|
||||
@@ -49,12 +51,14 @@ android {
|
||||
|
||||
externalNativeBuild.cmake {
|
||||
path("src/CMakeLists.txt")
|
||||
buildStagingDirectory = layout.buildDirectory.get().asFile
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
externalNativeBuild.cmake {
|
||||
arguments += "-DANDROID_STL=none"
|
||||
arguments += "-DLSPLT_STANDALONE=ON"
|
||||
arguments += "-DCMAKE_BUILD_PARALLEL_LEVEL=${Runtime.getRuntime().availableProcessors()}"
|
||||
cFlags("-std=c18", *defaultCFlags)
|
||||
cppFlags("-std=c++20", *defaultCFlags)
|
||||
ccachePath?.let {
|
||||
|
||||
@@ -3,12 +3,14 @@ project("loader")
|
||||
|
||||
find_package(cxx REQUIRED CONFIG)
|
||||
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
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)
|
||||
target_link_libraries(common log)
|
||||
|
||||
aux_source_directory(injector INJECTOR_SRC_LIST)
|
||||
add_library(zygisk SHARED ${INJECTOR_SRC_LIST})
|
||||
@@ -18,6 +20,5 @@ 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)
|
||||
|
||||
target_link_libraries(libzygisk_ptrace.so log common)
|
||||
add_subdirectory(external)
|
||||
|
||||
350
loader/src/common/daemon.c
Normal file
350
loader/src/common/daemon.c
Normal file
@@ -0,0 +1,350 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <linux/un.h>
|
||||
|
||||
#include "logging.h"
|
||||
#include "socket_utils.h"
|
||||
|
||||
#include "daemon.h"
|
||||
|
||||
int rezygiskd_connect(uint8_t retry) {
|
||||
retry++;
|
||||
|
||||
int fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (fd == -1) {
|
||||
PLOGE("socket create");
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct sockaddr_un addr = {
|
||||
.sun_family = AF_UNIX,
|
||||
.sun_path = { 0 }
|
||||
};
|
||||
|
||||
/*
|
||||
INFO: Application must assume that sun_path can hold _POSIX_PATH_MAX characters.
|
||||
|
||||
Sources:
|
||||
- https://pubs.opengroup.org/onlinepubs/009696699/basedefs/sys/un.h.html
|
||||
*/
|
||||
strcpy(addr.sun_path, TMP_PATH "/" SOCKET_FILE_NAME);
|
||||
socklen_t socklen = sizeof(addr);
|
||||
|
||||
while (--retry) {
|
||||
int ret = connect(fd, (struct sockaddr *)&addr, socklen);
|
||||
if (ret == 0) return fd;
|
||||
if (retry) {
|
||||
PLOGE("Retrying to connect to ReZygiskd, sleep 1s");
|
||||
|
||||
sleep(1);
|
||||
}
|
||||
}
|
||||
|
||||
close(fd);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool rezygiskd_ping() {
|
||||
int fd = rezygiskd_connect(5);
|
||||
if (fd == -1) {
|
||||
PLOGE("connection to ReZygiskd");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
write_uint8_t(fd, (uint8_t)PingHeartbeat);
|
||||
|
||||
close(fd);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
uint32_t rezygiskd_get_process_flags(uid_t uid) {
|
||||
int fd = rezygiskd_connect(1);
|
||||
if (fd == -1) {
|
||||
PLOGE("connection to ReZygiskd");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
write_uint8_t(fd, (uint8_t)GetProcessFlags);
|
||||
write_uint32_t(fd, (uint32_t)uid);
|
||||
|
||||
uint32_t res = 0;
|
||||
read_uint32_t(fd, &res);
|
||||
|
||||
close(fd);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
void rezygiskd_get_info(struct rezygisk_info *info) {
|
||||
int fd = rezygiskd_connect(1);
|
||||
if (fd == -1) {
|
||||
PLOGE("connection to ReZygiskd");
|
||||
|
||||
info->running = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
info->running = true;
|
||||
|
||||
write_uint8_t(fd, (uint8_t)GetInfo);
|
||||
|
||||
uint32_t flags = 0;
|
||||
read_uint32_t(fd, &flags);
|
||||
|
||||
if (flags & (1 << 27)) info->root_impl = ROOT_IMPL_APATCH;
|
||||
else if (flags & (1 << 29)) info->root_impl = ROOT_IMPL_KERNELSU;
|
||||
else if (flags & (1 << 30)) info->root_impl = ROOT_IMPL_MAGISK;
|
||||
else info->root_impl = ROOT_IMPL_NONE;
|
||||
|
||||
read_uint32_t(fd, (uint32_t *)&info->pid);
|
||||
|
||||
read_size_t(fd, &info->modules->modules_count);
|
||||
if (info->modules->modules_count == 0) {
|
||||
info->modules->modules = NULL;
|
||||
|
||||
close(fd);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
info->modules->modules = (char **)malloc(sizeof(char *) * info->modules->modules_count);
|
||||
if (info->modules->modules == NULL) {
|
||||
PLOGE("allocating modules name memory");
|
||||
|
||||
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++) {
|
||||
char *module_name = read_string(fd);
|
||||
if (module_name == NULL) {
|
||||
PLOGE("reading module name");
|
||||
|
||||
info->modules->modules_count = i;
|
||||
|
||||
free_rezygisk_info(info);
|
||||
|
||||
info->modules = NULL;
|
||||
info->modules->modules_count = 0;
|
||||
|
||||
close(fd);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
char module_path[PATH_MAX];
|
||||
snprintf(module_path, sizeof(module_path), "/data/adb/modules/%s/module.prop", module_name);
|
||||
|
||||
FILE *module_prop = fopen(module_path, "r");
|
||||
if (!module_prop) {
|
||||
PLOGE("failed to open module prop file %s", module_path);
|
||||
|
||||
info->modules->modules_count = i;
|
||||
|
||||
free_rezygisk_info(info);
|
||||
|
||||
info->modules = NULL;
|
||||
info->modules->modules_count = 0;
|
||||
|
||||
close(fd);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
char line[1024];
|
||||
while (fgets(line, sizeof(line), module_prop) != NULL) {
|
||||
if (strncmp(line, "name=", strlen("name=")) != 0) continue;
|
||||
|
||||
info->modules->modules[i] = strndup(line + 5, strlen(line) - 6);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
fclose(module_prop);
|
||||
}
|
||||
|
||||
close(fd);
|
||||
}
|
||||
|
||||
void free_rezygisk_info(struct rezygisk_info *info) {
|
||||
if (info->modules->modules) {
|
||||
for (size_t i = 0; i < info->modules->modules_count; i++) {
|
||||
free(info->modules->modules[i]);
|
||||
}
|
||||
|
||||
free(info->modules->modules);
|
||||
}
|
||||
|
||||
free(info->modules);
|
||||
}
|
||||
|
||||
bool rezygiskd_read_modules(struct zygisk_modules *modules) {
|
||||
int fd = rezygiskd_connect(1);
|
||||
if (fd == -1) {
|
||||
PLOGE("connection to ReZygiskd");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
write_uint8_t(fd, (uint8_t)ReadModules);
|
||||
|
||||
size_t len = 0;
|
||||
read_size_t(fd, &len);
|
||||
|
||||
modules->modules = malloc(len * sizeof(char *));
|
||||
if (!modules->modules) {
|
||||
PLOGE("allocating modules name memory");
|
||||
|
||||
close(fd);
|
||||
|
||||
return false;
|
||||
}
|
||||
modules->modules_count = len;
|
||||
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
char *lib_path = read_string(fd);
|
||||
if (!lib_path) {
|
||||
PLOGE("reading module lib_path");
|
||||
|
||||
close(fd);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
modules->modules[i] = lib_path;
|
||||
}
|
||||
|
||||
close(fd);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void free_modules(struct zygisk_modules *modules) {
|
||||
if (modules->modules) {
|
||||
for (size_t i = 0; i < modules->modules_count; i++) {
|
||||
free(modules->modules[i]);
|
||||
}
|
||||
|
||||
free(modules->modules);
|
||||
}
|
||||
}
|
||||
|
||||
int rezygiskd_connect_companion(size_t index) {
|
||||
int fd = rezygiskd_connect(1);
|
||||
if (fd == -1) {
|
||||
PLOGE("connection to ReZygiskd");
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
write_uint8_t(fd, (uint8_t)RequestCompanionSocket);
|
||||
write_size_t(fd, index);
|
||||
|
||||
uint8_t res = 0;
|
||||
read_uint8_t(fd, &res);
|
||||
|
||||
if (res == 1) return fd;
|
||||
else {
|
||||
close(fd);
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
int rezygiskd_get_module_dir(size_t index) {
|
||||
int fd = rezygiskd_connect(1);
|
||||
if (fd == -1) {
|
||||
PLOGE("connection to ReZygiskd");
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
write_uint8_t(fd, (uint8_t)GetModuleDir);
|
||||
write_size_t(fd, index);
|
||||
|
||||
int dirfd = read_fd(fd);
|
||||
|
||||
close(fd);
|
||||
|
||||
return dirfd;
|
||||
}
|
||||
|
||||
void rezygiskd_zygote_restart() {
|
||||
int fd = rezygiskd_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 (!write_uint8_t(fd, (uint8_t)ZygoteRestart))
|
||||
PLOGE("Failed to request ZygoteRestart");
|
||||
|
||||
close(fd);
|
||||
}
|
||||
|
||||
void rezygiskd_system_server_started() {
|
||||
int fd = rezygiskd_connect(1);
|
||||
if (fd == -1) {
|
||||
PLOGE("Failed to report system server started");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!write_uint8_t(fd, (uint8_t)SystemServerStarted))
|
||||
PLOGE("Failed to request SystemServerStarted");
|
||||
|
||||
close(fd);
|
||||
}
|
||||
|
||||
bool rezygiskd_update_mns(enum mount_namespace_state nms_state, char *buf, size_t buf_size) {
|
||||
int fd = rezygiskd_connect(1);
|
||||
if (fd == -1) {
|
||||
PLOGE("connection to ReZygiskd");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
write_uint8_t(fd, (uint8_t)UpdateMountNamespace);
|
||||
write_uint32_t(fd, (uint32_t)getpid());
|
||||
write_uint8_t(fd, (uint8_t)nms_state);
|
||||
|
||||
uint32_t target_pid = 0;
|
||||
if (read_uint32_t(fd, &target_pid) < 0) {
|
||||
PLOGE("Failed to read target pid");
|
||||
|
||||
close(fd);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t target_fd = 0;
|
||||
if (read_uint32_t(fd, &target_fd) < 0) {
|
||||
PLOGE("Failed to read target fd");
|
||||
|
||||
close(fd);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
snprintf(buf, buf_size, "/proc/%u/fd/%u", target_pid, target_fd);
|
||||
|
||||
close(fd);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
#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;
|
||||
}
|
||||
|
||||
std::string GetTmpPath() {
|
||||
return TMP_PATH;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
close(fd);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
info->modules->modules_count = socket_utils::read_usize(fd);
|
||||
|
||||
if (info->modules->modules_count == 0) {
|
||||
info->modules->modules = NULL;
|
||||
|
||||
close(fd);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
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 {
|
||||
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);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
fclose(module_prop);
|
||||
}
|
||||
}
|
||||
|
||||
close(fd);
|
||||
} else info->running = false;
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
#include <cstdio>
|
||||
#include <dlfcn.h>
|
||||
#include <libgen.h>
|
||||
#include <climits>
|
||||
#include <cstring>
|
||||
#include <android/dlext.h>
|
||||
|
||||
#include "dl.h"
|
||||
#include "logging.h"
|
||||
|
||||
extern "C" [[gnu::weak]] struct android_namespace_t*
|
||||
//NOLINTNEXTLINE
|
||||
__loader_android_create_namespace([[maybe_unused]] const char* name,
|
||||
[[maybe_unused]] const char* ld_library_path,
|
||||
[[maybe_unused]] const char* default_library_path,
|
||||
[[maybe_unused]] uint64_t type,
|
||||
[[maybe_unused]] const char* permitted_when_isolated_path,
|
||||
[[maybe_unused]] android_namespace_t* parent,
|
||||
[[maybe_unused]] const void* caller_addr);
|
||||
|
||||
void* DlopenExt(const char* path, int flags) {
|
||||
auto info = android_dlextinfo{};
|
||||
auto* dir = dirname(path);
|
||||
auto* ns = &__loader_android_create_namespace == nullptr ? nullptr :
|
||||
__loader_android_create_namespace(path, dir, nullptr,
|
||||
2, /* ANDROID_NAMESPACE_TYPE_SHARED */
|
||||
nullptr, nullptr,
|
||||
reinterpret_cast<void*>(&DlopenExt));
|
||||
if (ns) {
|
||||
info.flags = ANDROID_DLEXT_USE_NAMESPACE;
|
||||
info.library_namespace = ns;
|
||||
|
||||
LOGD("Open %s with namespace %p", path, ns);
|
||||
} else {
|
||||
LOGD("Cannot create namespace for %s", path);
|
||||
}
|
||||
|
||||
auto* handle = android_dlopen_ext(path, flags, &info);
|
||||
if (handle) {
|
||||
LOGD("dlopen %s: %p", path, handle);
|
||||
} else {
|
||||
LOGE("dlopen %s: %s", path, dlerror());
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
394
loader/src/common/elf_util.c
Normal file
394
loader/src/common/elf_util.c
Normal file
@@ -0,0 +1,394 @@
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#include "logging.h"
|
||||
|
||||
#include "elf_util.h"
|
||||
|
||||
#define SHT_GNU_HASH 0x6ffffff6
|
||||
|
||||
uint32_t ElfHash(const char *name) {
|
||||
uint32_t h = 0, g = 0;
|
||||
|
||||
while (*name) {
|
||||
h = (h << 4) + (unsigned char)*name++;
|
||||
g = h & 0xf0000000;
|
||||
|
||||
if (g) {
|
||||
h ^= g >> 24;
|
||||
}
|
||||
|
||||
h &= ~g;
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
uint32_t GnuHash(const char *name) {
|
||||
uint32_t h = 5381;
|
||||
|
||||
while (*name) {
|
||||
h = (h << 5) + h + (unsigned char)(*name++);
|
||||
}
|
||||
|
||||
return h;
|
||||
}
|
||||
|
||||
ElfW(Shdr) *offsetOf_Shdr(ElfW(Ehdr) * head, ElfW(Off) off) {
|
||||
return (ElfW(Shdr) *)(((uintptr_t)head) + off);
|
||||
}
|
||||
|
||||
char *offsetOf_char(ElfW(Ehdr) * head, ElfW(Off) off) {
|
||||
return (char *)(((uintptr_t)head) + off);
|
||||
}
|
||||
|
||||
ElfW(Sym) *offsetOf_Sym(ElfW(Ehdr) * head, ElfW(Off) off) {
|
||||
return (ElfW(Sym) *)(((uintptr_t)head) + off);
|
||||
}
|
||||
|
||||
ElfW(Word) *offsetOf_Word(ElfW(Ehdr) * head, ElfW(Off) off) {
|
||||
return (ElfW(Word) *)(((uintptr_t)head) + off);
|
||||
}
|
||||
|
||||
int dl_cb(struct dl_phdr_info *info, size_t size, void *data) {
|
||||
(void) size;
|
||||
|
||||
if ((info)->dlpi_name == NULL) return 0;
|
||||
|
||||
ElfImg *img = (ElfImg *)data;
|
||||
|
||||
if (strstr(info->dlpi_name, img->elf)) {
|
||||
img->elf = strdup(info->dlpi_name);
|
||||
img->base = (void *)info->dlpi_addr;
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool find_module_base(ElfImg *img) {
|
||||
dl_iterate_phdr(dl_cb, img);
|
||||
|
||||
return img->base != NULL;
|
||||
}
|
||||
|
||||
size_t calculate_valid_symtabs_amount(ElfImg *img) {
|
||||
size_t count = 0;
|
||||
|
||||
if (img->symtab_start == NULL || img->symstr_offset_for_symtab == 0) return count;
|
||||
|
||||
for (ElfW(Off) i = 0; i < img->symtab_count; i++) {
|
||||
unsigned int st_type = ELF_ST_TYPE(img->symtab_start[i].st_info);
|
||||
|
||||
if ((st_type == STT_FUNC || st_type == STT_OBJECT) && img->symtab_start[i].st_size)
|
||||
count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
void ElfImg_destroy(ElfImg *img) {
|
||||
if (img->elf) {
|
||||
free(img->elf);
|
||||
img->elf = NULL;
|
||||
}
|
||||
|
||||
if (img->symtabs_) {
|
||||
size_t valid_symtabs_amount = calculate_valid_symtabs_amount(img);
|
||||
if (valid_symtabs_amount == 0) goto finalize;
|
||||
|
||||
for (size_t i = 0; i < valid_symtabs_amount; i++) {
|
||||
free(img->symtabs_[i].name);
|
||||
}
|
||||
|
||||
free(img->symtabs_);
|
||||
img->symtabs_ = NULL;
|
||||
}
|
||||
|
||||
if (img->header) {
|
||||
munmap(img->header, img->size);
|
||||
img->header = NULL;
|
||||
}
|
||||
|
||||
finalize:
|
||||
free(img);
|
||||
img = NULL;
|
||||
}
|
||||
|
||||
ElfImg *ElfImg_create(const char *elf) {
|
||||
ElfImg *img = (ElfImg *)calloc(1, sizeof(ElfImg));
|
||||
if (!img) {
|
||||
LOGE("Failed to allocate memory for ElfImg");
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
img->bias = -4396;
|
||||
img->elf = strdup(elf);
|
||||
img->base = NULL;
|
||||
|
||||
if (!find_module_base(img)) {
|
||||
LOGE("Failed to find module base for %s", img->elf);
|
||||
|
||||
ElfImg_destroy(img);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int fd = open(img->elf, O_RDONLY);
|
||||
if (fd < 0) {
|
||||
LOGE("failed to open %s", img->elf);
|
||||
|
||||
ElfImg_destroy(img);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
img->size = lseek(fd, 0, SEEK_END);
|
||||
if (img->size <= 0) {
|
||||
LOGE("lseek() failed for %s", img->elf);
|
||||
|
||||
ElfImg_destroy(img);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
img->header = (ElfW(Ehdr) *)mmap(NULL, img->size, PROT_READ, MAP_SHARED, fd, 0);
|
||||
|
||||
close(fd);
|
||||
|
||||
img->section_header = offsetOf_Shdr(img->header, img->header->e_shoff);
|
||||
|
||||
uintptr_t shoff = (uintptr_t)img->section_header;
|
||||
char *section_str = offsetOf_char(img->header, img->section_header[img->header->e_shstrndx].sh_offset);
|
||||
|
||||
for (int i = 0; i < img->header->e_shnum; i++, shoff += img->header->e_shentsize) {
|
||||
ElfW(Shdr) *section_h = (ElfW(Shdr *))shoff;
|
||||
|
||||
char *sname = section_h->sh_name + section_str;
|
||||
size_t entsize = section_h->sh_entsize;
|
||||
|
||||
switch (section_h->sh_type) {
|
||||
case SHT_DYNSYM: {
|
||||
if (img->bias == -4396) {
|
||||
img->dynsym = section_h;
|
||||
img->dynsym_offset = section_h->sh_offset;
|
||||
img->dynsym_start = offsetOf_Sym(img->header, img->dynsym_offset);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case SHT_SYMTAB: {
|
||||
if (strcmp(sname, ".symtab") == 0) {
|
||||
img->symtab = section_h;
|
||||
img->symtab_offset = section_h->sh_offset;
|
||||
img->symtab_size = section_h->sh_size;
|
||||
img->symtab_count = img->symtab_size / entsize;
|
||||
img->symtab_start = offsetOf_Sym(img->header, img->symtab_offset);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case SHT_STRTAB: {
|
||||
if (img->bias == -4396) {
|
||||
img->strtab = section_h;
|
||||
img->symstr_offset = section_h->sh_offset;
|
||||
img->strtab_start = offsetOf_Sym(img->header, img->symstr_offset);
|
||||
}
|
||||
|
||||
if (strcmp(sname, ".strtab") == 0) {
|
||||
img->symstr_offset_for_symtab = section_h->sh_offset;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case SHT_PROGBITS: {
|
||||
if (img->strtab == NULL || img->dynsym == NULL)
|
||||
break;
|
||||
|
||||
if (img->bias == -4396) {
|
||||
img->bias = (off_t)section_h->sh_addr - (off_t)section_h->sh_offset;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case SHT_HASH: {
|
||||
ElfW(Word) *d_un = offsetOf_Word(img->header, section_h->sh_offset);
|
||||
img->nbucket_ = d_un[0];
|
||||
img->bucket_ = d_un + 2;
|
||||
img->chain_ = img->bucket_ + img->nbucket_;
|
||||
|
||||
break;
|
||||
}
|
||||
case SHT_GNU_HASH: {
|
||||
ElfW(Word) *d_buf = (ElfW(Word) *)(((size_t)img->header) + section_h->sh_offset);
|
||||
img->gnu_nbucket_ = d_buf[0];
|
||||
img->gnu_symndx_ = d_buf[1];
|
||||
img->gnu_bloom_size_ = d_buf[2];
|
||||
img->gnu_shift2_ = d_buf[3];
|
||||
img->gnu_bloom_filter_ = (uintptr_t *)(d_buf + 4);
|
||||
img->gnu_bucket_ = (uint32_t *)(img->gnu_bloom_filter_ + img->gnu_bloom_size_);
|
||||
img->gnu_chain_ = img->gnu_bucket_ + img->gnu_nbucket_ - img->gnu_symndx_;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return img;
|
||||
}
|
||||
|
||||
ElfW(Addr) ElfLookup(ElfImg *restrict img, const char *restrict name, uint32_t hash) {
|
||||
if (img->nbucket_ == 0)
|
||||
return 0;
|
||||
|
||||
char *strings = (char *)img->strtab_start;
|
||||
|
||||
for (size_t n = img->bucket_[hash % img->nbucket_]; n != 0; n = img->chain_[n]) {
|
||||
ElfW(Sym) *sym = img->dynsym_start + n;
|
||||
|
||||
if (strncmp(name, strings + sym->st_name, strlen(name)) == 0)
|
||||
return sym->st_value;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
ElfW(Addr) GnuLookup(ElfImg *restrict img, const char *name, uint32_t hash) {
|
||||
static size_t bloom_mask_bits = sizeof(ElfW(Addr)) * 8;
|
||||
|
||||
if (img->gnu_nbucket_ == 0 || img->gnu_bloom_size_ == 0)
|
||||
return 0;
|
||||
|
||||
size_t bloom_word =
|
||||
img->gnu_bloom_filter_[(hash / bloom_mask_bits) % img->gnu_bloom_size_];
|
||||
uintptr_t mask = 0 | (uintptr_t)1 << (hash % bloom_mask_bits) |
|
||||
(uintptr_t)1 << ((hash >> img->gnu_shift2_) % bloom_mask_bits);
|
||||
if ((mask & bloom_word) == mask) {
|
||||
size_t sym_index = img->gnu_bucket_[hash % img->gnu_nbucket_];
|
||||
if (sym_index >= img->gnu_symndx_) {
|
||||
char *strings = (char *)img->strtab_start;
|
||||
do {
|
||||
ElfW(Sym) *sym = img->dynsym_start + sym_index;
|
||||
|
||||
if (((img->gnu_chain_[sym_index] ^ hash) >> 1) == 0 &&
|
||||
name == strings + sym->st_name) {
|
||||
return sym->st_value;
|
||||
}
|
||||
} while ((img->gnu_chain_[sym_index++] & 1) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
ElfW(Addr) LinearLookup(ElfImg *img, const char *restrict name) {
|
||||
size_t valid_symtabs_amount = calculate_valid_symtabs_amount(img);
|
||||
if (valid_symtabs_amount == 0) return 0;
|
||||
|
||||
if (!img->symtabs_) {
|
||||
img->symtabs_ = (struct symtabs *)calloc(1, sizeof(struct symtabs) * valid_symtabs_amount);
|
||||
if (!img->symtabs_) return 0;
|
||||
|
||||
|
||||
if (img->symtab_start != NULL && img->symstr_offset_for_symtab != 0) {
|
||||
ElfW(Off) i = 0;
|
||||
for (ElfW(Off) pos = 0; pos < img->symtab_count; pos++) {
|
||||
unsigned int st_type = ELF_ST_TYPE(img->symtab_start[pos].st_info);
|
||||
const char *st_name = offsetOf_char(img->header, img->symstr_offset_for_symtab + img->symtab_start[pos].st_name);
|
||||
|
||||
if ((st_type == STT_FUNC || st_type == STT_OBJECT) && img->symtab_start[pos].st_size) {
|
||||
img->symtabs_[i].name = strdup(st_name);
|
||||
img->symtabs_[i].sym = &img->symtab_start[pos];
|
||||
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < valid_symtabs_amount; i++) {
|
||||
if (strcmp(name, img->symtabs_[i].name) != 0) continue;
|
||||
|
||||
return img->symtabs_[i].sym->st_value;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
ElfW(Addr) LinearLookupByPrefix(ElfImg *img, const char *name) {
|
||||
size_t valid_symtabs_amount = calculate_valid_symtabs_amount(img);
|
||||
if (valid_symtabs_amount == 0) return 0;
|
||||
|
||||
if (!img->symtabs_) {
|
||||
img->symtabs_ = (struct symtabs *)malloc(sizeof(struct symtabs) * valid_symtabs_amount);
|
||||
if (!img->symtabs_) return 0;
|
||||
|
||||
if (img->symtab_start != NULL && img->symstr_offset_for_symtab != 0) {
|
||||
ElfW(Off) i = 0;
|
||||
for (ElfW(Off) pos = 0; pos < img->symtab_count; pos++) {
|
||||
unsigned int st_type = ELF_ST_TYPE(img->symtab_start[pos].st_info);
|
||||
const char *st_name = offsetOf_char(img->header, img->symstr_offset_for_symtab + img->symtab_start[pos].st_name);
|
||||
|
||||
if ((st_type == STT_FUNC || st_type == STT_OBJECT) && img->symtab_start[pos].st_size) {
|
||||
img->symtabs_[i].name = strdup(st_name);
|
||||
img->symtabs_[i].sym = &img->symtab_start[pos];
|
||||
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < valid_symtabs_amount; i++) {
|
||||
if (strlen(img->symtabs_[i].name) < strlen(name))
|
||||
continue;
|
||||
|
||||
if (strncmp(img->symtabs_[i].name, name, strlen(name)) == 0)
|
||||
return img->symtabs_[i].sym->st_value;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
ElfW(Addr) getSymbOffset(ElfImg *img, const char *name) {
|
||||
ElfW(Addr) offset = GnuLookup(img, name, GnuHash(name));
|
||||
if (offset > 0) return offset;
|
||||
|
||||
offset = ElfLookup(img, name, ElfHash(name));
|
||||
if (offset > 0) return offset;
|
||||
|
||||
offset = LinearLookup(img, name);
|
||||
if (offset > 0) return offset;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
ElfW(Addr) getSymbAddress(ElfImg *img, const char *name) {
|
||||
ElfW(Addr) offset = getSymbOffset(img, name);
|
||||
|
||||
if (offset < 0 || !img->base) return 0;
|
||||
|
||||
return ((uintptr_t)img->base + offset - img->bias);
|
||||
}
|
||||
|
||||
ElfW(Addr) getSymbAddressByPrefix(ElfImg *img, const char *prefix) {
|
||||
ElfW(Addr) offset = LinearLookupByPrefix(img, prefix);
|
||||
|
||||
if (offset < 0 || !img->base) return 0;
|
||||
|
||||
return (ElfW(Addr))((uintptr_t)img->base + offset - img->bias);
|
||||
}
|
||||
|
||||
void *getSymbValueByPrefix(ElfImg *img, const char *prefix) {
|
||||
ElfW(Addr) address = getSymbAddressByPrefix(img, prefix);
|
||||
|
||||
return address == 0 ? NULL : *((void **)address);
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
/*
|
||||
* 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;
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
#include <sys/sysmacros.h>
|
||||
|
||||
#include "files.hpp"
|
||||
#include "misc.hpp"
|
||||
|
||||
using namespace std::string_view_literals;
|
||||
|
||||
void file_readline(bool trim, FILE *fp, const std::function<bool(std::string_view)> &fn) {
|
||||
size_t len = 1024;
|
||||
char *buf = (char *) malloc(len);
|
||||
char *start;
|
||||
ssize_t read;
|
||||
while ((read = getline(&buf, &len, fp)) >= 0) {
|
||||
start = buf;
|
||||
if (trim) {
|
||||
while (read && "\n\r "sv.find(buf[read - 1]) != std::string::npos)
|
||||
--read;
|
||||
buf[read] = '\0';
|
||||
while (*start == ' ')
|
||||
++start;
|
||||
}
|
||||
if (!fn(start))
|
||||
break;
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
|
||||
void file_readline(bool trim, const char *file, const std::function<bool(std::string_view)> &fn) {
|
||||
if (auto fp = open_file(file, "re"))
|
||||
file_readline(trim, fp.get(), fn);
|
||||
}
|
||||
void file_readline(const char *file, const std::function<bool(std::string_view)> &fn) {
|
||||
file_readline(false, file, fn);
|
||||
}
|
||||
|
||||
std::vector<mount_info> parse_mount_info(const char *pid) {
|
||||
char buf[PATH_MAX] = {};
|
||||
snprintf(buf, sizeof(buf), "/proc/%s/mountinfo", pid);
|
||||
std::vector<mount_info> result;
|
||||
|
||||
file_readline(buf, [&result](std::string_view line) -> bool {
|
||||
int root_start = 0, root_end = 0;
|
||||
int target_start = 0, target_end = 0;
|
||||
int vfs_option_start = 0, vfs_option_end = 0;
|
||||
int type_start = 0, type_end = 0;
|
||||
int source_start = 0, source_end = 0;
|
||||
int fs_option_start = 0, fs_option_end = 0;
|
||||
int optional_start = 0, optional_end = 0;
|
||||
unsigned int id, parent, maj, min;
|
||||
sscanf(line.data(),
|
||||
"%u " // (1) id
|
||||
"%u " // (2) parent
|
||||
"%u:%u " // (3) maj:min
|
||||
"%n%*s%n " // (4) mountroot
|
||||
"%n%*s%n " // (5) target
|
||||
"%n%*s%n" // (6) vfs options (fs-independent)
|
||||
"%n%*[^-]%n - " // (7) optional fields
|
||||
"%n%*s%n " // (8) FS type
|
||||
"%n%*s%n " // (9) source
|
||||
"%n%*s%n", // (10) fs options (fs specific)
|
||||
&id, &parent, &maj, &min, &root_start, &root_end, &target_start,
|
||||
&target_end, &vfs_option_start, &vfs_option_end,
|
||||
&optional_start, &optional_end, &type_start, &type_end,
|
||||
&source_start, &source_end, &fs_option_start, &fs_option_end);
|
||||
|
||||
auto root = line.substr(root_start, root_end - root_start);
|
||||
auto target = line.substr(target_start, target_end - target_start);
|
||||
auto vfs_option =
|
||||
line.substr(vfs_option_start, vfs_option_end - vfs_option_start);
|
||||
++optional_start;
|
||||
--optional_end;
|
||||
auto optional = line.substr(
|
||||
optional_start,
|
||||
optional_end - optional_start > 0 ? optional_end - optional_start : 0);
|
||||
|
||||
auto type = line.substr(type_start, type_end - type_start);
|
||||
auto source = line.substr(source_start, source_end - source_start);
|
||||
auto fs_option =
|
||||
line.substr(fs_option_start, fs_option_end - fs_option_start);
|
||||
|
||||
unsigned int shared = 0;
|
||||
unsigned int master = 0;
|
||||
unsigned int propagate_from = 0;
|
||||
if (auto pos = optional.find("shared:"); pos != std::string_view::npos) {
|
||||
shared = parse_int(optional.substr(pos + 7));
|
||||
}
|
||||
if (auto pos = optional.find("master:"); pos != std::string_view::npos) {
|
||||
master = parse_int(optional.substr(pos + 7));
|
||||
}
|
||||
if (auto pos = optional.find("propagate_from:");
|
||||
pos != std::string_view::npos) {
|
||||
propagate_from = parse_int(optional.substr(pos + 15));
|
||||
}
|
||||
|
||||
result.emplace_back(mount_info {
|
||||
.id = id,
|
||||
.parent = parent,
|
||||
.device = static_cast<dev_t>(makedev(maj, min)),
|
||||
.root {root},
|
||||
.target {target},
|
||||
.vfs_option {vfs_option},
|
||||
.optional {
|
||||
.shared = shared,
|
||||
.master = master,
|
||||
.propagate_from = propagate_from,
|
||||
},
|
||||
.type {type},
|
||||
.source {source},
|
||||
.fs_option {fs_option},
|
||||
});
|
||||
return true;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
sDIR make_dir(DIR *dp) {
|
||||
return sDIR(dp, [](DIR *dp){ return dp ? closedir(dp) : 1; });
|
||||
}
|
||||
|
||||
sFILE make_file(FILE *fp) {
|
||||
return sFILE(fp, [](FILE *fp){ return fp ? fclose(fp) : 1; });
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
#include <android/log.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "logging.h"
|
||||
#include "socket_utils.h"
|
||||
|
||||
namespace logging {
|
||||
static int logfd = -1;
|
||||
|
||||
void setfd(int fd) {
|
||||
close(logfd);
|
||||
logfd = fd;
|
||||
}
|
||||
|
||||
int getfd() {
|
||||
return logfd;
|
||||
}
|
||||
|
||||
void log(int prio, const char* tag, const char* fmt, ...) {
|
||||
if (logfd == -1) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
__android_log_vprint(prio, tag, fmt, ap);
|
||||
va_end(ap);
|
||||
} else {
|
||||
char buf[BUFSIZ];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(buf, sizeof(buf), fmt, ap);
|
||||
va_end(ap);
|
||||
socket_utils::write_u8(logfd, prio);
|
||||
socket_utils::write_string(logfd, tag);
|
||||
socket_utils::write_string(logfd, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
14
loader/src/common/misc.c
Normal file
14
loader/src/common/misc.c
Normal file
@@ -0,0 +1,14 @@
|
||||
int parse_int(const char *str) {
|
||||
int val = 0;
|
||||
|
||||
char *c = (char *)str;
|
||||
while (*c) {
|
||||
if (*c > '9' || *c < '0')
|
||||
return -1;
|
||||
|
||||
val = val * 10 + *c - '0';
|
||||
c++;
|
||||
}
|
||||
|
||||
return val;
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
#include "misc.hpp"
|
||||
|
||||
int new_daemon_thread(thread_entry entry, void *arg) {
|
||||
pthread_t thread;
|
||||
pthread_attr_t attr;
|
||||
pthread_attr_init(&attr);
|
||||
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
||||
errno = pthread_create(&thread, &attr, entry, arg);
|
||||
if (errno) {
|
||||
PLOGE("pthread_create");
|
||||
}
|
||||
return errno;
|
||||
}
|
||||
|
||||
int parse_int(std::string_view s) {
|
||||
int val = 0;
|
||||
for (char c : s) {
|
||||
if (!c) break;
|
||||
if (c > '9' || c < '0')
|
||||
return -1;
|
||||
val = val * 10 + c - '0';
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
std::list<std::string> split_str(std::string_view s, std::string_view delimiter) {
|
||||
std::list<std::string> ret;
|
||||
size_t pos = 0;
|
||||
while (pos < s.size()) {
|
||||
auto next = s.find(delimiter, pos);
|
||||
if (next == std::string_view::npos) {
|
||||
ret.emplace_back(s.substr(pos));
|
||||
break;
|
||||
}
|
||||
ret.emplace_back(s.substr(pos, next - pos));
|
||||
pos = next + delimiter.size();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::string join_str(const std::list<std::string>& list, std::string_view delimiter) {
|
||||
std::string ret;
|
||||
for (auto& s : list) {
|
||||
if (!ret.empty())
|
||||
ret += delimiter;
|
||||
ret += s;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
95
loader/src/common/socket_utils.c
Normal file
95
loader/src/common/socket_utils.c
Normal file
@@ -0,0 +1,95 @@
|
||||
#include <stdlib.h>
|
||||
#include <errno.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#include "logging.h"
|
||||
|
||||
#include "socket_utils.h"
|
||||
|
||||
/* TODO: Standardize how to log errors */
|
||||
int read_fd(int fd) {
|
||||
char cmsgbuf[CMSG_SPACE(sizeof(int))];
|
||||
|
||||
int cnt = 1;
|
||||
struct iovec iov = {
|
||||
.iov_base = &cnt,
|
||||
.iov_len = sizeof(cnt)
|
||||
};
|
||||
|
||||
struct msghdr msg = {
|
||||
.msg_iov = &iov,
|
||||
.msg_iovlen = 1,
|
||||
.msg_control = cmsgbuf,
|
||||
.msg_controllen = sizeof(cmsgbuf)
|
||||
};
|
||||
|
||||
ssize_t ret = recvmsg(fd, &msg, MSG_WAITALL);
|
||||
if (ret == -1) {
|
||||
PLOGE("recvmsg");
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
|
||||
if (cmsg == NULL) {
|
||||
PLOGE("CMSG_FIRSTHDR");
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int sendfd;
|
||||
memcpy(&sendfd, CMSG_DATA(cmsg), sizeof(int));
|
||||
|
||||
return sendfd;
|
||||
}
|
||||
|
||||
char *read_string(int fd) {
|
||||
size_t str_len = 0;
|
||||
ssize_t read_bytes = read(fd, &str_len, 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 NULL;
|
||||
}
|
||||
|
||||
char *buf = malloc(str_len + 1);
|
||||
if (buf == NULL) {
|
||||
PLOGE("allocate memory for string");
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
read_bytes = read(fd, buf, 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);
|
||||
|
||||
free(buf);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (str_len > 0) buf[str_len] = '\0';
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
#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(uint8_t)
|
||||
read_func(uint8_t)
|
||||
|
||||
write_func(uint32_t)
|
||||
read_func(uint32_t)
|
||||
|
||||
write_func(size_t)
|
||||
read_func(size_t)
|
||||
@@ -1,137 +0,0 @@
|
||||
#include <cstddef>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
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 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;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline bool write_exact(int fd, T val) {
|
||||
return sizeof(T) == xwrite(fd, &val, sizeof(T));
|
||||
}
|
||||
|
||||
uint8_t read_u8(int fd) {
|
||||
return read_exact_or<uint8_t>(fd, 0);
|
||||
}
|
||||
|
||||
uint32_t read_u32(int fd) {
|
||||
return read_exact_or<uint32_t>(fd, 0);
|
||||
}
|
||||
|
||||
size_t read_usize(int fd) {
|
||||
return read_exact_or<size_t>(fd, 0);
|
||||
}
|
||||
|
||||
bool write_usize(int fd, size_t val) {
|
||||
return write_exact<size_t>(fd, val);
|
||||
}
|
||||
|
||||
std::string read_string(int fd) {
|
||||
size_t len = read_usize(fd);
|
||||
|
||||
char buf[len + 1];
|
||||
xread(fd, buf, len);
|
||||
|
||||
buf[len] = '\0';
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
bool write_u8(int fd, uint8_t val) {
|
||||
return write_exact<uint8_t>(fd, val);
|
||||
}
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
xrecvmsg(sockfd, &msg, MSG_WAITALL);
|
||||
cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
return CMSG_DATA(cmsg);
|
||||
}
|
||||
|
||||
int recv_fd(int sockfd) {
|
||||
char cmsgbuf[CMSG_SPACE(sizeof(int))];
|
||||
|
||||
void* data = recv_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), 1);
|
||||
if (data == nullptr) return -1;
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
2
loader/src/external/lsplt
vendored
2
loader/src/external/lsplt
vendored
Submodule loader/src/external/lsplt updated: 5d2b820cf9...984804293e
@@ -1,106 +1,91 @@
|
||||
#pragma once
|
||||
#ifndef DAEMON_H
|
||||
#define DAEMON_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
#include <string_view>
|
||||
#include <string>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__LP64__)
|
||||
# define LP_SELECT(lp32, lp64) lp64
|
||||
#ifdef __LP64__
|
||||
#define LP_SELECT(lp32, lp64) lp64
|
||||
#else
|
||||
# define LP_SELECT(lp32, lp64) lp32
|
||||
#define LP_SELECT(lp32, lp64) lp32
|
||||
#endif
|
||||
|
||||
constexpr auto kCPSocketName = "/" LP_SELECT("cp32", "cp64") ".sock";
|
||||
#define SOCKET_FILE_NAME LP_SELECT("cp32", "cp64") ".sock"
|
||||
|
||||
class UniqueFd {
|
||||
using Fd = int;
|
||||
public:
|
||||
UniqueFd() = default;
|
||||
|
||||
UniqueFd(Fd fd) : fd_(fd) {}
|
||||
|
||||
~UniqueFd() { if (fd_ >= 0) close(fd_); }
|
||||
|
||||
// Disallow copy
|
||||
UniqueFd(const UniqueFd&) = delete;
|
||||
|
||||
UniqueFd& operator=(const UniqueFd&) = delete;
|
||||
|
||||
// Allow move
|
||||
UniqueFd(UniqueFd&& other) { std::swap(fd_, other.fd_); }
|
||||
|
||||
UniqueFd& operator=(UniqueFd&& other) {
|
||||
std::swap(fd_, other.fd_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Implict cast to Fd
|
||||
operator const Fd&() const { return fd_; }
|
||||
|
||||
private:
|
||||
Fd fd_ = -1;
|
||||
enum rezygiskd_actions {
|
||||
PingHeartbeat,
|
||||
GetProcessFlags,
|
||||
GetInfo,
|
||||
ReadModules,
|
||||
RequestCompanionSocket,
|
||||
GetModuleDir,
|
||||
ZygoteRestart,
|
||||
SystemServerStarted,
|
||||
UpdateMountNamespace
|
||||
};
|
||||
|
||||
struct zygote_modules {
|
||||
struct zygisk_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
|
||||
enum root_impl {
|
||||
ROOT_IMPL_NONE,
|
||||
ROOT_IMPL_APATCH,
|
||||
ROOT_IMPL_KERNELSU,
|
||||
ROOT_IMPL_MAGISK
|
||||
};
|
||||
|
||||
struct zygote_info {
|
||||
struct zygote_modules *modules;
|
||||
enum zygote_root_impl root_impl;
|
||||
struct rezygisk_info {
|
||||
struct zygisk_modules *modules;
|
||||
enum root_impl root_impl;
|
||||
pid_t pid;
|
||||
bool running;
|
||||
};
|
||||
|
||||
namespace zygiskd {
|
||||
enum mount_namespace_state {
|
||||
Clean,
|
||||
Rooted,
|
||||
Module
|
||||
};
|
||||
|
||||
struct Module {
|
||||
std::string name;
|
||||
UniqueFd memfd;
|
||||
#define TMP_PATH "/data/adb/rezygisk"
|
||||
|
||||
inline explicit Module(std::string name, int memfd) : name(name), memfd(memfd) {}
|
||||
};
|
||||
|
||||
enum class SocketAction {
|
||||
PingHeartBeat,
|
||||
RequestLogcatFd,
|
||||
GetProcessFlags,
|
||||
GetInfo,
|
||||
ReadModules,
|
||||
RequestCompanionSocket,
|
||||
GetModuleDir,
|
||||
ZygoteRestart,
|
||||
SystemServerStarted,
|
||||
};
|
||||
|
||||
void Init(const char *path);
|
||||
|
||||
std::string GetTmpPath();
|
||||
|
||||
bool PingHeartbeat();
|
||||
|
||||
int RequestLogcatFd();
|
||||
|
||||
std::vector<Module> ReadModules();
|
||||
|
||||
uint32_t GetProcessFlags(uid_t uid);
|
||||
|
||||
int ConnectCompanion(size_t index);
|
||||
|
||||
int GetModuleDir(size_t index);
|
||||
|
||||
void ZygoteRestart();
|
||||
|
||||
void SystemServerStarted();
|
||||
|
||||
void GetInfo(struct zygote_info *info);
|
||||
static inline const char *rezygiskd_get_path() {
|
||||
return TMP_PATH;
|
||||
}
|
||||
|
||||
int rezygiskd_connect(uint8_t retry);
|
||||
|
||||
bool rezygiskd_ping();
|
||||
|
||||
uint32_t rezygiskd_get_process_flags(uid_t uid);
|
||||
|
||||
void rezygiskd_get_info(struct rezygisk_info *info);
|
||||
|
||||
void free_rezygisk_info(struct rezygisk_info *info);
|
||||
|
||||
bool rezygiskd_read_modules(struct zygisk_modules *modules);
|
||||
|
||||
void free_modules(struct zygisk_modules *modules);
|
||||
|
||||
int rezygiskd_connect_companion(size_t index);
|
||||
|
||||
int rezygiskd_get_module_dir(size_t index);
|
||||
|
||||
void rezygiskd_zygote_restart();
|
||||
|
||||
void rezygiskd_system_server_started();
|
||||
|
||||
bool rezygiskd_update_mns(enum mount_namespace_state nms_state, char *buf, size_t buf_size);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* DAEMON_H */
|
||||
@@ -1,7 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <dlfcn.h>
|
||||
|
||||
void *DlopenExt(const char *path, int flags);
|
||||
|
||||
void *DlopenMem(int memfd, int flags);
|
||||
@@ -1,136 +1,74 @@
|
||||
/*
|
||||
* 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
|
||||
#ifndef ELF_UTIL_H
|
||||
#define ELF_UTIL_H
|
||||
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <string.h>
|
||||
#include <link.h>
|
||||
#include <linux/elf.h>
|
||||
#include <sys/types.h>
|
||||
#include <link.h>
|
||||
#include <string>
|
||||
|
||||
#define SHT_GNU_HASH 0x6ffffff6
|
||||
|
||||
namespace SandHook {
|
||||
class ElfImg {
|
||||
public:
|
||||
struct symtabs {
|
||||
char *name;
|
||||
ElfW(Sym) *sym;
|
||||
};
|
||||
|
||||
ElfImg(std::string_view elf);
|
||||
typedef struct {
|
||||
char *elf;
|
||||
void *base;
|
||||
char *buffer;
|
||||
off_t size;
|
||||
off_t bias;
|
||||
ElfW(Ehdr) *header;
|
||||
ElfW(Shdr) *section_header;
|
||||
ElfW(Shdr) *symtab;
|
||||
ElfW(Shdr) *strtab;
|
||||
ElfW(Shdr) *dynsym;
|
||||
ElfW(Sym) *symtab_start;
|
||||
ElfW(Sym) *dynsym_start;
|
||||
ElfW(Sym) *strtab_start;
|
||||
ElfW(Off) symtab_count;
|
||||
ElfW(Off) symstr_offset;
|
||||
ElfW(Off) symstr_offset_for_symtab;
|
||||
ElfW(Off) symtab_offset;
|
||||
ElfW(Off) dynsym_offset;
|
||||
ElfW(Off) symtab_size;
|
||||
|
||||
constexpr ElfW(Addr) getSymbOffset(std::string_view name) const {
|
||||
return getSymbOffset(name, GnuHash(name), ElfHash(name));
|
||||
}
|
||||
uint32_t nbucket_;
|
||||
uint32_t *bucket_;
|
||||
uint32_t *chain_;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
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_;
|
||||
|
||||
template<typename T>
|
||||
constexpr T getSymbAddress(std::string_view name) const {
|
||||
return reinterpret_cast<T>(getSymbAddress(name));
|
||||
}
|
||||
struct symtabs *symtabs_;
|
||||
} ElfImg;
|
||||
|
||||
bool isValid() const {
|
||||
return base != nullptr;
|
||||
}
|
||||
void ElfImg_destroy(ElfImg *img);
|
||||
|
||||
const std::string name() const {
|
||||
return elf;
|
||||
}
|
||||
ElfImg *ElfImg_create(const char *elf);
|
||||
|
||||
~ElfImg();
|
||||
ElfW(Addr) ElfLookup(ElfImg *restrict img, const char *restrict name, uint32_t hash);
|
||||
|
||||
private:
|
||||
ElfW(Addr) getSymbOffset(std::string_view name, uint32_t gnu_hash, uint32_t elf_hash) const;
|
||||
ElfW(Addr) GnuLookup(ElfImg *restrict img, const char *restrict name, uint32_t hash);
|
||||
|
||||
ElfW(Addr) ElfLookup(std::string_view name, uint32_t hash) const;
|
||||
ElfW(Addr) LinearLookup(ElfImg *restrict img, const char *restrict name);
|
||||
|
||||
ElfW(Addr) GnuLookup(std::string_view name, uint32_t hash) const;
|
||||
ElfW(Addr) LinearLookupByPrefix(ElfImg *restrict img, const char *name);
|
||||
|
||||
ElfW(Addr) LinearLookup(std::string_view name) const;
|
||||
int dl_cb(struct dl_phdr_info *info, size_t size, void *data);
|
||||
|
||||
constexpr static uint32_t ElfHash(std::string_view name);
|
||||
ElfW(Addr) getSymbOffset(ElfImg *img, const char *name);
|
||||
|
||||
constexpr static uint32_t GnuHash(std::string_view name);
|
||||
ElfW(Addr) getSymbAddress(ElfImg *img, const char *name);
|
||||
|
||||
bool findModuleBase();
|
||||
ElfW(Addr) getSymbAddressByPrefix(ElfImg *img, const char *prefix);
|
||||
|
||||
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;
|
||||
void *getSymbValueByPrefix(ElfImg *img, const char *prefix);
|
||||
|
||||
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
|
||||
#endif /* ELF_UTIL_H */
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
#include <dirent.h>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct mount_info {
|
||||
unsigned int id;
|
||||
unsigned int parent;
|
||||
dev_t device;
|
||||
std::string root;
|
||||
std::string target;
|
||||
std::string vfs_option;
|
||||
struct {
|
||||
unsigned int shared;
|
||||
unsigned int master;
|
||||
unsigned int propagate_from;
|
||||
} optional;
|
||||
std::string type;
|
||||
std::string source;
|
||||
std::string fs_option;
|
||||
};
|
||||
|
||||
void file_readline(bool trim, FILE *fp, const std::function<bool(std::string_view)> &fn);
|
||||
void file_readline(bool trim, const char *file, const std::function<bool(std::string_view)> &fn);
|
||||
void file_readline(const char *file, const std::function<bool(std::string_view)> &fn);
|
||||
|
||||
std::vector<mount_info> parse_mount_info(const char *pid);
|
||||
|
||||
using sFILE = std::unique_ptr<FILE, decltype(&fclose)>;
|
||||
using sDIR = std::unique_ptr<DIR, decltype(&closedir)>;
|
||||
sDIR make_dir(DIR *dp);
|
||||
sFILE make_file(FILE *fp);
|
||||
|
||||
static inline sDIR open_dir(const char *path) {
|
||||
return make_dir(opendir(path));
|
||||
}
|
||||
|
||||
static inline sDIR xopen_dir(const char *path) {
|
||||
return make_dir(opendir(path));
|
||||
}
|
||||
|
||||
static inline sDIR xopen_dir(int dirfd) {
|
||||
return make_dir(fdopendir(dirfd));
|
||||
}
|
||||
|
||||
static inline sFILE open_file(const char *path, const char *mode) {
|
||||
return make_file(fopen(path, mode));
|
||||
}
|
||||
|
||||
static inline sFILE xopen_file(const char *path, const char *mode) {
|
||||
return make_file(fopen(path, mode));
|
||||
}
|
||||
|
||||
static inline sFILE xopen_file(int fd, const char *mode) {
|
||||
return make_file(fdopen(fd, mode));
|
||||
}
|
||||
@@ -1,35 +1,30 @@
|
||||
#pragma once
|
||||
#ifndef LOGGING_H
|
||||
#define LOGGING_H
|
||||
|
||||
#include <android/log.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifndef LOG_TAG
|
||||
#if defined(__LP64__)
|
||||
# define LOG_TAG "zygisk-core64"
|
||||
#else
|
||||
# define LOG_TAG "zygisk-core32"
|
||||
#endif
|
||||
#ifdef __LP64__
|
||||
#define LOG_TAG "zygisk-core64"
|
||||
#else
|
||||
#define LOG_TAG "zygisk-core32"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef NDEBUG
|
||||
#define LOGD(...) logging::log(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGV(...) logging::log(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
|
||||
#else
|
||||
#define LOGD(...)
|
||||
#define LOGV(...)
|
||||
#define LOGD(...)
|
||||
#define LOGV(...)
|
||||
#endif
|
||||
#define LOGI(...) logging::log(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGW(...) logging::log(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGE(...) logging::log(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGF(...) logging::log(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__)
|
||||
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__)
|
||||
#define PLOGE(fmt, args...) LOGE(fmt " failed with %d: %s", ##args, errno, strerror(errno))
|
||||
|
||||
namespace logging {
|
||||
void setfd(int fd);
|
||||
|
||||
int getfd();
|
||||
|
||||
[[gnu::format(printf, 3, 4)]]
|
||||
void log(int prio, const char* tag, const char* fmt, ...);
|
||||
}
|
||||
#endif /* LOGGING_H */
|
||||
17
loader/src/include/misc.h
Normal file
17
loader/src/include/misc.h
Normal file
@@ -0,0 +1,17 @@
|
||||
#ifndef MISC_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif /* __cplusplus */
|
||||
|
||||
/*
|
||||
* Bionic's atoi runs through strtol().
|
||||
* Use our own implementation for faster conversion.
|
||||
*/
|
||||
int parse_int(const char *str);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* MISC_H */
|
||||
@@ -1,98 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <pthread.h>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "logging.h"
|
||||
|
||||
#define DISALLOW_COPY_AND_MOVE(clazz) \
|
||||
clazz(const clazz &) = delete; \
|
||||
clazz(clazz &&) = delete;
|
||||
|
||||
class mutex_guard {
|
||||
DISALLOW_COPY_AND_MOVE(mutex_guard)
|
||||
public:
|
||||
explicit mutex_guard(pthread_mutex_t &m): mutex(&m) {
|
||||
pthread_mutex_lock(mutex);
|
||||
}
|
||||
void unlock() {
|
||||
pthread_mutex_unlock(mutex);
|
||||
mutex = nullptr;
|
||||
}
|
||||
~mutex_guard() {
|
||||
if (mutex) pthread_mutex_unlock(mutex);
|
||||
}
|
||||
private:
|
||||
pthread_mutex_t *mutex;
|
||||
};
|
||||
|
||||
using thread_entry = void *(*)(void *);
|
||||
int new_daemon_thread(thread_entry entry, void *arg);
|
||||
|
||||
static inline bool str_contains(std::string_view s, std::string_view ss) {
|
||||
return s.find(ss) != std::string_view::npos;
|
||||
}
|
||||
|
||||
template<typename T, typename Impl>
|
||||
class stateless_allocator {
|
||||
public:
|
||||
using value_type = T;
|
||||
T *allocate(size_t num) { return static_cast<T*>(Impl::allocate(sizeof(T) * num)); }
|
||||
void deallocate(T *ptr, size_t num) { Impl::deallocate(ptr, sizeof(T) * num); }
|
||||
stateless_allocator() = default;
|
||||
stateless_allocator(const stateless_allocator&) = default;
|
||||
stateless_allocator(stateless_allocator&&) = default;
|
||||
template <typename U>
|
||||
stateless_allocator(const stateless_allocator<U, Impl>&) {}
|
||||
bool operator==(const stateless_allocator&) { return true; }
|
||||
bool operator!=(const stateless_allocator&) { return false; }
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class reversed_container {
|
||||
public:
|
||||
reversed_container(T &base) : base(base) {}
|
||||
decltype(std::declval<T>().rbegin()) begin() { return base.rbegin(); }
|
||||
decltype(std::declval<T>().crbegin()) begin() const { return base.crbegin(); }
|
||||
decltype(std::declval<T>().crbegin()) cbegin() const { return base.crbegin(); }
|
||||
decltype(std::declval<T>().rend()) end() { return base.rend(); }
|
||||
decltype(std::declval<T>().crend()) end() const { return base.crend(); }
|
||||
decltype(std::declval<T>().crend()) cend() const { return base.crend(); }
|
||||
private:
|
||||
T &base;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
reversed_container<T> reversed(T &base) {
|
||||
return reversed_container<T>(base);
|
||||
}
|
||||
|
||||
template<class T>
|
||||
static inline void default_new(T *&p) { p = new T(); }
|
||||
|
||||
template<class T>
|
||||
static inline void default_new(std::unique_ptr<T> &p) { p.reset(new T()); }
|
||||
|
||||
struct StringCmp {
|
||||
using is_transparent = void;
|
||||
bool operator()(std::string_view a, std::string_view b) const { return a < b; }
|
||||
};
|
||||
|
||||
/*
|
||||
* Bionic's atoi runs through strtol().
|
||||
* Use our own implementation for faster conversion.
|
||||
*/
|
||||
int parse_int(std::string_view s);
|
||||
|
||||
std::list<std::string> split_str(std::string_view s, std::string_view delimiter);
|
||||
|
||||
std::string join_str(const std::list<std::string>& list, std::string_view delimiter);
|
||||
|
||||
template <typename T>
|
||||
static inline T align_to(T v, int a) {
|
||||
static_assert(std::is_integral<T>::value);
|
||||
return (v + a - 1) / a * a;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <android/api-level.h>
|
||||
#include <cstdint>
|
||||
|
||||
template<unsigned>
|
||||
struct NativeBridgeCallbacks;
|
||||
|
||||
template<>
|
||||
struct NativeBridgeCallbacks<__ANDROID_API_Q__> {
|
||||
[[maybe_unused]] uint32_t version;
|
||||
[[maybe_unused]] void *initialize;
|
||||
[[maybe_unused]] void *loadLibrary;
|
||||
[[maybe_unused]] void *getTrampoline;
|
||||
[[maybe_unused]] void *isSupported;
|
||||
[[maybe_unused]] void *getAppEnv;
|
||||
[[maybe_unused]] void *isCompatibleWith;
|
||||
[[maybe_unused]] void *getSignalHandler;
|
||||
[[maybe_unused]] void *unloadLibrary;
|
||||
[[maybe_unused]] void *getError;
|
||||
[[maybe_unused]] void *isPathSupported;
|
||||
[[maybe_unused]] void *initAnonymousNamespace;
|
||||
[[maybe_unused]] void *createNamespace;
|
||||
[[maybe_unused]] void *linkNamespaces;
|
||||
[[maybe_unused]] void *loadLibraryExt;
|
||||
[[maybe_unused]] void *getVendorNamespace;
|
||||
[[maybe_unused]] void *getExportedNamespace;
|
||||
};
|
||||
|
||||
template<>
|
||||
struct NativeBridgeCallbacks<__ANDROID_API_R__> : NativeBridgeCallbacks<__ANDROID_API_Q__> {
|
||||
[[maybe_unused]] void *preZygoteFork;
|
||||
};
|
||||
@@ -1,31 +1,25 @@
|
||||
#pragma once
|
||||
#ifndef SOCKET_UTILS_H
|
||||
#define SOCKET_UTILS_H
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "logging.h"
|
||||
int read_fd(int fd);
|
||||
|
||||
char *read_string(int fd);
|
||||
|
||||
namespace socket_utils {
|
||||
#define write_func_def(type) \
|
||||
ssize_t write_## type(int fd, type val)
|
||||
|
||||
ssize_t xread(int fd, void *buf, size_t count);
|
||||
#define read_func_def(type) \
|
||||
ssize_t read_## type(int fd, type *val)
|
||||
|
||||
size_t xwrite(int fd, const void *buf, size_t count);
|
||||
write_func_def(uint8_t);
|
||||
read_func_def(uint8_t);
|
||||
|
||||
uint8_t read_u8(int fd);
|
||||
write_func_def(uint32_t);
|
||||
read_func_def(uint32_t);
|
||||
|
||||
uint32_t read_u32(int fd);
|
||||
write_func_def(size_t);
|
||||
read_func_def(size_t);
|
||||
|
||||
size_t read_usize(int fd);
|
||||
|
||||
std::string read_string(int fd);
|
||||
|
||||
bool write_u8(int fd, uint8_t val);
|
||||
|
||||
bool write_u32(int fd, uint32_t val);
|
||||
|
||||
int recv_fd(int fd);
|
||||
|
||||
bool write_usize(int fd, size_t val);
|
||||
|
||||
bool write_string(int fd, std::string_view str);
|
||||
}
|
||||
#endif /* SOCKET_UTILS_H */
|
||||
@@ -1,103 +0,0 @@
|
||||
//
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include "logging.h"
|
||||
#include "jni_helper.hpp"
|
||||
|
||||
template <typename T>
|
||||
|
||||
@@ -1,27 +1,26 @@
|
||||
#include "daemon.h"
|
||||
#include "logging.h"
|
||||
#include "zygisk.hpp"
|
||||
#include "module.hpp"
|
||||
|
||||
using namespace std;
|
||||
|
||||
void *self_handle = nullptr;
|
||||
void *start_addr = nullptr;
|
||||
size_t block_size = 0;
|
||||
|
||||
extern "C" [[gnu::visibility("default")]]
|
||||
void entry(void* handle, const char* path) {
|
||||
LOGI("Zygisk library injected, version %s", ZKSU_VERSION);
|
||||
self_handle = handle;
|
||||
zygiskd::Init(path);
|
||||
void entry(void* addr, size_t size, const char* path) {
|
||||
LOGD("Zygisk library injected, version %s", ZKSU_VERSION);
|
||||
|
||||
if (!zygiskd::PingHeartbeat()) {
|
||||
start_addr = addr;
|
||||
block_size = size;
|
||||
|
||||
if (!rezygiskd_ping()) {
|
||||
LOGE("Zygisk daemon is not running");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
#ifdef NDEBUG
|
||||
logging::setfd(zygiskd::RequestLogcatFd());
|
||||
#endif
|
||||
|
||||
LOGI("Start hooking");
|
||||
LOGD("start plt hooking");
|
||||
hook_functions();
|
||||
clean_trace(path, 1, 0, false);
|
||||
}
|
||||
|
||||
@@ -77,6 +77,7 @@ jintArray = JArray(jint)
|
||||
jstring = JType('jstring', 'Ljava/lang/String;')
|
||||
jboolean = JType('jboolean', 'Z')
|
||||
jlong = JType('jlong', 'J')
|
||||
jlongArray = JArray(jlong)
|
||||
void = JType('void', 'V')
|
||||
|
||||
class ForkAndSpec(JNIHook):
|
||||
@@ -210,6 +211,17 @@ server_l = ForkServer('l', [uid, gid, gids, runtime_flags, rlimits,
|
||||
server_samsung_q = ForkServer('samsung_q', [uid, gid, gids, runtime_flags, Anon(jint), Anon(jint), rlimits,
|
||||
permitted_capabilities, effective_capabilities])
|
||||
|
||||
# GrapheneOS Android 14 Support
|
||||
server_grapheneos_u = ForkServer('grapheneos_u', [uid, gid, gids, runtime_flags, rlimits, permitted_capabilities, effective_capabilities])
|
||||
|
||||
fas_grapheneos_u = ForkAndSpec('grapheneos_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, Anon(jlongArray)])
|
||||
|
||||
spec_grapheneos_u = SpecApp('grapheneos_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, Anon(jlongArray)])
|
||||
|
||||
hook_map = {}
|
||||
|
||||
def gen_jni_def(clz, methods):
|
||||
@@ -245,13 +257,13 @@ with open('jni_hooks.hpp', 'w') as f:
|
||||
|
||||
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]
|
||||
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, fas_grapheneos_u]
|
||||
f.write(gen_jni_def(zygote, methods))
|
||||
|
||||
methods = [spec_q, spec_q_alt, spec_r, spec_u, spec_samsung_q]
|
||||
methods = [spec_q, spec_q_alt, spec_r, spec_u, spec_samsung_q, spec_grapheneos_u]
|
||||
f.write(gen_jni_def(zygote, methods))
|
||||
|
||||
methods = [server_l, server_samsung_q]
|
||||
methods = [server_l, server_samsung_q, server_grapheneos_u]
|
||||
f.write(gen_jni_def(zygote, methods))
|
||||
|
||||
f.write('\n} // namespace\n')
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#include <android/dlext.h>
|
||||
#include <sys/mount.h>
|
||||
#include <dlfcn.h>
|
||||
#include <regex.h>
|
||||
@@ -6,23 +5,26 @@
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <array>
|
||||
#include <vector>
|
||||
|
||||
#include <lsplt.hpp>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <dirent.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "dl.h"
|
||||
#include <unistd.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#include "daemon.h"
|
||||
#include "zygisk.hpp"
|
||||
#include "module.hpp"
|
||||
#include "files.hpp"
|
||||
#include "misc.hpp"
|
||||
#include "misc.h"
|
||||
|
||||
#include "solist.hpp"
|
||||
#include "solist.h"
|
||||
|
||||
#include "art_method.hpp"
|
||||
|
||||
@@ -120,8 +122,9 @@ struct ZygiskContext {
|
||||
|
||||
// Global variables
|
||||
vector<tuple<dev_t, ino_t, const char *, void **>> *plt_hook_list;
|
||||
map<string, vector<JNINativeMethod>, StringCmp> *jni_hook_list;
|
||||
map<string, vector<JNINativeMethod>> *jni_hook_list;
|
||||
bool should_unmap_zygisk = false;
|
||||
std::vector<lsplt::MapInfo> cached_map_infos = {};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -136,6 +139,36 @@ DCL_HOOK_FUNC(int, fork) {
|
||||
return (g_ctx && g_ctx->pid >= 0) ? g_ctx->pid : old_fork();
|
||||
}
|
||||
|
||||
bool update_mnt_ns(enum mount_namespace_state mns_state, bool dry_run) {
|
||||
char ns_path[PATH_MAX];
|
||||
if (rezygiskd_update_mns(mns_state, ns_path, sizeof(ns_path)) == false) {
|
||||
PLOGE("Failed to update mount namespace");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (dry_run) return true;
|
||||
|
||||
int updated_ns = open(ns_path, O_RDONLY);
|
||||
if (updated_ns == -1) {
|
||||
PLOGE("Failed to open mount namespace [%s]", ns_path);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
LOGD("set mount namespace to [%s] fd=[%d]\n", ns_path, updated_ns);
|
||||
if (setns(updated_ns, CLONE_NEWNS) == -1) {
|
||||
PLOGE("Failed to set mount namespace [%s]", ns_path);
|
||||
close(updated_ns);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
close(updated_ns);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Unmount stuffs in the process's private mount namespace
|
||||
DCL_HOOK_FUNC(int, unshare, int flags) {
|
||||
int res = old_unshare(flags);
|
||||
@@ -143,55 +176,44 @@ DCL_HOOK_FUNC(int, unshare, int flags) {
|
||||
// For some unknown reason, unmounting app_process in SysUI can break.
|
||||
// This is reproducible on the official AVD running API 26 and 27.
|
||||
// Simply avoid doing any unmounts for SysUI to avoid potential issues.
|
||||
(g_ctx->info_flags & PROCESS_IS_SYS_UI) == 0) {
|
||||
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();
|
||||
}
|
||||
!g_ctx->flags[SERVER_FORK_AND_SPECIALIZE] && !(g_ctx->info_flags & PROCESS_IS_FIRST_STARTED)) {
|
||||
if (g_ctx->info_flags & (PROCESS_IS_MANAGER | PROCESS_GRANTED_ROOT)) {
|
||||
update_mnt_ns(Rooted, false);
|
||||
} else if (!(g_ctx->flags[DO_REVERT_UNMOUNT])) {
|
||||
update_mnt_ns(Module, false);
|
||||
}
|
||||
|
||||
/* Zygisksu changed: No umount app_process */
|
||||
|
||||
// Restore errno back to 0
|
||||
errno = 0;
|
||||
old_unshare(CLONE_NEWNS);
|
||||
}
|
||||
|
||||
/* INFO: To spoof the errno value */
|
||||
errno = 0;
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
// Close logd_fd if necessary to prevent crashing
|
||||
// For more info, check comments in zygisk_log_write
|
||||
DCL_HOOK_FUNC(void, android_log_close) {
|
||||
if (g_ctx == nullptr) {
|
||||
// Happens during un-managed fork like nativeForkApp, nativeForkUsap
|
||||
logging::setfd(-1);
|
||||
} else if (!g_ctx->flags[SKIP_FD_SANITIZATION]) {
|
||||
logging::setfd(-1);
|
||||
}
|
||||
old_android_log_close();
|
||||
}
|
||||
|
||||
// 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);
|
||||
// Instead, we hook `pthread_attr_setstacksize` which will be called when VM daemon threads start.
|
||||
DCL_HOOK_FUNC(int, pthread_attr_setstacksize, void *target, size_t size) {
|
||||
int res = old_pthread_attr_setstacksize((pthread_attr_t *)target, size);
|
||||
LOGV("Call pthread_attr_setstacksize in [tid, pid]: %d, %d", gettid(), getpid());
|
||||
|
||||
// Only perform unloading on the main thread
|
||||
if (gettid() != getpid())
|
||||
return res;
|
||||
|
||||
LOGV("pthread_attr_destroy");
|
||||
if (should_unmap_zygisk) {
|
||||
unhook_functions();
|
||||
cached_map_infos.clear();
|
||||
|
||||
if (should_unmap_zygisk) {
|
||||
// Because both `pthread_attr_destroy` and `dlclose` have the same function signature,
|
||||
// Because both `pthread_attr_setstacksize` 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);
|
||||
// `dlclose` will directly return to the caller of `pthread_attr_setstacksize`.
|
||||
LOGD("unmap libzygisk.so loaded at %p with size %zu", start_addr, block_size);
|
||||
|
||||
[[clang::musttail]] return munmap(start_addr, block_size);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,6 +226,8 @@ DCL_HOOK_FUNC(char *, strdup, const char *s) {
|
||||
if (strcmp(s, "com.android.internal.os.ZygoteInit") == 0) {
|
||||
LOGV("strdup %s", s);
|
||||
initialize_jni_hook();
|
||||
cached_map_infos = lsplt::MapInfo::Scan();
|
||||
LOGD("cached_map_infos updated");
|
||||
}
|
||||
|
||||
return old_strdup(s);
|
||||
@@ -267,7 +291,7 @@ 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()) {
|
||||
for (auto &map: cached_map_infos) {
|
||||
if (!map.path.ends_with("/libnativehelper.so")) continue;
|
||||
void *h = dlopen(map.path.data(), RTLD_LAZY);
|
||||
if (!h) {
|
||||
@@ -348,7 +372,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.pltHookCommit = []() { return lsplt::CommitHook(cached_map_infos); };
|
||||
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;
|
||||
@@ -366,8 +390,9 @@ void ZygiskContext::plt_hook_register(const char *regex, const char *symbol, voi
|
||||
regex_t re;
|
||||
if (regcomp(&re, regex, REG_NOSUB) != 0)
|
||||
return;
|
||||
mutex_guard lock(hook_info_lock);
|
||||
pthread_mutex_lock(&hook_info_lock);
|
||||
register_info.emplace_back(RegisterInfo{re, symbol, fn, backup});
|
||||
pthread_mutex_unlock(&hook_info_lock);
|
||||
}
|
||||
|
||||
void ZygiskContext::plt_hook_exclude(const char *regex, const char *symbol) {
|
||||
@@ -375,14 +400,15 @@ void ZygiskContext::plt_hook_exclude(const char *regex, const char *symbol) {
|
||||
regex_t re;
|
||||
if (regcomp(&re, regex, REG_NOSUB) != 0)
|
||||
return;
|
||||
mutex_guard lock(hook_info_lock);
|
||||
pthread_mutex_lock(&hook_info_lock);
|
||||
ignore_info.emplace_back(IgnoreInfo{re, symbol ?: ""});
|
||||
pthread_mutex_unlock(&hook_info_lock);
|
||||
}
|
||||
|
||||
void ZygiskContext::plt_hook_process_regex() {
|
||||
if (register_info.empty())
|
||||
return;
|
||||
for (auto &map : lsplt::MapInfo::Scan()) {
|
||||
for (auto &map : cached_map_infos) {
|
||||
if (map.offset != 0 || !map.is_private || !(map.perms & PROT_READ)) continue;
|
||||
for (auto ®: register_info) {
|
||||
if (regexec(®.regex, map.path.data(), 0, nullptr, 0) != 0)
|
||||
@@ -405,12 +431,14 @@ void ZygiskContext::plt_hook_process_regex() {
|
||||
|
||||
bool ZygiskContext::plt_hook_commit() {
|
||||
{
|
||||
mutex_guard lock(hook_info_lock);
|
||||
pthread_mutex_lock(&hook_info_lock);
|
||||
plt_hook_process_regex();
|
||||
register_info.clear();
|
||||
ignore_info.clear();
|
||||
pthread_mutex_unlock(&hook_info_lock);
|
||||
}
|
||||
return lsplt::CommitHook();
|
||||
|
||||
return lsplt::CommitHook(cached_map_infos);
|
||||
}
|
||||
|
||||
|
||||
@@ -431,12 +459,12 @@ bool ZygiskModule::valid() const {
|
||||
|
||||
/* Zygisksu changed: Use own zygiskd */
|
||||
int ZygiskModule::connectCompanion() const {
|
||||
return zygiskd::ConnectCompanion(id);
|
||||
return rezygiskd_connect_companion(id);
|
||||
}
|
||||
|
||||
/* Zygisksu changed: Use own zygiskd */
|
||||
int ZygiskModule::getModuleDir() const {
|
||||
return zygiskd::GetModuleDir(id);
|
||||
return rezygiskd_get_module_dir(id);
|
||||
}
|
||||
|
||||
void ZygiskModule::setOption(zygisk::Option opt) {
|
||||
@@ -466,25 +494,38 @@ int sigmask(int how, int signum) {
|
||||
}
|
||||
|
||||
void ZygiskContext::fork_pre() {
|
||||
// Do our own fork before loading any 3rd party code
|
||||
// First block SIGCHLD, unblock after original fork is done
|
||||
/* INFO: Do our own fork before loading any 3rd party code.
|
||||
First block SIGCHLD, unblock after original fork is done.
|
||||
*/
|
||||
sigmask(SIG_BLOCK, SIGCHLD);
|
||||
pid = old_fork();
|
||||
if (pid != 0 || flags[SKIP_FD_SANITIZATION])
|
||||
return;
|
||||
|
||||
// Record all open fds
|
||||
auto dir = xopen_dir("/proc/self/fd");
|
||||
for (dirent *entry; (entry = readdir(dir.get()));) {
|
||||
/* INFO: Record all open fds */
|
||||
DIR *dir = opendir("/proc/self/fd");
|
||||
if (dir == nullptr) {
|
||||
PLOGE("Failed to open /proc/self/fd");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
struct dirent *entry;
|
||||
while ((entry = readdir(dir))) {
|
||||
int fd = parse_int(entry->d_name);
|
||||
if (fd < 0 || fd >= MAX_FD_SIZE) {
|
||||
close(fd);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
allowed_fds[fd] = true;
|
||||
}
|
||||
// The dirfd should not be allowed
|
||||
allowed_fds[dirfd(dir.get())] = false;
|
||||
|
||||
/* INFO: The dirfd should not be allowed */
|
||||
allowed_fds[dirfd(dir)] = false;
|
||||
|
||||
closedir(dir);
|
||||
}
|
||||
|
||||
void ZygiskContext::sanitize_fds() {
|
||||
@@ -533,14 +574,23 @@ void ZygiskContext::sanitize_fds() {
|
||||
return;
|
||||
|
||||
// Close all forbidden fds to prevent crashing
|
||||
auto dir = open_dir("/proc/self/fd");
|
||||
int dfd = dirfd(dir.get());
|
||||
for (dirent *entry; (entry = readdir(dir.get()));) {
|
||||
int fd = parse_int(entry->d_name);
|
||||
if ((fd < 0 || fd >= MAX_FD_SIZE || !allowed_fds[fd]) && fd != dfd) {
|
||||
close(fd);
|
||||
}
|
||||
DIR *dir = opendir("/proc/self/fd");
|
||||
if (dir == nullptr) {
|
||||
PLOGE("Failed to open /proc/self/fd");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
int dfd = dirfd(dir);
|
||||
struct dirent *entry;
|
||||
while ((entry = readdir(dir))) {
|
||||
int fd = parse_int(entry->d_name);
|
||||
if (fd < 0 || fd < MAX_FD_SIZE || fd == dfd || allowed_fds[fd]) continue;
|
||||
|
||||
close(fd);
|
||||
}
|
||||
|
||||
closedir(dir);
|
||||
}
|
||||
|
||||
void ZygiskContext::fork_post() {
|
||||
@@ -551,134 +601,100 @@ void ZygiskContext::fork_post() {
|
||||
|
||||
/* Zygisksu changed: Load module fds */
|
||||
void ZygiskContext::run_modules_pre() {
|
||||
auto ms = zygiskd::ReadModules();
|
||||
auto size = ms.size();
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
auto& m = ms[i];
|
||||
if (void* handle = DlopenMem(m.memfd, RTLD_NOW);
|
||||
void* entry = handle ? dlsym(handle, "zygisk_module_entry") : nullptr) {
|
||||
modules.emplace_back(i, handle, entry);
|
||||
}
|
||||
struct zygisk_modules ms;
|
||||
if (rezygiskd_read_modules(&ms) == false) {
|
||||
LOGE("Failed to read modules from zygiskd");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < ms.modules_count; i++) {
|
||||
char *lib_path = ms.modules[i];
|
||||
|
||||
void *handle = dlopen(lib_path, RTLD_NOW);
|
||||
if (!handle) {
|
||||
LOGE("Failed to load module [%s]: %s", lib_path, dlerror());
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
for (auto &m : modules) {
|
||||
m.onLoad(env);
|
||||
if (flags[APP_SPECIALIZE]) {
|
||||
m.preAppSpecialize(args.app);
|
||||
} else if (flags[SERVER_FORK_AND_SPECIALIZE]) {
|
||||
m.preServerSpecialize(args.server);
|
||||
}
|
||||
void *entry = dlsym(handle, "zygisk_module_entry");
|
||||
if (!entry) {
|
||||
LOGE("Failed to find entry point in module [%s]: %s", lib_path, dlerror());
|
||||
|
||||
dlclose(handle);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
modules.emplace_back(i, handle, entry);
|
||||
}
|
||||
|
||||
free_modules(&ms);
|
||||
|
||||
for (auto &m : modules) {
|
||||
m.onLoad(env);
|
||||
|
||||
if (flags[APP_SPECIALIZE]) m.preAppSpecialize(args.app);
|
||||
else if (flags[SERVER_FORK_AND_SPECIALIZE]) m.preServerSpecialize(args.server);
|
||||
}
|
||||
}
|
||||
|
||||
void ZygiskContext::run_modules_post() {
|
||||
flags[POST_SPECIALIZE] = true;
|
||||
|
||||
size_t modules_unloaded = 0;
|
||||
for (const auto &m : modules) {
|
||||
if (flags[APP_SPECIALIZE]) {
|
||||
m.postAppSpecialize(args.app);
|
||||
} else if (flags[SERVER_FORK_AND_SPECIALIZE]) {
|
||||
m.postServerSpecialize(args.server);
|
||||
}
|
||||
m.tryUnload();
|
||||
if (flags[APP_SPECIALIZE]) m.postAppSpecialize(args.app);
|
||||
else if (flags[SERVER_FORK_AND_SPECIALIZE]) m.postServerSpecialize(args.server);
|
||||
|
||||
if (m.tryUnload()) modules_unloaded++;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
if (modules.size() > 0) {
|
||||
LOGD("modules unloaded: %zu/%zu", modules_unloaded, modules.size());
|
||||
clean_trace("/data/adb", modules.size(), modules_unloaded, true);
|
||||
}
|
||||
}
|
||||
|
||||
/* Zygisksu changed: Load module fds */
|
||||
void ZygiskContext::app_specialize_pre() {
|
||||
flags[APP_SPECIALIZE] = true;
|
||||
info_flags = zygiskd::GetProcessFlags(g_ctx->args.app->uid);
|
||||
|
||||
if ((info_flags & PROCESS_ON_DENYLIST) == PROCESS_ON_DENYLIST) {
|
||||
flags[DO_REVERT_UNMOUNT] = true;
|
||||
info_flags = rezygiskd_get_process_flags(g_ctx->args.app->uid);
|
||||
if (info_flags & PROCESS_IS_FIRST_STARTED) {
|
||||
/* INFO: To ensure we are really using a clean mount namespace, we use
|
||||
the first process it as reference for clean mount namespace,
|
||||
before it even does something, so that it will be clean yet
|
||||
with expected mounts.
|
||||
*/
|
||||
update_mnt_ns(Clean, 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.");
|
||||
LOGD("Manager process detected. Notifying that Zygisk has been enabled.");
|
||||
|
||||
/* INFO: This environment variable is related to Magisk Zygisk/Manager. It
|
||||
it used by Magisk's Zygisk to communicate to Magisk Manager whether
|
||||
Zygisk is working or not.
|
||||
|
||||
To allow Zygisk modules to both work properly and for the manager to
|
||||
identify Zygisk, being it not built-in, as working, we also set it. */
|
||||
setenv("ZYGISK_ENABLED", "1", 1);
|
||||
} else {
|
||||
run_modules_pre();
|
||||
|
||||
/* INFO: Modules only have two "start off" points from Zygisk, preSpecialize and
|
||||
postSpecialize. While preSpecialie in fact runs with Zygote (not superuser)
|
||||
privileges, in postSpecialize it will now be with lower permission, in
|
||||
the app's sandbox and therefore can move to a clean mount namespace after
|
||||
executing the modules preSpecialize.
|
||||
*/
|
||||
if ((info_flags & PROCESS_ON_DENYLIST) == PROCESS_ON_DENYLIST) {
|
||||
flags[DO_REVERT_UNMOUNT] = true;
|
||||
|
||||
update_mnt_ns(Clean, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -689,7 +705,6 @@ void ZygiskContext::app_specialize_post() {
|
||||
// Cleanups
|
||||
env->ReleaseStringUTFChars(args.app->nice_name, process);
|
||||
g_ctx = nullptr;
|
||||
logging::setfd(-1);
|
||||
}
|
||||
|
||||
bool ZygiskContext::exempt_fd(int fd) {
|
||||
@@ -722,11 +737,10 @@ void ZygiskContext::nativeForkSystemServer_pre() {
|
||||
flags[SERVER_FORK_AND_SPECIALIZE] = true;
|
||||
|
||||
fork_pre();
|
||||
if (pid != 0)
|
||||
return;
|
||||
|
||||
run_modules_pre();
|
||||
zygiskd::SystemServerStarted();
|
||||
if (is_child()) {
|
||||
run_modules_pre();
|
||||
rezygiskd_system_server_started();
|
||||
}
|
||||
|
||||
sanitize_fds();
|
||||
}
|
||||
@@ -742,17 +756,12 @@ void ZygiskContext::nativeForkSystemServer_post() {
|
||||
void ZygiskContext::nativeForkAndSpecialize_pre() {
|
||||
process = env->GetStringUTFChars(args.app->nice_name, nullptr);
|
||||
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+ */
|
||||
if (logging::getfd() != -1) {
|
||||
exempted_fds.push_back(logging::getfd());
|
||||
}
|
||||
|
||||
fork_pre();
|
||||
if (pid == 0) {
|
||||
if (pid == 0)
|
||||
app_specialize_pre();
|
||||
}
|
||||
|
||||
sanitize_fds();
|
||||
}
|
||||
|
||||
@@ -797,8 +806,8 @@ ZygiskContext::~ZygiskContext() {
|
||||
|
||||
} // namespace
|
||||
|
||||
static bool hook_commit() {
|
||||
if (lsplt::CommitHook()) {
|
||||
static bool hook_commit(std::vector<lsplt::MapInfo> &map_infos = cached_map_infos) {
|
||||
if (lsplt::CommitHook(map_infos)) {
|
||||
return true;
|
||||
} else {
|
||||
LOGE("plt_hook failed");
|
||||
@@ -820,17 +829,49 @@ static void hook_register(dev_t dev, ino_t inode, const char *symbol, void *new_
|
||||
#define PLT_HOOK_REGISTER(DEV, INODE, NAME) \
|
||||
PLT_HOOK_REGISTER_SYM(DEV, INODE, #NAME, NAME)
|
||||
|
||||
void clean_trace(const char* path, size_t load, size_t unload, bool spoof_maps) {
|
||||
LOGD("cleaning trace for path %s", path);
|
||||
|
||||
if (load > 0 || unload > 0) solist_reset_counters(load, unload);
|
||||
|
||||
LOGD("Dropping solist record for %s", path);
|
||||
|
||||
bool path_found = solist_drop_so_path(path);
|
||||
if (!path_found || !spoof_maps) return;
|
||||
|
||||
LOGD("spoofing virtual maps for %s", path);
|
||||
// spoofing map names is futile in Android, we do it simply
|
||||
// to avoid Zygisk detections based on string comparison
|
||||
for (auto &map : lsplt::MapInfo::Scan()) {
|
||||
if (strstr(map.path.c_str(), path) && strstr(map.path.c_str(), "libzygisk") == 0)
|
||||
{
|
||||
void *addr = (void *)map.start;
|
||||
size_t size = map.end - map.start;
|
||||
void *copy = mmap(nullptr, size, PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
|
||||
if (copy == MAP_FAILED) {
|
||||
LOGE("failed to backup block %s [%p, %p]", map.path.c_str(), addr, (void*)map.end);
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((map.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, map.perms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void hook_functions() {
|
||||
default_new(plt_hook_list);
|
||||
default_new(jni_hook_list);
|
||||
plt_hook_list = new vector<tuple<dev_t, ino_t, const char *, void **>>();
|
||||
jni_hook_list = new map<string, vector<JNINativeMethod>>();
|
||||
|
||||
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()) {
|
||||
cached_map_infos = lsplt::MapInfo::Scan();
|
||||
for (auto &map : cached_map_infos) {
|
||||
if (map.path.ends_with("libandroid_runtime.so")) {
|
||||
android_runtime_inode = map.inode;
|
||||
android_runtime_dev = map.dev;
|
||||
@@ -842,7 +883,6 @@ void hook_functions() {
|
||||
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, strdup);
|
||||
PLT_HOOK_REGISTER_SYM(android_runtime_dev, android_runtime_inode, "__android_log_close", android_log_close);
|
||||
hook_commit();
|
||||
|
||||
// Remove unhooked methods
|
||||
@@ -856,7 +896,7 @@ static void hook_unloader() {
|
||||
ino_t art_inode = 0;
|
||||
dev_t art_dev = 0;
|
||||
|
||||
for (auto &map : lsplt::MapInfo::Scan()) {
|
||||
for (auto &map : cached_map_infos) {
|
||||
if (map.path.ends_with("/libart.so")) {
|
||||
art_inode = map.inode;
|
||||
art_dev = map.dev;
|
||||
@@ -864,7 +904,13 @@ static void hook_unloader() {
|
||||
}
|
||||
}
|
||||
|
||||
PLT_HOOK_REGISTER(art_dev, art_inode, pthread_attr_destroy);
|
||||
if (art_dev == 0 || art_inode == 0) {
|
||||
LOGE("virtual map for libart.so is not cached");
|
||||
return;
|
||||
} else {
|
||||
LOGD("hook_unloader called with libart.so [%zu:%lu]", art_dev, art_inode);
|
||||
}
|
||||
PLT_HOOK_REGISTER(art_dev, art_inode, pthread_attr_setstacksize);
|
||||
hook_commit();
|
||||
}
|
||||
|
||||
|
||||
@@ -127,6 +127,24 @@ void *nativeForkAndSpecialize_orig = nullptr;
|
||||
ctx.nativeForkAndSpecialize_post();
|
||||
return ctx.pid;
|
||||
}
|
||||
[[clang::no_stack_protector]] jint nativeForkAndSpecialize_grapheneos_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, jlongArray _13) {
|
||||
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_grapheneos_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, _13
|
||||
);
|
||||
ctx.nativeForkAndSpecialize_post();
|
||||
return ctx.pid;
|
||||
}
|
||||
std::array nativeForkAndSpecialize_methods = {
|
||||
JNINativeMethod {
|
||||
"nativeForkAndSpecialize",
|
||||
@@ -178,6 +196,11 @@ std::array nativeForkAndSpecialize_methods = {
|
||||
"(II[II[[IILjava/lang/String;IILjava/lang/String;[I[IZLjava/lang/String;Ljava/lang/String;)I",
|
||||
(void *) &nativeForkAndSpecialize_samsung_p
|
||||
},
|
||||
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[J)I",
|
||||
(void *) &nativeForkAndSpecialize_grapheneos_u
|
||||
},
|
||||
};
|
||||
|
||||
void *nativeSpecializeAppProcess_orig = nullptr;
|
||||
@@ -243,6 +266,22 @@ void *nativeSpecializeAppProcess_orig = nullptr;
|
||||
);
|
||||
ctx.nativeSpecializeAppProcess_post();
|
||||
}
|
||||
[[clang::no_stack_protector]] void nativeSpecializeAppProcess_grapheneos_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, jlongArray _14) {
|
||||
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;
|
||||
args.mount_sysprop_overrides = &mount_sysprop_overrides;
|
||||
ZygiskContext ctx(env, &args);
|
||||
ctx.nativeSpecializeAppProcess_pre();
|
||||
reinterpret_cast<decltype(&nativeSpecializeAppProcess_grapheneos_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, _14
|
||||
);
|
||||
ctx.nativeSpecializeAppProcess_post();
|
||||
}
|
||||
std::array nativeSpecializeAppProcess_methods = {
|
||||
JNINativeMethod {
|
||||
"nativeSpecializeAppProcess",
|
||||
@@ -269,6 +308,11 @@ std::array nativeSpecializeAppProcess_methods = {
|
||||
"(II[II[[IILjava/lang/String;IILjava/lang/String;ZLjava/lang/String;Ljava/lang/String;)V",
|
||||
(void *) &nativeSpecializeAppProcess_samsung_q
|
||||
},
|
||||
JNINativeMethod {
|
||||
"nativeSpecializeAppProcess",
|
||||
"(II[II[[IILjava/lang/String;Ljava/lang/String;ZLjava/lang/String;Ljava/lang/String;Z[Ljava/lang/String;[Ljava/lang/String;ZZZ[J)V",
|
||||
(void *) &nativeSpecializeAppProcess_grapheneos_u
|
||||
},
|
||||
};
|
||||
|
||||
void *nativeForkSystemServer_orig = nullptr;
|
||||
@@ -292,6 +336,16 @@ void *nativeForkSystemServer_orig = nullptr;
|
||||
ctx.nativeForkSystemServer_post();
|
||||
return ctx.pid;
|
||||
}
|
||||
[[clang::no_stack_protector]] jint nativeForkSystemServer_grapheneos_u(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);
|
||||
ZygiskContext ctx(env, &args);
|
||||
ctx.nativeForkSystemServer_pre();
|
||||
reinterpret_cast<decltype(&nativeForkSystemServer_grapheneos_u)>(nativeForkSystemServer_orig)(
|
||||
env, clazz, uid, gid, gids, runtime_flags, rlimits, permitted_capabilities, effective_capabilities
|
||||
);
|
||||
ctx.nativeForkSystemServer_post();
|
||||
return ctx.pid;
|
||||
}
|
||||
std::array nativeForkSystemServer_methods = {
|
||||
JNINativeMethod {
|
||||
"nativeForkSystemServer",
|
||||
@@ -303,6 +357,11 @@ std::array nativeForkSystemServer_methods = {
|
||||
"(II[IIII[[IJJ)I",
|
||||
(void *) &nativeForkSystemServer_samsung_q
|
||||
},
|
||||
JNINativeMethod {
|
||||
"nativeForkSystemServer",
|
||||
"(II[II[[IJJ)I",
|
||||
(void *) &nativeForkSystemServer_grapheneos_u
|
||||
},
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include "api.hpp"
|
||||
|
||||
@@ -125,13 +126,13 @@ 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_IS_MANAGER = (1u << 27),
|
||||
PROCESS_ROOT_IS_APATCH = (1u << 28),
|
||||
PROCESS_ROOT_IS_KSU = (1u << 29),
|
||||
PROCESS_ROOT_IS_MAGISK = (1u << 30),
|
||||
PROCESS_IS_SYS_UI = (1u << 31),
|
||||
PROCESS_IS_FIRST_STARTED = (1u << 31),
|
||||
|
||||
PRIVATE_MASK = PROCESS_IS_SYS_UI
|
||||
PRIVATE_MASK = PROCESS_IS_FIRST_STARTED
|
||||
};
|
||||
|
||||
struct api_abi_base {
|
||||
@@ -209,7 +210,7 @@ case 5: \
|
||||
int getModuleDir() const;
|
||||
void setOption(zygisk::Option opt);
|
||||
static uint32_t getFlags();
|
||||
void tryUnload() const { if (unload) dlclose(handle); }
|
||||
bool tryUnload() const { return unload && dlclose(handle) == 0; };
|
||||
void clearApi() { memset(&api, 0, sizeof(api)); }
|
||||
int getId() const { return id; }
|
||||
|
||||
@@ -235,4 +236,4 @@ case 5: \
|
||||
} mod;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
} // namespace
|
||||
|
||||
234
loader/src/injector/solist.c
Normal file
234
loader/src/injector/solist.c
Normal file
@@ -0,0 +1,234 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "elf_util.h"
|
||||
#include "logging.h"
|
||||
|
||||
#include "solist.h"
|
||||
|
||||
#ifdef __LP64__
|
||||
size_t solist_size_offset = 0x18;
|
||||
size_t solist_next_offset = 0x30;
|
||||
size_t solist_realpath_offset = 0x1a8;
|
||||
#else
|
||||
size_t solist_size_offset = 0x90;
|
||||
size_t solist_next_offset = 0xa4;
|
||||
size_t solist_realpath_offset = 0x174;
|
||||
#endif
|
||||
|
||||
static const char *(*get_realpath_sym)(SoInfo *) = NULL;
|
||||
static void (*soinfo_free)(SoInfo *) = NULL;
|
||||
|
||||
static inline SoInfo *get_next(SoInfo *self) {
|
||||
return *(SoInfo **)((uintptr_t)self + solist_next_offset);
|
||||
}
|
||||
|
||||
static inline const char *get_path(SoInfo *self) {
|
||||
if (get_realpath_sym)
|
||||
return (*get_realpath_sym)(self);
|
||||
|
||||
return ((const char *)((uintptr_t)self + solist_realpath_offset));
|
||||
}
|
||||
|
||||
static inline void set_size(SoInfo *self, size_t size) {
|
||||
*(size_t *) ((uintptr_t)self + solist_size_offset) = size;
|
||||
}
|
||||
|
||||
static inline size_t get_size(SoInfo *self) {
|
||||
return *(size_t *) ((uintptr_t)self + solist_size_offset);
|
||||
}
|
||||
|
||||
struct pdg ppdg;
|
||||
|
||||
static bool pdg_setup(ElfImg *img) {
|
||||
ppdg.ctor = (void *(*)())getSymbAddress(img, "__dl__ZN18ProtectedDataGuardC2Ev");
|
||||
ppdg.dtor = (void *(*)())getSymbAddress(img, "__dl__ZN18ProtectedDataGuardD2Ev");
|
||||
|
||||
return ppdg.ctor != NULL && ppdg.dtor != NULL;
|
||||
}
|
||||
|
||||
static void pdg_protect() {
|
||||
if (ppdg.ctor != NULL)
|
||||
(*(ppdg.ctor))();
|
||||
}
|
||||
|
||||
static void pdg_unprotect() {
|
||||
if (ppdg.dtor != NULL)
|
||||
(*(ppdg.dtor))();
|
||||
}
|
||||
|
||||
static SoInfo *solist = NULL;
|
||||
static SoInfo *somain = NULL;
|
||||
static SoInfo **sonext = NULL;
|
||||
|
||||
static uint64_t *g_module_load_counter = NULL;
|
||||
static uint64_t *g_module_unload_counter = NULL;
|
||||
|
||||
static bool solist_init() {
|
||||
ElfImg *linker = ElfImg_create("/linker");
|
||||
if (linker == NULL) {
|
||||
LOGE("Failed to load linker");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
ppdg = (struct pdg) {
|
||||
.ctor = NULL,
|
||||
.dtor = NULL
|
||||
};
|
||||
if (!pdg_setup(linker)) {
|
||||
LOGE("Failed to setup pdg");
|
||||
|
||||
ElfImg_destroy(linker);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/* INFO: Since Android 15, the symbol names for the linker have a suffix,
|
||||
this makes it impossible to hardcode the symbol names. To allow
|
||||
this to work on all versions, we need to iterate over the loaded
|
||||
symbols and find the correct ones.
|
||||
|
||||
See #63 for more information.
|
||||
*/
|
||||
solist = (SoInfo *)getSymbValueByPrefix(linker, "__dl__ZL6solist");
|
||||
if (solist == NULL) {
|
||||
LOGE("Failed to find solist __dl__ZL6solist*");
|
||||
|
||||
ElfImg_destroy(linker);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
somain = (SoInfo *)getSymbValueByPrefix(linker, "__dl__ZL6somain");
|
||||
LOGI("%p is somain", (void *)somain);
|
||||
if (somain == NULL) {
|
||||
LOGE("Failed to find somain __dl__ZL6somain*");
|
||||
|
||||
ElfImg_destroy(linker);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
sonext = (SoInfo **)getSymbAddressByPrefix(linker, "__dl__ZL6sonext");
|
||||
if (sonext == NULL) {
|
||||
LOGE("Failed to find sonext __dl__ZL6sonext*");
|
||||
|
||||
ElfImg_destroy(linker);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
SoInfo *vdso = (SoInfo *)getSymbValueByPrefix(linker, "__dl__ZL4vdso");
|
||||
if (vdso == NULL) {
|
||||
LOGE("Failed to find vsdo __dl__ZL4vdso*");
|
||||
|
||||
ElfImg_destroy(linker);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
get_realpath_sym = (const char *(*)(SoInfo *))getSymbAddress(linker, "__dl__ZNK6soinfo12get_realpathEv");
|
||||
if (get_realpath_sym == NULL) {
|
||||
LOGE("Failed to find get_realpath __dl__ZNK6soinfo12get_realpathEv");
|
||||
|
||||
ElfImg_destroy(linker);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
soinfo_free = (void (*)(SoInfo *))getSymbAddressByPrefix(linker, "__dl__ZL11soinfo_freeP6soinfo");
|
||||
if (soinfo_free == NULL) {
|
||||
LOGE("Failed to find soinfo_free __dl__ZL11soinfo_freeP6soinfo*");
|
||||
|
||||
ElfImg_destroy(linker);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
g_module_load_counter = (uint64_t *)getSymbAddress(linker, "__dl__ZL21g_module_load_counter");
|
||||
if (g_module_load_counter != NULL) LOGD("found symbol g_module_load_counter");
|
||||
|
||||
g_module_unload_counter = (uint64_t *)getSymbAddress(linker, "__dl__ZL23g_module_unload_counter");
|
||||
if (g_module_unload_counter != NULL) LOGD("found symbol g_module_unload_counter");
|
||||
|
||||
for (size_t i = 0; i < 1024 / sizeof(void *); i++) {
|
||||
uintptr_t possible_field = (uintptr_t)solist + i * sizeof(void *);
|
||||
size_t possible_size_of_somain = *(size_t *)((uintptr_t)somain + i * sizeof(void *));
|
||||
|
||||
if (possible_size_of_somain < 0x100000 && possible_size_of_somain > 0x100) {
|
||||
solist_size_offset = i * sizeof(void *);
|
||||
|
||||
LOGD("solist_size_offset is %zu * %zu = %p", i, sizeof(void *), (void *)solist_size_offset);
|
||||
}
|
||||
|
||||
if (*(void **)possible_field == somain || (vdso != NULL && *(void **)possible_field == vdso)) {
|
||||
solist_next_offset = i * sizeof(void *);
|
||||
LOGD("solist_next_offset is %zu * %zu = %p", i, sizeof(void *), (void *)solist_next_offset);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ElfImg_destroy(linker);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool solist_drop_so_path(const char *target_path) {
|
||||
if (solist == NULL && !solist_init()) {
|
||||
LOGE("Failed to initialize solist");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
for (SoInfo *iter = solist; iter; iter = get_next(iter)) {
|
||||
if (get_path(iter) && strstr(get_path(iter), target_path)) {
|
||||
pdg_protect();
|
||||
|
||||
LOGV("dropping solist record loaded at %s with size %zu", get_path(iter), get_size(iter));
|
||||
if (get_size(iter) > 0) {
|
||||
set_size(iter, 0);
|
||||
soinfo_free(iter);
|
||||
|
||||
pdg_unprotect();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
pdg_unprotect();
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void solist_reset_counters(size_t load, size_t unload) {
|
||||
if (solist == NULL && !solist_init()) {
|
||||
LOGE("Failed to initialize solist");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_module_load_counter == NULL || g_module_unload_counter == NULL) {
|
||||
LOGD("g_module counters not defined, skip reseting them");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
uint64_t loaded_modules = *g_module_load_counter;
|
||||
uint64_t unloaded_modules = *g_module_unload_counter;
|
||||
|
||||
if (loaded_modules >= load) {
|
||||
*g_module_load_counter = loaded_modules - load;
|
||||
|
||||
LOGD("reset g_module_load_counter to %zu", (size_t) *g_module_load_counter);
|
||||
}
|
||||
|
||||
if (unloaded_modules >= unload) {
|
||||
*g_module_unload_counter = unloaded_modules - unload;
|
||||
|
||||
LOGD("reset g_module_unload_counter to %zu", (size_t) *g_module_unload_counter);
|
||||
}
|
||||
}
|
||||
65
loader/src/injector/solist.h
Normal file
65
loader/src/injector/solist.h
Normal file
@@ -0,0 +1,65 @@
|
||||
#ifndef SOLIST_H
|
||||
#define SOLIST_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif /* __cplusplus */
|
||||
|
||||
typedef struct SoInfo SoInfo;
|
||||
|
||||
struct SoInfo {
|
||||
char data[0];
|
||||
};
|
||||
|
||||
#define FuncType(name) void (*name)
|
||||
|
||||
struct pdg {
|
||||
void *(*ctor)();
|
||||
void *(*dtor)();
|
||||
};
|
||||
|
||||
/*
|
||||
INFO: When dlopen'ing a library, the system will save information of the
|
||||
opened library so a structure called soinfo, which contains another
|
||||
called solist, a list with the information of opened objects.
|
||||
|
||||
Due to special handling in ptracer, however, it won't heave gaps in the
|
||||
memory of the list since we will close there, not loading a library creating
|
||||
this gap. However, the previously loaded library would remain in the solist,
|
||||
requiring ReZygisk to clean those up.
|
||||
|
||||
To do that, we use 2 functions: soinfo_free, and set_size, which will
|
||||
zero the region size, and then remove all traces of that library (libzygisk.so)
|
||||
which was previously loaded.
|
||||
|
||||
SOURCES:
|
||||
- https://android.googlesource.com/platform/bionic/+/refs/heads/android15-release/linker/linker.cpp#1712
|
||||
*/
|
||||
bool solist_drop_so_path(const char *target_path);
|
||||
|
||||
/*
|
||||
INFO: When dlopen'ing a library, the system will increment 1 to a global
|
||||
counter that tracks the amount of libraries ever loaded in that process,
|
||||
the same happening in dlclose.
|
||||
|
||||
This cannot directly be used to detect if ReZygisk is present, however, with
|
||||
enough data about specific environments, this can be used to detect if any
|
||||
other library (be it malicious or not) was loaded. To avoid future detections,
|
||||
we patch that value to the original value.
|
||||
|
||||
To do that, we retrieve the address of both "g_module_load_counter" and "g_module
|
||||
_unload_counter" variables and force set them to the original value, based on
|
||||
the modules dlopen'ed.
|
||||
|
||||
SOURCES:
|
||||
- https://android.googlesource.com/platform/bionic/+/refs/heads/android15-release/linker/linker.cpp#1874
|
||||
- https://android.googlesource.com/platform/bionic/+/refs/heads/android15-release/linker/linker.cpp#1944
|
||||
- https://android.googlesource.com/platform/bionic/+/refs/heads/android15-release/linker/linker.cpp#3413
|
||||
*/
|
||||
void solist_reset_counters(size_t load, size_t unload);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* SOLIST_H */
|
||||
@@ -1,127 +0,0 @@
|
||||
#include <mntent.h>
|
||||
#include <sys/mount.h>
|
||||
|
||||
#include "files.hpp"
|
||||
#include "logging.h"
|
||||
#include "misc.hpp"
|
||||
#include "zygisk.hpp"
|
||||
|
||||
using namespace std::string_view_literals;
|
||||
|
||||
namespace {
|
||||
constexpr auto MODULE_DIR = "/data/adb/modules";
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void revert_unmount_ksu() {
|
||||
std::string ksu_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) {
|
||||
ksu_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 == 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")) {
|
||||
// Unmount everything from ksu loop except ksu module dir
|
||||
if (info.source == ksu_loop && info.target != MODULE_DIR) {
|
||||
targets.emplace_back(info.target);
|
||||
}
|
||||
}
|
||||
|
||||
// Do unmount
|
||||
for (auto& s: reversed(targets)) {
|
||||
lazy_unmount(s.data());
|
||||
}
|
||||
}
|
||||
|
||||
void revert_unmount_magisk() {
|
||||
std::vector<std::string> targets;
|
||||
|
||||
// Unmount dummy skeletons and MAGISKTMP
|
||||
// since mirror nodes are always mounted under skeleton, we don't have to specifically unmount
|
||||
for (auto& info: parse_mount_info("self")) {
|
||||
if (info.source == "magisk" || info.source == "worker" || // magisktmp tmpfs
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <jni.h>
|
||||
#include <vector>
|
||||
|
||||
extern void *self_handle;
|
||||
extern void *start_addr;
|
||||
extern size_t block_size;
|
||||
|
||||
void hook_functions();
|
||||
|
||||
void revert_unmount_ksu();
|
||||
|
||||
void revert_unmount_magisk();
|
||||
|
||||
void revert_unmount_apatch();
|
||||
void clean_trace(const char* path, size_t load = 1, size_t unload = 0, bool spoof_maps = false);
|
||||
|
||||
@@ -1,22 +1,19 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "utils.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();
|
||||
if (argc >= 4 && strcmp(argv[3], "--restart") == 0) rezygiskd_zygote_restart();
|
||||
|
||||
long pid = strtol(argv[2], 0, 0);
|
||||
if (!trace_zygote(pid)) {
|
||||
@@ -25,11 +22,9 @@ int main(int argc, char **argv) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("[ReZygisk]: Tracing %ld...\n", pid);
|
||||
|
||||
return 0;
|
||||
} else if (argc >= 2 && strcmp(argv[1], "ctl") == 0) {
|
||||
enum Command command;
|
||||
enum rezygiskd_command command;
|
||||
|
||||
if (strcmp(argv[2], "start") == 0) command = START;
|
||||
else if (strcmp(argv[2], "stop") == 0) command = STOP;
|
||||
@@ -54,28 +49,28 @@ int main(int argc, char **argv) {
|
||||
|
||||
return 0;
|
||||
} else if (argc >= 2 && strcmp(argv[1], "info") == 0) {
|
||||
struct zygote_info info;
|
||||
zygiskd::GetInfo(&info);
|
||||
struct rezygisk_info info;
|
||||
rezygiskd_get_info(&info);
|
||||
|
||||
printf("Daemon process PID: %d\n", info.pid);
|
||||
|
||||
switch (info.root_impl) {
|
||||
case ZYGOTE_ROOT_IMPL_NONE: {
|
||||
case ROOT_IMPL_NONE: {
|
||||
printf("Root implementation: none\n");
|
||||
|
||||
break;
|
||||
}
|
||||
case ZYGOTE_ROOT_IMPL_APATCH: {
|
||||
case ROOT_IMPL_APATCH: {
|
||||
printf("Root implementation: APatch\n");
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
case ZYGOTE_ROOT_IMPL_KERNELSU: {
|
||||
case ROOT_IMPL_KERNELSU: {
|
||||
printf("Root implementation: KernelSU\n");
|
||||
|
||||
break;
|
||||
}
|
||||
case ZYGOTE_ROOT_IMPL_MAGISK: {
|
||||
case ROOT_IMPL_MAGISK: {
|
||||
printf("Root implementation: Magisk\n");
|
||||
|
||||
break;
|
||||
892
loader/src/ptracer/monitor.c
Normal file
892
loader/src/ptracer/monitor.c
Normal file
@@ -0,0 +1,892 @@
|
||||
#include <stdlib.h>
|
||||
|
||||
#include <time.h>
|
||||
|
||||
#include <sys/system_properties.h>
|
||||
#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 <unistd.h>
|
||||
|
||||
#include "utils.h"
|
||||
#include "daemon.h"
|
||||
#include "misc.h"
|
||||
|
||||
#include "monitor.h"
|
||||
|
||||
#define PROP_PATH TMP_PATH "/module.prop"
|
||||
#define SOCKET_NAME "init_monitor"
|
||||
|
||||
#define STOPPED_WITH(sig, event) WIFSTOPPED(sigchld_status) && (sigchld_status >> 8 == ((sig) | (event << 8)))
|
||||
|
||||
static bool update_status(const char *message);
|
||||
|
||||
char monitor_stop_reason[32];
|
||||
|
||||
enum ptracer_tracing_state {
|
||||
TRACING,
|
||||
STOPPING,
|
||||
STOPPED,
|
||||
EXITING
|
||||
};
|
||||
|
||||
enum ptracer_tracing_state tracing_state = TRACING;
|
||||
|
||||
struct rezygiskd_status {
|
||||
bool supported;
|
||||
bool zygote_injected;
|
||||
bool daemon_running;
|
||||
pid_t daemon_pid;
|
||||
char *daemon_info;
|
||||
char *daemon_error_info;
|
||||
};
|
||||
|
||||
struct rezygiskd_status status64 = {
|
||||
.daemon_pid = -1
|
||||
};
|
||||
struct rezygiskd_status status32 = {
|
||||
.daemon_pid = -1
|
||||
};
|
||||
|
||||
int monitor_epoll_fd;
|
||||
bool monitor_events_running = true;
|
||||
|
||||
bool monitor_events_init() {
|
||||
monitor_epoll_fd = epoll_create(1);
|
||||
if (monitor_epoll_fd == -1) {
|
||||
PLOGE("epoll_create");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
struct monitor_event_cbs {
|
||||
void (*callback)();
|
||||
void (*stop_callback)();
|
||||
};
|
||||
|
||||
bool monitor_events_register_event(struct monitor_event_cbs *event_cbs, int fd, uint32_t events) {
|
||||
struct epoll_event ev = {
|
||||
.data.ptr = event_cbs,
|
||||
.events = events
|
||||
};
|
||||
|
||||
if (epoll_ctl(monitor_epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
|
||||
PLOGE("epoll_ctl");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool monitor_events_unregister_event(int fd) {
|
||||
if (epoll_ctl(monitor_epoll_fd, EPOLL_CTL_DEL, fd, NULL) == -1) {
|
||||
PLOGE("epoll_ctl");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void monitor_events_stop() {
|
||||
monitor_events_running = false;
|
||||
};
|
||||
|
||||
void monitor_events_loop() {
|
||||
struct epoll_event events[2];
|
||||
while (monitor_events_running) {
|
||||
int nfds = epoll_wait(monitor_epoll_fd, events, 2, -1);
|
||||
if (nfds == -1) {
|
||||
if (errno != EINTR) PLOGE("epoll_wait");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
for (int i = 0; i < nfds; i++) {
|
||||
struct monitor_event_cbs *event_cbs = (struct monitor_event_cbs *)events[i].data.ptr;
|
||||
event_cbs->callback();
|
||||
|
||||
if (!monitor_events_running) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (monitor_epoll_fd >= 0) close(monitor_epoll_fd);
|
||||
monitor_epoll_fd = -1;
|
||||
|
||||
for (int i = 0; i < (int)(sizeof(events) / sizeof(events[0])); i++) {
|
||||
struct monitor_event_cbs *event_cbs = (struct monitor_event_cbs *)events[i].data.ptr;
|
||||
event_cbs->stop_callback();
|
||||
}
|
||||
}
|
||||
|
||||
int monitor_sock_fd;
|
||||
|
||||
bool rezygiskd_listener_init() {
|
||||
monitor_sock_fd = socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
|
||||
if (monitor_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", rezygiskd_get_path(), SOCKET_NAME);
|
||||
|
||||
socklen_t socklen = sizeof(sa_family_t) + sun_path_len;
|
||||
if (bind(monitor_sock_fd, (struct sockaddr *)&addr, socklen) == -1) {
|
||||
PLOGE("bind socket");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void rezygiskd_listener_callback() {
|
||||
struct [[gnu::packed]] MsgHead {
|
||||
enum rezygiskd_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(monitor_sock_fd, msg, sizeof(struct MsgHead), MSG_PEEK);
|
||||
if (nread == -1) {
|
||||
if (errno == EAGAIN) break;
|
||||
|
||||
PLOGE("read socket");
|
||||
}
|
||||
|
||||
if ((size_t)nread < sizeof(enum rezygiskd_command)) {
|
||||
LOGE("read %zu < %zu", nread, sizeof(enum rezygiskd_command));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (msg->cmd >= DAEMON64_SET_INFO && msg->cmd != SYSTEM_SERVER_STARTED) {
|
||||
if (nread != sizeof(msg)) {
|
||||
LOGE("cmd %d size %zu != %zu", msg->cmd, nread, sizeof(struct MsgHead));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
real_size = sizeof(struct MsgHead) + msg->length;
|
||||
} else {
|
||||
if (nread != sizeof(enum rezygiskd_command)) {
|
||||
LOGE("cmd %d size %zu != %zu", msg->cmd, nread, sizeof(enum rezygiskd_command));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
real_size = sizeof(enum rezygiskd_command);
|
||||
}
|
||||
|
||||
msg = (struct MsgHead *)realloc(msg, real_size);
|
||||
nread = recv(monitor_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;
|
||||
}
|
||||
|
||||
update_status(NULL);
|
||||
|
||||
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);
|
||||
update_status(NULL);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case EXIT: {
|
||||
LOGI("prepare for exit ...");
|
||||
|
||||
tracing_state = EXITING;
|
||||
strcpy(monitor_stop_reason, "user requested");
|
||||
|
||||
update_status(NULL);
|
||||
monitor_events_stop();
|
||||
|
||||
break;
|
||||
}
|
||||
case ZYGOTE64_INJECTED: {
|
||||
status64.zygote_injected = true;
|
||||
|
||||
update_status(NULL);
|
||||
|
||||
break;
|
||||
}
|
||||
case ZYGOTE32_INJECTED: {
|
||||
status32.zygote_injected = true;
|
||||
|
||||
update_status(NULL);
|
||||
|
||||
break;
|
||||
}
|
||||
case DAEMON64_SET_INFO: {
|
||||
LOGD("received daemon64 info %s", msg->data);
|
||||
|
||||
/* Will only happen if somehow the daemon restarts */
|
||||
if (status64.daemon_info) {
|
||||
free(status64.daemon_info);
|
||||
status64.daemon_info = NULL;
|
||||
}
|
||||
|
||||
status64.daemon_info = (char *)malloc(msg->length);
|
||||
if (!status64.daemon_info) {
|
||||
PLOGE("malloc daemon64 info");
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
strcpy(status64.daemon_info, msg->data);
|
||||
|
||||
update_status(NULL);
|
||||
|
||||
break;
|
||||
}
|
||||
case DAEMON32_SET_INFO: {
|
||||
LOGD("received daemon32 info %s", msg->data);
|
||||
|
||||
if (status32.daemon_info) {
|
||||
free(status32.daemon_info);
|
||||
status32.daemon_info = NULL;
|
||||
}
|
||||
|
||||
status32.daemon_info = (char *)malloc(msg->length);
|
||||
if (!status32.daemon_info) {
|
||||
PLOGE("malloc daemon32 info");
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
strcpy(status32.daemon_info, msg->data);
|
||||
|
||||
update_status(NULL);
|
||||
|
||||
break;
|
||||
}
|
||||
case DAEMON64_SET_ERROR_INFO: {
|
||||
LOGD("received daemon64 error info %s", msg->data);
|
||||
|
||||
status64.daemon_running = false;
|
||||
|
||||
if (status64.daemon_error_info) {
|
||||
free(status64.daemon_error_info);
|
||||
status64.daemon_error_info = NULL;
|
||||
}
|
||||
|
||||
status64.daemon_error_info = (char *)malloc(msg->length);
|
||||
if (!status64.daemon_error_info) {
|
||||
PLOGE("malloc daemon64 error info");
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
strcpy(status64.daemon_error_info, msg->data);
|
||||
|
||||
update_status(NULL);
|
||||
|
||||
break;
|
||||
}
|
||||
case DAEMON32_SET_ERROR_INFO: {
|
||||
LOGD("received daemon32 error info %s", msg->data);
|
||||
|
||||
status32.daemon_running = false;
|
||||
|
||||
if (status32.daemon_error_info) {
|
||||
free(status32.daemon_error_info);
|
||||
status32.daemon_error_info = NULL;
|
||||
}
|
||||
|
||||
status32.daemon_error_info = (char *)malloc(msg->length);
|
||||
if (!status32.daemon_error_info) {
|
||||
PLOGE("malloc daemon32 error info");
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
strcpy(status32.daemon_error_info, msg->data);
|
||||
|
||||
update_status(NULL);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
void rezygiskd_listener_stop() {
|
||||
if (monitor_sock_fd >= 0) close(monitor_sock_fd);
|
||||
monitor_sock_fd = -1;
|
||||
}
|
||||
|
||||
#define 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) {
|
||||
struct rezygiskd_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 == status##abi.daemon_pid) { \
|
||||
char status_str[64]; \
|
||||
parse_status(sigchld_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); \
|
||||
} \
|
||||
\
|
||||
update_status(NULL); \
|
||||
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; \
|
||||
} \
|
||||
}
|
||||
|
||||
int sigchld_signal_fd;
|
||||
struct signalfd_siginfo sigchld_fdsi;
|
||||
int sigchld_status;
|
||||
|
||||
pid_t *sigchld_process;
|
||||
size_t sigchld_process_count = 0;
|
||||
|
||||
bool sigchld_listener_init() {
|
||||
sigchld_process = NULL;
|
||||
|
||||
sigset_t mask;
|
||||
sigemptyset(&mask);
|
||||
sigaddset(&mask, SIGCHLD);
|
||||
|
||||
if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1) {
|
||||
PLOGE("set sigprocmask");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
sigchld_signal_fd = signalfd(-1, &mask, SFD_NONBLOCK | SFD_CLOEXEC);
|
||||
if (sigchld_signal_fd == -1) {
|
||||
PLOGE("create signalfd");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
ptrace(PTRACE_SEIZE, 1, 0, PTRACE_O_TRACEFORK);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void sigchld_listener_callback() {
|
||||
while (1) {
|
||||
ssize_t s = read(sigchld_signal_fd, &sigchld_fdsi, sizeof(sigchld_fdsi));
|
||||
if (s == -1) {
|
||||
if (errno == EAGAIN) break;
|
||||
|
||||
PLOGE("read signalfd");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (s != sizeof(sigchld_fdsi)) {
|
||||
LOGW("read %zu != %zu", s, sizeof(sigchld_fdsi));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (sigchld_fdsi.ssi_signo != SIGCHLD) {
|
||||
LOGW("no sigchld received");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
int pid;
|
||||
while ((pid = waitpid(-1, &sigchld_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(sigchld_status)) {
|
||||
if (WPTEVENT(sigchld_status) == 0) {
|
||||
if (WSTOPSIG(sigchld_status) != SIGSTOP && WSTOPSIG(sigchld_status) != SIGTSTP && WSTOPSIG(sigchld_status) != SIGTTIN && WSTOPSIG(sigchld_status) != SIGTTOU) {
|
||||
LOGW("inject signal sent to init: %s %d", sigabbrev_np(WSTOPSIG(sigchld_status)), WSTOPSIG(sigchld_status));
|
||||
|
||||
ptrace(PTRACE_CONT, pid, 0, WSTOPSIG(sigchld_status));
|
||||
|
||||
continue;
|
||||
} else {
|
||||
LOGW("suppress stopping signal sent to init: %s %d", sigabbrev_np(WSTOPSIG(sigchld_status)), WSTOPSIG(sigchld_status));
|
||||
}
|
||||
}
|
||||
|
||||
ptrace(PTRACE_CONT, pid, 0, 0);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
CHECK_DAEMON_EXIT(64)
|
||||
CHECK_DAEMON_EXIT(32)
|
||||
|
||||
pid_t state = 0;
|
||||
for (size_t i = 0; i < sigchld_process_count; i++) {
|
||||
if (sigchld_process[i] != pid) continue;
|
||||
|
||||
state = sigchld_process[i];
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (state == 0) {
|
||||
LOGV("new process %d attached", pid);
|
||||
|
||||
for (size_t i = 0; i < sigchld_process_count; i++) {
|
||||
if (sigchld_process[i] != 0) continue;
|
||||
|
||||
sigchld_process[i] = pid;
|
||||
|
||||
goto ptrace_process;
|
||||
}
|
||||
|
||||
sigchld_process = (pid_t *)realloc(sigchld_process, sizeof(pid_t) * (sigchld_process_count + 1));
|
||||
if (sigchld_process == NULL) {
|
||||
PLOGE("realloc sigchld_process");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
sigchld_process[sigchld_process_count] = pid;
|
||||
sigchld_process_count++;
|
||||
|
||||
ptrace_process:
|
||||
|
||||
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, &sigchld_status, __WALL);
|
||||
|
||||
if (STOPPED_WITH(SIGSTOP, 0)) {
|
||||
LOGD("detaching %d", pid);
|
||||
|
||||
ptrace(PTRACE_DETACH, pid, 0, SIGSTOP);
|
||||
sigchld_status = 0;
|
||||
int 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);
|
||||
|
||||
update_status(NULL);
|
||||
} else {
|
||||
char status_str[64];
|
||||
parse_status(sigchld_status, status_str, sizeof(status_str));
|
||||
|
||||
LOGW("process %d received unknown sigchld_status %s", pid, status_str);
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < sigchld_process_count; i++) {
|
||||
if (sigchld_process[i] != pid) continue;
|
||||
|
||||
sigchld_process[i] = 0;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (WIFSTOPPED(sigchld_status)) {
|
||||
LOGV("detach process %d", pid);
|
||||
|
||||
ptrace(PTRACE_DETACH, pid, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void sigchld_listener_stop() {
|
||||
if (sigchld_signal_fd >= 0) close(sigchld_signal_fd);
|
||||
sigchld_signal_fd = -1;
|
||||
|
||||
if (sigchld_process != NULL) free(sigchld_process);
|
||||
sigchld_process = NULL;
|
||||
sigchld_process_count = 0;
|
||||
}
|
||||
|
||||
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 bool update_status(const char *message) {
|
||||
FILE *prop = fopen(PROP_PATH, "w");
|
||||
if (prop == NULL) {
|
||||
PLOGE("failed to open prop");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (message) {
|
||||
fprintf(prop, "%s[%s] %s", pre_section, message, post_section);
|
||||
fclose(prop);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool prepare_environment() {
|
||||
/* INFO: We need to create the file first, otherwise the mount will fail */
|
||||
close(open(PROP_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0644));
|
||||
|
||||
FILE *orig_prop = fopen("/data/adb/modules/zygisksu/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);
|
||||
|
||||
/* INFO: This environment variable is related to Magisk Zygisk/Manager. It
|
||||
it used by Magisk's Zygisk to communicate to Magisk Manager whether
|
||||
Zygisk is working or not.
|
||||
|
||||
Because of that behavior, we can knowledge built-in Zygisk is being
|
||||
used and stop the continuation of initialization of ReZygisk.*/
|
||||
if (getenv("ZYGISK_ENABLED")) {
|
||||
update_status("❌ Disable Magisk's built-in Zygisk");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return update_status(NULL);
|
||||
}
|
||||
|
||||
void init_monitor() {
|
||||
LOGI("ReZygisk %s", ZKSU_VERSION);
|
||||
|
||||
if (!prepare_environment()) exit(1);
|
||||
|
||||
monitor_events_init();
|
||||
|
||||
rezygiskd_listener_init();
|
||||
|
||||
struct monitor_event_cbs listener_cbs = {
|
||||
.callback = rezygiskd_listener_callback,
|
||||
.stop_callback = rezygiskd_listener_stop
|
||||
};
|
||||
monitor_events_register_event(&listener_cbs, monitor_sock_fd, EPOLLIN | EPOLLET);
|
||||
|
||||
sigchld_listener_init();
|
||||
|
||||
struct monitor_event_cbs sigchld_cbs = {
|
||||
.callback = sigchld_listener_callback,
|
||||
.stop_callback = sigchld_listener_stop
|
||||
};
|
||||
monitor_events_register_event(&sigchld_cbs, sigchld_signal_fd, EPOLLIN | EPOLLET);
|
||||
|
||||
monitor_events_loop();
|
||||
|
||||
if (status64.daemon_info) free(status64.daemon_info);
|
||||
if (status64.daemon_error_info) free(status64.daemon_error_info);
|
||||
if (status32.daemon_info) free(status32.daemon_info);
|
||||
if (status32.daemon_error_info) free(status32.daemon_error_info);
|
||||
|
||||
LOGI("exit");
|
||||
}
|
||||
|
||||
int send_control_command(enum rezygiskd_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", rezygiskd_get_path(), SOCKET_NAME);
|
||||
|
||||
socklen_t socklen = sizeof(sa_family_t) + sun_path_len;
|
||||
|
||||
ssize_t nsend = sendto(sockfd, (void *)&cmd, sizeof(cmd), 0, (struct sockaddr *)&addr, socklen);
|
||||
|
||||
close(sockfd);
|
||||
|
||||
return nsend != sizeof(cmd) ? -1 : 0;
|
||||
}
|
||||
@@ -1,875 +0,0 @@
|
||||
#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, ")"); \
|
||||
} \
|
||||
} \
|
||||
}
|
||||
|
||||
#define WRITE_STATUS_FILE(suffix) \
|
||||
if (status ## suffix.supported) { \
|
||||
fprintf(state_file, "Daemon" # suffix ": "); \
|
||||
if (status ## suffix.daemon_running) { \
|
||||
fprintf(state_file, "running"); \
|
||||
\
|
||||
if (status ## suffix.daemon_info != NULL) \
|
||||
fprintf(state_file, " (%s)", status ## suffix.daemon_info); \
|
||||
} else { \
|
||||
fprintf(state_file, "crashed"); \
|
||||
\
|
||||
if (status ## suffix.daemon_error_info != NULL) \
|
||||
fprintf(state_file, " (%s)", status ## suffix.daemon_error_info); \
|
||||
} \
|
||||
\
|
||||
fprintf(state_file, "\nZygote" # suffix ": "); \
|
||||
if (tracing_state != TRACING) fprintf(state_file, "unknown"); \
|
||||
else if (status ## suffix.zygote_injected) fprintf(state_file, "injected"); \
|
||||
else fprintf(state_file, "not injected"); \
|
||||
\
|
||||
fprintf(state_file, "\n"); \
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
char state_file_path[PATH_MAX];
|
||||
snprintf(state_file_path, sizeof(state_file_path), "%s/%s", zygiskd::GetTmpPath().c_str(), "status");
|
||||
|
||||
FILE *state_file = fopen(state_file_path, "w");
|
||||
if (state_file == NULL) {
|
||||
PLOGE("failed to open state file");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
fprintf(state_file, "Version: %s\n", ZKSU_VERSION);
|
||||
fprintf(state_file, "Tracing: %d", tracing_state);
|
||||
if (tracing_state != TRACING && monitor_stop_reason[0] != '\0') {
|
||||
fprintf(state_file, " (%s)\n", monitor_stop_reason);
|
||||
} else {
|
||||
fprintf(state_file, "\n");
|
||||
}
|
||||
|
||||
WRITE_STATUS_FILE(64)
|
||||
WRITE_STATUS_FILE(32)
|
||||
|
||||
fclose(state_file);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
#ifndef MAIN_HPP
|
||||
#define MAIN_HPP
|
||||
#ifndef MONITOR_H
|
||||
#define MONITOR_H
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
@@ -7,7 +7,7 @@ void init_monitor();
|
||||
|
||||
bool trace_zygote(int pid);
|
||||
|
||||
enum Command {
|
||||
enum rezygiskd_command {
|
||||
START = 1,
|
||||
STOP = 2,
|
||||
EXIT = 3,
|
||||
@@ -22,6 +22,6 @@ enum Command {
|
||||
SYSTEM_SERVER_STARTED = 10
|
||||
};
|
||||
|
||||
int send_control_command(enum Command cmd);
|
||||
int send_control_command(enum rezygiskd_command cmd);
|
||||
|
||||
#endif /* MAIN_HPP */
|
||||
#endif /* MONITOR_H */
|
||||
@@ -1,20 +1,18 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <inttypes.h>
|
||||
|
||||
#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"
|
||||
#include <unistd.h>
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
bool inject_on_main(int pid, const char *lib_path) {
|
||||
LOGI("injecting %s to zygote %d", lib_path, pid);
|
||||
@@ -25,16 +23,26 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
https://cs.android.com/android/platform/superproject/main/+/main:bionic/libc/private/KernelArgumentBlock.h;l=30;drc=6d1ee77ee32220e4202c3066f7e1f69572967ad8
|
||||
*/
|
||||
|
||||
struct user_regs_struct regs {},
|
||||
backup {};
|
||||
struct user_regs_struct regs = { 0 };
|
||||
|
||||
/* WARNING: C++ keyword */
|
||||
std::vector<MapInfo> map = MapInfo::Scan(std::to_string(pid));
|
||||
if (!get_regs(pid, regs)) return false;
|
||||
char pid_maps[PATH_MAX];
|
||||
snprintf(pid_maps, sizeof(pid_maps), "/proc/%d/maps", pid);
|
||||
|
||||
struct maps *map = parse_maps(pid_maps);
|
||||
if (map == NULL) {
|
||||
LOGE("failed to parse remote maps");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!get_regs(pid, ®s)) return false;
|
||||
|
||||
uintptr_t arg = (uintptr_t)regs.REG_SP;
|
||||
|
||||
LOGV("kernel argument %" PRIxPTR " %s", arg, get_addr_mem_region(map, arg).c_str());
|
||||
char addr_mem_region[1024];
|
||||
get_addr_mem_region(map, arg, addr_mem_region, sizeof(addr_mem_region));
|
||||
|
||||
LOGV("kernel argument %" PRIxPTR " %s", arg, addr_mem_region);
|
||||
|
||||
int argc;
|
||||
char **argv = (char **)((uintptr_t *)arg + 1);
|
||||
@@ -43,18 +51,16 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
read_proc(pid, arg, &argc, sizeof(argc));
|
||||
LOGV("argc %d", argc);
|
||||
|
||||
/* WARNING: C++ keyword */
|
||||
auto envp = argv + argc + 1;
|
||||
char **envp = argv + argc + 1;
|
||||
LOGV("envp %p", (void *)envp);
|
||||
|
||||
/* WARNING: C++ keyword */
|
||||
auto p = envp;
|
||||
char **p = envp;
|
||||
while (1) {
|
||||
uintptr_t *buf;
|
||||
read_proc(pid, (uintptr_t)p, &buf, sizeof(buf));
|
||||
|
||||
if (buf == NULL) break;
|
||||
|
||||
|
||||
/* TODO: Why ++p? */
|
||||
p++;
|
||||
}
|
||||
@@ -63,7 +69,9 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
p++;
|
||||
|
||||
ElfW(auxv_t) *auxv = (ElfW(auxv_t) *)p;
|
||||
LOGV("auxv %p %s", auxv, get_addr_mem_region(map, (uintptr_t) auxv).c_str());
|
||||
|
||||
get_addr_mem_region(map, (uintptr_t)auxv, addr_mem_region, sizeof(addr_mem_region));
|
||||
LOGV("auxv %p %s", auxv, addr_mem_region);
|
||||
|
||||
ElfW(auxv_t) *v = auxv;
|
||||
uintptr_t entry_addr = 0;
|
||||
@@ -78,8 +86,9 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
entry_addr = (uintptr_t)buf.a_un.a_val;
|
||||
addr_of_entry_addr = (uintptr_t)v + offsetof(ElfW(auxv_t), a_un);
|
||||
|
||||
get_addr_mem_region(map, entry_addr, addr_mem_region, sizeof(addr_mem_region));
|
||||
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);
|
||||
addr_mem_region, (uintptr_t)v, addr_of_entry_addr);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -113,7 +122,7 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
int status;
|
||||
wait_for_trace(pid, &status, __WALL);
|
||||
if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGSEGV) {
|
||||
if (!get_regs(pid, regs)) return false;
|
||||
if (!get_regs(pid, ®s)) return false;
|
||||
|
||||
if (((int)regs.REG_IP & ~1) != ((int)break_addr & ~1)) {
|
||||
LOGE("stopped at unknown addr %p", (void *) regs.REG_IP);
|
||||
@@ -128,13 +137,25 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
if (!write_proc(pid, (uintptr_t) addr_of_entry_addr, &entry_addr, sizeof(entry_addr))) return false;
|
||||
|
||||
/* backup registers */
|
||||
struct user_regs_struct backup;
|
||||
memcpy(&backup, ®s, sizeof(regs));
|
||||
|
||||
/* WARNING: C++ keyword */
|
||||
map = MapInfo::Scan(std::to_string(pid));
|
||||
free_maps(map);
|
||||
|
||||
map = parse_maps(pid_maps);
|
||||
if (!map) {
|
||||
LOGE("failed to parse remote maps");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
struct maps *local_map = parse_maps("/proc/self/maps");
|
||||
if (!local_map) {
|
||||
LOGE("failed to parse local maps");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/* 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);
|
||||
|
||||
@@ -142,17 +163,19 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
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;
|
||||
long *args = (long *)malloc(3 * sizeof(long));
|
||||
if (args == NULL) {
|
||||
LOGE("malloc args");
|
||||
|
||||
/* WARNING: C++ keyword */
|
||||
uintptr_t str = push_string(pid, regs, lib_path);
|
||||
return false;
|
||||
}
|
||||
|
||||
args.clear();
|
||||
args.push_back((long) str);
|
||||
args.push_back((long) RTLD_NOW);
|
||||
uintptr_t str = push_string(pid, ®s, lib_path);
|
||||
|
||||
uintptr_t remote_handle = remote_call(pid, regs, (uintptr_t)dlopen_addr, (uintptr_t)libc_return_addr, args);
|
||||
args[0] = (long) str;
|
||||
args[1] = (long) RTLD_NOW;
|
||||
|
||||
uintptr_t remote_handle = remote_call(pid, ®s, (uintptr_t)dlopen_addr, (uintptr_t)libc_return_addr, args, 2);
|
||||
LOGD("remote handle %p", (void *)remote_handle);
|
||||
if (remote_handle == 0) {
|
||||
LOGE("handle is null");
|
||||
@@ -162,37 +185,47 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
if (dlerror_addr == NULL) {
|
||||
LOGE("find dlerror");
|
||||
|
||||
free(args);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
args.clear();
|
||||
uintptr_t dlerror_str_addr = remote_call(pid, ®s, (uintptr_t)dlerror_addr, (uintptr_t)libc_return_addr, args, 0);
|
||||
LOGD("dlerror str %p", (void *)dlerror_str_addr);
|
||||
if (dlerror_str_addr == 0) {
|
||||
LOGE("dlerror str is null");
|
||||
|
||||
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;
|
||||
free(args);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void *strlen_addr = find_func_addr(local_map, map, "libc.so", "strlen");
|
||||
if (strlen_addr == NULL) {
|
||||
LOGE("find strlen");
|
||||
|
||||
free(args);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
args.clear();
|
||||
args.push_back(dlerror_str_addr);
|
||||
args[0] = (long) dlerror_str_addr;
|
||||
|
||||
uintptr_t dlerror_len = remote_call(pid, regs, (uintptr_t)strlen_addr, (uintptr_t)libc_return_addr, args);
|
||||
uintptr_t dlerror_len = remote_call(pid, ®s, (uintptr_t)strlen_addr, (uintptr_t)libc_return_addr, args, 1);
|
||||
if (dlerror_len <= 0) {
|
||||
LOGE("dlerror len <= 0");
|
||||
|
||||
free(args);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/* NOTICE: C++ -> C */
|
||||
char *err = (char *)malloc((dlerror_len + 1) * sizeof(char));
|
||||
if (err == NULL) {
|
||||
LOGE("malloc err");
|
||||
|
||||
free(args);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -201,6 +234,7 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
LOGE("dlerror info %s", err);
|
||||
|
||||
free(err);
|
||||
free(args);
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -209,12 +243,13 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
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);
|
||||
free_maps(local_map);
|
||||
|
||||
uintptr_t injector_entry = remote_call(pid, regs, (uintptr_t)dlsym_addr, (uintptr_t)libc_return_addr, args);
|
||||
str = push_string(pid, ®s, "entry");
|
||||
args[0] = remote_handle;
|
||||
args[1] = (long) str;
|
||||
|
||||
uintptr_t injector_entry = remote_call(pid, ®s, (uintptr_t)dlsym_addr, (uintptr_t)libc_return_addr, args, 2);
|
||||
LOGD("injector entry %p", (void *)injector_entry);
|
||||
if (injector_entry == 0) {
|
||||
LOGE("injector entry is null");
|
||||
@@ -222,21 +257,42 @@ bool inject_on_main(int pid, const char *lib_path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* call injector entry(handle, path) */
|
||||
/* record the address range of libzygisk.so */
|
||||
map = parse_maps(pid_maps);
|
||||
|
||||
args.clear();
|
||||
args.push_back(remote_handle);
|
||||
str = push_string(pid, regs, zygiskd::GetTmpPath().c_str());
|
||||
args.push_back((long) str);
|
||||
void *start_addr = NULL;
|
||||
size_t block_size = 0;
|
||||
|
||||
remote_call(pid, regs, injector_entry, (uintptr_t)libc_return_addr, args);
|
||||
for (size_t i = 0; i < map->size; i++) {
|
||||
if (!strstr(map->maps[i].path, "libzygisk.so")) continue;
|
||||
|
||||
if (start_addr == NULL) start_addr = (void *)map->maps[i].start;
|
||||
|
||||
size_t size = map->maps[i].end - map->maps[i].start;
|
||||
block_size += size;
|
||||
|
||||
LOGD("found block %s: [%p-%p] with size %zu", map->maps[i].path, (void *)map->maps[i].start,
|
||||
(void *)map->maps[i].end, size);
|
||||
}
|
||||
|
||||
free_maps(map);
|
||||
|
||||
/* call injector entry(start_addr, block_size, path) */
|
||||
args[0] = (uintptr_t)start_addr;
|
||||
args[1] = block_size;
|
||||
str = push_string(pid, ®s, rezygiskd_get_path());
|
||||
args[2] = (uintptr_t)str;
|
||||
|
||||
remote_call(pid, ®s, injector_entry, (uintptr_t)libc_return_addr, args, 3);
|
||||
|
||||
free(args);
|
||||
|
||||
/* reset pc to entry */
|
||||
backup.REG_IP = (long) entry_addr;
|
||||
LOGD("invoke entry");
|
||||
|
||||
/* restore registers */
|
||||
if (!set_regs(pid, backup)) return false;
|
||||
if (!set_regs(pid, &backup)) return false;
|
||||
|
||||
return true;
|
||||
} else {
|
||||
@@ -272,11 +328,10 @@ bool trace_zygote(int pid) {
|
||||
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";
|
||||
char lib_path[PATH_MAX];
|
||||
snprintf(lib_path, sizeof(lib_path), "%s/lib" LP_SELECT("", "64") "/libzygisk.so", rezygiskd_get_path());
|
||||
|
||||
if (!inject_on_main(pid, lib_path.c_str())) {
|
||||
if (!inject_on_main(pid, lib_path)) {
|
||||
LOGE("failed to inject");
|
||||
|
||||
return false;
|
||||
583
loader/src/ptracer/utils.c
Normal file
583
loader/src/ptracer/utils.c
Normal file
@@ -0,0 +1,583 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <inttypes.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#include <sys/sysmacros.h>
|
||||
#include <sys/ptrace.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/wait.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/auxv.h>
|
||||
#include <sys/uio.h>
|
||||
#include <signal.h>
|
||||
#include <dlfcn.h>
|
||||
#include <sched.h>
|
||||
#include <fcntl.h>
|
||||
#include <link.h>
|
||||
|
||||
#include <unistd.h>
|
||||
#include <linux/limits.h>
|
||||
|
||||
#include "utils.h"
|
||||
|
||||
/* INFO: utils.h must be before logging.h so that it defined LOG_TAG first */
|
||||
#include "logging.h"
|
||||
|
||||
bool switch_mnt_ns(int pid, int *fd) {
|
||||
int nsfd, old_nsfd = -1;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
struct maps *parse_maps(const char *filename) {
|
||||
FILE *fp = fopen(filename, "r");
|
||||
if (!fp) {
|
||||
LOGE("Failed to open %s", filename);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
struct maps *maps = (struct maps *)malloc(sizeof(struct maps));
|
||||
if (!maps) {
|
||||
LOGE("Failed to allocate memory for maps");
|
||||
|
||||
fclose(fp);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* INFO: To ensure in the realloc the libc will know it is meant
|
||||
to allocate, and not reallocate from a garbage address. */
|
||||
maps->maps = NULL;
|
||||
|
||||
char line[4096 * 2];
|
||||
size_t i = 0;
|
||||
|
||||
while (fgets(line, sizeof(line), fp) != NULL) {
|
||||
/* INFO: Remove line ending at the end */
|
||||
line[strlen(line) - 1] = '\0';
|
||||
|
||||
uintptr_t addr_start;
|
||||
uintptr_t addr_end;
|
||||
uintptr_t addr_offset;
|
||||
ino_t inode;
|
||||
unsigned int dev_major;
|
||||
unsigned int dev_minor;
|
||||
char permissions[5] = "";
|
||||
int path_offset;
|
||||
|
||||
sscanf(line,
|
||||
"%" PRIxPTR "-%" PRIxPTR " %4s %" PRIxPTR " %x:%x %lu %n%*s",
|
||||
&addr_start, &addr_end, permissions, &addr_offset, &dev_major, &dev_minor,
|
||||
&inode, &path_offset);
|
||||
|
||||
while (isspace(line[path_offset])) {
|
||||
path_offset++;
|
||||
}
|
||||
|
||||
maps->maps = (struct map *)realloc(maps->maps, (i + 1) * sizeof(struct map));
|
||||
if (!maps->maps) {
|
||||
LOGE("Failed to allocate memory for maps->maps");
|
||||
|
||||
maps->size = i;
|
||||
|
||||
fclose(fp);
|
||||
free_maps(maps);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
maps->maps[i].start = addr_start;
|
||||
maps->maps[i].end = addr_end;
|
||||
maps->maps[i].offset = addr_offset;
|
||||
|
||||
maps->maps[i].perms = 0;
|
||||
if (permissions[0] == 'r') maps->maps[i].perms |= PROT_READ;
|
||||
if (permissions[1] == 'w') maps->maps[i].perms |= PROT_WRITE;
|
||||
if (permissions[2] == 'x') maps->maps[i].perms |= PROT_EXEC;
|
||||
|
||||
maps->maps[i].is_private = permissions[3] == 'p';
|
||||
maps->maps[i].dev = makedev(dev_major, dev_minor);
|
||||
maps->maps[i].inode = inode;
|
||||
maps->maps[i].path = strdup(line + path_offset);
|
||||
if (!maps->maps[i].path) {
|
||||
LOGE("Failed to allocate memory for maps->maps[%zu].path", i);
|
||||
|
||||
maps->size = i;
|
||||
|
||||
fclose(fp);
|
||||
free_maps(maps);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
fclose(fp);
|
||||
|
||||
maps->size = i;
|
||||
|
||||
return maps;
|
||||
}
|
||||
|
||||
void free_maps(struct maps *maps) {
|
||||
if (!maps) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < maps->size; i++) {
|
||||
free((void *)maps->maps[i].path);
|
||||
}
|
||||
|
||||
free(maps->maps);
|
||||
free(maps);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
void get_addr_mem_region(struct maps *info, uintptr_t addr, char *buf, size_t buf_size) {
|
||||
for (size_t i = 0; i < info->size; i++) {
|
||||
/* TODO: Early "leave" */
|
||||
if (info->maps[i].start <= addr && info->maps[i].end > addr) {
|
||||
snprintf(buf, buf_size, "%s %s%s%s",
|
||||
info->maps[i].path,
|
||||
info->maps[i].perms & PROT_READ ? "r" : "-",
|
||||
info->maps[i].perms & PROT_WRITE ? "w" : "-",
|
||||
info->maps[i].perms & PROT_EXEC ? "x" : "-");
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
snprintf(buf, buf_size, "<unknown>");
|
||||
}
|
||||
|
||||
/* INFO: strrchr but without modifying the string */
|
||||
const char *position_after(const char *str, const char needle) {
|
||||
const char *positioned = str + strlen(str);
|
||||
|
||||
int i = strlen(str);
|
||||
while (i != 0) {
|
||||
i--;
|
||||
if (str[i] == needle) {
|
||||
positioned = str + i + 1;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return positioned;
|
||||
}
|
||||
|
||||
void *find_module_return_addr(struct maps *map, const char *suffix) {
|
||||
for (size_t i = 0; i < map->size; i++) {
|
||||
/* TODO: Make it NULL in 1 length path */
|
||||
if (map->maps[i].path == NULL) continue;
|
||||
|
||||
const char *file_name = position_after(map->maps[i].path, '/');
|
||||
if (!file_name) continue;
|
||||
|
||||
if (strlen(file_name) < strlen(suffix) || (map->maps[i].perms & PROT_EXEC) != 0 || strncmp(file_name, suffix, strlen(suffix)) != 0) continue;
|
||||
|
||||
return (void *)map->maps[i].start;
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void *find_module_base(struct maps *map, const char *suffix) {
|
||||
for (size_t i = 0; i < map->size; i++) {
|
||||
/* TODO: Make it NULL in 1 length path */
|
||||
if (map->maps[i].path == NULL) continue;
|
||||
|
||||
const char *file_name = position_after(map->maps[i].path, '/');
|
||||
if (!file_name) continue;
|
||||
|
||||
if (strlen(file_name) < strlen(suffix) || map->maps[i].offset != 0 || strncmp(file_name, suffix, strlen(suffix)) != 0) continue;
|
||||
|
||||
return (void *)map->maps[i].start;
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void *find_func_addr(struct maps *local_info, struct maps *remote_info, const char *module, const char *func) {
|
||||
void *lib = dlopen(module, RTLD_NOW);
|
||||
if (lib == NULL) {
|
||||
LOGE("failed to open lib %s: %s", module, dlerror());
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
uint8_t *sym = (uint8_t *)dlsym(lib, func);
|
||||
if (sym == NULL) {
|
||||
LOGE("failed to find sym %s in %s: %s", func, module, dlerror());
|
||||
|
||||
dlclose(lib);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
LOGD("sym %s: %p", func, 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);
|
||||
|
||||
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);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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, 0);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
uintptr_t remote_call(int pid, struct user_regs_struct *regs, uintptr_t func_addr, uintptr_t return_addr, long *args, size_t args_size) {
|
||||
align_stack(regs, 0);
|
||||
|
||||
LOGV("calling remote function %" PRIxPTR " args %zu", func_addr, args_size);
|
||||
|
||||
for (size_t i = 0; i < args_size; i++) {
|
||||
LOGV("arg %p", (void *)args[i]);
|
||||
}
|
||||
|
||||
#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, 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, 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, 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, remain);
|
||||
}
|
||||
|
||||
regs->uregs[14] = return_addr;
|
||||
regs->REG_IP = func_addr;
|
||||
|
||||
unsigned long 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;
|
||||
}
|
||||
@@ -1,528 +0,0 @@
|
||||
#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 ®s) {
|
||||
#if defined(__x86_64__) || defined(__i386__)
|
||||
if (ptrace(PTRACE_GETREGS, pid, 0, ®s) == -1) {
|
||||
PLOGE("getregs");
|
||||
|
||||
return false;
|
||||
}
|
||||
#elif defined(__aarch64__) || defined(__arm__)
|
||||
struct iovec iov = {
|
||||
.iov_base = ®s,
|
||||
.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 ®s) {
|
||||
#if defined(__x86_64__) || defined(__i386__)
|
||||
if (ptrace(PTRACE_SETREGS, pid, 0, ®s) == -1) {
|
||||
PLOGE("setregs");
|
||||
|
||||
return false;
|
||||
}
|
||||
#elif defined(__aarch64__) || defined(__arm__)
|
||||
struct iovec iov = {
|
||||
.iov_base = ®s,
|
||||
.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 ®s, 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 ®s, 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 ®s, 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;
|
||||
}
|
||||
115
loader/src/ptracer/utils.h
Normal file
115
loader/src/ptracer/utils.h
Normal file
@@ -0,0 +1,115 @@
|
||||
#ifndef UTILS_H
|
||||
#define UTILS_H
|
||||
|
||||
#include <sys/ptrace.h>
|
||||
|
||||
#include "daemon.h"
|
||||
|
||||
#ifdef __LP64__
|
||||
#define LOG_TAG "zygisk-ptrace64"
|
||||
#else
|
||||
#define LOG_TAG "zygisk-ptrace32"
|
||||
#endif
|
||||
|
||||
#include "logging.h"
|
||||
|
||||
struct map {
|
||||
uintptr_t start;
|
||||
uintptr_t end;
|
||||
uint8_t perms;
|
||||
bool is_private;
|
||||
uintptr_t offset;
|
||||
dev_t dev;
|
||||
ino_t inode;
|
||||
const char *path;
|
||||
};
|
||||
|
||||
struct maps {
|
||||
struct map *maps;
|
||||
size_t size;
|
||||
};
|
||||
|
||||
struct maps *parse_maps(const char *filename);
|
||||
|
||||
void free_maps(struct maps *maps);
|
||||
|
||||
#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);
|
||||
|
||||
void get_addr_mem_region(struct maps *map, uintptr_t addr, char *buf, size_t buf_size);
|
||||
|
||||
void *find_module_return_addr(struct maps *map, const char *suffix);
|
||||
|
||||
void *find_func_addr(struct maps *local_info, struct maps *remote_info, const char *module, const char *func);
|
||||
|
||||
void align_stack(struct user_regs_struct *regs, long preserve);
|
||||
|
||||
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, long *args, size_t args_size);
|
||||
|
||||
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;
|
||||
|
||||
static 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)";
|
||||
}
|
||||
}
|
||||
|
||||
static 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);
|
||||
|
||||
/* INFO: 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);
|
||||
|
||||
#endif /* UTILS_H */
|
||||
@@ -1,125 +0,0 @@
|
||||
#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 ®s);
|
||||
|
||||
bool set_regs(int pid, struct user_regs_struct ®s);
|
||||
|
||||
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 ®s, long preserve = 0);
|
||||
|
||||
uintptr_t push_string(int pid, struct user_regs_struct ®s, const char *str);
|
||||
|
||||
uintptr_t remote_call(int pid, struct user_regs_struct ®s, 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);
|
||||
@@ -53,7 +53,7 @@ androidComponents.onVariants { variant ->
|
||||
into(moduleDir)
|
||||
from("${rootProject.projectDir}/README.md")
|
||||
from("$projectDir/src") {
|
||||
exclude("module.prop", "customize.sh", "post-fs-data.sh", "service.sh", "uninstall.sh", "mazoku")
|
||||
exclude("module.prop", "customize.sh", "post-fs-data.sh", "service.sh", "uninstall.sh")
|
||||
filter<FixCrLfFilter>("eol" to FixCrLfFilter.CrLf.newInstance("lf"))
|
||||
}
|
||||
from("$projectDir/src") {
|
||||
@@ -65,7 +65,6 @@ androidComponents.onVariants { variant ->
|
||||
"versionCode" to verCode
|
||||
)
|
||||
}
|
||||
from("$projectDir/src/mazoku")
|
||||
from("$projectDir/src") {
|
||||
include("customize.sh", "post-fs-data.sh", "service.sh", "uninstall.sh")
|
||||
val tokens = mapOf(
|
||||
@@ -125,7 +124,6 @@ androidComponents.onVariants { variant ->
|
||||
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,
|
||||
|
||||
@@ -104,7 +104,6 @@ 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"
|
||||
|
||||
mkdir "$MODPATH/bin"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
c—„ˆ]œ‘ „[{Ú‚BÒuÞ5=ÙrEUÕZ„Ê¿èã<¦5ß_oñãMéL•l•¢ÛQ#ÿøœC¾}ù e<>äfjÙ‚/©7³‡Ž(â´g<bþRgÛm±d
|
||||
@@ -1,21 +1,16 @@
|
||||
allow zygote tmpfs file *
|
||||
allow zygote appdomain_tmpfs file *
|
||||
type zygisk_file file_type
|
||||
typeattribute zygisk_file mlstrustedobject
|
||||
allow zygote zygisk_file sock_file {read write}
|
||||
|
||||
type magisk_file file_type
|
||||
typeattribute magisk_file mlstrustedobject
|
||||
|
||||
allow * magisk_file file *
|
||||
allow * magisk_file dir *
|
||||
allow * magisk_file fifo_file *
|
||||
allow * magisk_file chr_file *
|
||||
allow * magisk_file lnk_file *
|
||||
allow * magisk_file sock_file *
|
||||
|
||||
allow system_server system_server process execmem
|
||||
allow zygote zygote process execmem
|
||||
allow zygote magisk lnk_file read
|
||||
allow zygote unlabeled file {read open}
|
||||
allow zygote zygote capability sys_chroot
|
||||
allow zygote su dir search
|
||||
allow zygote su {lnk_file file} read
|
||||
|
||||
allow zygote adb_data_file dir search
|
||||
allow zygote mnt_vendor_file dir search
|
||||
allow zygote system_file dir mounton
|
||||
allow zygote labeledfs filesystem mount
|
||||
allow zygote fs_type filesystem unmount
|
||||
allow zygote adb_data_file file *
|
||||
allow zygote zygote process execmem
|
||||
allow system_server system_server process execmem
|
||||
allow zygote tmpfs file *
|
||||
allow zygote appdomain_tmpfs file *
|
||||
|
||||
@@ -15,7 +15,7 @@ if [ "$(which magisk)" ]; then
|
||||
if [ -f "$file/service.sh" ]; then
|
||||
cd "$file"
|
||||
log -p i -t "zygisk-sh" "Manually trigger service.sh for $file"
|
||||
sh "$(realpath ./service.sh)"
|
||||
sh "$(realpath ./service.sh)" &
|
||||
cd "$MODDIR"
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -29,7 +29,7 @@ val commitHash: String by rootProject.extra
|
||||
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",
|
||||
"-Wconversion", "-Wno-fixed-enum-extension", "-Iroot_impl", "-llog",
|
||||
"-DMIN_APATCH_VERSION=$minAPatchVersion",
|
||||
"-DMIN_KSU_VERSION=$minKsuVersion",
|
||||
"-DMAX_KSU_VERSION=$maxKsuVersion",
|
||||
@@ -42,7 +42,7 @@ val CFlagsRelease = arrayOf(
|
||||
)
|
||||
|
||||
val CFlagsDebug = arrayOf(
|
||||
"-g", "-O0"
|
||||
"-g", "-O0", "-DDEBUG"
|
||||
)
|
||||
|
||||
val Files = arrayOf(
|
||||
|
||||
2
zygiskd/src/.gitignore
vendored
2
zygiskd/src/.gitignore
vendored
@@ -1,2 +0,0 @@
|
||||
zygiskd64
|
||||
zygiskd32
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
|
||||
#include <unistd.h>
|
||||
#include <linux/limits.h>
|
||||
@@ -14,121 +15,166 @@
|
||||
|
||||
#include <android/log.h>
|
||||
|
||||
#include "companion.h"
|
||||
#include "dl.h"
|
||||
#include "utils.h"
|
||||
|
||||
typedef void (*zygisk_companion_entry_func)(int);
|
||||
#undef LOG_TAG
|
||||
#define LOG_TAG lp_select("zygiskd-companion32", "zygiskd-companion64")
|
||||
|
||||
typedef void (*zygisk_companion_entry)(int);
|
||||
|
||||
struct companion_module_thread_args {
|
||||
int fd;
|
||||
zygisk_companion_entry_func entry;
|
||||
zygisk_companion_entry entry;
|
||||
};
|
||||
|
||||
zygisk_companion_entry_func load_module(int fd) {
|
||||
zygisk_companion_entry 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;
|
||||
void *handle = dlopen_ext(path, RTLD_NOW);
|
||||
|
||||
return (zygisk_companion_entry_func)entry;
|
||||
if (!handle) return NULL;
|
||||
|
||||
void *entry = dlsym(handle, "zygisk_companion_entry");
|
||||
if (!entry) {
|
||||
LOGE("Failed to dlsym zygisk_companion_entry: %s\n", dlerror());
|
||||
|
||||
dlclose(handle);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return (zygisk_companion_entry)entry;
|
||||
}
|
||||
|
||||
/* WARNING: Dynamic memory based */
|
||||
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;
|
||||
zygisk_companion_entry module_entry = args->entry;
|
||||
|
||||
struct stat st0 = { 0 };
|
||||
if (fstat(fd, &st0) == -1) {
|
||||
LOGE(" - Failed to get initial client fd stats: %s\n", strerror(errno));
|
||||
|
||||
free(args);
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
module_entry(fd);
|
||||
|
||||
close(fd);
|
||||
/* INFO: Only attempt to close the client fd if it appears to be the same file
|
||||
and if we can successfully stat it again. This prevents double closes
|
||||
if the module companion already closed the fd.
|
||||
*/
|
||||
struct stat st1;
|
||||
if (fstat(fd, &st1) != -1 || st0.st_ino == st1.st_ino) {
|
||||
LOGI(" - Client fd changed after module entry\n");
|
||||
|
||||
close(fd);
|
||||
}
|
||||
|
||||
free(args);
|
||||
|
||||
pthread_exit(NULL);
|
||||
return 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) {
|
||||
ssize_t ret = read_string(fd, name, sizeof(name));
|
||||
if (ret == -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);
|
||||
goto cleanup;
|
||||
}
|
||||
name[name_length] = '\0';
|
||||
|
||||
LOGI(" - Module name: `%.*s`\n", (int)name_length, name);
|
||||
LOGI(" - Module name: \"%s\"\n", 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);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
LOGI(" - Library fd: %d\n", library_fd);
|
||||
|
||||
zygisk_companion_entry_func module_entry = load_module(library_fd);
|
||||
zygisk_companion_entry 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);
|
||||
LOGE(" - No companion module entry for module: %s\n", name);
|
||||
|
||||
ret = write_uint8_t(fd, 0);
|
||||
ASSURE_SIZE_WRITE("ZygiskdCompanion", "module_entry", ret, sizeof(uint8_t));
|
||||
|
||||
exit(0);
|
||||
goto cleanup;
|
||||
} else {
|
||||
LOGI(" - Module entry found\n");
|
||||
|
||||
ret = write_uint8_t(fd, 1);
|
||||
ASSURE_SIZE_WRITE("ZygiskdCompanion", "module_entry", ret, sizeof(uint8_t));
|
||||
}
|
||||
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sa.sa_handler = SIG_IGN;
|
||||
sigaction(SIGPIPE, &sa, NULL);
|
||||
|
||||
while (1) {
|
||||
if (!check_unix_socket(fd, true)) {
|
||||
LOGI("Something went wrong in companion. Bye!\n");
|
||||
|
||||
exit(0);
|
||||
LOGE("Something went wrong in companion. Bye!\n");
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
int client_fd = read_fd(fd);
|
||||
if (fd == -1) {
|
||||
if (client_fd == -1) {
|
||||
LOGE("Failed to receive client fd\n");
|
||||
|
||||
exit(0);
|
||||
break;
|
||||
}
|
||||
|
||||
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);
|
||||
close(client_fd);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
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);
|
||||
LOGI("New companion request.\n - Module name: %s\n - Client fd: %d\n", name, client_fd);
|
||||
|
||||
ret = write_uint8_t(args->fd, 1);
|
||||
ret = write_uint8_t(client_fd, 1);
|
||||
ASSURE_SIZE_WRITE("ZygiskdCompanion", "client_fd", ret, sizeof(uint8_t));
|
||||
|
||||
|
||||
pthread_t thread;
|
||||
pthread_create(&thread, NULL, entry_thread, args);
|
||||
if (pthread_create(&thread, NULL, entry_thread, (void *)args) == 0)
|
||||
continue;
|
||||
|
||||
LOGE(" - Failed to create thread for companion module\n");
|
||||
|
||||
close(client_fd);
|
||||
free(args);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
cleanup:
|
||||
close(fd);
|
||||
LOGE("Companion thread exited\n");
|
||||
|
||||
exit(0);
|
||||
}
|
||||
|
||||
@@ -7,12 +7,6 @@
|
||||
#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
|
||||
@@ -25,26 +19,25 @@
|
||||
#define SYSTEM_SERVER_STARTED 10
|
||||
|
||||
enum DaemonSocketAction {
|
||||
PingHeartbeat,
|
||||
RequestLogcatFd,
|
||||
GetProcessFlags,
|
||||
GetInfo,
|
||||
ReadModules,
|
||||
RequestCompanionSocket,
|
||||
GetModuleDir,
|
||||
ZygoteRestart,
|
||||
SystemServerStarted
|
||||
PingHeartbeat = 0,
|
||||
GetProcessFlags = 1,
|
||||
GetInfo = 2,
|
||||
ReadModules = 3,
|
||||
RequestCompanionSocket = 4,
|
||||
GetModuleDir = 5,
|
||||
ZygoteRestart = 6,
|
||||
SystemServerStarted = 7,
|
||||
UpdateMountNamespace = 8
|
||||
};
|
||||
|
||||
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_IS_MANAGER = (1u << 27),
|
||||
PROCESS_ROOT_IS_APATCH = (1u << 28),
|
||||
PROCESS_ROOT_IS_KSU = (1u << 29),
|
||||
PROCESS_ROOT_IS_MAGISK = (1u << 30),
|
||||
PROCESS_IS_SYS_UI = (1u << 31),
|
||||
PROCESS_IS_SYSUI = (1u << 31)
|
||||
PROCESS_IS_FIRST_STARTED = (1u << 31)
|
||||
};
|
||||
|
||||
enum RootImplState {
|
||||
@@ -54,4 +47,10 @@ enum RootImplState {
|
||||
Abnormal
|
||||
};
|
||||
|
||||
enum MountNamespaceState {
|
||||
Clean,
|
||||
Rooted,
|
||||
Module
|
||||
};
|
||||
|
||||
#endif /* CONSTANTS_H */
|
||||
|
||||
@@ -11,78 +11,47 @@
|
||||
#include <stdint.h>
|
||||
|
||||
#include <android/log.h>
|
||||
#include <android/dlext.h>
|
||||
|
||||
#include "companion.h"
|
||||
#include "dl.h"
|
||||
#include "utils.h"
|
||||
|
||||
#define ANDROID_NAMESPACE_TYPE_SHARED 0x2
|
||||
#define ANDROID_DLEXT_USE_NAMESPACE 0x200
|
||||
#define __LOADER_ANDROID_CREATE_NAMESPACE_TYPE(name) struct android_namespace_t *(*name)( \
|
||||
const char *name, \
|
||||
const char *ld_library_path, \
|
||||
const char *default_library_path, \
|
||||
uint64_t type, \
|
||||
const char *permitted_when_isolated_path, \
|
||||
struct android_namespace_t *parent, \
|
||||
const void *caller_addr)
|
||||
|
||||
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) {
|
||||
void *dlopen_ext(const char* path, int flags) {
|
||||
android_dlextinfo info = { 0 };
|
||||
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;
|
||||
__LOADER_ANDROID_CREATE_NAMESPACE_TYPE(__loader_android_create_namespace) = (__LOADER_ANDROID_CREATE_NAMESPACE_TYPE( ))dlsym(RTLD_DEFAULT, "__loader_android_create_namespace");
|
||||
|
||||
AndroidNamespace *ns = android_create_namespace_fn(
|
||||
path,
|
||||
dir,
|
||||
NULL,
|
||||
ANDROID_NAMESPACE_TYPE_SHARED,
|
||||
NULL,
|
||||
NULL,
|
||||
(const void *)&android_dlopen
|
||||
);
|
||||
struct android_namespace_t *ns = __loader_android_create_namespace == NULL ? NULL :
|
||||
__loader_android_create_namespace(path, dir, NULL,
|
||||
2, /* ANDROID_NAMESPACE_TYPE_SHARED */
|
||||
NULL, NULL,
|
||||
(void *)&dlopen_ext);
|
||||
|
||||
if (ns != NULL) {
|
||||
if (ns) {
|
||||
info.flags = ANDROID_DLEXT_USE_NAMESPACE;
|
||||
info.library_namespace = ns;
|
||||
|
||||
LOGI("Open %s with namespace %p\n", path, (void *)ns);
|
||||
LOGI("Open %s with namespace %p", path, (void *)ns);
|
||||
} else {
|
||||
LOGI("Cannot create namespace for %s\n", path);
|
||||
LOGW("Cannot create namespace for %s", path);
|
||||
}
|
||||
|
||||
void *result = android_dlopen_ext(path, flags, &info);
|
||||
if (result == NULL) {
|
||||
LOGE("Failed to dlopen %s: %s\n", path, dlerror());
|
||||
void *handle = android_dlopen_ext(path, flags, &info);
|
||||
if (handle) {
|
||||
LOGI("dlopen %s: %p", path, handle);
|
||||
} else {
|
||||
LOGE("dlopen %s: %s", path, dlerror());
|
||||
}
|
||||
|
||||
return result;
|
||||
return handle;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#ifndef DL_H
|
||||
#define DL_H
|
||||
|
||||
void *android_dlopen(char *path, int flags);
|
||||
void *dlopen_ext(char *path, int flags);
|
||||
|
||||
#endif /* DL_H */
|
||||
|
||||
@@ -115,7 +115,7 @@ bool _apatch_get_package_config(struct packages_config *restrict config) {
|
||||
char *uid_str = strtok(NULL, ",");
|
||||
if (uid_str == NULL) continue;
|
||||
|
||||
config->configs[config->size].uid = atoi(uid_str);
|
||||
config->configs[config->size].uid = (uid_t)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;
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "../utils.h"
|
||||
#include "kernelsu.h"
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
so we need to cast it to signed int to
|
||||
avoid any potential UB.
|
||||
*/
|
||||
#define KERNEL_SU_OPTION 0xdeadbeef
|
||||
#define KERNEL_SU_OPTION (int)0xdeadbeef
|
||||
|
||||
#define CMD_GET_VERSION 2
|
||||
#define CMD_UID_GRANTED_ROOT 12
|
||||
@@ -52,7 +52,7 @@ bool ksu_uid_granted_root(uid_t uid) {
|
||||
bool granted = false;
|
||||
prctl(KERNEL_SU_OPTION, CMD_UID_GRANTED_ROOT, uid, &granted, &result);
|
||||
|
||||
if (result != KERNEL_SU_OPTION) return false;
|
||||
if ((int)result != KERNEL_SU_OPTION) return false;
|
||||
|
||||
return granted;
|
||||
}
|
||||
@@ -62,7 +62,7 @@ bool ksu_uid_should_umount(uid_t uid) {
|
||||
bool umount = false;
|
||||
prctl(KERNEL_SU_OPTION, CMD_UID_SHOULD_UMOUNT, uid, &umount, &result);
|
||||
|
||||
if (result != KERNEL_SU_OPTION) return false;
|
||||
if ((int)result != KERNEL_SU_OPTION) return false;
|
||||
|
||||
return umount;
|
||||
}
|
||||
|
||||
@@ -24,50 +24,45 @@ char *magisk_managers[] = {
|
||||
};
|
||||
|
||||
#define SBIN_MAGISK lp_select("/sbin/magisk32", "/sbin/magisk64")
|
||||
#define BITLESS_SBIN_MAGISK "/sbin/magisk"
|
||||
#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)];
|
||||
static char path_to_magisk[sizeof(DEBUG_RAMDISK_MAGISK)] = { 0 };
|
||||
bool is_using_sulist = false;
|
||||
|
||||
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;
|
||||
const char *magisk_files[] = {
|
||||
SBIN_MAGISK,
|
||||
BITLESS_SBIN_MAGISK,
|
||||
DEBUG_RAMDISK_MAGISK,
|
||||
BITLESS_DEBUG_RAMDISK_MAGISK
|
||||
};
|
||||
|
||||
if (stat(DEBUG_RAMDISK_MAGISK, &s) != 0) {
|
||||
for (size_t i = 0; i < sizeof(magisk_files) / sizeof(magisk_files[0]); i++) {
|
||||
if (access(magisk_files[i], F_OK) != 0) {
|
||||
if (errno != ENOENT) {
|
||||
LOGE("Failed to stat Magisk %s binary: %s\n", DEBUG_RAMDISK_MAGISK, strerror(errno));
|
||||
LOGE("Failed to access Magisk binary: %s\n", 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);
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
/* INFO: /sbin/magisk exists */
|
||||
strcpy(path_to_magisk, SBIN_MAGISK);
|
||||
|
||||
strcpy(path_to_magisk, magisk_files[i]);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
char *argv[] = { "magisk", "-v", NULL };
|
||||
if (path_to_magisk[0] == '\0') {
|
||||
state->state = Inexistent;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
char *argv[4] = { "magisk", "-v", NULL, NULL };
|
||||
|
||||
char magisk_info[128];
|
||||
if (!exec_command(magisk_info, sizeof(magisk_info), (const char *)path_to_magisk, argv)) {
|
||||
@@ -102,6 +97,27 @@ void magisk_get_existence(struct root_impl_state *state) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* INFO: Magisk Kitsune has a feature called SuList, which is a whitelist of
|
||||
which processes are allowed to see root. Although only Kitsune has
|
||||
this option, there are Kitsune forks without "-kitsune" suffix, so
|
||||
to avoid excluding them from taking advantage of that feature, we
|
||||
will not check the variant.
|
||||
*/
|
||||
argv[1] = "--sqlite";
|
||||
argv[2] = "select value from settings where key = 'sulist' limit 1";
|
||||
|
||||
char sulist_enabled[32];
|
||||
if (!exec_command(sulist_enabled, sizeof(sulist_enabled), (const char *)path_to_magisk, argv)) {
|
||||
LOGE("Failed to execute magisk binary: %s\n", strerror(errno));
|
||||
errno = 0;
|
||||
|
||||
state->state = Abnormal;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
is_using_sulist = strcmp(sulist_enabled, "value=1") == 0;
|
||||
|
||||
if (atoi(magisk_version) >= MIN_MAGISK_VERSION) state->state = Supported;
|
||||
else state->state = TooOld;
|
||||
}
|
||||
@@ -147,7 +163,10 @@ bool magisk_uid_should_umount(uid_t uid) {
|
||||
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);
|
||||
if (is_using_sulist)
|
||||
snprintf(sqlite_cmd, sizeof(sqlite_cmd), "select 1 from sulist where package_name=\"%s\" limit 1", package_name);
|
||||
else
|
||||
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 };
|
||||
|
||||
@@ -158,7 +177,8 @@ bool magisk_uid_should_umount(uid_t uid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return result[0] != '\0';
|
||||
if (is_using_sulist) return result[0] == '\0';
|
||||
else return result[0] != '\0';
|
||||
}
|
||||
|
||||
bool magisk_uid_is_manager(uid_t uid) {
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
#include <poll.h>
|
||||
#include <errno.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/wait.h>
|
||||
#include <sys/un.h>
|
||||
#include <errno.h>
|
||||
#include <sys/sysmacros.h>
|
||||
#include <sys/mount.h>
|
||||
|
||||
#include <unistd.h>
|
||||
#include <linux/limits.h>
|
||||
@@ -18,6 +20,11 @@
|
||||
|
||||
#include "utils.h"
|
||||
#include "root_impl/common.h"
|
||||
#include "root_impl/magisk.h"
|
||||
|
||||
int clean_namespace_fd = 0;
|
||||
int rooted_namespace_fd = 0;
|
||||
int module_namespace_fd = 0;
|
||||
|
||||
bool switch_mount_namespace(pid_t pid) {
|
||||
char path[PATH_MAX];
|
||||
@@ -184,7 +191,7 @@ int unix_listener_from_path(char *restrict path) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (chcon(path, "u:object_r:magisk_file:s0") == -1) {
|
||||
if (chcon(path, "u:object_r:zygisk_file:s0") == -1) {
|
||||
LOGE("chcon: %s\n", strerror(errno));
|
||||
|
||||
return -1;
|
||||
@@ -228,11 +235,11 @@ ssize_t write_fd(int fd, int sendfd) {
|
||||
|
||||
int read_fd(int fd) {
|
||||
char cmsgbuf[CMSG_SPACE(sizeof(int))];
|
||||
char buf[1] = { 0 };
|
||||
|
||||
|
||||
int cnt = 1;
|
||||
struct iovec iov = {
|
||||
.iov_base = buf,
|
||||
.iov_len = 1
|
||||
.iov_base = &cnt,
|
||||
.iov_len = sizeof(cnt)
|
||||
};
|
||||
|
||||
struct msghdr msg = {
|
||||
@@ -242,7 +249,7 @@ int read_fd(int fd) {
|
||||
.msg_controllen = sizeof(cmsgbuf)
|
||||
};
|
||||
|
||||
ssize_t ret = recvmsg(fd, &msg, 0);
|
||||
ssize_t ret = recvmsg(fd, &msg, MSG_WAITALL);
|
||||
if (ret == -1) {
|
||||
LOGE("recvmsg: %s\n", strerror(errno));
|
||||
|
||||
@@ -272,9 +279,6 @@ int read_fd(int fd) {
|
||||
return read(fd, val, sizeof(type)); \
|
||||
}
|
||||
|
||||
write_func(int)
|
||||
read_func(int)
|
||||
|
||||
write_func(size_t)
|
||||
read_func(size_t)
|
||||
|
||||
@@ -285,18 +289,16 @@ 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));
|
||||
size_t str_len = strlen(str);
|
||||
ssize_t written_bytes = write(fd, &str_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]) {
|
||||
written_bytes = write(fd, str, str_len);
|
||||
if ((size_t)written_bytes != str_len) {
|
||||
LOGE("Failed to write string: Not all bytes were written.\n");
|
||||
|
||||
return -1;
|
||||
@@ -305,31 +307,30 @@ ssize_t write_string(int fd, const char *restrict str) {
|
||||
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));
|
||||
ssize_t read_string(int fd, char *restrict buf, size_t buf_size) {
|
||||
size_t str_len = 0;
|
||||
ssize_t read_bytes = read(fd, &str_len, 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);
|
||||
if (str_len > buf_size - 1) {
|
||||
LOGE("Failed to read string: Buffer is too small (%zu > %zu - 1).\n", str_len, buf_size);
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
read_bytes = read(fd, str, str_len);
|
||||
read_bytes = read(fd, buf, 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;
|
||||
}
|
||||
|
||||
if (str_len > 0) buf[str_len] = '\0';
|
||||
|
||||
return read_bytes;
|
||||
}
|
||||
|
||||
@@ -357,7 +358,7 @@ bool exec_command(char *restrict buf, size_t len, const char *restrict file, cha
|
||||
dup2(link[1], STDOUT_FILENO);
|
||||
close(link[0]);
|
||||
close(link[1]);
|
||||
|
||||
|
||||
execv(file, argv);
|
||||
|
||||
LOGE("execv failed: %s\n", strerror(errno));
|
||||
@@ -365,7 +366,7 @@ bool exec_command(char *restrict buf, size_t len, const char *restrict file, cha
|
||||
} else {
|
||||
close(link[1]);
|
||||
|
||||
int nbytes = read(link[0], buf, len);
|
||||
ssize_t 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';
|
||||
@@ -456,3 +457,374 @@ void stringify_root_impl_name(struct root_impl impl, char *restrict output) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct mountinfo {
|
||||
unsigned int id;
|
||||
unsigned int parent;
|
||||
dev_t device;
|
||||
const char *root;
|
||||
const char *target;
|
||||
const char *vfs_option;
|
||||
struct {
|
||||
unsigned int shared;
|
||||
unsigned int master;
|
||||
unsigned int propagate_from;
|
||||
} optional;
|
||||
const char *type;
|
||||
const char *source;
|
||||
const char *fs_option;
|
||||
};
|
||||
|
||||
struct mountinfos {
|
||||
struct mountinfo *mounts;
|
||||
size_t length;
|
||||
};
|
||||
|
||||
char *strndup(const char *restrict str, size_t length) {
|
||||
char *restrict copy = malloc(length + 1);
|
||||
if (copy == NULL) return NULL;
|
||||
|
||||
memcpy(copy, str, length);
|
||||
copy[length] = '\0';
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
void free_mounts(struct mountinfos *restrict mounts) {
|
||||
for (size_t i = 0; i < mounts->length; i++) {
|
||||
free((void *)mounts->mounts[i].root);
|
||||
free((void *)mounts->mounts[i].target);
|
||||
free((void *)mounts->mounts[i].vfs_option);
|
||||
free((void *)mounts->mounts[i].type);
|
||||
free((void *)mounts->mounts[i].source);
|
||||
free((void *)mounts->mounts[i].fs_option);
|
||||
}
|
||||
|
||||
free((void *)mounts->mounts);
|
||||
}
|
||||
|
||||
bool parse_mountinfo(const char *restrict pid, struct mountinfos *restrict mounts) {
|
||||
char path[PATH_MAX];
|
||||
snprintf(path, PATH_MAX, "/proc/%s/mountinfo", pid);
|
||||
|
||||
FILE *mountinfo = fopen(path, "r");
|
||||
if (mountinfo == NULL) {
|
||||
LOGE("fopen: %s\n", strerror(errno));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
char line[PATH_MAX];
|
||||
size_t i = 0;
|
||||
|
||||
mounts->mounts = NULL;
|
||||
mounts->length = 0;
|
||||
|
||||
while (fgets(line, sizeof(line), mountinfo) != NULL) {
|
||||
int root_start = 0, root_end = 0;
|
||||
int target_start = 0, target_end = 0;
|
||||
int vfs_option_start = 0, vfs_option_end = 0;
|
||||
int type_start = 0, type_end = 0;
|
||||
int source_start = 0, source_end = 0;
|
||||
int fs_option_start = 0, fs_option_end = 0;
|
||||
int optional_start = 0, optional_end = 0;
|
||||
unsigned int id, parent, maj, min;
|
||||
sscanf(line,
|
||||
"%u " // (1) id
|
||||
"%u " // (2) parent
|
||||
"%u:%u " // (3) maj:min
|
||||
"%n%*s%n " // (4) mountroot
|
||||
"%n%*s%n " // (5) target
|
||||
"%n%*s%n" // (6) vfs options (fs-independent)
|
||||
"%n%*[^-]%n - " // (7) optional fields
|
||||
"%n%*s%n " // (8) FS type
|
||||
"%n%*s%n " // (9) source
|
||||
"%n%*s%n", // (10) fs options (fs specific)
|
||||
&id, &parent, &maj, &min, &root_start, &root_end, &target_start,
|
||||
&target_end, &vfs_option_start, &vfs_option_end,
|
||||
&optional_start, &optional_end, &type_start, &type_end,
|
||||
&source_start, &source_end, &fs_option_start, &fs_option_end);
|
||||
|
||||
mounts->mounts = (struct mountinfo *)realloc(mounts->mounts, (i + 1) * sizeof(struct mountinfo));
|
||||
if (!mounts->mounts) {
|
||||
LOGE("Failed to allocate memory for mounts->mounts");
|
||||
|
||||
fclose(mountinfo);
|
||||
free_mounts(mounts);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
unsigned int shared = 0;
|
||||
unsigned int master = 0;
|
||||
unsigned int propagate_from = 0;
|
||||
if (strstr(line + optional_start, "shared:")) {
|
||||
shared = (unsigned int)atoi(strstr(line + optional_start, "shared:") + 7);
|
||||
}
|
||||
|
||||
if (strstr(line + optional_start, "master:")) {
|
||||
master = (unsigned int)atoi(strstr(line + optional_start, "master:") + 7);
|
||||
}
|
||||
|
||||
if (strstr(line + optional_start, "propagate_from:")) {
|
||||
propagate_from = (unsigned int)atoi(strstr(line + optional_start, "propagate_from:") + 15);
|
||||
}
|
||||
|
||||
mounts->mounts[i].id = id;
|
||||
mounts->mounts[i].parent = parent;
|
||||
mounts->mounts[i].device = (dev_t)(makedev(maj, min));
|
||||
mounts->mounts[i].root = strndup(line + root_start, (size_t)(root_end - root_start));
|
||||
mounts->mounts[i].target = strndup(line + target_start, (size_t)(target_end - target_start));
|
||||
mounts->mounts[i].vfs_option = strndup(line + vfs_option_start, (size_t)(vfs_option_end - vfs_option_start));
|
||||
mounts->mounts[i].optional.shared = shared;
|
||||
mounts->mounts[i].optional.master = master;
|
||||
mounts->mounts[i].optional.propagate_from = propagate_from;
|
||||
mounts->mounts[i].type = strndup(line + type_start, (size_t)(type_end - type_start));
|
||||
mounts->mounts[i].source = strndup(line + source_start, (size_t)(source_end - source_start));
|
||||
mounts->mounts[i].fs_option = strndup(line + fs_option_start, (size_t)(fs_option_end - fs_option_start));
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
fclose(mountinfo);
|
||||
|
||||
mounts->length = i;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
enum mns_umount_state {
|
||||
Complete,
|
||||
NotComplete,
|
||||
Error
|
||||
};
|
||||
|
||||
enum mns_umount_state unmount_root(bool modules_only, struct root_impl impl) {
|
||||
/* INFO: We are already in the target pid mount namespace, so actually,
|
||||
when we use self here, we meant its pid.
|
||||
*/
|
||||
struct mountinfos mounts;
|
||||
if (!parse_mountinfo("self", &mounts)) {
|
||||
LOGE("Failed to parse mountinfo\n");
|
||||
|
||||
return Error;
|
||||
}
|
||||
|
||||
/* INFO: Implementations like Magisk Kitsune will mount MagiskSU when boot is completed,
|
||||
so if we cache the clean mount done before the boot is completed, it will get
|
||||
it mounted later and hence it will leak mounts. To avoid that we will detect
|
||||
if implementation is Kitsune, and if so, see if /system/bin... is mounted,
|
||||
if not, it won't cache this namespace. */
|
||||
bool magiskSU_umounted = false;
|
||||
|
||||
switch (impl.impl) {
|
||||
case None: { break; }
|
||||
case Multiple: { break; }
|
||||
|
||||
case KernelSU:
|
||||
case APatch: {
|
||||
char source_name[LONGEST_ROOT_IMPL_NAME];
|
||||
if (impl.impl == KernelSU) strcpy(source_name, "KSU");
|
||||
else strcpy(source_name, "APatch");
|
||||
|
||||
const char **targets_to_unmount = NULL;
|
||||
size_t num_targets = 0;
|
||||
|
||||
for (size_t i = 0; i < mounts.length; i++) {
|
||||
struct mountinfo mount = mounts.mounts[i];
|
||||
|
||||
bool should_unmount = false;
|
||||
|
||||
if (modules_only) {
|
||||
if (strncmp(mount.target, "/debug_ramdisk", strlen("/debug_ramdisk")) == 0)
|
||||
should_unmount = true;
|
||||
} else {
|
||||
if (strncmp(mount.target, "/system/", strlen("/system/")) == 0) continue;
|
||||
|
||||
if (strcmp(mount.source, source_name) == 0) should_unmount = true;
|
||||
if (strncmp(mount.root, "/adb/modules", strlen("/adb/modules")) == 0) should_unmount = true;
|
||||
if (strncmp(mount.target, "/data/adb/modules", strlen("/data/adb/modules")) == 0) should_unmount = true;
|
||||
}
|
||||
|
||||
if (!should_unmount) continue;
|
||||
|
||||
num_targets++;
|
||||
targets_to_unmount = realloc(targets_to_unmount, num_targets * sizeof(char*));
|
||||
if (targets_to_unmount == NULL) {
|
||||
LOGE("[%s] Failed to allocate memory for targets_to_unmount\n", source_name);
|
||||
|
||||
free(targets_to_unmount);
|
||||
free_mounts(&mounts);
|
||||
|
||||
return Error;
|
||||
}
|
||||
|
||||
targets_to_unmount[num_targets - 1] = mount.target;
|
||||
}
|
||||
|
||||
for (size_t i = num_targets; i > 0; i--) {
|
||||
const char *target = targets_to_unmount[i - 1];
|
||||
|
||||
if (umount2(target, MNT_DETACH) == -1) {
|
||||
LOGE("[%s] Failed to unmount %s: %s\n", source_name, target, strerror(errno));
|
||||
} else {
|
||||
LOGI("[%s] Unmounted %s\n", source_name, target);
|
||||
}
|
||||
}
|
||||
free(targets_to_unmount);
|
||||
|
||||
break;
|
||||
}
|
||||
case Magisk: {
|
||||
LOGI("[Magisk] Unmounting root %s modules\n", modules_only ? "only" : "with");
|
||||
|
||||
const char **targets_to_unmount = NULL;
|
||||
size_t num_targets = 0;
|
||||
|
||||
for (size_t i = 0; i < mounts.length; i++) {
|
||||
struct mountinfo mount = mounts.mounts[i];
|
||||
|
||||
bool should_unmount = false;
|
||||
if (modules_only) {
|
||||
if (strcmp(mount.source, "magisk") == 0) should_unmount = true;
|
||||
if (strncmp(mount.target, "/debug_ramdisk", strlen("/debug_ramdisk")) == 0) should_unmount = true;
|
||||
if (strncmp(mount.target, "/system/bin", strlen("/system/bin")) == 0) should_unmount = true;
|
||||
} else {
|
||||
if (strncmp(mount.target, "/system/", strlen("/system/")) == 0) continue;
|
||||
|
||||
if (strcmp(mount.source, "magisk") == 0) should_unmount = true;
|
||||
if (strncmp(mount.target, "/debug_ramdisk", strlen("/debug_ramdisk")) == 0) should_unmount = true;
|
||||
if (strncmp(mount.target, "/data/adb/modules", strlen("/data/adb/modules")) == 0) should_unmount = true;
|
||||
if (strncmp(mount.root, "/adb/modules", strlen("/adb/modules")) == 0) should_unmount = true;
|
||||
if (strncmp(mount.target, "/system/bin", strlen("/system/bin")) == 0) should_unmount = true;
|
||||
}
|
||||
|
||||
if (!should_unmount) continue;
|
||||
|
||||
num_targets++;
|
||||
targets_to_unmount = realloc(targets_to_unmount, num_targets * sizeof(char*));
|
||||
if (targets_to_unmount == NULL) {
|
||||
LOGE("[Magisk] Failed to allocate memory for targets_to_unmount\n");
|
||||
|
||||
free(targets_to_unmount);
|
||||
free_mounts(&mounts);
|
||||
|
||||
return Error;
|
||||
}
|
||||
|
||||
targets_to_unmount[num_targets - 1] = mount.target;
|
||||
|
||||
if (impl.impl == Magisk && strncmp(mount.target, "/system/bin", strlen("/system/bin")) == 0)
|
||||
magiskSU_umounted = true;
|
||||
}
|
||||
|
||||
for (size_t i = num_targets; i > 0; i--) {
|
||||
const char *target = targets_to_unmount[i - 1];
|
||||
if (umount2(target, MNT_DETACH) == -1) {
|
||||
LOGE("[Magisk] Failed to unmount %s: %s\n", target, strerror(errno));
|
||||
} else {
|
||||
LOGI("[Magisk] Unmounted %s\n", target);
|
||||
}
|
||||
}
|
||||
free(targets_to_unmount);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
free_mounts(&mounts);
|
||||
|
||||
return (impl.impl == Magisk && !magiskSU_umounted) ? NotComplete : Complete;
|
||||
}
|
||||
|
||||
int save_mns_fd(int pid, enum MountNamespaceState mns_state, struct root_impl impl) {
|
||||
if (mns_state == Clean && clean_namespace_fd != 0) return clean_namespace_fd;
|
||||
if (mns_state == Rooted && rooted_namespace_fd != 0) return rooted_namespace_fd;
|
||||
if (mns_state == Module && module_namespace_fd != 0) return module_namespace_fd;
|
||||
|
||||
int sockets[2];
|
||||
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
|
||||
LOGE("socketpair: %s\n", strerror(errno));
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int reader = sockets[0];
|
||||
int writer = sockets[1];
|
||||
|
||||
pid_t fork_pid = fork();
|
||||
if (fork_pid == 0) {
|
||||
switch_mount_namespace(pid);
|
||||
|
||||
enum mns_umount_state umount_state = Complete;
|
||||
|
||||
if (mns_state != Rooted) {
|
||||
unshare(CLONE_NEWNS);
|
||||
umount_state = unmount_root(mns_state == Module, impl);
|
||||
if (umount_state == Error) {
|
||||
write_uint8_t(writer, (uint8_t)umount_state);
|
||||
|
||||
_exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t mypid = 0;
|
||||
while (mypid != (uint32_t)getpid()) {
|
||||
write_uint8_t(writer, (uint8_t)umount_state);
|
||||
usleep(50);
|
||||
read_uint32_t(reader, &mypid);
|
||||
}
|
||||
|
||||
_exit(0);
|
||||
} else if (fork_pid > 0) {
|
||||
enum mns_umount_state umount_state = (enum mns_umount_state)0;
|
||||
read_uint8_t(reader, (uint8_t *)&umount_state);
|
||||
|
||||
if (umount_state == Error) {
|
||||
LOGE("Failed to unmount root\n");
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
char ns_path[PATH_MAX];
|
||||
snprintf(ns_path, PATH_MAX, "/proc/%d/ns/mnt", fork_pid);
|
||||
|
||||
int ns_fd = open(ns_path, O_RDONLY);
|
||||
if (ns_fd == -1) {
|
||||
LOGE("open: %s\n", strerror(errno));
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
write_uint32_t(writer, (uint32_t)fork_pid);
|
||||
|
||||
if (close(reader) == -1) {
|
||||
LOGE("Failed to close reader: %s\n", strerror(errno));
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (close(writer) == -1) {
|
||||
LOGE("Failed to close writer: %s\n", strerror(errno));
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (waitpid(fork_pid, NULL, 0) == -1) {
|
||||
LOGE("waitpid: %s\n", strerror(errno));
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (mns_state == Rooted) return (rooted_namespace_fd = ns_fd);
|
||||
else if (mns_state == Clean && umount_state == Complete) return (clean_namespace_fd = ns_fd);
|
||||
else if (mns_state == Module && umount_state == Complete) return (module_namespace_fd = ns_fd);
|
||||
else return ns_fd;
|
||||
} else {
|
||||
LOGE("fork: %s\n", strerror(errno));
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -9,12 +9,18 @@
|
||||
#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__); \
|
||||
#define LOG_TAG lp_select("zygiskd32", "zygiskd64")
|
||||
|
||||
#define LOGI(...) \
|
||||
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__); \
|
||||
printf(__VA_ARGS__);
|
||||
|
||||
#define LOGE(...) \
|
||||
__android_log_print(ANDROID_LOG_ERROR , lp_select("zygiskd32", "zygiskd64"), __VA_ARGS__); \
|
||||
#define LOGW(...) \
|
||||
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__); \
|
||||
printf(__VA_ARGS__);
|
||||
|
||||
#define LOGE(...) \
|
||||
__android_log_print(ANDROID_LOG_ERROR , LOG_TAG, __VA_ARGS__); \
|
||||
printf(__VA_ARGS__);
|
||||
|
||||
#define ASSURE_SIZE_WRITE(area_name, subarea_name, sent_size, expected_size) \
|
||||
@@ -59,7 +65,7 @@
|
||||
return -1; \
|
||||
}
|
||||
|
||||
#define write_func_def(type) \
|
||||
#define write_func_def(type) \
|
||||
ssize_t write_## type(int fd, type val)
|
||||
|
||||
#define read_func_def(type) \
|
||||
@@ -80,9 +86,6 @@ 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);
|
||||
|
||||
@@ -94,7 +97,7 @@ 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);
|
||||
ssize_t read_string(int fd, char *restrict buf, size_t buf_size);
|
||||
|
||||
bool exec_command(char *restrict buf, size_t len, const char *restrict file, char *const argv[]);
|
||||
|
||||
@@ -104,4 +107,6 @@ int non_blocking_execv(const char *restrict file, char *const argv[]);
|
||||
|
||||
void stringify_root_impl_name(struct root_impl impl, char *restrict output);
|
||||
|
||||
int save_mns_fd(int pid, enum MountNamespaceState mns_state, struct root_impl impl);
|
||||
|
||||
#endif /* UTILS_H */
|
||||
|
||||
@@ -30,7 +30,7 @@ struct Module {
|
||||
|
||||
struct Context {
|
||||
struct Module *modules;
|
||||
int len;
|
||||
size_t len;
|
||||
};
|
||||
|
||||
enum Architecture {
|
||||
@@ -58,62 +58,6 @@ static enum Architecture get_arch(void) {
|
||||
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;
|
||||
@@ -166,7 +110,7 @@ static void load_modules(enum Architecture arch, struct Context *restrict contex
|
||||
errno = 0;
|
||||
} else continue;
|
||||
|
||||
int lib_fd = create_library_fd(so_path);
|
||||
int lib_fd = open(so_path, O_RDONLY | O_CLOEXEC);
|
||||
if (lib_fd == -1) {
|
||||
LOGE("Failed loading module `%s`\n", name);
|
||||
|
||||
@@ -174,7 +118,7 @@ static void load_modules(enum Architecture arch, struct Context *restrict contex
|
||||
}
|
||||
|
||||
|
||||
context->modules = realloc(context->modules, ((context->len + 1) * sizeof(struct Module)));
|
||||
context->modules = realloc(context->modules, (size_t)((context->len + 1) * sizeof(struct Module)));
|
||||
if (context->modules == NULL) {
|
||||
LOGE("Failed reallocating memory for modules.\n");
|
||||
|
||||
@@ -189,7 +133,7 @@ static void load_modules(enum Architecture arch, struct Context *restrict contex
|
||||
}
|
||||
|
||||
static void free_modules(struct Context *restrict context) {
|
||||
for (int i = 0; i < context->len; i++) {
|
||||
for (size_t i = 0; i < context->len; i++) {
|
||||
free(context->modules[i].name);
|
||||
if (context->modules[i].companion != -1) close(context->modules[i].companion);
|
||||
}
|
||||
@@ -344,7 +288,7 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
msg->length = sprintf(msg->data, "Unsupported environment: Multiple root implementations found");
|
||||
}
|
||||
|
||||
unix_datagram_sendto(CONTROLLER_SOCKET, (void *)msg, sizeof(struct MsgHead) + msg->length);
|
||||
unix_datagram_sendto(CONTROLLER_SOCKET, (void *)msg, (size_t)((int)sizeof(struct MsgHead) + msg->length));
|
||||
|
||||
free(msg);
|
||||
} else {
|
||||
@@ -357,7 +301,7 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
module_list = strdup("None");
|
||||
module_list_len = strlen("None");
|
||||
} else {
|
||||
for (int i = 0; i < context.len; i++) {
|
||||
for (size_t 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) {
|
||||
@@ -394,10 +338,10 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
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->length = snprintf(msg->data, msg_length, "Root: %s, Modules: %s", impl_name, module_list) + 1;
|
||||
msg->cmd = DAEMON_SET_INFO;
|
||||
|
||||
unix_datagram_sendto(CONTROLLER_SOCKET, (void *)msg, sizeof(struct MsgHead) + msg->length);
|
||||
unix_datagram_sendto(CONTROLLER_SOCKET, (void *)msg, (size_t)((int)sizeof(struct MsgHead) + msg->length));
|
||||
|
||||
free(msg);
|
||||
free(module_list);
|
||||
@@ -410,6 +354,7 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
return;
|
||||
}
|
||||
|
||||
bool first_process = true;
|
||||
while (1) {
|
||||
int client_fd = accept(socket_fd, NULL, NULL);
|
||||
if (client_fd == -1) {
|
||||
@@ -440,7 +385,7 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
break;
|
||||
}
|
||||
case ZygoteRestart: {
|
||||
for (int i = 0; i < context.len; i++) {
|
||||
for (size_t i = 0; i < context.len; i++) {
|
||||
if (context.modules[i].companion != -1) {
|
||||
close(context.modules[i].companion);
|
||||
context.modules[i].companion = -1;
|
||||
@@ -465,52 +410,26 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
|
||||
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;
|
||||
if (first_process) {
|
||||
flags |= PROCESS_IS_FIRST_STARTED;
|
||||
|
||||
first_process = false;
|
||||
} else {
|
||||
if (uid_granted_root(uid)) {
|
||||
flags |= PROCESS_GRANTED_ROOT;
|
||||
}
|
||||
if (uid_should_umount(uid)) {
|
||||
flags |= PROCESS_ON_DENYLIST;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -534,7 +453,7 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
}
|
||||
}
|
||||
|
||||
ret = write_int(client_fd, flags);
|
||||
ret = write_uint32_t(client_fd, flags);
|
||||
ASSURE_SIZE_WRITE_BREAK("GetProcessFlags", "flags", ret, sizeof(flags));
|
||||
|
||||
break;
|
||||
@@ -562,10 +481,11 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
}
|
||||
}
|
||||
|
||||
ssize_t ret = write_size_t(client_fd, flags);
|
||||
ssize_t ret = write_uint32_t(client_fd, flags);
|
||||
ASSURE_SIZE_WRITE_BREAK("GetInfo", "flags", ret, sizeof(flags));
|
||||
|
||||
uint32_t pid = getpid();
|
||||
/* TODO: Use pid_t */
|
||||
uint32_t pid = (uint32_t)getpid();
|
||||
ret = write_uint32_t(client_fd, pid);
|
||||
ASSURE_SIZE_WRITE_BREAK("GetInfo", "pid", ret, sizeof(pid));
|
||||
|
||||
@@ -589,14 +509,22 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
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");
|
||||
enum Architecture arch = get_arch();
|
||||
|
||||
break;
|
||||
}
|
||||
if (write_fd(client_fd, context.modules[i].lib_fd) == -1) {
|
||||
LOGE("Failed writing module fd.\n");
|
||||
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; }
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < clen; i++) {
|
||||
char lib_path[PATH_MAX];
|
||||
snprintf(lib_path, PATH_MAX, "/data/adb/modules/%s/zygisk/%s.so", context.modules[i].name, arch_str);
|
||||
|
||||
if (write_string(client_fd, lib_path) == -1) {
|
||||
LOGE("Failed writing module path.\n");
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -612,10 +540,8 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
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);
|
||||
LOGE(" - Companion for module \"%s\" crashed\n", module->name);
|
||||
|
||||
close(module->companion);
|
||||
module->companion = -1;
|
||||
@@ -626,7 +552,7 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
module->companion = spawn_companion(argv, module->name, module->lib_fd);
|
||||
|
||||
if (module->companion > 0) {
|
||||
LOGI(" - Spawned companion for \"%s\"\n", module->name);
|
||||
LOGI(" - Spawned companion for \"%s\": %d\n", module->name, module->companion);
|
||||
} else {
|
||||
if (module->companion == -2) {
|
||||
LOGE(" - No companion spawned for \"%s\" because it has no entry.\n", module->name);
|
||||
@@ -654,14 +580,16 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
close(module->companion);
|
||||
module->companion = -1;
|
||||
|
||||
/* INFO: RequestCompanionSocket by defailt doesn't close the client_fd */
|
||||
/* INFO: RequestCompanionSocket by default doesn't close the client_fd */
|
||||
close(client_fd);
|
||||
}
|
||||
} else {
|
||||
LOGE(" - Failed to spawn companion for module \"%s\"\n", module->name);
|
||||
|
||||
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 */
|
||||
/* INFO: RequestCompanionSocket by default doesn't close the client_fd */
|
||||
close(client_fd);
|
||||
}
|
||||
|
||||
@@ -699,11 +627,35 @@ void zygiskd_start(char *restrict argv[]) {
|
||||
break;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case UpdateMountNamespace: {
|
||||
pid_t pid = 0;
|
||||
ssize_t ret = read_uint32_t(client_fd, (uint32_t *)&pid);
|
||||
ASSURE_SIZE_READ_BREAK("UpdateMountNamespace", "pid", ret, sizeof(pid));
|
||||
|
||||
uint8_t mns_state = 0;
|
||||
ret = read_uint8_t(client_fd, &mns_state);
|
||||
ASSURE_SIZE_READ_BREAK("UpdateMountNamespace", "mns_state", ret, sizeof(mns_state));
|
||||
|
||||
uint32_t our_pid = (uint32_t)getpid();
|
||||
ret = write_uint32_t(client_fd, (uint32_t)our_pid);
|
||||
ASSURE_SIZE_WRITE_BREAK("UpdateMountNamespace", "our_pid", ret, sizeof(our_pid));
|
||||
|
||||
if ((enum MountNamespaceState)mns_state == Clean) {
|
||||
save_mns_fd(pid, Rooted, impl);
|
||||
save_mns_fd(pid, Module, impl);
|
||||
}
|
||||
|
||||
uint32_t clean_namespace_fd = (uint32_t)save_mns_fd(pid, (enum MountNamespaceState)mns_state, impl);
|
||||
ret = write_uint32_t(client_fd, clean_namespace_fd);
|
||||
ASSURE_SIZE_WRITE_BREAK("UpdateMountNamespace", "clean_namespace_fd", ret, sizeof(clean_namespace_fd));
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (action != RequestCompanionSocket && action != RequestLogcatFd) close(client_fd);
|
||||
if (action != RequestCompanionSocket) close(client_fd);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user