美文网首页
ASM学习思路

ASM学习思路

作者: 折剑游侠 | 来源:发表于2021-11-10 15:18 被阅读0次

关于AOP、Plugin、Transform的概念,大家都卷到这个份上了,就不再细说了。撸个经典的demo,方法耗时检测,提供一下学习思路。相信按照下面这个流程走下来,肯定是能入门了,毕竟我都能学会。

进入正题,说实话直接用asm api织入字节码还是很懵逼的。工欲善其事必先利其器,下载字节码插件ASM Bytecode Viewer

首先需要一个辅助类,保存方法起始时间、结束时间,还需要计算耗时的方法current

public class TimeManager {
    private static final HashMap<String, Long> startMap = new HashMap<>();
    private static final HashMap<String, Long> endMap = new HashMap<>();

    public static void start(String key, long timeMills) {
        startMap.put(key, timeMills);
    }

    public static void end(String key, long timeMills) {
        endMap.put(key, timeMills);
    }

    public static long current(String key) {
        long startTimeMills = 0L;
        long endTimeMills = 0L;
        if (startMap.get(key) != null) {
            startTimeMills = startMap.get(key);
        }
        if (endMap.get(key) != null) {
            endTimeMills = endMap.get(key);
        }
        return endTimeMills - startTimeMills;
    }
}

没什么好多说的,以方法名为key。那么接下来就是ClassVisitorMethodVisitor

class TrackClassVisitor(classVisitor: ClassVisitor) : ClassVisitor(Opcodes.ASM9, classVisitor) {
    
    override fun visitMethod(
        access: Int,
        name: String?,
        descriptor: String?,
        signature: String?,
        exceptions: Array<out String>?
    ): MethodVisitor {
        val mv = cv.visitMethod(access, name, descriptor, signature, exceptions)
        return TrackMethodVisitor(mv, access, name, descriptor)
    }
}

object TrackMethodVisitor {

    operator fun invoke(
        mv: MethodVisitor,
        access: Int,
        name: String?,
        descriptor: String?,
    ): MethodVisitor {
        return object : AdviceAdapter(Opcodes.ASM9, mv, access, name, descriptor) {

            override fun visitAnnotation(descriptor: String?, visible: Boolean): AnnotationVisitor {
                return super.visitAnnotation(descriptor, visible)
            }

            override fun onMethodEnter() {
                super.onMethodEnter()
            }

            override fun onMethodExit(opcode: Int) {
                super.onMethodExit(opcode)
            }
        }
    }
}

asm的代码怎么写呢,别急,弄个工具类TimeUtil,启动插件。

public class TimeUtil {

    public void handler() {
        TimeManager.start("", System.currentTimeMillis());
        TimeManager.end("", System.currentTimeMillis());
        long currentTimeMills = TimeManager.current("");
    }
}

点个锤子编译一下,查看build中编译后的TimeUtil,右键ASM Bytecode Viewer

TimeUtil.class
直接看生成的asm api还是看不太明白
ASMified
没关系,对应字节码看就很清晰了,切换到Bytecodetab
Bytecode
仔细对照一下,从LDC ""开始对比,asm api和字节码能一一对应。接下来的工作就很简单了,对照字节码去掉无用的label,然后cv大法。

因为这里MethodVisitor使用的AdviceAdapter,onMethodEnter()onMethodExit()就可以很方便的在方法前后插桩。

方法前插入

        TimeManager.start("", System.currentTimeMillis());

onMethodEnter()

            override fun onMethodEnter() {
                mv.visitLdcInsn(name);//方法名
                mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
                mv.visitMethodInsn(INVOKESTATIC, "com/chenxuan/annotation/TimeManager", "start", "(Ljava/lang/String;J)V", false);
                super.onMethodEnter()
            }

方法后插入

        TimeManager.end("", System.currentTimeMillis());
        long currentTimeMills = TimeManager.current("");
        Log.d("chenxuan----->", "Method name total time: " + currentTimeMills + "ms");

onMethodExit()

            override fun onMethodExit(opcode: Int) {
                mv.visitLdcInsn(name)
                mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false)
                mv.visitMethodInsn(INVOKESTATIC, "com/chenxuan/annotation/TimeManager", "end", "(Ljava/lang/String;J)V", false)
                mv.visitLdcInsn(name)
                mv.visitMethodInsn(INVOKESTATIC, "com/chenxuan/annotation/TimeManager", "current", "(Ljava/lang/String;)J", false)
                mv.visitVarInsn(LSTORE, 1)
                mv.visitLdcInsn("chenxuan----->")
                mv.visitTypeInsn(NEW, "java/lang/StringBuilder")
                mv.visitInsn(DUP)
                mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false)
                mv.visitLdcInsn("Method $name total time: ")
                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false)
                mv.visitVarInsn(LLOAD, 1)
                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(J)Ljava/lang/StringBuilder;", false)
                mv.visitLdcInsn("ms")
                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false)
                mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false)
                mv.visitMethodInsn(INVOKESTATIC, "android/util/Log", "d", "(Ljava/lang/String;Ljava/lang/String;)I", false)
                mv.visitInsn(POP)
                super.onMethodExit(opcode)
            }

加个注解Track,只对注解过的方法进行插桩。

@Target({ElementType.METHOD})
public @interface Track {
}

TrackMethodVisitor最终代码

object TrackMethodVisitor {

    operator fun invoke(
        mv: MethodVisitor,
        access: Int,
        name: String?,
        descriptor: String?,
    ): MethodVisitor {
        return object : AdviceAdapter(Opcodes.ASM9, mv, access, name, descriptor) {
            var needTrack = false

            override fun visitAnnotation(descriptor: String?, visible: Boolean): AnnotationVisitor {
                if (Type.getDescriptor(Track::class.java) == descriptor) needTrack = true
                return super.visitAnnotation(descriptor, visible)
            }

            override fun onMethodEnter() {
                if (needTrack){
                    mv.visitLdcInsn("");
                    mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
                    mv.visitMethodInsn(INVOKESTATIC, "com/chenxuan/annotation/TimeManager", "start", "(Ljava/lang/String;J)V", false);
                }
                super.onMethodEnter()
            }

            override fun onMethodExit(opcode: Int) {
                if (needTrack){
                    mv.visitLdcInsn(name)
                    mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false)
                    mv.visitMethodInsn(INVOKESTATIC, "com/chenxuan/annotation/TimeManager", "end", "(Ljava/lang/String;J)V", false)
                    mv.visitLdcInsn(name)
                    mv.visitMethodInsn(INVOKESTATIC, "com/chenxuan/annotation/TimeManager", "current", "(Ljava/lang/String;)J", false)
                    mv.visitVarInsn(LSTORE, 1)
                    mv.visitLdcInsn("chenxuan----->")
                    mv.visitTypeInsn(NEW, "java/lang/StringBuilder")
                    mv.visitInsn(DUP)
                    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false)
                    mv.visitLdcInsn("Method $name total time: ")
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false)
                    mv.visitVarInsn(LLOAD, 1)
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(J)Ljava/lang/StringBuilder;", false)
                    mv.visitLdcInsn("ms")
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false)
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false)
                    mv.visitMethodInsn(INVOKESTATIC, "android/util/Log", "d", "(Ljava/lang/String;Ljava/lang/String;)I", false)
                    mv.visitInsn(POP)
                }
                super.onMethodExit(opcode)
            }
        }
    }
}

测试一下MainActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        trackMethod()
    }

    @Track
    private fun trackMethod() {
        val data = mutableListOf<String>()
        Thread.sleep(50)
    }
}

编译后查看build下transforms文件夹


MainActivity.class

Tools->kotlin反编译成Java


MainActivity
插桩成功,但是有个问题,TimeManager工具类以方法名为key保存方法调用的起始时间、结束时间,不太优雅。而且方法名会重复,当然也可以做一下优化,key拼接下类名,但是同一个类多个对象还是会重复,虽然可以继续优化,但是最好的做法肯定是用局部变量。
public class TimeUtil {

    public void handler() {
        long start = System.currentTimeMillis();
        long end = System.currentTimeMillis();
        long currentTimeMills = end - start;
        Log.d("chenxuan----->", "Method name total time: " + currentTimeMills + "ms");
    }
}

老样子,编译后查看TimeUtil.class,然后使用插件。


ASMified

嗯,对照Bytecode,cv到TrackMethodVisitor

object TrackMethodVisitor {

    operator fun invoke(
        mv: MethodVisitor,
        access: Int,
        name: String?,
        descriptor: String?,
    ): MethodVisitor {
        return object : AdviceAdapter(Opcodes.ASM9, mv, access, name, descriptor) {
            var needTrack = false

            override fun visitAnnotation(descriptor: String?, visible: Boolean): AnnotationVisitor {
                if (Type.getDescriptor(Track::class.java) == descriptor) needTrack = true
                return super.visitAnnotation(descriptor, visible)
            }

            override fun onMethodEnter() {
                if (needTrack) {
                    mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
                    mv.visitVarInsn(LSTORE, 1);
                }
                super.onMethodEnter()
            }

            override fun onMethodExit(opcode: Int) {
                if (needTrack) {
                    mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
                    mv.visitVarInsn(LSTORE, 3);
                    mv.visitVarInsn(LLOAD, 3);
                    mv.visitVarInsn(LLOAD, 1);
                    mv.visitInsn(LSUB);
                    mv.visitVarInsn(LSTORE, 5);
                    mv.visitLdcInsn("chenxuan----->");
                    mv.visitTypeInsn(NEW, "java/lang/StringBuilder");
                    mv.visitInsn(DUP);
                    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false);
                    mv.visitLdcInsn("Method name total time: ");
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
                    mv.visitVarInsn(LLOAD, 5);
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(J)Ljava/lang/StringBuilder;", false);
                    mv.visitLdcInsn("ms");
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false);
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false);
                    mv.visitMethodInsn(INVOKESTATIC, "android/util/Log", "d", "(Ljava/lang/String;Ljava/lang/String;)I", false);
                    mv.visitInsn(POP);
                }
                super.onMethodExit(opcode)
            }
        }
    }
}

build不出意外会报错。MainActivity中的track()有一行

val data = mutableListOf<String>()

回看上面的asm中插入两个局部变量的代码

            override fun onMethodEnter() {
                if (needTrack) {
                    mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
                    mv.visitVarInsn(LSTORE, 1);
                }
                super.onMethodEnter()
            }

             override fun onMethodExit(opcode: Int) {
                if (needTrack) {
                    mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false);
                    mv.visitVarInsn(LSTORE, 3);
                }
                super.onMethodExit(opcode)
            }
        }

LSTORE在方法前插入1的位置,方法后插入3,这个可没有考虑到方法体本身也有局部变量,在方法后插入局部变量表的理想操作是先拿到表的长度N,然后mv.visitVarInsn(LSTORE, N+2);。理想很丰满现实很骨感,搜索一番没有找到获取局部变量表长度的api,有点裂开了。好在之前有不少大佬写过这种东西,面向google不丢人,“借鉴”了大佬们的写法,最后用newLocal搞定了,先上代码。

object TrackMethodVisitor {

    operator fun invoke(
        mv: MethodVisitor,
        access: Int,
        name: String?,
        descriptor: String?,
    ): MethodVisitor {
        return object : AdviceAdapter(Opcodes.ASM9, mv, access, name, descriptor) {
            var needTrack = false
            var startTimeMills = -1

            override fun visitAnnotation(descriptor: String?, visible: Boolean): AnnotationVisitor {
                if (Type.getDescriptor(Track::class.java) == descriptor) needTrack = true
                return super.visitAnnotation(descriptor, visible)
            }

            override fun onMethodEnter() {
                if (needTrack) {
                    startTimeMills = newLocal(Type.LONG_TYPE)
                    mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false)
                    mv.visitIntInsn(LSTORE, startTimeMills)
                }
                super.onMethodEnter()
            }

            override fun onMethodExit(opcode: Int) {
                if (needTrack) {
                    val durationTimeMills = newLocal(Type.LONG_TYPE)
                    mv.visitMethodInsn(INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false)
                    mv.visitVarInsn(LLOAD, startTimeMills)
                    mv.visitInsn(LSUB)
                    mv.visitVarInsn(LSTORE, durationTimeMills)
                    mv.visitLdcInsn("chenxuan----->")
                    mv.visitTypeInsn(NEW, "java/lang/StringBuilder")
                    mv.visitInsn(DUP)
                    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false)
                    mv.visitLdcInsn("Method $name total time: ")
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false)
                    mv.visitVarInsn(LLOAD, durationTimeMills)
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(J)Ljava/lang/StringBuilder;", false)
                    mv.visitLdcInsn("ms")
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false)
                    mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false)
                    mv.visitMethodInsn(INVOKESTATIC, "android/util/Log", "d", "(Ljava/lang/String;Ljava/lang/String;)I", false)
                    mv.visitInsn(POP);
                }
                super.onMethodExit(opcode)
            }
        }
    }
}

说人话:startTimeMills记录了插入的位置mv.visitIntInsn(LSTORE, startTimeMills),然后计算结束时间end;取出startTimeMills,end与其相减,插入局部变量表,记录一下durationTimeMills;后面拼接string的时候mv.visitVarInsn(LLOAD, durationTimeMills)取出duration。好起来了,接下来编译看一下成果。

MainActivity
没啥问题,按照这个思路卷一卷岂不是美滋滋。

相关文章

  • ASM学习思路

    关于AOP、Plugin、Transform的概念,大家都卷到这个份上了,就不再细说了。撸个经典的demo,方法耗...

  • ASM统一线程池

    ASM学习思路[https://www.jianshu.com/p/4d3d86929611]ASM图片监控hoo...

  • ASM图片监控hook glide

    ASM学习思路[https://www.jianshu.com/p/4d3d86929611]承接上篇,对照字节码...

  • 05 - 如何编写ASM代码

    在刚开始学习ASM的时候,编写ASM代码是不太容易的。或者,有些人原来对ASM很熟悉,但由于长时间不使用ASM,编...

  • 学习自定义Gradle插件2

    前序步骤参考链接:学习自定义gradle插件 使用 ASM,插入字节码到 Activity 文件 1.在 asm_...

  • ASM files number 10 and 11

    ASM metadata file number 10 is ASM user directory and ASM...

  • C代码中嵌入汇编代码

    内嵌汇编语法 同时 “asm” 也可以由 “__asm__” 来代替,“asm” 是 “__asm__” 的别名。...

  • ASM学习小结

    一个最简单的java程序 public class HelloWorld { public static void...

  • ASM 学习笔记

    参考 https://asm.ow2.io/documentation.html[https://asm.ow2....

  • ORA-00099: warning: no parameter

    问题现象:启动ora.cssd正常,但是起ASM实例报错ORA-00099。 解决思路及方法: 查看crs及所有的...

网友评论

      本文标题:ASM学习思路

      本文链接:https://www.haomeiwen.com/subject/oppbzltx.html