diff --git a/common/graalvm-reachability-metadata/src/main/java/org/graalvm/reachability/internal/FileSystemRepository.java b/common/graalvm-reachability-metadata/src/main/java/org/graalvm/reachability/internal/FileSystemRepository.java index e1d645a75..1fc00bba9 100644 --- a/common/graalvm-reachability-metadata/src/main/java/org/graalvm/reachability/internal/FileSystemRepository.java +++ b/common/graalvm-reachability-metadata/src/main/java/org/graalvm/reachability/internal/FileSystemRepository.java @@ -133,6 +133,10 @@ public Set findConfigurationsFor(Consumer .collect(Collectors.toSet()); } + public Path getRootDirectory() { + return rootDirectory; + } + /** * Allows getting insights about how configuration is picked. */ diff --git a/common/utils/src/main/java/org/graalvm/buildtools/utils/DynamicAccessMetadataUtils.java b/common/utils/src/main/java/org/graalvm/buildtools/utils/DynamicAccessMetadataUtils.java new file mode 100644 index 000000000..654b680c3 --- /dev/null +++ b/common/utils/src/main/java/org/graalvm/buildtools/utils/DynamicAccessMetadataUtils.java @@ -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 readArtifacts(File inputFile) throws IOException { + Set 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. + *

+ * The output follows the schema defined at: + * + * dynamic-access-metadata-schema-v1.0.0.json + * + */ + public static void serialize(File outputFile, Map> exportMap) throws IOException { + JSONArray jsonArray = new JSONArray(); + + for (Map.Entry> 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)); + } + } +} diff --git a/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/NativeImagePlugin.java b/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/NativeImagePlugin.java index 6d5a79011..a92a4c321 100644 --- a/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/NativeImagePlugin.java +++ b/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/NativeImagePlugin.java @@ -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; @@ -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; @@ -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 = 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 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); }); @@ -656,6 +679,18 @@ private TaskProvider registerResourcesConfigTask(Pr }); } + private TaskProvider registerDynamicAccessMetadataTask(Configuration classpathConfiguration, + Provider 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) { diff --git a/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/internal/GraalVMReachabilityMetadataService.java b/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/internal/GraalVMReachabilityMetadataService.java index fd0537ef2..07e9518fd 100644 --- a/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/internal/GraalVMReachabilityMetadataService.java +++ b/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/internal/GraalVMReachabilityMetadataService.java @@ -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; @@ -235,4 +236,11 @@ public Set findConfigurationsFor(Set excludedMod query.useLatestConfigWhenVersionIsUntested(); }); } + + public Optional getRepositoryDirectory() { + if (repository instanceof FileSystemRepository fsRepo) { + return Optional.of(fsRepo.getRootDirectory()); + } + return Optional.empty(); + } } diff --git a/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/tasks/GenerateDynamicAccessMetadata.java b/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/tasks/GenerateDynamicAccessMetadata.java new file mode 100644 index 000000000..2fc05396c --- /dev/null +++ b/native-gradle-plugin/src/main/java/org/graalvm/buildtools/gradle/tasks/GenerateDynamicAccessMetadata.java @@ -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. + *

+ * If {@value #LIBRARY_AND_FRAMEWORK_LIST} doesn't exist in the used release of the + * {@code GraalVM Reachability Metadata} repository, this task does nothing. + *

+ * The format of the generated JSON file conforms the following + * schema. + */ +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 getRuntimeClasspathGraph(); + + @Internal + public abstract SetProperty getRuntimeClasspathArtifacts(); + + @Internal + public abstract Property getMetadataService(); + + @OutputFile + public abstract RegularFileProperty getOutputJson(); + + @TaskAction + public void generate() { + Optional 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 artifactsToInclude = DynamicAccessMetadataUtils.readArtifacts(jsonFile); + + Map 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> 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> buildExportMap(ResolvedComponentResult root, Set artifactsToInclude, Map coordinatesToPath) { + Map> exportMap = new HashMap<>(); + Map> dependencyMap = new HashMap<>(); + + collectDependencies(root, dependencyMap, new LinkedHashSet<>(), coordinatesToPath); + + for (Map.Entry> 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> dependencyMap, Set visited, Map coordinatesToPath) { + String coordinates = null; + if (node.getId() instanceof ModuleComponentIdentifier mci) { + coordinates = mci.getGroup() + ":" + mci.getModule(); + } + + if (coordinates != null && !visited.add(coordinates)) { + return; + } + + Set 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 transitiveDependencies = dependencyMap.get(dependencyCoordinates); + if (transitiveDependencies != null) { + dependencies.addAll(transitiveDependencies); + } + } + } + } + dependencyMap.put(coordinates, dependencies); + } + + private void serializeExportMap(File outputFile, Map> exportMap) throws IOException { + DynamicAccessMetadataUtils.serialize(outputFile, exportMap); + GraalVMLogger.of(getLogger()).lifecycle("Dynamic Access Metadata written into " + outputFile); + } +} diff --git a/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/AbstractNativeImageMojo.java b/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/AbstractNativeImageMojo.java index ae27dd6a3..d1034f9d6 100644 --- a/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/AbstractNativeImageMojo.java +++ b/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/AbstractNativeImageMojo.java @@ -437,6 +437,7 @@ protected void populateClasspath() throws MojoExecutionException { addDependenciesToClasspath(); } addInferredDependenciesToClasspath(); + maybeAddDynamicAccessMetadataToClasspath(); imageClasspath.removeIf(entry -> !entry.toFile().exists()); } @@ -543,7 +544,11 @@ protected void maybeAddGeneratedResourcesConfig(List 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 configDirs) { if (isMetadataRepositoryEnabled() && !metadataRepositoryConfigurations.isEmpty()) { diff --git a/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/NativeBuildDynamicAccessMetadataMojo.java b/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/NativeBuildDynamicAccessMetadataMojo.java new file mode 100644 index 000000000..0c9aef719 --- /dev/null +++ b/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/NativeBuildDynamicAccessMetadataMojo.java @@ -0,0 +1,186 @@ +/* + * 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.maven; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.RepositorySystemSession; +import org.eclipse.aether.artifact.DefaultArtifact; +import org.eclipse.aether.collection.CollectRequest; +import org.eclipse.aether.collection.DependencyCollectionException; +import org.eclipse.aether.graph.Dependency; +import org.eclipse.aether.graph.DependencyNode; +import org.eclipse.aether.repository.RemoteRepository; +import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator; +import org.graalvm.buildtools.utils.DynamicAccessMetadataUtils; +import org.graalvm.reachability.internal.FileSystemRepository; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +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. + *

+ * If {@value #LIBRARY_AND_FRAMEWORK_LIST} doesn't exist in the used release of the + * {@code GraalVM Reachability Metadata} repository, this task does nothing. + *

+ * The format of the generated JSON file conforms the following + * schema. + */ +@Mojo(name = "generateDynamicAccessMetadata", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, requiresDependencyResolution = ResolutionScope.RUNTIME, requiresDependencyCollection = ResolutionScope.RUNTIME) +public class NativeBuildDynamicAccessMetadataMojo extends AbstractNativeMojo { + private static final String LIBRARY_AND_FRAMEWORK_LIST = "library-and-framework-list.json"; + + @Component + private RepositorySystem repoSystem; + + @Parameter(defaultValue = "${repositorySystemSession}", readonly = true) + private RepositorySystemSession repoSession; + + @Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true) + private List remoteRepos; + + @Parameter(defaultValue = "${project.build.directory}/dynamic-access-metadata.json", required = true) + private File outputJson; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + configureMetadataRepository(); + File jsonFile = ((FileSystemRepository) metadataRepository).getRootDirectory().resolve(LIBRARY_AND_FRAMEWORK_LIST).toFile(); + + if (!jsonFile.exists()) { + getLog().warn(LIBRARY_AND_FRAMEWORK_LIST + " is not packaged with the provided reachability metadata repository."); + return; + } + + try { + Set artifactsToInclude = DynamicAccessMetadataUtils.readArtifacts(jsonFile); + + Map coordinatesToPath = new HashMap<>(); + for (Artifact artifact : project.getArtifacts()) { + File file = artifact.getFile(); + if (file != null) { + String coordinates = artifact.getGroupId() + ":" + artifact.getArtifactId(); + coordinatesToPath.put(coordinates, file.getAbsolutePath()); + } + } + + Map> exportMap = buildExportMap(artifactsToInclude, coordinatesToPath); + + serializeExportMap(outputJson, exportMap); + } catch (IOException e) { + getLog().warn("Failed generating dynamic access metadata: " + e); + } catch (DependencyCollectionException e) { + getLog().warn("Failed collecting dependencies: " + 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> buildExportMap(Set artifactsToInclude, Map coordinatesToPath) throws DependencyCollectionException { + Map> exportMap = new HashMap<>(); + + for (Artifact artifact : project.getArtifacts()) { + String coordinates = artifact.getGroupId() + ":" + artifact.getArtifactId(); + if (!artifactsToInclude.contains(coordinates) || artifact.getFile() == null) { + continue; + } + + Set transitiveDependencies = collectDependencies( + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion(), + coordinatesToPath); + + exportMap.put(artifact.getFile().getAbsolutePath(), transitiveDependencies); + } + return exportMap; + } + + /** + * Recursively collects all classpath entry paths for the given dependency and its transitive dependencies. + */ + private Set collectDependencies(String coordinates, Map coordinatesToPath) throws DependencyCollectionException { + DefaultArtifact artifact = new DefaultArtifact(coordinates); + + CollectRequest collectRequest = new CollectRequest(); + collectRequest.setRoot(new Dependency(artifact, "")); + collectRequest.setRepositories(remoteRepos); + + DependencyNode node = repoSystem.collectDependencies(repoSession, collectRequest).getRoot(); + + PreorderNodeListGenerator nlg = new PreorderNodeListGenerator(); + node.accept(nlg); + + Set dependencies = new LinkedHashSet<>(); + nlg.getNodes().forEach(dependencyNode -> { + if (dependencyNode.getDependency() != null) { + DefaultArtifact dependencyArtifact = (DefaultArtifact) dependencyNode.getDependency().getArtifact(); + String dependencyPath = coordinatesToPath.get(dependencyArtifact.getGroupId() + ":" + dependencyArtifact.getArtifactId()); + if (dependencyPath != null) { + dependencies.add(dependencyPath); + } + } + }); + + return dependencies; + } + + private void serializeExportMap(File outputFile, Map> exportMap) throws IOException { + DynamicAccessMetadataUtils.serialize(outputFile, exportMap); + getLog().info("Dynamic Access Metadata written into " + outputFile); + } +} diff --git a/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/NativeCompileNoForkMojo.java b/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/NativeCompileNoForkMojo.java index 4ad126b3d..a9baff345 100644 --- a/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/NativeCompileNoForkMojo.java +++ b/native-maven-plugin/src/main/java/org/graalvm/buildtools/maven/NativeCompileNoForkMojo.java @@ -55,6 +55,7 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; import org.graalvm.buildtools.maven.sbom.SBOMGenerator; import org.graalvm.buildtools.utils.NativeImageUtils; +import org.twdata.maven.mojoexecutor.MojoExecutor; import java.util.Arrays; import java.util.List; @@ -111,11 +112,37 @@ public void execute() throws MojoExecutionException { maybeSetMainClassFromPlugin(this::consumeConfigurationNodeValue, "org.apache.maven.plugins:maven-jar-plugin", "archive", "manifest", "mainClass"); maybeAddGeneratedResourcesConfig(buildArgs); + generateDynamicAccessMetadataIfNeeded(buildArgs); + generateBaseSBOMIfNeeded(); buildImage(); } + /** + * Executes the {@code generateDynamicAccessMetadata} goal of the + * {@code native-maven-plugin} if the build arguments indicate that + * a build report should be emitted. + * + * @throws MojoExecutionException if executing the {@code generateDynamicAccessMetadata} + * Mojo fails + */ + private void generateDynamicAccessMetadataIfNeeded(List buildArgs) throws MojoExecutionException { + if (buildArgs.stream().anyMatch(arg -> arg.startsWith("--emit build-report"))) { + MojoExecutor.executeMojo( + MojoExecutor.plugin( + MojoExecutor.groupId(project.getPlugin("org.graalvm.buildtools:native-maven-plugin").getGroupId()), + MojoExecutor.artifactId(project.getPlugin("org.graalvm.buildtools:native-maven-plugin").getArtifactId()), + MojoExecutor.version(project.getPlugin("org.graalvm.buildtools:native-maven-plugin").getVersion()) + ), + MojoExecutor.goal("generateDynamicAccessMetadata"), + MojoExecutor.configuration( + MojoExecutor.element("outputJson", "${project.build.directory}/dynamic-access-metadata.json") + ), + MojoExecutor.executionEnvironment(project, session, pluginManager)); + } + } + /** * Invokes {@link SBOMGenerator#generateIfSupportedAndEnabled} if {@link NativeCompileNoForkMojo#skipBaseSBOM} * is false.