登录
  • 欢迎访问 Sharezer Blog

Gradle 插件结合 asm 实现 android AOP 埋点

Android sharezer 3927次浏览 已收录 0个评论

本文由 简悦 SimpRead 转码, 原文地址 https://www.jianshu.com/p/067b1399158d

1、在 buildsrc 中新建 AsmInjectPlugin 插件
public class AsmInjectPlugin implements Plugin<Project>{
    @Override
    void apply(Project project) {
        System.out.println("========================")
        System.out.println("这是AsmInjectPlugin插件!")
        System.out.println("========================")
    }
}
2、在 groovy 下新建 AsmInjectTrans 继承 Transform
public class AsmInjectTrans extends Transform{

    @Override
    void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
        super.transform(transformInvocation)
        // Transform的inputs有两种类型,一种是目录,一种是jar包,要分开遍历
        transformInvocation.inputs.each { TransformInput input ->
            //对类型为“文件夹”的input进行遍历
            input.directoryInputs.each { DirectoryInput directoryInput ->
                //文件夹里面包含的是我们手写的类以及R.class、BuildConfig.class以及R$XXX.class等
                if (directoryInput.file.isDirectory()) {
                    // println "==== directoryInput.file = " + directoryInput.file
                    directoryInput.file.eachFileRecurse { File file ->
                        def name = file.name
                        //  println "==== directoryInput file name ==== " + file.getAbsolutePath()
                        if (name.endsWith(".class")
                            && !name.endsWith("R.class")
                            && !name.endsWith("BuildConfig.class")
                            && !name.contains("R\$")) {
                            println "==== directoryInput file name ==== " + file.getAbsolutePath()

                        }
                    }
                }

                // 获取output目录
                def dest = transformInvocation.outputProvider.getContentLocation(directoryInput.name,
                                                                                 directoryInput.contentTypes, directoryInput.scopes,
                                                                                 Format.DIRECTORY)

                // 将input的目录复制到output指定目录
                FileUtils.copyDirectory(directoryInput.file, dest)
            }
            //对类型为jar文件的input进行遍历
            input.jarInputs.each { JarInput jarInput ->

                //jar文件一般是第三方依赖库jar文件
                // 重命名输出文件(同目录copyFile会冲突)
                def jarName = jarInput.name
                def md5Name = DigestUtils.md5Hex(jarInput.file.getAbsolutePath())
                if (jarName.endsWith(".jar")) {
                    jarName = jarName.substring(0, jarName.length() - 4)
                }
                //生成输出路径
                def dest = transformInvocation.outputProvider.getContentLocation(jarName + md5Name,
                                                                                 jarInput.contentTypes, jarInput.scopes, Format.JAR)
                //将输入内容复制到输出
                FileUtils.copyFile(jarInput.file, dest)
            }
        }
    }
    //用于指明本Transform的名字,也是代表该Transform的task的名字
    @Override
    String getName() {
        return "AsmInject"
    }

    //指明Transform的输入类型,可以作为输入过滤的手段
    @Override
    Set<QualifiedContent.ContentType> getInputTypes() {
        return TransformManager.CONTENT_CLASS
    }

    //指明Transform的作用域
    @Override
    Set<? super QualifiedContent.Scope> getScopes() {
        return TransformManager.SCOPE_FULL_PROJECT
    }

    //指明是否是增量构建
    @Override
    boolean isIncremental() {
        return false
    }
}
3、在 AsmInjectPlugin 的 apply 中添加如下代码
def android = project.extensions.getByType(AppExtension)
AsmInjectTrans asmInjectTrans = new AsmInjectTrans()
android.registerTransform(asmInjectTrans)    
4、app 下的 gradle.build 中添加
apply plugin: com.liujian.AsmInjectPlugin

Clean project,然后 make project,从 messages 窗口中看到如下打印信息(app 工程下,只有一个 MainActivity)

Gradle 插件结合 asm 实现 android AOP 埋点

5、在 buidlsrc 的 gradle.build 中添加 asm 依赖
compile 'org.ow2.asm:asm:5.1'
compile 'org.ow2.asm:asm-commons:5.1'

然后在 AsmInjectTrans 的 transform 中编写注入代码:

void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
    super.transform(transformInvocation)
    // Transform的inputs有两种类型,一种是目录,一种是jar包,要分开遍历
    transformInvocation.inputs.each { TransformInput input ->
        //对类型为“文件夹”的input进行遍历
        input.directoryInputs.each { DirectoryInput directoryInput ->
            //文件夹里面包含的是我们手写的类以及R.class、BuildConfig.class以及R$XXX.class等
            if (directoryInput.file.isDirectory()) {
                // println "==== directoryInput.file = " + directoryInput.file
                directoryInput.file.eachFileRecurse { File file ->
                    def name = file.name
                    //  println "==== directoryInput file name ==== " + file.getAbsolutePath()
                    if (name.endsWith(".class")
                        && !name.endsWith("R.class")
                        && !name.endsWith("BuildConfig.class")
                        && !name.contains("R\$")) {
                        println "==== directoryInput file name ==== " + file.getAbsolutePath()

                        ClassReader classReader = new ClassReader(file.bytes)
                        ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_MAXS)
                        AsmClassVisitor classVisitor = new AsmClassVisitor(Opcodes.ASM5, classWriter)
                        classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES)
                        byte[] bytes = classWriter.toByteArray()
                        File destFile = new File(file.parentFile.absoluteFile, name)
                        //project.logger.error "==== 重新写入的位置->lastFilePath === " + destFile.getAbsolutePath()
                        FileOutputStream fileOutputStream = new FileOutputStream(destFile)
                        fileOutputStream.write(bytes)
                        fileOutputStream.close()
                    }
                }
            }

            // 获取output目录
            def dest = transformInvocation.outputProvider.getContentLocation(directoryInput.name,
                                                                             directoryInput.contentTypes, directoryInput.scopes,
                                                                             Format.DIRECTORY)

            // 将input的目录复制到output指定目录
            FileUtils.copyDirectory(directoryInput.file, dest)
        }
        //对类型为jar文件的input进行遍历
        input.jarInputs.each { JarInput jarInput ->

            //jar文件一般是第三方依赖库jar文件
            // 重命名输出文件(同目录copyFile会冲突)
            def jarName = jarInput.name
            def md5Name = DigestUtils.md5Hex(jarInput.file.getAbsolutePath())
            if (jarName.endsWith(".jar")) {
                jarName = jarName.substring(0, jarName.length() - 4)
            }
            //生成输出路径
            def dest = transformInvocation.outputProvider.getContentLocation(jarName + md5Name,
                                                                             jarInput.contentTypes, jarInput.scopes, Format.JAR)
            //将输入内容复制到输出
            FileUtils.copyFile(jarInput.file, dest)
        }
    }
}
6、完成注入过程

新建 AsmClassVisitor

public class AsmClassVisitor extends ClassVisitor {

    public AsmClassVisitor(int api) {
        super(api);
    }

    public AsmClassVisitor(int api, ClassVisitor classVisitor) {
        super(api, 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);
    }

    @Override
    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
        return super.visitAnnotation(desc, visible);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        MyLog.log("=====---------- visitMethod ----------=====");
        MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
        AsmMethodVisitor mMethodVisitor = new AsmMethodVisitor(Opcodes.ASM5, mv, access, name, desc);
        return mMethodVisitor;
    }

    @Override
    public void visitEnd() {
        super.visitEnd();
    }
}

然后新建 AsmMethodVisitor

public class AsmMethodVisitor extends AdviceAdapter{
    private String methodName;
    private String methodDes;

    public AsmMethodVisitor(int api, MethodVisitor mv, int access, String name, String desc) {
        super(api, mv, access, name, desc);
        methodName = name;
        methodDes = desc;
    }

    @Override
    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
        return super.visitAnnotation(desc, visible);
    }

    @Override
    protected void onMethodEnter() {
        if("onClick".equals(methodName) && "(Landroid/view/View;)V".equals(methodDes)){
            mv.visitVarInsn(ALOAD, 1);
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, "com/example/liujian/asmdemo/LogUtils", "system", "(Landroid/view/View;)V", false);

        }
    }

    @Override
    protected void onMethodExit(int opcode) {
        super.onMethodExit(opcode);
    }
}
7、调试。在 app 工程下,新建 com.example.liujian.asmdemo 包下 LogUtils 类
public class LogUtils {

    public static void system(View v){
        Log.d("MainActivity-asm--", "onclick---"+v.getId());
    }
}

然后在 MainActivity 添加调试代码调试

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_1).setOnClickListener(this);
        findViewById(R.id.btn_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("MainActivity-btn_2-", "onclick---"+view.getId());
            }
        });

    }

    @Override
    public void onClick(View view) {
        Log.d("MainActivity-btn_1-", "onclick---"+view.getId());
    }
}

clean project,然后 run

Gradle 插件结合 asm 实现 android AOP 埋点

完成注入!
此时在 app/build/intermediates/classes/debug/com/example/liujian/asmdemo 下查看 MainActivity.class 文件

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.example.liujian.asmdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends AppCompatActivity implements OnClickListener {
    public MainActivity() {
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(2131296283);
        this.findViewById(2131165219).setOnClickListener(this);
        this.findViewById(2131165220).setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                LogUtils.system(view);
                Log.d("MainActivity-btn_2-", "onclick---" + view.getId());
            }
        });
    }

    public void onClick(View view) {
        LogUtils.system(view);
        Log.d("MainActivity-btn_1-", "onclick---" + view.getId());
    }
}

其中 LogUtils.system(view); 为我们 plugin 注入的代码

demo 地址:https://github.com/liujianwj/AsmDemo


Sharezer , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Gradle 插件结合 asm 实现 android AOP 埋点
喜欢 (2)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址