Android开发中AsmClassVisitorFactory如何使用

发布时间:2022-06-22 09:30:59 作者:iii
来源:亿速云 阅读:267

这篇文章主要讲解了“Android开发中AsmClassVisitorFactory如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Android开发中AsmClassVisitorFactory如何使用”吧!

AsmClassVisitorFactory

@Incubating
interface AsmClassVisitorFactory<ParametersT : InstrumentationParameters> : Serializable {
    /**
     * The parameters that will be instantiated, configured using the given config when registering
     * the visitor, and injected on instantiation.
     *
     * This field must be left unimplemented.
     */
    @get:Nested
    val parameters: Property<ParametersT>
    /**
     * Contains parameters to help instantiate the visitor objects.
     *
     * This field must be left unimplemented.
     */
    @get:Nested
    val instrumentationContext: InstrumentationContext
    /**
     * Creates a class visitor object that will visit a class with the given [classContext]. The
     * returned class visitor must delegate its calls to [nextClassVisitor].
     *
     * The given [classContext] contains static information about the classes before starting the
     * instrumentation process. Any changes in interfaces or superclasses for the class with the
     * given [classContext] or for any other class in its classpath by a previous visitor will
     * not be reflected in the [classContext] object.
     *
     * [classContext] can also be used to get the data for classes that are in the runtime classpath
     * of the class being visited.
     *
     * This method must handle asynchronous calls.
     *
     * @param classContext contains information about the class that will be instrumented by the
     *                     returned class visitor.
     * @param nextClassVisitor the [ClassVisitor] to which the created [ClassVisitor] must delegate
     *                         method calls.
     */
    fun createClassVisitor(
        classContext: ClassContext,
        nextClassVisitor: ClassVisitor
    ): ClassVisitor
    /**
     * Whether or not the factory wants to instrument the class with the given [classData].
     *
     * If returned true, [createClassVisitor] will be called and the returned class visitor will
     * visit the class.
     *
     * This method must handle asynchronous calls.
     */
    fun isInstrumentable(classData: ClassData): Boolean
}

简单的分析下这个接口,我们要做的就是在createClassVisitor这个方法中返回一个ClassVisitor,正常我们在构造ClassVisitor实例的时候是需要传入下一个ClassVisitor实例的,所以我们之后在new的时候传入nextClassVisitor就行了。

另外就是isInstrumentable,这个方法是判断当前类是否要进行扫描,因为如果所有类都要通过ClassVisitor进行扫描还是太耗时了,我们可以通过这个方法过滤掉很多我们不需要扫描的类。

@Incubating
interface ClassData {
    /**
     * Fully qualified name of the class.
     */
    val className: String
    /**
     * List of the annotations the class has.
     */
    val classAnnotations: List<String>
    /**
     * List of all the interfaces that this class or a superclass of this class implements.
     */
    val interfaces: List<String>
    /**
     * List of all the super classes that this class or a super class of this class extends.
     */
    val superClasses: List<String>
}

ClassData并不是asm的api,所以其中包含的内容相对来说比较少,但是应该也勉强够用了。这部分大家简单看看就行了,就不多做介绍了呢。

新的Extension

AGP版本升级之后,应该是为了区分新旧版的Extension,所以在AppExtension的基础上,新增了一个AndroidComponentsExtension出来。

我们的transformClassesWith就需要注册在这个上面。这个需要考虑到变种,和之前的Transform还是有比较大的区别的,这样我们就可以基于不同的变种增加对应的适配工作了。

        val androidComponents = project.extensions.getByType(AndroidComponentsExtension::class.java)
        androidComponents.onVariants { variant ->
            variant.transformClassesWith(PrivacyClassVisitorFactory::class.java,
                    InstrumentationScope.ALL) {}
            variant.setAsmFramesComputationMode(FramesComputationMode.COPY_FRAMES)
        }

实战

这次还是在之前的敏感权限api替换的字节码替换工具的基础上进行测试开发。

ClassVisitor

看看我们正常是如何写一个简单的ClassVisitor的。

ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassVisitor methodFilterCV = new ClassFilterVisitor(classWriter);
ClassReader cr = new ClassReader(srcClass);
cr.accept(methodFilterCV, ClassReader.SKIP_DEBUG);
return classWriter.toByteArray();

首先我们会构造好一个空的ClassWriter,接着会构造一个ClassVisitor实例,然后传入这个ClassWriter。然后我们构造一个ClassReader实例,然后将byte数组传入,之后调用classReader.accept方法,之后我们就能在visitor中逐个访问数据了。

那么其实我们的类信息,方法啥的都是通过ClassReader读入的,然后由当前的ClassVisitor访问完之后交给我们最后一个ClassWriter

其中ClassWriter也是一个ClassVisitor对象,他复杂重新将修改过的类转化成byte数据。可以看得出来ClassVisitor就有一个非常简单的链表结构,之后逐层向下访问。

介绍完了这个哦,我们做个大胆的假设,如果我们这个ClassVisitor链表前插入几个不同的ClassVisitor,那么我们是不是就可以让asm修改逐个生效,然后也不需要多余的io操作了呢。这就是新的asm api 的设计思路了,也是我们这边大佬的字节码框架大佬的设计。另外bytex内的设计思路也是如此。

tips ClassNode 因为是先生成的语法树,所以和一般的ClassVisitor有点小区别,需要在visitEnd方法内调用accept(next)

实际代码分析

接下来我们上实战咯。我将之前的代码套用到这次的逻辑上来。

demo地址

abstract class PrivacyClassVisitorFactory : AsmClassVisitorFactory<InstrumentationParameters.None> {
    override fun createClassVisitor(classContext: ClassContext, nextClassVisitor: ClassVisitor): ClassVisitor {
        return PrivacyClassNode(nextClassVisitor)
    }
    override fun isInstrumentable(classData: ClassData): Boolean {
        return true
    }
}

我在isInstrumentable都返回的是true,其实我可以将扫描规则限定在特定包名内,这样就可以加快构建速度了。

class PrivacyClassNode(private val nextVisitor: ClassVisitor) : ClassNode(Opcodes.ASM5) {
    override fun visitEnd() {
        super.visitEnd()
        PrivacyHelper.whiteList.let {
            val result = it.firstOrNull { whiteName ->
                name.contains(whiteName, true)
            }
            result
        }.apply {
            if (this == null) {
                //   println("filter: $name")
            }
        }
        PrivacyHelper.whiteList.firstOrNull {
            name.contains(it, true)
        }?.apply {
            val iterator: Iterator<MethodNode> = methods.iterator()
            while (iterator.hasNext()) {
                val method = iterator.next()
                method.instructions?.iterator()?.forEach {
                    if (it is MethodInsnNode) {
                        it.isPrivacy()?.apply {
                            println("privacy transform classNodeName: ${name@this}")
                            it.opcode = code
                            it.owner = owner
                            it.name = name
                            it.desc = desc
                        }
                    }
                }
            }
        }
        accept(nextVisitor)
    }
}
private fun MethodInsnNode.isPrivacy(): PrivacyAsmEntity? {
    val pair = PrivacyHelper.privacyList.firstOrNull {
        val first = it.first
        first.owner == owner && first.code == opcode && first.name == name && first.desc == desc
    }
    return pair?.second
}

这部分比较简单,把逻辑抽象定义在类ClassNode内,然后在visitEnd方法的时候调用我之前说的accept(nextVisitor)方法。

感谢各位的阅读,以上就是“Android开发中AsmClassVisitorFactory如何使用”的内容了,经过本文的学习后,相信大家对Android开发中AsmClassVisitorFactory如何使用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. Android开发中Bitmap高效加载使用详解
  2. Android开发中本地html文件怎么使用webView打开

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android asmclassvisitorfactory

上一篇:Android如何实现加载圈

下一篇:Android开发Viewbinding委托怎么实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》