Home  >  Article  >  Java  >  Example of method to implement Class parser in Java

Example of method to implement Class parser in Java

黄舟
黄舟Original
2017-09-15 10:16:001257browse

This article mainly introduces examples of Java Class parser implementation methods through the analysis of class files. It has certain reference value and friends in need can learn about it.

Recently I am writing a private project called ClassAnalyzer. The purpose of ClassAnalyzer is to give us an in-depth understanding of the design and structure of Java Class files. The main 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 a carrier of class or interface information, each Class file completely defines a class. In order to make Java programs "write once and run anywhere", the Java virtual machine specification has strict regulations on Class files. The basic data unit that constitutes a Class file is bytes. There are no separators between these bytes. This makes the content stored in the entire Class file almost all necessary data for program operation. Data that cannot be represented by a single byte is represented by multiple represented by 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. There are only two data types in this pseudo-structure: unsigned numbers and tables. The Java virtual machine specification defines u1, u2, u4 and u8 to represent unsigned numbers of 1 byte, 2 bytes, 4 bytes and 8 bytes respectively. Unsigned numbers can be used to describe numbers and indexes. A reference, quantity, or string. A table is a composite data type composed of multiple unsigned numbers or other tables as data items. The table is used to describe data with a hierarchical composite structure, so the entire Class file is essentially a table. In ClassAnalyzer, byte, short, int and long correspond to u1, u2, u4 and u8 data types respectively. 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 and the version of the Class file Data items, access flags, class indexes, and parent class indexes all 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, there are mainly four parts that need to be handled flexibly: 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, method names, etc. The Java virtual machine specification defines multiple constant types, each of which 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 u1 type tag.


The constant pool size (constantPoolCount) given in the header is 1 larger than the actual value. For example, if constantPoolCount is 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 equals 47, then the index range of the constant pool is 1~46. The designer's purpose of leaving item 0 empty is to express "not referencing any constant pool item".


The structure of the CONSTANT_Utf8_info constant contains a tag of type u1, a length of type u2 and length bytes of type u1. The continuous data of length bytes is a MUTF-8 (Modified UTF-8) encoded string. 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 found here (variant UTF-8).


Attribute tables are used to describe information specific to certain scenarios. Class files, field tables, and method tables all have corresponding attribute table sets. The Java virtual machine specification defines a variety of attributes, and ClassAnalyzer currently implements the analysis of commonly used attributes. Unlike data items of constant type, attributes do not have a tag to identify the type of the attribute, but each attribute contains an attribute_name_index of type u2. Attribute_name_index points to a constant of type CONSTANT_Utf8_info in the constant pool, which contains the attribute's name. When parsing attributes, ClassAnalyzer knows the type of the attribute through the attribute name corresponding to the constant pointed to by attribute_name_index.


Field table is used to describe variables declared in a class or interface. Fields include class-level variables and instance-level variables. The structure of the field table includes a u2 type access_flags, a u2 type name_index, a u2 type descriptor_index, a u2 type attributes_count and attributes_count attributes_info type attributes. We have already introduced the parsing of attribute tables. The parsing method of attributes is consistent with the parsing method of attribute tables.


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

代码实现

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

The above is the detailed content of Example of method to implement Class parser in Java. 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