From 1553959cf413e4f51f586b45b83386210ac374ef Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 5 Oct 2026 18:24:53 +0200 Subject: [PATCH] Limit pack modules to the API, the JDK and their own pack The pack class loader's parent is now ApiAndJdkClassLoader: com.volmit. classes and resources come from the API's loader, everything else from the platform loader, so modules no longer see Iris internals or the libraries Iris bundles. Before any class is defined, a pack load now fails when a jar holds a com.volmit. class, and when a class references a class that is not in the API, the JDK or a jar of the pack (read with java.lang.classfile). Linkage errors while installing name the module's jar. ModuleInfo names and versions reject line breaks and other control characters. --- src/main/java/com/volmit/ModuleInfo.java | 28 +++- .../com/volmit/host/ApiAndJdkClassLoader.java | 67 +++++++++ .../java/com/volmit/host/ClassReferences.java | 71 ++++++++++ .../java/com/volmit/host/LoadedModules.java | 17 ++- src/main/java/com/volmit/host/ModuleJar.java | 72 ++++++++-- .../java/com/volmit/host/PackClassCheck.java | 110 +++++++++++++++ .../java/com/volmit/host/PackModules.java | 42 ++---- src/test/java/com/volmit/ApiValuesTest.java | 10 ++ .../volmit/host/ApiAndJdkClassLoaderTest.java | 48 +++++++ .../java/com/volmit/host/PackModulesTest.java | 131 +++++++++++++++++- .../com/volmit/support/TestModuleJar.java | 27 +++- 11 files changed, 563 insertions(+), 60 deletions(-) create mode 100644 src/main/java/com/volmit/host/ApiAndJdkClassLoader.java create mode 100644 src/main/java/com/volmit/host/ClassReferences.java create mode 100644 src/main/java/com/volmit/host/PackClassCheck.java create mode 100644 src/test/java/com/volmit/host/ApiAndJdkClassLoaderTest.java diff --git a/src/main/java/com/volmit/ModuleInfo.java b/src/main/java/com/volmit/ModuleInfo.java index b4b6743e1..3a1ed26f0 100644 --- a/src/main/java/com/volmit/ModuleInfo.java +++ b/src/main/java/com/volmit/ModuleInfo.java @@ -4,22 +4,36 @@ import com.volmit.resource.ResourceId; import java.util.Objects; /** Module identity. Stages a module defines must use the namespace of its id. The name is for - * people, for example in load logs; the id is what the host and other modules match on. + * people, for example in load logs; the id is what the host and other modules match on. Name and + * version must fit on one log line, so they reject control characters such as line breaks. */ public record ModuleInfo(ResourceId id, String name, String version) { public ModuleInfo { Objects.requireNonNull(id, "id"); Objects.requireNonNull(name, "name"); Objects.requireNonNull(version, "version"); - if (name.isBlank()) { - throw new IllegalArgumentException("Blank module name: " + id); - } - if (version.isBlank()) { - throw new IllegalArgumentException("Blank module version: " + id); - } + requireOneLineText(id, "name", name); + requireOneLineText(id, "version", version); } public static ModuleInfo of(String id, String name, String version) { return new ModuleInfo(ResourceId.parse(id), name, version); } + + private static void requireOneLineText(ResourceId id, String field, String value) { + if (value.isBlank()) { + throw new IllegalArgumentException("Blank module " + field + ": " + id); + } + if (value.chars().anyMatch(ModuleInfo::breaksLogLine)) { + throw new IllegalArgumentException("Module " + field + " of " + id + + " contains a line break or other control character"); + } + } + + private static boolean breaksLogLine(int character) { + var type = Character.getType(character); + return Character.isISOControl(character) + || type == Character.LINE_SEPARATOR + || type == Character.PARAGRAPH_SEPARATOR; + } } diff --git a/src/main/java/com/volmit/host/ApiAndJdkClassLoader.java b/src/main/java/com/volmit/host/ApiAndJdkClassLoader.java new file mode 100644 index 000000000..94fac97d8 --- /dev/null +++ b/src/main/java/com/volmit/host/ApiAndJdkClassLoader.java @@ -0,0 +1,67 @@ +package com.volmit.host; + +import java.io.IOException; +import java.net.URL; +import java.util.Enumeration; +import java.util.Objects; + +/** Parent of every pack class loader. It shows a pack the Iris API and the JDK and nothing else: + * API classes come from the loader that defines the API, every other class from the platform class + * loader. Iris internals and the libraries Iris bundles stay hidden even when they sit in the API's + * loader, so a module can use only the API, the JDK and the classes of its own pack's jars. + * + *

Resources follow the same rule, by path: {@code com/volmit/...} from the API's loader, + * everything else from the platform loader. A class and its class file therefore always come from + * the same place, and a pack never sees Iris's own resources, such as its service files. + * + *

This loader defines no classes itself. + */ +final class ApiAndJdkClassLoader extends ClassLoader { + /** Every class in a package with this prefix belongs to the Iris API. Module classes must not use it. */ + static final String API_PACKAGE_PREFIX = "com.volmit."; + private static final String API_RESOURCE_PREFIX = API_PACKAGE_PREFIX.replace('.', '/'); + private static final String CLASS_FILE_SUFFIX = ".class"; + private static final String NAME = "iris-api-and-jdk"; + + static { + registerAsParallelCapable(); + } + + private final ClassLoader apiLoader; + + ApiAndJdkClassLoader(ClassLoader apiLoader) { + super(NAME, ClassLoader.getPlatformClassLoader()); + this.apiLoader = Objects.requireNonNull(apiLoader, "apiLoader"); + } + + static boolean isApiClass(String binaryName) { + return binaryName.startsWith(API_PACKAGE_PREFIX); + } + + /** Whether this loader can load the class, judged by its class file so that nothing is loaded. */ + boolean hasClass(String binaryName) { + return getResource(binaryName.replace('.', '/') + CLASS_FILE_SUFFIX) != null; + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + if (isApiClass(name)) return apiLoader.loadClass(name); + return super.loadClass(name, resolve); + } + + @Override + public URL getResource(String name) { + if (isApiResource(name)) return apiLoader.getResource(name); + return super.getResource(name); + } + + @Override + public Enumeration getResources(String name) throws IOException { + if (isApiResource(name)) return apiLoader.getResources(name); + return super.getResources(name); + } + + private static boolean isApiResource(String name) { + return name.startsWith(API_RESOURCE_PREFIX); + } +} diff --git a/src/main/java/com/volmit/host/ClassReferences.java b/src/main/java/com/volmit/host/ClassReferences.java new file mode 100644 index 000000000..a6bd988f5 --- /dev/null +++ b/src/main/java/com/volmit/host/ClassReferences.java @@ -0,0 +1,71 @@ +package com.volmit.host; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.constantpool.ClassEntry; +import java.lang.classfile.constantpool.MethodTypeEntry; +import java.lang.classfile.constantpool.NameAndTypeEntry; +import java.lang.classfile.constantpool.PoolEntry; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; +import java.util.Collections; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +/** The classes one class file links against, as binary names: every class in its constant pool + * (supertypes, instantiated, cast, caught and called-on types) and every type in the descriptors of + * its fields, methods and the members it uses. Arrays count as their element type; primitives do + * not count. + * + *

Annotations and generic signatures are left out. The JVM never resolves them while linking, + * and reflection skips annotations whose type is missing. + */ +final class ClassReferences { + private static final String METHOD_DESCRIPTOR_START = "("; + + private ClassReferences() {} + + /** Throws {@link IllegalArgumentException} when the bytes are not a valid class file. */ + static SortedSet read(byte[] classFile) { + var model = ClassFile.of().parse(classFile); + var references = new TreeSet(); + for (var entry : model.constantPool()) addPoolEntry(entry, references); + model.fields().forEach(field -> addType(field.fieldTypeSymbol(), references)); + model.methods().forEach(method -> addMethodType(method.methodTypeSymbol(), references)); + return Collections.unmodifiableSortedSet(references); + } + + private static void addPoolEntry(PoolEntry entry, Set references) { + switch (entry) { + case ClassEntry type -> addType(type.asSymbol(), references); + case NameAndTypeEntry member -> addDescriptor(member.type().stringValue(), references); + case MethodTypeEntry methodType -> addMethodType(methodType.asSymbol(), references); + default -> {} + } + } + + private static void addDescriptor(String descriptor, Set references) { + if (descriptor.startsWith(METHOD_DESCRIPTOR_START)) { + addMethodType(MethodTypeDesc.ofDescriptor(descriptor), references); + } else { + addType(ClassDesc.ofDescriptor(descriptor), references); + } + } + + private static void addMethodType(MethodTypeDesc type, Set references) { + addType(type.returnType(), references); + type.parameterList().forEach(parameter -> addType(parameter, references)); + } + + private static void addType(ClassDesc type, Set references) { + var element = type; + while (element.isArray()) element = element.componentType(); + if (element.isPrimitive()) return; + references.add(binaryName(element)); + } + + private static String binaryName(ClassDesc type) { + var descriptor = type.descriptorString(); + return descriptor.substring(1, descriptor.length() - 1).replace('/', '.'); + } +} diff --git a/src/main/java/com/volmit/host/LoadedModules.java b/src/main/java/com/volmit/host/LoadedModules.java index c9c50556d..6c323ef1a 100644 --- a/src/main/java/com/volmit/host/LoadedModules.java +++ b/src/main/java/com/volmit/host/LoadedModules.java @@ -24,10 +24,23 @@ public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, Res var registry = new ModuleRegistry(reservedHostFields); var stages = new StageGraphBuilder(); for (var discovered : modules) { - stages.install(discovered); - discovered.module().register(registry); + installModule(discovered, stages, registry); } stages.settingsTypes().forEach(registry::registerSettings); return new LoadedModules(registry.freeze(), stages.resolve(Pipeline.PLACEMENT), stages.resolve(Pipeline.CHUNK)); } + + /** The pack load checks that every class a module uses exists, not that every method or field + * it uses does, so a jar built against another Iris API can still fail to link here. + */ + private static void installModule(DiscoveredModule discovered, StageGraphBuilder stages, ModuleRegistry registry) { + try { + stages.install(discovered); + discovered.module().register(registry); + } catch (LinkageError error) { + throw new IllegalArgumentException("Module " + discovered.module().info().id() + " from " + + discovered.origin() + " failed to link or initialize a class while installing: " + error + + "; a missing method or field means the jar was built against a different Iris API", error); + } + } } diff --git a/src/main/java/com/volmit/host/ModuleJar.java b/src/main/java/com/volmit/host/ModuleJar.java index 340dd10c9..cd36af894 100644 --- a/src/main/java/com/volmit/host/ModuleJar.java +++ b/src/main/java/com/volmit/host/ModuleJar.java @@ -10,21 +10,25 @@ import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.Objects; +import java.util.SortedSet; import java.util.function.Predicate; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipFile; -/** One jar in a pack's modules directory, the entry class it names and the classes it holds. +/** One jar in a pack's modules directory, the entry class it names and the classes it holds, + * each with the classes it links against. * *

The entry point is the jar's own {@code META-INF/services/com.volmit.IrisModule} file, in * the format {@link java.util.ServiceLoader} reads. The host reads that file from this jar only: * {@code ServiceLoader} would also return providers from parent class loaders and could not tell * which jar a broken entry came from. */ -record ModuleJar(Path path, String origin, String entryClass, List classNames) { +record ModuleJar(Path path, String origin, String entryClass, List classes) { static final String ENTRY_POINT_FILE = "META-INF/services/" + IrisModule.class.getName(); private static final String COMMENT_START = "#"; private static final String CLASS_FILE_SUFFIX = ".class"; @@ -35,22 +39,37 @@ record ModuleJar(Path path, String origin, String entryClass, List class Objects.requireNonNull(path, "path"); Objects.requireNonNull(origin, "origin"); Objects.requireNonNull(entryClass, "entryClass"); - classNames = List.copyOf(classNames); + classes = List.copyOf(classes); + } + + /** A class in the jar, by binary name, and the binary names of the classes it links against. */ + record JarClass(String name, SortedSet references) { + JarClass { + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(references, "references"); + } } /** Reads the single entry class a jar names and the classes it holds. The origin is the jar - * path relative to its pack. + * path relative to its pack. Fails if the jar holds a class of the Iris API or a class file that + * cannot be parsed. */ static ModuleJar read(Path packRoot, Path jar) { var origin = packRoot.relativize(jar).toString(); try (var file = openAsClassLoaderSeesIt(jar)) { var entryClass = requireSingleEntryClass(origin, readEntryClasses(file)); - return new ModuleJar(jar, origin, entryClass, readClassNames(file)); + var classEntries = findClassEntries(file); + requireNoApiClasses(origin, classEntries); + return new ModuleJar(jar, origin, entryClass, readClasses(origin, file, classEntries)); } catch (IOException exception) { throw new UncheckedIOException("Module jar " + origin + " is not a readable jar", exception); } } + List classNames() { + return classes.stream().map(JarClass::name).toList(); + } + URL url() { try { return path.toUri().toURL(); @@ -102,18 +121,16 @@ record ModuleJar(Path path, String origin, String entryClass, List class } } - /** Binary names of the classes in the jar, sorted. A multi-release jar contributes each class + /** The class file entries of the jar, sorted by name. A multi-release jar contributes each class * once, under its base name, in the version this runtime would load. Anything left below * {@code META-INF/}, such as versioned entries of a jar that is not multi-release, cannot be * loaded as a class: {@code META-INF} is not a valid package name. */ - private static List readClassNames(JarFile file) { + private static List findClassEntries(JarFile file) { return file.versionedStream() .filter(Predicate.not(JarEntry::isDirectory)) - .map(JarEntry::getName) - .filter(ModuleJar::isClassFile) - .map(ModuleJar::toBinaryName) - .sorted() + .filter(entry -> isClassFile(entry.getName())) + .sorted(Comparator.comparing(entry -> toBinaryName(entry.getName()))) .toList(); } @@ -123,6 +140,39 @@ record ModuleJar(Path path, String origin, String entryClass, List class && !entryName.startsWith(META_INF); } + /** The API package prefix is reserved for the API that Iris provides at runtime. The pack loader + * asks the host for those classes first, so a packaged API class would be silently replaced by the + * host's copy, and a module's own class there could be replaced by a later API class of that name. + */ + private static void requireNoApiClasses(String origin, List classEntries) { + var apiClasses = classEntries.stream() + .map(entry -> toBinaryName(entry.getName())) + .filter(ApiAndJdkClassLoader::isApiClass) + .toList(); + if (apiClasses.isEmpty()) return; + var others = apiClasses.size() == 1 ? "" : " and " + (apiClasses.size() - 1) + " more"; + throw new IllegalArgumentException("Module jar " + origin + " contains Iris API class " + apiClasses.getFirst() + + others + "; Iris provides the API at runtime, so mark the Iris API dependency compileOnly" + + " (Maven: provided) and keep module classes out of " + ApiAndJdkClassLoader.API_PACKAGE_PREFIX + "*"); + } + + private static List readClasses(String origin, JarFile file, List classEntries) throws IOException { + var classes = new ArrayList(classEntries.size()); + for (var entry : classEntries) { + classes.add(new JarClass(toBinaryName(entry.getName()), readReferences(origin, file, entry))); + } + return classes; + } + + private static SortedSet readReferences(String origin, JarFile file, JarEntry entry) throws IOException { + try (var input = file.getInputStream(entry)) { + return ClassReferences.read(input.readAllBytes()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Module jar " + origin + " holds a class file this runtime cannot read, " + + entry.getRealName() + ": " + exception.getMessage(), exception); + } + } + private static String toBinaryName(String entryName) { return entryName.substring(0, entryName.length() - CLASS_FILE_SUFFIX.length()).replace('/', '.'); } diff --git a/src/main/java/com/volmit/host/PackClassCheck.java b/src/main/java/com/volmit/host/PackClassCheck.java new file mode 100644 index 000000000..79d090ac1 --- /dev/null +++ b/src/main/java/com/volmit/host/PackClassCheck.java @@ -0,0 +1,110 @@ +package com.volmit.host; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Checks the classes of all jars of one pack before its class loader exists, so a pack that + * cannot link fails at load with the jar to fix, not later with a {@link NoClassDefFoundError} + * during install or generation. + */ +final class PackClassCheck { + private static final int MAX_REPORTED_REFERENCES_PER_JAR = 10; + private static final String INDENT = " "; + + private PackClassCheck() {} + + /** Fails when a class is in two jars, or when a class uses a class that is neither in the API, + * the JDK nor a jar of the pack. + */ + static void requireLinkable(List jars, ApiAndJdkClassLoader apiAndJdk) { + requireDistinctClasses(jars); + requireResolvableReferences(jars, apiAndJdk); + } + + /** The shared pack loader would otherwise silently use whichever copy comes first in file name order. */ + private static void requireDistinctClasses(List jars) { + var owners = new HashMap(); + for (var jar : jars) { + for (var className : jar.classNames()) { + var owner = owners.putIfAbsent(className, jar); + if (owner != null) throw duplicateClass(className, owner, jar); + } + } + } + + private static IllegalArgumentException duplicateClass(String className, ModuleJar first, ModuleJar second) { + return new IllegalArgumentException("Class " + className + " is in both module jars " + first.origin() + + " and " + second.origin() + "; every class of a pack must come from one jar, so relocate" + + " shaded libraries or keep shared classes in one module"); + } + + private static void requireResolvableReferences(List jars, ApiAndJdkClassLoader apiAndJdk) { + var resolver = new ReferenceResolver(jars, apiAndJdk); + var unresolved = jars.stream() + .map(jar -> new UnresolvedReferences(jar, resolver.unresolvedIn(jar))) + .filter(UnresolvedReferences::any) + .toList(); + if (!unresolved.isEmpty()) throw unresolvedReferences(unresolved); + } + + private static IllegalArgumentException unresolvedReferences(List jars) { + var text = new StringBuilder(); + for (var jar : jars) jar.describeTo(text); + text.append("A module can use only the Iris API, the JDK and the classes in its pack's module jars;" + + " ship any library it needs inside a module jar of the pack."); + if (jars.stream().anyMatch(UnresolvedReferences::missesApiClasses)) { + text.append(" A missing ").append(ApiAndJdkClassLoader.API_PACKAGE_PREFIX) + .append("* class means the jar was built against a different Iris API."); + } + return new IllegalArgumentException(text.toString()); + } + + /** Decides per referenced class whether the pack loader will find it. Classes outside the pack + * are looked up once per pack. + */ + private static final class ReferenceResolver { + private final Set packClasses = new HashSet<>(); + private final Map outsidePack = new HashMap<>(); + private final ApiAndJdkClassLoader apiAndJdk; + + ReferenceResolver(List jars, ApiAndJdkClassLoader apiAndJdk) { + this.apiAndJdk = apiAndJdk; + jars.forEach(jar -> packClasses.addAll(jar.classNames())); + } + + List unresolvedIn(ModuleJar jar) { + return jar.classes().stream() + .flatMap(type -> type.references().stream().map(target -> new Reference(type.name(), target))) + .filter(reference -> !resolves(reference.target())) + .toList(); + } + + private boolean resolves(String className) { + return packClasses.contains(className) || outsidePack.computeIfAbsent(className, apiAndJdk::hasClass); + } + } + + private record Reference(String source, String target) {} + + private record UnresolvedReferences(ModuleJar jar, List references) { + boolean any() { + return !references.isEmpty(); + } + + boolean missesApiClasses() { + return references.stream().anyMatch(reference -> ApiAndJdkClassLoader.isApiClass(reference.target())); + } + + void describeTo(StringBuilder text) { + text.append("Module jar ").append(jar.origin()) + .append(" uses classes that are not in the Iris API, the JDK or the pack's module jars:\n"); + references.stream().limit(MAX_REPORTED_REFERENCES_PER_JAR).forEach(reference -> text.append(INDENT) + .append(reference.source()).append(" -> ").append(reference.target()).append('\n')); + int hidden = references.size() - MAX_REPORTED_REFERENCES_PER_JAR; + if (hidden > 0) text.append(INDENT).append("and ").append(hidden).append(" more\n"); + } + } +} diff --git a/src/main/java/com/volmit/host/PackModules.java b/src/main/java/com/volmit/host/PackModules.java index 42c0df484..9ffeb253f 100644 --- a/src/main/java/com/volmit/host/PackModules.java +++ b/src/main/java/com/volmit/host/PackModules.java @@ -9,17 +9,17 @@ import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; -import java.util.HashMap; import java.util.List; import java.util.Objects; /** The module jars of one pack: every {@code /modules/*.jar}, one module per jar, ordered * by file name so the result never depends on directory listing order. * - *

All jars of a pack share one class loader whose parent is the loader of the API. A pack jar - * can therefore name another pack jar's stage constants in {@code requires(...)}, as well as - * those of built-in modules visible to the API. Packs do not see each other's classes, and no class - * may appear in two jars of one pack. + *

All jars of a pack share one class loader. A pack jar can therefore name another pack jar's + * stage constants in {@code requires(...)}. Besides the pack's own classes, that loader sees only + * the Iris API and the JDK ({@link ApiAndJdkClassLoader}); packs do not see each other or Iris + * internals. Before the loader exists, the load fails if a jar holds API classes, if a class is in + * two jars, or if a class uses a class the loader would not find. * *

A successful load logs one INFO summary of the pack's modules through {@link System.Logger}, * which the host can route to its own logging. @@ -48,8 +48,9 @@ public final class PackModules implements AutoCloseable { var jars = findModuleJars(packRoot).stream() .map(jar -> ModuleJar.read(packRoot, jar)) .toList(); - requireDistinctClasses(jars); - var packModules = defineModules(packRoot, jars); + var apiAndJdk = new ApiAndJdkClassLoader(IrisModule.class.getClassLoader()); + PackClassCheck.requireLinkable(jars, apiAndJdk); + var packModules = defineModules(packRoot, jars, apiAndJdk); LOGGER.log(Level.INFO, () -> PackModulesSummary.describe(packName(packRoot), packModules.modules())); return packModules; } @@ -85,27 +86,8 @@ public final class PackModules implements AutoCloseable { return Files.isRegularFile(path) && path.getFileName().toString().endsWith(JAR_EXTENSION); } - /** Fails before any class is defined when two jars hold the same class. The shared loader would - * otherwise silently use whichever copy comes first in file name order. - */ - private static void requireDistinctClasses(List jars) { - var owners = new HashMap(); - for (var jar : jars) { - for (var className : jar.classNames()) { - var owner = owners.putIfAbsent(className, jar); - if (owner != null) throw duplicateClass(className, owner, jar); - } - } - } - - private static IllegalArgumentException duplicateClass(String className, ModuleJar first, ModuleJar second) { - return new IllegalArgumentException("Class " + className + " is in both module jars " + first.origin() - + " and " + second.origin() + "; every class of a pack must come from one jar, so relocate" - + " shaded libraries or keep shared classes in one module"); - } - - private static PackModules defineModules(Path packRoot, List jars) { - var loader = newPackClassLoader(packRoot, jars); + private static PackModules defineModules(Path packRoot, List jars, ClassLoader apiAndJdk) { + var loader = newPackClassLoader(packRoot, jars, apiAndJdk); try { return new PackModules(createModules(jars, loader), loader); } catch (RuntimeException | Error failure) { @@ -114,9 +96,9 @@ public final class PackModules implements AutoCloseable { } } - private static URLClassLoader newPackClassLoader(Path packRoot, List jars) { + private static URLClassLoader newPackClassLoader(Path packRoot, List jars, ClassLoader apiAndJdk) { var urls = jars.stream().map(ModuleJar::url).toArray(URL[]::new); - return new URLClassLoader("pack:" + packName(packRoot), urls, IrisModule.class.getClassLoader()); + return new URLClassLoader("pack:" + packName(packRoot), urls, apiAndJdk); } private static String packName(Path packRoot) { diff --git a/src/test/java/com/volmit/ApiValuesTest.java b/src/test/java/com/volmit/ApiValuesTest.java index 40234f7c0..146207462 100644 --- a/src/test/java/com/volmit/ApiValuesTest.java +++ b/src/test/java/com/volmit/ApiValuesTest.java @@ -41,6 +41,16 @@ class ApiValuesTest { assertThrows(NullPointerException.class, () -> ModuleInfo.of("example:moss", null, "1.0.0")); } + @Test + void moduleInfoTextFitsOnOneLogLine() { + for (var broken : List.of("Moss\nINFO forged line", "Moss\r", "Moss\tTabbed", "Moss\u2028Next")) { + var failure = assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("example:moss", broken, "1.0.0")); + assertEquals("Module name of example:moss contains a line break or other control character", failure.getMessage()); + } + assertThrows(IllegalArgumentException.class, () -> ModuleInfo.of("example:moss", "Moss", "1.0\n")); + assertEquals("Mosß é", ModuleInfo.of("example:moss", "Mosß é", "1.0.0").name()); + } + @Test void sparseObjectsCopySortAndRejectDuplicateOrOutOfBoundsBlocks() { var a = new ObjectBlock(new BlockPosition(-1, 0, 0), new BlockState("minecraft:stone")); diff --git a/src/test/java/com/volmit/host/ApiAndJdkClassLoaderTest.java b/src/test/java/com/volmit/host/ApiAndJdkClassLoaderTest.java new file mode 100644 index 000000000..cd16561a1 --- /dev/null +++ b/src/test/java/com/volmit/host/ApiAndJdkClassLoaderTest.java @@ -0,0 +1,48 @@ +package com.volmit.host; + +import com.volmit.IrisModule; +import org.junit.jupiter.api.Test; +import java.util.Collections; +import java.util.List; +import static org.junit.jupiter.api.Assertions.*; + +class ApiAndJdkClassLoaderTest { + private static final ClassLoader HOST = IrisModule.class.getClassLoader(); + private static final String HOST_LIBRARY_SERVICE_FILE = "META-INF/services/org.junit.platform.engine.TestEngine"; + + private final ApiAndJdkClassLoader loader = new ApiAndJdkClassLoader(HOST); + + private static String classFile(Class type) { + return type.getName().replace('.', '/') + ".class"; + } + + @Test + void loadsApiClassesFromTheHostAndJdkClassesFromThePlatform() throws Exception { + assertSame(IrisModule.class, loader.loadClass(IrisModule.class.getName())); + assertSame(List.class, loader.loadClass(List.class.getName())); + assertSame(java.sql.Connection.class, loader.loadClass(java.sql.Connection.class.getName())); + } + + @Test + void hidesHostClassesOutsideTheApi() { + assertDoesNotThrow(() -> HOST.loadClass(Test.class.getName())); + assertThrows(ClassNotFoundException.class, () -> loader.loadClass(Test.class.getName())); + } + + @Test + void resourcesFollowTheSameRuleAsClasses() throws Exception { + assertNotNull(loader.getResource(classFile(IrisModule.class))); + assertNotNull(loader.getResource(classFile(List.class))); + assertNull(loader.getResource(classFile(Test.class))); + assertFalse(Collections.list(HOST.getResources(HOST_LIBRARY_SERVICE_FILE)).isEmpty()); + assertTrue(Collections.list(loader.getResources(HOST_LIBRARY_SERVICE_FILE)).isEmpty()); + } + + @Test + void knowsWhichClassesItHasWithoutLoadingThem() { + assertTrue(loader.hasClass(IrisModule.class.getName())); + assertTrue(loader.hasClass("java.lang.String")); + assertFalse(loader.hasClass(Test.class.getName())); + assertFalse(loader.hasClass("com.volmit.DoesNotExist")); + } +} diff --git a/src/test/java/com/volmit/host/PackModulesTest.java b/src/test/java/com/volmit/host/PackModulesTest.java index 6d15b2f9b..eaf413393 100644 --- a/src/test/java/com/volmit/host/PackModulesTest.java +++ b/src/test/java/com/volmit/host/PackModulesTest.java @@ -1,5 +1,7 @@ package com.volmit.host; +import com.volmit.IrisModule; +import com.volmit.example.placement.AnchorModule; import com.volmit.example.placement.PlacementModules; import com.volmit.support.TestModuleJar; import org.junit.jupiter.api.Test; @@ -21,6 +23,7 @@ class PackModulesTest { private static final String SHARED_CLASS = "pack.shared.Util"; private static final String SHARED_SOURCE = "package pack.shared; public final class Util {}"; private static final byte[] UNUSED_CLASS_BYTES = {(byte) 0xCA, (byte) 0xFE}; + private static final String VERSIONED_SHARED_CLASS = "META-INF/versions/9/pack/shared/Util.class"; private static final String DEFINED_PROPERTY = "irisapi.test.packModuleConstructed"; @TempDir @@ -36,6 +39,11 @@ class PackModulesTest { return LoadedModules.load(modules, Map.of()); } + /** Versioned entries of a multi-release jar are read like any class, so they must be real class files. */ + private byte[] sharedClassFile() { + return TestModuleJar.compileClass(pack, SHARED_CLASS, SHARED_SOURCE); + } + private static String failure(Executable load) { return assertThrows(IllegalArgumentException.class, load).getMessage(); } @@ -54,7 +62,8 @@ class PackModulesTest { @Test void loadsOneModulePerJarInFileNameOrderAndResolvesThemWithBuiltIns(@TempDir Path build) throws Exception { var alpha = module("pack.alpha.AlphaModule", "alpha:core", ALPHA_MEMBERS, - "graph.define(MARK).requires(com.volmit.example.placement.AnchorModule.HEIGHT).run(context -> {});"); + "graph.define(MARK).requires(com.volmit.example.placement.AnchorModule.HEIGHT).run(context -> {});") + .compileAgainstHostOf(AnchorModule.class); var alphaJar = alpha.writeInto(build, "alpha.jar"); module("pack.beta.BetaModule", "beta:core", NO_MEMBERS, "graph.define(Stage.placement(\"beta:core/use\")).requires(pack.alpha.AlphaModule.MARK).run(context -> {});") @@ -77,6 +86,18 @@ class PackModulesTest { } } + @Test + void packClassLoaderSeesOnlyTheApiTheJdkAndThePack() throws Exception { + module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "gamma.jar"); + + try (var packModules = PackModules.load(pack)) { + var loader = packModules.modules().getFirst().module().getClass().getClassLoader(); + assertSame(IrisModule.class, loader.loadClass(IrisModule.class.getName())); + assertSame(List.class, loader.loadClass(List.class.getName())); + assertThrows(ClassNotFoundException.class, () -> loader.loadClass(Test.class.getName())); + } + } + @Test void closingThePackStopsItsClassLoaderFromLoadingMoreClasses() throws Exception { module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES) @@ -172,7 +193,7 @@ class PackModulesTest { .source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "alpha.jar"); module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_STAGES) .multiRelease() - .resource("META-INF/versions/9/pack/shared/Util.class", UNUSED_CLASS_BYTES) + .resource(VERSIONED_SHARED_CLASS, sharedClassFile()) .writeInto(pack, "beta.jar"); assertMentions(failure(() -> PackModules.load(pack)), @@ -183,10 +204,10 @@ class PackModulesTest { void versionedEntriesOutsideAMultiReleaseJarAreNotClasses() { module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) .source(SHARED_CLASS, SHARED_SOURCE) - .resource("META-INF/versions/9/pack/shared/Util.class", UNUSED_CLASS_BYTES) + .resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES) .writeInto(pack, "alpha.jar"); module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_STAGES) - .resource("META-INF/versions/9/pack/shared/Util.class", UNUSED_CLASS_BYTES) + .resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES) .writeInto(pack, "beta.jar"); try (var packModules = PackModules.load(pack)) { @@ -199,7 +220,7 @@ class PackModulesTest { module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) .source(SHARED_CLASS, SHARED_SOURCE) .multiRelease() - .resource("META-INF/versions/9/pack/shared/Util.class", UNUSED_CLASS_BYTES) + .resource(VERSIONED_SHARED_CLASS, sharedClassFile()) .writeInto(pack, "alpha.jar"); try (var packModules = PackModules.load(pack)) { @@ -207,6 +228,106 @@ class PackModulesTest { } } + @Test + void apiClassInAJarFailsNamingTheJarAndTheClass() { + module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) + .source("com.volmit.extra.Helper", "package com.volmit.extra; public final class Helper {}") + .source("com.volmit.extra.Other", "package com.volmit.extra; public final class Other {}") + .writeInto(pack, "alpha.jar"); + + assertEquals("Module jar " + origin("alpha.jar") + " contains Iris API class com.volmit.extra.Helper and 1 more;" + + " Iris provides the API at runtime, so mark the Iris API dependency compileOnly (Maven: provided)" + + " and keep module classes out of com.volmit.*", + failure(() -> PackModules.load(pack))); + } + + @Test + void referenceToAHostLibraryFailsNamingTheJarAndBothClasses() { + module("pack.user.User", "user:core", "static Object probe() { return org.junit.jupiter.api.Test.class; }", NO_STAGES) + .compileAgainstHostOf(Test.class) + .writeInto(pack, "user.jar"); + + assertEquals("Module jar " + origin("user.jar") + " uses classes that are not in the Iris API, the JDK or the" + + " pack's module jars:\n pack.user.User -> org.junit.jupiter.api.Test\n" + + "A module can use only the Iris API, the JDK and the classes in its pack's module jars;" + + " ship any library it needs inside a module jar of the pack.", + failure(() -> PackModules.load(pack))); + } + + @Test + void referenceToAMissingApiClassPointsAtADifferentApiBuild(@TempDir Path build) { + var newerApi = new TestModuleJar() + .source("com.volmit.Newer", "package com.volmit; public final class Newer {}") + .writeInto(build, "newer-api.jar"); + module("pack.user.User", "user:core", "static Object probe() { return com.volmit.Newer.class; }", NO_STAGES) + .compileAgainst(newerApi) + .writeInto(pack, "user.jar"); + + assertMentions(failure(() -> PackModules.load(pack)), + "pack.user.User -> com.volmit.Newer", "the jar was built against a different Iris API"); + } + + @Test + void referencesToTheJdkTheApiAndOtherPackJarsLoad(@TempDir Path build) throws Exception { + var marker = new TestModuleJar() + .source("pack.marker.Marker", """ + package pack.marker; + @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) + public @interface Marker {} + """) + .writeInto(build, "marker.jar"); + var alpha = module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) + .source("pack.alpha.Shared", """ + package pack.alpha; + public record Shared(int[] values, String[][] names) { + public enum Kind { SMALL, LARGE } + } + """); + var alphaJar = alpha.writeInto(build, "alpha.jar"); + alpha.writeInto(pack, "alpha.jar"); + module("pack.beta.Beta", "beta:core", """ + @pack.marker.Marker + static final pack.alpha.Shared[] SHARED = { new pack.alpha.Shared(new int[] {1}, new String[][] {{"a"}}) }; + + static int size(pack.alpha.Shared.Kind kind) { + return switch (kind) { case SMALL -> 1; case LARGE -> 2; }; + } + """, """ + java.util.function.IntSupplier size = () -> size(pack.alpha.Shared.Kind.LARGE) + SHARED[0].values().length; + graph.define(Stage.placement("beta:core/size")).run(context -> java.util.List.of(size).forEach(java.util.function.IntSupplier::getAsInt)); + """) + .compileAgainst(alphaJar) + .compileAgainst(marker) + .writeInto(pack, "beta.jar"); + + try (var packModules = PackModules.load(pack)) { + var loaded = LoadedModules.load(packModules.modules(), Map.of()); + assertTrue(loaded.placement().stages().stream().anyMatch(stage -> stage.stage().id().toString().equals("beta:core/size"))); + var beta = packModules.modules().getLast().module().getClass(); + assertEquals(0, beta.getDeclaredField("SHARED").getAnnotations().length, + "the annotation type is not in the pack, so the JVM skips it"); + } + } + + @Test + void methodMissingAtInstallFailsNamingTheJar(@TempDir Path build) { + var libraryWithMethod = new TestModuleJar() + .source("pack.lib.Lib", "package pack.lib; public final class Lib { public static void added() {} }") + .writeInto(build, "lib.jar"); + module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) + .source("pack.lib.Lib", "package pack.lib; public final class Lib {}") + .writeInto(pack, "alpha.jar"); + module("pack.beta.Beta", "beta:core", NO_MEMBERS, "pack.lib.Lib.added();") + .compileAgainst(libraryWithMethod) + .writeInto(pack, "beta.jar"); + + try (var packModules = PackModules.load(pack)) { + assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of())), + "Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class while installing", + "java.lang.NoSuchMethodError", "pack.lib.Lib.added()"); + } + } + @Test void duplicateModuleIdsAcrossJarsFailNamingBothJars() { module("pack.one.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "one.jar"); diff --git a/src/test/java/com/volmit/support/TestModuleJar.java b/src/test/java/com/volmit/support/TestModuleJar.java index 0a7f6c72b..1c6d0eb45 100644 --- a/src/test/java/com/volmit/support/TestModuleJar.java +++ b/src/test/java/com/volmit/support/TestModuleJar.java @@ -1,7 +1,6 @@ package com.volmit.support; import com.volmit.IrisModule; -import com.volmit.example.placement.AnchorModule; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; @@ -25,7 +24,9 @@ import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; /** Builds a real module jar from Java source at test time. Its classes are not on the test - * classpath, so only a pack class loader can define them. + * classpath, so only a pack class loader can define them. Sources compile against the API's main + * classes only, like a real module; built-in example modules and host libraries must be added with + * {@link #compileAgainstHostOf}, so a jar cannot depend on test support classes by accident. */ public final class TestModuleJar { private static final String SERVICES_FILE = "META-INF/services/" + IrisModule.class.getName(); @@ -34,13 +35,23 @@ public final class TestModuleJar { private final Map resources = new LinkedHashMap<>(); private boolean multiRelease; private final List entryPoints = new ArrayList<>(); - private final List classpath = new ArrayList<>(List.of(classesOf(IrisModule.class), classesOf(AnchorModule.class))); + private final List classpath = new ArrayList<>(List.of(classesOf(IrisModule.class))); /** An entry class with the given module id whose install body may use {@code graph}. */ public static TestModuleJar module(String className, String moduleId, String members, String install) { return new TestModuleJar().source(className, moduleSource(className, moduleId, members, install)).entryPoint(className); } + /** Compiles one class on its own and returns its class file, for raw entries such as versioned classes. */ + public static byte[] compileClass(Path workDirectory, String className, String code) { + try { + var classes = new TestModuleJar().source(className, code).compile(Files.createTempDirectory(workDirectory, "classes")); + return Files.readAllBytes(classes.resolve(className.replace('.', '/') + ".class")); + } catch (IOException exception) { + throw new UncheckedIOException(exception); + } + } + public TestModuleJar source(String className, String code) { sources.put(className, code); return this; @@ -64,11 +75,17 @@ public final class TestModuleJar { return this; } - public TestModuleJar compileAgainst(Path jar) { - classpath.add(jar); + /** Puts a jar or class directory on the compile classpath only; it is not packaged. */ + public TestModuleJar compileAgainst(Path classes) { + classpath.add(classes); return this; } + /** Compiles against wherever {@code type} was loaded from, such as a host library jar. */ + public TestModuleJar compileAgainstHostOf(Class type) { + return compileAgainst(classesOf(type)); + } + /** Writes {@code /modules/} and returns its path. */ public Path writeInto(Path packRoot, String jarName) { try {