天天看点

深入ASM源码之ClassReader、ClassVisitor、ClassWriter

<a href="http://www.blogjava.net/dlevin/archive/2014/06/25/414292.html">深入asm源码之classreader、classvisitor、classwriter</a>

asm是java中比较流行的用来读写字节码的类库,用来基于字节码层面对代码进行分析和转换。在读写的过程中可以加入自定义的逻辑以增强或修改原来已编译好的字节码,比如cglib用它来实现动态代理。asm被设计用于在运行时对java类进行生成和转换,当然也包括离线处理。asm短小精悍、且速度很快,从而避免在运行时动态生成字节码或转换时对程序速度的影响,又因为它体积小巧,可以在很多内存受限的环境中使用。

asm的主要优势包括如下几个方面:

1. 它又一个很小,但设计良好并且模块化的api,且易于使用。

2. 它具有很好的文档,并且还有eclipse插件。

3. 它支持最新的java版本。

4. 它短小精悍、快速、健壮。

5. 它又一个很大的用户社区,可以给新用户提供支持。

6. 它的开源许可允许你几乎以任何方式来使用它。

在asm的核心实现中,它主要有以下几个类、接口(在org.objectweb.asm包中):

classreader类:字节码的读取与分析引擎。它采用类似sax的事件读取机制,每当有事件发生时,调用注册的classvisitor、annotationvisitor、fieldvisitor、methodvisitor做相应的处理。

classvisitor接口:定义在读取class字节码时会触发的事件,如类头解析完成、注解解析、字段解析、方法解析等。

annotationvisitor接口:定义在解析注解时会触发的事件,如解析到一个基本值类型的注解、enum值类型的注解、array值类型的注解、注解值类型的注解等。

fieldvisitor接口:定义在解析字段时触发的事件,如解析到字段上的注解、解析到字段相关的属性等。

methodvisitor接口:定义在解析方法时触发的事件,如方法上的注解、属性、代码等。

classwriter类:它实现了classvisitor接口,用于拼接字节码。

annotationwriter类:它实现了annotationvisitor接口,用于拼接注解相关字节码。

fieldwriter类:它实现了fieldvisitor接口,用于拼接字段相关字节码。

methodwriter类:它实现了methodvisitor接口,用于拼接方法相关字节码。

signaturereader类:对类定义、字段定义、方法定义、本地变量定义的签名的解析。signature因范型引入,用于存储范型定义时的元数据(因为这些元数据在运行时会被擦除)。

signaturevisitor接口:定义在解析signature时会触发的事件,如正常的type参数、类或接口的边界等。

signaturewriter类:它实现了signaturevisitor接口,用于拼接范型相关字节码。

attribute类:字节码中属性的类抽象。

bytevector类:字节码二进制存储的容器。

opcodes接口:字节码指令的一些常量定义。

type类:类型相关的常量定义以及一些基于其上的操作。

他们之间的类图关系如下:

深入ASM源码之ClassReader、ClassVisitor、ClassWriter

在构建classreader实例时,它首先保存字节码二进制数组b,然后创建items数组,数组的长度在字节码数组的第8、9个字节指定(最前面4个字节是魔数cafebabe,之后2个字节是次版本号,再后2个字节是主版本号),每个item表示常量池项在字节码数组的偏移量加1(常量池中每个项由1个字节的type和紧跟的字节数组表示,常量池项有12种类型,其中constant_fieldref_info、constant_methodref_info、constant_interfacemethodref_info、constant_nameandtype_info包括其类型字节占用5个字节,另外4个字节每2个字节为字段、方法等所在的类、其名称、描述符在当前常量池中constant_utf8_info类型的引用;constant_integer_info、constant_float_info包括其类型字节占用5个字节,另外四个字节为其对应的值;constant_class_info、constant_string_info包括其类型字节占用3个字节,另外两个字节为在当前常量池constant_utf8_info项的索引;constant_utf8_info类型第1个字节表示类型,第2、3个字节为该项所表示的字符串的长度);constant_double_info、constant_long_info加类型字节为9个字;maxstringlength表示最长的utf8类型的常量池项的值,用于决定在解析constant_utf8_info类型项时最大需要的字符数组;header表示常量池之后的字节码的第一个字节。

在调用classreader的accept方法时,它解析字节码中常量池之后的所有元素。紧接着常量池的2个字节是该类的access标签:acc_public、acc_final等;之后2个字节为当前类名在常量池constant_utf8_info类型的索引;之后2个字节为其父类名在常量池constant_utf8_info类型的索引(索引值0表示父类为null,即直接继承自object类);再之后为其实现的接口数长度和对应各个接口名在常量池中constant_utf8_info类型的索引值;暂时先跳过field和method定义信息,解析类的attribute表,它用两个字节表达attribute数组的长度,每个attribute项中最前面2个字节是attribute名称:sourcefile(读取sourcefile值)、innerclasses(暂时纪录起始索引)、enclosingmethod(纪录当前匿名类、本地类包含者类名以及包含者的方法名和描述符)、signature(类的签名信息,用于范型)、runtimevisibleannotations(暂时纪录起始索引)、deprecated(表识属性)、synthetic(标识属性)、sourcedebugextension(为调试器提供的自定义扩展信息,读取成一个字符串)、runtimeinvisibleannotations(暂时纪录起始索引),对其他不识别的属性,纪录成attribute链,如果attribute名称符合在accept中attribute数组中指定的attribute名,则替换传入的attribute数组对应的项;根据解析出来的信息调用以下visit方法:

void visit(int version, int access, string name, string signature, string supername, string[] interfaces);

// sourcefile, sourcedebug

void visitsource(string source, string debug);

// enclosingmethod attribute: enclosingowner, enclosingname, enclosingdesc. 

// note: only when the class has enclosingmethod attribute, meaning the class is a local class or an anonymous class

void visitouterclass(string owner, string name, string desc);

依次解析runtimevisibleannotations和runtimeinvisibleannotations属性,首先解析定义的annotation的描述符以及运行时可见flag,返回用户自定义的annotationvisitor:

annotationvisitor visitannotation(string desc, boolean visible);

对每个定义的annotation,解析其键值对,并根据不同的annotation字段值调用annotationvisitor中的方法,在所有解析结束后,调用annotationvisitor.visitend方法:

public interface annotationvisitor {

    // 对基本类型的数组,依然采用该方法,visitarray只是在非基本类型时调用。

    void visit(string name, object value);

    void visitenum(string name, string desc, string value);

    annotationvisitor visitannotation(string name, string desc);

    annotationvisitor visitarray(string name);

    void visitend();

}

之前解析出的attribute链表(非标准的attribute定义),对每个attribute实例,调用classvisitor中的visitattribute方法:

void visitattribute(attribute attr);

attribute类包含type字段和一个字节数组:

public class attribute {

    public final string type;

    byte[] value;

    attribute next;

对每个innerclasses属性,解析并调用classvisitor的visitinnerclass方法(该属性事实上保存了所有其直接内部类以及它本身到最顶层类的路径):

void visitinnerclass(string name, string outername, string innername, int access);

解析字段,它紧跟接口数组定义之后,最前面的2个字节为字段数组的长度,对每个字段,前面2个字节为访问flag定义,再后2个字节为name索引,以及2个字节的描述符索引,然后解析其attribute信息:constantvalue、signature、deprecated、synthetic、runtimevisibleannotations、runtimeinvisibleannotations以及非标准定义的attribute链,而后调用classvisitor的visitfield方法,返回fieldvisitor实例:

// 其中value为静态字段的初始化值(对非静态字段,它的初始化必须由构造函数实现),如果没有初始化值,该值为null。

fieldvisitor visitfield(int access, string name, string desc, string signature, object value);

对返回的fieldvisitor依次对其annotation以及非标准attribute解析,调用其visit方法,并在完成后调用它的visitend方法:

public interface fieldvisitor {

    annotationvisitor visitannotation(string desc, boolean visible);

    void visitattribute(attribute attr);

解析方法定义,它紧跟字段定义之后,最前面的2个字节为方法数组长度,对每个方法,前面2个字节为访问flag定义,再后2个字节为name索引,以及2个字节的方法描述符索引,然后解析其attribute信息:code、exceptions、signature、deprecated、runtimevisibleannotations、annotationdefault、synthetic、runtimeinvisibleannotations、runtimevisibleparameterannotations、runtimeinvisibleparameterannotations以及非标准定义的attribute链,如果存在exceptions属性,解析其异常类数组,之后调用classvisitor的visitmethod方法,返回methodvisitor实例:

methodvisitor visitmethod(int access, string name, string desc, string signature, string[] exceptions);

annotationdefault为对annotation定义时指定默认值的解析;然后依次解析runtimevisibleannotations、runtimeinvisibleannotations、runtimevisibleparameterannotations、runtimeinvisibleparameterannotations等属性,调用相关annotationvisitor的visit方法;对非标准定义的attribute链,依次调用methodvisitor的visitattribute方法:

public interface methodvisitor {

    annotationvisitor visitannotationdefault();

    annotationvisitor visitparameterannotation(int parameter, string desc, boolean visible);

对code属性解析,读取2个字节的最深栈大小、最大local变量数、code占用字节数,调用methodvisitor的visitcode()方法表示开始解析code属性,对每条指令,创建一个label实例并构成label数组,解析code属性中的异常表,对每个异常项,调用visittrycatchblock方法:

void visittrycatchblock(label start, label end, label handler, string type);

label包含以下信息:

/**

 * a label represents a position in the bytecode of a method. labels are used

 * for jump, goto, and switch instructions, and for try catch blocks.

 * 

 * @author eric bruneton

 */

public class label {

    public object info;

    int status;

    int line;

    int position;

    private int referencecount;

    private int[] srcandrefpositions;

    int inputstacktop;

    int outputstackmax;

    frame frame;

    label successor;

    edge successors;

    label next;

解析code属性中的内部属性信息:localvariabletable、localvariabletypetable、linenumbertable、stackmaptable、stackmap以及非标准定义的attribute链,对每个label调用其visitlinenumber方法以及对每个frame调用visitframe方法,并且对相应的指令调用相应的方法:

void visitframe(int type, int nlocal, object[] local, int nstack, object[] stack);

// visits a zero operand instruction.

void visitinsn(int opcode);

// visits an instruction with a single int operand.

void visitintinsn(int opcode, int operand);

// visits a local variable instruction. a local variable instruction is an instruction that loads or stores the value of a local variable.

void visitvarinsn(int opcode, int var);

// visits a type instruction. a type instruction is an instruction that takes the internal name of a class as parameter.

void visittypeinsn(int opcode, string type);

// visits a field instruction. a field instruction is an instruction that loads or stores the value of a field of an object.

void visitfieldinsn(int opcode, string owner, string name, string desc);

// visits a method instruction. a method instruction is an instruction that invokes a method.

void visitmethodinsn(int opcode, string owner, string name, string desc);

// visits a jump instruction. a jump instruction is an instruction that may jump to another instruction.

void visitjumpinsn(int opcode, label label);

// visits a label. a label designates the instruction that will be visited just after it.

void visitlabel(label label);

// visits a ldc instruction.

void visitldcinsn(object cst);

// visits an iinc instruction.

void visitiincinsn(int var, int increment);

// visits a tableswitch instruction.

void visittableswitchinsn(int min, int max, label dflt, label[] labels);

// visits a lookupswitch instruction.

void visitlookupswitchinsn(label dflt, int[] keys, label[] labels);

// visits a multianewarray instruction.

void visitmultianewarrayinsn(string desc, int dims);

// visits a try catch block.

void visitlocalvariable(string name, string desc, string signature, label start, label end, int index);

// visits a line number declaration.

void visitlinenumber(int line, label start);

// visits the maximum stack size and the maximum number of local variables of the method.

void visitmaxs(int maxstack, int maxlocals);

最后调用classvisitor的visitend方法:

void visitend();

classwriter继承自classvisitor接口,可以使用它调用其相应的visit方法动态的构造一个字节码类。它包含以下字段信息:

public class classwriter implements classvisitor {

    //the class reader from which this class writer was constructed, if any.

    classreader cr;

    //minor and major version numbers of the class to be generated.

    int version;

    //index of the next item to be added in the constant pool.

    int index;

    //the constant pool of this class.

    final bytevector pool;

    //the constant pool's hash table data.

    item[] items;

    //the threshold of the constant pool's hash table.

    int threshold;

    //a reusable key used to look for items in the {@link #items} hash table.

    final item key;

    final item key2;

    final item key3;

    //a type table used to temporarily store internal names that will not necessarily be stored in the constant pool. 

    item[] typetable;

    //number of elements in the {@link #typetable} array.

    private short typecount;

    //the access flags of this class.

    private int access;

    //the constant pool item that contains the internal name of this class.

    private int name;

    //the internal name of this class.

    string thisname;

    //the constant pool item that contains the signature of this class.

    private int signature;

    //the constant pool item that contains the internal name of the super class of this class.

    private int supername;

    // number of interfaces implemented or extended by this class or interface.

    private int interfacecount;

    //the interfaces implemented or extended by this class or interface. 

    private int[] interfaces;

    //the index of the constant pool item that contains the name of the source file from which this class was compiled.

    private int sourcefile;

    //the sourcedebug attribute of this class.

    private bytevector sourcedebug;

    //the constant pool item that contains the name of the enclosing class of this class.

    private int enclosingmethodowner;

    //the constant pool item that contains the name and descriptor of the enclosing method of this class.

    private int enclosingmethod;

    //the runtime visible annotations of this class.

    private annotationwriter anns;

    //the runtime invisible annotations of this class.

    private annotationwriter ianns;

    //the non standard attributes of this class.

    private attribute attrs;

    //the number of entries in the innerclasses attribute.

    private int innerclassescount;

    //the innerclasses attribute.

    private bytevector innerclasses;

    //the fields of this class. these fields are stored in a linked list of {@link fieldwriter} objects, linked to each other by their {@link fieldwriter#next} field. this field stores the first element of this list.

    fieldwriter firstfield;

    //this field stores the last element of this list.

    fieldwriter lastfield;

    //the methods of this class. these methods are stored in a linked list of {@link methodwriter} objects, linked to each other by their {@link methodwriter#next} field. this field stores the first element of this list.

    methodwriter firstmethod;

    methodwriter lastmethod;

    //true if the maximum stack size and number of local variables must be automatically computed.

    private final boolean computemaxs;

    //true if the stack map frames must be recomputed from scratch.

    private final boolean computeframes;

   //true if the stack map tables of this class are invalid. 

    boolean invalidframes;

继续阅读