Java Byte Code details

Source: Internet
Author: User

Java compiler: The javac compiler reads the Java source code and compiles it into bytecode. The byte code is the executable form of the Java code executed in the Java Virtual Machine. It is also called interpreted code, pseudo code, or p-code.

Java binary bytecode File Parsing: refer to this article: http://wenku.baidu.com/view/23692b60ddccda38376baf4f.html

You can also take a look at this article: Java programming: Java Byte Code: bytes.

Java programmers seldom pay attention to the program compilation results. In fact, Java's byte code provides us with very valuable information. Especially when debugging and eliminating Java performance problems, the compilation results allow us to have a deeper understanding of how to improve the efficiency of program execution. In fact, JDK makes it very easy for us to study JAVA byte code. This article describes how to use the JDK tool to view and explain the java byte code, including the following:

L Java class splitter -- javap

L how does Java Byte Code prevent program memory errors?

L how to improve program execution efficiency by analyzing byte code

L decompile JAVA byte code using third-party tools

I. javap

Most Java programmers know that their programs do not compile the cost machine code. In fact, the program is compiled into intermediate byte code, which is interpreted and executed by the Java Virtual Machine. However, few programmers pay attention to byte code because the tools they use do not encourage them to do so. Most Java debugging tools do not allow single-step byte code debugging. These tools either display source code or nothing.

Fortunately, JDK provides Java class decomposition tool javap, a command line tool. Javap decompile the byte code provided by the file (. Class) given by the class name to print a readable version of these classes. By default, javap prints public domains, methods, constructors, and static initial values in a given class.

1. Usage of javap

Syntax: javap <option> <Class Name>...

The options include:

Parameters Description
B Backward compatible with javap in JDK 1.1
C Decompile the code and print out the Java VM commands for the methods in each given class. With this option, all methods including private and protected methods will be decompiled.
Classpath <pathlist> Specifies where to find your class files. This option value overwrites the path defined by the classpath environment variable and the missing path. The path here is an ordered list of directories and ZIP files. The elements are separated by ":" in UNIX and ";" in windows. To add some directories or ZIP files to be searched without overwriting the default system class path, use the classpath environment variable, which is used in the same way as the-classpath of the compiler.
Extdirs <dirs> Overwrite the installation extension directory
Help Show Help Information
J <flag> Pass <flag> directly to the running system
L Add the row number and local variable table based on the original printed information.
Public Show only public classes and their members
Protected Show protected/public classes and their members
Package Show the protected/public classes and their members of the package (default)
Private Show all classes and their members
S Print internal type mark
Bootclasspath <pathlist> Overwrite the class file location loaded by the bootstrap loader
Verbose Print the stack size, local variables of the method, and the number of parameters. If verifiable, print the cause of the Error

2. Application Instance

Let's take an example to illustrate how to use javap.

// Imports
Import java. Lang. String;
 
Public class exampleofbytecode {
// Constructors
Public exampleofbytecode (){}
 
// Methods
Public static void main (string [] ARGs ){
System. Out. println ("Hello World ");
}
}

After compiling this class, you can use a hexadecimal editor to open the. Class file, and then explain the meaning of the byte code through instructions on the virtual machine, but this is not a good method. By using javap, you can convert byte code into text that people can read, as long as the-C parameter is added:

Javap-C exampleofbytecode

The output result is as follows:

Compiled from exampleofbytecode. Java
Public class exampleofbytecode extends java. Lang. object {
Public exampleofbytecode ();
Public static void main (Java. Lang. String []);
}
 
Method exampleofbytecode ()
0 aload_0
1 invokespecial #6 <method java. Lang. Object ()>
4 return
 
Method void main (Java. Lang. String [])
0 getstatic #7 <field java. Io. printstream out>
3 LDC #1 <string "Hello World">
5 invokevirtual #8 <method void println (Java. Lang. String)>
8 return

From the above few lines of output code, you can learn a lot about byte code. The first command in the main method is as follows:

0 getstatic #7 <field java. Io. printstream out>

The initial number at the beginning is the offset of the instruction in the method, so the offset of the first instruction is 0. The offset is followed by the instruction mnemonic. In this example, the getstatic command pushes a static field into a data structure, which is called an operand stack. Subsequent commands can reference this field through this structure. Which field is followed by the getstatic command. The field here is "#7 <field java. Io. printstream out> ". If you view the byte code directly, the field information is not directly stored in the command. In fact, just like the constants used by all Java classes, field information is stored in the shared pool. Storing field information in the shared pool can reduce the size of the byte code. This is because commands only need to store integer index numbers, rather than storing the entire constant in the constant pool. In this example, the field information is stored in the 7th position of the constant pool. The sequence of storage is determined by the compiler, so we can see "#7 ".

By analyzing the first line of commands, we can see that it is relatively simple to guess the meaning of other commands. The "LDC" command pushes the constant "Hello, world." into the operand stack. "Invokevirtual" is used to activate the println method. Two parameters are popped up from the operand stack. Do not forget that a method like println has two parameters: a string parameter and an implicit "This" reference.

Ii. How does Java Byte Code prevent program memory errors?

The Java programming language has always been called the Internet Security language. On the surface, the code is like a typical C ++ code. Where does the security come from? An important aspect of security is to avoid program memory errors. Computer criminals can exploit program memory errors to add illegal code to other secure programs. Java byte code is on the front line to defend against such attacks

1. Type Security Detection instance

The following example shows how Java is implemented.

Public float add (float F, int N ){
Return F + N;
}

If you add this code to the first example, recompile and run javap, the analysis is as follows:

Method float add (float, INT)
0 fload_1
1 iload_2
2 i2f
3 FADD
4 freturn

At the beginning of the Java method, the virtual machine places the method parameters in a data structure called a variable table. From the name, we can see that the local variable table contains all declared local variables. In this example, the method starts from three local variable table entities. These are the three parameters of the add method. Position 0: Save the return type of this method. Positions 1 and 2 Save the floating point and Integer Parameters.

To really manipulate variables, they must be loaded (pressed) to the operand stack. The first command fload_1 presses the floating point parameter to the position 1 of the operand stack. The second instruction, iload_2, presses the integer parameter to the location 2 of the operand stack. Interestingly, the prefixes of these commands start with "I" and "F", which indicates that the commands of JAVA byte code are strictly classified. If the parameter type does not match the parameter type of the byte code, the virtual machine rejects insecure byte code. Even better, the byte code is designed to perform only one type security check-when the class is loaded.

2. Type Security Detection in Java

How does type security enhance system security? If attackers can make the Virtual Machine treat integer variables as floating-point variables, or more serious, it is easy to predict the computing crash. If the calculation occurs on the bank account, the security problems are obvious. What's more dangerous is to trick a virtual machine into programming an object reference with an integer variable. In most cases, virtual machines will crash, but attackers only need to find a vulnerability. Do not forget that attackers do not need to perform manual searches-a better and easy way is to write a program to generate a large number of converted bad byte code until a virtual machine can be found.

Another Byte Code protects Memory Security by Array Operations. "Aastore" and "aaload" Byte Code operate Java arrays, and they always need to check the boundary of the array. When the caller goes beyond the array boundary, these byte code will generate an array overflow error (arrayindexoutofboundsexception ). Maybe the most important detection in all applications is the branch command, for example, byte code starting with "if. In byte code, branch commands can only jump to another command in the same method. The only way to pass control outside the method is to return, generate an exception, or execute an invoke command. This not only closes many vulnerable doors, but also prevents hateful program errors caused by the crash of the accompanying references and stacks. If you have used the system debugger to open programs randomly located in the code, you will be familiar with these program errors.

It should be emphasized that all these checks are completed by the virtual machine at the byte code level, not just the compiler. Compilers in other programming languages, like C ++, can prevent some memory errors we have discussed above, but these protections are based on source code. The operating system will read and execute any machine code, regardless of whether the code is produced by a careful C ++ compiler or by an evil attacker. In short, C ++ Is Object-Oriented at the source program level, while Java's object-oriented feature extends to the compiled byte code.

3. How to improve program execution efficiency by analyzing byte code

Whether you pay attention to them or not, the memory and security protection of JAVA byte code exist objectively. Why bother reading the byte code? In fact, just like writing better C ++ code with a deep understanding of the compilation in DOS, understanding how the compiler translates your code into byte code can help you write more efficient code, and sometimes it can even prevent program errors without knowing it.

1. Why use stringbuffer to replace string during string merging?

Let's look at the following code:

// Return the concatenation str1 + str2
String Concat (string str1, string str2 ){
Return str1 + str2;
}
 
// Append str2 to str1
Void Concat (stringbuffer str1, string str2 ){
Str1.append (str2 );
}

Imagine how many functions each method needs to execute. Compile the program and execute javap. The output result is as follows:

Method java. Lang. String Concat (Java. Lang. String, java. Lang. String)
0 new #6 <class java. Lang. stringbuffer>
3 DUP
4 aload_1
5 invokestatic #14 <method java. Lang. String valueof (Java. Lang. Object)>
8 invokespecial #9 <method java. Lang. stringbuffer (Java. Lang. String)>
11 aload_2
12 invokevirtual #10 <method java. Lang. stringbuffer append (Java. Lang. String)>
15 invokevirtual #13 <method java. Lang. String tostring ()>
18 areturn
 
Method void Concat (Java. Lang. stringbuffer, java. Lang. String)
0 aload_1
1 aload_2
2 invokevirtual #10 <method java. Lang. stringbuffer append (Java. Lang. String)>
5 pop
6 Return

The first Concat method has five Call Methods: new, invokestatic, invokespecial, and two invokevirtual. This is much more work than the second cacat method, while the second cacat method has only one simple invokevirtual call. A feature of the string class is that once an instance is created, it cannot be changed unless it is assigned a value again. When learning Java programming, we were told that stringbuffer is more efficient than string connection. The difference between them can be clearly seen through javap analysis. If you suspect that the two different languages have the same performance, you should use javap to analyze the byte code. Different Java compilers have different methods to optimize byte code. You can also clearly see the differences using javap. The following is the analysis result of the byte code generated by JBuilder:

Method java. Lang. String Concat (Java. Lang. String, java. Lang. String)
0 aload_1
1 invokestatic #5 <method java. Lang. String valueof (Java. Lang. Object)>
4 aload_2
5 invokestatic #5 <method java. Lang. String valueof (Java. Lang. Object)>
8 invokevirtual #6 <method java. Lang. String Concat (Java. Lang. String)>
11 areturn

We can see that after JBuilder optimization, the first Concat method has three method calls: Two invokestatic invokevirtual. The second Concat method is not concise.

In any case, be familiar with the instant Compiler (JIT, just-in-time ). When a method is called for the first time, the instant compiler compiles the byte code pointed to in the virtual method table. After compilation, the pointer in the table points to the compiled machine code, in this way, the real-time compiler re-compiles the byte code, which enables you to perform more code optimization without revealing the javap analysis. Unless you have the source code of the virtual machine, you should use the performance benchmark for byte code analysis.

2. prevent errors in applications

The following example shows how to detect byte code to help prevent errors in applications. Create two public classes, which must be stored in two different files.

Public class changealot {
// Variable
Public static final Boolean DEBUG = false;
Public static Boolean log = false;
}
 
Public class eternallyconstant {
// Methods
Public static void main (string [] ARGs ){
System. Out. println ("eternallyconstant beginning execution ");
If (changealot. Debug)
System. Out. println ("debug mode is on ");
If (changealot. Log)
System. Out. println ("logging mode is on ");
}
}

If you run the eternallyconstant class, you should get the following information:

Eternallyconstant beginning execution.

Now we modify the changealot file and set the values of both Debug and log variables to true. Only recompile the changealot file and run eternallyconstant. The output result is as follows:

Eternallyconstant beginning execution
Logging mode is on

What happened in the debugging mode? "Debug mode is on" cannot be printed even if debug is set to true. The answer is in byte encoding. Run the javap analysis eternallyconstant class and you can see the following results:

Compiled from eternallyconstant. Java
Public class eternallyconstant extends java. Lang. object {
Public eternallyconstant ();
Public static void main (Java. Lang. String []);
}
 
Method eternallyconstant ()
0 aload_0
1 invokespecial #1 <method java. Lang. Object ()>
4 return
 
Method void main (Java. Lang. String [])
0 getstatic #2 <field java. Io. printstream out>
3 LDC #3 <string "eternallyconstant beginning execution">
5 invokevirtual #4 <method void println (Java. Lang. String)>
8 getstatic #5 <field Boolean log>
11 ifeq 22
14 getstatic #2 <field java. Io. printstream out>
17 LDC #6 <string "logging mode is on">
19 invokevirtual #4 <method void println (Java. Lang. String)>
22 return

Strange! Because "ifep" is used to detect the log field, the Code does not detect the debug field at all. Because the debug field is marked as final, the compiler knows that the debug field will not change during running. Therefore, the "if" statement is optimized and the branch is removed. This is a very useful optimization, because it allows you to embed debugging code in the reference program, and set it to false without the cost. Unfortunately, this will cause compilation confusion. If the final field is changed, remember to recompile other classes that reference this field. This is why the reference may be optimized. Java development tools do not detect this tiny change every time, which may lead to temporary very program errors. Here, the old c ++ motto is also true for the Java environment: "re-compile all programs whenever you are confused."

4. decompile JAVA byte code using third-party tools

The above describes the use of javap to analyze JAVA byte code. In fact, using a third-party tool, you can directly obtain the source code. There are many such tools. Among them, NMI's Java code Viewer (njcv) is a convenient tool.

1. Introduction to NMI's Java code Viewer

Njcv compile a Java node, that is, the. classfile. Zip or. jar file .. . ZIP file on the jarfile. Njcv decompilation tools can be used for further debugging, listening program errors, and security analysis. By analyzing some excellent Java code, we can learn a lot of Java program development skills.

The latest version of NMI's Java code viewer is 4.8.3 and can only run on the following Windows platforms:

L Windows 95/98

L
Windows 2000

L Windows NT 3.51/4.0

2. NMI's Java code Viewer application instance

Exampleofbytecode. class as an example. Open the Open menu in the File menu and open the java byte code file. Java class files lists all the files in the same directory as the file. Select the file to be decompiled, and select decompile or dissasemble from the process menu. decompiled files are listed in the Souce-code files column. Open the file with the programmer's file editor provided by NMI's Java code viewer. The source code is listed.

// Processed by NMI's Java code viewer 4.8.3? 1997-2000 B. Lemaire
// Website: http://njcv.htmlplanet.com E-mail: info@njcv.htmlplanet.com
// Copy registered to evaluation copy
// Source file name: exampleofbytecode. Java
 
Import java. Io. printstream;
 
Public class exampleofbytecode {
 
Public exampleofbytecode (){
}
 
Public static void main (string ARGs []) {
System. Out. println ("Hello World ");
}
 
Public float add (float F, int N ){
Return F + (float) N;
}
 
String Concat (string str1, string str2 ){
Return str1 + str2;
}
 
Void Concat (stringbuffer str1, string str2 ){
Str1.append (str2 );
}
}

NMI's Java code viewer also supports extracting class files directly from JAR/ZIP files. Decompiled files are stored with the. NMI extension by default. You can set the. Java extension. You can use the njcv editor to edit source files. You can select your preferred editor. The result is not much different from the original file. I believe you will like it.

V. Conclusion

Learning about byte code can help programmers who are engaged in Java programming language programming. The javap tool makes it easy to view byte code. some third-party tools make code decompilation easier. Javap detection code is often used, and third-party tools are used to decomcode code the code. To find program errors that are especially easy to forget, improve program running efficiency, and improve system security and performance, its value is immeasurable.

With the development of Java programming technology, Java class libraries are constantly improved, and more applications are developed using Java's superior cross-platform performance. Oracle compiled Oracle 8i Enterprise Manager in Java and its database installation program. Borland of Inprise
JBuilder 3.5 is also written in Java; some internet phones also use Java technology, such as mediaring and dialpad network phones use Java solutions; even the NMI's Java code viewer mentioned above is written in Java. Java2 has made Java's running performance almost close to the execution speed of C ++ programs. Combined with Enterprise JavaBean, Servlet, Cobra, and RMI technologies, Java will become more and more powerful, it will also be widely used.

 

Reprinted: http://blog.163.com/xiaopengyan_109/blog/static/149832173201062504753376/

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.