1

I am very new to Java bytecode. From my understanding, when disassembling a JAR file, the result will be bytecode interpreted by the JVM directly (numbers). Each byte or 2 bytes of numbers is associated with a Java method in the actual Java source file. Where can I find a mapping of these?

Moreover, lets say I want to find out if a variable was initialized in a class but then never again used. Could I simply check when it was instantiated, and then deem it never used if it never appears again in the bytecode after its initialization? For this logic to work, JVM would have to execute bytecode sequentially, so that that intialized variable could not jump to another function, etc. Are function boundaries defined unlike in general assembly code (intel, MIPS).

Thanks in advance.

2

4 Answers 4

3

It takes some time to understand the JVM bytecode. To get you started here are two things you need to know:

  • The JVM is a stack machine: when it needs to evaluate an expression it first pushes the expression's inputs into a stack and then evaluation of the expression is essentially popping all the inputs off of the stack and pushing the result back into the top of the stack. this result can, in turn, be used as an input to another expression's evaluation.

  • All parameters and local variables are stored in the local variable array.

Let's see that in practice. Here is a source code:

package p1;

public class Movie {
  public void setPrice(int price) {
    this.price = price;
  }
}

As EJP said, you should run javap -c, to see the bytecode: javap -c bin/p1/Movie.class. This is the output:

public class p1.Movie {
  public p1.Movie();
    Code:
       0: aload_0       
       1: invokespecial #10   // Method java/lang/Object."<init>":()V
       4: return        

  public void setPrice(int);
    Code:
       0: aload_0       
       1: iload_1       
       2: putfield      #18    // Field price:I
       5: return        
}

Looking at the output you can see that in the bytecode we see the default constructor, and the setPrice method.

The first instruction, aload_0 takes the value of local variable 0 and pushes it into the stack (complete list of instructions). In non-static method, local variable 0, is always the this parameter so after instruction 0 our stack is

| this |
+------+

The next instruction is aload_1 which takes the value of local variable 1 and pushes it into the stack. In our local variable 1 is the method's parameter (price). Our stack now looks as follows:

| price |
| this  |
+-------+

The next instruction putfield #18 is the one doing the assignment this.price = price. This instruction pops two value off of the stack. The first popped value is the fields new value. The second popped value is the pointer to the object holding the field to be assigned to. The name of the field to be assigned is encoded in the instruction (that's why the instruction takes three bytes: it starts at position 2, but the next instruction starts at position 5). The extra value encoded into the instruction is "#18". This is the an index into the constant pool. To see the constant pool you should run: javap -v bin/p1/Movie.class:

Classfile /home/imaman/workspace/Movie-shop/bin/p1/Movie.class
...
Constant pool:
   #1 = Class              #2             //  p1/Movie
   ...
   #5 = Utf8               price
   #6 = Utf8               I
   ...
   #18 = Fieldref          #1.#19          //  p1/Movie.price:I
   #19 = NameAndType       #5:#6           //  price:I
   ...

So #18 specifies that the field to be assigned is the price field of the p1.Movie class (as you can see #18 makes references to #1, #19 which, in turn reference #5 and #6. The actual name of the assigned to field appears in the constant pool)

back to our execution of the putfield instruction: having popped two values off the stack the JVM now assigns the first popped value into the price field (indicated by #18) of the this object (second popped value).

The evaluation stack is now empty.

The last instruction simply returns.

3

It's not entirely clear what you're asking here, so let me answer some things:

Method boundaries are well-defined, unlike "normal" assembly code. Types are well-defined everywhere. Fields are well-defined. Classes are well-defined. Instruction boundaries are well-defined (it is illegal to jump to the middle of an instruction). Code and data are easily distinguished. Methods cannot access each others' variables; only fields. These things make it much easier to analyze Java bytecode than machine code.

To read and write class files from a Java program, I recommend the ASM library. It will take care of understanding the class file format, and will translate it into an easier-to-use format (either a tree of Java objects, or a sequence of method calls). There are other libraries with similar purposes, such as BCEL, cgLib and Javassist. I am not familiar enough with those other libraries to compare them.

Bytecode within a method is executed sequentially, for "most" instructions. There are several instructions that can cause execution to not be sequential - usually this is the intent of the instruction (e.g. conditional jumps, used to implement if/while/etc). Many instructions can also throw exceptions, which causes execution to either jump to an exception handler or exit the current method.

The following instructions affect control flow:

  • areturn, dreturn, freturn, ireturn, lreturn - when executed, cause the method to return normally. Can also throw a IllegalMonitorStateException, under rare conditions (mis-generated bytecode).
  • athrow - when executed, causes an exception to be thrown.
  • if_icmpne, if_icmpeq, if_icmplt, if_icmpge, if_icmpgt, if_icmple, ifne, ifeq, iflt, ifge, ifgt, ifle, ifnonnull, ifnull - conditional jump instructions
  • goto, goto_w - unconditional jump instructions
  • aaload, aastore, anewarray, arraylength, baload, bastore, caload, castore, checkcast, daload, dastore, faload, fastore, getfield, getstatic, iaload, iastore, idiv, instanceof, irem, laload, lastore, ldc, ldc_w, ldc2_w, ldiv, lrem, monitorenter, monitorexit, multianewarray, newarray, putfield, putstatic, saload, sastore - can throw exceptions under some circumstances.
  • invokedynamic, invokeinterface, invokespecial, invokestatic, invokevirtual, new- cause other methods to be called, which can result in an exception being thrown.
  • jsr, jsr_w, ret - allow methods to contain subroutines that are called from more than one place. Fortunately for you, modern compilers do not seem to generate these.
1

As EJP stated in a comment, you can decompile a class named example.Main by using the javap -c example.Main.class command. As one can see, Java bytecode is far more structured than IA32. The actual bytecode instructions are contained within methods, just as in Java itself.

You can find information regarding each of the bytecode instructions in:

  1. JVM Specification
  2. Wikipedia

JVM instructions manipulate a stack of operands. For example:

LDC 10    // Push the constant 10 onto the stack.
LDC 20    // Push the constant 20 onto the stack.
IADD      // Pop two numbers off the stack, add them, push the result.
ISTORE 5  // Pop an integer (in this case 30) off the stack and put it in variable #5.

As you may notice, local variables are actually stored in numbered slots in the stack-frame. It is the Java compiler's job to associate a local variable with a numbered slot. It it important to point out that variables of type (boolean, char, byte, short, int, or a reference-type) will be stored in a single slot. However, variables of type long or double require two slots to store them. In addition, in non-static methods, slot #0 is always used to hold this. Furthermore, parameters are always associated with the lowest numbered slots. So in a non-static method moo(String message, int times), this will be in slot #0, variable message will be in slot #1 and variable times will be in slot #2.

In order to determine where in the bytecode of a method a local variable is alive, you would need to use Live Variable Analysis on the method's bytecode, because bytecode instructions are executed subsequently (i.e. not all at once), but not necessarily linearly.

On the other hand, fields are not stored in the aforesaid in the stack-frame. I think you are may referring to fields, since they can be "initialized in a class" and then be used in different methods, whereas local variables are local to the method that declares them.

0

The JVM does not necessarily execute bytecode sequentially, but it behaves as if it did (a bit like out of order execution on processors, but with much more in depth optimization).

The main thing you seem to be concerned about though are the structural proeprties of the bytecode platform.

  • No, bytecode cannot jump to another function. The only way to transfer control is through exceptions or special call instructions, which go through the VM. Every stack frame is completely isolated.

  • Additionally, all bytecode has enforced type checking, though the type checking is somewhat looser than that done at the Java language level. You can't take a float and interpert it as an int for example, much less a pointer. All memory access is abstracted away by the VM, it's impossible to do raw memory access like you might in native code.

  • Instructions can be more than 2 bytes (in fact, switch instructions can be arbitrary long). But the vast majority of instructions are either 1 or 3 bytes. They do not necessarily correspond 1 to 1 with elements of the Java source, though the mapping usually is straightforward. In general, later versions of Java add more syntactic sugar, which reduces the similarity of bytecode to the original source code when using those features (a notable case is switching on a string).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.