Skip to content
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
c6d1038
Add generateDynamicAccessMetadata gradle task to the native-gradle-pl…
jormundur00 Oct 21, 2025
17d00f7
Implement dynamic access generator on the native-maven-plugin
jormundur00 Oct 23, 2025
7b37e44
Touch-up maven plugin
jormundur00 Oct 24, 2025
f17e327
Relax exception catches and be more specific with exceptions
jormundur00 Oct 24, 2025
1f4148e
Make GenerateDynamicAccessMetadata contingent on the presence of "--e…
jormundur00 Oct 24, 2025
ea322e5
Cleanup both plugins and make them more consistent with eachother
jormundur00 Oct 24, 2025
0c73931
Hotfix private method being public
jormundur00 Oct 27, 2025
f033acf
Make the generateDynamicAccessMetadata mojo execute when executing co…
jormundur00 Oct 27, 2025
fc0acfb
Add EOF newlines
jormundur00 Oct 30, 2025
fe588bc
Make the dynamic access metadata generation parts of the maven and gr…
jormundur00 Oct 31, 2025
3ba7d33
Add documentation for the dynamic access metadata generation parts of…
jormundur00 Oct 31, 2025
5f0b4c5
Make --emit build-report detection cover cases where the build report…
jormundur00 Oct 31, 2025
05a2271
Move away from "JAR" usage, as different formats can be also found on…
jormundur00 Nov 3, 2025
564ef46
Make the JSON output format more verbose for the native-gradle-plugin
jormundur00 Nov 7, 2025
da047df
Make the JSON output format more verbose for the native-maven-plugin
jormundur00 Nov 7, 2025
6b9ccb8
Update docs
jormundur00 Nov 10, 2025
7655aca
Make GraalVMReachabilityMetadataService#getRepositoryDirectory optional
jormundur00 Nov 10, 2025
1c497ea
Migrate to the use of LinkedHashSet to have consistent results across…
jormundur00 Nov 10, 2025
e948593
Use non-eager transformation when checking if a build report is being…
jormundur00 Nov 10, 2025
d001a47
Use Property<ResolvedComponentResult> and PropertySet<ResolvedArtifac…
jormundur00 Nov 12, 2025
f04d7e2
Move JSON generation and parsing to a new DynamicAccessMetadataUtils …
jormundur00 Nov 12, 2025
e2d7aeb
Update and move serialization documentation to the util class
jormundur00 Nov 12, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ public Set<DirectoryConfiguration> findConfigurationsFor(Consumer<? super Query>
.collect(Collectors.toSet());
}

public Path getRootDirectory() {
return rootDirectory;
}

/**
* Allows getting insights about how configuration is picked.
*/
Expand Down
1 change: 1 addition & 0 deletions native-gradle-plugin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ maven {
}

dependencies {
implementation libs.openjson
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ The Gradle plugin shouldn't have a direct dependency on openjson. The common utils should have one, but there's no reason the Gradle plugin should directly depend on it.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've created a separate DynamicAccessMetadataUtils class where I do this serialization and JSON parsing (which I left in the commons.utils package), so now I don't add this direct dependency on openjson here anymore.

FYI: Not sure if the same applies for the native-maven-plugin, but in the build.gradle.kts for it, we already depend on both libs.utils and libs.openjson.

implementation libs.utils
implementation libs.jvmReachabilityMetadata
testImplementation libs.test.spock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import org.graalvm.buildtools.gradle.internal.agent.AgentConfigurationFactory;
import org.graalvm.buildtools.gradle.tasks.BuildNativeImageTask;
import org.graalvm.buildtools.gradle.tasks.CollectReachabilityMetadata;
import org.graalvm.buildtools.gradle.tasks.GenerateDynamicAccessMetadata;
import org.graalvm.buildtools.gradle.tasks.GenerateResourcesConfigFile;
import org.graalvm.buildtools.gradle.tasks.MetadataCopyTask;
import org.graalvm.buildtools.gradle.tasks.NativeRunTask;
Expand Down Expand Up @@ -92,6 +93,7 @@
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileSystemLocation;
import org.gradle.api.file.FileSystemOperations;
import org.gradle.api.file.RegularFile;
import org.gradle.api.logging.LogLevel;
import org.gradle.api.plugins.ExtensionAware;
import org.gradle.api.plugins.JavaApplication;
Expand Down Expand Up @@ -389,6 +391,22 @@ private void configureAutomaticTaskCreation(Project project,
options.getConfigurationFileDirectories().from(generateResourcesConfig.map(serializableTransformerOf(t ->
t.getOutputFile().map(serializableTransformerOf(f -> f.getAsFile().getParentFile()))
)));
TaskProvider<GenerateDynamicAccessMetadata> generateDynamicAccessMetadata = registerDynamicAccessMetadataTask(
project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME),
graalVMReachabilityMetadataService(project, reachabilityExtensionOn(graalExtension)),
project.getLayout().getBuildDirectory(),
tasks,
deriveTaskName(binaryName, "generate", "DynamicAccessMetadata"));
imageBuilder.configure(buildImageTask -> {
if (buildImageTask.getOptions().get().getBuildArgs().get().stream()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ This is likely to fail, because you are reading the build arguments during configuration of a task, which is non deterministic (depends on when the build args are changed in a script). Either the reasoning has to be deferred to execution time, based on the actual arguments, or it should use a non eager transformation (not use .get() but .map).

.anyMatch(arg -> arg.startsWith("--emit build-report"))) {
options.getClasspath().from(
generateDynamicAccessMetadata.flatMap(task ->
task.getOutputJson().map(RegularFile::getAsFile)
)
);
}
});
configureJvmReachabilityConfigurationDirectories(project, graalExtension, options, sourceSet);
configureJvmReachabilityExcludeConfigArgs(project, graalExtension, options, sourceSet);
});
Expand Down Expand Up @@ -656,6 +674,18 @@ private TaskProvider<GenerateResourcesConfigFile> registerResourcesConfigTask(Pr
});
}

private TaskProvider<GenerateDynamicAccessMetadata> registerDynamicAccessMetadataTask(Configuration classpathConfiguration,
Provider<GraalVMReachabilityMetadataService> metadataService,
DirectoryProperty buildDir,
TaskContainer tasks,
String name) {
return tasks.register(name, GenerateDynamicAccessMetadata.class, task -> {
task.getRuntimeClasspath().set(classpathConfiguration);
task.getMetadataService().set(metadataService);
task.getOutputJson().set(buildDir.dir("generated").map(dir -> dir.file("dynamic-access-metadata.json")));
});
}

public void registerTestBinary(Project project,
DefaultGraalVmExtension graalExtension,
DefaultTestBinaryConfig config) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,4 +235,11 @@ public Set<DirectoryConfiguration> findConfigurationsFor(Set<String> excludedMod
query.useLatestConfigWhenVersionIsUntested();
});
}

public Path getRepositoryDirectory() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ Should probably return Optional<Path> instead, so that we don't have to figure out if null is expected or not.

if (repository instanceof FileSystemRepository fsRepo) {
return fsRepo.getRootDirectory();
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/*
* Copyright (c) 2025, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.graalvm.buildtools.gradle.tasks;

import com.github.openjson.JSONArray;
import com.github.openjson.JSONObject;
import org.graalvm.buildtools.gradle.internal.GraalVMLogger;
import org.graalvm.buildtools.gradle.internal.GraalVMReachabilityMetadataService;
import org.gradle.api.DefaultTask;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ResolvedArtifact;
import org.gradle.api.artifacts.ResolvedDependency;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
* Generates a {@code dynamic-access-metadata.json} file used by the dynamic access tab of the native image
* Build Report. This json file contains the mapping of all classpath entries that exist in the
* {@value #LIBRARY_AND_FRAMEWORK_LIST} to their transitive dependencies.
* <p>
* If {@value #LIBRARY_AND_FRAMEWORK_LIST} doesn't exist in the used release of the
* {@code GraalVM Reachability Metadata} repository, this task does nothing.
* <p>
* The format of the generated JSON file conforms the following
* <a href="https://github.com/oracle/graal/blob/master/docs/reference-manual/native-image/assets/dynamic-access-metadata-schema-v1.0.0.json">schema</a>.
*/
public abstract class GenerateDynamicAccessMetadata extends DefaultTask {
private static final String LIBRARY_AND_FRAMEWORK_LIST = "library-and-framework-list.json";
private static final String ARTIFACT = "artifact";
private static final String METADATA_PROVIDER = "metadataProvider";
private static final String PROVIDES_FOR = "providesFor";

@Internal
public abstract Property<Configuration> getRuntimeClasspath();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ This is not compatible with Gradle's configuration cache. We shouldn't use Configuration as input (probably a Property<ResolvedComponentResult>).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've since moved to the usage of Property<ResolvedComponentResult> and SetProperty<ResolvedArtifactResult> (trying to follow the pattern you used when setting properties for the CollectReachabilityMetadata task to be safe).


@Internal
public abstract Property<GraalVMReachabilityMetadataService> getMetadataService();

@OutputFile
public abstract RegularFileProperty getOutputJson();

@TaskAction
public void generate() {
File jsonFile = getMetadataService().get().getRepositoryDirectory().resolve(LIBRARY_AND_FRAMEWORK_LIST).toFile();
if (!jsonFile.exists()) {
GraalVMLogger.of(getLogger()).log("{} is not packaged with the provided reachability metadata repository.", LIBRARY_AND_FRAMEWORK_LIST);
return;
}

try {
Set<String> artifactsToInclude = readArtifacts(jsonFile);

Configuration runtimeClasspathConfig = getRuntimeClasspath().get();
Set<File> classpathEntries = runtimeClasspathConfig.getFiles();

Map<String, Set<String>> exportMap = buildExportMap(
runtimeClasspathConfig.getResolvedConfiguration().getFirstLevelModuleDependencies(),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ You should use a dependency graph as input instead. This isn't compatible with the configuration cache.

artifactsToInclude,
classpathEntries
);

writeMapToJson(getOutputJson().getAsFile().get(), exportMap);
} catch (IOException e) {
GraalVMLogger.of(getLogger()).log("Failed to generate dynamic access metadata: {}", e);
}
}

/**
* Collects all versionless artifact coordinates ({@code groupId:artifactId}) from each
* entry in the {@value #LIBRARY_AND_FRAMEWORK_LIST} file.
*/
private Set<String> readArtifacts(File inputFile) throws IOException {
Set<String> artifacts = new HashSet<>();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably use a LinkedHashSet so that the result is consistent across invocations.

String content = Files.readString(inputFile.toPath());
JSONArray jsonArray = new JSONArray(content);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject entry = jsonArray.getJSONObject(i);
if (entry.has(ARTIFACT)) {
artifacts.add(entry.getString(ARTIFACT));
}
}
return artifacts;
}

/**
* Builds a mapping from each entry in the classpath, whose corresponding artifact
* exists in the {@value #LIBRARY_AND_FRAMEWORK_LIST} file, to the set of all of its
* transitive dependency entry paths.
*/
private Map<String, Set<String>> buildExportMap(Set<ResolvedDependency> dependencies, Set<String> artifactsToInclude, Set<File> classpathEntries) {
Map<String, Set<String>> exportMap = new HashMap<>();
for (ResolvedDependency dependency : dependencies) {
String dependencyCoordinates = dependency.getModuleGroup() + ":" + dependency.getModuleName();
if (!artifactsToInclude.contains(dependencyCoordinates)) {
continue;
}

for (ResolvedArtifact artifact : dependency.getModuleArtifacts()) {
File file = artifact.getFile();
if (classpathEntries.contains(file)) {
Set<String> files = new HashSet<>();
collectDependencies(dependency, files, classpathEntries);
exportMap.put(file.getAbsolutePath(), files);
}
}
}
return exportMap;
}

/**
* Recursively collects all classpath entry paths for the given dependency and its transitive dependencies.
*/
private void collectDependencies(ResolvedDependency dep, Set<String> collector, Set<File> classpathEntries) {
for (ResolvedArtifact artifact : dep.getModuleArtifacts()) {
File file = artifact.getFile();
if (classpathEntries.contains(file)) {
collector.add(file.getAbsolutePath());
}
}

for (ResolvedDependency child : dep.getChildren()) {
collectDependencies(child, collector, classpathEntries);
}
}

/**
* Writes the export map to a JSON file. Each key (a classpath entry) maps to
* a JSON array of classpath entry paths of its dependencies.
*/
private void writeMapToJson(File outputFile, Map<String, Set<String>> exportMap) {
try {
JSONArray jsonArray = new JSONArray();

for (Map.Entry<String, Set<String>> entry : exportMap.entrySet()) {
JSONObject obj = new JSONObject();
obj.put(METADATA_PROVIDER, entry.getKey());

JSONArray providedArray = new JSONArray();
entry.getValue().forEach(providedArray::put);
obj.put(PROVIDES_FOR, providedArray);

jsonArray.put(obj);
}

try (FileWriter writer = new FileWriter(outputFile)) {
writer.write(jsonArray.toString(2));
}
} catch (IOException e) {
GraalVMLogger.of(getLogger()).log("Failed to write dynamic access metadata JSON: {}", e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,7 @@ protected void populateClasspath() throws MojoExecutionException {
addDependenciesToClasspath();
}
addInferredDependenciesToClasspath();
maybeAddDynamicAccessMetadataToClasspath();
imageClasspath.removeIf(entry -> !entry.toFile().exists());
}

Expand Down Expand Up @@ -543,7 +544,11 @@ protected void maybeAddGeneratedResourcesConfig(List<String> into) {
}
}


protected void maybeAddDynamicAccessMetadataToClasspath() {
if (Files.exists(Path.of(outputDirectory.getPath() ,"dynamic-access-metadata.json"))) {
imageClasspath.add(Path.of(outputDirectory.getPath() ,"dynamic-access-metadata.json"));
}
}

protected void maybeAddReachabilityMetadata(List<String> configDirs) {
if (isMetadataRepositoryEnabled() && !metadataRepositoryConfigurations.isEmpty()) {
Expand Down
Loading
Loading