Sub topic 11
Linking: verification, preparation and resolution
This chapter assumes you can compile and run Java programs with javac and java, and that you have read the earlier chapters on the class file format, the constant pool and the class loading lifecycle. You should know that a loaded class is a Class object backed by bytes from a .class file, and that the constant pool holds symbolic references such as java/lang/String or Foo.bar:(I)V.
Where linking fits
Loading gets the bytes of a class and builds an internal representation of it. The class is not yet safe to run. Linking prepares it for use and has three sub-steps: verification, preparation and resolution. Initialization, which runs static initializers, comes after linking and is covered in the next chapter.
The Java Virtual Machine Specification (JVMS) fixes the order of loading, linking and initialization for a class, but it leaves the timing of some work open. HotSpot, the JVM in OpenJDK, links a class lazily, just before it initializes it. It also resolves each symbolic reference lazily, the first time an instruction uses it. Your code should not depend on these timings, except where the specification guarantees them.
| Phase | Input | Output | Typical errors |
|---|---|---|---|
| Verification | Parsed class file | Confidence that the bytecode is safe | `VerifyError`, `ClassFormatError` |
| Preparation | Static field declarations | Static storage with default values | `OutOfMemoryError` (rare) |
| Resolution | Symbolic reference in the constant pool | Direct reference (class, method, field) | `NoSuchMethodError`, `NoSuchFieldError`, `IllegalAccessError`, `NoClassDefFoundError` |
Verification
The JVM executes whatever bytes a loader gives it. Those bytes may come from a buggy compiler, a bytecode-rewriting tool, or an attacker. The verifier checks the class before any of its code runs, so the interpreter and the JIT compiler can assume the code is well formed. Without verification, malformed code could corrupt memory or break the type rules that Java security depends on.
The checks fall into groups:
- Format checks. The magic number is
0xCAFEBABE. The version is supported. Constant pool entries have valid types and indexes. Attribute lengths are correct. - Structural rules. A
finalclass is not subclassed. Afinalmethod is not overridden. Every class exceptObjecthas a superclass. - Type and flow checks on bytecode. An
iaddfinds twointvalues on the operand stack. Agetfieldreceives an object of the right class. The operand stack never underflows or exceeds themax_stackvalue in theCodeattribute. Local variables are written before they are read. Every branch lands on a valid instruction.
Since class file version 50 (Java 6), javac emits a StackMapTable attribute that records the expected types of locals and stack slots at each branch target. The verifier checks the code in one linear pass against these recorded types. Class files of version 51 and later (Java 7 and later) must use this type-checking verifier. Older files fall back to a slower type-inferencing verifier that has to compute the types itself.
You can see the stack maps with javap -v:
javap -v MathOpsLook for lines such as StackMapTable: number_of_entries = 2 inside methods that contain branches.
A failure looks like this. The exact text varies by JDK version and by the defect.
Exception in thread "main" java.lang.VerifyError: Bad type on operand stack
Exception Details:
Location:
Broken.run()V @4: iadd
Reason:
Type 'java/lang/String' (current frame, stack[1]) is not assignable to integerYou rarely see VerifyError from javac output. It usually points to a bytecode generator or instrumentation agent, or to a class file compiled by a newer tool than the runtime supports. Class files that are too new produce UnsupportedClassVersionError, which is detected earlier, during loading.
Preparation
Preparation allocates storage for the class's static fields and gives each one its default value:
0forbyte,short,intandlong0.0forfloatanddoublefalseforboolean'\u0000'forcharnullfor references
Preparation does not run any Java code. Assignments such as static int x = 5; are compiled into the class's <clinit> method, which runs during initialization. Between preparation and initialization, the field holds its default.
This matters when initializers refer to each other. The program below reads second before its initializer has run:
public class Prep {
static int first = readSecond();
static int second = 10;
static int readSecond() {
return second;
}
public static void main(String[] args) {
System.out.println(first + " " + second);
}
}It prints 0 10. When readSecond runs, second has been prepared but not yet assigned, so it still holds 0. Instance fields are different. They are allocated and zeroed per object, when new runs, not during preparation.
A static final field initialized with a compile-time constant gets a ConstantValue attribute in the class file. Its value comes straight from the class file, so you never observe the default for such fields. The JVMS describes this as part of initialization, while older texts place it in preparation. The visible behavior is the same.
Preparation also builds the method tables the JVM uses for virtual dispatch. HotSpot lays out the method tables during linking. You see no effect from this except faster calls.
Resolution
Bytecode refers to other classes, fields and methods by name. An invokestatic instruction carries an index into the constant pool, where a Methodref entry names the class, the method name and the descriptor, for example MathOps.add:(II)I. Resolution turns that symbolic reference into a direct one, such as a pointer to the method's internal structure.
Resolving a method reference involves several steps:
- Resolve the named class. This may trigger loading of that class through the loader of the referencing class.
- Look up the method in that class and then in its superclasses and superinterfaces, following the lookup rules in the JVMS.
- Check access. A
privatemethod of another class, for example, is not accessible. - Store the result so later executions of the same instruction skip the lookup.
Resolution can fail in several ways, and the error type tells you which step went wrong:
NoClassDefFoundError: the class named in the reference could not be loaded.NoSuchMethodErrorandNoSuchFieldError: the class exists but has no member with that name and descriptor.IllegalAccessError: the member exists but is not accessible from the caller.IncompatibleClassChangeError: the shape of the target changed, for example a method became non-static, or a class became an interface.AbstractMethodError: a method found at call time is abstract. This is raised during invocation rather than resolution proper.
All of these usually mean the code that was compiled against one version of a library is running against another. javac checked the references at compile time, but the JVM checks them again at run time against whatever is on the class path.
HotSpot resolves lazily, so a reference to a missing class causes no error until the instruction runs. This program demonstrates it:
public class LazyResolve {
public static void main(String[] args) {
System.out.println("start");
if (args.length > 0) {
Missing.hello();
}
System.out.println("end");
}
}
class Missing {
static void hello() {
System.out.println("hi");
}
}Compile it, delete the helper class, and run it twice:
javac LazyResolve.java
rm Missing.class
java LazyResolve
java LazyResolve goThe first run prints start and end, because the invokestatic for Missing.hello never executes. The second run prints start and then fails with NoClassDefFoundError: Missing, caused by a ClassNotFoundException. The error is raised at the instruction that needs the class, not when LazyResolve was loaded.
The JVMS also requires consistency. Once a reference fails to resolve, later attempts from the same class fail with the same error. A successful resolution stays valid for that class, so replacing a class file on disk does not change references that were already resolved.
Watching linking happen
Linking has no dedicated log tag that is easy to read in Java 11, but unified logging shows when classes are loaded, which is the usual trigger for linking:
java -Xlog:class+load:file=classload.log LazyResolve goUse -Xlog:class+init for details of linking and initialization, if your JDK build supports it. In the log from the run above, Missing never appears as loaded, because loading it failed.
Exercise
A program builds and runs correctly. After you upgrade a library jar to a new version, it fails at run time with NoSuchMethodError on a call that still compiles when you rebuild against the new jar. Which linking phase raised the error, and what does it say about the old build?
Show answer
Resolution raised it. The old compiled class contains a symbolic reference to a method name and descriptor that the new library no longer provides. Rebuilding recompiles against the new jar, and javac would have shown a compile error if the method had really disappeared, so the signature probably changed in a binary-incompatible way, for example a changed return type or parameter type. The old class file was stale.
Exercise
What does Prep print if you change static int second = 10; to static final int second = 10;, and why?
Show answer
It prints 10 10. second is now a compile-time constant with a ConstantValue attribute, and javac also inlines it in readSecond, so the method returns 10 regardless of initialization order.