JVM Knowledge

When a prospective class file is loaded by the Java Virtual Machine (§5.3), the Java Virtual Machine first ensures that the file has the basic format of a class file (§4.1). This process is known as format checking. The checks are as follows:

  • The first four bytes must contain the right magic number.

  • All predefined attributes (§4.7) must be of the proper length, except for StackMapTable, RuntimeVisibleAnnotations, RuntimeInvisibleAnnotations, RuntimeVisibleParameterAnnotations, RuntimeInvisibleParameterAnnotations, RuntimeVisibleTypeAnnotations, RuntimeInvisibleTypeAnnotations, and AnnotationDefault.

  • The class file must not be truncated or have extra bytes at the end.

  • The constant pool must satisfy the constraints documented throughout §4.4.

    For example, each CONSTANT_Class_info structure in the constant pool must contain in its name_index item a valid constant pool index for a CONSTANT_Utf8_info structure.

  • All field references and method references in the constant pool must have valid names, valid classes, and valid descriptors (§4.3).

    Format checking does not ensure that the given field or method actually exists in the given class, nor that the descriptors given refer to real classes. Format checking ensures only that these items are well formed. More detailed checking is performed when the bytecodes themselves are verified, and during resolution.

These checks for basic class file integrity are necessary for any interpretation of the class file contents. Format checking is distinct from bytecode verification, although historically they have been confused because both are a form of integrity check.