app: Remove dynamic code loading and simplify stub

Remove dynamic APK class and resource loading across :app, :shared,
and :stub. Consolidate stub resources into :stub and remove stub
obfuscation and encryption.

- Merge :stub-res into :stub and delete the :stub-res module.
- Delete DynLoad, DelegateComponentFactory, ClassLoaders,
  StubApplication, StubRootService, and dummy component classes.
- Delete StubApk, DynamicClassLoader, and CompoundEnumeration from
  :shared.
- Remove lsparanoid, stub component randomization, resource
  encryption, and Stub.kt from build-logic.
- Remove stubVersion and STUB_VERSION tracking.
- Simplify DownloadActivity to use direct resources and APKInstall.
- Remove isRunningAsStub and stub-specific hooks across :core.

Assisted-by: Gemini 4 Argon
This commit is contained in:
topjohnwu
2026-10-22 14:06:48 -07:00
committed by John Wu
parent 1240c2e35c
commit 7d9b0dfb3e
89 changed files with 59 additions and 1367 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ For Magisk app crashes, record and upload the logcat when the crash occurs.
Default string resources for the Magisk app and its stub APK are located here:
- `app/core/src/main/res/values/strings.xml`
- `app/stub-res/src/main/res/values/strings.xml`
- `app/stub/src/main/res/values/strings.xml`
Translate each and place them in the respective locations (`[module]/src/main/res/values-[lang]/strings.xml`).
-2
View File
@@ -1,5 +1,3 @@
/dict.txt
# Gradle
.gradle
.kotlin
@@ -238,8 +238,6 @@ class MainActivity : ComponentActivity(), SplashScreenHost {
}
}
override fun showInvalidStateMessage() {}
private fun showUnsupportedMessage() {
val messages = mutableListOf<Pair<Int, Int>>()
-8
View File
@@ -4,12 +4,6 @@ import org.gradle.api.Project
import org.gradle.kotlin.dsl.provideDelegate
import java.io.File
import java.util.Properties
import java.util.Random
// Set non-zero value here to fix the random seed for reproducible builds
// CI builds are always reproducible
val RAND_SEED = if (System.getenv("CI") != null) 42 else 0
lateinit var RANDOM: Random
val ABI_SUPPORT_LIST = listOf("armeabi-v7a", "arm64-v8a", "x86", "x86_64", "riscv64")
private val props = Properties()
@@ -28,7 +22,6 @@ object Config {
// Properties from gradle.properties, should always exist
val versionCode: Int get() = get("magisk.versionCode")!!.toInt()
val stubVersion: String get() = get("magisk.stubVersion")!!
}
fun Project.rootFile(path: String): File {
@@ -41,7 +34,6 @@ class MagiskPlugin : Plugin<Project> {
override fun apply(project: Project) = project.applyPlugin()
private fun Project.applyPlugin() {
initRandom(rootProject.file("dict.txt"))
props.clear()
// Get gradle properties relevant to Magisk
+1 -2
View File
@@ -262,8 +262,7 @@ fun Project.setupAppCommon() {
// Always add a transformation to set comments on the APK
this.transformations.add {
it.eocdComment = ("version=${Config.version}\n" +
"versionCode=${Config.versionCode}\n" +
"stubVersion=${Config.stubVersion}\n").toByteArray()
"versionCode=${Config.versionCode}\n").toByteArray()
}
}
-309
View File
@@ -1,309 +0,0 @@
import com.android.build.api.artifact.SingleArtifact
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.assign
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import java.security.SecureRandom
import java.util.Random
import java.util.zip.Deflater
import java.util.zip.DeflaterOutputStream
import java.util.zip.ZipFile
import javax.crypto.Cipher
import javax.crypto.CipherOutputStream
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import kotlin.random.asKotlinRandom
private val kRANDOM get() = RANDOM.asKotlinRandom()
private val c1 = mutableListOf<String>()
private val c2 = mutableListOf<String>()
private val c3 = mutableListOf<String>()
fun initRandom(dict: File) {
RANDOM = if (RAND_SEED != 0) Random(RAND_SEED.toLong()) else SecureRandom()
c1.clear()
c2.clear()
c3.clear()
for (a in chain('a'..'z', 'A'..'Z')) {
if (a != 'a' && a != 'A') {
c1.add("$a")
}
for (b in chain('a'..'z', 'A'..'Z', '0'..'9')) {
c2.add("$a$b")
for (c in chain('a'..'z', 'A'..'Z', '0'..'9')) {
c3.add("$a$b$c")
}
}
}
c1.shuffle(RANDOM)
c2.shuffle(RANDOM)
c3.shuffle(RANDOM)
PrintStream(dict).use {
for (c in chain(c1, c2, c3)) {
it.println(c)
}
}
}
private fun <T> chain(vararg iters: Iterable<T>) = sequence {
iters.forEach { it.forEach { v -> yield(v) } }
}
private fun PrintStream.byteField(name: String, bytes: ByteArray) {
println("public static byte[] $name() {")
print("byte[] buf = {")
print(bytes.joinToString(",") { it.toString() })
println("};")
println("return buf;")
println("}")
}
@CacheableTask
private abstract class ManifestUpdater: DefaultTask() {
@get:Input
abstract val applicationId: Property<String>
@get:Input
abstract val factoryClass: Property<String>
@get:Input
abstract val appClass: Property<String>
@get:InputFile
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val mergedManifest: RegularFileProperty
@get:OutputFile
abstract val outputManifest: RegularFileProperty
@TaskAction
fun taskAction() {
fun String.ind(level: Int) = replaceIndentByMargin(" ".repeat(level))
val cmpList = mutableListOf<String>()
cmpList.add("""
|<provider
| android:name="x.COMPONENT_PLACEHOLDER_0"
| android:authorities="${'$'}{applicationId}.provider"
| android:directBootAware="true"
| android:exported="false"
| android:grantUriPermissions="true" />""".ind(2)
)
cmpList.add("""
|<receiver
| android:name="x.COMPONENT_PLACEHOLDER_1"
| android:exported="false">
| <intent-filter>
| <action android:name="android.intent.action.LOCALE_CHANGED" />
| <action android:name="android.intent.action.UID_REMOVED" />
| <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
| </intent-filter>
| <intent-filter>
| <action android:name="android.intent.action.PACKAGE_FULLY_REMOVED" />
|
| <data android:scheme="package" />
| </intent-filter>
|</receiver>""".ind(2)
)
cmpList.add("""
|<activity
| android:name="x.COMPONENT_PLACEHOLDER_2"
| android:exported="true">
| <intent-filter>
| <action android:name="android.intent.action.MAIN" />
| <category android:name="android.intent.category.LAUNCHER" />
| </intent-filter>
|</activity>""".ind(2)
)
cmpList.add("""
|<service
| android:name="x.COMPONENT_PLACEHOLDER_3"
| android:exported="false"
| android:foregroundServiceType="dataSync" />""".ind(2)
)
cmpList.add("""
|<service
| android:name="x.COMPONENT_PLACEHOLDER_4"
| android:exported="false"
| android:permission="android.permission.BIND_JOB_SERVICE" />""".ind(2)
)
// Shuffle the order of the components
cmpList.shuffle(RANDOM)
val components = cmpList.joinToString("\n\n")
.replace("\${applicationId}", applicationId.get())
val manifest = mergedManifest.asFile.get().readText().replace(Regex(".*\\<application"), """
|<application
| android:appComponentFactory="${factoryClass.get()}"
| android:name="${appClass.get()}"""".ind(1)
).replace(Regex(".*\\<\\/application"), "$components\n </application")
outputManifest.get().asFile.writeText(manifest)
}
}
private fun genStubClasses(outDir: File): Pair<String, String> {
val classNameGenerator = sequence {
fun notJavaKeyword(name: String) = when (name) {
"do", "if", "for", "int", "new", "try" -> false
else -> true
}
fun List<String>.process() = asSequence()
.filter(::notJavaKeyword)
// Distinct by lower case to support case insensitive file systems
.distinctBy { it.lowercase() }
val names = mutableListOf<String>()
names.addAll(c1)
names.addAll(c2.process().take(30))
names.addAll(c3.process().take(30))
names.shuffle(RANDOM)
while (true) {
val cls = StringBuilder()
cls.append(names.random(kRANDOM))
cls.append('.')
cls.append(names.random(kRANDOM))
// Old Android does not support capitalized package names
// Check Android 7.0.0 PackageParser#buildClassName
yield(cls.toString().replaceFirstChar { it.lowercase() })
}
}.distinct().iterator()
fun genClass(type: String, outDir: File): String {
val clzName = classNameGenerator.next()
val (pkg, name) = clzName.split('.')
val pkgDir = File(outDir, pkg)
pkgDir.mkdirs()
PrintStream(File(pkgDir, "$name.java")).use {
it.println("package $pkg;")
it.println("public class $name extends com.topjohnwu.magisk.$type {}")
}
return clzName
}
val factory = genClass("DelegateComponentFactory", outDir)
val app = genClass("StubApplication", outDir)
return Pair(factory, app)
}
private fun genEncryptedResources(res: ByteArray, outDir: File) {
val mainPkgDir = File(outDir, "com/topjohnwu/magisk")
mainPkgDir.mkdirs()
// Generate iv and key
val iv = ByteArray(16)
val key = ByteArray(32)
RANDOM.nextBytes(iv)
RANDOM.nextBytes(key)
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), IvParameterSpec(iv))
val bos = ByteArrayOutputStream()
ByteArrayInputStream(res).use {
CipherOutputStream(bos, cipher).use { os ->
it.transferTo(os)
}
}
PrintStream(File(mainPkgDir, "Bytes.java")).use {
it.println("package com.topjohnwu.magisk;")
it.println("public final class Bytes {")
it.byteField("key", key)
it.byteField("iv", iv)
it.byteField("res", bos.toByteArray())
it.println("}")
}
}
private abstract class TaskWithDir : DefaultTask() {
@get:OutputDirectory
abstract val outputFolder: DirectoryProperty
}
fun Project.setupStubApk() {
setupAppCommon()
androidAppComponents {
onVariants { variant ->
val variantName = variant.name
val variantCapped = variantName.replaceFirstChar { it.uppercase() }
val variantLowered = variantName.lowercase()
val componentJavaOutDir = layout.buildDirectory
.dir("generated/${variantLowered}/components").get().asFile
componentJavaOutDir.deleteRecursively()
val (factory, app) = genStubClasses(componentJavaOutDir)
val manifestUpdater =
project.tasks.register("${variantName}ManifestProducer", ManifestUpdater::class.java) {
applicationId = variant.applicationId
factoryClass.set(factory)
appClass.set(app)
}
variant.artifacts.use(manifestUpdater)
.wiredWithFiles(
ManifestUpdater::mergedManifest,
ManifestUpdater::outputManifest)
.toTransform(SingleArtifact.MERGED_MANIFEST)
val resTask = tasks.getByPath(":stub-res:package$variantCapped")
val genResourcesTask = tasks.register("generate${variantCapped}BundledResources", TaskWithDir::class) {
dependsOn(resTask)
outputFolder.set(layout.buildDirectory.dir("generated/${variantLowered}/resources"))
doLast {
val apk = resTask.outputs.files.asFileTree
.filter { it.name.endsWith(".apk") }.files.first()
val bos = ByteArrayOutputStream()
ZipFile(apk).use { src ->
DeflaterOutputStream(bos, Deflater(Deflater.BEST_COMPRESSION)).use {
src.getInputStream(src.getEntry("resources.arsc")).transferTo(it)
}
}
genEncryptedResources(bos.toByteArray(), outputFolder.get().asFile)
}
}
tasks.withType(TransformApkTask::class) {
transformations.add {
// Always delete resources.arsc from the APK
// to ensure that external resources can be loaded
it.get("resources.arsc")?.delete()
}
}
variant.sources.java?.let {
it.addStaticSourceDirectory(componentJavaOutDir.path)
it.addGeneratedSourceDirectory(genResourcesTask, TaskWithDir::outputFolder)
}
}
}
}
-1
View File
@@ -5,7 +5,6 @@ plugins {
alias(libs.plugins.ksp) apply false
alias(libs.plugins.compose.compiler) apply false
alias(libs.plugins.moshix) apply false
alias(libs.plugins.lsparanoid) apply false
}
tasks.register("clean", Delete::class) {
-1
View File
@@ -23,7 +23,6 @@ android {
buildConfigField("String", "APP_PACKAGE_NAME", "\"com.topjohnwu.magisk\"")
buildConfigField("int", "APP_VERSION_CODE", "${Config.versionCode}")
buildConfigField("String", "APP_VERSION_NAME", "\"${Config.version}\"")
buildConfigField("int", "STUB_VERSION", Config.stubVersion)
consumerProguardFile("proguard-rules.pro")
}
@@ -2,26 +2,11 @@ package com.topjohnwu.magisk.core
import android.app.Application
import android.content.Context
import com.topjohnwu.magisk.StubApk
import com.topjohnwu.magisk.core.utils.RootUtils
open class App() : Application() {
constructor(o: Any) : this() {
val data = StubApk.Data(o)
// Add the root service name mapping
data.classToComponent[RootUtils::class.java.name] = data.rootService.name
// Send back the actual root service class
data.rootService = RootUtils::class.java
Info.stub = data
}
open class App : Application() {
override fun attachBaseContext(context: Context) {
if (context is Application) {
AppContext.attachApplication(context)
} else {
super.attachBaseContext(context)
AppContext.attachApplication(this)
}
super.attachBaseContext(context)
AppContext.attachApplication(this)
}
}
@@ -2,7 +2,6 @@ package com.topjohnwu.magisk.core
import android.app.Activity
import android.app.Application
import android.app.LocaleManager
import android.content.ComponentCallbacks2
import android.content.Context
import android.content.ContextWrapper
@@ -11,7 +10,6 @@ import android.os.Build.VERSION.SDK_INT
import android.os.Bundle
import android.system.Os
import androidx.profileinstaller.ProfileInstaller
import com.topjohnwu.magisk.StubApk
import com.topjohnwu.magisk.core.base.UntrackedActivity
import com.topjohnwu.magisk.core.utils.LocaleSetting
import com.topjohnwu.magisk.core.utils.NetworkObserver
@@ -78,11 +76,7 @@ object AppContext : ContextWrapper(null),
app.registerActivityLifecycleCallbacks(this)
app.registerComponentCallbacks(this)
AppApkPath = if (isRunningAsStub) {
StubApk.current(base).path
} else {
base.packageResourcePath
}
AppApkPath = base.packageResourcePath
resources.patch()
val shellBuilder = Shell.Builder.create()
@@ -100,13 +94,8 @@ object AppContext : ContextWrapper(null),
// Pre-heat the shell ASAP
Shell.getShell(null) {}
if (SDK_INT >= 34 && isRunningAsStub) {
// Send over the locale config manually
val lm = getSystemService(LocaleManager::class.java)
lm.overrideLocaleConfig = LocaleSetting.localeConfig
}
networkObserver = NetworkObserver.init(this)
if (!BuildConfig.DEBUG && !isRunningAsStub) {
if (!BuildConfig.DEBUG) {
@OptIn(kotlinx.coroutines.DelicateCoroutinesApi::class)
GlobalScope.launch(Dispatchers.IO) {
ProfileInstaller.writeProfile(this@AppContext)
@@ -8,15 +8,10 @@ import android.content.ContextWrapper
import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import com.topjohnwu.magisk.StubApk
import com.topjohnwu.magisk.core.ktx.unwrap
import com.topjohnwu.magisk.core.utils.LocaleSetting
fun Resources.addAssetPath(path: String) = StubApk.addAssetPath(this, path)
fun Resources.patch(): Resources {
if (isRunningAsStub)
addAssetPath(AppApkPath)
LocaleSetting.instance.updateResource(this)
return this
}
@@ -36,8 +31,7 @@ fun Context.wrap(): Context {
}
}
fun Class<*>.cmp(pkg: String) =
ComponentName(pkg, Info.stub?.classToComponent?.get(name) ?: name)
fun Class<*>.cmp(pkg: String) = ComponentName(pkg, name)
inline fun <reified T> Context.intent() = Intent().setComponent(T::class.java.cmp(packageName))
@@ -3,7 +3,6 @@ package com.topjohnwu.magisk.core
import android.app.KeyguardManager
import android.os.Build
import androidx.lifecycle.MutableLiveData
import com.topjohnwu.magisk.StubApk
import com.topjohnwu.magisk.core.ktx.getProperty
import com.topjohnwu.magisk.core.model.UpdateInfo
import com.topjohnwu.magisk.core.repository.NetworkService
@@ -13,12 +12,8 @@ import com.topjohnwu.superuser.ShellUtils.fastCmd
import com.topjohnwu.superuser.ShellUtils.fastCmdResult
import kotlinx.coroutines.Runnable
val isRunningAsStub get() = Info.stub != null
object Info {
var stub: StubApk.Data? = null
private val EMPTY_UPDATE = UpdateInfo()
var update = EMPTY_UPDATE
private set
@@ -6,9 +6,7 @@ import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.Lifecycle
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.JobService
import com.topjohnwu.magisk.core.R
import com.topjohnwu.magisk.core.di.ServiceLocator
import com.topjohnwu.magisk.core.isRunningAsStub
import com.topjohnwu.magisk.core.utils.RootUtils
import com.topjohnwu.magisk.view.Notifications
import com.topjohnwu.magisk.view.Shortcuts
@@ -18,7 +16,6 @@ interface SplashScreenHost : IActivityExtension {
val splashController: SplashController<*>
fun onCreateUi(savedInstanceState: Bundle?)
fun showInvalidStateMessage()
}
class SplashController<T>(private val activity: T)
@@ -30,39 +27,23 @@ class SplashController<T>(private val activity: T)
private var shouldCreateUiOnResume = false
fun preOnCreate() {
if (isRunningAsStub && !splashShown) {
// Manually apply splash theme for stub
activity.theme.applyStyle(R.style.StubSplashTheme, true)
}
}
fun preOnCreate() {}
fun onCreate(savedInstanceState: Bundle?) {
if (!isRunningAsStub) {
val splashScreen = activity.installSplashScreen()
splashScreen.setKeepOnScreenCondition { !splashShown }
}
val splashScreen = activity.installSplashScreen()
splashScreen.setKeepOnScreenCondition { !splashShown }
if (splashShown) {
doCreateUi(savedInstanceState)
} else {
Shell.getShell(Shell.EXECUTOR) {
if (isRunningAsStub && !it.isRoot) {
activity.showInvalidStateMessage()
return@getShell
}
activity.initializeApp()
activity.runOnUiThread {
splashShown = true
if (isRunningAsStub) {
// Re-launch main activity without splash theme
activity.relaunch()
if (activity.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
doCreateUi(savedInstanceState)
} else {
if (activity.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
doCreateUi(savedInstanceState)
} else {
shouldCreateUiOnResume = true
}
shouldCreateUiOnResume = true
}
}
}
@@ -6,14 +6,12 @@ import android.os.Process
import android.system.Os
import androidx.annotation.WorkerThread
import androidx.core.os.postDelayed
import com.topjohnwu.magisk.StubApk
import com.topjohnwu.magisk.core.AppApkPath
import com.topjohnwu.magisk.core.BuildConfig
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.di.ServiceLocator
import com.topjohnwu.magisk.core.isRunningAsStub
import com.topjohnwu.magisk.core.ktx.copyAll
import com.topjohnwu.magisk.core.ktx.writeTo
import com.topjohnwu.magisk.core.utils.DataChannel
@@ -32,7 +30,6 @@ import com.topjohnwu.superuser.nio.ExtendedFile
import com.topjohnwu.superuser.nio.FileSystemManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.commons.compress.archivers.zip.ZipFile
import timber.log.Timber
import java.io.Closeable
import java.io.File
@@ -126,47 +123,24 @@ abstract class MagiskInstallImpl protected constructor(
try {
// Extract binaries
if (isRunningAsStub) {
ZipFile.builder().setFile(StubApk.current(context)).get().use { zf ->
zf.entries.asSequence().filter {
!it.isDirectory && it.name.startsWith("lib/${Const.CPU_ABI}/")
}.forEach {
val n = it.name.substring(it.name.lastIndexOf('/') + 1)
val name = n.substring(3, n.length - 3)
val dest = File(installDir, name)
zf.getInputStream(it).writeTo(dest)
dest.setExecutable(true)
}
val info = context.applicationInfo
val libs = File(info.nativeLibraryDir).listFiles { _, name ->
name.startsWith("lib") && name.endsWith(".so")
} ?: emptyArray()
val abi32 = Const.CPU_ABI_32
if (Process.is64Bit() && abi32 != null) {
val entry = zf.getEntry("lib/$abi32/libmagisk.so")
if (entry != null) {
val magisk32 = File(installDir, "magisk32")
zf.getInputStream(entry).writeTo(magisk32)
}
}
}
} else {
val info = context.applicationInfo
val libs = File(info.nativeLibraryDir).listFiles { _, name ->
name.startsWith("lib") && name.endsWith(".so")
} ?: emptyArray()
for (lib in libs) {
val name = lib.name.substring(3, lib.name.length - 3)
Os.symlink(lib.path, "$installDir/$name")
}
for (lib in libs) {
val name = lib.name.substring(3, lib.name.length - 3)
Os.symlink(lib.path, "$installDir/$name")
}
// Also extract magisk32 on 64-bit devices that supports 32-bit
val abi32 = Const.CPU_ABI_32
if (Process.is64Bit() && abi32 != null) {
val name = "lib/$abi32/libmagisk.so"
val entry = javaClass.classLoader!!.getResourceAsStream(name)
if (entry != null) {
val magisk32 = File(installDir, "magisk32")
entry.writeTo(magisk32)
}
// Also extract magisk32 on 64-bit devices that supports 32-bit
val abi32 = Const.CPU_ABI_32
if (Process.is64Bit() && abi32 != null) {
val name = "lib/$abi32/libmagisk.so"
val entry = javaClass.classLoader!!.getResourceAsStream(name)
if (entry != null) {
val magisk32 = File(installDir, "magisk32")
entry.writeTo(magisk32)
}
}
@@ -3,7 +3,6 @@ package com.topjohnwu.magisk.core.utils
import android.annotation.SuppressLint
import android.app.LocaleConfig
import android.app.LocaleManager
import android.content.ContextWrapper
import android.content.Intent
import android.content.res.Resources
import android.net.Uri
@@ -11,12 +10,10 @@ import android.os.Build
import android.os.LocaleList
import android.provider.Settings
import androidx.annotation.RequiresApi
import com.topjohnwu.magisk.core.AppApkPath
import com.topjohnwu.magisk.core.AppContext
import com.topjohnwu.magisk.core.Config
import com.topjohnwu.magisk.core.R
import com.topjohnwu.magisk.core.base.relaunch
import com.topjohnwu.magisk.core.isRunningAsStub
import org.xmlpull.v1.XmlPullParser
import java.util.Locale
@@ -91,7 +88,7 @@ interface LocaleSetting {
names.add(AppContext.getString(R.string.system_default))
tags.add("")
if ((Build.VERSION.SDK_INT == 34 && !isRunningAsStub) || Build.VERSION.SDK_INT >= 35) {
if (Build.VERSION.SDK_INT >= 34) {
// Use platform LocaleConfig parser
val config = localeConfig
val list = config.supportedLocales ?: LocaleList.getEmptyLocaleList()
@@ -124,22 +121,11 @@ interface LocaleSetting {
@get:RequiresApi(34)
val localeConfig: LocaleConfig by lazy {
val context = if (isRunningAsStub) {
val pkgInfo = AppContext.packageManager.getPackageArchiveInfo(AppApkPath, 0)!!
object : ContextWrapper(AppContext) {
override fun getApplicationInfo() = pkgInfo.applicationInfo
}
} else {
AppContext
}
LocaleConfig.fromContextIgnoringOverride(context)
LocaleConfig.fromContextIgnoringOverride(AppContext)
}
private val localeManagerUsable get() =
if (isRunningAsStub) Build.VERSION.SDK_INT >= 35 else Build.VERSION.SDK_INT >= 33
val useLocaleManager by lazy {
localeManagerUsable &&
Build.VERSION.SDK_INT >= 33 &&
localeSettingsIntent.resolveActivity(AppContext.packageManager) != null
}
@@ -1,17 +1,9 @@
package com.topjohnwu.magisk.core.utils
import android.content.Context
import com.topjohnwu.magisk.StubApk
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.isRunningAsStub
import com.topjohnwu.magisk.core.ktx.cachedFile
import com.topjohnwu.magisk.core.ktx.writeTo
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.io.File
import java.util.jar.JarFile
class ShellInit : Shell.Initializer() {
override fun onInit(context: Context, shell: Shell): Boolean {
@@ -23,21 +15,7 @@ class ShellInit : Shell.Initializer() {
shell.newJob().apply {
add("export ASH_STANDALONE=1")
val localBB: File
if (isRunningAsStub) {
if (!shell.isRoot)
return true
val jar = JarFile(StubApk.current(context))
val bb = jar.getJarEntry("lib/${Const.CPU_ABI}/libbusybox.so")
localBB = context.createDeviceProtectedStorageContext().cachedFile("busybox")
localBB.delete()
runBlocking {
jar.getInputStream(bb).writeTo(localBB, dispatcher = Dispatchers.Unconfined)
}
localBB.setExecutable(true)
} else {
localBB = File(context.applicationInfo.nativeLibraryDir, "libbusybox.so")
}
val localBB = File(context.applicationInfo.nativeLibraryDir, "libbusybox.so")
if (shell.isRoot) {
add("export MAGISKTMP=\$(magisk --path)")
@@ -11,8 +11,6 @@ import androidx.core.content.getSystemService
import com.topjohnwu.magisk.core.Const
import com.topjohnwu.magisk.core.Info
import com.topjohnwu.magisk.core.R
import com.topjohnwu.magisk.core.isRunningAsStub
import com.topjohnwu.magisk.core.ktx.getBitmap
object Shortcuts {
@@ -23,16 +21,7 @@ object Shortcuts {
}
}
private fun Context.getIcon(id: Int): Icon {
return if (isRunningAsStub) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
Icon.createWithAdaptiveBitmap(getBitmap(id))
else
Icon.createWithBitmap(getBitmap(id))
} else {
Icon.createWithResource(this, id)
}
}
private fun Context.getIcon(id: Int): Icon = Icon.createWithResource(this, id)
@RequiresApi(api = 25)
private fun getShortCuts(context: Context): List<ShortcutInfo> {
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- For stub on API 31+, we cannot rely on the platform SplashScreen -->
<!-- Force using SplashScreen.Common that was used for older APIs -->
<style name="StubSplashTheme" parent="Theme.SplashScreen.Common">
<item name="android:enforceStatusBarContrast">false</item>
<item name="android:enforceNavigationBarContrast">false</item>
<item name="windowSplashScreenBackground">@color/splash_background</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/ic_magisk_padded</item>
</style>
</resources>
-1
View File
@@ -4,5 +4,4 @@
<item name="windowSplashScreenBackground">@color/splash_background</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/ic_magisk_padded</item>
</style>
<style name="StubSplashTheme" parent="SplashTheme"/>
</resources>
-1
View File
@@ -30,5 +30,4 @@ kapt.use.k2=true
android.injected.testOnly=false
# Magisk
magisk.stubVersion=41
magisk.versionCode=31000
-1
View File
@@ -76,6 +76,5 @@ android-application = { id = "com.android.application", version.ref = "android"
android-library = { id = "com.android.library", version.ref = "android" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
lsparanoid = { id = "org.lsposed.lsparanoid", version = "0.6.0" }
moshix = { id = "dev.zacsweers.moshix", version = "0.37.0" }
wire = { id = "com.squareup.wire", version.ref = "wire" }
+1 -1
View File
@@ -31,4 +31,4 @@ pluginManagement {
}
rootProject.name = "Magisk"
include(":apk", ":core", ":shared", ":stub", ":stub-res", ":test")
include(":apk", ":core", ":shared", ":stub", ":test")
@@ -1,114 +0,0 @@
package com.topjohnwu.magisk;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.ParcelFileDescriptor.MODE_READ_ONLY;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.loader.ResourcesLoader;
import android.content.res.loader.ResourcesProvider;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
public class StubApk {
private static File dynDir;
private static Method addAssetPath;
private static File getDynDir(ApplicationInfo info) {
if (dynDir == null) {
// Use device protected path to allow directBootAware
dynDir = new File(info.deviceProtectedDataDir, "dyn");
dynDir.mkdirs();
}
return dynDir;
}
public static File current(Context c) {
return new File(getDynDir(c.getApplicationInfo()), "current.apk");
}
public static File current(ApplicationInfo info) {
return new File(getDynDir(info), "current.apk");
}
public static File update(Context c) {
return new File(getDynDir(c.getApplicationInfo()), "update.apk");
}
public static File update(ApplicationInfo info) {
return new File(getDynDir(info), "update.apk");
}
@TargetApi(Build.VERSION_CODES.R)
private static ResourcesLoader getResourcesLoader(File path) throws IOException {
var loader = new ResourcesLoader();
ResourcesProvider provider;
if (path.isDirectory()) {
provider = ResourcesProvider.loadFromDirectory(path.getPath(), null);
} else {
var fd = ParcelFileDescriptor.open(path, MODE_READ_ONLY);
provider = ResourcesProvider.loadFromApk(fd);
}
loader.addProvider(provider);
return loader;
}
public static void addAssetPath(Resources res, String path) {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
res.addLoaders(getResourcesLoader(new File(path)));
} catch (IOException ignored) {}
} else {
AssetManager asset = res.getAssets();
try {
if (addAssetPath == null)
addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
addAssetPath.invoke(asset, path);
} catch (Exception ignored) {}
}
}
public static void restartProcess(Activity activity) {
Intent intent = activity.getPackageManager()
.getLaunchIntentForPackage(activity.getPackageName());
activity.finishAffinity();
activity.startActivity(intent);
Runtime.getRuntime().exit(0);
}
public static class Data {
// Indices of the object array
private static final int STUB_VERSION = 0;
private static final int CLASS_COMPONENT_MAP = 1;
private static final int ROOT_SERVICE = 2;
private static final int ARR_SIZE = 3;
private final Object[] arr;
public Data() { arr = new Object[ARR_SIZE]; }
public Data(Object o) { arr = (Object[]) o; }
public Object getObject() { return arr; }
public int getVersion() { return (int) arr[STUB_VERSION]; }
public void setVersion(int version) { arr[STUB_VERSION] = version; }
public Map<String, String> getClassToComponent() {
// noinspection unchecked
return (Map<String, String>) arr[CLASS_COMPONENT_MAP];
}
public void setClassToComponent(Map<String, String> map) {
arr[CLASS_COMPONENT_MAP] = map;
}
public Class<?> getRootService() { return (Class<?>) arr[ROOT_SERVICE]; }
public void setRootService(Class<?> service) { arr[ROOT_SERVICE] = service; }
}
}
@@ -1,35 +0,0 @@
package com.topjohnwu.magisk.utils;
import java.util.Enumeration;
import java.util.NoSuchElementException;
public class CompoundEnumeration<E> implements Enumeration<E> {
private Enumeration<E>[] enums;
private int index = 0;
@SafeVarargs
public CompoundEnumeration(Enumeration<E> ...enums) {
this.enums = enums;
}
private boolean next() {
while (index < enums.length) {
if (enums[index] != null && enums[index].hasMoreElements()) {
return true;
}
index++;
}
return false;
}
public boolean hasMoreElements() {
return next();
}
public E nextElement() {
if (!next()) {
throw new NoSuchElementException();
}
return enums[index].nextElement();
}
}
@@ -1,65 +0,0 @@
package com.topjohnwu.magisk.utils;
import android.os.Process;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import dalvik.system.BaseDexClassLoader;
public class DynamicClassLoader extends BaseDexClassLoader {
public DynamicClassLoader(File apk) {
this(apk, DynamicClassLoader.class.getClassLoader());
}
public DynamicClassLoader(File apk, ClassLoader parent) {
// Set optimizedDirectory to null for RootService to bypass DexFile's security checks
super(apk.getPath(), Process.myUid() == 0 ? null : apk.getParentFile(), null, parent);
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
// First check if already loaded
Class<?> cls = findLoadedClass(name);
if (cls != null)
return cls;
try {
// Then check boot classpath
return getSystemClassLoader().loadClass(name);
} catch (ClassNotFoundException ignored) {
try {
// Next try current dex
return findClass(name);
} catch (ClassNotFoundException fromSuper) {
try {
// Finally try parent
return getParent().loadClass(name);
} catch (ClassNotFoundException e) {
throw fromSuper;
}
}
}
}
@Override
public URL getResource(String name) {
URL resource = getSystemClassLoader().getResource(name);
if (resource != null)
return resource;
resource = findResource(name);
if (resource != null)
return resource;
resource = getParent().getResource(name);
return resource;
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
return new CompoundEnumeration<>(getSystemClassLoader().getResources(name),
findResources(name), getParent().getResources(name));
}
}
-16
View File
@@ -1,16 +0,0 @@
plugins {
alias(libs.plugins.android.application)
}
setupCommon()
android {
namespace = "com.topjohnwu.magisk"
enableKotlin = false
buildTypes {
release {
isShrinkResources = false
}
}
}
@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest><application /></manifest>
+1 -9
View File
@@ -1,12 +1,5 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.lsparanoid)
}
lsparanoid {
seed = if (RAND_SEED != 0) RAND_SEED else null
includeDependencies = true
classFilter = { true }
}
android {
@@ -21,7 +14,6 @@ android {
versionCode = 1
versionName = "1.0"
buildConfigField("String", "APK_URL", "\"$url\"")
buildConfigField("int", "STUB_VERSION", Config.stubVersion)
}
buildTypes {
@@ -36,7 +28,7 @@ android {
}
}
setupStubApk()
setupAppCommon()
dependencies {
implementation(project(":shared"))
-9
View File
@@ -20,13 +20,4 @@
# hide the original source file name.
#-renamesourcefileattribute SourceFile
-obfuscationdictionary ../dict.txt
-classobfuscationdictionary ../dict.txt
-packageobfuscationdictionary ../dict.txt
# Excessive obfuscation
-repackageclasses
-allowaccessmodification
-keepclassmembers class com.topjohnwu.magisk.dummy.* { <init>(); }
-keepclassmembers class com.topjohnwu.magisk.DownloadActivity { <init>(); }
-keepclassmembers class com.topjohnwu.magisk.StubRootService { <init>(); }
+8 -4
View File
@@ -3,11 +3,15 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission
android:name="com.android.launcher.permission.INSTALL_SHORTCUT"
android:maxSdkVersion="25" />
<application tools:ignore="MissingApplicationIcon">
<activity
android:name=".DownloadActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -1,68 +0,0 @@
package com.topjohnwu.magisk;
import android.content.pm.PackageInfo;
import com.topjohnwu.magisk.dummy.DummyProvider;
import com.topjohnwu.magisk.dummy.DummyReceiver;
import com.topjohnwu.magisk.dummy.DummyService;
import java.util.HashMap;
import java.util.Map;
// Wrap the actual classloader as we only want to resolve classname
// mapping when loading from platform (via LoadedApk.mClassLoader)
class MappingClassLoader extends ClassLoader {
private final Map<String, String> mapping;
MappingClassLoader(ClassLoader parent, Map<String, String> m) {
super(parent);
mapping = m;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
String clz = mapping.get(name);
name = clz != null ? clz : name;
return super.loadClass(name, resolve);
}
}
class StubClassLoader extends ClassLoader {
private final Map<String, Class<?>> mapping = new HashMap<>();
StubClassLoader(PackageInfo info) {
super(StubClassLoader.class.getClassLoader());
for (var c : info.activities) {
mapping.put(c.name, DownloadActivity.class);
}
for (var c : info.services) {
mapping.put(c.name, DummyService.class);
}
for (var c : info.providers) {
mapping.put(c.name, DummyProvider.class);
}
for (var c : info.receivers) {
mapping.put(c.name, DummyReceiver.class);
}
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class<?> clz = mapping.get(name);
return clz == null ? super.loadClass(name, resolve) : clz;
}
}
class DelegateClassLoader extends ClassLoader {
DelegateClassLoader() {
super();
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
return DynLoad.activeClassLoader.loadClass(name);
}
}
@@ -1,78 +0,0 @@
package com.topjohnwu.magisk;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AppComponentFactory;
import android.app.Application;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentProvider;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import com.topjohnwu.magisk.dummy.DummyProvider;
import com.topjohnwu.magisk.dummy.DummyReceiver;
import com.topjohnwu.magisk.dummy.DummyService;
@SuppressLint("NewApi")
public class DelegateComponentFactory extends AppComponentFactory {
AppComponentFactory receiver;
public DelegateComponentFactory() {
DynLoad.componentFactory = this;
}
@Override
public ClassLoader instantiateClassLoader(ClassLoader cl, ApplicationInfo info) {
return new DelegateClassLoader();
}
@Override
public Application instantiateApplication(ClassLoader cl, String className) {
return new StubApplication();
}
@Override
public Activity instantiateActivity(ClassLoader cl, String className, Intent intent)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (receiver != null)
return receiver.instantiateActivity(DynLoad.activeClassLoader, className, intent);
return create(className, DownloadActivity.class);
}
@Override
public BroadcastReceiver instantiateReceiver(ClassLoader cl, String className, Intent intent)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (receiver != null)
return receiver.instantiateReceiver(DynLoad.activeClassLoader, className, intent);
return create(className, DummyReceiver.class);
}
@Override
public Service instantiateService(ClassLoader cl, String className, Intent intent)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (receiver != null)
return receiver.instantiateService(DynLoad.activeClassLoader, className, intent);
return create(className, DummyService.class);
}
@Override
public ContentProvider instantiateProvider(ClassLoader cl, String className)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (receiver != null)
return receiver.instantiateProvider(DynLoad.activeClassLoader, className);
return create(className, DummyProvider.class);
}
private <T> T create(String name, Class<T> fallback)
throws IllegalAccessException, InstantiationException {
try {
// noinspection unchecked
return (T) DynLoad.activeClassLoader.loadClass(name).newInstance();
} catch (ClassNotFoundException e) {
return fallback.newInstance();
}
}
}
@@ -7,65 +7,26 @@ import static android.R.string.yes;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.loader.ResourcesLoader;
import android.content.res.loader.ResourcesProvider;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.system.Os;
import android.system.OsConstants;
import android.util.Log;
import android.view.ContextThemeWrapper;
import com.topjohnwu.magisk.net.Networking;
import com.topjohnwu.magisk.net.Request;
import com.topjohnwu.magisk.utils.APKInstall;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.InflaterInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class DownloadActivity extends Activity {
private static final String APP_NAME = "Magisk";
private static final String RES_PKG_NAME = "com.topjohnwu.magisk";
private boolean dynLoad;
private int dling;
private int no_internet_msg;
private int upgrade_msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getTheme().applyStyle(android.R.style.Theme_DeviceDefault_Dialog_NoActionBar, true);
// Only download and dynamic load full APK if hidden
dynLoad = !getPackageName().equals(BuildConfig.APPLICATION_ID);
// Inject resources
try {
loadResources();
} catch (Exception e) {
error(e);
return;
}
ProviderInstaller.install(this);
if (Networking.checkNetworkStatus(this)) {
@@ -74,7 +35,7 @@ public class DownloadActivity extends Activity {
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(APP_NAME)
.setMessage(getString(no_internet_msg))
.setMessage(R.string.no_internet_msg)
.setNegativeButton(ok, (d, w) -> finish())
.show();
}
@@ -99,72 +60,26 @@ public class DownloadActivity extends Activity {
new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle(APP_NAME)
.setMessage(getString(upgrade_msg))
.setMessage(R.string.upgrade_msg)
.setPositiveButton(yes, (d, w) -> dlAPK())
.setNegativeButton(no, (d, w) -> finish())
.show();
}
private void dlAPK() {
ProgressDialog.show(this, getString(dling), getString(dling) + " " + APP_NAME, true);
// Download and upgrade the app
ProgressDialog.show(this, getString(R.string.dling), getString(R.string.dling) + " " + APP_NAME, true);
var request = request(BuildConfig.APK_URL).setExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
if (dynLoad) {
request.getAsFile(StubApk.current(this), file -> StubApk.restartProcess(this));
} else {
request.getAsInputStream(input -> {
var session = APKInstall.startSession(this);
try (input; var out = session.openStream(this)) {
if (out != null)
APKInstall.transfer(input, out);
} catch (IOException e) {
error(e);
}
Intent intent = session.waitIntent();
if (intent != null)
startActivity(intent);
});
}
}
private void decryptResources(OutputStream out) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKey key = new SecretKeySpec(Bytes.key(), "AES");
IvParameterSpec iv = new IvParameterSpec(Bytes.iv());
cipher.init(Cipher.DECRYPT_MODE, key, iv);
var is = new InflaterInputStream(new CipherInputStream(
new ByteArrayInputStream(Bytes.res()), cipher));
try (is; out) {
APKInstall.transfer(is, out);
}
}
private void loadResources() throws Exception {
var res = getResources();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
var fd = Os.memfd_create("res", 0);
try {
decryptResources(new FileOutputStream(fd));
Os.lseek(fd, 0, OsConstants.SEEK_SET);
var loader = new ResourcesLoader();
try (var pfd = ParcelFileDescriptor.dup(fd)) {
loader.addProvider(ResourcesProvider.loadFromTable(pfd, null));
res.addLoaders(loader);
}
} finally {
Os.close(fd);
request.getAsInputStream(input -> {
var session = APKInstall.startSession(this);
try (input; var out = session.openStream(this)) {
if (out != null)
APKInstall.transfer(input, out);
} catch (IOException e) {
error(e);
}
} else {
File apk = new File(getCodeCacheDir(), "res.apk");
try (var out = new ZipOutputStream(new FileOutputStream(apk))) {
// Directory support is broken on Android 9-10
out.putNextEntry(new ZipEntry("resources.arsc"));
decryptResources(out);
}
StubApk.addAssetPath(res, apk.getPath());
}
dling = res.getIdentifier("dling", "string", RES_PKG_NAME);
no_internet_msg = res.getIdentifier("no_internet_msg", "string", RES_PKG_NAME);
upgrade_msg = res.getIdentifier("upgrade_msg", "string", RES_PKG_NAME);
Intent intent = session.waitIntent();
if (intent != null)
startActivity(intent);
});
}
}
@@ -1,250 +0,0 @@
package com.topjohnwu.magisk;
import static com.topjohnwu.magisk.BuildConfig.APPLICATION_ID;
import android.app.AppComponentFactory;
import android.app.Application;
import android.app.job.JobService;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.util.Log;
import com.topjohnwu.magisk.utils.APKInstall;
import com.topjohnwu.magisk.utils.DynamicClassLoader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("ResultOfMethodCallIgnored")
public class DynLoad {
static Object componentFactory;
static ClassLoader activeClassLoader = DynLoad.class.getClassLoader();
static StubApk.Data createApkData() {
var data = new StubApk.Data();
data.setVersion(BuildConfig.STUB_VERSION);
data.setClassToComponent(new HashMap<>());
data.setRootService(StubRootService.class);
return data;
}
static void attachContext(Object o, Context context) {
if (!(o instanceof ContextWrapper))
return;
try {
Method m = ContextWrapper.class.getDeclaredMethod("attachBaseContext", Context.class);
m.setAccessible(true);
m.invoke(o, context);
} catch (Exception ignored) { /* Impossible */ }
}
// Dynamically load APK from internal, external storage, or previous app
static DynamicClassLoader loadApk(Context context) {
File apk = StubApk.current(context);
File update = StubApk.update(context);
if (update.exists()) {
// Rename from update
update.renameTo(apk);
}
// Copy from external for easier development
if (BuildConfig.DEBUG) {
try {
File external = new File(context.getExternalFilesDir(null), "magisk.apk");
if (external.exists()) {
apk.delete();
try {
var in = new FileInputStream(external);
var out = new FileOutputStream(apk);
apk.setReadOnly();
try (in; out) {
APKInstall.transfer(in, out);
}
} catch (IOException e) {
Log.e(DynLoad.class.getSimpleName(), "", e);
apk.delete();
} finally {
external.delete();
}
}
} catch (SecurityException e) {
// Do not crash in root service
}
}
if (apk.exists()) {
apk.setReadOnly();
return new DynamicClassLoader(apk);
}
// If no APK is loaded, attempt to copy from previous app
if (!context.getPackageName().equals(APPLICATION_ID)) {
try {
var info = context.getPackageManager().getApplicationInfo(APPLICATION_ID, 0);
apk.delete();
var src = new FileInputStream(info.sourceDir);
var out = new FileOutputStream(apk);
apk.setReadOnly();
try (src; out) {
APKInstall.transfer(src, out);
}
return new DynamicClassLoader(apk);
} catch (PackageManager.NameNotFoundException ignored) {
} catch (IOException e) {
Log.e(DynLoad.class.getSimpleName(), "", e);
apk.delete();
}
}
return null;
}
// Dynamically load APK and initialize the application
static void loadAndInitializeApp(Application context) {
// On API >= 29, AppComponentFactory will replace the ClassLoader for us
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q)
replaceClassLoader(context);
int flags = PackageManager.GET_ACTIVITIES | PackageManager.GET_SERVICES
| PackageManager.GET_PROVIDERS | PackageManager.GET_RECEIVERS
| PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DISABLED_COMPONENTS
| PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
var pm = context.getPackageManager();
final PackageInfo stubInfo;
try {
// noinspection WrongConstant
stubInfo = pm.getPackageInfo(context.getPackageName(), flags);
} catch (PackageManager.NameNotFoundException e) {
// Impossible
throw new RuntimeException(e);
}
File apk = StubApk.current(context);
final var cl = loadApk(context);
if (cl != null) try {
// noinspection WrongConstant
var apkInfo = pm.getPackageArchiveInfo(apk.getPath(), flags);
var mapping = generateMapping(stubInfo, apkInfo);
var data = createApkData();
var map = data.getClassToComponent();
// Create the inverse mapping (class to component name)
for (var e : mapping.entrySet()) {
map.put(e.getValue(), e.getKey());
}
var appInfo = apkInfo.applicationInfo;
// Create the receiver Application with proper constructor
var app = cl.loadClass(appInfo.className)
.getConstructor(Object.class)
.newInstance(data.getObject());
// Create the receiver component factory
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && componentFactory != null) {
var delegate = (DelegateComponentFactory) componentFactory;
if (appInfo.appComponentFactory == null) {
delegate.receiver = new AppComponentFactory();
} else {
Object factory = cl.loadClass(appInfo.appComponentFactory).newInstance();
delegate.receiver = (AppComponentFactory) factory;
}
}
activeClassLoader = new MappingClassLoader(cl, mapping);
// Call Application.attachBaseContext
attachContext(app, context);
} catch (Exception e) {
Log.e(DynLoad.class.getSimpleName(), "", e);
apk.delete();
} else {
// Dynamic loading failed, use normal stub classloader
activeClassLoader = new StubClassLoader(stubInfo);
}
}
// Replace LoadedApk mClassLoader
private static void replaceClassLoader(Context context) {
// Get ContextImpl
while (context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
}
try {
Field mInfo = context.getClass().getDeclaredField("mPackageInfo");
mInfo.setAccessible(true);
Object loadedApk = mInfo.get(context);
assert loadedApk != null;
Field mcl = loadedApk.getClass().getDeclaredField("mClassLoader");
mcl.setAccessible(true);
mcl.set(loadedApk, new DelegateClassLoader());
} catch (Exception e) {
// Actually impossible as this method is only called on API < 29,
// and API 24 - 28 do not restrict access to these fields.
Log.e(DynLoad.class.getSimpleName(), "", e);
}
}
private static Map<String, String> generateMapping(PackageInfo stub, PackageInfo app) {
var mapping = new HashMap<String, String>();
{
var src = stub.activities;
var dest = app.activities;
mapping.put(src[0].name, dest[0].name);
}
{
var src = stub.services;
var dest = app.services;
final ServiceInfo sa;
final ServiceInfo da;
final ServiceInfo sb;
final ServiceInfo db;
if (JobService.PERMISSION_BIND.equals(src[0].permission)) {
sa = src[0];
sb = src[1];
} else {
sa = src[1];
sb = src[0];
}
if (JobService.PERMISSION_BIND.equals(dest[0].permission)) {
da = dest[0];
db = dest[1];
} else {
da = dest[1];
db = dest[0];
}
mapping.put(sa.name, da.name);
mapping.put(sb.name, db.name);
}
{
var src = stub.receivers;
var dest = app.receivers;
mapping.put(src[0].name, dest[0].name);
}
{
var src = stub.providers;
var dest = app.providers;
mapping.put(src[0].name, dest[0].name);
}
return mapping;
}
}
@@ -1,12 +0,0 @@
package com.topjohnwu.magisk;
import android.app.Application;
import android.content.Context;
public class StubApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
DynLoad.loadAndInitializeApp(this);
}
}
@@ -1,43 +0,0 @@
package com.topjohnwu.magisk;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import java.io.File;
import java.lang.reflect.Constructor;
public class StubRootService extends ContextWrapper {
public StubRootService() {
super(null);
}
@Override
protected void attachBaseContext(Context base) {
ClassLoader loader = DynLoad.loadApk(base);
if (loader == null)
return;
try {
// Create application to get the real root service class
var data = DynLoad.createApkData();
File apk = StubApk.current(base);
PackageManager pm = base.getPackageManager();
PackageInfo pkgInfo = pm.getPackageArchiveInfo(apk.getPath(), 0);
loader.loadClass(pkgInfo.applicationInfo.className)
.getConstructor(Object.class)
.newInstance(data.getObject());
// Create the actual RootService and call its attachBaseContext
Constructor<?> ctor = data.getRootService().getConstructor(Object.class);
ctor.setAccessible(true);
Object service = ctor.newInstance(this);
DynLoad.attachContext(service, base);
} catch (Exception e) {
Log.e(StubRootService.class.getSimpleName(), "", e);
}
}
}
@@ -1,38 +0,0 @@
package com.topjohnwu.magisk.dummy;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
public class DummyProvider extends ContentProvider {
@Override
public boolean onCreate() {
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
}
@@ -1,10 +0,0 @@
package com.topjohnwu.magisk.dummy;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class DummyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {}
}
@@ -1,12 +0,0 @@
package com.topjohnwu.magisk.dummy;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class DummyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
}