Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.graalvm.buildtools.utils;

import com.github.openjson.JSONArray;
import com.github.openjson.JSONObject;

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

public final class DynamicAccessMetadataUtils {
/**
* Collects all versionless artifact coordinates ({@code groupId:artifactId}) from each
* entry in the {@code library-and-framework-list.json} file.
*/
public static Set<String> readArtifacts(File inputFile) throws IOException {
Set<String> artifacts = new LinkedHashSet<>();
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;
}

/**
* Serializes dynamic access metadata to JSON.
* <p>
* The output follows the schema defined at:
* <a href="https://github.com/oracle/graal/blob/master/docs/reference-manual/native-image/assets/dynamic-access-metadata-schema-v1.0.0.json">
* dynamic-access-metadata-schema-v1.0.0.json
* </a>
*/
public static void serialize(File outputFile, Map<String, Set<String>> exportMap) throws IOException {
JSONArray jsonArray = new JSONArray();

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

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

jsonArray.put(obj);
}

try (FileWriter writer = new FileWriter(outputFile)) {
writer.write(jsonArray.toString(2));
}
}
}
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,27 @@ 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 -> {
Provider<Boolean> emittingBuildReport =
buildImageTask.getOptions()
.flatMap(o -> o.getBuildArgs()
.map(args -> args.stream()
.anyMatch(arg -> arg.startsWith("--emit build-report"))));
options.getClasspath().from(
emittingBuildReport.flatMap(enabled ->
enabled
? generateDynamicAccessMetadata.flatMap(task ->
task.getOutputJson().map(RegularFile::getAsFile))
: buildImageTask.getProject().provider(Collections::emptyList))
);
});

configureJvmReachabilityConfigurationDirectories(project, graalExtension, options, sourceSet);
configureJvmReachabilityExcludeConfigArgs(project, graalExtension, options, sourceSet);
});
Expand Down Expand Up @@ -656,6 +679,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.setClasspath(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 @@ -71,6 +71,7 @@
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
Expand Down Expand Up @@ -235,4 +236,11 @@ public Set<DirectoryConfiguration> findConfigurationsFor(Set<String> excludedMod
query.useLatestConfigWhenVersionIsUntested();
});
}

public Optional<Path> getRepositoryDirectory() {
if (repository instanceof FileSystemRepository fsRepo) {
return Optional.of(fsRepo.getRootDirectory());
}
return Optional.empty();
}
}
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 org.graalvm.buildtools.gradle.internal.GraalVMLogger;
import org.graalvm.buildtools.gradle.internal.GraalVMReachabilityMetadataService;
import org.graalvm.buildtools.utils.DynamicAccessMetadataUtils;
import org.gradle.api.DefaultTask;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.artifacts.result.DependencyResult;
import org.gradle.api.artifacts.result.ResolvedArtifactResult;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
import org.gradle.api.artifacts.result.ResolvedDependencyResult;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.provider.Property;
import org.gradle.api.provider.SetProperty;
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.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Optional;
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";

public void setClasspath(Configuration classpath) {
getRuntimeClasspathGraph().set(classpath.getIncoming().getResolutionResult().getRootComponent());
getRuntimeClasspathArtifacts().set(classpath.getIncoming().getArtifacts().getResolvedArtifacts());
}

@Internal
public abstract Property<ResolvedComponentResult> getRuntimeClasspathGraph();

@Internal
public abstract SetProperty<ResolvedArtifactResult> getRuntimeClasspathArtifacts();

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

@OutputFile
public abstract RegularFileProperty getOutputJson();

@TaskAction
public void generate() {
Optional<Path> repositoryDirectory = getMetadataService().get().getRepositoryDirectory();
if (repositoryDirectory.isEmpty()) {
GraalVMLogger.of(getLogger())
.log("No reachability metadata repository is configured or available.");
return;
}
File jsonFile = repositoryDirectory.get().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 = DynamicAccessMetadataUtils.readArtifacts(jsonFile);

Map<String, String> coordinatesToPath = new HashMap<>();
for (ResolvedArtifactResult artifact : getRuntimeClasspathArtifacts().get()) {
if (artifact.getId().getComponentIdentifier() instanceof ModuleComponentIdentifier mci) {
String coordinates = mci.getGroup() + ":" + mci.getModule();
coordinatesToPath.put(coordinates, artifact.getFile().getAbsolutePath());
}
}

ResolvedComponentResult root = getRuntimeClasspathGraph().get();

Map<String, Set<String>> exportMap = buildExportMap(root, artifactsToInclude, coordinatesToPath);

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

/**
* 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(ResolvedComponentResult root, Set<String> artifactsToInclude, Map<String, String> coordinatesToPath) {
Map<String, Set<String>> exportMap = new HashMap<>();
Map<String, Set<String>> dependencyMap = new HashMap<>();

collectDependencies(root, dependencyMap, new LinkedHashSet<>(), coordinatesToPath);

for (Map.Entry<String, Set<String>> entry : dependencyMap.entrySet()) {
String coordinates = entry.getKey();
if (artifactsToInclude.contains(coordinates)) {
String absolutePath = coordinatesToPath.get(coordinates);
if (absolutePath != null) {
exportMap.put(absolutePath, entry.getValue());
}
}
}

return exportMap;
}

/**
* Recursively collects all classpath entry paths for the given dependency and its transitive dependencies.
*/
private void collectDependencies(ResolvedComponentResult node, Map<String, Set<String>> dependencyMap, Set<String> visited, Map<String, String> coordinatesToPath) {
String coordinates = null;
if (node.getId() instanceof ModuleComponentIdentifier mci) {
coordinates = mci.getGroup() + ":" + mci.getModule();
}

if (coordinates != null && !visited.add(coordinates)) {
return;
}

Set<String> dependencies = new LinkedHashSet<>();
for (DependencyResult dep : node.getDependencies()) {
if (dep instanceof ResolvedDependencyResult resolved) {
ResolvedComponentResult target = resolved.getSelected();

if (target.getId() instanceof ModuleComponentIdentifier targetMci) {
String dependencyCoordinates = targetMci.getGroup() + ":" + targetMci.getModule();
String dependencyPath = coordinatesToPath.get(dependencyCoordinates);

if (dependencyPath != null) {
dependencies.add(dependencyPath);
}

collectDependencies(target, dependencyMap, visited, coordinatesToPath);

Set<String> transitiveDependencies = dependencyMap.get(dependencyCoordinates);
if (transitiveDependencies != null) {
dependencies.addAll(transitiveDependencies);
}
}
}
}
dependencyMap.put(coordinates, dependencies);
}

private void serializeExportMap(File outputFile, Map<String, Set<String>> exportMap) throws IOException {
DynamicAccessMetadataUtils.serialize(outputFile, exportMap);
GraalVMLogger.of(getLogger()).lifecycle("Dynamic Access Metadata written into " + outputFile);
}
}
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