Upgrade to GraalVM 22.3 and introduce PreComputeFieldFeature

This new GraalVM feature replaces ConstantFieldFeature and
introduces various enhancements:
 - Leverage the new FieldValueTransformer API
 - Use GraalVM 22.3 graal-sdk dependency instead of svm one
 - Avoid using internal GraalVM APIs
 - No need to configure JPMS exports
 - Directly integrated in spring-core module
 - Simplified build configuration

Closes gh-29081
Closes gh-29080
Closes gh-29089
This commit is contained in:
Sébastien Deleuze
2022-10-16 18:15:01 +02:00
parent ba99672fd6
commit 0889e47608
16 changed files with 111 additions and 335 deletions

View File

@@ -0,0 +1,86 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex.feature;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.regex.Pattern;
import org.graalvm.nativeimage.hosted.Feature;
/**
* GraalVM {@link Feature} that substitutes boolean field values that match a certain pattern
* with values pre-computed AOT without causing class build-time initialization.
*
* @author Sebastien Deleuze
* @author Phillip Webb
* @since 6.0
*/
class PreComputeFieldFeature implements Feature {
private static Pattern[] patterns = {
Pattern.compile(Pattern.quote("org.springframework.core.NativeDetector#imageCode")),
Pattern.compile(Pattern.quote("org.springframework.") + ".*#.*Present"),
Pattern.compile(Pattern.quote("org.springframework.") + ".*#.*PRESENT"),
Pattern.compile(Pattern.quote("reactor.") + ".*#.*Available")
};
private final ThrowawayClassLoader throwawayClassLoader = new ThrowawayClassLoader(PreComputeFieldFeature.class.getClassLoader());
@Override
public void beforeAnalysis(BeforeAnalysisAccess access) {
access.registerSubtypeReachabilityHandler(this::iterateFields, Object.class);
}
/* This method is invoked for every type that is reachable. */
private void iterateFields(DuringAnalysisAccess access, Class<?> subtype) {
try {
for (Field field : subtype.getDeclaredFields()) {
int modifiers = field.getModifiers();
if (!Modifier.isStatic(modifiers) || !Modifier.isFinal(modifiers) || field.isEnumConstant() ||
(field.getType() != boolean.class && field.getType() != Boolean.class)) {
continue;
}
String fieldIdentifier = field.getDeclaringClass().getName() + "#" + field.getName();
for (Pattern pattern : patterns) {
if (pattern.matcher(fieldIdentifier).matches()) {
try {
Object fieldValue = provideFieldValue(field);
access.registerFieldValueTransformer(field, (receiver, originalValue) -> fieldValue);
System.out.println("Field " + fieldIdentifier + " set to " + fieldValue + " at build time");
}
catch (Throwable ex) {
System.out.println("Processing of field " + fieldIdentifier + " skipped due the following error : " + ex.getMessage());
}
}
}
}
}
catch (NoClassDefFoundError ex) {
// Skip classes that have not all their field types in the classpath
}
}
/* This method is invoked when the field value is written to the image heap or the field is constant folded. */
private Object provideFieldValue(Field field) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
Class<?> throwawayClass = this.throwawayClassLoader.loadClass(field.getDeclaringClass().getName());
Field throwawayField = throwawayClass.getDeclaredField(field.getName());
throwawayField.setAccessible(true);
return throwawayField.get(null);
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex.feature;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* {@link ClassLoader} used to load classes without causing build-time
* initialization.
*
* @author Phillip Webb
* @since 6.0
*/
class ThrowawayClassLoader extends ClassLoader {
static {
registerAsParallelCapable();
}
private final ClassLoader resourceLoader;
ThrowawayClassLoader(ClassLoader parent) {
super(parent.getParent());
this.resourceLoader = parent;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loaded = findLoadedClass(name);
if (loaded != null) {
return loaded;
}
try {
return super.loadClass(name, true);
}
catch (ClassNotFoundException ex) {
return loadClassFromResource(name);
}
}
}
private Class<?> loadClassFromResource(String name) throws ClassNotFoundException, ClassFormatError {
String resourceName = name.replace('.', '/') + ".class";
InputStream inputStream = this.resourceLoader.getResourceAsStream(resourceName);
if (inputStream == null) {
return null;
}
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
inputStream.transferTo(outputStream);
byte[] bytes = outputStream.toByteArray();
return defineClass(name, bytes, 0, bytes.length);
}
catch (IOException ex) {
throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex);
}
}
@Override
protected URL findResource(String name) {
return this.resourceLoader.getResource(name);
}
}

View File

@@ -0,0 +1,9 @@
/**
* GraalVM native image features, not part of Spring Framework public API.
*/
@NonNullApi
@NonNullFields
package org.springframework.aot.nativex.feature;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex.substitution;
import com.oracle.svm.core.annotate.Alias;
import com.oracle.svm.core.annotate.TargetClass;
/**
* Allow to reference {@code com.sun.beans.finder.ClassFinder} from
* {@link Target_Introspector}.
*
* @author Sebastien Deleuze
* @since 6.0
*/
@TargetClass(className = "com.sun.beans.finder.ClassFinder")
final class Target_ClassFinder {
@Alias
public static Class<?> findClass(String name, ClassLoader loader) throws ClassNotFoundException {
return null;
}
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aot.nativex.substitution;
import java.beans.Customizer;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
/**
* {@link java.beans.Introspector} substitution with a refined {@code findCustomizerClass} implementation
* designed to avoid thousands of AWT classes to be included in the native image.
*
* @author Sebastien Deleuze
* @since 6.0
*/
@TargetClass(className = "java.beans.Introspector")
final class Target_Introspector {
@Substitute
private static Class<?> findCustomizerClass(Class<?> type) {
String name = type.getName() + "Customizer";
try {
type = Target_ClassFinder.findClass(name, type.getClassLoader());
if (Customizer.class.isAssignableFrom(type)) {
Class<?> c = type;
do {
c = c.getSuperclass();
if (c.getName().equals("java.awt.Component")) {
return type;
}
} while (!c.getName().equals("java.lang.Object"));
}
}
catch (Exception exception) {
}
return null;
}
}

View File

@@ -0,0 +1,9 @@
/**
* GraalVM native image substitutions, not part of Spring Framework public API.
*/
@NonNullApi
@NonNullFields
package org.springframework.aot.nativex.substitution;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

View File

@@ -1,5 +1,2 @@
Args = --initialize-at-build-time=org.springframework.aot.graalvm.ThrowawayClassLoader \
--add-exports org.graalvm.nativeimage.builder/com.oracle.svm.hosted=ALL-UNNAMED \
--add-exports jdk.internal.vm.compiler/org.graalvm.compiler.debug=ALL-UNNAMED \
--add-exports jdk.internal.vm.ci/jdk.vm.ci.meta=ALL-UNNAMED \
--add-exports org.graalvm.nativeimage.builder/com.oracle.svm.core.meta=ALL-UNNAMED
Args = --initialize-at-build-time=org.springframework.aot.nativex.feature.ThrowawayClassLoader \
--features=org.springframework.aot.nativex.feature.PreComputeFieldFeature