How does bytecode get verified in the JVM?
The best source of information is probably the relevant section in the JVM specification, 4.10 Verification of class Files.
See the link for details, but broadly:
Linking-time verification enhances the performance of the interpreter. Expensive checks that would otherwise have to be performed to verify constraints at run time for each interpreted instruction can be eliminated. The Java Virtual Machine can assume that these checks have already been performed. For example, the Java Virtual Machine will already know the following:
- There are no operand stack overflows or underflows.
- All local variable uses and stores are valid.
- The arguments to all the Java Virtual Machine instructions are of valid types.
The verifier also performs verification that can be done without looking at the code array of the Code attribute (§4.7.3). The checks performed include the following:
- Ensuring that final classes are not subclassed and that final methods are not overridden (§5.4.5).
- Checking that every class (except
Object) has a direct superclass.- Ensuring that the constant pool satisfies the documented static constraints; for example, that each
CONSTANT_Class_infostructure in the constant pool contains in itsname_indexitem a valid constant pool index for aCONSTANT_Utf8_infostructure.- Checking that all field references and method references in the constant pool have valid names, valid classes, and a valid type descriptor.