Android开发AsmClassVisitorFactory使用详解
作者:究极逮虾户 发布时间:2023-07-22 05:34:53
前言
之前就和大家介绍过AGP(Android Gradle Plugin) 7.0.0
版本之后Transform
已经过期即将废弃的事情。而且也简单的介绍了替换的方式是Transform Action
,经过我这一阵子的学习和调研,发现只能说答对了一半吧。下面介绍个新东西AsmClassVisitorFactory
。
com.android.build.api.instrumentation.AsmClassVisitorFactory
A factory to create class visitor objects to instrument classes.
The implementation of this interface must be an abstract class where the parameters and instrumentationContext are left unimplemented. The class must have an empty constructor which will be used to construct the factory object.
当前官方推荐使用的应该是这个类,这个类的底层实现就是基于gradle
原生的Transform Action
,这次的学习过程其实走了一点点弯路,一开始尝试的是Transform Action
,但是貌似弯弯绕绕的,最后也没有成功,而且Transform Action
的输入产物都是单一文件,修改也是针对单一文件的,所以貌似也不完全是一个很好的替换方案,之前文章介绍的那种复杂的asm操作则无法负荷了。
AsmClassVisitorFactory
根据官方说法,编译速度会有提升,大概18%左右,这个下面我们会在使用阶段对其进行介绍的。
我们先从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)
方法。
另外就是注册逻辑了,和我前面介绍的内容基本都是一样的。
个人观点
AsmClassVisitorFactory
相比较于之前的Transform
确实简化了非常非常多,我们不需要关心之前的增量更新等等逻辑,只要专注于asm api的操作就行了。
其次就是因为减少了io操作,所以其速度自然也就比之前有所提升。同时因为基于的是Transform Action
,所以整体性能还是非常ok的,那部分增量可以说是更简单了。
另外我也和我的同事大佬交流过哦,复杂的这种类似上篇文章介绍的,最好还是使用Gradle Task
的形式进行修改。
来源:https://juejin.cn/post/7016147287889936397


猜你喜欢
- 本文为大家分享了 Android Retrofit 2.0框架上传图片解决方案,具体内容如下1.单张图片的上传/** * 上传一
- 背景2021年第一天早上,客户突然投诉说系统的一个功能出了问题,紧急排查后发现后端系统确实出了bug,原因为前端传输的JSON报文,后端反序
- HttpServletRequest介绍HttpServletRequest对象代表客户端的请求,当客户端通过HTTP协议访问服务器时,HT
- 本文实例讲述了C#使用回溯法解决背包问题的方法。分享给大家供大家参考。具体如下:背包问题描述:给定一组物品,每种物品都有自己的重量和价格,在
- 前言随着微软对C#不断发展和更新,C#中对于数组操作的方式也变得越来越多样化。以往要实现过滤数组中的空字符串,都是需要实行循环的方式来排除和
- 本文实例为大家分享了SpringBoot实现分页功能的具体代码,供大家参考,具体内容如下新建demo\src\main\java\com\e
- 概览1. 基于链表的可选有界阻塞队列。根据FIFO的出入队顺序,从队列头部检索和获取元素,在队列尾部插入新元素。2. 当作为有界阻塞队列,在
- 文档合并是一种高效文档处理方式。如果能够有一个方法能将多种不同类型的文档合并成一种文档格式,那么在文档存储管理上将为我们提供极大的便利。因此
- 本文实例为大家分享了Android Webview使用小结,供大家参考,具体内容如下#采用重载URL的方式实现Java与Js交互在Andro
- 在上个星期阿里巴巴一面的时候,最后面试官问我如何把一篇文章中重复出现的词或者句子找出来,当时太紧张,答的不是很好。今天有时间再来亲手实现一遍
- Java提供了许多创建线程池的方式,并得到一个Future实例来作为任务结果。对于Spring同样小菜一碟,通过其scheduling包就可
- JSONObject toJSONString错误1.com.alibaba.fastjson.JSONObject 继承了JSON可以使用
- 创建SpringBoot项目可以通过两种方式1、通过访问:https://start.spring.io/,SpringBoot的官方网站进
- 一、创建一个cs文件,定义Time 对象 public class WebTimer_AutoRepayment{ &n
- 完成一个简单的基于MVC的数据查询模块,要求能够按照name进行模糊查询。Index.jsp:<%@ page import=&quo
- 本文实例为大家分享了java实现微信扫码支付的具体代码,供大家参考,具体内容如下1、maven项目的pom.xml中添加如下jar包:<
- 我这里主要是对串口类的简单使用,实现的功能是以读写方式打开串口,点击发送数据按钮将发送区的数据发送到缓冲区,然后在接收区显示出来,界面如下:
- Handler的定义:主要接受子线程发送的数据, 并用此数据配合主线程更新UI.解释: 当应用程序启动时,Android首先会开启一个主线程
- @Valid:@Valid注解用于校验,所属包为:javax.validation.Valid。① 首先需要在实体类的相应字段上添加用于充当
- 问题描述:我的PopupWindow位于屏幕底部,它上面有一个EditText输入框,而当我点击这个EditText的时候,随着输入法的弹出