Skip to content

Initializing annotation member's class at build time leads to runtime error #2946

@ziyilin

Description

@ziyilin

Describe the issue
Annotation member's class and all related classes are initialized at build time, but the not all are safe to initialize at build time.
This issue is discovered with Spring-boot, and here is a simplified case for illustration:

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Anno {
    TestEnum value();
}

public enum TestEnum {
    A(new Bar()),B(null);

    TestEnum(Bar b){
        this.bar = b;
    }

    private Bar bar;
}

public class Bar {
    static private long timeStamp=System.currentTimeMillis();
}

Given the above data structure, when the annotation Anno is parsed by java.lang.reflect.AnnotatedElement.getAnnotations called in com.oracle.svm.hosted.ImageClassLoader.annotationsAvailable, enum TestEnum and class Bar are all eventually initialized. However, as class Bar should not be initialized at build time because it calls the native method, an error Error: Classes that should be initialized at run time got initialized during image building: will be thrown to stop the compilation. Setting --initialize-at-build-time=Bar can help finishing compilation successfully, but will lead to potential run time error.

The root cause is the application class is unintentionally initialized by hosted system, and there is no way to roll back the initialization.

Steps to reproduce the issue
Here is a test case can reproduce the issue: initializationTest.zip

There are two methods in the main method. realisticCase (commented by default) shows the original Spring case and simplifiedCase method illustrates the issue with simplified code.

  1. Set environment variable GRAALVM_HOME to your Graalvm home
  2. Choose GRAALVM_CP_11 or GRAALVM_CP_8 in test.sh accord to your JDK version
  3. Run test.sh can see the runtime error
  4. Comment out the following line in test.sh and run it again can see the compilation error.
    OPTS="${OPTS} --initialize-at-build-time=com.alibaba.test.Bar"

Describe GraalVM and your environment:

  • GraalVM commit id : 9c1865f
  • JDK major version: 8 and 11
  • OS: Linux

More details
Consider adding the --native-image-info and --verbose flags when building your native image and paste output below.

Add any other information about the problem here. Especially important are stack traces or log output. Feel free to link to gists or to screenshots if necessary.

    PASTE YOUR LOG/STACK TRACE HERE

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions