ASM修改class信息

Stella981
• 阅读 629

Java asm修改class信息

[TOC]

1 asm中提供了ClassReader和ClassVisitor用来获取class信息,如果要修改class信息就要用到ClassWriter

1.1 ClassWriter的构造方法

public ClassWriter(final int flags)
public ClassVisitor(final int api, final ClassVisitor cv)

2 BusIndex.class反编译后的代码为

public final class BusIndex extends a {
    public BusIndex() {
    }

    public d generateSubscribeMethodIndex(Object var1) {
        d var2 = new d();
        Class var3 = var1.getClass();
        Class var4 = null;
        Class var5 = null;
        String var6 = null;
        if(var3 == MainActivity.class) {
            var4 = com.sample.app.MainActivity.a.class;
            var5 = com.a.a.d.a.class;
            var6 = "showMessage";
            var2.a(var6, var4, var5, new com.eventbus.gen.a(this, var1, var6, var4, var5));
            var4 = com.sample.app.MainActivity.a.class;
            var5 = com.a.a.d.a.class;
            var6 = "showMessagedd";
            var2.a(var6, var4, var5, new b(this, var1, var6, var4, var5));
            return var2;
        } else if(var3 == Main2Activity.class) {
            var4 = com.sample.app.MainActivity.a.class;
            var5 = com.a.a.d.a.class;
            var6 = "showMessage";
            var2.a(var6, var4, var5, new c(this, var1, var6, var4, var5));
            var4 = com.sample.app.MainActivity.a.class;
            var5 = com.a.a.d.a.class;
            var6 = "showMessagedd";
            var2.a(var6, var4, var5, new com.eventbus.gen.d(this, var1, var6, var4, var5));
            return var2;
        } else {
            return var2;
        }
    }
}

3 使用asm将generateSubscribeMethodIndex方法中String变量的值都加上前缀

3.1 首先加载BusIndex.class

ClassReader classReader = new ClassReader(BusIndex.class.getName());

3.2 使用ClassReader的accept方法查找generateSubscribeMethodIndex方法

如果有多个generateSubscribeMethodIndex重载方法,查找方法时必须验证方法的 desc signature等其他参数

ClassReader classReader = new ClassReader(BusIndex.class.getName());
classReader.accept(new ClassVisitorAdapter(null), 0);

public class ClassVisitorAdapter extends ClassVisitor {

    public ClassVisitorAdapter(ClassWriter classWriter) {
        super(Opcodes.ASM6, classWriter);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions);
        if (name.equals("generateSubscribeMethodIndex")) {
            //methodVisitor = new MethodVisitorAdapter(methodVisitor);
            return methodVisitor;
        }

        return methodVisitor;
    }
}

3.3 使用自定义MethodVisitor遍历generateSubscribeMethodIndex方法的具体信息

public class ClassVisitorAdapter extends ClassVisitor {

    public ClassVisitorAdapter(ClassWriter classWriter) {
        super(Opcodes.ASM6, classWriter);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions);
        if (name.equals("generateSubscribeMethodIndex")) {
            methodVisitor = new MethodVisitorAdapter(methodVisitor);
            return methodVisitor;
        }

        return methodVisitor;
    }
}

public class MethodVisitorAdapter extends MethodVisitor {
    public MethodVisitorAdapter(MethodVisitor methodVisitor) {
        super(Opcodes.ASM6, methodVisitor);
    }


    @Override
    public void visitCode() {
        super.visitCode();
        System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());

    }


    @Override
    public void visitEnd() {
        super.visitEnd();
        System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName());

        System.out.println(csts);
    }


    @Override
    public void visitInsn(int opcode) {
        super.visitInsn(opcode);
        System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + ", opcode:" + Optcodes.options.get(opcode));

    }


    @Override
    public void visitJumpInsn(int opcode, Label label) {
        super.visitJumpInsn(opcode, label);
        System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + ", opcode:" + Optcodes.options.get(opcode));
    }

    @Override
    public void visitLdcInsn(Object cst) {
        System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + ", cst:" + cst);

    }

    @Override
    public void visitMaxs(int maxStack, int maxLocals) {
        System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName() + " ,maxstack:" + maxStack);

        super.visitMaxs(maxStack, maxLocals);
    }

}

3.4 运行查看输出结果

visitCode
visitInsn, opcode:DUP
visitInsn, opcode:ACONST_NULL
visitInsn, opcode:ACONST_NULL
visitInsn, opcode:ACONST_NULL
visitLdcInsn, cst:Lcom/sample/app/MainActivity;
visitJumpInsn, opcode:IF_ACMPNE
visitLdcInsn, cst:Lcom/sample/app/MainActivity$a;
visitLdcInsn, cst:Lcom/a/a/d/a;
visitLdcInsn, cst:showMessage
visitInsn, opcode:DUP
visitLdcInsn, cst:Lcom/sample/app/MainActivity$a;
visitLdcInsn, cst:Lcom/a/a/d/a;
visitLdcInsn, cst:showMessagedd
visitInsn, opcode:DUP
visitInsn, opcode:ARETURN
visitLdcInsn, cst:Lcom/sample/app/Main2Activity;
visitJumpInsn, opcode:IF_ACMPNE
visitLdcInsn, cst:Lcom/sample/app/MainActivity$a;
visitLdcInsn, cst:Lcom/a/a/d/a;
visitLdcInsn, cst:showMessage
visitInsn, opcode:DUP
visitLdcInsn, cst:Lcom/sample/app/MainActivity$a;
visitLdcInsn, cst:Lcom/a/a/d/a;
visitLdcInsn, cst:showMessagedd
visitInsn, opcode:DUP
visitInsn, opcode:ARETURN
visitInsn, opcode:ARETURN
visitMaxs ,maxstack:11
visitEnd

3.5 输出的结果中可以看到visitLdcInsn 指令给变量的赋值操作

visitLdcInsn, cst:Lcom/sample/app/MainActivity$a;
visitLdcInsn, cst:Lcom/a/a/d/a;
visitLdcInsn, cst:showMessage

visitLdcInsn, cst:Lcom/sample/app/MainActivity$a;
visitLdcInsn, cst:Lcom/a/a/d/a;
visitLdcInsn, cst:showMessagedd

visitLdcInsn, cst:Lcom/sample/app/Main2Activity;

visitLdcInsn, cst:Lcom/sample/app/MainActivity$a;
visitLdcInsn, cst:Lcom/a/a/d/a;
visitLdcInsn, cst:showMessage

visitLdcInsn, cst:Lcom/sample/app/MainActivity$a;
visitLdcInsn, cst:Lcom/a/a/d/a;
visitLdcInsn, cst:showMessagedd

3.6 MethodVisitorAdapter的visitLdcInsn方法中获取cst的类型

if(cst instanceof Type){
   System.out.println("cst value type:"+((Type)cst).getClassName());
}else {
    System.out.println("cst value type:"+cst.getClass());
}

3.7 在MethodVisitorAdapter的visitLdcInsn方法中给showMessage开头并且为String类型的cst加上前缀modify,然后通过父类的visitLdcInsn写回class

if (cst instanceof String) {
      if(cst != null && cst.toString().startsWith("showMessage")){
          super.visitLdcInsn("modify"+cst);
      }else{ 
          super.visitLdcInsn(cst);
      }
} else {
   super.visitLdcInsn(cst);
}

3.8 ClassReader遍历class信息时传入ClassWriter,并输出修改后的class

ClassReader classReader = new ClassReader(BusIndex.class.getName());
ClassWriter classWriter = new ClassWriter(0);
classReader.accept(new ClassVisitorAdapter(classWriter), 0);
System.out.println("修改后的字节码:\n"+new String(classWriter.toByteArray()));

3.9 输出结果

修改后的字节码:
����   3 6   com/eventbus/gen/BusIndex    com/a/a/c/a    
SourceFile   com/eventbus/gen/d     com/eventbus/gen/c    com/eventbus/gen/b 
   com/eventbus/gen/a    com/sample/app/MainActivity$a     com/sample/app/MainActivity     a   <init>   ()V    
       generateSubscribeMethodIndex  !(Ljava/lang/Object;)Lcom/a/a/c/d;  com/a/a/c/d  
       java/lang/Object    getClass   ()Ljava/lang/Class;    
      com/a/a/d/a "   modifyshowMessage $  d(Lcom/eventbus/gen/BusIndex;Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/Class;)V   &
 '  D(Ljava/lang/String;Ljava/lang/Class;Ljava/lang/Class;Lcom/a/a/b/a;)V   )
   *   modifyshowMessagedd ,
  '   com/sample/app/Main2Activity/
      '

3.10 将修改后的class写入文件

Files.write(Paths.get(System.getProperty("user.dir")+"/BusIndex.class"), classWriter.toByteArray());
System.out.println("修改后的字节码成功保存到:\n"+Paths.get(System.getProperty("user.dir")+"/BusIndex.class"));

3.11 反编译生成的BusIndex.class

public final class BusIndex extends a {
    public BusIndex() {
    }

    public d generateSubscribeMethodIndex(Object var1) {
        d var2 = new d();
        Class var3 = var1.getClass();
        Class var4 = null;
        Class var5 = null;
        String var6 = null;
        if(var3 == MainActivity.class) {
            var4 = com.sample.app.MainActivity.a.class;
            var5 = com.a.a.d.a.class;
            var6 = "modifyshowMessage";
            var2.a(var6, var4, var5, new com.eventbus.gen.a(this, var1, var6, var4, var5));
            var4 = com.sample.app.MainActivity.a.class;
            var5 = com.a.a.d.a.class;
            var6 = "showMessagedd";
            var2.a(var6, var4, var5, new b(this, var1, var6, var4, var5));
            return var2;
        } else if(var3 == Main2Activity.class) {
            var4 = com.sample.app.MainActivity.a.class;
            var5 = com.a.a.d.a.class;
            var6 = "modifyshowMessage";
            var2.a(var6, var4, var5, new c(this, var1, var6, var4, var5));
            var4 = com.sample.app.MainActivity.a.class;
            var5 = com.a.a.d.a.class;
            var6 = "showMessagedd";
            var2.a(var6, var4, var5, new com.eventbus.gen.d(this, var1, var6, var4, var5));
            return var2;
        } else {
            return var2;
        }
    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
9个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这