[
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2025 Cuynu\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "META-INF/com/google/android/update-binary",
    "content": "#!/sbin/sh\n\n#################\n# Initialization\n#################\n\numask 022\n\n# echo before loading util_functions\nui_print() { echo \"$1\"; }\n\nrequire_new_magisk() {\n  ui_print \"*******************************\"\n  ui_print \" Please install Magisk v20.4+! \"\n  ui_print \"*******************************\"\n  exit 1\n}\n\n#########################\n# Load util_functions.sh\n#########################\n\nOUTFD=$2\nZIPFILE=$3\n\nmount /data 2>/dev/null\n\n[ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk\n. /data/adb/magisk/util_functions.sh\n[ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk\n\ninstall_module\nexit 0\n"
  },
  {
    "path": "META-INF/com/google/android/updater-script",
    "content": "#MAGISK"
  },
  {
    "path": "README.md",
    "content": "# Google Photos unlimited backup module\nAdds Photos features and unlimited original backup\n\nCurrent version : **1.1-stable** [Download from releases](https://git.disroot.org/cuynu/gphotos-unlimited-zygisk/releases)\n\n### [Chuyển ngôn ngữ Tiếng Việt](https://git.disroot.org/cuynu/gphotos-unlimited-zygisk/wiki/VI)\n\n# Introduction \nBased from Pixelify GitHub. This module will spoof your device info to Pixel XL on Google apps and Google Photos to get unlimited backup storage at original quality !\n\n# Warning !\nModule will only works with Zygisk, it will not works with Riru, Shamiko, etc !!\n\nSome modules could break and prevent this module from running, if module does not work, try disable some modules and see.\n\n# Usage \nDownload module from [release page](https://git.disroot.org/cuynu/gphotos-unlimited-zygisk/releases), enable Zygisk then install with Magisk v24.3+ and reboot. \n\nFor KernelSU/KernelSU-Next/RKSU/APatch users, **DON'T use ZygiskNext 1.0.0+** !. Instead, use [ReZygisk](https://github.com/PerformanC/ReZygisk/releases). \n- Tested with : `Magisk v25.2+` `Magisk Delta/Kitsune` `KernelSU` `KernelSU-Next `APatch`\n\n# Known issues \n- **Some Xiaomi devices with MIUI 14 when this module is active, its will cause Bootloop with SystemUI crash exception**\n- When use with `Magisk-GApps` module, it will conflict and cause lose the ability to backup unlimited at original quality (Still able to backup unlimited at storage saver quality)\n\n# Tested devices\n- Sony Xperia XZ2 (Stock Android 10, LineageOS 18.1,19.1,20.0,21.0,22.2)\n- Redmi Note 7 (MIUI 12.5 CN, Nusantara EOL A10)\n- Google Pixel 2 (Android 11 stock)\n- Masstel_X9 (Stock Android 9, LineageOS 18.1/19.1)\n- LG G7 ThinQ (Stock Android 10, LineageOS 21.0/22.2)\n- Vsmart Joy 2+ (LineageOS 20.0)\n\n# ToDo\n- Rewrite hook library in C++ and take it away from Pixelify (as long as i learn C++ :>)\n\n# Build zygisk binary\n`git clone https://git.disroot.org/cuynu/gphotos-unlimited-zygisk.git`\n\nImport folder zygisk_build to Android Studio or Gradle and build then copy compiled zygisk library to zygisk folder (not zygisk_build)\n\n"
  },
  {
    "path": "customize.sh",
    "content": "for i in /system/product/etc/sysconfig/*; do\n    file=$i\n    file=${file/\\/system\\/product\\/etc\\/sysconfig\\//}\n    if [ ! -z \"$(grep PIXEL_2020_ $i)\" ] || [ ! -z \"$(grep PIXEL_2021_ $i)\" ] || [ ! -z \"$(grep PIXEL_2019_PRELOAD $i)\" ] || [ ! -z \"$(grep PIXEL_2018_PRELOAD $i)\" ] || [ ! -z \"$(grep PIXEL_2017_PRELOAD $i)\" ] || [ ! -z \"$(grep PIXEL_2022_ $i)\" ]; then\n        [ ! -f $MODPATH/system/product/etc/sysconfig/$file ] && cat /system/product/etc/sysconfig/$file | grep -v PIXEL_2020_ | grep -v PIXEL_2021_ | grep -v PIXEL_2022_ | grep -v PIXEL_2018_PRELOAD | grep -v PIXEL_2019_PRELOAD >$MODPATH/system/product/etc/sysconfig/$file\n    fi\ndone\nfor i in /system/etc/sysconfig/*; do\n    file=$i\n    file=${file/\\/system\\/etc\\/sysconfig\\//}\n    if [ ! -z \"$(grep PIXEL_2020_ $i)\" ] || [ ! -z \"$(grep PIXEL_2021_ $i)\" ] || [ ! -z \"$(grep PIXEL_2019_PRELOAD $i)\" ] || [ ! -z \"$(grep PIXEL_2018_PRELOAD $i)\" ] || [ ! -z \"$(grep PIXEL_2017_PRELOAD $i)\" ] || [ ! -z \"$(grep PIXEL_2022_ $i)\" ]; then\n        [ ! -f $MODPATH/system/product/etc/sysconfig/$file ] && cat /system/etc/sysconfig/$file | grep -v PIXEL_2020_ | grep -v PIXEL_2021_ | grep -v PIXEL_2022_ | grep -v PIXEL_2018_PRELOAD | grep -v PIXEL_2019_PRELOAD | grep -v PIXEL_2017_PRELOAD >$MODPATH/system/etc/sysconfig/$file\n    fi\ndone\nif [ -d /data/adb/modules/PixelifyPhotos/system/product/etc/sysconfig ]; then\n    for i in /data/adb/modules/PixelifyPhotos/system/product/etc/sysconfig/*; do\n        file=$i\n        file=${file/\\/data\\/adb\\/modules\\/PixelifyPhotos\\/system\\/product\\/etc\\/sysconfig\\//}\n        if [ ! -f $MODPATH/system/product/etc/sysconfig/$file ]; then\n            cp -f /data/adb/modules/PixelifyPhotos/system/product/etc/sysconfig/$file $MODPATH/system/product/etc/sysconfig/$file\n        fi\n    done\nfi\nif [ -d /data/adb/modules/PixelifyPhotos/system/etc/sysconfig ]; then\n    for i in /data/adb/modules/PixelifyPhotos/system/etc/sysconfig/*; do\n        file=$i\n        file=${file/\\/data\\/adb\\/modules\\/PixelifyPhotos\\/system\\/etc\\/sysconfig\\//}\n        if [ ! -f $MODPATH/system/etc/sysconfig/$file ]; then\n            cp -f /data/adb/modules/PixelifyPhotos/system/etc/sysconfig/$file $MODPATH/system/etc/sysconfig/$file\n        fi\n    done\nfi\n"
  },
  {
    "path": "module.prop",
    "content": "id=PixelifyPhotos\nname=Google Photos Unlimited backup\nversion=1.1-stable\nversionCode=002\nauthor=cuynu\ndescription=Adds Photos features and unlimited Google Photos original backup quality by spoof device info to Pixel XL only on Photos app.\n"
  },
  {
    "path": "system/etc/sysconfig/pixel_2017_exclusive.xml",
    "content": ""
  },
  {
    "path": "system/etc/sysconfig/pixel_2018_exclusive.xml",
    "content": ""
  },
  {
    "path": "system/etc/sysconfig/pixel_2019_exclusive.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_2016_exclusive.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<!-- These are configurations that should exist on Google's 2016 Pixel devices. -->\n<config>\n    <!-- Both versions of this string are needed due to a miscommunication. b/29978934 -->\n    <feature name=\"com.google.android.apps.photos.NEXUS_PRELOAD\" />\n    <feature name=\"com.google.android.apps.photos.nexus_preload\" />\n</config>\n"
  },
  {
    "path": "system/product/etc/sysconfig/pixel_2017_exclusive.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_2018_exclusive.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_2019_exclusive.xml",
    "content": "\n"
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2017.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<!-- These are configurations that should exist on Google's 2017 and newer Nexus devices. -->\n<config>\n    <!-- This is meant to be the canonical feature identifying 2017 and newer Nexus devices. -->\n    <feature name=\"com.google.android.feature.PIXEL_2017_EXPERIENCE\" />\n\n    <!--\n       This is the canonical feature identifying devices which bundle Google Fi support. The\n       Fi app and associated apps will be bundled (but may be disabled until a matching SIM\n       is inserted).\n       This feature may not be present before Android S.\n    -->\n    <feature name=\"com.google.android.feature.GOOGLE_FI_BUNDLED\" />\n\n    <!-- Allow SCONE JobIntentService & Services to run in background -->\n    <allow-in-power-save package=\"com.google.android.apps.scone\" />\n\n    <!-- Allow Flipendo in power save. Will be present on pre-2020 devices for dogfooding. -->\n    <allow-in-power-save-except-idle package=\"com.google.android.flipendo\" />\n\n    <!-- Allow Better Bug to take bug report. -->\n    <bugreport-whitelisted package=\"com.google.android.apps.betterbug\" />\n    <bugreport-whitelisted package=\"com.google.android.apps.internal.betterbug\" />\n    <bugreport-whitelisted package=\"com.google.android.apps.betterbug.partners\" />\n\n    <!-- Allow Pixel modem service to run in background -->\n    <allow-in-power-save package=\"com.google.modemservice\" />\n\n    <!-- Allow MDS ExperimentService to run in background -->\n    <allow-in-power-save package=\"com.google.mds\" />\n\n    <!-- Allow Exo services to run in background -->\n    <allow-in-power-save package=\"com.google.pixel.exo\" />\n    <allow-in-power-save package=\"com.google.ambient.streaming\" />\n\n    <!-- Allow OMA DM to run in background -->\n    <allow-in-power-save package=\"com.android.omadm.service\" />\n    <allow-in-power-save package=\"com.android.sdm.plugins.connmo\" />\n    <allow-in-power-save package=\"com.android.sdm.plugins.dcmo\" />\n    <allow-in-power-save package=\"com.android.sdm.plugins.diagmon\" />\n    <allow-in-power-save package=\"com.android.vzwomatrigger\" />\n    <allow-in-power-save package=\"com.android.sdm.plugins.usccdm\" />\n\n    <!-- Allow Gate runners to run in background -->\n    <allow-in-power-save package=\"com.google.pixel.gate.android.pysupport\" />\n    <allow-in-power-save package=\"com.google.pixel.gate.android.daemon\" />\n\n    <!-- Hide DocumentsUi Launcher/Downloads intent handling. DocumentsUi\n         PrebootReceiver does not properly hide the launcher in work profile,\n         so we need to include this as well. -->\n    <component-override package=\"com.google.android.documentsui\" >\n        <component class=\"com.android.documentsui.LauncherActivity\" enabled=\"false\" />\n        <component class=\"com.android.documentsui.ViewDownloadsActivity\" enabled=\"false\" />\n    </component-override>\n\n    <!-- ACTION_MANAGE_STORAGE handled by Files by Google -->\n    <component-override package=\"com.google.android.storagemanager\" >\n        <component class=\"com.android.storagemanager.deletionhelper.DeletionHelperActivity\" enabled=\"false\" />\n    </component-override>\n\n    <!-- Make sure photos/video previews are handled by Photos. -->\n    <component-override package=\"com.google.android.apps.nbu.files\" >\n        <component class=\"com.google.android.apps.nbu.files.gateway.preview.PreviewActivity\" enabled=\"false\" />\n    </component-override>\n\n    <component-override package=\"com.android.settings\" >\n        <!-- Display regulatory info in settings. -->\n        <component class=\".RegulatoryInfoDisplayActivity\" enabled=\"true\" />\n    </component-override>\n\n    <!-- Feature flag on RVC builds for AER requirements, b/159247801 -->\n    <feature name=\"com.google.android.feature.AER_OPTIMIZED\" />\n\n</config>\n"
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2018.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<!-- These are configurations that should exist on Google's 2018 and newer Pixel devices. -->\n<config>\n    <!-- Allow Pixel modem service in background -->\n    <allow-in-power-save package=\"com.google.modemservice\" />\n\n    <!-- Allow PixelLogger LoggingService to run in background -->\n    <allow-in-power-save package=\"com.android.pixellogger\" />\n\n    <!-- Allow Pixel Logger to take bug report. -->\n    <bugreport-whitelisted package=\"com.android.pixellogger\" />\n\n    <!-- Allow Flipendo in power save. Will be present on pre-2020 devices for dogfooding. -->\n    <allow-in-power-save-except-idle package=\"com.google.android.flipendo\" />\n\n    <!-- The AI services open-source network component can bind to the odad package. -->\n    <allow-association target=\"com.google.android.as.oss\" allowed=\"com.google.android.odad\" />\n\n    <!-- The odad package can only bind to the AI services open-source network component. -->\n    <allow-association target=\"com.google.android.odad\" allowed=\"com.google.android.as.oss\" />\n\n    <!-- This is meant to be the canonical feature identifying 2018 and newer Pixel devices. -->\n    <feature name=\"com.google.android.feature.PIXEL_2018_EXPERIENCE\" />\n</config>\n"
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2019.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<!-- These are configurations that should exist on Google's 2019 and newer devices. -->\n<config>\n    <!-- This is meant to be the canonical feature identifying 2019 and newer devices. -->\n    <feature name=\"com.google.android.feature.PIXEL_2019_EXPERIENCE\" />\n\n    <!-- Allow Flipendo in power save. Will be present on pre-2020 devices for dogfooding. -->\n    <allow-in-power-save-except-idle package=\"com.google.android.flipendo\" />\n</config>\n"
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2019_midyear.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2020.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2020_midyear.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2021.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2021_midyear.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2022.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixel_experience_2022_midyear.xml",
    "content": ""
  },
  {
    "path": "system/product/etc/sysconfig/pixelify_experience.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<!-- These are configurations that should exist on Pixelify devices. -->\n<config>\n    <!-- This is meant to be the canonical feature identifying 2016 and newer Nexus devices. -->\n    <feature name=\"com.google.android.feature.PIXEL_EXPERIENCE\" />\n\n    <!-- google KidsHome feature -->\n    <!-- <feature name=\"com.google.android.feature.KIDS_HOME_EXPERIENCE\" /> -->\n\n    <!-- Starting from Android R and above, the device with the system feature included would get Dialer call recording. -->\n    <feature name=\"com.google.android.apps.dialer.call_recording_audio\" />\n\n    <!-- <feature name=\"com.google.android.feature.PREMIER_TIER\" /> -->\n\n    <system-user-whitelisted-app package=\"com.google.android.tts\" />\n\n    <!-- TODO: This is a temporary workaround for allowing GmsCore to receive this broadcast.\n         This can be removed once OneTimeInitializer functionality is moved to GmsCore. -->\n    <!-- <allow-implicit-broadcast action=\"com.google.android.onetimeinitializer.ONE_TIME_INITIALIZED\" /> -->\n\n    <!-- <feature name=\"com.google.android.feature.EEA_DEVICE\" /> -->\n    <!-- <feature name=\"com.google.android.feature.EEA_V2_DEVICE\" /> -->\n    <!-- <feature name=\"com.google.android.paid.search\" /> -->\n    <!-- <feature name=\"com.google.android.paid.chrome\" /> -->\n    <!-- <feature name=\"com.google.android.feature.ASI_PIXEL6\" /> -->\n</config>\n"
  },
  {
    "path": "zygisk_build/build.gradle",
    "content": "import org.apache.tools.ant.filters.FixCrLfFilter\nimport org.apache.tools.ant.filters.ReplaceTokens\n\nimport java.security.MessageDigest\n\nplugins {\n    id 'com.android.library'\n}\n\napply from: file(rootProject.file('module.gradle'))\n\nandroid {\n    compileSdk target_sdk\n    defaultConfig {\n        minSdk min_sdk\n        targetSdk target_sdk\n        externalNativeBuild {\n            // ndkBuild {\n            //     path(\"src/main/cpp/external/Android.mk\")\n            // }\n            cmake {\n                arguments \"-DMODULE_NAME:STRING=$moduleLibraryName\";\n            }\n        }\n    }\n    buildFeatures {\n        prefab false\n    }\n    externalNativeBuild {\n        cmake {\n            path \"src/main/cpp/CMakeLists.txt\"\n        }\n    }\n}\n\nafterEvaluate {\n    android.libraryVariants.forEach { variant ->\n        def variantCapped = variant.name.capitalize()\n        def variantLowered = variant.name.toLowerCase()\n\n        def zipName = \"${magiskModuleId.replace('_', '-')}-${moduleVersion}.zip\"\n        def zipNamenovk = \"${magiskModuleId.replace('_', '-')}-${moduleVersion}-no-VK.zip\"\n        def magiskDir = file(\"$outDir/magisk_module_$variantLowered\")\n        def templatePath = \"$rootDir/module\"\n        def types = [Instance1: 'arm64-v8a', Instance2: 'armeabi-v7a',Instance3: 'x86',Instance4: 'x86_64']\n\n        task(\"prepareMagiskFiles${variantCapped}\", type: Sync) {\n            dependsOn(\"assemble$variantCapped\")\n            def nativeOutDir = file(\"$rootDir/riru/build/intermediates/cmake/$variant.name/obj\")\n\n            into magiskDir\n            from(templatePath) {\n                exclude 'module.prop', 'files/system'\n            }\n            from(templatePath) {\n                include 'module.prop'\n                expand([\n                        id         : magiskModuleId,\n                        name       : moduleName,\n                        version    : moduleVersion,\n                        versionCode: moduleVersionCode.toString(),\n                        author     : moduleAuthor,\n                        description: moduleDescription,\n                        volType: \"1\",\n                ])\n                filter(FixCrLfFilter.class,\n                        eol: FixCrLfFilter.CrLf.newInstance(\"lf\"))\n            }\n            types.each { instance, resourceDir ->\n                from(\"$buildDir/intermediates/stripped_native_libs/$variantLowered/out/lib/$resourceDir\") {\n                    into 'lib/zygisk'\n                    exclude \"**/libpixelify-tensor.so\"\n                    rename 'libpixelify.so', \"${resourceDir}.so\"\n                }\n                from(\"$buildDir/intermediates/stripped_native_libs/$variantLowered/out/lib/$resourceDir\") {\n                    into 'lib/zygisk_tensor'\n                    exclude \"**/libpixelify.so\"\n                    rename 'libpixelify-tensor.so', \"${resourceDir}.so\"\n                }\n            }\n            doLast {\n                copy {\n                    from \"$nativeOutDir\"\n                    into \"$magiskDir/lib/riru\"\n                    exclude \"**/*.txt\" , \"**/libpixelify-tensor.so\"\n                }\n                copy {\n                    from \"$nativeOutDir\"\n                    into \"$magiskDir/lib/riru_tensor\"\n                    exclude \"**/*.txt\" , \"**/libpixelify.so\"\n                    rename \"libpixelify-tensor.so\" , \"$variant.name\"\n                }\n            }\n\n        }\n\n        task(\"novk${variantCapped}\", type: Sync) {\n            dependsOn(\"assemble$variantCapped\")\n            def nativeOutDir = file(\"$rootDir/riru/build/intermediates/cmake/$variant.name/obj\")\n\n            into magiskDir\n            from(templatePath) {\n                exclude 'module.prop', 'files/system'\n            }\n            from(templatePath) {\n                include 'module.prop'\n                expand([\n                        id         : magiskModuleId,\n                        name       : moduleName,\n                        version    : moduleVersion,\n                        versionCode: moduleVersionCode.toString(),\n                        author     : moduleAuthor,\n                        description: moduleDescription,\n                        volType: \"0\",\n                ])\n                filter(FixCrLfFilter.class,\n                        eol: FixCrLfFilter.CrLf.newInstance(\"lf\"))\n            }\n            types.each { instance, resourceDir ->\n                from(\"$buildDir/intermediates/stripped_native_libs/$variantLowered/out/lib/$resourceDir\") {\n                    into 'lib/zygisk'\n                    exclude \"**/libpixelify-tensor.so\"\n                    rename 'libpixelify.so', \"${resourceDir}.so\"\n                }\n                from(\"$buildDir/intermediates/stripped_native_libs/$variantLowered/out/lib/$resourceDir\") {\n                    into 'lib/zygisk_tensor'\n                    exclude \"**/libpixelify.so\"\n                    rename 'libpixelify-tensor.so', \"${resourceDir}.so\"\n                }\n            }\n            doLast {\n                copy {\n                    from \"$nativeOutDir\"\n                    into \"$magiskDir/lib/riru\"\n                    exclude \"**/*.txt\" , \"**/libpixelify-tensor.so\"\n                }\n                copy {\n                    from \"$nativeOutDir\"\n                    into \"$magiskDir/lib/riru_tensor\"\n                    exclude \"**/*.txt\" , \"**/libpixelify.so\"\n                    rename \"libpixelify-tensor.so\" , \"libpixelify.so\"\n                }\n            }\n        }\n\n        task(\"zip${variantCapped}\", type: Zip) {\n            dependsOn(\"prepareMagiskFiles${variantCapped}\")\n            from magiskDir\n            archiveName zipName\n            destinationDir outDir\n        }\n\n        task(\"novkzip${variantCapped}\", type: Zip) {\n            dependsOn(\"zip${variantCapped}\")\n            dependsOn(\"novk${variantCapped}\")\n            tasks.findByName(\"novk${variantCapped}\").mustRunAfter \"zip${variantCapped}\"\n            from magiskDir\n            archiveName zipNamenovk\n            destinationDir outDir\n            doLast {\n                delete {\n                    from \"$outDir\"\n                    include \"config.prop\"\n                }\n                copy {\n                    from \"$templatePath\"\n                    into \"$outDir\"\n                    include \"config.prop\"\n                }\n            }           \n        }\n\n        task(\"push${variantCapped}\", type: Exec) {\n            dependsOn(\"zip${variantCapped}\")\n            workingDir outDir\n            commandLine android.adbExecutable, \"push\", zipName, \"/data/local/tmp/\"\n        }\n\n        task(\"flash${variantCapped}\", type: Exec) {\n            dependsOn(\"push${variantCapped}\")\n            commandLine android.adbExecutable, \"shell\", \"su\", \"-c\",\n                    \"magisk --install-module /data/local/tmp/${zipName}\"\n        }\n\n        task(\"flashAndReboot${variantCapped}\", type: Exec) {\n            dependsOn(\"flash${variantCapped}\")\n            commandLine android.adbExecutable, \"shell\", \"reboot\"\n        }\n\n        variant.assembleProvider.get().finalizedBy(\"novkzip${variantCapped}\")\n    }\n}\n"
  },
  {
    "path": "zygisk_build/src/main/AndroidManifest.xml",
    "content": "<manifest package=\"zygisk.template\" />\n"
  },
  {
    "path": "zygisk_build/src/main/cpp/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.4.1)\n\nif (NOT DEFINED MODULE_NAME)\n    message(FATAL_ERROR \"MODULE_NAME is not set\")\nelse ()\n    project(${MODULE_NAME})\nendif ()\n\n\nmessage(\"Build type: ${CMAKE_BUILD_TYPE}\")\n\nset(CMAKE_CXX_STANDARD 17)\n\nset(LINKER_FLAGS \"-ffixed-x18 -Wl,--hash-style=both\")\nset(C_FLAGS \"-Werror=format -fdata-sections -ffunction-sections\")\nset(CXX_FLAGS \"${CXX_FLAGS} -fno-exceptions -fno-rtti\")\n\nif (NOT CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n    set(C_FLAGS \"${C_FLAGS} -O2 -fvisibility=hidden -fvisibility-inlines-hidden\")\n    set(LINKER_FLAGS \"${LINKER_FLAGS} -Wl,-exclude-libs,ALL -Wl,--gc-sections -Wl,--strip-all\")\nelse ()\n    set(C_FLAGS \"${C_FLAGS} -O0\")\nendif ()\n\nset(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} ${C_FLAGS}\")\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} ${C_FLAGS} ${CXX_FLAGS}\")\n\nset(CMAKE_SHARED_LINKER_FLAGS \"${CMAKE_SHARED_LINKER_FLAGS} ${LINKER_FLAGS}\")\nset(CMAKE_MODULE_LINKER_FLAGS \"${CMAKE_MODULE_LINKER_FLAGS} ${LINKER_FLAGS}\")\n\n# find_package(REQUIRED CONFIG)\n\nadd_library(${MODULE_NAME} SHARED \n            pixelify.cpp\n            module.h)\ntarget_link_libraries(${MODULE_NAME} log)\n\nadd_library(${MODULE_NAME}-tensor SHARED\n            tensor.cpp\n            module.h)\ntarget_link_libraries(${MODULE_NAME}-tensor log)\n\nif (NOT CMAKE_BUILD_TYPE STREQUAL \"Debug\")\n    add_custom_command(TARGET ${MODULE_NAME} POST_BUILD\n            COMMAND ${CMAKE_STRIP} --strip-all --remove-section=.comment \"${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/lib${MODULE_NAME}.so\")\nendif ()\n"
  },
  {
    "path": "zygisk_build/src/main/cpp/module.h",
    "content": "#include \"errno.h\"\n#include \"android/log.h\"\n\n#pragma once\n\nnamespace pixelifytag {\n\n#ifndef TAG\n#define TAG    \"Pixelify\"\n#endif\n\n#ifdef NDEBUG\n#define LOGD(...)\n#else\n#define LOGD(...)     __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)\n#endif\n\n#define LOGI(...)     __android_log_print(ANDROID_LOG_INFO,  TAG, __VA_ARGS__)\n#define LOGW(...) \t  __android_log_print(ANDROID_LOG_WARN,  TAG, __VA_ARGS__)\n#define LOGE(...)     __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)\n#define LOGERRNO(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__ \": %d (%s)\", errno, strerror(errno))\n\n}\n"
  },
  {
    "path": "zygisk_build/src/main/cpp/pixelify.cpp",
    "content": "#include <cstdlib>\n#include <unistd.h>\n#include <fcntl.h>\n#include <string>\n#include <vector>\n#include <android/log.h>\n\n#include \"module.h\"\n#include \"zygisk.hpp\"\n\nusing zygisk::Api;\nusing zygisk::AppSpecializeArgs;\nusing zygisk::ServerSpecializeArgs;\n\n// Spoofing apps\nstatic std::vector<std::string> P1 = {\"com.google.android.apps.photos\", \"com.google.ar.core\", \"com.google.vr.apps.ornament\"};\nstatic std::vector<std::string> P5 = {\"com.google.android.tts\", \"com.google.android.apps.wearables.maestro.companion\", \"com.nothing.smartcenter\",\"com.google.android.googlequicksearchbox:interactor\"};\nstatic std::vector<std::string> P6 = {\"com.google\"};\nstatic std::vector<std::string> P7 = {\"com.google.pixel.livewallpaper\", \"com.google.android.apps.subscriptions.red\", \"com.breel.wallpaper\", \"com.snapchat.android\", \"com.google.android.gms\", \"com.google.android.googlequicksearchbox\",\"com.google.process.gapps\",\"com.google.process.gservices\"};\nstatic std::vector<std::string> PFold = {\"com.google.android.apps.subscriptions.red\"};\nstatic std::vector<std::string> keep = {\"com.google.android.apps.recorder\", \"com.google.android.GoogleCamera\", \"com.google.android.apps.motionsense.bridge\", \"com.google.android.gms.chimera\", \"com.google.android.gms.update\", \"com.android.camera\", \"com.google.android.xx\", \"com.google.android.googlequicksearchbox:HotwordDetectionService\",\"com.google.android.as:nonpersistent\",\"com.google.android.apps.mesagging:rcs\",\"com.google.android.googlequicksearchbox:assistant\"};\n\n// Fingerprint\nconst char P1_FP[256] = \"google/marlin/marlin:10/QP1A.191005.007.A3/5972272:user/release-keys\";\nconst char P5_FP[256] = \"google/redfin/redfin:13/TQ2A.230305.008.C1/9619669:user/release-keys\";\nconst char P6_FP[256] = \"google/raven/raven:13/TQ1A.230105.002/9325679:user/release-keys\";\nconst char P7_FP[256] = \"google/cheetah/cheetah:13/TQ2A.230305.008.C1/9619669:user/release-keys\";\n\nbool DEBUG = true;\nchar package_name[256];\nstatic int spoof_type;\n\n// Changed by magisk module\nconst char INTERNAL_SPOOFING[256] = \"INTERNAL_SPOOFING_NOT_SUPPORTED\";\n\nclass pixelify : public zygisk::ModuleBase\n{\npublic:\n    void onLoad(Api *api, JNIEnv *env) override\n    {\n        this->api = api;\n        this->env = env;\n    }\n    void preAppSpecialize(AppSpecializeArgs *args) override\n    {\n        // Use JNI to fetch our process name\n        const char *process = env->GetStringUTFChars(args->nice_name, nullptr);\n        spoof_type = getSpoof(process);\n        strcpy(package_name, process);\n        env->ReleaseStringUTFChars(args->nice_name, process);\n    }\n    void postAppSpecialize(const AppSpecializeArgs *) override\n    {\n        switch (spoof_type)\n        {\n        case 1:\n            injectBuild(\"Pixel XL\", \"marlin\", P1_FP);\n            //Register_Has_system_feature();\n            break;\n        case 2:\n            injectBuild(\"Pixel 5\", \"redfin\", P5_FP);\n            break;\n        case 3:\n            injectBuild(\"Pixel 6 Pro\", \"raven\", P6_FP);\n            break;\n        case 4:\n            injectBuild(\"Pixel 7 Pro\", \"cheetah\", P7_FP);\n            break;\n        case 5:\n            injectBuild(\"Pixel XL\", \"marlin\", P1_FP);\n            // N_MR1 (7.1.2) SDK Version is 25\n            injectversion(25);\n            break;\n        case 6:\n            injectBuild(\"Pixel Fold\", \"felix\", P7_FP);\n            break;\n        case 7:\n            if (strcmp(INTERNAL_SPOOFING, \"INTERNAL_SPOOFING_SUPPORTED\") == 0)\n            {\n                disablespoofinghack();\n            }\n            break;\n        default:\n            break;\n        }\n    }\n\nprivate:\n    Api *api;\n    JNIEnv *env;\n\n    void injectBuild(const char *model1, const char *product1, const char *finger1)\n    {\n        if (env == nullptr)\n        {\n            LOGW(\"failed to inject android.os.Build for %s due to env is null\", package_name);\n            return;\n        }\n\n        jclass build_class = env->FindClass(\"android/os/Build\");\n        if (build_class == nullptr)\n        {\n            LOGW(\"failed to inject android.os.Build for %s due to build is null\", package_name);\n            return;\n        }\n        else if (DEBUG)\n        {\n            LOGI(\"inject android.os.Build for %s with \\nPRODUCT:%s \\nMODEL:%s \\nFINGERPRINT:%s\", package_name, product1, model1, finger1);\n        }\n\n        jstring product = env->NewStringUTF(product1);\n        jstring model = env->NewStringUTF(model1);\n        jstring brand = env->NewStringUTF(\"google\");\n        jstring manufacturer = env->NewStringUTF(\"Google\");\n        jstring finger = env->NewStringUTF(finger1);\n\n        jfieldID brand_id = env->GetStaticFieldID(build_class, \"BRAND\", \"Ljava/lang/String;\");\n        if (brand_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, brand_id, brand);\n        }\n\n        jfieldID manufacturer_id = env->GetStaticFieldID(build_class, \"MANUFACTURER\", \"Ljava/lang/String;\");\n        if (manufacturer_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, manufacturer_id, manufacturer);\n        }\n\n        jfieldID product_id = env->GetStaticFieldID(build_class, \"PRODUCT\", \"Ljava/lang/String;\");\n        if (product_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, product_id, product);\n        }\n\n        jfieldID device_id = env->GetStaticFieldID(build_class, \"DEVICE\", \"Ljava/lang/String;\");\n        if (device_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, device_id, product);\n        }\n\n        jfieldID model_id = env->GetStaticFieldID(build_class, \"MODEL\", \"Ljava/lang/String;\");\n        if (model_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, model_id, model);\n        }\n        if (strcmp(finger1, \"\") != 0)\n        {\n            jfieldID finger_id = env->GetStaticFieldID(build_class, \"FINGERPRINT\", \"Ljava/lang/String;\");\n            if (finger_id != nullptr)\n            {\n                env->SetStaticObjectField(build_class, finger_id, finger);\n            }\n        }\n\n        if (env->ExceptionCheck())\n        {\n            env->ExceptionClear();\n        }\n\n        env->DeleteLocalRef(brand);\n        env->DeleteLocalRef(manufacturer);\n        env->DeleteLocalRef(product);\n        env->DeleteLocalRef(model);\n        env->DeleteLocalRef(finger);\n    }\n    void injectversion(const int inc_c)\n    {\n        if (env == nullptr)\n        {\n            LOGW(\"failed to inject android.os.Build for %s due to env is null\", package_name);\n            return;\n        }\n\n        jclass build_class = env->FindClass(\"android/os/Build$VERSION\");\n        if (build_class == nullptr)\n        {\n            LOGW(\"failed to inject android.os.Build.VERSION for %s due to build is null\", package_name);\n            return;\n        }\n\n        jint inc = (jint)inc_c;\n\n        jfieldID inc_id = env->GetStaticFieldID(build_class, \"DEVICE_INITIAL_SDK_INT\", \"I\");\n        if (inc_id != nullptr)\n        {\n            env->SetStaticIntField(build_class, inc_id, inc);\n        }\n\n        if (env->ExceptionCheck())\n        {\n            env->ExceptionClear();\n        }\n    }\n    void disablespoofinghack()\n    {\n        if (env == nullptr)\n        {\n            LOGW(\"failed to inject android.os.Build for %s due to env is null\", package_name);\n            return;\n        }\n        jclass pixel_prop_class = env->FindClass(\"com/android/internal/util/custom/PixelPropsUtils\");\n        if (pixel_prop_class == nullptr)\n        {\n            LOGW(\"failed to inject PixelPropUtils for %s due to build is null\", package_name);\n            return;\n        }\n        jstring pixelify = env->NewStringUTF(\"ro.pixelify.device\");\n        jfieldID device_id = env->GetStaticFieldID(pixel_prop_class, \"DEVICE\", \"Ljava/lang/String;\");\n        if (device_id != nullptr)\n        {\n            env->SetStaticObjectField(pixel_prop_class, device_id, pixelify);\n        }\n        env->DeleteLocalRef(pixelify);\n    }\n    int getSpoof(const char *process)\n    {\n        std::string package = process;\n        if (strcmp(process, \"com.google.android.gms.unstable\") == 0)\n            return 5;\n        else if (strcmp(process, \"system_server\") == 0)\n            return 7;\n\n        for (auto &s : keep)\n        {\n            if (package.find(s) != std::string::npos)\n                return 0;\n        }\n        for (auto &s : P1)\n        {\n            if (package.find(s) != std::string::npos)\n                return 1;\n        }\n        for (auto &s : P5)\n        {\n            if (package.find(s) != std::string::npos)\n                return 2;\n        }\n        for (auto &s : P7)\n        {\n            if (package.find(s) != std::string::npos)\n                return 4;\n        }\n        for (auto &s : PFold)\n        {\n            if (package.find(s) != std::string::npos)\n                return 6;\n        }\n        for (auto &s : P6)\n        {\n            if (package.find(s) != std::string::npos)\n                return 3;\n        }\n        return 0;\n    }\n};\n\nREGISTER_ZYGISK_MODULE(pixelify)"
  },
  {
    "path": "zygisk_build/src/main/cpp/tensor.cpp",
    "content": "#include <cstdlib>\n#include <unistd.h>\n#include <string>\n#include <vector>\n#include <fcntl.h>\n#include <android/log.h>\n\n#include \"zygisk.hpp\"\n#include \"module.h\"\n\nusing zygisk::Api;\nusing zygisk::AppSpecializeArgs;\nusing zygisk::ServerSpecializeArgs;\n\nclass pixelify : public zygisk::ModuleBase\n{\npublic:\n    void onLoad(Api *api, JNIEnv *env) override\n    {\n        this->api = api;\n        this->env = env;\n    }\n\n    void preAppSpecialize(AppSpecializeArgs *args) override\n    {\n        // Use JNI to fetch our process name\n        const char *process = env->GetStringUTFChars(args->nice_name, nullptr);\n        preSpecialize(process);\n        env->ReleaseStringUTFChars(args->nice_name, process);\n    }\n\n    void preServerSpecialize(ServerSpecializeArgs *args) override\n    {\n        preSpecialize(\"system_server\");\n    }\n\n    void injectBuild(const char *package_name, const char *model1, const char *product1, const char *finger1)\n    {\n        if (env == nullptr)\n        {\n            LOGW(\"failed to inject android.os.Build for %s due to env is null\", package_name);\n            return;\n        }\n\n        jclass build_class = env->FindClass(\"android/os/Build\");\n        if (build_class == nullptr)\n        {\n            LOGW(\"failed to inject android.os.Build for %s due to build is null\", package_name);\n            return;\n        }\n        else\n        {\n            LOGI(\"inject android.os.Build for %s with \\nPRODUCT:%s \\nMODEL:%s \\nFINGERPRINT:%s\", package_name, product1, model1, finger1);\n        }\n\n        jstring product = env->NewStringUTF(product1);\n        jstring model = env->NewStringUTF(model1);\n        jstring brand = env->NewStringUTF(\"google\");\n        jstring manufacturer = env->NewStringUTF(\"Google\");\n        jstring finger = env->NewStringUTF(finger1);\n\n        jfieldID brand_id = env->GetStaticFieldID(build_class, \"BRAND\", \"Ljava/lang/String;\");\n        if (brand_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, brand_id, brand);\n        }\n\n        jfieldID manufacturer_id = env->GetStaticFieldID(build_class, \"MANUFACTURER\", \"Ljava/lang/String;\");\n        if (manufacturer_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, manufacturer_id, manufacturer);\n        }\n\n        jfieldID product_id = env->GetStaticFieldID(build_class, \"PRODUCT\", \"Ljava/lang/String;\");\n        if (product_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, product_id, product);\n        }\n\n        jfieldID device_id = env->GetStaticFieldID(build_class, \"DEVICE\", \"Ljava/lang/String;\");\n        if (device_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, device_id, product);\n        }\n\n        jfieldID model_id = env->GetStaticFieldID(build_class, \"MODEL\", \"Ljava/lang/String;\");\n        if (model_id != nullptr)\n        {\n            env->SetStaticObjectField(build_class, model_id, model);\n        }\n        if (strcmp(finger1, \"\") != 0)\n        {\n            jfieldID finger_id = env->GetStaticFieldID(build_class, \"FINGERPRINT\", \"Ljava/lang/String;\");\n            if (finger_id != nullptr)\n            {\n                env->SetStaticObjectField(build_class, finger_id, finger);\n            }\n        }\n\n        if (env->ExceptionCheck())\n        {\n            env->ExceptionClear();\n        }\n\n        env->DeleteLocalRef(brand);\n        env->DeleteLocalRef(manufacturer);\n        env->DeleteLocalRef(product);\n        env->DeleteLocalRef(model);\n        if (strcmp(finger1, \"\") != 0)\n        {\n            env->DeleteLocalRef(finger);\n        }\n    }\n\nprivate:\n    Api *api;\n    JNIEnv *env;\n\n    void preSpecialize(const char *process)\n    {\n        unsigned r = 0;\n        int fd = api->connectCompanion();\n        read(fd, &r, sizeof(r));\n        close(fd);\n        int need_p6 = 0;\n        std::string package_name = process;\n        if (package_name.find(\"com.google.android.apps.photos\") != std::string::npos)\n        {\n            injectBuild(process, \"Pixel XL\", \"marlin\", \"google/marlin/marlin:10/QP1A.191005.007.A3/5972272:user/release-keys\");\n        }\n\n        api->setOption(zygisk::Option::DLCLOSE_MODULE_LIBRARY);\n    }\n};\n\nstatic int urandom = -1;\n\nstatic void companion_handler(int i)\n{\n    if (urandom < 0)\n    {\n        urandom = open(\"/dev/urandom\", O_RDONLY);\n    }\n    unsigned r;\n    read(urandom, &r, sizeof(r));\n    LOGD(\"example: companion r=[%u]\\n\", r);\n    write(i, &r, sizeof(r));\n}\n\nREGISTER_ZYGISK_MODULE(pixelify)\nREGISTER_ZYGISK_COMPANION(companion_handler)"
  },
  {
    "path": "zygisk_build/src/main/cpp/zygisk.hpp",
    "content": "/* Copyright 2022-2023 John \"topjohnwu\" Wu\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n * PERFORMANCE OF THIS SOFTWARE.\n */\n\n// This is the public API for Zygisk modules.\n// DO NOT MODIFY ANY CODE IN THIS HEADER.\n\n#pragma once\n\n#include <jni.h>\n\n#define ZYGISK_API_VERSION 4\n\n/*\n\n***************\n* Introduction\n***************\n\nOn Android, all app processes are forked from a special daemon called \"Zygote\".\nFor each new app process, zygote will fork a new process and perform \"specialization\".\nThis specialization operation enforces the Android security sandbox on the newly forked\nprocess to make sure that 3rd party application code is only loaded after it is being\nrestricted within a sandbox.\n\nOn Android, there is also this special process called \"system_server\". This single\nprocess hosts a significant portion of system services, which controls how the\nAndroid operating system and apps interact with each other.\n\nThe Zygisk framework provides a way to allow developers to build modules and run custom\ncode before and after system_server and any app processes' specialization.\nThis enable developers to inject code and alter the behavior of system_server and app processes.\n\nPlease note that modules will only be loaded after zygote has forked the child process.\nTHIS MEANS ALL OF YOUR CODE RUNS IN THE APP/SYSTEM_SERVER PROCESS, NOT THE ZYGOTE DAEMON!\n\n*********************\n* Development Guide\n*********************\n\nDefine a class and inherit zygisk::ModuleBase to implement the functionality of your module.\nUse the macro REGISTER_ZYGISK_MODULE(className) to register that class to Zygisk.\n\nExample code:\n\nstatic jint (*orig_logger_entry_max)(JNIEnv *env);\nstatic jint my_logger_entry_max(JNIEnv *env) { return orig_logger_entry_max(env); }\n\nclass ExampleModule : public zygisk::ModuleBase {\npublic:\n    void onLoad(zygisk::Api *api, JNIEnv *env) override {\n        this->api = api;\n        this->env = env;\n    }\n    void preAppSpecialize(zygisk::AppSpecializeArgs *args) override {\n        JNINativeMethod methods[] = {\n            { \"logger_entry_max_payload_native\", \"()I\", (void*) my_logger_entry_max },\n        };\n        api->hookJniNativeMethods(env, \"android/util/Log\", methods, 1);\n        *(void **) &orig_logger_entry_max = methods[0].fnPtr;\n    }\nprivate:\n    zygisk::Api *api;\n    JNIEnv *env;\n};\n\nREGISTER_ZYGISK_MODULE(ExampleModule)\n\n-----------------------------------------------------------------------------------------\n\nSince your module class's code runs with either Zygote's privilege in pre[XXX]Specialize,\nor runs in the sandbox of the target process in post[XXX]Specialize, the code in your class\nnever runs in a true superuser environment.\n\nIf your module require access to superuser permissions, you can create and register\na root companion handler function. This function runs in a separate root companion\ndaemon process, and an Unix domain socket is provided to allow you to perform IPC between\nyour target process and the root companion process.\n\nExample code:\n\nstatic void example_handler(int socket) { ... }\n\nREGISTER_ZYGISK_COMPANION(example_handler)\n\n*/\n\nnamespace zygisk {\n\nstruct Api;\nstruct AppSpecializeArgs;\nstruct ServerSpecializeArgs;\n\nclass ModuleBase {\npublic:\n\n    // This method is called as soon as the module is loaded into the target process.\n    // A Zygisk API handle will be passed as an argument.\n    virtual void onLoad([[maybe_unused]] Api *api, [[maybe_unused]] JNIEnv *env) {}\n\n    // This method is called before the app process is specialized.\n    // At this point, the process just got forked from zygote, but no app specific specialization\n    // is applied. This means that the process does not have any sandbox restrictions and\n    // still runs with the same privilege of zygote.\n    //\n    // All the arguments that will be sent and used for app specialization is passed as a single\n    // AppSpecializeArgs object. You can read and overwrite these arguments to change how the app\n    // process will be specialized.\n    //\n    // If you need to run some operations as superuser, you can call Api::connectCompanion() to\n    // get a socket to do IPC calls with a root companion process.\n    // See Api::connectCompanion() for more info.\n    virtual void preAppSpecialize([[maybe_unused]] AppSpecializeArgs *args) {}\n\n    // This method is called after the app process is specialized.\n    // At this point, the process has all sandbox restrictions enabled for this application.\n    // This means that this method runs with the same privilege of the app's own code.\n    virtual void postAppSpecialize([[maybe_unused]] const AppSpecializeArgs *args) {}\n\n    // This method is called before the system server process is specialized.\n    // See preAppSpecialize(args) for more info.\n    virtual void preServerSpecialize([[maybe_unused]] ServerSpecializeArgs *args) {}\n\n    // This method is called after the system server process is specialized.\n    // At this point, the process runs with the privilege of system_server.\n    virtual void postServerSpecialize([[maybe_unused]] const ServerSpecializeArgs *args) {}\n};\n\nstruct AppSpecializeArgs {\n    // Required arguments. These arguments are guaranteed to exist on all Android versions.\n    jint &uid;\n    jint &gid;\n    jintArray &gids;\n    jint &runtime_flags;\n    jobjectArray &rlimits;\n    jint &mount_external;\n    jstring &se_info;\n    jstring &nice_name;\n    jstring &instruction_set;\n    jstring &app_data_dir;\n\n    // Optional arguments. Please check whether the pointer is null before de-referencing\n    jintArray *const fds_to_ignore;\n    jboolean *const is_child_zygote;\n    jboolean *const is_top_app;\n    jobjectArray *const pkg_data_info_list;\n    jobjectArray *const whitelisted_data_info_list;\n    jboolean *const mount_data_dirs;\n    jboolean *const mount_storage_dirs;\n\n    AppSpecializeArgs() = delete;\n};\n\nstruct ServerSpecializeArgs {\n    jint &uid;\n    jint &gid;\n    jintArray &gids;\n    jint &runtime_flags;\n    jlong &permitted_capabilities;\n    jlong &effective_capabilities;\n\n    ServerSpecializeArgs() = delete;\n};\n\nnamespace internal {\nstruct api_table;\ntemplate <class T> void entry_impl(api_table *, JNIEnv *);\n}\n\n// These values are used in Api::setOption(Option)\nenum Option : int {\n    // Force Magisk's denylist unmount routines to run on this process.\n    //\n    // Setting this option only makes sense in preAppSpecialize.\n    // The actual unmounting happens during app process specialization.\n    //\n    // Set this option to force all Magisk and modules' files to be unmounted from the\n    // mount namespace of the process, regardless of the denylist enforcement status.\n    FORCE_DENYLIST_UNMOUNT = 0,\n\n    // When this option is set, your module's library will be dlclose-ed after post[XXX]Specialize.\n    // Be aware that after dlclose-ing your module, all of your code will be unmapped from memory.\n    // YOU MUST NOT ENABLE THIS OPTION AFTER HOOKING ANY FUNCTIONS IN THE PROCESS.\n    DLCLOSE_MODULE_LIBRARY = 1,\n};\n\n// Bit masks of the return value of Api::getFlags()\nenum StateFlag : uint32_t {\n    // The user has granted root access to the current process\n    PROCESS_GRANTED_ROOT = (1u << 0),\n\n    // The current process was added on the denylist\n    PROCESS_ON_DENYLIST = (1u << 1),\n};\n\n// All API methods will stop working after post[XXX]Specialize as Zygisk will be unloaded\n// from the specialized process afterwards.\nstruct Api {\n\n    // Connect to a root companion process and get a Unix domain socket for IPC.\n    //\n    // This API only works in the pre[XXX]Specialize methods due to SELinux restrictions.\n    //\n    // The pre[XXX]Specialize methods run with the same privilege of zygote.\n    // If you would like to do some operations with superuser permissions, register a handler\n    // function that would be called in the root process with REGISTER_ZYGISK_COMPANION(func).\n    // Another good use case for a companion process is that if you want to share some resources\n    // across multiple processes, hold the resources in the companion process and pass it over.\n    //\n    // The root companion process is ABI aware; that is, when calling this method from a 32-bit\n    // process, you will be connected to a 32-bit companion process, and vice versa for 64-bit.\n    //\n    // Returns a file descriptor to a socket that is connected to the socket passed to your\n    // module's companion request handler. Returns -1 if the connection attempt failed.\n    int connectCompanion();\n\n    // Get the file descriptor of the root folder of the current module.\n    //\n    // This API only works in the pre[XXX]Specialize methods.\n    // Accessing the directory returned is only possible in the pre[XXX]Specialize methods\n    // or in the root companion process (assuming that you sent the fd over the socket).\n    // Both restrictions are due to SELinux and UID.\n    //\n    // Returns -1 if errors occurred.\n    int getModuleDir();\n\n    // Set various options for your module.\n    // Please note that this method accepts one single option at a time.\n    // Check zygisk::Option for the full list of options available.\n    void setOption(Option opt);\n\n    // Get information about the current process.\n    // Returns bitwise-or'd zygisk::StateFlag values.\n    uint32_t getFlags();\n\n    // Exempt the provided file descriptor from being automatically closed.\n    //\n    // This API only make sense in preAppSpecialize; calling this method in any other situation\n    // is either a no-op (returns true) or an error (returns false).\n    //\n    // When false is returned, the provided file descriptor will eventually be closed by zygote.\n    bool exemptFd(int fd);\n\n    // Hook JNI native methods for a class\n    //\n    // Lookup all registered JNI native methods and replace it with your own methods.\n    // The original function pointer will be saved in each JNINativeMethod's fnPtr.\n    // If no matching class, method name, or signature is found, that specific JNINativeMethod.fnPtr\n    // will be set to nullptr.\n    void hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods);\n\n    // Hook functions in the PLT (Procedure Linkage Table) of ELFs loaded in memory.\n    //\n    // Parsing /proc/[PID]/maps will give you the memory map of a process. As an example:\n    //\n    //       <address>       <perms>  <offset>   <dev>  <inode>           <pathname>\n    // 56b4346000-56b4347000  r-xp    00002000   fe:00    235       /system/bin/app_process64\n    // (More details: https://man7.org/linux/man-pages/man5/proc.5.html)\n    //\n    // The `dev` and `inode` pair uniquely identifies a file being mapped into memory.\n    // For matching ELFs loaded in memory, replace function `symbol` with `newFunc`.\n    // If `oldFunc` is not nullptr, the original function pointer will be saved to `oldFunc`.\n    void pltHookRegister(dev_t dev, ino_t inode, const char *symbol, void *newFunc, void **oldFunc);\n\n    // Commit all the hooks that was previously registered.\n    // Returns false if an error occurred.\n    bool pltHookCommit();\n\nprivate:\n    internal::api_table *tbl;\n    template <class T> friend void internal::entry_impl(internal::api_table *, JNIEnv *);\n};\n\n// Register a class as a Zygisk module\n\n#define REGISTER_ZYGISK_MODULE(clazz) \\\nvoid zygisk_module_entry(zygisk::internal::api_table *table, JNIEnv *env) { \\\n    zygisk::internal::entry_impl<clazz>(table, env);                        \\\n}\n\n// Register a root companion request handler function for your module\n//\n// The function runs in a superuser daemon process and handles a root companion request from\n// your module running in a target process. The function has to accept an integer value,\n// which is a Unix domain socket that is connected to the target process.\n// See Api::connectCompanion() for more info.\n//\n// NOTE: the function can run concurrently on multiple threads.\n// Be aware of race conditions if you have globally shared resources.\n\n#define REGISTER_ZYGISK_COMPANION(func) \\\nvoid zygisk_companion_entry(int client) { func(client); }\n\n/*********************************************************\n * The following is internal ABI implementation detail.\n * You do not have to understand what it is doing.\n *********************************************************/\n\nnamespace internal {\n\nstruct module_abi {\n    long api_version;\n    ModuleBase *impl;\n\n    void (*preAppSpecialize)(ModuleBase *, AppSpecializeArgs *);\n    void (*postAppSpecialize)(ModuleBase *, const AppSpecializeArgs *);\n    void (*preServerSpecialize)(ModuleBase *, ServerSpecializeArgs *);\n    void (*postServerSpecialize)(ModuleBase *, const ServerSpecializeArgs *);\n\n    module_abi(ModuleBase *module) : api_version(ZYGISK_API_VERSION), impl(module) {\n        preAppSpecialize = [](auto m, auto args) { m->preAppSpecialize(args); };\n        postAppSpecialize = [](auto m, auto args) { m->postAppSpecialize(args); };\n        preServerSpecialize = [](auto m, auto args) { m->preServerSpecialize(args); };\n        postServerSpecialize = [](auto m, auto args) { m->postServerSpecialize(args); };\n    }\n};\n\nstruct api_table {\n    // Base\n    void *impl;\n    bool (*registerModule)(api_table *, module_abi *);\n\n    void (*hookJniNativeMethods)(JNIEnv *, const char *, JNINativeMethod *, int);\n    void (*pltHookRegister)(dev_t, ino_t, const char *, void *, void **);\n    bool (*exemptFd)(int);\n    bool (*pltHookCommit)();\n    int  (*connectCompanion)(void * /* impl */);\n    void (*setOption)(void * /* impl */, Option);\n    int  (*getModuleDir)(void * /* impl */);\n    uint32_t (*getFlags)(void * /* impl */);\n};\n\ntemplate <class T>\nvoid entry_impl(api_table *table, JNIEnv *env) {\n    static Api api;\n    api.tbl = table;\n    static T module;\n    ModuleBase *m = &module;\n    static module_abi abi(m);\n    if (!table->registerModule(table, &abi)) return;\n    m->onLoad(&api, env);\n}\n\n} // namespace internal\n\ninline int Api::connectCompanion() {\n    return tbl->connectCompanion ? tbl->connectCompanion(tbl->impl) : -1;\n}\ninline int Api::getModuleDir() {\n    return tbl->getModuleDir ? tbl->getModuleDir(tbl->impl) : -1;\n}\ninline void Api::setOption(Option opt) {\n    if (tbl->setOption) tbl->setOption(tbl->impl, opt);\n}\ninline uint32_t Api::getFlags() {\n    return tbl->getFlags ? tbl->getFlags(tbl->impl) : 0;\n}\ninline bool Api::exemptFd(int fd) {\n    return tbl->exemptFd != nullptr && tbl->exemptFd(fd);\n}\ninline void Api::hookJniNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int numMethods) {\n    if (tbl->hookJniNativeMethods) tbl->hookJniNativeMethods(env, className, methods, numMethods);\n}\ninline void Api::pltHookRegister(dev_t dev, ino_t inode, const char *symbol, void *newFunc, void **oldFunc) {\n    if (tbl->pltHookRegister) tbl->pltHookRegister(dev, inode, symbol, newFunc, oldFunc);\n}\ninline bool Api::pltHookCommit() {\n    return tbl->pltHookCommit != nullptr && tbl->pltHookCommit();\n}\n\n} // namespace zygisk\n\nextern \"C\" {\n\n[[gnu::visibility(\"default\"), maybe_unused]]\nvoid zygisk_module_entry(zygisk::internal::api_table *, JNIEnv *);\n\n[[gnu::visibility(\"default\"), maybe_unused]]\nvoid zygisk_companion_entry(int);\n\n} // extern \"C\""
  }
]