Verification là giai đoạn quan trọng trong JVM class loading (sau Loading, trước Preparation). Mục đích: đảm bảo bytecode an toàn, tuân thủ spec, không crash JVM.
Vị trí trong Class Loading Process
- Loading: Đọc .class file → binary data → Method Area.
- Linking:
- Verification: Kiểm tra bytecode validity.
- Preparation: Cấp phát memory cho static fields, gán default values.
- Resolution: Resolve symbolic references → direct references (optional, lazy).
- Initialization: Chạy
<clinit>(static initializers, static field initializers). - Mặc định: Bật (tất cả passes).
-Xverify:none: Tắt verification (KHÔNG KHUYẾN NGHỊ – bảo mật, ổn định).-Xverify:remote: Chỉ verify remote classes (legacy).- JSR 202: Type annotations tại các điểm join (branch target, exception handler) để verification Pass 3 nhanh hơn (single-pass data flow).
- Compiler tự động generate
StackMapTableattribute. - Nếu thiếu → JVM fallback về type inference chậm hơn (hoặc fail nếu strict).
- Verification đảm bảo type safety, access control, structural integrity của bytecode.
- Bảo vệ JVM khỏi malicious/corrupt bytecode.
- Pass 3 (Bytecode verification) phức tạp nhất – data flow analysis trên operand stack & local variables.
- StackMapTable (Java 6+) tối ưu verification speed.
- Developer bình thường không lo verification – javac đảm bảo bytecode valid. Chỉ quan trọng khi: bytecode manipulation (ASM, ByteBuddy), custom classloader, compiler development.
4 Passes của Verification (Spec JVM)
| Pass | Tên | Kiểm tra |
|---|---|---|
| Pass 1 | Structural | File format: magic number (0xCAFEBABE), version, constant pool validity, attribute lengths, no truncation. |
| Pass 2 | Semantic | Final class không subclass, final method không override, class/interface hierarchy, method signatures, field/method existence, access modifiers. |
| Pass 3 | Bytecode | Data flow analysis: operand stack size, local variable types, jump targets valid, type safety (int không gán cho ref), method call signatures match, return type match, exception handlers valid. |
| Pass 4 | Resolution (Lazy) | Resolve symbolic refs khi dùng: class/interface/field/method tồn tại, accessible, signature match. |