I have the following program in a file called Test.java:
import sun.misc.Unsafe;
import java.lang.reflect.*;
public class Test {
public static void main(String[] args) throws Exception {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Unsafe unsafe = (Unsafe) unsafeField.get(null);
long offset = unsafe.staticFieldOffset(unsafeField);
System.out.println(offset);
}
}
It just obtains an Unsafe instance and then calls its staticFieldOffset() method.
I compile it with javac Test.java, it outputs a bunch of warnings about the dangers of Unsafe.
Then I run the produced class file with java Test and get the following:
104
So it works.
Now, I build a native image with native-image --no-server --no-fallback Test app.
[app:11806] classlist: 1,486.00 ms, 0.96 GB
[app:11806] (cap): 481.32 ms, 0.96 GB
[app:11806] setup: 1,628.06 ms, 0.96 GB
[app:11806] (clinit): 201.38 ms, 1.70 GB
[app:11806] (typeflow): 5,540.87 ms, 1.70 GB
[app:11806] (objects): 4,523.67 ms, 1.70 GB
[app:11806] (features): 251.65 ms, 1.70 GB
[app:11806] analysis: 10,741.48 ms, 1.70 GB
[app:11806] universe: 368.62 ms, 1.70 GB
[app:11806] (parse): 1,327.10 ms, 1.70 GB
[app:11806] (inline): 1,156.04 ms, 1.70 GB
[app:11806] (compile): 8,106.76 ms, 2.33 GB
[app:11806] compile: 10,998.36 ms, 2.33 GB
[app:11806] image: 765.81 ms, 2.33 GB
[app:11806] write: 137.50 ms, 2.33 GB
[app:11806] [total]: 26,315.42 ms, 2.33 GB
Ok, finally, I run it with ./app. The result follows:
Exception in thread "main" com.oracle.svm.core.jdk.UnsupportedFeatureError: Unsupported method of Unsafe
at com.oracle.svm.core.util.VMError.unsupportedFeature(VMError.java:86)
at jdk.internal.misc.Unsafe.staticFieldOffset(Unsafe.java:230)
at sun.misc.Unsafe.staticFieldOffset(Unsafe.java:662)
at Test.main(Test.java:9)
So it seems that in the native mode, it does not support Unsafe.staticFieldOffset() method.
Is there any way to make it work, or should it be addressed in the GraalVM code? This seems to obstruct the usage of Netty in native images, see https://github.com/netty/netty/issues/10051 as an example.
I'm using GraalVM 20.1:
openjdk version "11.0.7" 2020-04-14
OpenJDK Runtime Environment GraalVM CE 20.1.0 (build 11.0.7+10-jvmci-20.1-b02)
OpenJDK 64-Bit Server VM GraalVM CE 20.1.0 (build 11.0.7+10-jvmci-20.1-b02, mixed mode, sharing)
PS Configuration collection using an agent does not help. That is, when I add -agentlib:native-image-agent=config-output-dir=target/config to the java command to collect runtime data about reflection and stuff add then add -H:ConfigurationFileDirectories=target/config to the native-image command, the resulting native program behaves identically.