1. 配置阶段
在工程下创建Module,命名buildSrc,注意S大写,不是这个名字本项目识别不到插件。
删除所有的目录仅留下java目录,在java目录下创建插件:
public class AutoTracePlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
System.out.println("插件引用了");
}
}
继续在java同级目录创建resources,暴露给主项目调用的插件位置,在resources下创建目录/META-INF/gradle-plugins,继续创建文件xxx.properties,xxx就是主项目会引用的插件名字。
xxx.properties配置:
implementation-class=com.beiins.dolly.AutoTracePlugin
指定插件的相对路径。
在主app的build.gradle下引用:
apply plugin: 'com.beiins.dolly.plugin'
插件的定义和引用就完成了,点击build,就能看到输出“插件引用了”。
2. 插件Transform定义
插件只是读取字节码的入口,真正操作字节码需要交给Transform,Transform的定义比较固定化:
public class AutoTraceTransform extends Transform {
@Override
public String getName() {
return "auto-trace-transform";
}
@Override
public Set<QualifiedContent.ContentType> getInputTypes() {
return TransformManager.CONTENT_CLASS;
}
@Override
public Set<? super QualifiedContent.Scope> getScopes() {
return TransformManager.SCOPE_FULL_PROJECT;
}
@Override
public boolean isIncremental() {
return false;
}
@Override
public void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
Collection<TransformInput> inputs = transformInvocation.getInputs();
TransformOutputProvider outputProvider = transformInvocation.getOutputProvider();
inputs.forEach(transformInput -> {
transformInput.getJarInputs().forEach(jarInput -> {
File dest = outputProvider.getContentLocation(jarInput.getName(), jarInput.getContentTypes(), jarInput.getScopes(), Format.JAR);
try {
System.out.println("拷贝jar文件" + jarInput.getName());
FileUtils.copyFile(jarInput.getFile(), dest);
} catch (Exception e) {
e.printStackTrace();
}
});
transformInput.getDirectoryInputs().forEach(directoryInput -> {
File dest = outputProvider.getContentLocation(directoryInput.getName(), directoryInput.getContentTypes(), directoryInput.getScopes(), Format.DIRECTORY);
try {
System.out.println("拷贝directory文件" + directoryInput.getName());
FileUtils.copyDirectory(directoryInput.getFile(), dest);
} catch (Exception e) {
e.printStackTrace();
}
});
});
}
}
必须重写4个方法,指定Transform的name,指定Transform接受的输入,指定Transform作用的范围,指定Transform是否支持增量更新。最关键的是transform,对字节码的操作就在这个方法内,上面是简单的拷贝工程的class文件,从主app的build/intermediates/javac下拷贝到build/intermediates/transforms下。
自动埋点,需要对以上遍历的jarInputs和directoryInputs进行修改:
public void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
Collection<TransformInput> inputs = transformInvocation.getInputs();
TransformOutputProvider outputProvider = transformInvocation.getOutputProvider();
inputs.forEach(transformInput -> {
transformInput.getJarInputs().forEach(jarInput -> {
File dest = outputProvider.getContentLocation(jarInput.getName(), jarInput.getContentTypes(), jarInput.getScopes(), Format.JAR);
try {
System.out.println("拷贝jar文件" + jarInput.getName());
FileUtils.copyFile(jarInput.getFile(), dest);
} catch (Exception e) {
e.printStackTrace();
}
});
transformInput.getDirectoryInputs().forEach(directoryInput -> {
File dir = directoryInput.getFile();
try {
traverse(dir);
} catch (Exception e) {
e.printStackTrace();
} finally {
File dest = outputProvider.getContentLocation(directoryInput.getName(), directoryInput.getContentTypes(), directoryInput.getScopes(), Format.DIRECTORY);
try {
System.out.println("拷贝directory文件" + directoryInput.getName());
FileUtils.copyDirectory(directoryInput.getFile(), dest);
} catch (Exception e) {
e.printStackTrace();
}
}
});
});
}
/**
* 循环遍历java文件修改
*
* @param file
*/
private void traverse(File file) throws Exception {
if (file == null || !file.exists()) {
return;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
traverse(f);
}
} else {
System.out.println("find class========== " + file.getName());
if (!file.getName().endsWith(".class")) {
return;
}
ClassReader classReader = new ClassReader(new FileInputStream(file.getPath()));
ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_MAXS);
ClassVisitor classVisitor = new AutoTraceClassVisitor(classWriter);
classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);
byte[] bytes = classWriter.toByteArray();
FileOutputStream outputStream = new FileOutputStream(file.getPath());
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
}
主要增加了traverse循环遍历class文件进行字节码修改,关键类AutoTraceClassVisitor,对class文件进行访问,如果满足条件,就插入字节码。
自定义ClassVisitor访问类:
public class AutoTraceClassVisitor extends ClassVisitor {
private String mClassName;
private String mSuperName;
private String[] mInterfaces;
public AutoTraceClassVisitor(ClassVisitor classVisitor) {
super(Opcodes.ASM5, classVisitor);
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
System.out.println("visit name = " + name + " superName = " + superName);
mClassName = name;
mSuperName = superName;
mInterfaces = interfaces;
}
@Override
public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
System.out.println("visit name = " + name + " signature = " + signature + " access = " + access);
MethodVisitor methodVisitor = cv.visitMethod(access, name, descriptor, signature, exceptions);
if ("onClick(Landroid/view/View;)V".equals(name + descriptor)) {
System.out.println("遍历到点击事件了");
return new AutoTraceMethodVisitor(methodVisitor, mClassName, name);
}
return methodVisitor;
}
@Override
public void visitEnd() {
super.visitEnd();
}
}
在visitMethod方法类进行访问时,对类中遍历的类进行判断,如果是onClick方法,并且入参是View类型,也就是点击事件的回调方法,就触发方法的访问类AutoTraceMethodVisitor。
自定义方法访问类AutoTraceMethodVisitor:
public class AutoTraceMethodVisitor extends MethodVisitor {
private String mMethodName;
private String mClassName;
public AutoTraceMethodVisitor(int api) {
super(api);
}
public AutoTraceMethodVisitor(MethodVisitor methodVisitor, String className, String methodName) {
super(Opcodes.ASM5, methodVisitor);
mClassName = className;
mMethodName = methodName;
}
@Override
public void visitCode() {
super.visitCode();
mv.visitVarInsn(ALOAD, 1);
mv.visitMethodInsn(INVOKESTATIC, "com/beiins/point/PointUtil", "record", "(Landroid/view/View;)V", false);
}
}
在访问方法的code之前,插入字节码。这个字节码不用看懂,看懂也没啥用,直接使用Android Studio插件ASM Bytecode Viewer,对想要插入的代码进行编译,获取对应的字节码。
3. 字节码生成
按照插入的代码越精简风险越小的原理,最好是提前写一个工具类,将插入的代码封装成工具类调用,类似:
PointUtil.record(v);
这样一行代码,风险极小。新建一个类,写一个方法,方法定义一个参数View,方法内只有上述工具类调用,将干扰降到最低:
public void method(View view){
PointUtil.record(view);
}
在安装ASM Bytecode Viewer插件的条件下,右键,选择ASM Bytecode Viewer,在右边就可以看到字节码了。
注意辨别行号。