Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ sealed interface PatchTarget {
/** Every apk of the target, base first. */
val apkPaths: List<String>

/**
* The apks the package manager itself named, or nothing when they are not its.
*
* Only an installed app's paths say anything about what is installed: the other targets' paths are copies this
* manager made, which exist whatever the device has. Being the system's, they are what recognises an app
* installed in another user and not in this one, a state no query an ordinary app may make reports.
*/
val systemOwnedApks: List<String>
get() = (this as? InstalledApp)?.apkPaths.orEmpty()

/** An app already on the device, patched from its installed apks. */
data class InstalledApp(
override val packageName: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,8 @@ object PatchJobHost {
android.util.Log.INFO,
"Install: ${files.size} apk(s) via ${if (useShizuku) "Shizuku shell" else "platform installer"}",
)
if (!uninstallFirst && needsUninstall(pkg, files)) {
val recordedApks = request.target.systemOwnedApks
if (!uninstallFirst && needsUninstall(pkg, files, recordedApks)) {
// Worth recording even though it is not a failure: it is the moment the flow stops
// and waits, and a report that skips it looks like one that simply ended.
append(android.util.Log.WARN, "A differently-signed $pkg is installed; asking to uninstall first")
Expand All @@ -225,7 +226,7 @@ object PatchJobHost {
if (uninstallFirst) {
_step.value = PatchStep.Uninstalling(pkg)
append(android.util.Log.INFO, "Uninstalling $pkg")
val (status, message) = uninstall(pkg, useShizuku)
val (status, message) = uninstall(pkg, useShizuku, recordedApks)
append(statusLevel(status), "Uninstall: ${describe(status, message)}")
if (status != PackageInstaller.STATUS_SUCCESS) {
archive(pkg)
Expand Down Expand Up @@ -280,7 +281,10 @@ object PatchJobHost {
ConfigManager.clearScopeForApp(pkg)

_step.value = PatchStep.Uninstalling(pkg)
val (uninstallStatus, uninstallMessage) = uninstall(pkg, useShizuku)
// Read while the app is still here: restoring the original installs a differently signed
// build over it, so this path needs the same evidence a fresh patch does.
val recordedApks = LSPPackageManager.installedApkPaths(pkg).orEmpty()
val (uninstallStatus, uninstallMessage) = uninstall(pkg, useShizuku, recordedApks)
append(statusLevel(uninstallStatus), "Uninstall: ${describe(uninstallStatus, uninstallMessage)}")
if (uninstallStatus != PackageInstaller.STATUS_SUCCESS) {
throw java.io.IOException(uninstallMessage ?: "Uninstall failed")
Expand Down Expand Up @@ -351,9 +355,17 @@ object PatchJobHost {
// every non-LSPatch build clashes. A custom keystore that matches the installed app updates in
// place, and that case must not be sent to the uninstall prompt. Signers are readable without
// Shizuku, so the check is the same on either install path.
private fun needsUninstall(packageName: String, files: List<File>): Boolean =
files.firstOrNull()?.let { LSPPackageManager.signatureBlocksUpdate(packageName, it) } ?: false
private fun needsUninstall(packageName: String, files: List<File>, recordedApks: List<String>): Boolean =
files.firstOrNull()?.let { LSPPackageManager.signatureBlocksUpdate(packageName, it, recordedApks) } ?: false

private suspend fun uninstall(packageName: String, useShizuku: Boolean): Pair<Int, String?> =
if (useShizuku) LSPPackageManager.uninstall(packageName) else LSPPackageManager.uninstallBySystem(packageName)
private suspend fun uninstall(
packageName: String,
useShizuku: Boolean,
recordedApks: List<String>,
): Pair<Int, String?> =
if (useShizuku) {
LSPPackageManager.uninstall(packageName)
} else {
LSPPackageManager.uninstallBySystem(packageName, recordedApks)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1480,7 +1480,12 @@ private fun PatchBar(
PatchStep.Idle -> {
val needsUninstall =
remember(request.packageName, MyKeyStore.useDefault) {
LSPPackageManager.keystoreConflictsWith(request.packageName)
// The installed app's own apks, so the warning is right for an app
// installed in another user and not in this one, which no query shows.
LSPPackageManager.keystoreConflictsWith(
request.packageName,
request.target.systemOwnedApks,
)
}
Text(
text =
Expand Down
102 changes: 82 additions & 20 deletions manager/src/main/java/org/lsposed/lspatch/util/LSPPackageManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.parcelize.Parcelize
import org.lsposed.lspatch.R
import org.lsposed.lspatch.config.ConfigManager
import org.lsposed.lspatch.config.Configs
import org.lsposed.lspatch.config.MyKeyStore
Expand Down Expand Up @@ -87,6 +88,17 @@ object LSPPackageManager {
*/
private const val INSTALL_DISABLE_VERIFICATION = 0x00080000

/**
* Asks the package manager to install for every user rather than only the installer's own.
*
* Declared here because the hidden-api stubs do not carry it. It is what `pm install` sets for itself by default,
* and it is the other half of the all-users uninstall: an app that was present in several users is replaced by the
* patched build in all of them, instead of landing in the primary one and leaving the other users without the app
* they had -- and, for a secondary user, with no way to get it back short of patching again. Set only for the
* shell session, which holds the cross-user permission it needs; an app does not.
*/
private const val INSTALL_ALL_USERS = 0x00000040

private const val INSTALL_ACTION = "org.lsposed.lspatch.action.INSTALL_RESULT"

@Parcelize
Expand Down Expand Up @@ -510,6 +522,7 @@ object LSPPackageManager {
// report. Asking to skip it costs nothing and helps where the service allows it.
flags =
flags or
INSTALL_ALL_USERS or
PackageManagerHidden.INSTALL_ALLOW_TEST or
PackageManagerHidden.INSTALL_REPLACE_EXISTING or
INSTALL_DISABLE_VERIFICATION
Expand Down Expand Up @@ -738,7 +751,7 @@ object LSPPackageManager {
* Uninstalls [packageName] through the platform installer (OS confirmation UI). Used, without Shizuku, to clear a
* differently-signed original before a system install can replace it.
*/
suspend fun uninstallBySystem(packageName: String): Pair<Int, String?> {
suspend fun uninstallBySystem(packageName: String, recordedApks: List<String> = emptyList()): Pair<Int, String?> {
Log.i(TAG, "Perform system uninstall of $packageName")
val context = lspApp
var status = PackageInstaller.STATUS_FAILURE
Expand All @@ -757,6 +770,21 @@ object LSPPackageManager {
message = it.message + "\n" + it.stackTraceToString()
}
}
// The platform installer acts for the user that called it and has no flag for the others: an app
// this user shares with a secondary user or a work profile is still on record afterwards, keeping
// its certificate, and the install this uninstall was performed for would be refused with a bare
// INSTALL_FAILED_UPDATE_INCOMPATIBLE. Said here instead, where the reader can act on it. Asked only
// of an uninstall that reported success: on any other outcome there is nothing to add, and the apk
// read below would name a survivor for a package nothing has removed.
val leftOver =
status == PackageInstaller.STATUS_SUCCESS &&
(knownPackage(packageName, 0) != null || signersOfSurvivingApk(recordedApks) != null)
if (leftOver) {
status = PackageInstaller.STATUS_FAILURE
// Localised, unlike the platform's own status text above it: this one is the app speaking, and it
// is what the failure screen puts in front of the reader.
message = lspApp.getString(R.string.patch_uninstall_other_users, packageName)
}
Log.i(TAG, "System uninstall result: status=$status message=$message")
return Pair(status, message)
}
Expand All @@ -775,14 +803,26 @@ object LSPPackageManager {
* PackageManager (no Shizuku), so it is usable on the system-install fallback path.
*/
fun isInstalledWithoutPatch(packageName: String): Boolean {
return try {
val info = lspApp.packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA)
info.applicationInfo?.metaData?.containsKey("lspatch") != true
} catch (e: PackageManager.NameNotFoundException) {
false
}
val info = knownPackage(packageName, PackageManager.GET_META_DATA) ?: return false
return info.applicationInfo?.metaData?.containsKey("lspatch") != true
}

/**
* What the package manager will tell THIS user about [packageName], or null when it says nothing.
*
* [PackageManager.MATCH_UNINSTALLED_PACKAGES] covers one case the plain read does not: a package removed here
* with its data kept, whose certificate is still on record. It does NOT reach a package that is installed in
* another user and not in this one, for which it answers nothing.
* Seeing another user's install needs MATCH_ANY_USER and INTERACT_ACROSS_USERS, which an app does not hold, so
* that case is decided by [signersOfSurvivingApk] from the apk still on disk instead.
*/
private fun knownPackage(packageName: String, flags: Int): android.content.pm.PackageInfo? =
runCatching { lspApp.packageManager.getPackageInfo(packageName, flags) }.getOrNull()
?: runCatching {
lspApp.packageManager.getPackageInfo(packageName, flags or PackageManager.MATCH_UNINSTALLED_PACKAGES)
}
.getOrNull()

/**
* Whether an already-installed [packageName] would have to be uninstalled before [patchedApk] can replace it — i.e.
* Android would reject the update because the signing certificates differ.
Expand All @@ -795,23 +835,44 @@ object LSPPackageManager {
* on either side does it fall back to [isInstalledWithoutPatch], so an undetermined case still errs toward asking
* rather than firing an install Android will refuse.
*/
fun signatureBlocksUpdate(packageName: String, patchedApk: File): Boolean {
val installed = installedSigners(packageName) ?: return false
fun signatureBlocksUpdate(
packageName: String,
patchedApk: File,
recordedApks: List<String> = emptyList(),
): Boolean {
val installed =
installedSigners(packageName) ?: signersOfSurvivingApk(recordedApks) ?: return false
val patched = archiveSigners(patchedApk)
if (installed.isEmpty() || patched.isEmpty()) return isInstalledWithoutPatch(packageName)
return installed != patched
}

/** Current signers of an installed package; null when it is not installed, empty when unreadable. */
private fun installedSigners(packageName: String): Set<Signature>? {
val info =
try {
lspApp.packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES)
} catch (e: PackageManager.NameNotFoundException) {
return null
/**
* Signers read from a recorded apk of the package that is still on disk, or null when none is.
*
* The one piece of evidence an unprivileged app has about a package installed in another user and not in this
* one. These paths come from the package manager at a moment the app WAS visible here, they point into
* `/data/app`, and that directory is deleted when the last user's install goes -- so a file still there means
* the package is still installed somewhere, and its certificate is still what an install has to match. The apk
* itself is world-readable, as every installed apk is, so nothing is needed to read it.
*
* Only ever called with paths the system owns ([PatchTarget.InstalledApp]); an apk the manager extracted itself
* would exist regardless of what is installed and would prove nothing.
*/
private fun signersOfSurvivingApk(recordedApks: List<String>): Set<Signature>? =
recordedApks
.asSequence()
.map { File(it) }
.firstOrNull { it.isFile }
?.let { apk ->
archiveSigners(apk).takeIf { it.isNotEmpty() }?.also {
Log.i(TAG, "Read signers from ${apk.path}: still installed for another user")
}
}
return signersOf(info)
}

/** Signers on record for a package under any user; null when none is, empty when unreadable. */
private fun installedSigners(packageName: String): Set<Signature>? =
knownPackage(packageName, PackageManager.GET_SIGNING_CERTIFICATES)?.let { signersOf(it) }

/** Signers of an apk on disk; empty when the archive cannot be read. */
private fun archiveSigners(apk: File): Set<Signature> {
Expand All @@ -831,8 +892,9 @@ object LSPPackageManager {
* -- the same certificate the patched apk will carry -- so a custom keystore that matches the app is not
* mislabelled as a conflict. Falls back to [isInstalledWithoutPatch] only when a signature cannot be read.
*/
fun keystoreConflictsWith(packageName: String): Boolean {
val installed = installedSigners(packageName) ?: return false
fun keystoreConflictsWith(packageName: String, recordedApks: List<String> = emptyList()): Boolean {
val installed =
installedSigners(packageName) ?: signersOfSurvivingApk(recordedApks) ?: return false
val signer = selectedKeystoreSigner()
if (installed.isEmpty() || signer == null) return isInstalledWithoutPatch(packageName)
return installed != setOf(signer)
Expand Down
57 changes: 55 additions & 2 deletions manager/src/main/java/org/lsposed/lspatch/util/ShizukuApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -766,16 +766,69 @@ object ShizukuApi {
}
}

/** Uninstalls through the shell installer. Throws like the session above, and for the reason. */
/**
* Delete flag asking the package manager to remove a package for EVERY user, not only the caller's.
*
* Declared here because the hidden-api stubs do not carry it. It claims nothing the shell does not already hold:
* it is what `pm uninstall` sets for itself, which is why an uninstall over adb clears every user at once.
*/
private const val DELETE_ALL_USERS = 0x00000002

/**
* Uninstalls through the shell installer, for every user that has the package.
*
* All users rather than this one, because a package has one apk and one certificate device-wide while the
* installed bit is per user. An app left behind in a secondary user or a work profile therefore keeps its
* signature on record, and the next install of a differently signed build -- which is every patched build -- is
* refused with INSTALL_FAILED_UPDATE_INCOMPATIBLE. A single-user uninstall reports success, removes the app from
* view, and leaves the install it was performed for impossible.
*
* The flagged overload is hidden rather than absent, so it is called reflectively; a platform without it falls
* back to the single-user call, which clears it here only. Throws like the session above, and for the reason.
*/
fun uninstallPackage(packageName: String, intentSender: IntentSender) {
try {
packageInstaller.uninstall(packageName, intentSender)
if (!uninstallForAllUsers(packageName, intentSender)) {
Log.w(TAG, "Uninstalling $packageName for this user only: the all-users call is not on this platform")
packageInstaller.uninstall(packageName, intentSender)
}
} catch (t: Throwable) {
record(ShizukuOp.Uninstall, ShizukuReason.CallFailed, t.toString(), t)
throw t
}
}

/**
* The all-users uninstall; false when the platform does not offer it, having done nothing.
*
* False is returned for a missing method only. Whatever the call itself throws is its answer and is passed on:
* retrying that as a single-user uninstall would half-do the job and report it as done.
*/
private fun uninstallForAllUsers(packageName: String, intentSender: IntentSender): Boolean {
val uninstall =
runCatching {
PackageInstaller::class.java.getMethod(
"uninstall",
VersionedPackage::class.java,
Int::class.javaPrimitiveType,
IntentSender::class.java,
)
}
.getOrNull() ?: return false
try {
uninstall.invoke(
packageInstaller,
VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST),
DELETE_ALL_USERS,
intentSender,
)
} catch (t: java.lang.reflect.InvocationTargetException) {
// The reflection is an implementation detail; what the package manager said is not.
throw t.targetException ?: t
}
return true
}

/** Runs a shell command through the Shizuku user service (shell UID); null if unavailable. */
suspend fun runShellCommand(command: String): String? =
onService(ShizukuOp.Shell, null) { it.runShellCommand(command) }
Expand Down
Loading
Loading