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.
This commit is contained in:
piexel committed 2026-10-05 18:24:53 +02:00
1 parent 862f4d19be
commit 1553959cf4
11 files changed
+563 -60

No files matched your search

+21 -7
View File
@@ -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;
}
}
@@ -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.
*
* <p>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.
*
* <p>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<URL> 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);
}
}
@@ -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.
*
* <p>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<String> read(byte[] classFile) {
var model = ClassFile.of().parse(classFile);
var references = new TreeSet<String>();
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<String> 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<String> 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<String> references) {
addType(type.returnType(), references);
type.parameterList().forEach(parameter -> addType(parameter, references));
}
private static void addType(ClassDesc type, Set<String> 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('/', '.');
}
}
@@ -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);
}
}
}
+61 -11
View File
@@ -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.
*
* <p>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<String> classNames) {
record ModuleJar(Path path, String origin, String entryClass, List<JarClass> 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<String> 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<String> 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<String> 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<String> 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<String> readClassNames(JarFile file) {
private static List<JarEntry> 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<String> 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<JarEntry> 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<JarClass> readClasses(String origin, JarFile file, List<JarEntry> classEntries) throws IOException {
var classes = new ArrayList<JarClass>(classEntries.size());
for (var entry : classEntries) {
classes.add(new JarClass(toBinaryName(entry.getName()), readReferences(origin, file, entry)));
}
return classes;
}
private static SortedSet<String> 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('/', '.');
}
@@ -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<ModuleJar> 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<ModuleJar> jars) {
var owners = new HashMap<String, ModuleJar>();
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<ModuleJar> 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<UnresolvedReferences> 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<String> packClasses = new HashSet<>();
private final Map<String, Boolean> outsidePack = new HashMap<>();
private final ApiAndJdkClassLoader apiAndJdk;
ReferenceResolver(List<ModuleJar> jars, ApiAndJdkClassLoader apiAndJdk) {
this.apiAndJdk = apiAndJdk;
jars.forEach(jar -> packClasses.addAll(jar.classNames()));
}
List<Reference> 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<Reference> 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");
}
}
}
+12 -30
View File
@@ -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 <pack>/modules/*.jar}, one module per jar, ordered
* by file name so the result never depends on directory listing order.
*
* <p>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.
* <p>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.
*
* <p>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<ModuleJar> jars) {
var owners = new HashMap<String, ModuleJar>();
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<ModuleJar> jars) {
var loader = newPackClassLoader(packRoot, jars);
private static PackModules defineModules(Path packRoot, List<ModuleJar> 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<ModuleJar> jars) {
private static URLClassLoader newPackClassLoader(Path packRoot, List<ModuleJar> 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) {