Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions maven-plugin/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@
<artifactId>maven-settings</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;

import io.smallrye.classfile.ClassFile;
import io.smallrye.classfile.ClassModel;
Expand All @@ -19,6 +20,26 @@
public abstract class AbstractTransformMojo extends AbstractMojo {
private static final ClassFile cf = ClassFile.of(ClassFile.StackMapsOption.STACK_MAPS_WHEN_REQUIRED);

/**
* The project group ID, used in the path of the generated native image metadata.
*/
@Parameter(defaultValue = "${project.groupId}", readonly = true)
private String groupId;

/**
* The project artifact ID, used in the path of the generated native image metadata.
*/
@Parameter(defaultValue = "${project.artifactId}", readonly = true)
private String artifactId;

/**
* Skip writing the GraalVM native image metadata
* ({@code META-INF/native-image/<groupId>/<artifactId>/smallrye-ffm/reachability-metadata.json})
* which registers the downcalls linked by the transformed classes.
*/
@Parameter(defaultValue = "false", property = "smallrye-ffm.skipNativeMetadata")
private boolean skipNativeMetadata;
Comment on lines +40 to +41

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we please make this opt-in instead of opt-out?


/**
* Construct a new instance.
*/
Expand All @@ -28,20 +49,33 @@ public abstract class AbstractTransformMojo extends AbstractMojo {
public void execute() throws MojoExecutionException, MojoFailureException {
Path classes = classesDirectory().toPath();
getLog().info("Transforming classes in path: " + classes);
int cnt = processPath(classes);
NativeMetadata metadata = new NativeMetadata();
int cnt = processPath(classes, metadata);
if (!skipNativeMetadata) {
Path file = classes.resolve("META-INF").resolve("native-image").resolve(groupId).resolve(artifactId)
.resolve("smallrye-ffm").resolve("reachability-metadata.json");
try {
metadata.write(file);
} catch (IOException e) {
throw new MojoFailureException("Failed to write " + file, e);
}
if (!metadata.downcalls().isEmpty()) {
getLog().info("Registered " + metadata.downcalls().size() + " downcall shapes for native image in " + file);
}
}
switch (cnt) {
case 0 -> getLog().info("No classes transformed");
case 1 -> getLog().info("Transformed 1 class");
default -> getLog().info("Transformed " + cnt + " classes");
}
}

private int processPath(final Path path) throws MojoFailureException {
private int processPath(final Path path, final NativeMetadata metadata) throws MojoFailureException {
int cnt = 0;
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
for (Path file : ds) {
if (Files.isDirectory(file)) {
cnt += processPath(file);
cnt += processPath(file, metadata);
} else if (file.getFileName().toString().endsWith(".class")) {
ClassModel cm;
try {
Expand All @@ -59,11 +93,14 @@ private int processPath(final Path path) throws MojoFailureException {
});
if (resHolder.res) {
cnt++;
metadata.addClass(cf.parse(result));
try {
Files.write(file, result);
} catch (IOException e) {
throw new MojoFailureException("Failed to write " + file, e);
}
} else {
metadata.addClass(cm);
}
}
}
Expand Down
206 changes: 206 additions & 0 deletions maven-plugin/src/main/java/io/smallrye/ffm/maven/NativeMetadata.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
package io.smallrye.ffm.maven;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import io.smallrye.classfile.ClassModel;
import io.smallrye.classfile.CodeElement;
import io.smallrye.classfile.MethodModel;
import io.smallrye.classfile.instruction.InvokeDynamicInstruction;

/**
* The GraalVM native image reachability metadata for the downcalls linked by transformed classes.
* <p>
* native-image compiles one stub for each downcall shape at build time, and each shape must be registered
* in the {@code foreign} section of a {@code reachability-metadata.json} file.
* The shapes are read back from the {@code invokedynamic} instructions which use the {@code Bootstraps.downcall}
* bootstrap, so classes which were transformed by an earlier build are included as well.
* <p>
* The layouts are those which {@code Bootstraps} selects on a 64-bit platform (the only kind native-image supports).
* The C {@code long} and {@code wchar_t} types are given by their canonical layout names, which native-image resolves
* for the target platform.
* The C {@code char} type is a {@code jbyte} where it is signed and a {@code jint} where it is unsigned,
* so a shape which uses it is registered in both forms.
*/
final class NativeMetadata {
private static final String BOOTSTRAPS = "io/smallrye/ffm/Bootstraps";

private final Set<String> downcalls = new TreeSet<>();

NativeMetadata() {
}

/**
* Add the downcall shapes linked by the given class.
*
* @param cm the class model (must not be {@code null})
*/
void addClass(ClassModel cm) {
for (MethodModel mm : cm.methods()) {
mm.code().ifPresent(code -> {
for (CodeElement ce : code) {
if (ce instanceof InvokeDynamicInstruction idi
&& idi.bootstrapMethod().owner().descriptorString().equals("L" + BOOTSTRAPS + ";")
&& idi.bootstrapMethod().methodName().equals("downcall")) {
downcalls.addAll(entries(idi.name().stringValue()));
}
}
});
}
}

/**
* {@return the downcall entries, in a stable order}
*/
Set<String> downcalls() {
return downcalls;
}

/**
* Write the metadata file, or delete it if there are no downcalls.
*
* @param file the file to write (must not be {@code null})
* @throws IOException if the file could not be written
*/
void write(Path file) throws IOException {
if (downcalls.isEmpty()) {
Files.deleteIfExists(file);
return;
}
StringBuilder sb = new StringBuilder();
sb.append("{\n");
sb.append(" \"comment\": \"Generated by smallrye-ffm-maven-plugin for the downcalls linked by this module\",\n");
sb.append(" \"foreign\": {\n");
sb.append(" \"downcalls\": [\n");
boolean first = true;
for (String entry : downcalls) {
if (!first) {
sb.append(",\n");
}
first = false;
sb.append(" ").append(entry);
}
sb.append("\n ]\n");
sb.append(" }\n");
sb.append("}\n");
Files.createDirectories(file.getParent());
byte[] bytes = sb.toString().getBytes(StandardCharsets.UTF_8);
if (Files.exists(file) && Arrays.equals(Files.readAllBytes(file), bytes)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What happens if something else is competing to write the metadata for other things, like reflection etc.?

// keep the time stamp
return;
}
Files.write(file, bytes);
}

/**
* Get the {@code foreign.downcalls} entries for a downcall descriptor of the form produced by the generator,
* for example {@code e(*sI~*)sI}.
*
* @param desc the downcall descriptor (must not be {@code null})
* @return the JSON entries (one, or two if the descriptor uses the C {@code char} type)
*/
static List<String> entries(String desc) {
String signedChar = entry(desc, "jbyte");
String unsignedChar = entry(desc, "jint");
return signedChar.equals(unsignedChar) ? List.of(signedChar) : List.of(signedChar, unsignedChar);
}

private static String entry(String desc, String charLayout) {
boolean capture = false;
int critical = -1;
int i = 0;
loop: for (;; i++) {
switch (desc.charAt(i)) {
case 'e', 'E', 'W' -> capture = true;
case 'r' -> critical = Math.max(critical, 0);
case 'R' -> critical = 1;
case '(' -> {
i++;
break loop;
}
default -> throw invalid(desc);
}
}
int firstVariadic = -1;
List<String> params = new ArrayList<>();
while (desc.charAt(i) != ')') {
if (desc.charAt(i) == '~') {
firstVariadic = params.size();
i++;
} else {
params.add(layout(desc, i, firstVariadic != -1, charLayout));
i += desc.charAt(i) == 'u' || desc.charAt(i) == 's' ? 2 : 1;
}
}
i++;
String ret = desc.charAt(i) == 'V' ? "void" : layout(desc, i, false, charLayout);
StringBuilder sb = new StringBuilder();
sb.append("{\"returnType\": \"").append(ret).append("\", \"parameterTypes\": [");
for (int j = 0; j < params.size(); j++) {
if (j > 0) {
sb.append(", ");
}
sb.append('"').append(params.get(j)).append('"');
}
sb.append(']');
if (capture || firstVariadic != -1 || critical != -1) {
sb.append(", \"options\": {");
String sep = "";
if (capture) {
sb.append("\"captureCallState\": true");
sep = ", ";
}
if (firstVariadic != -1) {
sb.append(sep).append("\"firstVariadicArg\": ").append(firstVariadic);
sep = ", ";
}
if (critical != -1) {
sb.append(sep).append("\"critical\": {\"allowHeapAccess\": ").append(critical == 1).append('}');
}
sb.append('}');
}
sb.append('}');
return sb.toString();
}

/**
* {@return the canonical layout name for the descriptor item at the given offset}
* This follows {@code Bootstraps.layoutOf} for a 64-bit platform.
*/
private static String layout(String desc, int offs, boolean variadic, String charLayout) {
return switch (desc.charAt(offs)) {
case 'u' -> switch (desc.charAt(offs + 1)) {
case 'B', 'c', 's', 'S' -> "jint";
case 'I', 'i', 'J', 'l', '*' -> "jlong";
default -> throw invalid(desc);
};
case 'e' -> "jint";
case 's' -> switch (desc.charAt(offs + 1)) {
case 'B', 'c' -> "jbyte";
case 'S', 's' -> "jshort";
case 'I', 'i' -> "jint";
case 'l' -> "long";
case 'J', '*' -> "jlong";
default -> throw invalid(desc);
};
case 'c' -> charLayout;
case 'w' -> "wchar_t";
case '*' -> "void*";
case 'Z' -> "jboolean";
case 'F' -> variadic ? "jdouble" : "jfloat";
case 'D' -> "jdouble";
default -> throw invalid(desc);
};
}

private static IllegalArgumentException invalid(String desc) {
return new IllegalArgumentException("Invalid downcall descriptor " + desc);
}
}
Loading
Loading