Video in progress

Strong Middle ⚙️ JVM and memory

What does bytecode verification check, and why was turning it off with -Xverify:none deprecated?

When a class loads, the verifier checks that its bytecode follows the JVM rules: the stack doesn't overflow, types match, jumps stay inside the method, private members aren't accessed without permission. Turning it off speeds up startup a little, but broken or malicious bytecode could crash the JVM, so -Xverify:none was deprecated in JDK 13.

📖 Answer

javac produces correct bytecode, but the JVM doesn't trust that: a class may come from another compiler, a bytecode generator (ASM, ByteBuddy), an agent or a corrupted jar. The verifier guarantees the following:

  • the operand stack never overflows or underflows;
  • int and long aren't mixed, a number isn't used in place of a reference;
  • every local variable is written before it is read;
  • goto doesn't jump outside the method;
  • no one inherits from a final class, a private method isn't called from outside.

Since Java 7 the faster "type checking" verifier is used: javac writes a StackMapTable attribute into the class file, and the JVM only checks the types instead of inferring them itself. That is why bytecode generators must write correct stack maps too, otherwise you get VerifyError: Expecting a stackmap frame at branch target.

On prod this error usually appears when an old version of an agent or bytecode library is run on a new JDK:

java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location: com/acme/OrderService.save(...) @12: invokevirtual

The fix is to update the library, not to turn off the verifier.

-Xverify:none and -noverify were deprecated in JDK 13 and print a warning. With them the JVM may execute incorrect bytecode and crash or corrupt memory. They used to be used for startup; today CDS/AOT cache is a better answer, because the classes in the archive are already verified.