### Metainstall.sh - Installation Hook Example Source: https://kernelsu.org/guide/metamodule.html This script is sourced during module installation to customize the process. It inherits variables and functions from the built-in install.sh. ```shell #!/system/bin/sh # metainstall.sh - Installation Hook # Purpose : Customize how regular modules are installed. # When executed : During module installation, after files are extracted but before installation completes. # Inherited variables and functions from install.sh: # MODPATH, TMPDIR, ZIPFILE, ARCH, API, IS64BIT, KSU, KSU_VER, KSU_VER_CODE, KSU_UAPI_VER, KSU_RUNTIME_MODE, KSU_LATE_LOAD, BOOTMODE, etc. # ui_print , abort , set_perm, set_perm_recursive, install_module # Example use case: Process module files before or after built-in installation # ui_print "Processing module files..." # install_module # Call the built-in module installation process when ready ``` -------------------------------- ### Example: Registering a Custom Android Service Source: https://kernelsu.org/guide/module.html This .rc file defines a custom service 'myservice' and starts it after the system boot is completed. Ensure the service binary exists at the specified path. ```rc service myservice /data/adb/modules/mymodule/bin/myservice user root group root disabled seclabel u:r:ksu:s0 on property:sys.boot_completed=1 start myservice ``` -------------------------------- ### Basic metamount.sh Script Example Source: https://kernelsu.org/guide/metamodule.html This is a basic example of a `metamount.sh` script, showing how to access the metamodule directory using `MODDIR`. This script is responsible for handling module mounting during boot. ```shell #!/system/bin/sh MODDIR="${0%/*}" ``` -------------------------------- ### Kernel Version Format Example Source: https://kernelsu.org/guide/installation.html This example shows the expected format for kernel release versions, highlighting the KMI version components. ```text KernelRelease := Version.PatchLevel.SubLevel-AndroidRelease-KmiGeneration-suffix w .x .y -zzz -k -something `w.x-zzz-k` is the KMI version. For example, if a device kernel version is `5.10.101-android12-9-g30979850fc20`, then its KMI is `5.10-android12-9`. Theoretically, it can boot up normally with other KMI kernels. ``` -------------------------------- ### Add KernelSU (Latest Tag) Source: https://kernelsu.org/guide/how-to-build.html Integrates the latest stable version of KernelSU into the kernel source by downloading and executing the setup script. ```shell curl -LSs "https://raw.githubusercontent.com/tiann/KernelSU/main/kernel/setup.sh" | bash - ``` -------------------------------- ### Correct Mount Operation with 'KSU' Source Source: https://kernelsu.org/guide/metamodule.html When performing mount operations within a metamodule, it is critical to set the source/device name to 'KSU'. This example demonstrates the correct syntax for overlay mounts. ```shell mount -t overlay -o lowerdir=/lower,upperdir=/upper,workdir=/work KSU /target ``` -------------------------------- ### Install AnyKernel3 ZIP via ADB Sideload Source: https://kernelsu.org/guide/installation.html This command installs the KernelSU AnyKernel3 ZIP package onto the device when it's in TWRP recovery mode. Ensure the ZIP file is in the device's `/sdcard` directory. ```bash adb sideload AnyKernel-*.zip ``` -------------------------------- ### ksud boot-patch command example Source: https://kernelsu.org/guide/installation.html This command is used to patch a boot image with KernelSU, specifying the boot image path and KMI version. ```sh ksud boot-patch -b --kmi android13-5.10 ``` -------------------------------- ### KernelSU Module Installer ZIP Structure Source: https://kernelsu.org/guide/module.html A basic KernelSU module installer is a ZIP archive containing module files and an optional customize.sh script for custom installation logic. ```text module.zip │ ├── customize.sh <--- (Optional, more details later) │ This script will be sourced by update-binary ├── ... ├── ... /* The rest of module's files */ │ ``` -------------------------------- ### Metauninstall.sh - Cleanup Hook Example Source: https://kernelsu.org/guide/metamodule.html This script is executed during module uninstallation to clean up resources. It receives the MODULE_ID as an argument. ```shell #!/system/bin/sh # metauninstall.sh - Cleanup Hook # Purpose : Clean up resources when regular modules are uninstalled. # When executed : During module uninstallation, before the module directory is removed. # Environment variables: MODULE_ID MODULE_ID="$1" IMG_MNT="/data/adb/metamodule/mnt" # Remove module files from image if [ -d "$IMG_MNT/$MODULE_ID" ]; then rm -rf "$IMG_MNT/$MODULE_ID" fi ``` -------------------------------- ### KernelSU `ksud` Command-Line Tool Help Source: https://kernelsu.org/guide/installation.html Displays the usage information for the `ksud boot-patch` command, which is used to patch boot or init_boot images for KernelSU installation. ```sh oriole:/ # ksud boot-patch -h Patch boot or init_boot images to apply KernelSU Usage: ksud boot-patch [OPTIONS] ``` -------------------------------- ### KernelSU customize.sh Functions Source: https://kernelsu.org/guide/module.html Provides essential functions for managing file permissions and contexts during module installation. Use these instead of standard shell commands for better integration. ```shell ui_print print to console Avoid using 'echo' as it will not display in custom recovery's console abort print error message to console and terminate the installation Avoid using 'exit' as it will skip the termination cleanup steps set_perm [context] if [context] is not set, the default is "u:object_r:system_file:s0" this function is a shorthand for the following commands: chown owner.group target chmod permission target chcon context target set_perm_recursive [context] if [context] is not set, the default is "u:object_r:system_file:s0" for all files in , it will call: set_perm file owner group filepermission context for all directories in (including itself), it will call: set_perm dir owner group dirpermission context ``` -------------------------------- ### Get Configuration Value Source: https://kernelsu.org/guide/module-config.html Retrieves a configuration value for the current module. The value is stored in the `value` variable. ```bash # Get a configuration value value=$(ksud module config get my_setting) ``` -------------------------------- ### Execute Shell Command with Kernelsu API Source: https://kernelsu.org/guide/module-webui.html Use the `exec` function from the `kernelsu` JavaScript library to run shell commands and retrieve their output. This is useful for getting system properties or configurations. ```javascript import { exec } from 'kernelsu'; const { errno, stdout } = exec("getprop ro.product.model"); ``` -------------------------------- ### KernelSU Boot Execution Order Overview Source: https://kernelsu.org/guide/metamodule.html This text outlines the sequence of script execution during different boot stages (post-fs-data, service, boot-completed) for both metamodules and regular modules. ```text post-fs-data stage: 1. Common post-fs-data.d scripts execute 2. Prune modules, restorecon, load sepolicy.rule 3. Metamodule's post-fs-data.sh executes (if exists) 4. Regular modules' post-fs-data.sh execute 5. Load system.prop 6. Metamodule's metamount.sh executes └─> Mounts all modules systemlessly 7. post-mount.d stage runs - Common post-mount.d scripts - Metamodule's post-mount.sh (if exists) - Regular modules' post-mount.sh service stage: 1. Common service.d scripts execute 2. Metamodule's service.sh executes (if exists) 3. Regular modules' service.sh execute boot-completed stage: 1. Common boot-completed.d scripts execute 2. Metamodule's boot-completed.sh executes (if exists) 3. Regular modules' boot-completed.sh execute ``` -------------------------------- ### List All Configuration Entries Source: https://kernelsu.org/guide/module-config.html Lists all configuration entries, merging both persistent and temporary settings. Useful for debugging and understanding the current configuration state. ```bash ksud module config list ``` -------------------------------- ### Meta-overlayfs Metamount.sh Implementation Source: https://kernelsu.org/guide/metamodule.html This script demonstrates the metamount.sh implementation for the meta-overlayfs metamodule, defining the image file and mount directory. ```shell #!/system/bin/sh MODDIR="${0%/*}" IMG_FILE="$MODDIR/modules.img" MNT_DIR="$MODDIR/mnt" ``` -------------------------------- ### KernelSU Boot Process Explanation Source: https://kernelsu.org/guide/module.html This outlines the Android boot process, highlighting KernelSU operations and script execution points during standard boot. ```text 0. Bootloader (nothing on screen) load patched boot.img load kernel: - GKI mode: GKI kernel with KernelSU integrated - LKM mode: stock kernel ... 1. kernel exec init (OEM logo on screen): - GKI mode: stock init - LKM mode: exec ksuinit, insmod kernelsu.ko, exec stock init mount /dev, /dev/pts, /proc, /sys, etc. property-init -> read default props read init.rc *initrc injection: Kernel hook appends KernelSU core RC and module modules.rc to init.rc ... early-init -> init -> late_init early-fs start vold fs mount /vendor, /system, /persist, etc. post-fs-data *safe mode check *execute general scripts in post-fs-data.d/ *load sepolicy.rule *execute metamodule's post-fs-data.sh (if exists) *execute module scripts post-fs-data.sh **(Zygisk)./bin/zygisk-ptrace64 monitor *(pre)load system.prop (same as resetprop -n) *execute metamodule's metamount.sh (mounts all modules) *execute general scripts in post-mount.d/ *execute metamodule's post-mount.sh (if exists) *execute module scripts post-mount.sh zygote-start load_all_props_action *execute resetprop (actual set props for resetprop with -n option) ... -> boot class_start core start-service logd, console, vold, etc. class_start main start-service adb, netd (iptables), zygote, etc. 2. kernel2user init (ROM animation on screen, start by service bootanim) *execute general scripts in service.d/ *execute metamodule's service.sh (if exists) *execute module scripts service.sh *set props for resetprop without -p option **(Zygisk) hook zygote (start zygiskd) **(Zygisk) mount zygisksu/module.prop start system apps (autostart) ... boot complete (broadcast ACTION_BOOT_COMPLETED event) *execute general scripts in boot-completed.d/ *execute metamodule's boot-completed.sh (if exists) *execute module scripts boot-completed.sh 3. User operable (lock screen) input password to decrypt /data/data *actual set props for resetprop with -p option start user apps (autostart) ``` -------------------------------- ### Custom SELinux Domain and Rules Source: https://kernelsu.org/guide/app-profile.html This snippet demonstrates how to define a custom SELinux domain ('app1') and set basic enforcement rules. The 'allow app1 * * *' rule is for demonstration and should be used with caution in production. ```shell type app1 enforce app1 typeattribute app1 mlstrustedsubject allow app1 * * * ``` -------------------------------- ### KernelSU Metamodule Symlink Mechanism Source: https://kernelsu.org/guide/metamodule.html This shows the symlink created by KernelSU when a metamodule is installed, providing a stable path for accessing the active metamodule. ```shell /data/adb/metamodule -> /data/adb/modules/ ``` -------------------------------- ### Enable SU Compatibility Management Source: https://kernelsu.org/guide/module-config.html Use this command to declare that a module is managing SU compatibility and enable it. ```bash ksud module config set manage.su_compat true ``` -------------------------------- ### Temporarily boot boot.img using fastboot Source: https://kernelsu.org/guide/installation.html This command allows you to temporarily boot a system using a specified boot image. It's useful for testing or recovery if flashing fails. ```sh fastboot boot boot.img ``` -------------------------------- ### Simple Bind Mount Implementation Source: https://kernelsu.org/guide/metamodule.html This script iterates through modules in /data/adb/modules/, checks for disable or skip_mount flags, and performs a bind mount for modules with a system directory. ```shell #!/system/bin/sh # Example: Simple bind mount implementation for module in /data/adb/modules/*; do if [ -f "$module/disable" ] || [ -f "$module/skip_mount" ]; then continue fi if [ -d "$module/system" ]; then # Mount with source=KSU (REQUIRED!) mount -o bind,dev=KSU "$module/system" /system fi done ``` -------------------------------- ### Metamodule File Structure Source: https://kernelsu.org/guide/metamodule.html A typical metamodule includes `module.prop` and optional hook scripts like `metamount.sh`, `metainstall.sh`, and `metauninstall.sh`. Standard module files can also be included. ```plaintext meta-example/ ├── module.prop (must include metamodule=1) │ │ *** Metamodule-specific hooks *** ├── metamount.sh (optional: custom mount handler) ├── metainstall.sh (optional: installation hook for regular modules) ├── metauninstall.sh (optional: cleanup hook for regular modules) │ │ *** Standard module files (all optional) *** ├── customize.sh (installation customization) ├── post-fs-data.sh (post-fs-data stage script) ├── service.sh (late_start service script) ├── boot-completed.sh (boot completed script) ├── uninstall.sh (metamodule's own uninstallation script) └── [any additional files] ``` -------------------------------- ### Mount ext4 Image and Set Environment Variables Source: https://kernelsu.org/guide/metamodule.html This script snippet demonstrates how to mount an ext4 image as a read-write overlay directory and set necessary environment variables for dual-directory support in KernelSU metamodules. ```bash # Mount ext4 image if not already mounted if ! mountpoint -q "$MNT_DIR"; then mkdir -p "$MNT_DIR" mount -t ext4 -o loop,rw,noatime "$IMG_FILE" "$MNT_DIR" fi # Set environment variables for dual-directory support export MODULE_METADATA_DIR="/data/adb/modules" export MODULE_CONTENT_DIR="$MNT_DIR" # Execute the mount binary # (The actual mounting logic is in a Rust binary) "$MODDIR/meta-overlayfs" ``` -------------------------------- ### Sync Kernel Source Code Source: https://kernelsu.org/guide/how-to-build.html Initializes the kernel manifest repository and syncs the source code. Ensure you have the correct manifest file for reproducible builds. ```shell repo init -u https://android.googlesource.com/kernel/manifest mv .repo/manifests repo init -m manifest.xml repo sync ``` -------------------------------- ### Flash boot.img using fastboot Source: https://kernelsu.org/guide/installation.html This command flashes the KernelSU boot image to the device's boot partition after entering fastboot mode. ```sh fastboot flash boot boot.img ``` -------------------------------- ### General initrc Directory Structure Source: https://kernelsu.org/guide/module.html General .rc files can be placed in '/data/adb/initrc.d/'. These files require executable permissions and are processed before module RC files. ```text /data/adb/initrc.d/ ├── myservice.rc └── another.rc ``` -------------------------------- ### Module File Structure Source: https://kernelsu.org/guide/module-webui.html The basic structure for a KernelSU module with a web interface includes a `module.prop` file and a `webroot` directory containing `index.html`. ```txt . |-- module.prop `-- webroot `-- index.html ``` -------------------------------- ### module.prop Configuration File Format Source: https://kernelsu.org/guide/module.html Defines the key-value pairs for the module.prop file, which stores essential metadata for a KernelSU module. This file is mandatory for module recognition. ```txt id= name= version= versionCode= author= description= updateJson= (optional) actionIcon= (optional) webuiIcon= (optional) ``` -------------------------------- ### Repack boot.img with magiskboot Source: https://kernelsu.org/guide/installation.html After replacing the kernel, use this command to repack the modified boot image. This generates `new-boot.img` which can then be flashed to the device. ```bash ./magiskboot repack boot.img ``` -------------------------------- ### Enable CONFIG_KSU in Defconfig Source: https://kernelsu.org/guide/how-to-integrate-for-non-gki.html Modify your kernel's defconfig file to enable KernelSU. Ensure the CONFIG_KSU option is set to 'y'. The defconfig file might be located in different paths depending on your device. ```text # KernelSU CONFIG_KSU=y ``` -------------------------------- ### Backporting path_umount Function Source: https://kernelsu.org/guide/how-to-integrate-for-non-gki.html This code snippet shows the `can_umount` and `path_umount` functions that need to be added to `fs/namespace.c` for pre-GKI kernels. It includes the necessary checks and logic for unmounting paths. ```c static inline bool may_mandlock(void) { return true; } #endif static int can_umount(const struct path *path, int flags) { struct mount *mnt = real_mount(path->mnt); if (flags & ~(MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW)) return -EINVAL; if (!may_mount()) return -EPERM; if (path->dentry != path->mnt->mnt_root) return -EINVAL; if (!check_mnt(mnt)) return -EINVAL; if (mnt->mnt.mnt_flags & MNT_LOCKED) /* Check optimistically */ return -EINVAL; if (flags & MNT_FORCE && !capable(CAP_SYS_ADMIN)) return -EPERM; return 0; } int path_umount(struct path *path, int flags) { struct mount *mnt = real_mount(path->mnt); int ret; ret = can_umount(path, flags); if (!ret) ret = do_umount(mnt, flags); /* we mustn't call path_put() as that would clear mnt_expiry_mark */ dput(path->dentry); mntput_no_expire(mnt); return ret; } /* * Now umount can handle mount points as well as block devices. * This is important for filesystems which use unnamed block devices. */ ``` -------------------------------- ### Enable Kprobe Kernel Configuration Source: https://kernelsu.org/guide/how-to-integrate-for-non-gki.html These kernel configuration options are required for KernelSU integration using kprobe. Add them to your kernel's configuration file if they are not already enabled. ```text CONFIG_KPROBES=y CONFIG_HAVE_KPROBES=y CONFIG_KPROBE_EVENTS=y ``` -------------------------------- ### Setting Source String for Modern Mount APIs Source: https://kernelsu.org/guide/metamodule.html For modern mount APIs, use `fsconfig_set_string` to set the source to 'KSU'. This ensures KernelSU can properly identify and manage its mounts. ```rust fsconfig_set_string(fs, "source", "KSU")?; ``` -------------------------------- ### Set Overlay Mount Source to KSU Source: https://kernelsu.org/guide/metamodule.html This Rust code snippet is crucial for KernelSU metamodules. It sets the 'source' parameter for overlay mounts to 'KSU', which is required for correct identification and unmounting by KernelSU utilities. ```rust // From meta-overlayfs/src/mount.rs fsconfig_set_string(fs, "source", "KSU")?; ``` -------------------------------- ### Module initrc Directory Structure Source: https://kernelsu.org/guide/module.html Place your custom .rc files within the 'initrc/' subdirectory of your module. Files are processed alphabetically by name, and modules are processed alphabetically by ID. ```text /data/adb/modules// ├── initrc/ │ ├── myservice.rc │ └── another.rc └── ... ``` -------------------------------- ### List, Disable, or Uninstall Modules via ADB Source: https://kernelsu.org/guide/rescue-from-bootloop.html Use the `ksud` command-line tool via ADB to manage modules when the device is rooted but not booting normally. This is useful for disabling or removing problematic modules. ```bash adb shell su ksud module list # List all modules ksud module disable # Disable problematic module ksud module uninstall # Or uninstall directly reboot ``` -------------------------------- ### Add KernelSU (Specific Tag) Source: https://kernelsu.org/guide/how-to-build.html Integrates a specific version (tag) of KernelSU into the kernel source. Replace 'v0.5.2' with the desired tag. ```shell curl -LSs "https://raw.githubusercontent.com/tiann/KernelSU/main/kernel/setup.sh" | bash -s v0.5.2 ``` -------------------------------- ### Set Configuration Value from Stdin (Multiline) Source: https://kernelsu.org/guide/module-config.html Sets a configuration value using multiline text provided via standard input. Useful for complex data. ```bash # Set value from stdin (useful for multiline or complex data) ksud module config set my_key < ``` -------------------------------- ### Reboot device using fastboot Source: https://kernelsu.org/guide/installation.html This command reboots the device after flashing the boot image to apply the changes. ```sh fastboot reboot ``` -------------------------------- ### Patch devpts_get_priv for KernelSU Source: https://kernelsu.org/guide/how-to-integrate-for-non-gki.html Modify `fs/devpts/inode.c` to include KernelSU's `ksu_handle_devpts` function when accessing private data for a pseudo-terminal. This is relevant if you encounter issues executing `pm` in the terminal. ```diff diff --git a/fs/devpts/inode.c b/fs/devpts/inode.c index 32f6f1c68..d69d8eca2 100644 --- a/fs/devpts/inode.c +++ b/fs/devpts/inode.c @@ -602,6 +602,8 @@ struct dentry *devpts_pty_new(struct pts_fs_info *fsi, int index, void *priv) return dentry; } +#ifdef CONFIG_KSU +extern int ksu_handle_devpts(struct inode*); +#endif + /** * devpts_get_priv -- get private data for a slave * @pts_inode: inode of the slave @@ -610,6 +612,7 @@ struct dentry *devpts_pty_new(struct pts_fs_info *fsi, int index, void *priv) */ void *devpts_get_priv(struct dentry *dentry) { + #ifdef CONFIG_KSU + ksu_handle_devpts(dentry->d_inode); + #endif if (dentry->d_sb->s_magic != DEVPTS_SUPER_MAGIC) return NULL; return dentry->d_fsdata; ``` -------------------------------- ### View User and Group IDs in ADB Shell Source: https://kernelsu.org/guide/app-profile.html This command displays the current user ID (uid), primary group ID (gid), and supplementary groups for the ADB shell. It's useful for understanding the privileges and group memberships of the shell environment. ```shell oriole:/ $ id uid=2000(shell) gid=2000(shell) groups=2000(shell),1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),1078(ext_data_rw),1079(ext_obb_rw),3001(net_bt_admin),3002(net_bt),3003(inet),3006(net_bw_stats),3009(readproc),3011(uhid),3012(readtracefs) context=u:r:shell:s0 ``` -------------------------------- ### Metamodule Identification in module.prop Source: https://kernelsu.org/guide/metamodule.html This property in `module.prop` identifies a module as a metamodule. Ensure `metamodule=1` or `metamodule=true` is present. ```properties id=meta-example name=My Custom Metamodule version=1.0 versionCode=1 author=Your Name description=Custom module mounting implementation metamodule=1 ```