Support loading Magisk Manager from stub on 9.0+

In the effort of preventing apps from crawling APK contents across the
whole installed app list to detect Magisk Manager, the solution here
is to NOT install the actual APK into the system, but instead
dynamically load the full app at runtime by a stub app. The full APK
will be stored in the application's private internal data where
non-root processes cannot read or scan.

The basis of this implementation is the class "AppComponentFactory"
that is introduced in API 28. If assigned, the system framework will
delegate app component instantiation to our custom implementation,
which allows us to do all sorts of crazy stuffs, in our case dynamically
load classes and create objects that does not exist in our APK.

There are a few challenges to achieve our goal though. First, Java
ClassLoaders follow the "delegation pattern", which means class loading
resolution will first be delegated to the parent loader before we get
a chance to do anything. This includes DexClassLoader, which is what
we will be using to load DEX files at runtime. This is a problem
because our stub app and full app share quite a lot of class names.
A custom ClassLoader, DynamicClassLoader, is created to overcome this
issue: it will always load classes in its current dex path before
delegating it to the parent.

Second, all app components (with the exception of runtime
BroadcastReceivers) are required to be declared in AndroidManifest.xml.
The full Magisk Manager has quite a lot of components (including
those from WorkManager and Room). The solution is to copy the complete
AndroidManifest.xml from the full app to the stub, and our
AppComponentFactory is responsible to construct the proper objects or
return dummy implementations in case the full APK isn't downloaded yet.

Third, other than classes, all resources required to run the full app
are also not bundled with the stub APK. We have to call an internal API
`AssetManager.addAssetPath(String)` to add our downloaded full APK into
AssetManager in order to access resources within our full app. That
internal API has existed forever, and is whitelisted from restricted
API access on modern Android versions, so it is pretty safe to use.

Fourth, on the subject of resources, some resources are not just being
used by our app at runtime. Resources such as the app icon, app label,
launch theme, basically everything referred in AndroidManifest.xml,
are used by the system to display the app properly. The system get these
resources via resource IDs and direct loading from the installed APK.
This subset of resources would have to be copied into the stub to make
the app work properly.

Fifth, resource IDs are used all over the place in XMLs and Java code.
The resource IDs in the stub and full app cannot missmatch, or
somewhere, either it be the system or AssetManager, will refer to the
incorrect resource. The full app will have to include all resources in
the stub, and all of them have to be assigned to the exact same IDs in
both APKs. To achieve this, we use AAPT2's "--emit-ids" option to dump
the resource ID mapping when building the stub, and "--stable-ids" when
building the full APK to make sure all overlapping resources in full
and stub are always assigned to the same ID.

Finally, both stub and full app have to work properly independently.
On 9.0+, the stub will have to first launch an Activity to download
the full APK before it can relaunch into the full app. On pre-9.0, the
stub should behave as it always did: download and prompt installation
to upgrade itself to full Magisk Manager. In the full app, the goal
is to introduce minimal intrusion to the code base to make sure this
whole thing is maintainable in the future. Fortunately, the solution
ends up pretty slick: all ContextWrappers in the app will be injected
with custom Contexts. The custom Contexts will return our patched
Resources object and the ClassLoader that loads itself, which will be
DynamicClassLoader in the case of running as a delegate app.
By directly patching the base Context of ContextWrappers (which covers
tons of app components) and in the Koin DI, the effect propagates deep
into every aspect of the code, making this change basically fully
transparent to almost every piece of code in full Magisk Manager.

After this commit, the stub app is able to properly download and launch
the full app, with most basic functionalities working just fine.
Do not expect Magisk Manager upgrades and hiding (repackaging) to
work properly, and some other minor issues might pop up.
This feature is still in the early WIP stages.
This commit is contained in:
topjohnwu 2019-10-14 03:49:17 -04:00
parent b05b688267
commit 5ffb9eaa5b
98 changed files with 1194 additions and 492 deletions

View File

@ -33,7 +33,6 @@ Furthermore, Magisk provides a **Systemless Interface** to alter the system (or
Default string resources for Magisk Manager are scattered throughout Default string resources for Magisk Manager are scattered throughout
- `app/src/main/res/values/strings.xml` - `app/src/main/res/values/strings.xml`
- `stub/src/main/res/values/strings.xml`
- `shared/src/main/res/values/strings.xml` - `shared/src/main/res/values/strings.xml`
Translate each and place them in the respective locations (`<module>/src/main/res/values-<lang>/strings.xml`). Translate each and place them in the respective locations (`<module>/src/main/res/values-<lang>/strings.xml`).

View File

@ -1,4 +1,22 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!--
** Special Requirements **
This AndroidManifest.xml will be copied into the stub
APK to allow APK delegation. This is why these special
requirements exist.
* Class names *
Class names a.a, a.c, a.e should not be changed as they are used
externally. All other class names can be changed.
* Resource IDs *
All resource IDs referred in AndroidManifest.xml is required to be
included into the "shared" module to make the ID match with stub.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
package="com.topjohnwu.magisk"> package="com.topjohnwu.magisk">
@ -11,32 +29,37 @@
<application <application
android:name="a.e" android:name="a.e"
android:appComponentFactory="a.a"
android:allowBackup="true" android:allowBackup="true"
android:theme="@style/MagiskTheme"
android:usesCleartextTraffic="true" android:usesCleartextTraffic="true"
tools:ignore="UnusedAttribute,GoogleAppIndexingWarning"> tools:ignore="UnusedAttribute,GoogleAppIndexingWarning"
tools:replace="android:appComponentFactory">
<!-- Activities --> <!-- Splash -->
<activity
android:name="a.b"
android:configChanges="orientation|screenSize"
android:exported="true" />
<activity <activity
android:name="a.c" android:name="a.c"
android:configChanges="orientation|screenSize" android:configChanges="orientation|screenSize"
android:exported="true"
android:theme="@style/SplashTheme"> android:theme="@style/SplashTheme">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<!-- Main -->
<activity
android:name="a.b"
android:configChanges="orientation|screenSize"
android:exported="true" />
<!-- Flashing -->
<activity <activity
android:name="a.f" android:name="a.f"
android:configChanges="keyboardHidden|orientation|screenSize" android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="nosensor" android:screenOrientation="nosensor" />
android:theme="@style/MagiskTheme.Flashing" />
<!-- Superuser --> <!-- Superuser -->
@ -44,8 +67,7 @@
android:name="a.m" android:name="a.m"
android:directBootAware="true" android:directBootAware="true"
android:excludeFromRecents="true" android:excludeFromRecents="true"
android:exported="false" android:exported="false" />
android:theme="@style/MagiskTheme.SU" />
<!-- Receiver --> <!-- Receiver -->
@ -64,9 +86,10 @@
</intent-filter> </intent-filter>
</receiver> </receiver>
<!-- Service --> <!-- DownloadService -->
<service android:name="a.j" <service
android:name="a.j"
android:exported="false" /> android:exported="false" />
<!-- Hardcode GMS version --> <!-- Hardcode GMS version -->

View File

@ -1,13 +1,19 @@
package a; package a;
import androidx.annotation.Keep;
import androidx.core.app.AppComponentFactory;
import com.topjohnwu.magisk.utils.PatchAPK; import com.topjohnwu.magisk.utils.PatchAPK;
import com.topjohnwu.signing.BootSigner; import com.topjohnwu.signing.BootSigner;
import androidx.annotation.Keep;
@Keep @Keep
public class a extends BootSigner { public class a extends AppComponentFactory {
public static boolean patchAPK(String in, String out, String pkg) { public static boolean patchAPK(String in, String out, String pkg) {
return PatchAPK.patch(in, out, pkg); return PatchAPK.patch(in, out, pkg);
} }
public static void main(String[] args) throws Exception {
BootSigner.main(args);
}
} }

View File

@ -7,6 +7,7 @@ import androidx.work.Worker;
import androidx.work.WorkerParameters; import androidx.work.WorkerParameters;
import com.topjohnwu.magisk.base.DelegateWorker; import com.topjohnwu.magisk.base.DelegateWorker;
import com.topjohnwu.magisk.utils.ResourceMgrKt;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
@ -18,7 +19,7 @@ public abstract class w<T extends DelegateWorker> extends Worker {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
w(@NonNull Context context, @NonNull WorkerParameters workerParams) { w(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams); super(ResourceMgrKt.wrap(context, false), workerParams);
try { try {
base = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) base = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0]).newInstance(); .getActualTypeArguments()[0]).newInstance();

View File

@ -13,8 +13,11 @@ import com.topjohnwu.magisk.data.database.RepoDatabase_Impl
import com.topjohnwu.magisk.di.ActivityTracker import com.topjohnwu.magisk.di.ActivityTracker
import com.topjohnwu.magisk.di.koinModules import com.topjohnwu.magisk.di.koinModules
import com.topjohnwu.magisk.extensions.get import com.topjohnwu.magisk.extensions.get
import com.topjohnwu.magisk.utils.LocaleManager import com.topjohnwu.magisk.extensions.unwrap
import com.topjohnwu.magisk.utils.RootUtils import com.topjohnwu.magisk.utils.ResourceMgr
import com.topjohnwu.magisk.utils.RootInit
import com.topjohnwu.magisk.utils.isRunningAsStub
import com.topjohnwu.magisk.utils.wrap
import com.topjohnwu.superuser.Shell import com.topjohnwu.superuser.Shell
import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin import org.koin.core.context.startKoin
@ -26,7 +29,7 @@ open class App : Application() {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
Shell.Config.setFlags(Shell.FLAG_MOUNT_MASTER or Shell.FLAG_USE_MAGISK_BUSYBOX) Shell.Config.setFlags(Shell.FLAG_MOUNT_MASTER or Shell.FLAG_USE_MAGISK_BUSYBOX)
Shell.Config.verboseLogging(BuildConfig.DEBUG) Shell.Config.verboseLogging(BuildConfig.DEBUG)
Shell.Config.addInitializers(RootUtils::class.java) Shell.Config.addInitializers(RootInit::class.java)
Shell.Config.setTimeout(2) Shell.Config.setTimeout(2)
Room.setFactory { Room.setFactory {
when (it) { when (it) {
@ -38,22 +41,42 @@ open class App : Application() {
} }
override fun attachBaseContext(base: Context) { override fun attachBaseContext(base: Context) {
super.attachBaseContext(base) // Basic setup
if (BuildConfig.DEBUG) if (BuildConfig.DEBUG)
MultiDex.install(base) MultiDex.install(base)
Timber.plant(Timber.DebugTree()) Timber.plant(Timber.DebugTree())
// Some context magic
val app: Application
val impl: Context
if (base is Application) {
isRunningAsStub = true
app = base
impl = base.baseContext
} else {
app = this
impl = base
}
ResourceMgr.init(impl)
super.attachBaseContext(impl.wrap())
// Normal startup
startKoin { startKoin {
androidContext(this@App) androidContext(baseContext)
modules(koinModules) modules(koinModules)
} }
ResourceMgr.reload()
app.registerActivityLifecycleCallbacks(get<ActivityTracker>())
}
registerActivityLifecycleCallbacks(get<ActivityTracker>()) // This is required as some platforms expect ContextImpl
LocaleManager.setLocale(this) override fun getBaseContext(): Context {
return super.getBaseContext().unwrap()
} }
override fun onConfigurationChanged(newConfig: Configuration) { override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig) ResourceMgr.reload(newConfig)
LocaleManager.setLocale(this) if (!isRunningAsStub)
super.onConfigurationChanged(newConfig)
} }
} }

View File

@ -15,12 +15,13 @@ import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding import androidx.databinding.ViewDataBinding
import com.topjohnwu.magisk.BR import com.topjohnwu.magisk.BR
import com.topjohnwu.magisk.Config import com.topjohnwu.magisk.Config
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.base.viewmodel.BaseViewModel import com.topjohnwu.magisk.base.viewmodel.BaseViewModel
import com.topjohnwu.magisk.extensions.set import com.topjohnwu.magisk.extensions.set
import com.topjohnwu.magisk.model.events.EventHandler import com.topjohnwu.magisk.model.events.EventHandler
import com.topjohnwu.magisk.model.permissions.PermissionRequestBuilder import com.topjohnwu.magisk.model.permissions.PermissionRequestBuilder
import com.topjohnwu.magisk.utils.LocaleManager
import com.topjohnwu.magisk.utils.currentLocale import com.topjohnwu.magisk.utils.currentLocale
import com.topjohnwu.magisk.utils.wrap
import kotlin.random.Random import kotlin.random.Random
typealias RequestCallback = BaseActivity<*, *>.(Int, Intent?) -> Unit typealias RequestCallback = BaseActivity<*, *>.(Int, Intent?) -> Unit
@ -31,9 +32,8 @@ abstract class BaseActivity<ViewModel : BaseViewModel, Binding : ViewDataBinding
protected lateinit var binding: Binding protected lateinit var binding: Binding
protected abstract val layoutRes: Int protected abstract val layoutRes: Int
protected abstract val viewModel: ViewModel protected abstract val viewModel: ViewModel
protected open val themeRes: Int = R.style.MagiskTheme
protected open val snackbarView get() = binding.root protected open val snackbarView get() = binding.root
protected open val navHostId: Int = 0
protected open val defaultPosition: Int = 0
private val resultCallbacks by lazy { SparseArrayCompat<RequestCallback>() } private val resultCallbacks by lazy { SparseArrayCompat<RequestCallback>() }
@ -53,10 +53,11 @@ abstract class BaseActivity<ViewModel : BaseViewModel, Binding : ViewDataBinding
} }
override fun attachBaseContext(base: Context) { override fun attachBaseContext(base: Context) {
super.attachBaseContext(LocaleManager.getLocaleContext(base)) super.attachBaseContext(base.wrap(false))
} }
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
setTheme(themeRes)
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
viewModel.viewEvents.observe(this, viewEventObserver) viewModel.viewEvents.observe(this, viewEventObserver)

View File

@ -0,0 +1,17 @@
package com.topjohnwu.magisk.base
import android.content.BroadcastReceiver
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import com.topjohnwu.magisk.utils.wrap
import org.koin.core.KoinComponent
abstract class BaseReceiver : BroadcastReceiver(), KoinComponent {
final override fun onReceive(context: Context, intent: Intent?) {
onReceive(context.wrap() as ContextWrapper, intent)
}
abstract fun onReceive(context: ContextWrapper, intent: Intent?)
}

View File

@ -0,0 +1,12 @@
package com.topjohnwu.magisk.base
import android.app.Service
import android.content.Context
import com.topjohnwu.magisk.utils.wrap
import org.koin.core.KoinComponent
abstract class BaseService : Service(), KoinComponent {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base.wrap())
}
}

View File

@ -1,6 +1,8 @@
package com.topjohnwu.magisk.extensions package com.topjohnwu.magisk.extensions
import android.content.ComponentName
import android.content.Context import android.content.Context
import android.content.ContextWrapper
import android.content.Intent import android.content.Intent
import android.content.pm.ApplicationInfo import android.content.pm.ApplicationInfo
import android.content.pm.ComponentInfo import android.content.pm.ComponentInfo
@ -18,11 +20,13 @@ import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.net.toUri import androidx.core.net.toUri
import com.topjohnwu.magisk.utils.DynamicClassLoader
import com.topjohnwu.magisk.utils.FileProvider import com.topjohnwu.magisk.utils.FileProvider
import com.topjohnwu.magisk.utils.Utils import com.topjohnwu.magisk.utils.Utils
import com.topjohnwu.magisk.utils.currentLocale import com.topjohnwu.magisk.utils.currentLocale
import java.io.File import java.io.File
import java.io.FileNotFoundException import java.io.FileNotFoundException
import java.util.*
val packageName: String get() = get<Context>().packageName val packageName: String get() = get<Context>().packageName
@ -93,6 +97,105 @@ fun Context.readUri(uri: Uri) =
fun Intent.startActivity(context: Context) = context.startActivity(this) fun Intent.startActivity(context: Context) = context.startActivity(this)
fun Intent.toCommand(args: MutableList<String>) {
if (action != null) {
args.add("-a")
args.add(action!!)
}
if (component != null) {
args.add("-n")
args.add(component!!.flattenToString())
}
if (data != null) {
args.add("-d")
args.add(dataString!!)
}
if (categories != null) {
for (cat in categories) {
args.add("-c")
args.add(cat)
}
}
if (type != null) {
args.add("-t")
args.add(type!!)
}
val extras = extras
if (extras != null) {
loop@ for (key in extras.keySet()) {
val v = extras.get(key) ?: continue
var value: Any = v
val arg: String
when {
v is String -> arg = "--es"
v is Boolean -> arg = "--ez"
v is Int -> arg = "--ei"
v is Long -> arg = "--el"
v is Float -> arg = "--ef"
v is Uri -> arg = "--eu"
v is ComponentName -> {
arg = "--ecn"
value = v.flattenToString()
}
v is ArrayList<*> -> {
if (v.size <= 0)
/* Impossible to know the type due to type erasure */
continue@loop
arg = if (v[0] is Int)
"--eial"
else if (v[0] is Long)
"--elal"
else if (v[0] is Float)
"--efal"
else if (v[0] is String)
"--esal"
else
continue@loop /* Unsupported */
val sb = StringBuilder()
for (o in v) {
sb.append(o.toString().replace(",", "\\,"))
sb.append(',')
}
// Remove trailing comma
sb.deleteCharAt(sb.length - 1)
value = sb
}
v.javaClass.isArray -> {
arg = if (v is IntArray)
"--eia"
else if (v is LongArray)
"--ela"
else if (v is FloatArray)
"--efa"
else if (v is Array<*> && v.isArrayOf<String>())
"--esa"
else
continue@loop /* Unsupported */
val sb = StringBuilder()
val len = java.lang.reflect.Array.getLength(v)
for (i in 0 until len) {
sb.append(java.lang.reflect.Array.get(v, i)!!.toString().replace(",", "\\,"))
sb.append(',')
}
// Remove trailing comma
sb.deleteCharAt(sb.length - 1)
value = sb
}
else -> continue@loop
} /* Unsupported */
args.add(arg)
args.add(key)
args.add(value.toString())
}
}
args.add("-f")
args.add(flags.toString())
}
fun File.provide(context: Context = get()): Uri { fun File.provide(context: Context = get()): Uri {
return FileProvider.getUriForFile(context, context.packageName + ".provider", this) return FileProvider.getUriForFile(context, context.packageName + ".provider", this)
} }
@ -157,3 +260,18 @@ fun Context.startEndToLeftRight(start: Int, end: Int): Pair<Int, Int> {
} }
fun Context.openUrl(url: String) = Utils.openLink(this, url.toUri()) fun Context.openUrl(url: String) = Utils.openLink(this, url.toUri())
@Suppress("FunctionName")
inline fun <reified T> T.DynamicClassLoader(apk: File)
= DynamicClassLoader(apk, T::class.java.classLoader)
fun Context.unwrap() : Context {
var context = this
while (true) {
if (context is ContextWrapper)
context = context.baseContext
else
break
}
return context
}

View File

@ -5,13 +5,13 @@ import com.topjohnwu.magisk.BuildConfig
import com.topjohnwu.magisk.ClassMap import com.topjohnwu.magisk.ClassMap
import com.topjohnwu.magisk.Config import com.topjohnwu.magisk.Config
import com.topjohnwu.magisk.R import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.extensions.DynamicClassLoader
import com.topjohnwu.magisk.model.entity.internal.Configuration.APK.Restore import com.topjohnwu.magisk.model.entity.internal.Configuration.APK.Restore
import com.topjohnwu.magisk.model.entity.internal.Configuration.APK.Upgrade import com.topjohnwu.magisk.model.entity.internal.Configuration.APK.Upgrade
import com.topjohnwu.magisk.model.entity.internal.DownloadSubject import com.topjohnwu.magisk.model.entity.internal.DownloadSubject
import com.topjohnwu.magisk.ui.SplashActivity import com.topjohnwu.magisk.ui.SplashActivity
import com.topjohnwu.magisk.utils.DynamicClassLoader
import com.topjohnwu.magisk.utils.PatchAPK import com.topjohnwu.magisk.utils.PatchAPK
import com.topjohnwu.magisk.utils.RootUtils import com.topjohnwu.magisk.utils.Utils
import com.topjohnwu.superuser.Shell import com.topjohnwu.superuser.Shell
import timber.log.Timber import timber.log.Timber
import java.io.File import java.io.File
@ -54,7 +54,7 @@ private fun RemoteFileService.restore(apk: File, id: Int) {
if (Shell.su("pm install $apk").exec().isSuccess) { if (Shell.su("pm install $apk").exec().isSuccess) {
val component = ComponentName(BuildConfig.APPLICATION_ID, val component = ComponentName(BuildConfig.APPLICATION_ID,
ClassMap.get<Class<*>>(SplashActivity::class.java).name) ClassMap.get<Class<*>>(SplashActivity::class.java).name)
RootUtils.rmAndLaunch(packageName, component) Utils.rmAndLaunch(packageName, component)
} }
} }

View File

@ -1,16 +1,16 @@
package com.topjohnwu.magisk.model.download package com.topjohnwu.magisk.model.download
import android.app.Notification import android.app.Notification
import android.app.Service
import android.content.Intent import android.content.Intent
import android.os.IBinder import android.os.IBinder
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat
import com.topjohnwu.magisk.base.BaseService
import org.koin.core.KoinComponent import org.koin.core.KoinComponent
import java.util.* import java.util.*
import kotlin.random.Random.Default.nextInt import kotlin.random.Random.Default.nextInt
abstract class NotificationService : Service(), KoinComponent { abstract class NotificationService : BaseService(), KoinComponent {
abstract val defaultNotification: NotificationCompat.Builder abstract val defaultNotification: NotificationCompat.Builder

View File

@ -1,15 +1,14 @@
package com.topjohnwu.magisk.model.receiver package com.topjohnwu.magisk.model.receiver
import android.content.BroadcastReceiver import android.content.ContextWrapper
import android.content.Context
import android.content.Intent import android.content.Intent
import com.topjohnwu.magisk.ClassMap import com.topjohnwu.magisk.ClassMap
import com.topjohnwu.magisk.Config import com.topjohnwu.magisk.Config
import com.topjohnwu.magisk.Const import com.topjohnwu.magisk.Const
import com.topjohnwu.magisk.Info import com.topjohnwu.magisk.Info
import com.topjohnwu.magisk.base.BaseReceiver
import com.topjohnwu.magisk.data.database.PolicyDao import com.topjohnwu.magisk.data.database.PolicyDao
import com.topjohnwu.magisk.data.database.base.su import com.topjohnwu.magisk.data.database.base.su
import com.topjohnwu.magisk.extensions.inject
import com.topjohnwu.magisk.extensions.reboot import com.topjohnwu.magisk.extensions.reboot
import com.topjohnwu.magisk.model.download.DownloadService import com.topjohnwu.magisk.model.download.DownloadService
import com.topjohnwu.magisk.model.entity.ManagerJson import com.topjohnwu.magisk.model.entity.ManagerJson
@ -20,8 +19,9 @@ import com.topjohnwu.magisk.utils.SuLogger
import com.topjohnwu.magisk.view.Notifications import com.topjohnwu.magisk.view.Notifications
import com.topjohnwu.magisk.view.Shortcuts import com.topjohnwu.magisk.view.Shortcuts
import com.topjohnwu.superuser.Shell import com.topjohnwu.superuser.Shell
import org.koin.core.inject
open class GeneralReceiver : BroadcastReceiver() { open class GeneralReceiver : BaseReceiver() {
private val policyDB: PolicyDao by inject() private val policyDB: PolicyDao by inject()
@ -36,7 +36,7 @@ open class GeneralReceiver : BroadcastReceiver() {
return intent.data?.encodedSchemeSpecificPart.orEmpty() return intent.data?.encodedSchemeSpecificPart.orEmpty()
} }
override fun onReceive(context: Context, intent: Intent?) { override fun onReceive(context: ContextWrapper, intent: Intent?) {
intent ?: return intent ?: return
when (intent.action ?: return) { when (intent.action ?: return) {
Intent.ACTION_REBOOT, Intent.ACTION_BOOT_COMPLETED -> { Intent.ACTION_REBOOT, Intent.ACTION_BOOT_COMPLETED -> {

View File

@ -40,8 +40,8 @@ open class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>(), Na
override val layoutRes: Int = R.layout.activity_main override val layoutRes: Int = R.layout.activity_main
override val viewModel: MainViewModel by viewModel() override val viewModel: MainViewModel by viewModel()
override val navHostId: Int = R.id.main_nav_host private val navHostId: Int = R.id.main_nav_host
override val defaultPosition: Int = 0 private val defaultPosition: Int = 0
private val navigationController by lazy { private val navigationController by lazy {
FragNavController(supportFragmentManager, navHostId) FragNavController(supportFragmentManager, navHostId)

View File

@ -1,17 +1,23 @@
package com.topjohnwu.magisk.ui package com.topjohnwu.magisk.ui
import android.app.Activity
import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.text.TextUtils import android.text.TextUtils
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.topjohnwu.magisk.* import com.topjohnwu.magisk.*
import com.topjohnwu.magisk.utils.Utils import com.topjohnwu.magisk.utils.Utils
import com.topjohnwu.magisk.utils.wrap
import com.topjohnwu.magisk.view.Notifications import com.topjohnwu.magisk.view.Notifications
import com.topjohnwu.magisk.view.Shortcuts import com.topjohnwu.magisk.view.Shortcuts
import com.topjohnwu.superuser.Shell import com.topjohnwu.superuser.Shell
open class SplashActivity : AppCompatActivity() { open class SplashActivity : Activity() {
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base.wrap())
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)

View File

@ -23,6 +23,7 @@ import java.io.File
open class FlashActivity : BaseActivity<FlashViewModel, ActivityFlashBinding>() { open class FlashActivity : BaseActivity<FlashViewModel, ActivityFlashBinding>() {
override val layoutRes: Int = R.layout.activity_flash override val layoutRes: Int = R.layout.activity_flash
override val themeRes: Int = R.style.MagiskTheme_Flashing
override val viewModel: FlashViewModel by viewModel { override val viewModel: FlashViewModel by viewModel {
val uri = intent.data ?: let { finish(); Uri.EMPTY } val uri = intent.data ?: let { finish(); Uri.EMPTY }
val additionalUri = intent.getParcelableExtra(Const.Key.FLASH_DATA) ?: uri val additionalUri = intent.getParcelableExtra(Const.Key.FLASH_DATA) ?: uri

View File

@ -9,11 +9,11 @@ import com.topjohnwu.magisk.base.BaseActivity
import com.topjohnwu.magisk.base.BaseFragment import com.topjohnwu.magisk.base.BaseFragment
import com.topjohnwu.magisk.data.repository.MagiskRepository import com.topjohnwu.magisk.data.repository.MagiskRepository
import com.topjohnwu.magisk.databinding.FragmentMagiskBinding import com.topjohnwu.magisk.databinding.FragmentMagiskBinding
import com.topjohnwu.magisk.extensions.DynamicClassLoader
import com.topjohnwu.magisk.extensions.openUrl import com.topjohnwu.magisk.extensions.openUrl
import com.topjohnwu.magisk.extensions.subscribeK import com.topjohnwu.magisk.extensions.subscribeK
import com.topjohnwu.magisk.extensions.writeTo import com.topjohnwu.magisk.extensions.writeTo
import com.topjohnwu.magisk.model.events.* import com.topjohnwu.magisk.model.events.*
import com.topjohnwu.magisk.utils.DynamicClassLoader
import com.topjohnwu.magisk.utils.SafetyNetHelper import com.topjohnwu.magisk.utils.SafetyNetHelper
import com.topjohnwu.magisk.view.MarkDownWindow import com.topjohnwu.magisk.view.MarkDownWindow
import com.topjohnwu.magisk.view.dialogs.* import com.topjohnwu.magisk.view.dialogs.*

View File

@ -201,7 +201,7 @@ class SettingsFragment : BasePreferenceFragment() {
Shell.su("magiskhide --disable").submit() Shell.su("magiskhide --disable").submit()
} }
Config.Key.LOCALE -> { Config.Key.LOCALE -> {
LocaleManager.setLocale(activity.application) ResourceMgr.reload()
activity.recreate() activity.recreate()
} }
Config.Key.CHECK_UPDATES -> Utils.scheduleUpdateCheck(activity) Config.Key.CHECK_UPDATES -> Utils.scheduleUpdateCheck(activity)
@ -230,7 +230,7 @@ class SettingsFragment : BasePreferenceFragment() {
val values = mutableListOf<String>() val values = mutableListOf<String>()
names.add( names.add(
LocaleManager.getString(defaultLocale, R.string.system_default) ResourceMgr.getString(defaultLocale, R.string.system_default)
) )
values.add("") values.add("")

View File

@ -18,6 +18,7 @@ import org.koin.androidx.viewmodel.ext.android.viewModel
open class SuRequestActivity : BaseActivity<SuRequestViewModel, ActivityRequestBinding>() { open class SuRequestActivity : BaseActivity<SuRequestViewModel, ActivityRequestBinding>() {
override val layoutRes: Int = R.layout.activity_request override val layoutRes: Int = R.layout.activity_request
override val themeRes: Int = R.style.MagiskTheme_SU
override val viewModel: SuRequestViewModel by viewModel() override val viewModel: SuRequestViewModel by viewModel()
override fun onBackPressed() { override fun onBackPressed() {

View File

@ -1,61 +0,0 @@
package com.topjohnwu.magisk.utils
import dalvik.system.DexClassLoader
import java.io.File
import java.io.IOException
import java.net.URL
import java.util.*
@Suppress("FunctionName")
inline fun <reified T> T.DynamicClassLoader(apk: File) = DynamicClassLoader(apk, T::class.java.classLoader)
class DynamicClassLoader(apk: File, parent: ClassLoader?)
: DexClassLoader(apk.path, apk.parent, null, parent) {
private val base by lazy { Any::class.java.classLoader!! }
@Throws(ClassNotFoundException::class)
override fun loadClass(name: String, resolve: Boolean) : Class<*>
= findLoadedClass(name) ?: runCatching {
base.loadClass(name)
}.getOrElse {
runCatching {
findClass(name)
}.getOrElse { err ->
runCatching {
parent.loadClass(name)
}.getOrElse { throw err }
}
}
override fun getResource(name: String) = base.getResource(name)
?: findResource(name)
?: parent?.getResource(name)
@Throws(IOException::class)
override fun getResources(name: String): Enumeration<URL> {
val resources = mutableListOf(
base.getResources(name),
findResources(name), parent.getResources(name))
return object : Enumeration<URL> {
override fun hasMoreElements(): Boolean {
while (true) {
if (resources.isEmpty())
return false
if (!resources[0].hasMoreElements()) {
resources.removeAt(0)
} else {
return true
}
}
}
override fun nextElement(): URL {
if (!hasMoreElements())
throw NoSuchElementException()
return resources[0].nextElement()
}
}
}
}

View File

@ -1,68 +0,0 @@
package com.topjohnwu.magisk.utils
import android.content.Context
import android.content.ContextWrapper
import android.content.res.Configuration
import android.content.res.Resources
import androidx.annotation.StringRes
import com.topjohnwu.magisk.Config
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.extensions.get
import com.topjohnwu.magisk.extensions.inject
import com.topjohnwu.magisk.extensions.langTagToLocale
import com.topjohnwu.superuser.internal.InternalUtils
import io.reactivex.Single
import java.util.*
var currentLocale = Locale.getDefault()!!
private set
val defaultLocale = Locale.getDefault()!!
val availableLocales = Single.fromCallable {
val compareId = R.string.app_changelog
val res: Resources by inject()
mutableListOf<Locale>().apply {
// Add default locale
add(Locale.ENGLISH)
// Add some special locales
add(Locale.TAIWAN)
add(Locale("pt", "BR"))
// Other locales
val otherLocales = res.assets.locales
.map { it.langTagToLocale() }
.distinctBy { LocaleManager.getString(it, compareId) }
listOf("", "").toTypedArray()
addAll(otherLocales)
}.sortedWith(Comparator { a, b ->
a.getDisplayName(a).toLowerCase(a)
.compareTo(b.getDisplayName(b).toLowerCase(b))
})
}.cache()!!
object LocaleManager {
fun setLocale(wrapper: ContextWrapper) {
val localeConfig = Config.locale
currentLocale = when {
localeConfig.isEmpty() -> defaultLocale
else -> localeConfig.langTagToLocale()
}
Locale.setDefault(currentLocale)
InternalUtils.replaceBaseContext(wrapper, getLocaleContext(wrapper, currentLocale))
}
fun getLocaleContext(context: Context, locale: Locale = currentLocale): Context {
val config = Configuration(context.resources.configuration)
config.setLocale(locale)
return context.createConfigurationContext(config)
}
fun getString(locale: Locale, @StringRes id: Int): String {
return getLocaleContext(get(), locale).getString(id)
}
}

View File

@ -102,7 +102,7 @@ object PatchAPK {
Config.suManager = pkg Config.suManager = pkg
Config.export() Config.export()
RootUtils.rmAndLaunch(BuildConfig.APPLICATION_ID, Utils.rmAndLaunch(BuildConfig.APPLICATION_ID,
ComponentName(pkg, ClassMap.get<Class<*>>(SplashActivity::class.java).name)) ComponentName(pkg, ClassMap.get<Class<*>>(SplashActivity::class.java).name))
return true return true

View File

@ -0,0 +1,126 @@
@file:Suppress("DEPRECATION")
package com.topjohnwu.magisk.utils
import android.annotation.SuppressLint
import android.content.Context
import android.content.ContextWrapper
import android.content.res.AssetManager
import android.content.res.Configuration
import android.content.res.Resources
import androidx.annotation.StringRes
import com.topjohnwu.magisk.Config
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.extensions.langTagToLocale
import io.reactivex.Single
import java.util.*
var isRunningAsStub = false
var currentLocale: Locale = Locale.getDefault()
private set
@SuppressLint("ConstantLocale")
val defaultLocale: Locale = Locale.getDefault()
val availableLocales = Single.fromCallable {
val compareId = R.string.app_changelog
mutableListOf<Locale>().apply {
// Add default locale
add(Locale.ENGLISH)
// Add some special locales
add(Locale.TAIWAN)
add(Locale("pt", "BR"))
val config = Configuration()
val metrics = ResourceMgr.resource.displayMetrics
val res = Resources(ResourceMgr.resource.assets, metrics, config)
// Other locales
val otherLocales = ResourceMgr.resource.assets.locales
.map { it.langTagToLocale() }
.distinctBy {
config.setLocale(it)
res.updateConfiguration(config, metrics)
res.getString(compareId)
}
listOf("", "").toTypedArray()
addAll(otherLocales)
}.sortedWith(Comparator { a, b ->
a.getDisplayName(a).toLowerCase(a)
.compareTo(b.getDisplayName(b).toLowerCase(b))
})
}.cache()!!
private val addAssetPath by lazy {
AssetManager::class.java.getMethod("addAssetPath", String::class.java)
}
fun AssetManager.addAssetPath(path: String) {
addAssetPath.invoke(this, path)
}
fun Context.wrap(global: Boolean = true): Context
= if (!global) ResourceMgr.ResContext(this) else ResourceMgr.GlobalResContext(this)
object ResourceMgr {
lateinit var resource: Resources
private lateinit var resApk: String
fun init(context: Context) {
resource = context.resources
if (isRunningAsStub)
resApk = DynAPK.current(context).path
}
// Override locale and inject resources from dynamic APK
private fun Resources.patch(config: Configuration = Configuration(configuration)): Resources {
config.setLocale(currentLocale)
updateConfiguration(config, displayMetrics)
if (isRunningAsStub)
assets.addAssetPath(resApk)
return this
}
fun reload(config: Configuration = Configuration(resource.configuration)) {
val localeConfig = Config.locale
currentLocale = when {
localeConfig.isEmpty() -> defaultLocale
else -> localeConfig.langTagToLocale()
}
Locale.setDefault(currentLocale)
resource.patch(config)
}
fun getString(locale: Locale, @StringRes id: Int): String {
val config = Configuration()
config.setLocale(locale)
return Resources(resource.assets, resource.displayMetrics, config).getString(id)
}
open class GlobalResContext(base: Context) : ContextWrapper(base) {
open val mRes: Resources get() = resource
private val loader by lazy { javaClass.classLoader!! }
override fun getResources(): Resources {
return mRes
}
override fun getClassLoader(): ClassLoader {
return loader
}
override fun createConfigurationContext(config: Configuration): Context {
return ResContext(super.createConfigurationContext(config))
}
}
class ResContext(base: Context) : GlobalResContext(base) {
override val mRes by lazy { base.resources.patch() }
}
}

View File

@ -0,0 +1,40 @@
package com.topjohnwu.magisk.utils
import android.content.Context
import com.topjohnwu.magisk.Const
import com.topjohnwu.magisk.Info
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.extensions.rawResource
import com.topjohnwu.superuser.Shell
import com.topjohnwu.superuser.ShellUtils
import com.topjohnwu.superuser.io.SuFile
class RootInit : Shell.Initializer() {
override fun onInit(context: Context, shell: Shell): Boolean {
return init(context.wrap(), shell)
}
fun init(context: Context, shell: Shell): Boolean {
val job = shell.newJob()
if (shell.isRoot) {
job.add(context.rawResource(R.raw.util_functions))
.add(context.rawResource(R.raw.utils))
Const.MAGISK_DISABLE_FILE = SuFile("/cache/.disable_magisk")
Info.loadMagiskInfo()
} else {
job.add(context.rawResource(R.raw.nonroot_utils))
}
job.add("mount_partitions",
"get_flags",
"run_migrations",
"export BOOTMODE=true")
.exec()
Info.keepVerity = ShellUtils.fastCmd("echo \$KEEPVERITY").toBoolean()
Info.keepEnc = ShellUtils.fastCmd("echo \$KEEPFORCEENCRYPT").toBoolean()
Info.recovery = ShellUtils.fastCmd("echo \$RECOVERYMODE").toBoolean()
return true
}
}

View File

@ -1,158 +0,0 @@
package com.topjohnwu.magisk.utils
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.topjohnwu.magisk.Const
import com.topjohnwu.magisk.Info
import com.topjohnwu.magisk.R
import com.topjohnwu.magisk.extensions.rawResource
import com.topjohnwu.magisk.extensions.toShellCmd
import com.topjohnwu.superuser.Shell
import com.topjohnwu.superuser.ShellUtils
import com.topjohnwu.superuser.io.SuFile
import java.util.*
import java.lang.reflect.Array as RArray
fun Intent.toCommand(args: MutableList<String>) {
if (action != null) {
args.add("-a")
args.add(action!!)
}
if (component != null) {
args.add("-n")
args.add(component!!.flattenToString())
}
if (data != null) {
args.add("-d")
args.add(dataString!!)
}
if (categories != null) {
for (cat in categories) {
args.add("-c")
args.add(cat)
}
}
if (type != null) {
args.add("-t")
args.add(type!!)
}
val extras = extras
if (extras != null) {
loop@ for (key in extras.keySet()) {
val v = extras.get(key) ?: continue
var value: Any = v
val arg: String
when {
v is String -> arg = "--es"
v is Boolean -> arg = "--ez"
v is Int -> arg = "--ei"
v is Long -> arg = "--el"
v is Float -> arg = "--ef"
v is Uri -> arg = "--eu"
v is ComponentName -> {
arg = "--ecn"
value = v.flattenToString()
}
v is ArrayList<*> -> {
if (v.size <= 0)
/* Impossible to know the type due to type erasure */
continue@loop
arg = if (v[0] is Int)
"--eial"
else if (v[0] is Long)
"--elal"
else if (v[0] is Float)
"--efal"
else if (v[0] is String)
"--esal"
else
continue@loop /* Unsupported */
val sb = StringBuilder()
for (o in v) {
sb.append(o.toString().replace(",", "\\,"))
sb.append(',')
}
// Remove trailing comma
sb.deleteCharAt(sb.length - 1)
value = sb
}
v.javaClass.isArray -> {
arg = if (v is IntArray)
"--eia"
else if (v is LongArray)
"--ela"
else if (v is FloatArray)
"--efa"
else if (v is Array<*> && v.isArrayOf<String>())
"--esa"
else
continue@loop /* Unsupported */
val sb = StringBuilder()
val len = RArray.getLength(v)
for (i in 0 until len) {
sb.append(RArray.get(v, i)!!.toString().replace(",", "\\,"))
sb.append(',')
}
// Remove trailing comma
sb.deleteCharAt(sb.length - 1)
value = sb
}
else -> continue@loop
} /* Unsupported */
args.add(arg)
args.add(key)
args.add(value.toString())
}
}
args.add("-f")
args.add(flags.toString())
}
fun startActivity(intent: Intent) {
if (intent.component == null)
return
val args = ArrayList<String>()
args.add("am")
args.add("start")
intent.toCommand(args)
Shell.su(args.toShellCmd()).exec()
}
class RootUtils : Shell.Initializer() {
override fun onInit(context: Context, shell: Shell): Boolean {
val job = shell.newJob()
if (shell.isRoot) {
job.add(context.rawResource(R.raw.util_functions))
.add(context.rawResource(R.raw.utils))
Const.MAGISK_DISABLE_FILE = SuFile("/cache/.disable_magisk")
Info.loadMagiskInfo()
} else {
job.add(context.rawResource(R.raw.nonroot_utils))
}
job.add("mount_partitions",
"get_flags",
"run_migrations",
"export BOOTMODE=true")
.exec()
Info.keepVerity = ShellUtils.fastCmd("echo \$KEEPVERITY").toBoolean()
Info.keepEnc = ShellUtils.fastCmd("echo \$KEEPFORCEENCRYPT").toBoolean()
Info.recovery = ShellUtils.fastCmd("echo \$RECOVERYMODE").toBoolean()
return true
}
companion object {
fun rmAndLaunch(rm: String, component: ComponentName) {
Shell.su("(rm_launch $rm ${component.flattenToString()})").exec()
}
}
}

View File

@ -1,5 +1,6 @@
package com.topjohnwu.magisk.utils package com.topjohnwu.magisk.utils
import android.content.ComponentName
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.res.Resources import android.content.res.Resources
@ -72,4 +73,8 @@ object Utils {
if ((exists() && isDirectory) || mkdirs()) this else null if ((exists() && isDirectory) || mkdirs()) this else null
} }
fun rmAndLaunch(rm: String, component: ComponentName) {
Shell.su("(rm_launch $rm ${component.flattenToString()})").exec()
}
} }

View File

@ -1,9 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<style name="SplashTheme" parent="SplashThemeBase.V19"/>
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/ic_splash_activity</item>
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
</resources> </resources>

View File

@ -32,10 +32,6 @@
<color name="dark_secondary_text">#dedede</color> <color name="dark_secondary_text">#dedede</color>
<color name="su_request_background">#e0e0e0</color> <color name="su_request_background">#e0e0e0</color>
<!-- Flashing colors -->
<color name="ic_launcher_background">#00AF9C</color>
<!-- Card colors --> <!-- Card colors -->
<color name="card_background_color_dark">#ff424242</color> <color name="card_background_color_dark">#ff424242</color>
<color name="card_background_color_light">#ffffffff</color> <color name="card_background_color_light">#ffffffff</color>

View File

@ -60,8 +60,6 @@
<item name="cardBackgroundColor">@color/card_background_color_light</item> <item name="cardBackgroundColor">@color/card_background_color_light</item>
</style> </style>
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar"> <style name="SplashTheme" parent="SplashThemeBase"/>
<item name="android:windowBackground">@drawable/ic_splash_activity</item>
</style>
</resources> </resources>

View File

@ -38,7 +38,7 @@ subprojects {
maven { url "https://jitpack.io" } maven { url "https://jitpack.io" }
maven { url "http://oss.sonatype.org/content/repositories/snapshots" } maven { url "http://oss.sonatype.org/content/repositories/snapshots" }
} }
afterEvaluate { afterEvaluate { module ->
if (getPlugins().hasPlugin('com.android.library') || if (getPlugins().hasPlugin('com.android.library') ||
getPlugins().hasPlugin('com.android.application')) { getPlugins().hasPlugin('com.android.application')) {
android { android {
@ -58,7 +58,7 @@ subprojects {
} }
} }
if (it.name == 'app' || it.name == 'stub') { if (module.name == 'app' || module.name == 'stub') {
android { android {
signingConfigs { signingConfigs {
config { config {
@ -76,8 +76,6 @@ subprojects {
signingConfig signingConfigs.config signingConfig signingConfigs.config
} }
release { release {
minifyEnabled true
shrinkResources true
signingConfig signingConfigs.config signingConfig signingConfigs.config
} }
} }
@ -85,6 +83,16 @@ subprojects {
lintOptions { lintOptions {
disable 'MissingTranslation' disable 'MissingTranslation'
} }
aaptOptions {
// Preserve stub resource IDs
File publicTxt = rootProject.file('stub-public.txt')
if (publicTxt.exists()) {
additionalParameters "--stable-ids", "${publicTxt.absolutePath}"
} else if (module.name == 'stub') {
additionalParameters "--emit-ids", "${publicTxt.absolutePath}"
}
}
} }
} }
} }

View File

@ -10,6 +10,12 @@
android:installLocation="internalOnly" android:installLocation="internalOnly"
android:label="@string/app_name" android:label="@string/app_name"
android:supportsRtl="true"> android:supportsRtl="true">
<activity
android:name="a.r"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:process=":remote" />
<provider <provider
android:name="a.p" android:name="a.p"
android:authorities="${applicationId}.provider" android:authorities="${applicationId}.provider"

View File

@ -0,0 +1,6 @@
package a;
import com.topjohnwu.magisk.ProcessPhoenix;
public class r extends ProcessPhoenix {
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (C) 2014 Jake Wharton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.topjohnwu.magisk;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.Arrays;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
/**
* Modified from JakeWharton/ProcessPhoenix
*
* Process Phoenix facilitates restarting your application process. This should only be used for
* things like fundamental state changes in your debug builds (e.g., changing from staging to
* production).
* <p>
* Trigger process recreation by calling {@link #triggerRebirth} with a {@link Context} instance.
*/
public class ProcessPhoenix extends Activity {
private static final String KEY_RESTART_INTENTS = "phoenix_restart_intents";
/**
* Call to restart the application process using the {@linkplain Intent#CATEGORY_DEFAULT default}
* activity as an intent.
* <p>
* Behavior of the current process after invoking this method is undefined.
*/
public static void triggerRebirth(Context context) {
triggerRebirth(context, getRestartIntent(context));
}
/**
* Call to restart the application process using the specified intents.
* <p>
* Behavior of the current process after invoking this method is undefined.
*/
public static void triggerRebirth(Context context, Intent... nextIntents) {
Intent intent = new Intent(context, a.r.class);
intent.addFlags(FLAG_ACTIVITY_NEW_TASK); // In case we are called with non-Activity context.
intent.putParcelableArrayListExtra(KEY_RESTART_INTENTS, new ArrayList<>(Arrays.asList(nextIntents)));
context.startActivity(intent);
if (context instanceof Activity) {
((Activity) context).finish();
}
Runtime.getRuntime().exit(0);
}
private static Intent getRestartIntent(Context context) {
String packageName = context.getPackageName();
Intent defaultIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (defaultIntent != null) {
defaultIntent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);
return defaultIntent;
}
throw new IllegalStateException("Unable to determine default activity for "
+ packageName
+ ". Does an activity specify the DEFAULT category in its intent filter?");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Intent> intents = getIntent().getParcelableArrayListExtra(KEY_RESTART_INTENTS);
startActivities(intents.toArray(new Intent[0]));
finish();
Runtime.getRuntime().exit(0);
}
}

View File

@ -0,0 +1,35 @@
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();
}
}

View File

@ -0,0 +1,16 @@
package com.topjohnwu.magisk.utils;
import android.content.Context;
import java.io.File;
public class DynAPK {
private static File dynDir;
public static File current(Context context) {
if (dynDir == null)
dynDir = new File(context.getFilesDir().getParent(), "dyn");
return new File(dynDir, "current.apk");
}
}

View File

@ -0,0 +1,60 @@
package com.topjohnwu.magisk.utils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import dalvik.system.DexClassLoader;
public class DynamicClassLoader extends DexClassLoader {
private ClassLoader base = Object.class.getClassLoader();
public DynamicClassLoader(File apk, ClassLoader parent) {
super(apk.getPath(), apk.getParent(), 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 base.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 = base.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<>(base.getResources(name),
findResources(name), getParent().getResources(name));
}
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/ic_launcher_background" />
<item
android:width="250dp"
android:height="250dp"
android:gravity="center"
android:drawable="@drawable/ic_magisk" />
</layer-list>

View File

@ -1,12 +1,6 @@
<resources> <resources>
<!--Not translatable--> <string name="upgrade_msg">Qurmanı sonlandırmaq üçün full Magisk Manager`ə yüksəldin. Yüklənib qurulsun?</string>
<string name="app_name" translatable="false">Magisk Manager</string> <string name="no_internet_msg">Lütfən internetə qoşulun! Full Magisk Manager\'ə yüksəltmə lazımidir.</string>
<string name="re_app_name" translatable="false">Manager</string>
<string name="magisk" translatable="false">Magisk</string>
<string name="magiskhide" translatable="false">Magisk Hide</string>
<string name="empty" translatable="false"/>
<!--Used in both stub and full app-->
<string name="no_thanks">Yox, sağolun</string> <string name="no_thanks">Yox, sağolun</string>
<string name="yes">Bəli</string> <string name="yes">Bəli</string>
<string name="ok">OK</string> <string name="ok">OK</string>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Не, благодаря.</string> <string name="no_thanks">Не, благодаря.</string>
<string name="yes">Да</string> <string name="yes">Да</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Надградете до пълната версия на Magisk Manager, за да довършите първоначалната настройка. Изтегляне и инсталиране сега?</string>
<string name="no_internet_msg">Моля да се свържете към работеща интернет мрежа, защото надграждането до пълната версия на Magisk Manager е задължително.</string>
</resources> </resources>

View File

@ -3,5 +3,7 @@
<string name="no_thanks">No, gràcies</string> <string name="no_thanks">No, gràcies</string>
<string name="yes"></string> <string name="yes"></string>
<string name="ok">Ok</string> <string name="ok">Ok</string>
<string name="upgrade_msg">Fes una actualització total de Magisk Manager per finalitzar l\'instalació. Descarregar i instalar?</string>
<string name="no_internet_msg">Si us plau, connecta\'t a internet! Es necessari fer una actualització total de Magisk Manager.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Nein danke</string> <string name="no_thanks">Nein danke</string>
<string name="yes">Ja</string> <string name="yes">Ja</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Upgrade zum vollständigen Magisk Manager, um das Setup abzuschließen. Herunterladen und installieren?</string>
<string name="no_internet_msg">Bitte eine Verbindung mit dem Internet herstellen! Upgrade zum vollständigen Magisk Manager ist erforderlich.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">No gracias</string> <string name="no_thanks">No gracias</string>
<string name="yes"></string> <string name="yes"></string>
<string name="ok">Aceptar</string> <string name="ok">Aceptar</string>
<string name="upgrade_msg">Actualizar a la Ver. Completa de Magisk Manager para finalizar la instalación. Descargar e instalar?</string>
<string name="no_internet_msg">¡Por favor conectarse a Internet! Se requiere actualizar a la Ver. Completa de Magisk Manager </string>
</resources> </resources>

View File

@ -3,4 +3,6 @@
<string name="no_thanks">Tänan ei</string> <string name="no_thanks">Tänan ei</string>
<string name="yes">Jah</string> <string name="yes">Jah</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Täienda seadistuse lõpetamiseks Magisk Manager\'i täisversioonile. Kas laadid alla ja installid?</string>
<string name="no_internet_msg">Palun ühendu Internetti! Nõutud on Magisk Manager\'i täisversioonile täiendamine.</string>
</resources> </resources>

View File

@ -4,4 +4,6 @@
<string name="no_thanks">Non merci</string> <string name="no_thanks">Non merci</string>
<string name="yes">Oui</string> <string name="yes">Oui</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Mettre à jour vers la version complête de Magisk Manager pour finir l\'installation. Télécharger et installer?</string>
<string name="no_internet_msg">Veuillez vous connecter à Internet! Une mise à niveau complête vers le Gestionnaire Magisk est requise.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Tidak, terima kasih</string> <string name="no_thanks">Tidak, terima kasih</string>
<string name="yes">Ya</string> <string name="yes">Ya</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Tingkatkan ke Magisk Manager versi penuh untuk menyelesaikan penyiapan. Unduh dan pasang?</string>
<string name="no_internet_msg">Harap menyambungkan ke Internet! Peningkatan ke Magisk Manager versi penuh diperlukan.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">No, grazie</string> <string name="no_thanks">No, grazie</string>
<string name="yes"></string> <string name="yes"></string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Aggiorna alla versione completa di Magisk Manager per completare l\'installazione. Vuoi procedere al download e all\'installazione?</string>
<string name="no_internet_msg">Controlla la connessione a Internet! È necessaria per l\'aggiornamento di Magisk Manager.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">아니오, 괜찮습니다</string> <string name="no_thanks">아니오, 괜찮습니다</string>
<string name="yes"></string> <string name="yes"></string>
<string name="ok">확인</string> <string name="ok">확인</string>
<string name="upgrade_msg">완전한 Magisk Manager로 업데이트하여 설치를 마치십시오. 다운로드하고 설치하시겠습니까?</string>
<string name="no_internet_msg">인터넷에 연결해 주시기 바랍니다! 완전한 Magisk Manager로 업데이트 해야 합니다.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Ačiū, nereikia</string> <string name="no_thanks">Ačiū, nereikia</string>
<string name="yes">Taip</string> <string name="yes">Taip</string>
<string name="ok">Gerai</string> <string name="ok">Gerai</string>
<string name="upgrade_msg">Atsinaujinkite į pilną Magisk Manager versiją, kad baigtumėte pasiruošimą. Atsisiųsti ir instaliuoti?</string>
<string name="no_internet_msg">Prašome prisijungti prie interneto! Atsinaujinimas į pilną Magisk Manager versiją yra privalomas.</string>
</resources> </resources>

View File

@ -1,13 +1,8 @@
<resources> <resources>
<!--Not translatable-->
<string name="app_name" translatable="false">Magisk Manager</string>
<string name="re_app_name" translatable="false">Manager</string>
<string name="magisk" translatable="false">Magisk</string>
<string name="magiskhide" translatable="false">Magisk Hide</string>
<string name="empty" translatable="false"/>
<!--Used in both stub and full app--> <!--Used in both stub and full app-->
<string name="no_thanks">Не, благодарам</string> <string name="no_thanks">Не, благодарам</string>
<string name="yes">Да</string> <string name="yes">Да</string>
<string name="ok">ОК</string> <string name="ok">ОК</string>
<string name="upgrade_msg">Надградете до целосната верзија на Magisk Manager за да го завршите поставувањето. Преземете и инсталирајте?</string>
<string name="no_internet_msg">Ве молиме поврзете се на интернет бидејќи е потребна надградба на целосната верзија на Magisk Manager.</string>
</resources> </resources>

View File

@ -4,4 +4,6 @@
<string name="no_thanks">Nei takk</string> <string name="no_thanks">Nei takk</string>
<string name="yes">Ja</string> <string name="yes">Ja</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Oppgrader til den komplette versjonen av Magisk Manager for å fullføre oppsettet. Vil du laste ned og installere?</string>
<string name="no_internet_msg">Vennligst koble deg på internettet! Å oppgradere til den komplette versjonen av Magisk Manager er påkrevd.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Nie dziękuję</string> <string name="no_thanks">Nie dziękuję</string>
<string name="yes">Tak</string> <string name="yes">Tak</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Przejdź na pełną wersję programu Magisk Manager, aby ukończyć konfigurację. Ściągnąć i zainstalować?</string>
<string name="no_internet_msg">Połącz się z Internetem! Wymagana jest aktualizacja do pełnego programu Magisk Manager.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Nu, mulțumesc</string> <string name="no_thanks">Nu, mulțumesc</string>
<string name="yes">Da</string> <string name="yes">Da</string>
<string name="ok">Ok</string> <string name="ok">Ok</string>
<string name="upgrade_msg">Treci la versiunea completă Magisk Manager pentru a finaliza configurarea. Descarci și instalezi?</string>
<string name="no_internet_msg">Te rugăm să te conectezi la internet! Este necesară actualizarea la versiunea completă Magisk Manager.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Нет</string> <string name="no_thanks">Нет</string>
<string name="yes">Да</string> <string name="yes">Да</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Обновите Magisk Manager для завершения установки. Загрузить и установить?</string>
<string name="no_internet_msg">Пожалуйста, подключитесь к интернету! Требуется обновление Magisk Manager.</string>
</resources> </resources>

View File

@ -3,4 +3,6 @@
<string name="no_thanks">Nie, ďakujem</string> <string name="no_thanks">Nie, ďakujem</string>
<string name="yes">Áno</string> <string name="yes">Áno</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Pre dokončenie inštalácie sa vyžaduje upgrade Magisk Managera. Stiahnuť a nainštalovať?</string>
<string name="no_internet_msg">Pripojte sa na internet! Upgrade Magisk Managera je potrebný.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Hayır, teşekkürler</string> <string name="no_thanks">Hayır, teşekkürler</string>
<string name="yes">Evet</string> <string name="yes">Evet</string>
<string name="ok">Tamam</string> <string name="ok">Tamam</string>
<string name="upgrade_msg">Kurulumu tamamlamak için tam Magisk Manager\'a yükseltin. İndirip yüklensin mi?</string>
<string name="no_internet_msg">Lütfen internete bağlanın! Tam Magisk Manager\'a yükseltmek gerekiyor.</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">Ні, дякую</string> <string name="no_thanks">Ні, дякую</string>
<string name="yes">Так</string> <string name="yes">Так</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Оновіть Magisk Manager для завершення встановлення. Завантажити і встановити?</string>
<string name="no_internet_msg">Будь ласка, підключіться до Інтернету! Потрібно оновити Magisk Manager.</string>
</resources> </resources>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="enable_system_alarm_service_default">false</bool>
<bool name="enable_system_job_service_default">true</bool>
</resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">不,谢谢</string> <string name="no_thanks">不,谢谢</string>
<string name="yes"></string> <string name="yes"></string>
<string name="ok"></string> <string name="ok"></string>
<string name="upgrade_msg">需要升级到完整的 Magisk Manager 来完成安装。 现在下载?</string>
<string name="no_internet_msg">请连接到互联网! 这是升级到完整 Magisk Manager 所必需的。</string>
</resources> </resources>

View File

@ -2,4 +2,6 @@
<string name="no_thanks">不,謝謝</string> <string name="no_thanks">不,謝謝</string>
<string name="yes"></string> <string name="yes"></string>
<string name="ok"></string> <string name="ok"></string>
<string name="upgrade_msg">需要升級到完整版 Magisk Manager。是否下載並安裝</string>
<string name="no_internet_msg">請連上網路!升級到完整版 Magisk Manager 是必須的。</string>
</resources> </resources>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#00AF9C</color>
</resources>

View File

@ -6,8 +6,9 @@
<string name="magiskhide" translatable="false">Magisk Hide</string> <string name="magiskhide" translatable="false">Magisk Hide</string>
<string name="empty" translatable="false"/> <string name="empty" translatable="false"/>
<!--Used in both stub and full app-->
<string name="no_thanks">No thanks</string> <string name="no_thanks">No thanks</string>
<string name="yes">Yes</string> <string name="yes">Yes</string>
<string name="ok">OK</string> <string name="ok">OK</string>
<string name="upgrade_msg">Upgrade to full Magisk Manager to finish the setup. Download and install?</string>
<string name="no_internet_msg">Please connect to the Internet! Upgrading to full Magisk Manager is required.</string>
</resources> </resources>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
<style name="SplashThemeBase" parent="android:Theme.DeviceDefault.NoActionBar">
<item name="android:windowBackground">@drawable/ic_splash_activity</item>
</style>
<style name="SplashThemeBase.V19" parent="SplashThemeBase">
<item name="android:windowTranslucentStatus" tools:targetApi="19">true</item>
<item name="android:windowTranslucentNavigation" tools:targetApi="19">true</item>
</style>
<style name="SplashTheme" parent="android:Theme.Translucent.NoTitleBar" />
</resources>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="enable_system_alarm_service_default">true</bool>
<bool name="enable_system_job_service_default">false</bool>
<bool name="workmanager_test_configuration">false</bool>
</resources>

View File

@ -9,7 +9,10 @@ android {
buildTypes { buildTypes {
release { release {
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' minifyEnabled true
shrinkResources false /* Do NOT allow resource shrinking */
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
'proguard-rules.pro'
} }
} }
} }

View File

@ -1,21 +1,182 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Try to recreate the main app's AndroidManifest.xml
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
package="com.topjohnwu.magisk"> package="com.topjohnwu.magisk">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application tools:ignore="GoogleAppIndexingWarning" <application
android:allowBackup="true"> android:name="a.e"
android:appComponentFactory="a.a"
android:allowBackup="true"
android:usesCleartextTraffic="true"
tools:ignore="UnusedAttribute,GoogleAppIndexingWarning" >
<!-- Download Activity -->
<activity <activity
android:name=".MainActivity" android:name="a.c"
android:theme="@android:style/Theme.Translucent.NoTitleBar"> android:configChanges="orientation|screenSize"
android:theme="@style/SplashTheme">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<!-- Magisk Manager Components -->
<activity
android:name="a.b"
android:configChanges="orientation|screenSize"
android:exported="true" />
<activity
android:name="a.f"
android:configChanges="keyboardHidden|orientation|screenSize"
android:screenOrientation="nosensor" />
<activity
android:name="a.m"
android:directBootAware="true"
android:excludeFromRecents="true"
android:exported="false" />
<receiver
android:name="a.h"
android:directBootAware="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCALE_CHANGED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<action android:name="android.intent.action.PACKAGE_FULLY_REMOVED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
<service
android:name="a.j"
android:exported="false" />
<meta-data
android:name="com.google.android.gms.version"
android:value="12451000" />
<!-- WorkManager -->
<provider
android:name="androidx.work.impl.WorkManagerInitializer"
android:authorities="${applicationId}.workmanager-init"
android:directBootAware="false"
android:exported="false"
android:multiprocess="true"
tools:targetApi="n" />
<service
android:name="androidx.work.impl.background.systemalarm.SystemAlarmService"
android:directBootAware="false"
android:enabled="@bool/enable_system_alarm_service_default"
android:exported="false"
tools:targetApi="n" />
<service
android:name="androidx.work.impl.background.systemjob.SystemJobService"
android:directBootAware="false"
android:enabled="@bool/enable_system_job_service_default"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE"
tools:targetApi="n" />
<receiver
android:name="androidx.work.impl.utils.ForceStopRunnable$BroadcastReceiver"
android:directBootAware="false"
android:enabled="true"
android:exported="false"
tools:targetApi="n" />
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxy$BatteryChargingProxy"
android:directBootAware="false"
android:enabled="false"
android:exported="false"
tools:targetApi="n" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxy$BatteryNotLowProxy"
android:directBootAware="false"
android:enabled="false"
android:exported="false"
tools:targetApi="n" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_OKAY" />
<action android:name="android.intent.action.BATTERY_LOW" />
</intent-filter>
</receiver>
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxy$StorageNotLowProxy"
android:directBootAware="false"
android:enabled="false"
android:exported="false"
tools:targetApi="n" >
<intent-filter>
<action android:name="android.intent.action.DEVICE_STORAGE_LOW" />
<action android:name="android.intent.action.DEVICE_STORAGE_OK" />
</intent-filter>
</receiver>
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxy$NetworkStateProxy"
android:directBootAware="false"
android:enabled="false"
android:exported="false"
tools:targetApi="n" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<receiver
android:name="androidx.work.impl.background.systemalarm.RescheduleReceiver"
android:directBootAware="false"
android:enabled="false"
android:exported="false"
tools:targetApi="n" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
</intent-filter>
</receiver>
<receiver
android:name="androidx.work.impl.background.systemalarm.ConstraintProxyUpdateReceiver"
android:directBootAware="false"
android:enabled="@bool/enable_system_alarm_service_default"
android:exported="false"
tools:targetApi="n" >
<intent-filter>
<action android:name="androidx.work.impl.background.systemalarm.UpdateProxies" />
</intent-filter>
</receiver>
<!-- Room -->
<service
android:name="androidx.room.MultiInstanceInvalidationService"
android:exported="false" />
</application> </application>
</manifest> </manifest>

View File

@ -0,0 +1,6 @@
package a;
import com.topjohnwu.magisk.DelegateComponentFactory;
public class a extends DelegateComponentFactory {
}

View File

@ -0,0 +1,6 @@
package a;
import com.topjohnwu.magisk.DownloadActivity;
public class c extends DownloadActivity {
}

View File

@ -0,0 +1,6 @@
package a;
import com.topjohnwu.magisk.DelegateApplication;
public class e extends DelegateApplication {
}

View File

@ -0,0 +1,12 @@
package androidx.work.impl;
import com.topjohnwu.magisk.dummy.DummyProvider;
public class WorkManagerInitializer extends DummyProvider {
/* This class have to exist, or else pre 9.0 devices
* will experience ClassNotFoundException crashes when
* launching the stub, as ContentProviders are constructed
* when an app starts up. Pre 9.0 devices do not have
* our custom DelegateComponentFactory to help creating
* dummies. */
}

View File

@ -0,0 +1,72 @@
package com.topjohnwu.magisk;
import android.app.AppComponentFactory;
import android.app.Application;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.os.Build;
import android.util.Log;
import com.topjohnwu.magisk.utils.DynAPK;
import com.topjohnwu.magisk.utils.DynamicClassLoader;
import java.io.File;
import java.lang.reflect.Method;
import static com.topjohnwu.magisk.DownloadActivity.TAG;
public class DelegateApplication extends Application {
static File MANAGER_APK;
private Object factory;
private Application delegate;
public DelegateApplication() {}
public DelegateApplication(Object o) {
factory = o;
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
if (Build.VERSION.SDK_INT >= 28) {
// If 9.0+, try to dynamically load the APK
DelegateComponentFactory factory = (DelegateComponentFactory) this.factory;
MANAGER_APK = DynAPK.current(this);
MANAGER_APK.getParentFile().mkdir();
if (MANAGER_APK.exists()) {
ClassLoader cl = new DynamicClassLoader(MANAGER_APK, factory.loader);
try {
// Create the delegate AppComponentFactory
Object df = cl.loadClass("a.a").newInstance();
// Create the delegate Application
delegate = (Application) cl.loadClass("a.e").newInstance();
// Call attachBaseContext without ContextImpl to show it is being wrapped
Method m = ContextWrapper.class.getDeclaredMethod("attachBaseContext", Context.class);
m.setAccessible(true);
m.invoke(delegate, this);
// If everything went well, set our loader and delegate
factory.delegate = (AppComponentFactory) df;
factory.loader = cl;
} catch (Exception e) {
Log.e(TAG, "dyn load", e);
MANAGER_APK.delete();
}
}
} else {
MANAGER_APK = new File(base.getCacheDir(), "manager.apk");
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
delegate.onConfigurationChanged(newConfig);
}
}

View File

@ -0,0 +1,72 @@
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 com.topjohnwu.magisk.dummy.DummyActivity;
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 {
ClassLoader loader;
AppComponentFactory delegate;
@Override
public Application instantiateApplication(ClassLoader cl, String className) {
loader = cl;
return new DelegateApplication(this);
}
@Override
public Activity instantiateActivity(ClassLoader cl, String className, Intent intent)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (delegate != null)
return delegate.instantiateActivity(loader, className, intent);
return create(className, DummyActivity.class);
}
@Override
public BroadcastReceiver instantiateReceiver(ClassLoader cl, String className, Intent intent)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (delegate != null)
return delegate.instantiateReceiver(loader, className, intent);
return create(className, DummyReceiver.class);
}
@Override
public Service instantiateService(ClassLoader cl, String className, Intent intent)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (delegate != null)
return delegate.instantiateService(loader, className, intent);
return create(className, DummyService.class);
}
@Override
public ContentProvider instantiateProvider(ClassLoader cl, String className)
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (delegate != null)
return delegate.instantiateProvider(loader, className);
return create(className, DummyProvider.class);
}
/**
* Create the class or dummy implementation if creation failed
*/
private <T> T create(String name, Class<? extends T> dummy)
throws InstantiationException, IllegalAccessException {
try {
return (T) loader.loadClass(name).newInstance();
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException ignored) {
return dummy.newInstance();
}
}
}

View File

@ -3,34 +3,55 @@ package com.topjohnwu.magisk;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.app.Application; import android.app.Application;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
import com.topjohnwu.magisk.utils.APKInstall; import com.topjohnwu.magisk.net.ErrorHandler;
import com.topjohnwu.magisk.net.Networking; import com.topjohnwu.magisk.net.Networking;
import com.topjohnwu.magisk.net.ResponseListener; import com.topjohnwu.magisk.net.ResponseListener;
import com.topjohnwu.magisk.utils.APKInstall;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.File; import static com.topjohnwu.magisk.DelegateApplication.MANAGER_APK;
public class MainActivity extends Activity { public class DownloadActivity extends Activity {
private static final String TAG = "MMStub"; static final String TAG = "MMStub";
private static final boolean IS_CANARY = BuildConfig.VERSION_NAME.contains("-"); private static final boolean IS_CANARY = BuildConfig.VERSION_NAME.contains("-");
private static final String URL = private static final String URL =
"https://raw.githubusercontent.com/topjohnwu/magisk_files/" + "https://raw.githubusercontent.com/topjohnwu/magisk_files/" +
(IS_CANARY ? "canary/release.json" : "master/stable.json"); (IS_CANARY ? "canary/release.json" : "master/stable.json");
private String apkLink; private String apkLink;
private ErrorHandler err = (conn, e) -> {
Log.e(TAG, "network error", e);
finish();
};
private void showDialog() {
ProgressDialog.show(this,
"Downloading...",
"Downloading Magisk Manager", true);
}
private void dlAPK() { private void dlAPK() {
Application app = getApplication(); showDialog();
Networking.get(apkLink) if (Build.VERSION.SDK_INT >= 28) {
.getAsFile(new File(getFilesDir(), "manager.apk"), // Download and relaunch the app
apk -> APKInstall.install(app, apk)); Networking.get(apkLink)
finish(); .setErrorHandler(err)
.getAsFile(MANAGER_APK, f -> ProcessPhoenix.triggerRebirth(this));
} else {
// Download and upgrade the app
Application app = getApplication();
Networking.get(apkLink)
.setErrorHandler(err)
.getAsFile(MANAGER_APK, apk -> APKInstall.install(app, apk));
}
} }
@Override @Override
@ -39,10 +60,7 @@ public class MainActivity extends Activity {
Networking.init(this); Networking.init(this);
if (Networking.checkNetworkStatus(this)) { if (Networking.checkNetworkStatus(this)) {
Networking.get(URL) Networking.get(URL)
.setErrorHandler(((conn, e) -> { .setErrorHandler(err)
Log.d(TAG, "network error", e);
finish();
}))
.getAsJSONObject(new JSONLoader()); .getAsJSONObject(new JSONLoader());
} else { } else {
new AlertDialog.Builder(this) new AlertDialog.Builder(this)
@ -61,7 +79,7 @@ public class MainActivity extends Activity {
try { try {
JSONObject manager = json.getJSONObject("app"); JSONObject manager = json.getJSONObject("app");
apkLink = manager.getString("link"); apkLink = manager.getString("link");
new AlertDialog.Builder(MainActivity.this) new AlertDialog.Builder(DownloadActivity.this)
.setCancelable(false) .setCancelable(false)
.setTitle(R.string.app_name) .setTitle(R.string.app_name)
.setMessage(R.string.upgrade_msg) .setMessage(R.string.upgrade_msg)

View File

@ -0,0 +1,13 @@
package com.topjohnwu.magisk.dummy;
import android.app.Activity;
import android.os.Bundle;
public class DummyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
}

View File

@ -0,0 +1,38 @@
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;
}
}

View File

@ -0,0 +1,10 @@
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) {}
}

View File

@ -0,0 +1,13 @@
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) {
stopSelf();
return null;
}
}

View File

@ -1,4 +0,0 @@
<resources>
<string name="upgrade_msg">Qurmanı sonlandırmaq üçün full Magisk Manager`ə yüksəldin. Yüklənib qurulsun?</string>
<string name="no_internet_msg">Lütfən internetə qoşulun! Full Magisk Manager\'ə yüksəltmə lazımidir.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Надградете до пълната версия на Magisk Manager, за да довършите първоначалната настройка. Изтегляне и инсталиране сега?</string>
<string name="no_internet_msg">Моля да се свържете към работеща интернет мрежа, защото надграждането до пълната версия на Magisk Manager е задължително.</string>
</resources>

View File

@ -1,4 +0,0 @@
<resources>
<string name="upgrade_msg">Fes una actualització total de Magisk Manager per finalitzar l\'instalació. Descarregar i instalar?</string>
<string name="no_internet_msg">Si us plau, connecta\'t a internet! Es necessari fer una actualització total de Magisk Manager.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Upgrade zum vollständigen Magisk Manager, um das Setup abzuschließen. Herunterladen und installieren?</string>
<string name="no_internet_msg">Bitte eine Verbindung mit dem Internet herstellen! Upgrade zum vollständigen Magisk Manager ist erforderlich.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Actualizar a la Ver. Completa de Magisk Manager para finalizar la instalación. Descargar e instalar?</string>
<string name="no_internet_msg">¡Por favor conectarse a Internet! Se requiere actualizar a la Ver. Completa de Magisk Manager </string>
</resources>

View File

@ -1,4 +0,0 @@
<resources>
<string name="upgrade_msg">Täienda seadistuse lõpetamiseks Magisk Manager\'i täisversioonile. Kas laadid alla ja installid?</string>
<string name="no_internet_msg">Palun ühendu Internetti! Nõutud on Magisk Manager\'i täisversioonile täiendamine.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Mettre à jour vers la version complête de Magisk Manager pour finir l\'installation. Télécharger et installer?</string>
<string name="no_internet_msg">Veuillez vous connecter à Internet! Une mise à niveau complête vers le Gestionnaire Magisk est requise.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Tingkatkan ke Magisk Manager versi penuh untuk menyelesaikan penyiapan. Unduh dan pasang?</string>
<string name="no_internet_msg">Harap menyambungkan ke Internet! Peningkatan ke Magisk Manager versi penuh diperlukan.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Aggiorna alla versione completa di Magisk Manager per completare l\'installazione. Vuoi procedere al download e all\'installazione?</string>
<string name="no_internet_msg">Controlla la connessione a Internet! È necessaria per l\'aggiornamento di Magisk Manager.</string>
</resources>

View File

@ -1,4 +0,0 @@
<resources>
<string name="upgrade_msg">완전한 Magisk Manager로 업데이트하여 설치를 마치십시오. 다운로드하고 설치하시겠습니까?</string>
<string name="no_internet_msg">인터넷에 연결해 주시기 바랍니다! 완전한 Magisk Manager로 업데이트 해야 합니다.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Atsinaujinkite į pilną Magisk Manager versiją, kad baigtumėte pasiruošimą. Atsisiųsti ir instaliuoti?</string>
<string name="no_internet_msg">Prašome prisijungti prie interneto! Atsinaujinimas į pilną Magisk Manager versiją yra privalomas.</string>
</resources>

View File

@ -1,4 +0,0 @@
<resources>
<string name="upgrade_msg">Надградете до целосната верзија на Magisk Manager за да го завршите поставувањето. Преземете и инсталирајте?</string>
<string name="no_internet_msg">Ве молиме поврзете се на интернет бидејќи е потребна надградба на целосната верзија на Magisk Manager.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Oppgrader til den komplette versjonen av Magisk Manager for å fullføre oppsettet. Vil du laste ned og installere?</string>
<string name="no_internet_msg">Vennligst koble deg på internettet! Å oppgradere til den komplette versjonen av Magisk Manager er påkrevd.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Przejdź na pełną wersję programu Magisk Manager, aby ukończyć konfigurację. Ściągnąć i zainstalować?</string>
<string name="no_internet_msg">Połącz się z Internetem! Wymagana jest aktualizacja do pełnego programu Magisk Manager.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Treci la versiunea completă Magisk Manager pentru a finaliza configurarea. Descarci și instalezi?</string>
<string name="no_internet_msg">Te rugăm să te conectezi la internet! Este necesară actualizarea la versiunea completă Magisk Manager.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Обновите Magisk Manager для завершения установки. Загрузить и установить?</string>
<string name="no_internet_msg">Пожалуйста, подключитесь к интернету! Требуется обновление Magisk Manager.</string>
</resources>

View File

@ -1,4 +0,0 @@
<resources>
<string name="upgrade_msg">Pre dokončenie inštalácie sa vyžaduje upgrade Magisk Managera. Stiahnuť a nainštalovať?</string>
<string name="no_internet_msg">Pripojte sa na internet! Upgrade Magisk Managera je potrebný.</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">Kurulumu tamamlamak için tam Magisk Manager\'a yükseltin. İndirip yüklensin mi?</string>
<string name="no_internet_msg">Lütfen internete bağlanın! Tam Magisk Manager\'a yükseltmek gerekiyor.</string>
</resources>

View File

@ -1,4 +0,0 @@
<resources>
<string name="upgrade_msg">Оновіть Magisk Manager для завершення встановлення. Завантажити і встановити?</string>
<string name="no_internet_msg">Будь ласка, підключіться до Інтернету! Потрібно оновити Magisk Manager.</string>
</resources>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="SplashTheme" parent="SplashThemeBase.V19" />
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">需要升级到完整的 Magisk Manager 来完成安装。 现在下载?</string>
<string name="no_internet_msg">请连接到互联网! 这是升级到完整 Magisk Manager 所必需的。</string>
</resources>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="upgrade_msg">需要升級到完整版 Magisk Manager。是否下載並安裝</string>
<string name="no_internet_msg">請連上網路!升級到完整版 Magisk Manager 是必須的。</string>
</resources>

View File

@ -1,4 +0,0 @@
<resources>
<string name="upgrade_msg">Upgrade to full Magisk Manager to finish the setup. Download and install?</string>
<string name="no_internet_msg">Please connect to the Internet! Upgrading to full Magisk Manager is required.</string>
</resources>