1
mirror of https://github.com/revanced/revanced-patcher synced 2025-09-06 16:38:50 +02:00

Compare commits

..

11 Commits

Author SHA1 Message Date
semantic-release-bot
b19e1131e8 chore(release): 3.3.2 [skip ci]
## [3.3.2](https://github.com/revanced/revanced-patcher/compare/v3.3.1...v3.3.2) (2022-08-06)

### Bug Fixes

* close open files ([#75](https://github.com/revanced/revanced-patcher/issues/75)) ([123ad54](123ad54c15))
2022-08-06 22:17:39 +00:00
dan1st
123ad54c15 fix: close open files (#75) 2022-08-07 00:16:23 +02:00
Sculas
09f6ab4155 Merge remote-tracking branch 'origin/main' into main 2022-08-03 18:32:34 +02:00
Sculas
01cf3fb50f refactor: util package structure 2022-08-03 18:31:31 +02:00
semantic-release-bot
6c5f9d4198 chore(release): 3.3.1 [skip ci]
## [3.3.1](https://github.com/revanced/revanced-patcher/compare/v3.3.0...v3.3.1) (2022-08-03)

### Bug Fixes

* revert soft dependencies ([7b2d058](7b2d058144))
2022-08-03 01:48:56 +00:00
oSumAtrIX
7b2d058144 fix: revert soft dependencies 2022-08-03 03:45:34 +02:00
semantic-release-bot
db2804270e chore(release): 3.3.0 [skip ci]
# [3.3.0](https://github.com/revanced/revanced-patcher/compare/v3.2.1...v3.3.0) (2022-08-02)

### Features

* add getValue & setValue for PatchOption ([2572cd0](2572cd04b5))
2022-08-02 21:31:59 +00:00
Sculas
2572cd04b5 feat: add getValue & setValue for PatchOption 2022-08-02 23:30:38 +02:00
semantic-release-bot
5eb8b428b9 chore(release): 3.2.1 [skip ci]
## [3.2.1](https://github.com/revanced/revanced-patcher/compare/v3.2.0...v3.2.1) (2022-08-02)

### Bug Fixes

* check if patch option requirement is met ([14a73bf](14a73bfcaf))
2022-08-02 20:43:26 +00:00
Sculas
3a118d9b9d Merge remote-tracking branch 'origin/main' into main 2022-08-02 22:41:41 +02:00
Sculas
14a73bfcaf fix: check if patch option requirement is met 2022-08-02 22:41:34 +02:00
13 changed files with 194 additions and 151 deletions

View File

@@ -1,3 +1,31 @@
## [3.3.2](https://github.com/revanced/revanced-patcher/compare/v3.3.1...v3.3.2) (2022-08-06)
### Bug Fixes
* close open files ([#75](https://github.com/revanced/revanced-patcher/issues/75)) ([123ad54](https://github.com/revanced/revanced-patcher/commit/123ad54c150bd04f4b8ef5c65334ea468ceb99cc))
## [3.3.1](https://github.com/revanced/revanced-patcher/compare/v3.3.0...v3.3.1) (2022-08-03)
### Bug Fixes
* revert soft dependencies ([7b2d058](https://github.com/revanced/revanced-patcher/commit/7b2d058144b0718992d329731e2af7cc704e4370))
# [3.3.0](https://github.com/revanced/revanced-patcher/compare/v3.2.1...v3.3.0) (2022-08-02)
### Features
* add getValue & setValue for PatchOption ([2572cd0](https://github.com/revanced/revanced-patcher/commit/2572cd04b5da4eeae738c8dde31493177edf0bf8))
## [3.2.1](https://github.com/revanced/revanced-patcher/compare/v3.2.0...v3.2.1) (2022-08-02)
### Bug Fixes
* check if patch option requirement is met ([14a73bf](https://github.com/revanced/revanced-patcher/commit/14a73bfcafac36bce2b8466788d460edde7a14fd))
# [3.2.0](https://github.com/revanced/revanced-patcher/compare/v3.1.0...v3.2.0) (2022-08-02)

View File

@@ -1,2 +1,2 @@
kotlin.code.style = official
version = 3.2.0
version = 3.3.2

View File

@@ -49,70 +49,74 @@ class Patcher(private val options: PatcherOptions) {
init {
val extInputFile = ExtFile(options.inputFile)
val outDir = File(options.resourceCacheDirectory)
if (outDir.exists()) {
logger.info("Deleting existing resource cache directory")
outDir.deleteRecursively()
}
outDir.mkdirs()
try {
val outDir = File(options.resourceCacheDirectory)
if (outDir.exists()) {
logger.info("Deleting existing resource cache directory")
outDir.deleteRecursively()
}
outDir.mkdirs()
val androlib = Androlib(BuildOptions().also { it.setBuildOptions(options) })
val resourceTable = androlib.getResTable(extInputFile, true)
val androlib = Androlib(BuildOptions().also { it.setBuildOptions(options) })
val resourceTable = androlib.getResTable(extInputFile, true)
val packageMetadata = PackageMetadata()
val packageMetadata = PackageMetadata()
if (options.patchResources) {
logger.info("Decoding resources")
if (options.patchResources) {
logger.info("Decoding resources")
// decode resources to cache directory
androlib.decodeManifestWithResources(extInputFile, outDir, resourceTable)
androlib.decodeResourcesFull(extInputFile, outDir, resourceTable)
// decode resources to cache directory
androlib.decodeManifestWithResources(extInputFile, outDir, resourceTable)
androlib.decodeResourcesFull(extInputFile, outDir, resourceTable)
// read additional metadata from the resource table
packageMetadata.metaInfo.usesFramework = UsesFramework().also { framework ->
framework.ids = resourceTable.listFramePackages().map { it.id }.sorted()
// read additional metadata from the resource table
packageMetadata.metaInfo.usesFramework = UsesFramework().also { framework ->
framework.ids = resourceTable.listFramePackages().map { it.id }.sorted()
}
packageMetadata.metaInfo.doNotCompress = buildList {
androlib.recordUncompressedFiles(extInputFile, this)
}
} else {
logger.info("Only decoding AndroidManifest.xml because resource patching is disabled")
// create decoder for the resource table
val decoder = ResAttrDecoder()
decoder.currentPackage = ResPackage(resourceTable, 0, null)
// create xml parser with the decoder
val axmlParser = AXmlResourceParser()
axmlParser.attrDecoder = decoder
// parse package information with the decoder and parser which will set required values in the resource table
// instead of decodeManifest another more low level solution can be created to make it faster/better
XmlPullStreamDecoder(
axmlParser, AndrolibResources().resXmlSerializer
).decodeManifest(
extInputFile.directory.getFileInput("AndroidManifest.xml"), nullOutputStream
)
}
packageMetadata.metaInfo.doNotCompress = buildList {
androlib.recordUncompressedFiles(extInputFile, this)
}
packageMetadata.packageName = resourceTable.currentResPackage.name
packageMetadata.packageVersion = resourceTable.versionInfo.versionName
packageMetadata.metaInfo.versionInfo = resourceTable.versionInfo
packageMetadata.metaInfo.sdkInfo = resourceTable.sdkInfo
} else {
logger.info("Only decoding AndroidManifest.xml because resource patching is disabled")
logger.info("Reading dex files")
// create decoder for the resource table
val decoder = ResAttrDecoder()
decoder.currentPackage = ResPackage(resourceTable, 0, null)
// read dex files
val dexFile = MultiDexIO.readDexFile(true, options.inputFile, NAMER, null, null)
// get the opcodes
opcodes = dexFile.opcodes
// create xml parser with the decoder
val axmlParser = AXmlResourceParser()
axmlParser.attrDecoder = decoder
// parse package information with the decoder and parser which will set required values in the resource table
// instead of decodeManifest another more low level solution can be created to make it faster/better
XmlPullStreamDecoder(
axmlParser, AndrolibResources().resXmlSerializer
).decodeManifest(
extInputFile.directory.getFileInput("AndroidManifest.xml"), nullOutputStream
// finally create patcher data
data = PatcherData(
dexFile.classes.toMutableList(), options.resourceCacheDirectory, packageMetadata
)
} finally {
extInputFile.close()
}
packageMetadata.packageName = resourceTable.currentResPackage.name
packageMetadata.packageVersion = resourceTable.versionInfo.versionName
packageMetadata.metaInfo.versionInfo = resourceTable.versionInfo
packageMetadata.metaInfo.sdkInfo = resourceTable.sdkInfo
logger.info("Reading dex files")
// read dex files
val dexFile = MultiDexIO.readDexFile(true, options.inputFile, NAMER, null, null)
// get the opcodes
opcodes = dexFile.opcodes
// finally create patcher data
data = PatcherData(
dexFile.classes.toMutableList(), options.resourceCacheDirectory, packageMetadata
)
}
/**
@@ -165,43 +169,46 @@ class Patcher(private val options: PatcherOptions) {
if (options.patchResources) {
val cacheDirectory = ExtFile(options.resourceCacheDirectory)
try {
val androlibResources = AndrolibResources().also { resources ->
resources.buildOptions = BuildOptions().also { buildOptions ->
buildOptions.setBuildOptions(options)
buildOptions.isFramework = metaInfo.isFrameworkApk
buildOptions.resourcesAreCompressed = metaInfo.compressionType
buildOptions.doNotCompress = metaInfo.doNotCompress
}
val androlibResources = AndrolibResources().also { resources ->
resources.buildOptions = BuildOptions().also { buildOptions ->
buildOptions.setBuildOptions(options)
buildOptions.isFramework = metaInfo.isFrameworkApk
buildOptions.resourcesAreCompressed = metaInfo.compressionType
buildOptions.doNotCompress = metaInfo.doNotCompress
resources.setSdkInfo(metaInfo.sdkInfo)
resources.setVersionInfo(metaInfo.versionInfo)
resources.setSharedLibrary(metaInfo.sharedLibrary)
resources.setSparseResources(metaInfo.sparseResources)
}
resources.setSdkInfo(metaInfo.sdkInfo)
resources.setVersionInfo(metaInfo.versionInfo)
resources.setSharedLibrary(metaInfo.sharedLibrary)
resources.setSparseResources(metaInfo.sparseResources)
}
val manifestFile = cacheDirectory.resolve("AndroidManifest.xml")
val manifestFile = cacheDirectory.resolve("AndroidManifest.xml")
ResXmlPatcher.fixingPublicAttrsInProviderAttributes(manifestFile)
ResXmlPatcher.fixingPublicAttrsInProviderAttributes(manifestFile)
val aaptFile = cacheDirectory.resolve("aapt_temp_file")
val aaptFile = cacheDirectory.resolve("aapt_temp_file")
// delete if it exists
Files.deleteIfExists(aaptFile.toPath())
// delete if it exists
Files.deleteIfExists(aaptFile.toPath())
val resDirectory = cacheDirectory.resolve("res")
val includedFiles = metaInfo.usesFramework.ids.map { id ->
androlibResources.getFrameworkApk(
id, metaInfo.usesFramework.tag
)
}.toTypedArray()
val resDirectory = cacheDirectory.resolve("res")
val includedFiles = metaInfo.usesFramework.ids.map { id ->
androlibResources.getFrameworkApk(
id, metaInfo.usesFramework.tag
logger.info("Compiling resources")
androlibResources.aaptPackage(
aaptFile, manifestFile, resDirectory, null, null, includedFiles
)
}.toTypedArray()
logger.info("Compiling resources")
androlibResources.aaptPackage(
aaptFile, manifestFile, resDirectory, null, null, includedFiles
)
resourceFile = aaptFile
resourceFile = aaptFile
} finally {
cacheDirectory.close()
}
}
logger.trace("Creating new dex file")
@@ -262,16 +269,15 @@ class Patcher(private val options: PatcherOptions) {
}
// recursively apply all dependency patches
patch.dependencies.forEach {
val dependency = it.patch.java
patch.dependencies?.forEach {
val patchDependency = it.java
val result = applyPatch(patchDependency, appliedPatches)
val result = applyPatch(dependency, appliedPatches)
if (result.isSuccess()) return@forEach
val error = result.error()!!
val errorMessage = error.cause ?: error.message
return PatchResultError("'$patchName' depends on '${dependency.patchName}' but the following error was raised: $errorMessage")
val errorMessage = result.error()!!.cause
return PatchResultError("'$patchName' depends on '${patchDependency.patchName}' but the following error was raised: $errorMessage")
}
val patchInstance = patch.getDeclaredConstructor().newInstance()

View File

@@ -7,9 +7,6 @@ import app.revanced.patcher.annotation.Version
import app.revanced.patcher.data.Data
import app.revanced.patcher.fingerprint.method.impl.MethodFingerprint
import app.revanced.patcher.patch.Patch
import app.revanced.patcher.patch.annotations.Dependencies
import app.revanced.patcher.patch.annotations.DependencyType
import app.revanced.patcher.patch.annotations.DependsOn
import kotlin.reflect.KClass
/**
@@ -38,26 +35,20 @@ private fun <T : Annotation> Class<*>.findAnnotationRecursively(
return null
}
private typealias PatchClass = Class<out Patch<Data>>
object PatchExtensions {
val PatchClass.patchName: String get() = recursiveAnnotation(Name::class)?.name ?: this.javaClass.simpleName
val PatchClass.version get() = recursiveAnnotation(Version::class)?.version
val PatchClass.include get() = recursiveAnnotation(app.revanced.patcher.patch.annotations.Patch::class)!!.include
val PatchClass.description get() = recursiveAnnotation(Description::class)?.description
val PatchClass.dependencies get() = buildList {
recursiveAnnotation(DependsOn::class)?.let { add(PatchDependency(it.value, it.type)) }
recursiveAnnotation(Dependencies::class)?.dependencies?.forEach { add(PatchDependency(it, DependencyType.HARD)) }
}.toTypedArray()
val PatchClass.compatiblePackages get() = recursiveAnnotation(Compatibility::class)?.compatiblePackages
val Class<out Patch<Data>>.patchName: String
get() = recursiveAnnotation(Name::class)?.name ?: this.javaClass.simpleName
val Class<out Patch<Data>>.version get() = recursiveAnnotation(Version::class)?.version
val Class<out Patch<Data>>.include get() = recursiveAnnotation(app.revanced.patcher.patch.annotations.Patch::class)!!.include
val Class<out Patch<Data>>.description get() = recursiveAnnotation(Description::class)?.description
val Class<out Patch<Data>>.dependencies get() = recursiveAnnotation(app.revanced.patcher.patch.annotations.DependsOn::class)?.dependencies
val Class<out Patch<Data>>.compatiblePackages get() = recursiveAnnotation(Compatibility::class)?.compatiblePackages
@JvmStatic
fun PatchClass.dependsOn(patch: PatchClass): Boolean {
fun Class<out Patch<Data>>.dependsOn(patch: Class<out Patch<Data>>): Boolean {
if (this.patchName == patch.patchName) throw IllegalArgumentException("thisval and patch may not be the same")
return this.dependencies.any { it.patch.java.patchName == this@dependsOn.patchName }
return this.dependencies?.any { it.java.patchName == this@dependsOn.patchName } == true
}
class PatchDependency internal constructor(val patch: KClass<out Patch<Data>>, val type: DependencyType = DependencyType.HARD)
}
object MethodFingerprintExtensions {

View File

@@ -1,12 +1,16 @@
@file:Suppress("CanBeParameter", "MemberVisibilityCanBePrivate")
@file:Suppress("CanBeParameter", "MemberVisibilityCanBePrivate", "UNCHECKED_CAST")
package app.revanced.patcher.patch
import kotlin.reflect.KProperty
class NoSuchOptionException(val option: String) : Exception("No such option: $option")
class IllegalValueException(val value: Any?) : Exception("Illegal value: $value")
class InvalidTypeException(val got: String, val expected: String) :
Exception("Invalid option value type: $got, expected $expected")
class RequirementNotMetException : Exception("null was passed into an option that requires a value")
/**
* A registry for an array of [PatchOption]s.
* @param options An array of [PatchOption]s.
@@ -72,12 +76,33 @@ sealed class PatchOption<T>(
) {
var value: T? = default
set(value) {
if (value == null && required) {
throw RequirementNotMetException()
}
if (!validator(value)) {
throw IllegalValueException(value)
}
field = value
}
/**
* Gets the value of the option.
* Please note that using the wrong value type results in a runtime error.
*/
operator fun <T> getValue(thisRef: Nothing?, property: KProperty<*>) = value as T
/**
* Gets the value of the option.
* Please note that using the wrong value type results in a runtime error.
*/
inline operator fun <reified V> setValue(thisRef: Any?, property: KProperty<*>, new: V) {
if (value !is V) throw InvalidTypeException(
V::class.java.canonicalName,
value?.let { it::class.java.canonicalName } ?: "null"
)
value = new as T
}
/**
* A [PatchOption] representing a [String].
* @see PatchOption

View File

@@ -19,29 +19,6 @@ annotation class Patch(val include: Boolean = true)
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Deprecated(
"Does not support new parameter 'type'",
ReplaceWith("DependsOn")
)
annotation class Dependencies(
val dependencies: Array<KClass<out Patch<Data>>> = []
)
/**
* Annotation for dependencies of [Patch]es .
*/
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Repeatable
annotation class DependsOn(
val value: KClass<out Patch<Data>>,
val type: DependencyType = DependencyType.HARD
)
enum class DependencyType {
/**
* Enforces that the dependency is applied, even if it was not selected.
*/
HARD
}
val dependencies: Array<KClass<out Patch<Data>>> = []
)

View File

@@ -5,6 +5,6 @@ import java.io.InputStream
/**
* Wrapper for dex files.
* @param name The original name of the dex file.
* @param dexFileInputStream The dex file as [InputStream].
* @param stream The dex file as [InputStream].
*/
data class DexFile(val name: String, val dexFileInputStream: InputStream)
data class DexFile(val name: String, val stream: InputStream)

View File

@@ -1,17 +1,17 @@
package app.revanced.patcher.util.patch.base
package app.revanced.patcher.util.patch
import app.revanced.patcher.data.Data
import app.revanced.patcher.patch.Patch
import java.io.File
/**
* @param patchBundlePath The path to the patch bundle.
* @param path The path to the patch bundle.
*/
abstract class PatchBundle(patchBundlePath: String) : File(patchBundlePath) {
abstract class PatchBundle(path: String) : File(path) {
internal fun loadPatches(classLoader: ClassLoader, classNames: Iterator<String>) = buildList {
classNames.forEach { className ->
for (className in classNames) {
val clazz = classLoader.loadClass(className)
if (!clazz.isAnnotationPresent(app.revanced.patcher.patch.annotations.Patch::class.java)) return@forEach
if (!clazz.isAnnotationPresent(app.revanced.patcher.patch.annotations.Patch::class.java)) continue
@Suppress("UNCHECKED_CAST") this.add(clazz as Class<out Patch<Data>>)
}
}

View File

@@ -1,4 +1,4 @@
package app.revanced.patcher.util.patch.util
package app.revanced.patcher.util.patch
internal class StringIterator<T, I : Iterator<T>>(
private val iterator: I,

View File

@@ -1,7 +1,7 @@
package app.revanced.patcher.util.patch.implementation
package app.revanced.patcher.util.patch.impl
import app.revanced.patcher.util.patch.base.PatchBundle
import app.revanced.patcher.util.patch.util.StringIterator
import app.revanced.patcher.util.patch.PatchBundle
import app.revanced.patcher.util.patch.StringIterator
import org.jf.dexlib2.DexFileFactory
/**

View File

@@ -1,7 +1,7 @@
package app.revanced.patcher.util.patch.implementation
package app.revanced.patcher.util.patch.impl
import app.revanced.patcher.util.patch.base.PatchBundle
import app.revanced.patcher.util.patch.util.StringIterator
import app.revanced.patcher.util.patch.PatchBundle
import app.revanced.patcher.util.patch.StringIterator
import java.net.URLClassLoader
import java.util.jar.JarFile

View File

@@ -3,6 +3,7 @@ package app.revanced.patcher.patch
import app.revanced.patcher.usage.bytecode.ExampleBytecodePatch
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import kotlin.test.assertNotEquals
internal class PatchOptionsTest {
private val options = ExampleBytecodePatch().options
@@ -31,18 +32,27 @@ internal class PatchOptionsTest {
}
}
}
println(options["key1"].value)
val option = options["key1"]
println(option.value)
options["key1"] = "Hello, world!"
println(options["key1"].value)
println(option.value)
}
@Test
fun `should return a different value when changed`() {
var value: String by options["key1"]
val current = value + "" // force a copy
value = "Hello, world!"
assertNotEquals(current, value)
}
@Test
fun `should be able to set value to null`() {
// Sadly, doing:
// > options["key1"] = null
// > options["key2"] = null
// is not possible because Kotlin
// cannot reify the type "Nothing?".
options.nullify("key1")
options.nullify("key2")
}
@Test
@@ -65,4 +75,11 @@ internal class PatchOptionsTest {
options["key3"] = "this value is not an allowed option"
}
}
@Test
fun `should fail because of the requirement is not met`() {
assertThrows<RequirementNotMetException> {
options.nullify("key1")
}
}
}

View File

@@ -11,7 +11,6 @@ import app.revanced.patcher.patch.PatchOption
import app.revanced.patcher.patch.PatchOptions
import app.revanced.patcher.patch.PatchResult
import app.revanced.patcher.patch.PatchResultSuccess
import app.revanced.patcher.patch.annotations.DependencyType
import app.revanced.patcher.patch.annotations.DependsOn
import app.revanced.patcher.patch.annotations.Patch
import app.revanced.patcher.patch.impl.BytecodePatch
@@ -39,7 +38,7 @@ import org.jf.dexlib2.util.Preconditions
@Description("Example demonstration of a bytecode patch.")
@ExampleResourceCompatibility
@Version("0.0.1")
@DependsOn(ExampleBytecodePatch::class, DependencyType.HARD)
@DependsOn([ExampleBytecodePatch::class])
class ExampleBytecodePatch : BytecodePatch(listOf(ExampleFingerprint)) {
// This function will be executed by the patcher.
// You can treat it as a constructor