Java – Responsibilities of JVM bytecode verifier

javajvm

Could someone list major tasks that the bytecode verifier has to perform to guarantee correctness of the program? Is there a standard, minimal set of responsibilities defined in JVM specification? I was also wondering whether verifications spans across other phases such as loading and initializing.

Best Answer

This is specified in the JVM Specification: Chapter 4.10. Verification of class Files .

The bulk of the page describes the various aspects of type safety. To check that the program is type-safe the verifier needs to figure out what types of operands reside in the operand stack at each program point, and make sure that they match the type expected by the respective instruction.

Other things it verifies include, but is not limited to the following:

  • Branches must be within the bounds of the code array for the method.

  • The targets of all control-flow instructions are each the start of an instruction. In the case of a wide instruction, the wide opcode is considered the start of the instruction, and the opcode giving the operation modified by that wide instruction is not considered to start an instruction. Branches into the middle of an instruction are disallowed.

  • No instruction can access or modify a local variable at an index greater than or equal to the number of local variables that its method indicates it allocates.

  • All references to the constant pool must be to an entry of the appropriate type. (For example, the instruction getfield must reference a field.)

  • The code does not end in the middle of an instruction.

  • Execution cannot fall off the end of the code.

  • For each exception handler, the starting and ending point of code protected by the handler must be at the beginning of an instruction or, in the case of the ending point, immediately past the end of the code. The starting point must be before the ending point. The exception handler code must start at a valid instruction, and it must not start at an opcode being modified by the wide instruction.

As a final step the verifier also performs a data-flow analysis, which makes sure that no instruction reference any uninitialized local variables.