Home  >  Article  >  Java  >  Sharing the powerful code to implement a Java Class parser

Sharing the powerful code to implement a Java Class parser

黄舟
黄舟Original
2017-03-18 10:41:322464browse

Recently I am writing a private project called ClassAnalyzer. The purpose of ClassAnalyzer is to allow us to analyze Java Class files. Design and structure can have an in-depth understanding. The main body framework and basic functions have been completed, and some detailed functions will be added in the future. In fact, JDK already provides the command line tool javap to decompile Class files, but this article will clarify my idea of ​​​​implementing the parser.

Class file

As the carrier of class or interface information, each Class file completely defines a class. In order to make Java programs "write once and run everywhere", the Java virtual machine specification has strict regulations on Class files. The basic data unit that constitutes the Class file is bytes, and there are no delimiters between these bytes. This makes almost all the content stored in the entire Class file necessary for the program to run. Data that cannot be represented by a single byte is represented by multiple consecutive bytes.

According to the Java virtual machine specification, the Class file uses a pseudo structure similar to the C language structure to store data. This pseudo structure There are only two data types in the structure: unsigned numbers and tables. Java The virtual machine specification defines u1, u2, u4 and u8 to represent 1 respectively. Unsigned numbers of bytes, 2 bytes, 4 bytes and 8 bytes, unsigned numbers can be used Description number, indexreference, quantity value or string. A table is a conforming data type composed of multiple unsigned numbers or other tables as data items. The table is used to describe structured data with hierarchical relationships, so the entire Class file is essentially a table. In ClassAnalyzer u1, u2, u4 and u8 respectively correspond to byte , short, int and long, the Class file is described as the following Java class.

public class ClassFile {

    public U4 magic;                            // magic
    public U2 minorVersion;                     // minor_version
    public U2 majorVersion;                     // major_version
    public U2 constantPoolCount;                // constant_pool_count
    public ConstantPoolInfo[] cpInfo;           // cp_info
    public U2 accessFlags;                      // access_flags
    public U2 thisClass;                        // this_class
    public U2 superClass;                       // super_class
    public U2 interfacesCount;                  // interfaces_count
    public U2[] interfaces;                     // interfaces
    public U2 fieldsCount;                      // fields_count
    public FieldInfo[] fields;                  // fields
    public U2 methodsCount;                     // methods_count
    public MethodInfo[] methods;                // methods
    public U2 attributesCount;                  // attributes_count
    public BasicAttributeInfo[] attributes;     // attributes

}

How to parse the various data items that make up the

Class

file, such as the magic number, the version of the Class file, and other data items, access flags , class index, parent class index, they occupy a fixed number of bytes in each Class file, and only the corresponding number of bytes need to be read during parsing. In addition, the main parts that need to be handled flexibly include 4: constant pool, field table collection, method table collection and attribute table collection. Fields and methods can have their own attributes, and Class itself also has corresponding attributes. Therefore, parsing the field table collection and method table collection also includes the parsing of the attribute table. The constant pool occupies a large part of the data in the

Class

file and is used to store all constant information, including numeric and string constants, class names, interface names, field names and method names, etc. . JavaThe virtual machine specification defines multiple constant types, and each constant type has its own structure. The constant pool itself is a table, and there are several points to pay attention to when parsing it.

    Each constant type is identified by a tag of type
  • u1

    .

  • The constant pool size (
  • constantPoolCount

    ) given in the header is 1 larger than the actual size, for example, if constantPoolCount Equal to 47, then there are 46 constants in the constant pool.

  • The index range of the constant pool starts from
  • 1

    . For example, if constantPoolCount is equal to 47, then the index range of the constant pool The index range is 1~46. The designer left the 0 item empty to express "not referencing any constant pool item". The structure of the

  • CONSTANT_Utf8_info

    type constant contains the tag and u2 types of the u1 type. The length and bytes composed of length u1 types, this length bytes of continuous data is A string encoded using MUTF-8 (Modified UTF-8). MUTF-8 is not compatible with UTF-8. There are two main differences: First, the null character will be encoded into 2 Bytes (0xC0 and 0x80); second, the supplementary characters are split into surrogate pairs and encoded separately according to UTF-16. The relevant details can be seen here ( variant UTF-8).

属性表用于描述某些场景专有的信息,Class文件、字段表和方法表都有相应的属性表集合。Java虚拟机规范定义了多种属性,ClassAnalyzer目前实现了对常用属性的解析。和常量类型的数据项不同,属性并没有一个tag来标识属性的类型,但是每个属性都包含有一个u2类型的attribute_name_indexattribute_name_index指向常量池中的一个CONSTANT_Utf8_info类型的常量,该常量包含着属性的名称。在解析属性时,ClassAnalyzer正是通过attribute_name_index指向的常量对应的属性名称来得知属性的类型。

字段表用于描述类或者接口中声明的变量,字段包括类级变量以及实例级变量。字段表的结构包含一个u2类型的access_flags、一个u2类型的name_index、一个u2类型的descriptor_index、一个u2类型的attributes_countattributes_countattribute_info类型的attributes。我们已经介绍了属性表的解析,attributes的解析方式与属性表的解析方式一致。

Class的文件方法表采用了和字段表相同的存储格式,只是access_flags对应的含义有所不同。方法表包含着一个重要的属性:Code属性。Code属性存储了Java代码编译成的字节码指令,在ClassAnalyzer中,Code对应的Java类如下所示(仅列出了类属性)。

public class Code extends BasicAttributeInfo {

    private short maxStack;
    private short maxLocals;
    private long codeLength;
    private byte[] code;
    private short exceptionTableLength;
    private ExceptionInfo[] exceptionTable;
    private short attributesCount;
    private BasicAttributeInfo[] attributes;
    ...

    private class ExceptionInfo {
        public short startPc;
        public short endPc;
        public short handlerPc;
        public short catchType;
          ...
    }
}

Code属性中,codeLengthcode分别用于存储字节码长度和字节码指令,每条指令即一个字节(u1类型)。在虚拟机执行时,通过读取code中的一个个字节码,并将字节码翻译成相应的指令。另外,虽然codeLength是一个u4类型的值,但是实际上一个方法不允许超过65535条字节码指令。

代码实现

ClassAnalyzer的源码已放在了GitHub上。在ClassAnalyzer的README中,我以一个类的Class文件为例,对该Class文件的每个字节进行了分析,希望对大家的理解有所帮助。

The above is the detailed content of Sharing the powerful code to implement a Java Class parser. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn