Let the host expose extra packages, such as built-in modules, to packs

A single API_PACKAGE_PREFIX made built-in modules in Iris packages
(art.arcane.iris...) invisible, so pack jars could not require their
stages. ExposedPackages now holds the packages packs may use: always
the API (IrisModule's package), plus what the host passes to the new
PackModules.load(packRoot, exposedHostPackages). Names must be package
names (trailing dot accepted) and match whole packages only.

ApiAndJdkClassLoader becomes ExposedHostClassLoader and routes classes
and resources of every exposed package to the host loader. A jar that
ships a class of any exposed package fails; the compileOnly API hint
stays for the API, other packages get their own message. That check
moves from ModuleJar to PackClassCheck. A reference missing from any
exposed package is the "different build" error.

Tests use a built-in module in example.builtin, outside com.volmit.,
which a pack jar can require only when that package is exposed.
This commit is contained in:
piexel committed 2026-10-05 20:30:20 +02:00
1 parent 98bd9a9c12
commit 13a9300ab4
11 files changed
+396 -121

No files matched your search

@@ -1,78 +0,0 @@
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(classFile(binaryName)) != null;
}
/** Whether the API's loader has the class, whether or not this loader shows it to packs. In
* production that loader also holds Iris internals and the libraries Iris bundles.
*/
boolean hostHasClass(String binaryName) {
return apiLoader.getResource(classFile(binaryName)) != 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 String classFile(String binaryName) {
return binaryName.replace('.', '/') + CLASS_FILE_SUFFIX;
}
private static boolean isApiResource(String name) {
return name.startsWith(API_RESOURCE_PREFIX);
}
}
@@ -0,0 +1,76 @@
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 exposed host packages and the JDK and
* nothing else: classes in an {@link ExposedPackages exposed package}, always including the Iris
* API, come from the host's loader, every other class from the platform class loader. Iris
* internals and the libraries Iris bundles stay hidden even though they sit in the host's loader,
* so a module can use only the exposed packages, the JDK and the classes of its own pack's jars.
*
* <p>Resources follow the same rule, by path: {@code com/volmit/...} and the paths of other
* exposed packages from the host'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 ExposedHostClassLoader extends ClassLoader {
private static final String CLASS_FILE_SUFFIX = ".class";
private static final String NAME = "iris-exposed-host-and-jdk";
static {
registerAsParallelCapable();
}
private final ClassLoader hostLoader;
private final ExposedPackages exposed;
/** {@code hostLoader} is the loader that defines the API; in production the Iris plugin's. */
ExposedHostClassLoader(ClassLoader hostLoader, ExposedPackages exposed) {
super(NAME, ClassLoader.getPlatformClassLoader());
this.hostLoader = Objects.requireNonNull(hostLoader, "hostLoader");
this.exposed = Objects.requireNonNull(exposed, "exposed");
}
ExposedPackages exposed() {
return exposed;
}
/** Whether this loader can load the class, judged by its class file so that nothing is loaded. */
boolean hasClass(String binaryName) {
return getResource(classFile(binaryName)) != null;
}
/** Whether the host's loader has the class, whether or not this loader shows it to packs. In
* production that loader also holds Iris internals and the libraries Iris bundles.
*/
boolean hostHasClass(String binaryName) {
return hostLoader.getResource(classFile(binaryName)) != null;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (exposed.exposes(name)) return hostLoader.loadClass(name);
return super.loadClass(name, resolve);
}
@Override
public URL getResource(String name) {
if (exposed.exposesResource(name)) return hostLoader.getResource(name);
return super.getResource(name);
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
if (exposed.exposesResource(name)) return hostLoader.getResources(name);
return super.getResources(name);
}
private static String classFile(String binaryName) {
return binaryName.replace('.', '/') + CLASS_FILE_SUFFIX;
}
}
@@ -0,0 +1,88 @@
package com.volmit.host;
import com.volmit.IrisModule;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.TreeSet;
/** The host packages pack modules may use: always the Iris API, plus whatever the host adds, such
* as the packages of built-in modules whose stages packs may require. A package is exposed with
* all its subpackages, and only whole package names match: {@code com.volmit} does not expose
* {@code com.volmitx}.
*/
final class ExposedPackages {
/** The root package of the Iris API. Module classes must not use it. */
static final String API_PACKAGE = IrisModule.class.getPackageName();
private static final char PACKAGE_SEPARATOR = '.';
private static final char PATH_SEPARATOR = '/';
private static final String PACKAGE_SEPARATOR_PATTERN = "\\.";
private final List<String> packages;
private ExposedPackages(List<String> packages) {
this.packages = List.copyOf(packages);
}
static ExposedPackages apiOnly() {
return apiAnd(List.of());
}
/** The API plus {@code hostPackages}. A trailing dot is accepted; anything that is not a package
* name, such as a blank string or a wildcard, is rejected.
*/
static ExposedPackages apiAnd(Collection<String> hostPackages) {
Objects.requireNonNull(hostPackages, "hostPackages");
var packages = new TreeSet<String>();
packages.add(API_PACKAGE);
hostPackages.forEach(name -> packages.add(requirePackageName(name)));
return new ExposedPackages(List.copyOf(packages));
}
static boolean isApiClass(String binaryName) {
return isInPackage(binaryName, API_PACKAGE);
}
boolean exposes(String binaryName) {
return packages.stream().anyMatch(name -> isInPackage(binaryName, name));
}
/** Whether a resource path, such as {@code com/volmit/IrisModule.class}, lies in an exposed package. */
boolean exposesResource(String path) {
return exposes(path.replace(PATH_SEPARATOR, PACKAGE_SEPARATOR));
}
/** The exposed package a class is in; the most specific one when exposed packages nest. */
String packageOf(String binaryName) {
return packages.stream()
.filter(name -> isInPackage(binaryName, name))
.max(Comparator.comparingInt(String::length))
.orElseThrow(() -> new IllegalArgumentException(binaryName + " is not in an exposed package"));
}
private static boolean isInPackage(String binaryName, String packageName) {
return binaryName.startsWith(packageName)
&& binaryName.length() > packageName.length()
&& binaryName.charAt(packageName.length()) == PACKAGE_SEPARATOR;
}
private static String requirePackageName(String name) {
Objects.requireNonNull(name, "exposed package");
var withoutTrailingDot = name.endsWith(String.valueOf(PACKAGE_SEPARATOR)) ? name.substring(0, name.length() - 1) : name;
if (isPackageName(withoutTrailingDot)) return withoutTrailingDot;
throw new IllegalArgumentException("Exposed package '" + name + "' is not a package name; name a package"
+ " such as art.arcane.iris.engine, which exposes that package and its subpackages");
}
private static boolean isPackageName(String name) {
return Arrays.stream(name.split(PACKAGE_SEPARATOR_PATTERN, -1)).allMatch(ExposedPackages::isIdentifier);
}
private static boolean isIdentifier(String segment) {
return !segment.isEmpty()
&& Character.isJavaIdentifierStart(segment.codePointAt(0))
&& segment.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
}
}
+1 -19
View File
@@ -51,15 +51,13 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
}
/** Reads the single entry class a jar names and the classes it holds. The origin is the jar
* path relative to its pack. Fails if the jar holds a class of the Iris API or a class file that
* cannot be parsed.
* path relative to its pack. Fails if a class file 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));
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);
@@ -140,22 +138,6 @@ record ModuleJar(Path path, String origin, String entryClass, List<JarClass> cla
&& !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) {
@@ -10,13 +10,44 @@ import java.util.List;
final class PackClassCheck {
private PackClassCheck() {}
/** Fails when a class is in two jars, or when a class uses a class that Iris hides from modules
* or that is missing from the API. Returns the classes that nobody has, per jar; they fail only
* when code that needs them runs.
/** Fails when a jar holds a class of an exposed host package, when a class is in two jars, or
* when a class uses a class that Iris hides from modules or that is missing from an exposed
* package. Returns the classes that nobody has, per jar; they fail only when code that needs them
* runs.
*/
static List<MissingClasses> requireLinkable(List<ModuleJar> jars, ApiAndJdkClassLoader apiAndJdk) {
static List<MissingClasses> requireLinkable(List<ModuleJar> jars, ExposedHostClassLoader host) {
jars.forEach(jar -> requireNoHostClasses(jar, host.exposed()));
requireDistinctClasses(jars);
return PackReferenceCheck.requireResolvable(jars, apiAndJdk);
return PackReferenceCheck.requireResolvable(jars, host);
}
/** Exposed packages belong to the host. The pack loader asks the host for their classes first, so
* a packaged copy would be silently replaced by the host's, and a module's own class there could be
* replaced by a later host class of that name.
*/
private static void requireNoHostClasses(ModuleJar jar, ExposedPackages exposed) {
var hostClasses = jar.classNames().stream().filter(exposed::exposes).toList();
if (hostClasses.isEmpty()) return;
var apiClasses = hostClasses.stream().filter(ExposedPackages::isApiClass).toList();
throw apiClasses.isEmpty() ? shippedHostClasses(jar, hostClasses, exposed) : shippedApiClasses(jar, apiClasses);
}
private static IllegalArgumentException shippedApiClasses(ModuleJar jar, List<String> apiClasses) {
return new IllegalArgumentException("Module jar " + jar.origin() + " contains Iris API class "
+ firstAndCount(apiClasses) + "; Iris provides the API at runtime, so mark the Iris API dependency"
+ " compileOnly (Maven: provided) and keep module classes out of " + ExposedPackages.API_PACKAGE + ".*");
}
private static IllegalArgumentException shippedHostClasses(ModuleJar jar, List<String> hostClasses, ExposedPackages exposed) {
var hostPackage = exposed.packageOf(hostClasses.getFirst());
return new IllegalArgumentException("Module jar " + jar.origin() + " contains class " + firstAndCount(hostClasses)
+ " of package " + hostPackage + ", which Iris provides to modules at runtime; compile against it"
+ " compileOnly (Maven: provided) instead of shipping it, and keep module classes out of " + hostPackage + ".*");
}
private static String firstAndCount(List<String> classNames) {
var others = classNames.size() == 1 ? "" : " and " + (classNames.size() - 1) + " more";
return classNames.getFirst() + others;
}
/** The shared pack loader would otherwise silently use whichever copy comes first in file name order. */
+24 -11
View File
@@ -8,6 +8,7 @@ import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
@@ -17,9 +18,11 @@ import java.util.Objects;
*
* <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 that Iris hides from modules or that is missing from the API.
* the exposed host packages and the JDK ({@link ExposedHostClassLoader}); packs do not see each
* other or Iris internals. The Iris API is always exposed; the host may expose more packages, such
* as those of built-in modules whose stages packs may require. Before the loader exists, the load
* fails if a jar holds classes of an exposed package, if a class is in two jars, or if a class uses
* a class that Iris hides from modules or that is missing from an exposed package.
* Classes that nobody has are not an error, because the JVM only needs them when code that uses
* them runs; they are reported as {@link #missingClasses()}.
*
@@ -44,17 +47,27 @@ public final class PackModules implements AutoCloseable {
this.loader = loader;
}
/** Loads the modules of the pack at {@code packRoot}, exposing only the Iris API. */
public static PackModules load(Path packRoot) {
return load(packRoot, List.of());
}
/** Loads the modules of the pack at {@code packRoot}. A pack without a modules directory has
* no modules. Errors name the offending jar relative to the pack root.
*
* @param exposedHostPackages host packages pack modules may use besides the Iris API, which is
* always exposed, such as the packages of built-in modules whose stages packs may require.
* Each exposes the package and its subpackages from the loader that defines the API. A
* trailing dot is accepted; blank names and wildcards are rejected.
*/
public static PackModules load(Path packRoot) {
public static PackModules load(Path packRoot, Collection<String> exposedHostPackages) {
Objects.requireNonNull(packRoot, "packRoot");
var host = new ExposedHostClassLoader(IrisModule.class.getClassLoader(), ExposedPackages.apiAnd(exposedHostPackages));
var jars = findModuleJars(packRoot).stream()
.map(jar -> ModuleJar.read(packRoot, jar))
.toList();
var apiAndJdk = new ApiAndJdkClassLoader(IrisModule.class.getClassLoader());
var missingClasses = PackClassCheck.requireLinkable(jars, apiAndJdk);
var packModules = defineModules(packRoot, jars, missingClasses, apiAndJdk);
var missingClasses = PackClassCheck.requireLinkable(jars, host);
var packModules = defineModules(packRoot, jars, missingClasses, host);
logLoad(packName(packRoot), packModules);
return packModules;
}
@@ -98,8 +111,8 @@ public final class PackModules implements AutoCloseable {
}
private static PackModules defineModules(
Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ClassLoader apiAndJdk) {
var loader = newPackClassLoader(packRoot, jars, apiAndJdk);
Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ClassLoader host) {
var loader = newPackClassLoader(packRoot, jars, host);
try {
return new PackModules(createModules(jars, loader), missingClasses, loader);
} catch (RuntimeException | Error failure) {
@@ -108,9 +121,9 @@ public final class PackModules implements AutoCloseable {
}
}
private static URLClassLoader newPackClassLoader(Path packRoot, List<ModuleJar> jars, ClassLoader apiAndJdk) {
private static URLClassLoader newPackClassLoader(Path packRoot, List<ModuleJar> jars, ClassLoader host) {
var urls = jars.stream().map(ModuleJar::url).toArray(URL[]::new);
return new URLClassLoader("pack:" + packName(packRoot), urls, apiAndJdk);
return new URLClassLoader("pack:" + packName(packRoot), urls, host);
}
private static void logLoad(String packName, PackModules packModules) {
@@ -22,7 +22,7 @@ final class PackReferenceCheck {
/** Where the pack loader would find a referenced class. */
private enum Resolution {
/** In the pack, a package the host exposes, or the JDK. */
/** In the pack, an exposed host package, or the JDK. */
PROVIDED,
/** Nowhere: an optional dependency, which only fails when code that needs it runs. */
ABSENT,
@@ -53,9 +53,9 @@ final class PackReferenceCheck {
private final Set<String> packClasses = new HashSet<>();
private final Map<String, Resolution> outsidePack = new HashMap<>();
private final ApiAndJdkClassLoader host;
private final ExposedHostClassLoader host;
private PackReferenceCheck(List<ModuleJar> jars, ApiAndJdkClassLoader host) {
private PackReferenceCheck(List<ModuleJar> jars, ExposedHostClassLoader host) {
this.host = host;
jars.forEach(jar -> packClasses.addAll(jar.classNames()));
}
@@ -63,7 +63,7 @@ final class PackReferenceCheck {
/** Fails when a jar uses a class Iris hides or a class missing from a package Iris exposes.
* Returns the classes nobody has, per jar, for jars that use any.
*/
static List<MissingClasses> requireResolvable(List<ModuleJar> jars, ApiAndJdkClassLoader host) {
static List<MissingClasses> requireResolvable(List<ModuleJar> jars, ExposedHostClassLoader host) {
var check = new PackReferenceCheck(jars, host);
var references = jars.stream().map(check::resolve).toList();
requireNoFailures(references);
@@ -88,7 +88,7 @@ final class PackReferenceCheck {
private Resolution resolveOutsidePack(String className) {
if (host.hasClass(className)) return Resolution.PROVIDED;
if (ApiAndJdkClassLoader.isApiClass(className)) return Resolution.MISSING_HOST_CLASS;
if (host.exposed().exposes(className)) return Resolution.MISSING_HOST_CLASS;
if (host.hostHasClass(className)) return Resolution.HIDDEN_HOST_CLASS;
return Resolution.ABSENT;
}