diff --git a/docs/README.md b/docs/README.md index 9fae39453..ecb7dad04 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,10 +1,12 @@ # Magisk Documentation +## Users + - [Installation Instructions](install.md) - [Frequently Asked Questions](faq.md) - [Magisk Changelog](changes.md) -The following sections are for developers +## Developers - [Building and Developing Magisk](build.md) (for developing Magisk itself) - [Developer Guides](guides.md) (for developers **using** Magisk) diff --git a/docs/boot.md b/docs/boot.md index 22c1dddbf..f0fcc5d2e 100644 --- a/docs/boot.md +++ b/docs/boot.md @@ -6,7 +6,7 @@ - **`initramfs`**: a section in Android's boot image that the Linux kernel will use as `rootfs`. People also use the term **ramdisk** interchangeably - **`recovery` and `boot` partition**: these 2 are actually very similar: both are Android boot images containing ramdisk and Linux kernel (plus some other stuff). The only difference is that booting `boot` partition will bring us to Android, while `recovery` has a minimalist self contained Linux environment for repairing and upgrading the device. - **SAR**: System-as-root. That is, the device uses `system` as rootdir instead of `rootfs` -- **A/B, A-only**: For devices supporting [Seamless System Updates](https://source.android.com/devices/tech/ota/ab), it will have 2 slots of all read-only partitions; we call these **A/B devices**. To differentiate, non A/B devices will be called **A-only** +- **A/B, A-only**: For devices supporting [Seamless System Updates](https://source.android.com/docs/core/ota/ab), it will have 2 slots of all read-only partitions; we call these **A/B devices**. To differentiate, non A/B devices will be called **A-only** - **2SI**: Two Stage Init. The way Android 10+ boots. More info later. Here are a few parameters to more precisely define a device's Android version: @@ -14,7 +14,7 @@ Here are a few parameters to more precisely define a device's Android version: - **LV**: Launch Version. The Android version the device is **launched** with. That is, the Android version pre-installed when the device first hit the market. - **RV**: Running Version. The Android version the device is currently running on. -We will use **Android API level** to represent LV and RV. The mapping between API level and Android versions can be seen in [this table](https://source.android.com/setup/start/build-numbers#platform-code-names-versions-api-levels-and-ndk-releases). For example: Pixel XL is released with Android 7.1, and is running Android 10, these parameters will be `(LV = 25, RV = 29)` +We will use **Android API level** to represent LV and RV. The mapping between API level and Android versions can be seen in [this table](https://source.android.com/docs/setup/start/build-numbers#platform-code-names-versions-api-levels-and-ndk-releases). For example: Pixel XL is released with Android 7.1, and is running Android 10, these parameters will be `(LV = 25, RV = 29)` ## Boot Methods @@ -27,7 +27,7 @@ Method | Initial rootdir | Final rootdir **C** | `rootfs` | `system` - **Method A - Legacy ramdisk**: This is how *all* Android devices used to boot (good old days). The kernel uses `initramfs` as rootdir, and exec `/init` to boot. - - Devices that does not fall in any of Method B and C's criteria + - Devices that do not fall in any of Method B and C's criteria - **Method B - Legacy SAR**: This method was first seen on Pixel 1. The kernel directly mounts the `system` partition as rootdir and exec `/init` to boot. - Devices with `(LV = 28)` - Google: Pixel 1 and 2. Pixel 3 and 3a when `(RV = 28)`. @@ -40,45 +40,47 @@ Method | Initial rootdir | Final rootdir ### Discussion -From documents online, Google's definition of SAR only considers how the kernel boots the device (**Initial rootdir** in the table above), meaning that only devices using **Method B** is *officially* considered an SAR device from Google's standpoint. +From documents online, Google's definition of SAR only considers how the kernel boots the device (**Initial rootdir** in the table above), meaning that only devices using **Method B** are *officially* considered SAR devices from Google's standpoint. -However for Magisk, the real difference lies in what the device ends up using when fully booted (**Final rootdir** in the table above), meaning that **as far as Magisk's concern, both Method B and C is a form of SAR**, but just implemented differently. Every instance of SAR later mentioned in this document will refer to **Magisk's definition** unless specifically says otherwise. +However for Magisk, the real difference lies in what the device ends up using when fully booted (**Final rootdir** in the table above), meaning that **as far as Magisk is concerned, both Method B and C are a form of SAR**, but just implemented differently. Every instance of SAR later mentioned in this document will refer to **Magisk's definition** unless specifically stated otherwise. The criteria for Method C is a little complicated, in layman's words: either your device is modern enough to launch with Android 10+, or you are running an Android 10+ custom ROM on a device that was using Method A. - Any Method A device running Android 10+ will automatically be using Method C - **Method B devices are stuck with Method B**, with the only exception being Pixel 3 and 3a, which Google retrofitted the device to adapt the new method. -SAR is a very important part of [Project Treble](https://source.android.com/devices/architecture#hidl) as rootdir should be tied to the platform. This is also the reason why Method B and C comes with `(LV >= ver)` criterion as Google has enforced all OEMs to comply with updated requirements every year. +SAR is a very important part of [Project Treble](https://source.android.com/docs/core/architecture#hidl) as rootdir should be tied to the platform. This is also the reason why Method B and C come with `(LV >= ver)` criteria as Google has enforced all OEMs to comply with updated requirements every year. ## Some History -When Google released the first generation Pixel, it also introduced [A/B (Seamless) System Updates](https://source.android.com/devices/tech/ota/ab). Due to [storage size concerns](https://source.android.com/devices/tech/ota/ab/ab_faqs), there are several differences compared to A-only, the most relevant one being the removal of `recovery` partition and the recovery ramdisk being merged into `boot`. +When Google released the first generation Pixel, it also introduced [A/B (Seamless) System Updates](https://source.android.com/docs/core/ota/ab). Due to [storage size concerns](https://source.android.com/docs/core/ota/ab/ab_faqs), there are several differences compared to A-only, the most relevant one being the removal of `recovery` partition and the recovery ramdisk being merged into `boot`. -Let's go back in time when Google is first designing A/B. If using SAR (only Boot Method B exists at that time), the kernel doesn't need `initramfs` to boot Android (because rootdir is in `system`). This mean we can be smart and just stuff the recovery ramdisk (containing the minimalist Linux environment) into `boot`, remove `recovery`, and let the kernel pick whichever rootdir to use (ramdisk or `system`) based on information from the bootloader. +Let's go back in time when Google was first designing A/B. If using SAR (only Boot Method B existed at that time), the kernel doesn't need `initramfs` to boot Android (because rootdir is in `system`). This means we can be smart and just stuff the recovery ramdisk (containing the minimalist Linux environment) into `boot`, remove `recovery`, and let the kernel pick whichever rootdir to use (ramdisk or `system`) based on information from the bootloader. -As time passed from Android 7.1 to Android 10, Google introduced [Dynamic Partitions](https://source.android.com/devices/tech/ota/dynamic_partitions/implement). This is bad news for SAR, because the Linux kernel cannot directly understand this new partition format, thus unable to directly mount `system` as rootdir. This is when they came up with Boot Method C: always boot into `initramfs`, and let userspace handle the rest of booting. This includes deciding whether to boot into Android or recovery, or as they officially call: `USES_RECOVERY_AS_BOOT`. +As time passed from Android 7.1 to Android 10, Google introduced [Dynamic Partitions](https://source.android.com/docs/core/ota/dynamic_partitions/implement). This is bad news for SAR, because the Linux kernel cannot directly understand this new partition format, thus unable to directly mount `system` as rootdir. This is when they came up with Boot Method C: always boot into `initramfs`, and let userspace handle the rest of booting. This includes deciding whether to boot into Android or recovery, or as they officially call: `USES_RECOVERY_AS_BOOT`. -Some modern devices using A/B with 2SI also comes with `recovery_a/_b` partitions. This is officially supported with Google's standard. These devices will then only use the boot ramdisk to boot into Android as recovery is stored on a separate partition. +Some modern devices using A/B with 2SI also come with `recovery_a/_b` partitions. This is officially supported with Google's standard. These devices will then only use the boot ramdisk to boot into Android as recovery is stored on a separate partition. + +Starting with Android 13 (`LV >= 33`) and [Generic Kernel Image (GKI) 2.0](https://source.android.com/docs/core/architecture/kernel/generic-kernel-image), Google decoupled the generic kernel from the generic ramdisk so that the `boot` partition contains only the GKI kernel, moving the generic first-stage ramdisk into a separate `init_boot` partition (or `vendor_boot` on some devices). From the booting perspective, these devices still use Boot Method C (2SI); the bootloader simply loads and concatenates the ramdisk(s) from `init_boot` / `vendor_boot` in memory before handing off to `/init`. ## Piecing Things Together With all the knowledge above, now we can categorize all Android devices into these different types: -Type | Boot Method | Partition | 2SI | Ramdisk in `boot` +Type | Boot Method | Partition | 2SI | Ramdisk in `boot` (or `init_boot`/`vendor_boot`) :---: | :---: | :---: | :---: | :---: **I** | A | A-only | No | `boot` ramdisk **II** | B | A/B | Any | `recovery` ramdisk **III** | B | A-only | Any | ***N/A*** -**IV** | C | Any | Yes | Hybrid ramdisk +**IV** | C | Any | Yes | Hybrid / 2SI ramdisk These types are ordered chronologically by the time they were first available. - **Type I**: Good old legacy ramdisk boot - **Type II**: Legacy A/B devices. Pixel 1 is the first device of this type, being both the first A/B and SAR device - **Type III**: Late 2018 - 2019 devices that are A-only. **The worst type of device to ever exist as far as Magisk is concerned.** -- **Type IV**: All devices using Boot Method C are Type IV. A/B Type IV ramdisk can boot into either Android or recovery based on info from bootloader; A-only Type IV ramdisk can only boot into Android. +- **Type IV**: All devices using Boot Method C are Type IV. A/B Type IV ramdisk can boot into either Android or recovery based on info from bootloader; A-only Type IV ramdisk (or devices with dedicated `recovery` / `vendor_boot` recovery ramdisks) only boots into Android. On Android 13+ GKI devices, this ramdisk is located in `init_boot` (or `vendor_boot`) rather than `boot`. -Further details on Type III devices: Magisk is always installed in the ramdisk of a boot image. For all other device types, because their `boot` partition have ramdisk included, Magisk can be easily installed by patching boot image through the Magisk app or flash zip in custom recovery. However for Type III devices, they are **limited to install Magisk into the `recovery` partition**. Magisk will not function when booted normally; instead Type III device owners have to always reboot to recovery to maintain Magisk access. +Further details on Type III devices: Magisk is always installed in the ramdisk of a boot image. For all other device types, because their boot partitions (`boot`, `init_boot`, or `vendor_boot`) have ramdisk included, Magisk can be easily installed by patching the image through the Magisk app. However for Type III devices, they are **limited to installing Magisk into the `recovery` partition**. Magisk will not function when booted normally; instead Type III device owners have to always reboot to recovery to maintain Magisk access. -Some Type III devices' bootloader will still accept and provide `initramfs` that was manually added to the `boot` image to the kernel (e.g. some Xiaomi phones), but many device don't (e.g. Samsung S10, Note 10). It solely depends on how the OEM implements its bootloader. +Some Type III devices' bootloader will still accept and provide `initramfs` that was manually added to the `boot` image to the kernel (e.g. some Xiaomi phones), but many devices don't (e.g. Samsung S10, Note 10). It solely depends on how the OEM implements its bootloader. diff --git a/docs/build.md b/docs/build.md index fc636d2ad..1bb1a1a89 100644 --- a/docs/build.md +++ b/docs/build.md @@ -15,28 +15,30 @@ - (Optional on Windows): Run `pip install colorama` to install the `colorama` python package - Install Git: - On Unix, install git with your favorite package manager - - On Windows, download the install the latest Git version on the [official website](https://git-scm.com/download/win).
+ - On Windows, download and install the latest Git version on the [official website](https://git-scm.com/download/win).
Make sure to **"Enable symbolic links"** during installation. - Install Android Studio and follow the instructions and go through the initial setup. - Set environment variable `ANDROID_HOME` to the Android SDK folder. This path can be found in Android Studio settings. - Setup JDK: - The recommended option is to set environment variable `ANDROID_STUDIO` to the path where your Android Studio is installed. The build script will automatically find and use the bundled JDK. - - You can also setup JDK 17 yourself, but this guide will not cover the instructions. + - You can also setup JDK 25 yourself, but this guide will not cover the instructions. - Clone sources: `git clone --recurse-submodules https://github.com/topjohnwu/Magisk.git` - Run `./build.py ndk` to let the script download and install NDK for you ## Building - To build everything and create the final Magisk APK, run `./build.py all`. -- You can also build specific sub-components; call `build.py` to see your options. \ - For each action, use `-h` to access help (e.g. `./build.py binary -h`) +- You can also build specific sub-components; call `./build.py -h` to see all available actions. \ + For each action, use `-h` to access help (e.g. `./build.py native -h`). - Configure the build by using `config.prop`. A sample `config.prop.sample` is provided. +- If `sccache` or `ccache` is installed and available in your `PATH`, `build.py` will automatically use it to speed up C++ and Rust builds. +- To run standalone tools (such as `./gradlew`, `cargo`, or `ndk-build`) with the same environment variables configured by `build.py`, prefix the command with `scripts/env.py` (e.g. `scripts/env.py ./gradlew :apk:assembleDebug`). You can also run `./build.py clippy` to lint Rust code or `./build.py cargo ...` to invoke Cargo directly against the native workspace. ## IDE Support - Kotlin, Java, C++, and C code in the project should be supported in Android Studio out of the box. This repository can be directly opened with Android Studio as a project. - For Rust development, see the next section. -- Before working on any native code, build all native code first with `./build.py binary`, as some generated code is only created during the build process. +- Before working on any native code, run `./build.py gen` (or build all native code with `./build.py native`), which generates build flags, C++/Rust FFI bindings, protobuf sources, and `native/compile_commands.json` for C/C++ language servers. ### Developing Rust @@ -57,7 +59,7 @@ If you plan to use VSCode, you can then install the [rust-analyzer](https://mark ```bash rustup toolchain install nightly -# Add some components that is also included in ONDK +# Add some components that are also included in ONDK rustup +nightly component add rust-src clippy ``` diff --git a/docs/changes.md b/docs/changes.md index 3637acc2b..c336a1f5e 100644 --- a/docs/changes.md +++ b/docs/changes.md @@ -100,7 +100,7 @@ - [App] Use user-initiated job instead of foreground services on Android 14 - [App] Support Android 13+ built-in per-app language preferences - [App] Add `action.sh` support to allow modules to define an action triggered from UI -- [MagiskBoot] Support spliting kernel images without decompression +- [MagiskBoot] Support splitting kernel images without decompression - [MagiskBoot] Properly support vendor boot images - [MagiskBoot] Disable Samsung PROCA from kernel image diff --git a/docs/details.md b/docs/details.md index 1256bc1ad..75a0ae306 100644 --- a/docs/details.md +++ b/docs/details.md @@ -17,23 +17,33 @@ MAGISKTMP=$(magisk --path) # Magisk internal stuffs INTERNALDIR=$MAGISKTMP/.magisk -# /data/adb/modules will be bind mounted here. -# The original folder is not used due to nosuid mount flag. +# /data/adb/modules will be bind mounted here as read-only. +# The original folder is not used directly due to the nosuid mount flag on /data. $INTERNALDIR/modules # The current Magisk installation config $INTERNALDIR/config -# Partition mirrors -# Each directory in this path will be mounted with the -# partition of its directory name. -# e.g. system, system_ext, vendor, data ... -$INTERNALDIR/mirror +# Symlink/mount to the pre-init storage directory +# Used to persist custom sepolicy.rule across reboots so it can be read during pre-init +$INTERNALDIR/preinit -# Root directory patch files +# Internal tmpfs workspace used for constructing magic mount trees +$INTERNALDIR/worker + +# Internal BusyBox directory containing busybox and its applet symlinks +$INTERNALDIR/busybox + +# Internal device nodes, pipes, and sockets (magiskd socket, preinit block device, log pipe) +$INTERNALDIR/device + +# Root directory patch/overlay files # On system-as-root devices, / is not writable. # All pre-init patched files are stored here and bind mounted. $INTERNALDIR/rootdir + +# Isolated devpts mount for root shells (if supported by the kernel) +$INTERNALDIR/pts ``` ### Paths in `/data` @@ -70,28 +80,34 @@ MAGISKDB=$SECURE_DIR/magisk.db # scripts, and magisk binaries. Used in supporting # module installation, addon.d, the Magisk app etc. DATABIN=$SECURE_DIR/magisk - ``` ## Magisk Booting Process ### Pre-Init -`magiskinit` will replace `init` as the first program to run. +`magiskinit` replaces `init` as the first program to run. -- Early mount required partitions. On legacy system-as-root devices, we switch root to system; on 2SI devices, we patch the original `init` to redirect the 2nd stage init file to magiskinit and execute it to mount partitions for us. -- Inject magisk services into `init.rc` -- On devices using monolithic policy, load sepolicy from `/sepolicy`; otherwise we hijack nodes in selinuxfs with FIFO, set `LD_PRELOAD` to hook `security_load_policy` and assist hijacking on 2SI devices, and start a daemon to wait until init tries to load sepolicy. -- Patch sepolicy rules. If we are using "hijack" method, load patched sepolicy into kernel, unblock init and exit daemon -- Execute the original `init` to continue the boot process +- Early mount required partitions (`sysfs`, `procfs`, `devtmpfs`, and the pre-init partition if available). +- On legacy system-as-root devices, `magiskinit` switches root to `/system`. On 2-Stage Init (2SI) devices, `magiskinit` intercepts first-stage `init`'s root switch (`SwitchRoot`) to `/system` by bind-mounting `magiskinit` over `/system/bin/init` (using a `/sdcard` -> `/storage/self/primary` -> `/system/system/bin/init` symlink trick in ramfs, or falling back to hex-patching `/init` to redirect `/system/bin/init` to `/data/magiskinit`), allowing the original first-stage `init` to mount dynamic partitions for us before handing control back to `magiskinit` as the second-stage `init`. +- Inject Magisk services into `init.rc` and apply any `overlay.d` root directory replacements/mounts. +- Intercept and patch SELinux policy (incorporating built-in Magisk rules and any custom `sepolicy.rule` files from the pre-init partition) using one of three strategies depending on the device's architecture: + - **2SI (Android 10+)**: Sets `LD_PRELOAD` (`init-ld`) on `init` to hook `security_load_policy` and intercept policy loading directly in memory before it is written to the kernel. + - **Treble / Split Policy (Android 8.0–9.0)**: Mounts `selinuxfs` early and replaces `/sys/fs/selinux/load` and `/sys/fs/selinux/enforce` with custom nodes (using a FIFO to pause `init` until `magiskinit` finishes patching and loading the policy into the kernel). + - **Legacy (Android 7.0–7.1)**: Replaces `/selinux_version` (or `/sepolicy_version`) with a FIFO to pause `init` right after it mounts `selinuxfs`, then replaces `/sys/fs/selinux/load` and `/sys/fs/selinux/enforce` with custom nodes in the same way as the Treble strategy. +- Restore the original `init` and execute it to continue the boot process. ### post-fs-data -This triggers on `post-fs-data` when `/data` is decrypted and mounted. The daemon `magiskd` will be launched, post-fs-data scripts are executed, and module files are magic mounted. +This triggers on `post-fs-data` when `/data` is decrypted and mounted. The daemon `magiskd` is launched, Safe Mode is evaluated (if the device failed to reach `boot-complete` twice in a row, or if Safe Mode was triggered via key combo or the Magisk app, all modules and Zygisk are disabled), `post-fs-data` scripts and module `system.prop` files are processed, and enabled module files are magic mounted. ### late_start -Later in the booting process, the class `late_start` will be triggered, and Magisk "service" mode will be started. In this mode, service scripts are executed. +Later in the booting process, the class `late_start` will be triggered, and Magisk "service" mode will be started. In this mode, general and module `service.sh` scripts are executed. + +### boot-complete + +When `sys.boot_completed=1` is triggered, Magisk resets the bootloop counter, mounts/symlinks the writable `preinit` storage directory for future module installations, and finalizes Zygisk state. ## Resetprop @@ -99,15 +115,17 @@ Usually, system properties are designed to only be updated by `init` and read-on `resetprop` is implemented by distilling out the source code related to system properties from AOSP and patched to allow direct modification to property area, or `prop_area`, bypassing the need to go through `property_service`. Since we are bypassing `property_service`, there are a few caveats: -- `on property:foo=bar` actions registered in `*.rc` scripts will not be triggered if property changes does not go through `property_service`. The default set property behavior of `resetprop` matches `setprop`, which **WILL** trigger events (implemented by first deleting the property then set it via `property_service`). There is a flag `-n` to disable it if you need this special behavior. -- persist properties (props that starts with `persist.`, like `persist.sys.usb.config`) are stored in both `prop_area` and `/data/property`. By default, deleting props will **NOT** remove it from persistent storage, meaning the property will be restored after the next reboot; reading props will **NOT** read from persistent storage, as this is the behavior of `getprop`. With the flag `-p`, deleting props will remove the prop in **BOTH** `prop_area` and `/data/property`, and reading props will be read from **BOTH** `prop_area` and persistent storage. +- `on property:foo=bar` actions registered in `*.rc` scripts will not be triggered if property changes do not go through `property_service`. For non-read-only properties, the default set property behavior of `resetprop` goes through `property_service` (matching `setprop`), which **WILL** trigger events. Modifying read-only (`ro.*`) properties or passing the `-n` flag bypasses `property_service` and modifies `prop_area` directly, which will **NOT** trigger property events. +- persist properties (props that start with `persist.`, like `persist.sys.usb.config`) are stored in both `prop_area` and `/data/property`. By default, deleting props will **NOT** remove them from persistent storage, meaning the property will be restored after the next reboot; reading props will **NOT** read from persistent storage, as this is the behavior of `getprop`. With the flag `-p`, deleting props will remove the prop in **BOTH** `prop_area` and `/data/property`, and reading props will read from **BOTH** `prop_area` and persistent storage. ## SELinux Policies -Magisk will patch the stock `sepolicy` to make sure root and Magisk operations can be done in a safe and secure way. The new domain `magisk` is effectively permissive, which is what `magiskd` and all root shell will run in. `magisk_file` is a new file type that is setup to be allowed to be accessed by every domain (unrestricted file context). +Magisk patches the stock `sepolicy` to ensure root and Magisk operations can be performed safely and reliably: -Before Android 8.0, all allowed su client domains are allowed to directly connect to `magiskd` and establish connection with the daemon to get a remote root shell. Magisk also have to relax some `ioctl` operations so root shells can function properly. +- `magisk` (`u:r:magisk:s0`): An unconstrained, permissive domain that `magiskd` and all root shells run in. +- `magisk_file` (`u:object_r:magisk_file:s0`): An unrestricted file type accessible by all domains, used to label Magisk sockets, binaries, and internal nodes. +- `magisk_log_file` (`u:object_r:magisk_log_file:s0`): A specialized FIFO file type for the Magisk log pipe that all domains are allowed to write to, while only `zygote` (and `magisk`) can open and read. +- Selected client domains (`zygote`, `shell`, `platform_app`, `system_app`, `priv_app`, `untrusted_app`, `untrusted_app_all`) are permitted to connect to `magisk` Unix stream sockets (used for `su`, `magisk`, and Zygisk IPC) and share file descriptors for root shell pseudo-terminals (`devpts`). -After Android 8.0, to reduce relaxation of rules in Android's sandbox, a new SELinux model is deployed. The `magisk` binary is labelled with `magisk_exec` file type, and processes running as allowed su client domains executing the `magisk` binary (this includes the `su` command) will transit to `magisk_client` by using a `type_transition` rule. Rules strictly restrict that only `magisk` domain processes are allowed to attribute files to `magisk_exec`. Direct connection to sockets of `magiskd` are not allowed; the only way to access the daemon is through a `magisk_client` process. These changes allow us to keep the sandbox intact, and keep Magisk specific rules separated from the rest of the policies. +The full set of built-in policy rules can be found in `native/src/sepolicy/rules.rs`. -The full set of rules can be found in `sepolicy/rules.cpp`. diff --git a/docs/faq.md b/docs/faq.md index e6c2d7c21..b194ce779 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -2,9 +2,14 @@ ### Q: I installed a module and it bootlooped my device. Help! -If you have USB debugging enabled in developer options, connect your phone to the PC. If your device is detected (check by `adb devices`), enter ADB shell and run the command `magisk --remove-modules`. This will remove all your modules and automatically reboot the device. +Magisk includes built-in bootloop protection: if your device fails to finish booting (`boot_completed`) **twice in a row**, Magisk will automatically enter **Safe Mode** on the next boot, disabling all modules (by creating a `disable` file in each module folder) and disabling Zygisk so your device can boot normally. -If unfortunately you do not have USB debugging enabled you can boot using the Safe Mode key combo to cause Magisk to create an empty file named 'disable' in modules directories which disables modules when next booted with Magisk. Most modern Android devices support such a special key combo at boot to enter system Safe Mode as an emergency option, but **please note** that Magisk's key combo detection occurs _earlier_ than system detection so the key combo timing indicated by many online guides may need to be altered to activate Magisk's Safe Mode. (It's possible to activate system Safe Mode but not Magisk Safe Mode and vice versa.) +If your device is stuck before automatic bootloop detection can recover it, or you want to manually recover: + +- If you have USB debugging enabled in developer options, connect your phone to the PC. If your device is detected (check by `adb devices`), enter ADB shell and run the command `magisk --remove-modules`. This will remove all your modules and automatically reboot the device. +- If your device can still boot into Android, you can also toggle **Safe Mode** directly from the Reboot menu (power icon) at the top of the Magisk app Home screen, then reboot. + +If you do not have USB debugging enabled and the device cannot boot, you can trigger Safe Mode manually using the hardware key combo at boot. Most modern Android devices support a special key combo at boot to enter system Safe Mode as an emergency option, but **please note** that Magisk's key combo detection occurs _earlier_ than system detection so the key combo timing indicated by many online guides may need to be altered to activate Magisk's Safe Mode. (It's possible to activate system Safe Mode but not Magisk Safe Mode and vice versa.) The following details should ensure that modules are properly disabled: @@ -18,6 +23,8 @@ Magisk no longer handles root hiding. There are plenty of Magisk/Zygisk modules ### Q: How to use Magisk in the emulator? -With the emulator running and accessible via ADB, run `./build.py emulator ` to temporarily install Magisk on to the emulator. The patch is not persistent, meaning Magisk will be lost after a reboot, so re-execute the script to emulate a reboot if required. +With the emulator running and accessible via ADB, run `./build.py emulator [path to Magisk APK]` (or `./build.py emulator -b` to build and install from source) to temporarily start Magisk on the running emulator. This runtime setup is not persistent across cold reboots, so re-execute the command to emulate a reboot if required. -The script is only tested on the official Android Virtual Device (AVD) shipped alongside Android Studio; other emulators may work, but the emulator must have SELinux enabled. +For a persistent installation on an Android Virtual Device (AVD), you can patch its `ramdisk.img` directly on your host machine using `./build.py patch --avd [output]`. + +These commands are tested on the official Android Virtual Device (AVD) shipped alongside Android Studio; other emulators may work, but the emulator must have SELinux enabled. diff --git a/docs/guides.md b/docs/guides.md index 11d12a5f1..3cd4d8221 100644 --- a/docs/guides.md +++ b/docs/guides.md @@ -113,6 +113,8 @@ Update JSON format: Please read the [Boot Scripts](#boot-scripts) section to understand the difference between `post-fs-data.sh` and `service.sh`. For most module developers, `service.sh` should be good enough if you just need to run a boot script. If you need to wait for boot completed, you can use `resetprop -w sys.boot_completed 0`. +If your module includes an `action.sh` script, the Magisk app will display an **Action** button on the module's card in the Modules tab. Tapping it executes `action.sh` in the app's built-in console with BusyBox standalone mode enabled (`BOOTMODE=true`). + In all scripts of your module, please use `MODDIR=${0%/*}` to get your module's base directory path; do **NOT** hardcode your module path in scripts. If Zygisk is enabled, the environment variable `ZYGISK_ENABLED` will be set to `1`. @@ -124,7 +126,7 @@ If you place a file named `.replace` in any of the folders, instead of merging i If you want to replace files in `/vendor`, `/product`, or `/system_ext`, please place them under `system/vendor`, `system/product`, and `system/system_ext` respectively. Magisk will transparently handle whether these partitions are in a separate partition or not. -If you want to remove a specific file or folder, please place a dummy character device with major number 0 and minor number 0 in the same path. For example, if you want to remove `/system/app/GoogleCamera`, you can `mknod GoogleCamera c 0 0` in `$MODDIR/system/app`. +If you want to remove a specific file or folder, please place a dummy character device with major number 0 and minor number 0 in the same path. For example, if you want to remove `/system/app/GoogleCamera`, you can `mknod GoogleCamera c 0 0` in `$MODDIR/system/app` (or declare `/system/app/GoogleCamera` in the `REMOVE` variable in `customize.sh`; see [Customization](#customization)). #### Zygisk @@ -245,7 +247,7 @@ The list above will result in the following dummy devices being created: `$MODPA In Magisk, you can run boot scripts in 2 different modes: **post-fs-data** and **late_start service** mode. - post-fs-data mode - - This stage is BLOCKING. The boot process is paused before execution is done, or 40 seconds have passed. + - This stage is BLOCKING. The boot process is paused before execution is done, or 40 seconds have passed (with `post-fs-data` scripts capped at 35 seconds so Magisk still has time to mount modules). - Scripts run before any modules are mounted. This allows a module developer to dynamically adjust their modules before it gets mounted. - This stage happens before Zygote is started, which pretty much means everything in Android - **WARNING:** using `setprop` will deadlock the boot process! Please use `resetprop -n ` instead. @@ -292,6 +294,7 @@ ramdisk │ │ ├── libfoo.ko <--- These 2 files will be copied │ │ └── myscript.sh <--- into Magisk's tmpfs directory │ ├── custom.rc <--- This file will be injected into init.rc +│ │ because /custom.rc does not exist │ ├── res │ │ └── random.png <--- This file will replace /res/random.png │ └── new_file <--- This file will be ignored because diff --git a/docs/images/device_info.png b/docs/images/device_info.png index 3764093f8..bd6202d22 100644 Binary files a/docs/images/device_info.png and b/docs/images/device_info.png differ diff --git a/docs/install.md b/docs/install.md index 3a6f6fd91..1b892bf9e 100644 --- a/docs/install.md +++ b/docs/install.md @@ -22,33 +22,36 @@ The result of **Ramdisk** determines whether your device has ramdisk in the boot If you are using a Samsung device, you can now jump to [its own section](#samsung-devices). -If your device has boot ramdisk, get a copy of the `boot.img` (or `init_boot.img` if exists).
-If your device does **NOT** have boot ramdisk, get a copy of the `recovery.img`.
-You should be able to extract the file you need from official firmware packages or your custom ROM zip. +If your device has boot ramdisk, you need to patch the partition image that contains the ramdisk (`boot.img`, `init_boot.img`, or `vendor_boot.img`).
+If your device does **NOT** have boot ramdisk, you need to patch `recovery.img`.
+You can either extract the raw `.img` file yourself, or provide the full official firmware package (OTA `.zip`, `payload.bin`, or factory image `.zip`), or even a direct HTTPS link to it and let the Magisk app extract the target image automatically. Quick recap, at this point, you should have known and prepared: 1. Whether your device has boot ramdisk -2. A `boot.img`, `init_boot.img` or `recovery.img` based on (1) +2. A firmware package (or extracted `boot.img`, `init_boot.img`, `vendor_boot.img`, or `recovery.img`) based on (1) Let's continue to [Patching Images](#patching-images). ## Patching Images -- Copy the boot/init_boot/recovery image to your device - Press the **Install** button in the Magisk card - If you are patching a recovery image, check the **"Recovery Mode"** option -- Choose **"Select and Patch a File"** in method, and select the boot/init_boot/recovery image +- Choose **"Patch firmware / image"** in method, then select how to provide the source image: + - **Select from storage**: Select a raw `.img` (`boot.img`, `init_boot.img`, `vendor_boot.img`, `recovery.img`), an OTA `.zip` / `payload.bin`, or a factory image `.zip` + - **Enter image URL**: Paste a direct HTTPS URL to a remote OTA `.zip`, factory image `.zip`, or `.img` file to stream and extract the target image on the fly without downloading the full archive first + - **Download latest Pixel factory image** _(Pixel devices only)_: Automatically fetch and extract the image matching your current Pixel build from Google's servers - Start the installation, and copy the patched image to your PC using ADB:
- `adb pull /sdcard/Download/magisk_patched_[random_strings].img` -- Flash the patched boot/init_boot/recovery image to your device;
+ `adb pull /sdcard/Download/magisk_patched-[version]_[random_strings].img` +- Flash the patched boot/init_boot/vendor_boot/recovery image to your device;
for most devices, reboot into fastboot mode and flash with command:
- `fastboot flash boot /path/to/magisk_patched_[random_strings].img` or
- `fastboot flash init_boot /path/to/magisk_patched_[random_strings].img` or
- `fastboot flash recovery /path/to/magisk_patched_[random_strings].img`
+ `fastboot flash boot /path/to/magisk_patched-[version]_[random_strings].img` or
+ `fastboot flash init_boot /path/to/magisk_patched-[version]_[random_strings].img` or
+ `fastboot flash vendor_boot /path/to/magisk_patched-[version]_[random_strings].img` or
+ `fastboot flash recovery /path/to/magisk_patched-[version]_[random_strings].img`
- (Optional) If your device has a separate `vbmeta` partition, you can patch the `vbmeta` partition with command:
`fastboot flash vbmeta --disable-verity --disable-verification vbmeta.img` (note that it may **wipe your data**) -- Reboot and launch Magisk app (you will see a stub Magisk app if you have wiped your data; use it to bootstrap to a complete Magisk app), and you will see a prompt asking for environment fix; click and wait for the reboot +- Reboot and launch Magisk app (if you have wiped your data, install the Magisk APK again first), and you will see a prompt asking for environment fix; click and wait for the reboot - Voila! > Warning: **NEVER** flash patched image shared by others or patch image on another device even if they have the same device model! You may need to do a full data wipe to recover your device. **ALWAYS** patch boot image **on the same device where you want to install Magisk**. @@ -112,11 +115,11 @@ Having KnoxGuard active will prevent you from installing/running Magisk regardle - Unzip the firmware and copy the `AP` tar file to your device. It is normally named as `AP_[device_model_sw_ver].tar.md5` - Press the **Install** button in the Magisk card - If your device does **NOT** have boot ramdisk, check the **"Recovery Mode"** option -- Choose **"Select and Patch a File"** in method, and select the `AP` tar file +- Choose **"Patch firmware / image"** in method, choose **"Select from storage"**, and select the `AP` tar file - Start the installation, and copy the patched tar file to your PC using ADB:
- `adb pull /sdcard/Download/magisk_patched_[random_strings].tar`
+ `adb pull /sdcard/Download/magisk_patched-[version]_[random_strings].tar`
**DO NOT USE MTP** as it is known to corrupt large files. -- Reboot to download mode. Use `samloader` on your PC to flash `magisk_patched_[random_strings].tar` as `AP`, together with `BL`, `CP`, and `CSC` (**NOT** `HOME_CSC` because we want to **wipe data**) from the original firmware. +- Reboot to download mode. Use `samloader` on your PC to flash `magisk_patched-[version]_[random_strings].tar` as `AP`, together with `BL`, `CP`, and `CSC` (**NOT** `HOME_CSC` because we want to **wipe data**) from the original firmware. - Your device should reboot automatically once `samloader` finished flashing. **Agree to do a factory reset if asked.** - If your device does **NOT** have boot ramdisk, reboot to recovery now to enable Magisk (reason stated in [Magisk in Recovery](#magisk-in-recovery)). - Install the Magisk app you've already downloaded and launch the app. It should show a dialog asking for additional setup. @@ -138,9 +141,9 @@ Once you have rooted your Samsung device, you can no longer upgrade your Android Installing using custom recoveries is only possible if your device has boot ramdisk. Installing Magisk through custom recoveries on modern devices is no longer recommended. If you face any issues, please use the [Patch Image](#patching-images) method. - Download the Magisk APK -- Rename the `.apk` file extension to `.zip`, for example: `Magisk-v24.0.apk` → `Magisk-v24.0.zip`. If you have trouble renaming the file extension (like on Windows), use a file manager on Android or the one included in the custom recovery to rename the file. +- Rename the `.apk` file extension to `.zip`, for example: `Magisk-v31.0.apk` → `Magisk-v31.0.zip`. If you have trouble renaming the file extension (like on Windows), use a file manager on Android or the one included in the custom recovery to rename the file. - Flash the zip just like any other ordinary flashable zip. -- Reboot and check whether the Magisk app is installed. If it isn't installed automatically, manually install the APK. +- Reboot and install the Magisk APK as a regular app if it is not already installed. - Launch the Magisk app; it will show a dialog asking for reinstallation. Do the reinstallation **directly within the app** and reboot (if you are using MTK devices that lock the boot partition after boot, please [patch the boot image](#patching-images) and flash it by custom recovery or fastboot). -> Warning: the `sepolicy.rule` file of modules may be stored in the `cache` partition. DO NOT WIPE THE `CACHE` PARTITION. +> Warning: the `sepolicy.rule` files of modules may be stored on the `cache` or `metadata` partition (the pre-init partition). DO NOT WIPE THE `CACHE` OR `METADATA` PARTITION, or active module `sepolicy.rule` files will be lost until the modules are reinstalled. diff --git a/docs/tools.md b/docs/tools.md index 0afa0e1e4..243d341ec 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -186,6 +186,7 @@ Options: --apply FILE apply rules from FILE, read and parsed line by line as policy statements (multiple --apply are allowed) + --print-rules print all rules in the loaded sepolicy If neither --load, --load-split, nor --compile-split is specified, it will load from current live policies (/sys/fs/selinux/policy) @@ -194,7 +195,7 @@ One policy statement should be treated as one parameter; this means each policy statement should be enclosed in quotes. Multiple policy statements can be provided in a single command. -Statements has a format of " [args...]". +Statements have a format of " [args...]". Arguments labeled with (^) can accept one or more entries. Multiple entries consist of a space separated list enclosed in braces ({}). Arguments labeled with (*) are the same as (^), but additionally @@ -208,6 +209,14 @@ allow s1 t2 class { all-permissions-of-class } allow s2 t1 class { all-permissions-of-class } allow s2 t2 class { all-permissions-of-class } +Extended permissions (xperm) are 16-bit values (0x0000-0xFFFF) that provide +fine-grained filtering on operations like ioctl. An xperm_set can be: + - A single hex value: 0x8910 + - A brace-enclosed list of hex values and ranges: { 0x8910 0x8920-0x8926 } + - A complement (~) of a single value or list: ~0x8910, ~{ 0x8910 0x892A } + - Match-all (*): represents the full range 0x0000-0xFFFF + - Reset (0): clears all rules (allow, auditallow, dontaudit) for the target + Supported policy statements: "allow *source_type *target_type *class *perm_set" @@ -219,12 +228,9 @@ Supported policy statements: "auditallowxperm *source_type *target_type *class operation xperm_set" "dontauditxperm *source_type *target_type *class operation xperm_set" - The only supported operation is 'ioctl' -- xperm_set format is either 'low-high', 'value', or '*'. - '*' will be treated as '0x0000-0xFFFF'. - All values should be written in hexadecimal. -"permissive ^type" -"enforce ^type" +"permissive *type" +"enforce *type" "typeattribute ^type ^attribute" @@ -295,6 +301,7 @@ An applet of `magisk`, the MagiskSU entry point. Good old `su` command. Usage: su [options] [--] [user [argument...]] Options: + -c, --command COMMAND Pass COMMAND to the invoked shell -s, --shell SHELL Use SHELL instead of the default /system/bin/sh -i, --interactive Force pseudo-terminal allocation when using -c -g, --group GROUP Specify the primary group @@ -304,6 +311,7 @@ Options: -Z, --context CONTEXT Change SELinux context -t, --target PID PID to take mount namespace from pid 0 means magisk global mount namespace + -M, --mount-master Force run in the global mount namespace (same as -t 0) -d, --drop-cap Drop all Linux capabilities -m, -p, --preserve-environment Preserve the entire environment