Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Class file structure in JVM

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "Class file structure in JVM". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the Class file structure in JVM.

Overview

This paper mainly introduces the main components of Class files, including magic number, version number, constant pool, access flag and so on.

Overview of Class files

According to the JVM specification, a Class file can be described very strictly as:

ClassFile {U4 magic; U2 minor_version; U2 major_version; U2 constant_pool_count; cp_info constant_ Pool [constant _ pool_count-1]; U2 access_flags; U2 this_class; U2 super_class; U2 interfaces_count U2 interfaces [interfaces _ count]; U2 fields_count; field_info fields [fields _ count]; U2 methods_count; method_info methods [methods _ count]; U2 attributes_count; attribute_info attributions [attributes _ count];}

The following is a detailed description of the fields in order.

Magic number

The magic number (Magic Number), as a sign of Class, is used to tell JVM that this is a Class file, and that the magic number is a 4-byte unsigned integer, fixed as 0xCAFEBABE.

Under Linux, you can directly use vim to open a class file for viewing. For example, if you need to open a Test.class file, enter the following command:

Vim-b Test.classvl% classxxd

After switching to hexadecimal, you can see the magic number:

Version

The magic number is followed by a small version and a large version of Class, which indicates which version of the current Class file was generated at compile time.

0000 is a small version number.

0037 is the large version number, and the decimal number is 55, which is the compilation time of the corresponding JDK 11 version.

Constant pool

The version number is followed by the number of constant pools and several constant pool table entries:

Examples of corresponding relations are as follows:

Tag is 3: type is CONSTANT_Integer

Tag is 4: type is CONSTANT_Float

Wait, wait. For example, the structure of CONSTANT_Integer is as follows:

CONSTANT_Integer_info {u1 tag; u4 bytes;}

A tag plus a four-byte unsigned integer. Most of the other types are similar, with space limitations. Please refer to the JVM specification for details.

Access tag

The access tag is represented by two bytes and is used to indicate the access information of this class, such as public/abstract. The corresponding relationship is as follows:

ACC_PUBLIC:0x0001, which represents the public class

ACC_FINAL:0x0010, indicating whether it is a final class

ACC_SUPER:0x0020, which means that the method of the parent class is called using the enhanced method

ACC_INTERFACE:0x0200, indicating whether it is an interface

ACC_ABSTRACT:0x0400, indicating whether it is an abstract class

ACC_SYNTHETIC:0x1000, a class generated at compile time, with no source code correspondence

ACC_ANNOTATION:0x2000, indicating whether it is a comment

ACC_ENUM:0x4000, indicating whether it is an enumeration

Current class, parent class, and interface

The format is as follows:

U2 this_class; u2 super_class;u2 interfaces_count;u2 interfaces[interfaces _ count]

Where this_class and super_class are two-byte unsigned integers pointing to a CONSTANT_Class in the constant pool that represents the current type and parent class. In addition, because a class can implement multiple interfaces, you need to keep the indexes of multiple interfaces as an array, and if no interfaces are implemented, interfaces_count is 0.

Field

The format of the field is as follows:

U2 fields_count;field_info fields[fields _ count]

Fields_count is a 2-byte unsigned integer. The number of fields is followed by specific field information. Each field is a field_info structure, as shown below:

Field_info {U2 access_flags; / / access tag, similar to the access tag of a class, can represent U2 name_index; / / two-byte integers such as public/private/static, pointing to CONSTANT_Utf8 U2 descriptor_index in the constant pool / / is also a two-byte integer, used to describe the field type, and also points to the number of CONSTANT_Utf8 U2 attributes_count; / / attributes in the constant pool [attributes _ count]; / / attributes, such as storing initialization values, some comment information, etc., need to use attribute_info} attribute_info {U2 attribute_name_index / / attribute name, pointing to the constant pool index U4 attribute_length; / / attribute length U1 in [attribute _ length]; / / Information represented by byte array} method 1 method basic structure

The format of the method is as follows:

U2 methods_count;method_info methods[methods _ count]

Each of these method_info structures represents a method:

Method_info {U2 access_flags; / / access tag, marked method is public/private, etc. U2 name_index; / / method name, an index to constant pool U2 descriptor_index / / method descriptor, which is also an index U2 attributes_count; / / number of attributes attribute_info attributes [attributes _ count]; / / attributes, similar to fields, methods can also carry attributes, one attribute quantity + one attribute description array} 2 Code attributes

The main content of the method is stored in the attribute. The most important attribute in the attribute is that Code,Code stores the bytecode and other information of the method. The structure is as follows:

Code_attribute {U2 attribute_name_index; / / attribute name, pointing to the constant pool index U4 attribute_length; / / attribute length, excluding the first 6 bytes (u2+u4) U2 max_stack; / / Operand stack maximum depth U2 max_locals / / the maximum value of the local variable table U4 code_length; / / bytecode length U1 code [code _ length]; / / bytecode content itself U2 exception_table_length; / / exception handling table length {U2 start_pc / / four fields indicate U2 end_pc; / / between the two offsets from start_pc to end_pc / / if an exception U2 handler_pc; / / code pointed to by catch_type is encountered, jump to the handler_pc location to execute U2 catch_type } exception_ table [exception _ table_length]; / / exception table U2 attributes_count; attribute_info attributes [attributes _ count];}

The Code property itself also contains other properties to further store some additional information, mainly including:

LineNumberTable

LocalVariableTable

StackMapTable

2.1 LineNumberTable

LineNumberTable is used to record the relationship between bytecode offset and line number. The structure is as follows:

LineNumberTable_attribute {U2 attribute_name_index; / / Index U4 attribute_length; / / attribute length U2 line_number_table_length; / / number of entries {U2 start_pc pointing to constant pool / / bytecode offset U2 line_number; / / Line number corresponding to bytecode offset} line_number_ table [line _ number_table_length]; / / table array, each element corresponds to a tuple} 2.2 LocalVariableTable

This attribute, also known as the local variable table, records all the local variables in a method and is structured as follows:

LocalVariableTable_attribute {U2 attribute_name_index; / / current attribute name, pointing to the constant pool index U4 attribute_length; / / attribute length U2 local_variable_table_length; / / table entry {U2 start_pc of the local variable table / / current local variable start position U2 length; / / current local variable length (can be used to calculate the end position) U2 name_index / / Local variable name, pointing to the type description of the constant pool index U2 descriptor_index; / / local variable, pointing to the constant pool index U2 index / / the slot of the local variable in the local variable table of the current stack frame} local_variable_ table [local _ variable_table_length];} 2.3 StackMapTable

StackMapTable contains the data of several stack mapped frames (StackMap Frame), does not contain the information needed by the runtime, and is only used as a type check for Class files. The structure is as follows:

StackMapTable_attribute {U2 attribute_name_index; / / constant pool index, always "StackMapTable" U4 attribute_length; / / attribute length U2 number_of_entries / / the number of stack-mapped frames stack_map_frame [number _ of_entries]; / / specific stack-mapped frames} union stack_map_frame {/ / each stack-mapped frame is defined as an enumerated value, with the following values: same_frame / / for more information on the meaning of each value, please see JVM specification same_locals_1_stack_item_frame; / / https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-4.html#jvms-4.7.4 same_locals_1_stack_item_frame_extended; chop_frame Same_frame_extended; append_frame; full_frame;}

Each stack maps the frame to show what the data type of the system is at a specific bytecode offset, including the type of the local variable table and the type of the Operand stack.

Appendix: ASM easy to use

ASM is an Java bytecode manipulation library, and many well-known libraries rely on it, such as AspectJ, CGLIB, and so on. However, the performance of ASM far exceeds that of high-level bytecode libraries such as CGLIB, because ASM is closer to the bottom, more flexible and more powerful.

Here is a simple example of using ASM to output Hello World:

Package com.company;import org.objectweb.asm.ClassWriter;import org.objectweb.asm.MethodVisitor;import org.objectweb.asm.Opcodes;public class Main extends ClassLoader implements Opcodes {public static void main (String [] args) throws Exception {/ / create ClassWriter, specify COMPUTE_MAXS and COMPUTE_FRAMES to represent the calculation of the maximum local variable table and the deepest Operand stack ClassWriter cw = new ClassWriter (ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES), respectively / / set the basic information of the class through ClassWriter, such as the public access tag, and the class name is Example cw.visit (V11 cw.visitMethod public, "Example", null, "java/lang/Object", null); / / generate Example constructor MethodVisitor mw = cw.visitMethod (ACC_PUBLIC, "", "() V", null,null); mw.visitVarInsn (ALOAD,0) Mw.visitMethodInsn (INVOKESPECIAL, "java/lang/Object", "", "() V", false); mw.visitInsn (RETURN); mw.visitMaxs (0Pie0); mw.visitEnd () / generate the public static void main (String [] args) method and generate the bytecode of the main () method / / require the runtime to call System.out.println () and output "Hello world": mw = cw.visitMethod (ACC_PUBLIC+ACC_STATIC, "main", "([Ljava/lang/String;) V", null,null) Mw.visitFieldInsn (GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mw.visitLdcInsn ("Hello world!"); mw.visitMethodInsn (INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;) V", false); mw.visitInsn (RETURN); mw.visitMaxs (0mem0); mw.visitEnd () / / get the binary representation byte [] code = cw.toByteArray (); Main m = new Main (); / / load the class file into the system, call the `main () `method through reflection, and output the result Class mainClass = m.defineClass ("Example", code,0,code.length); mainClass.getMethods () [0] .invoke (null, new Object [] {null});}}

At this point, I believe you have a deeper understanding of the "Class file structure in JVM". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report