Check tooling parts apart from generation code and load them in their own loader

Classes in a part's packages are not checked as generation code. Generation
code that uses a part class fails the pack load. Parts of the platform the host
runs on (ModuleHost.runningOn) are checked against what a part may see; parts of
other platforms are skipped unread. ToolingPartLoader is a child of the pack's
loader that defines the part itself and hands platform packages to the platform's
loader. ToolingPlatform describes a platform; BUKKIT is Paper's.
This commit is contained in:
piexel committed 2026-11-06 08:11:35 +01:00
1 parent 2e4fd306e8
commit 66c4f01b21
15 files changed
+947 -45

No files matched your search

@@ -37,7 +37,7 @@ public final class LoadedPack implements AutoCloseable {
public static LoadedPack load(Path packRoot, ModuleHost host) { public static LoadedPack load(Path packRoot, ModuleHost host) {
Objects.requireNonNull(host, "host"); Objects.requireNonNull(host, "host");
var packModules = PackModules.load(packRoot, host.exposedHostPackages(), host.bundledJars(), host.jarCopyRoot(), var packModules = PackModules.load(packRoot, host.exposedHostPackages(), host.bundledJars(), host.jarCopyRoot(),
host.logger()); host.logger(), host.platformApi());
try { try {
var loaded = LoadedModules.load(host.withPackModules(packModules.modules()), var loaded = LoadedModules.load(host.withPackModules(packModules.modules()),
host.reservedHostFields(), host.hostTypePackages(), host.reservedFolders()); host.reservedHostFields(), host.hostTypePackages(), host.reservedFolders());
@@ -60,6 +60,16 @@ public final class LoadedPack implements AutoCloseable {
return packModules.missingClasses(); return packModules.missingClasses();
} }
/** The pack's tooling parts of the platform the host runs on; see {@link PackModules#toolingParts()}. */
public List<ToolingPart> toolingParts() {
return packModules.toolingParts();
}
/** A loader for one of {@link #toolingParts()}; the caller closes it before this pack; see {@link PackModules#openToolingPart}. */
public ToolingPartLoader openToolingPart(ToolingPart part) {
return packModules.openToolingPart(part);
}
public FeatureCatalog catalog() { public FeatureCatalog catalog() {
return loaded.catalog(); return loaded.catalog();
} }
@@ -10,6 +10,7 @@ import java.util.EnumMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
@@ -39,7 +40,8 @@ public record ModuleHost(
Set<String> reservedFolders, Set<String> reservedFolders,
List<Path> bundledJars, List<Path> bundledJars,
Path jarCopyRoot, Path jarCopyRoot,
System.Logger logger) { System.Logger logger,
Optional<PlatformApi> platformApi) {
private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir"; private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir";
public ModuleHost { public ModuleHost {
@@ -51,6 +53,7 @@ public record ModuleHost(
bundledJars = List.copyOf(bundledJars); bundledJars = List.copyOf(bundledJars);
Objects.requireNonNull(jarCopyRoot, "jarCopyRoot"); Objects.requireNonNull(jarCopyRoot, "jarCopyRoot");
Objects.requireNonNull(logger, "logger"); Objects.requireNonNull(logger, "logger");
Objects.requireNonNull(platformApi, "platformApi");
ExposedPackages.apiAnd(exposedHostPackages); ExposedPackages.apiAnd(exposedHostPackages);
HostTypes.of(hostTypePackages); HostTypes.of(hostTypePackages);
requireFieldNames(reservedHostFields); requireFieldNames(reservedHostFields);
@@ -58,12 +61,13 @@ public record ModuleHost(
} }
/** The given built-in modules, exposing only the Iris API and reserving nothing. Jar copies go to /** The given built-in modules, exposing only the Iris API and reserving nothing. Jar copies go to
* {@code java.io.tmpdir} and the load log to the {@link System.Logger} named after {@link PackModules}. * {@code java.io.tmpdir} and the load log to the {@link System.Logger} named after {@link PackModules}. It runs on no
* platform, so packs' tooling parts are not checked or opened.
*/ */
public static ModuleHost of(List<? extends IrisModule> builtInModules) { public static ModuleHost of(List<? extends IrisModule> builtInModules) {
var builtIns = builtInModules.stream().map(DiscoveredModule::builtIn).toList(); var builtIns = builtInModules.stream().map(DiscoveredModule::builtIn).toList();
return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), List.of(), systemTemporaryDirectory(), return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), List.of(), systemTemporaryDirectory(),
PackModules.DEFAULT_LOGGER); PackModules.DEFAULT_LOGGER, Optional.empty());
} }
/** This configuration with {@code packages}, each with its subpackages, also exposed to pack /** This configuration with {@code packages}, each with its subpackages, also exposed to pack
@@ -71,7 +75,7 @@ public record ModuleHost(
*/ */
public ModuleHost exposing(String... packages) { public ModuleHost exposing(String... packages) {
return new ModuleHost(builtIns, union(exposedHostPackages, packages), reservedHostFields, return new ModuleHost(builtIns, union(exposedHostPackages, packages), reservedHostFields,
hostTypePackages, reservedFolders, bundledJars, jarCopyRoot, logger); hostTypePackages, reservedFolders, bundledJars, jarCopyRoot, logger, platformApi);
} }
/** This configuration with {@code fields} also reserved as JSON fields the host itself uses, /** This configuration with {@code fields} also reserved as JSON fields the host itself uses,
@@ -79,7 +83,7 @@ public record ModuleHost(
*/ */
public ModuleHost reservingFields(Map<Level, Set<String>> fields) { public ModuleHost reservingFields(Map<Level, Set<String>> fields) {
return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields), return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields),
hostTypePackages, reservedFolders, bundledJars, jarCopyRoot, logger); hostTypePackages, reservedFolders, bundledJars, jarCopyRoot, logger, platformApi);
} }
/** This configuration with the classes in {@code packages}, each with its subpackages, described by /** This configuration with the classes in {@code packages}, each with its subpackages, described by
@@ -93,7 +97,7 @@ public record ModuleHost(
@Deprecated(forRemoval = true) @Deprecated(forRemoval = true)
public ModuleHost describingHostTypesIn(String... packages) { public ModuleHost describingHostTypesIn(String... packages) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields,
union(hostTypePackages, packages), reservedFolders, bundledJars, jarCopyRoot, logger); union(hostTypePackages, packages), reservedFolders, bundledJars, jarCopyRoot, logger, platformApi);
} }
/** This configuration with {@code folders}, folder names directly below a pack's root, also read by the host /** This configuration with {@code folders}, folder names directly below a pack's root, also read by the host
@@ -101,7 +105,7 @@ public record ModuleHost(
*/ */
public ModuleHost reservingFolders(String... folders) { public ModuleHost reservingFolders(String... folders) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages, return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
union(reservedFolders, folders), bundledJars, jarCopyRoot, logger); union(reservedFolders, folders), bundledJars, jarCopyRoot, logger, platformApi);
} }
/** This configuration also loading {@code jars}, module jars the host ships, with every pack, as if they were in its /** This configuration also loading {@code jars}, module jars the host ships, with every pack, as if they were in its
@@ -112,7 +116,7 @@ public record ModuleHost(
var bundled = new ArrayList<>(bundledJars); var bundled = new ArrayList<>(bundledJars);
bundled.addAll(Arrays.asList(jars)); bundled.addAll(Arrays.asList(jars));
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages, reservedFolders, return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages, reservedFolders,
bundled, jarCopyRoot, logger); bundled, jarCopyRoot, logger, platformApi);
} }
/** This configuration copying module jars into new directories below {@code directory}, such as a /** This configuration copying module jars into new directories below {@code directory}, such as a
@@ -120,7 +124,7 @@ public record ModuleHost(
*/ */
public ModuleHost copyingJarsTo(Path directory) { public ModuleHost copyingJarsTo(Path directory) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages, return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, bundledJars, directory, logger); reservedFolders, bundledJars, directory, logger, platformApi);
} }
/** This configuration logging each pack load's module summary and missing-classes warning, and every module's own /** This configuration logging each pack load's module summary and missing-classes warning, and every module's own
@@ -131,7 +135,16 @@ public record ModuleHost(
Objects.requireNonNull(logger, "logger"); Objects.requireNonNull(logger, "logger");
var loggedBuiltIns = builtIns.stream().map(builtIn -> builtIn.loggingTo(logger)).toList(); var loggedBuiltIns = builtIns.stream().map(builtIn -> builtIn.loggingTo(logger)).toList();
return new ModuleHost(loggedBuiltIns, exposedHostPackages, reservedHostFields, hostTypePackages, return new ModuleHost(loggedBuiltIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, bundledJars, jarCopyRoot, logger); reservedFolders, bundledJars, jarCopyRoot, logger, platformApi);
}
/** This configuration running on {@code platform}, whose api classes {@code platform.classes()} defines, such as the Iris
* plugin's loader: a pack's tooling parts of that platform are checked when the pack loads and can be opened with
* {@link LoadedPack#openToolingPart}. The last call wins.
*/
public ModuleHost runningOn(PlatformApi platform) {
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, bundledJars, jarCopyRoot, logger, Optional.of(platform));
} }
/** The built-in modules followed by a pack's modules, in the order {@link LoadedModules} sets them up. */ /** The built-in modules followed by a pack's modules, in the order {@link LoadedModules} sets them up. */
@@ -9,6 +9,7 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** The checks a pack load makes on a module jar's classes, for a build to run on a jar it has just /** The checks a pack load makes on a module jar's classes, for a build to run on a jar it has just
* written: the jar names at least one module, every module class is in the jar, and no class uses * written: the jar names at least one module, every module class is in the jar, and no class uses
@@ -45,7 +46,7 @@ public final class ModuleJarCheck {
HostClassesLeftOut.parse(leftOutClasses)); HostClassesLeftOut.parse(leftOutClasses));
var read = ModuleJar.read(new JarSnapshot.CopiedJar(jar.toString(), jar)); var read = ModuleJar.read(new JarSnapshot.CopiedJar(jar.toString(), jar));
requireEntryClassesInJar(read); requireEntryClassesInJar(read);
PackClassCheck.requireLinkable(List.of(read), host); PackClassCheck.requireLinkable(List.of(read), host, Optional.empty());
return read.entryClasses(); return read.entryClasses();
} }
@@ -2,6 +2,7 @@ package com.volmit.host;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Optional;
/** Checks the classes of all jars of one pack before its class loader exists, so a pack that /** 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} * cannot link fails at load with the jar to fix, not later with a {@link NoClassDefFoundError}
@@ -12,13 +13,14 @@ final class PackClassCheck {
/** Fails when a jar holds a class of an exposed host package, when a class is in two jars, or /** 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 * 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 * package. Generation code may not use tooling parts, and the parts of {@code runningPlatform}, if the host runs on one,
* runs. * are checked against what a part may see; the parts of other platforms are skipped. Returns the classes that nobody
* has, per jar; they fail only when code that needs them runs.
*/ */
static List<MissingClasses> requireLinkable(List<ModuleJar> jars, ExposedHostClassLoader host) { static List<MissingClasses> requireLinkable(List<ModuleJar> jars, ExposedHostClassLoader host, Optional<PlatformApi> runningPlatform) {
jars.forEach(jar -> requireNoHostClasses(jar, host.exposed())); jars.forEach(jar -> requireNoHostClasses(jar, host.exposed()));
requireDistinctClasses(jars); requireDistinctClasses(jars);
return PackReferenceCheck.requireResolvable(jars, host); return PackReferenceCheck.requireResolvable(jars, host, runningPlatform);
} }
/** Exposed packages belong to the host. The pack loader asks the host for their classes first, so /** Exposed packages belong to the host. The pack loader asks the host for their classes first, so
@@ -12,6 +12,7 @@ import java.util.Collection;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -32,7 +33,9 @@ import java.util.stream.Stream;
* other or Iris internals. The Iris API is always exposed; the host may expose more packages, such * 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 * 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 * 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. * a class that Iris hides from modules or that is missing from an exposed package, or if generation code uses a class of a
* tooling part ({@link ToolingPart}). On a host that runs on a platform ({@link PlatformApi}) the parts of that platform are
* checked too, against what a part may see; the parts of other platforms are not read.
* Classes that nobody has are not an error, because the JVM only needs them when code that uses * 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()}, except those in the optional packages * them runs; they are reported as {@link #missingClasses()}, except those in the optional packages
* the jar's manifest declares ({@value ModuleJar#OPTIONAL_PACKAGES_ATTRIBUTE}). * the jar's manifest declares ({@value ModuleJar#OPTIONAL_PACKAGES_ATTRIBUTE}).
@@ -55,13 +58,20 @@ public final class PackModules implements AutoCloseable {
private final List<MissingClasses> missingClasses; private final List<MissingClasses> missingClasses;
private final URLClassLoader loader; private final URLClassLoader loader;
private final JarSnapshot snapshot; private final JarSnapshot snapshot;
private final ExposedPackages exposed;
private final Optional<PlatformApi> runningPlatform;
private final List<ToolingPart> toolingParts;
private PackModules( private PackModules(
List<DiscoveredModule> modules, List<MissingClasses> missingClasses, URLClassLoader loader, JarSnapshot snapshot) { List<DiscoveredModule> modules, List<MissingClasses> missingClasses, URLClassLoader loader, JarSnapshot snapshot,
ExposedPackages exposed, Optional<PlatformApi> runningPlatform, List<ToolingPart> toolingParts) {
this.modules = List.copyOf(modules); this.modules = List.copyOf(modules);
this.missingClasses = List.copyOf(missingClasses); this.missingClasses = List.copyOf(missingClasses);
this.loader = loader; this.loader = loader;
this.snapshot = snapshot; this.snapshot = snapshot;
this.exposed = exposed;
this.runningPlatform = runningPlatform;
this.toolingParts = List.copyOf(toolingParts);
} }
/** Loads the modules of the pack at {@code packRoot}, exposing only the Iris API. */ /** Loads the modules of the pack at {@code packRoot}, exposing only the Iris API. */
@@ -96,13 +106,22 @@ public final class PackModules implements AutoCloseable {
*/ */
static PackModules load(Path packRoot, Collection<String> exposedHostPackages, List<Path> bundledJars, Path temporaryRoot, static PackModules load(Path packRoot, Collection<String> exposedHostPackages, List<Path> bundledJars, Path temporaryRoot,
System.Logger logger) { System.Logger logger) {
return load(packRoot, exposedHostPackages, bundledJars, temporaryRoot, logger, Optional.empty());
}
/** Like {@link #load(Path, Collection, List, Path, System.Logger)} on a host that runs on {@code runningPlatform}, if
* any: the pack's tooling parts of that platform are checked at load and can be opened ({@link #openToolingPart}).
*/
static PackModules load(Path packRoot, Collection<String> exposedHostPackages, List<Path> bundledJars, Path temporaryRoot,
System.Logger logger, Optional<PlatformApi> runningPlatform) {
Objects.requireNonNull(packRoot, "packRoot"); Objects.requireNonNull(packRoot, "packRoot");
Objects.requireNonNull(logger, "logger"); Objects.requireNonNull(logger, "logger");
Objects.requireNonNull(runningPlatform, "runningPlatform");
var host = new ExposedHostClassLoader(IrisModule.class.getClassLoader(), ExposedPackages.apiAnd(exposedHostPackages)); var host = new ExposedHostClassLoader(IrisModule.class.getClassLoader(), ExposedPackages.apiAnd(exposedHostPackages));
StaleJarSnapshots.remove(temporaryRoot); StaleJarSnapshots.remove(temporaryRoot);
var snapshot = JarSnapshot.take(sourceJars(packRoot, bundledJars, findModuleJars(packRoot)), temporaryRoot); var snapshot = JarSnapshot.take(sourceJars(packRoot, bundledJars, findModuleJars(packRoot)), temporaryRoot);
try { try {
var packModules = loadSnapshot(packRoot, snapshot, host, logger); var packModules = loadSnapshot(packRoot, snapshot, host, logger, runningPlatform);
logLoad(logger, packName(packRoot), packModules); logLoad(logger, packName(packRoot), packModules);
return packModules; return packModules;
} catch (RuntimeException failure) { } catch (RuntimeException failure) {
@@ -127,6 +146,24 @@ public final class PackModules implements AutoCloseable {
return missingClasses; return missingClasses;
} }
/** The tooling parts the pack's jars declare for the platform the host runs on, in jar file name order and, within a jar,
* in the order it lists them. Empty when the host runs on no platform; the parts of other platforms are never loaded.
*/
public List<ToolingPart> toolingParts() {
return toolingParts;
}
/** A loader for {@code part}, which this pack's {@link #toolingParts()} lists: a child of the pack's loader that
* sees the running platform's api through the {@link PlatformApi} the host runs on. The caller closes it, before the
* pack closes.
*/
public ToolingPartLoader openToolingPart(ToolingPart part) {
if (!toolingParts.contains(part)) {
throw new IllegalArgumentException("Tooling part " + part.declaration() + " of " + part.jarOrigin() + " is not one of this pack's parts");
}
return ToolingPartLoader.open(part, loader, exposed, runningPlatform.orElseThrow());
}
/** Closes the class loader, then deletes the jar copies, which an open loader would keep locked on Windows. */ /** Closes the class loader, then deletes the jar copies, which an open loader would keep locked on Windows. */
@Override @Override
public void close() { public void close() {
@@ -144,10 +181,11 @@ public final class PackModules implements AutoCloseable {
return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY)); return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY));
} }
private static PackModules loadSnapshot(Path packRoot, JarSnapshot snapshot, ExposedHostClassLoader host, System.Logger logger) { private static PackModules loadSnapshot(
Path packRoot, JarSnapshot snapshot, ExposedHostClassLoader host, System.Logger logger, Optional<PlatformApi> runningPlatform) {
var jars = snapshot.jars().stream().map(ModuleJar::read).toList(); var jars = snapshot.jars().stream().map(ModuleJar::read).toList();
var missingClasses = PackClassCheck.requireLinkable(jars, host); var missingClasses = PackClassCheck.requireLinkable(jars, host, runningPlatform);
return defineModules(packRoot, jars, missingClasses, host, snapshot, logger); return defineModules(packRoot, jars, missingClasses, host, snapshot, logger, runningPlatform);
} }
private static List<Path> findModuleJars(Path packRoot) { private static List<Path> findModuleJars(Path packRoot) {
@@ -183,18 +221,27 @@ public final class PackModules implements AutoCloseable {
} }
private static PackModules defineModules( private static PackModules defineModules(
Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ClassLoader host, JarSnapshot snapshot, Path packRoot, List<ModuleJar> jars, List<MissingClasses> missingClasses, ExposedHostClassLoader host, JarSnapshot snapshot,
System.Logger logger) { System.Logger logger, Optional<PlatformApi> runningPlatform) {
var loader = newPackClassLoader(packRoot, jars, host); var loader = newPackClassLoader(packRoot, jars, host);
try { try {
var modules = createModules(jars, loader, snapshot, logger); var modules = createModules(jars, loader, snapshot, logger);
return new PackModules(modules, withoutDeclaredOptional(missingClasses, jars), loader, snapshot); return new PackModules(modules, withoutDeclaredOptional(missingClasses, jars), loader, snapshot, host.exposed(),
runningPlatform, partsOf(jars, runningPlatform));
} catch (RuntimeException | Error failure) { } catch (RuntimeException | Error failure) {
closeAfterFailure(loader, failure); closeAfterFailure(loader, failure);
throw failure; throw failure;
} }
} }
private static List<ToolingPart> partsOf(List<ModuleJar> jars, Optional<PlatformApi> runningPlatform) {
var platformName = runningPlatform.map(running -> running.platform().name());
return jars.stream()
.flatMap(jar -> jar.toolingParts().stream())
.filter(part -> platformName.filter(part.platform()::equals).isPresent())
.toList();
}
private static URLClassLoader newPackClassLoader(Path packRoot, List<ModuleJar> jars, ClassLoader host) { private static URLClassLoader newPackClassLoader(Path packRoot, List<ModuleJar> jars, ClassLoader host) {
var urls = jars.stream().map(ModuleJar::url).toArray(URL[]::new); var urls = jars.stream().map(ModuleJar::url).toArray(URL[]::new);
return new URLClassLoader("pack:" + packName(packRoot), urls, host); return new URLClassLoader("pack:" + packName(packRoot), urls, host);
@@ -5,9 +5,11 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors;
/** Decides for every class a pack's jars use whether the pack loader will find it, and why not /** Decides for every class a pack's jars use whether the pack loader will find it, and why not
* when it won't. Nothing is loaded: the host's classes are judged by their class files. * when it won't. Nothing is loaded: the host's classes are judged by their class files.
@@ -16,10 +18,16 @@ import java.util.function.Predicate;
* error: bundled libraries reference optional dependencies they only use when present. A class * error: bundled libraries reference optional dependencies they only use when present. A class
* that Iris has but hides, a class of a JDK module packs cannot see or of a JDK package packs may * that Iris has but hides, a class of a JDK module packs cannot see or of a JDK package packs may
* not use, or a class missing from a package Iris exposes always fails the load. * not use, or a class missing from a package Iris exposes always fails the load.
*
* <p>Tooling parts ({@link ToolingPart}) split the classes in two. Generation code is judged as above, plus it may not use
* a part class. A part of the platform this host runs on is judged against what a part may see; the parts of other
* platforms are not read.
*/ */
final class PackReferenceCheck { final class PackReferenceCheck {
private static final int MAX_REPORTED_REFERENCES_PER_JAR = 10; private static final int MAX_REPORTED_REFERENCES_PER_JAR = 10;
private static final String INDENT = " "; private static final String INDENT = " ";
private static final String PLATFORM_PLACEHOLDER = "{platform}";
private static final String NO_PLATFORM = "";
/** Where the pack loader would find a referenced class. */ /** Where the pack loader would find a referenced class. */
private enum Resolution { private enum Resolution {
@@ -49,7 +57,20 @@ final class PackReferenceCheck {
LEFT_OUT_HOST_CLASS( LEFT_OUT_HOST_CLASS(
"uses classes of the libraries Iris provides to modules that Iris's jar leaves out:", "uses classes of the libraries Iris provides to modules that Iris's jar leaves out:",
"Iris strips classes it does not use itself from the libraries it ships. Use another class, or have" "Iris strips classes it does not use itself from the libraries it ships. Use another class, or have"
+ " Iris keep the class you need."); + " Iris keep the class you need."),
GENERATION_USES_PART(
"has generation classes that use classes of the " + PLATFORM_PLACEHOLDER + " part:",
"Generation code cannot use the " + PLATFORM_PLACEHOLDER + " part; move the call into the part."),
PART_USES_OTHER_PART(
"has " + PLATFORM_PLACEHOLDER + " part classes that use classes of another part:",
"A part can use only its own packages; move what parts share into generation code or into one part."),
PART_USES_DENIED_CLASS(
"has " + PLATFORM_PLACEHOLDER + " part classes that use classes parts cannot see:",
"A " + PLATFORM_PLACEHOLDER + " part can use its own packages, the " + PLATFORM_PLACEHOLDER + " API and what"
+ " modules can use; it cannot use Iris internals, the server's own classes or the host side of IrisApi."),
MISSING_PLATFORM_CLASS(
"has " + PLATFORM_PLACEHOLDER + " part classes that use " + PLATFORM_PLACEHOLDER + " API classes this server does not have:",
"The jar was built against a different " + PLATFORM_PLACEHOLDER + " API version.");
private final String header; private final String header;
private final String advice; private final String advice;
@@ -66,23 +87,39 @@ final class PackReferenceCheck {
boolean failsLoad() { boolean failsLoad() {
return header != null; return header != null;
} }
/** Whether the failure is about one platform's part, so each platform gets its own group in the message. */
boolean namesPlatform() {
return failsLoad() && header.contains(PLATFORM_PLACEHOLDER);
}
String header(String platform) {
return header.replace(PLATFORM_PLACEHOLDER, platform);
}
String advice(String platform) {
return advice.replace(PLATFORM_PLACEHOLDER, platform);
}
} }
private final Set<String> packClasses = new HashSet<>(); private final Set<String> packClasses = new HashSet<>();
private final Map<String, Resolution> outsidePack = new HashMap<>(); private final Map<String, Resolution> outsidePack = new HashMap<>();
private final ExposedHostClassLoader host; private final ExposedHostClassLoader host;
private final ToolingPartition partition;
private PackReferenceCheck(List<ModuleJar> jars, ExposedHostClassLoader host) { private PackReferenceCheck(List<ModuleJar> jars, ExposedHostClassLoader host, ToolingPartition partition) {
this.host = host; this.host = host;
this.partition = partition;
jars.forEach(jar -> packClasses.addAll(jar.classNames())); jars.forEach(jar -> packClasses.addAll(jar.classNames()));
} }
/** Fails when a jar uses a class Iris hides, a class of a JDK module packs cannot see or of a JDK /** Fails when a jar uses a class Iris hides, a class of a JDK module packs cannot see or of a JDK
* package packs may not use, or a class missing from a package Iris exposes. * package packs may not use, or a class missing from a package Iris exposes, or when generation code uses a tooling
* part or a part of {@code runningPlatform} uses what parts cannot see.
* Returns the classes nobody has, per jar, for jars that use any. * Returns the classes nobody has, per jar, for jars that use any.
*/ */
static List<MissingClasses> requireResolvable(List<ModuleJar> jars, ExposedHostClassLoader host) { static List<MissingClasses> requireResolvable(List<ModuleJar> jars, ExposedHostClassLoader host, Optional<PlatformApi> runningPlatform) {
var check = new PackReferenceCheck(jars, host); var check = new PackReferenceCheck(jars, host, new ToolingPartition(jars, runningPlatform));
var references = jars.stream().map(check::resolve).toList(); var references = jars.stream().map(check::resolve).toList();
requireNoFailures(references); requireNoFailures(references);
return references.stream() return references.stream()
@@ -93,12 +130,42 @@ final class PackReferenceCheck {
private JarReferences resolve(ModuleJar jar) { private JarReferences resolve(ModuleJar jar) {
var references = jar.classes().stream() var references = jar.classes().stream()
.flatMap(type -> type.references().stream().map(target -> new Reference(type.name(), target, resolve(target)))) .filter(type -> partition.isChecked(type.name()))
.flatMap(type -> type.references().stream().map(target -> referenceFrom(type.name(), target)))
.filter(reference -> reference.resolution() != Resolution.PROVIDED) .filter(reference -> reference.resolution() != Resolution.PROVIDED)
.toList(); .toList();
return new JarReferences(jar, references); return new JarReferences(jar, references);
} }
private Reference referenceFrom(String source, String target) {
var resolution = partition.partOf(source)
.map(sourcePart -> resolveFromPart(sourcePart, target))
.orElseGet(() -> resolveFromGeneration(target));
var platform = resolution.namesPlatform() ? partition.platformInvolvedIn(source, target) : NO_PLATFORM;
return new Reference(source, target, resolution, platform);
}
private Resolution resolveFromGeneration(String className) {
if (partition.partOf(className).isPresent()) return Resolution.GENERATION_USES_PART;
return resolve(className);
}
/** What a part may use: itself, generation classes, the platform's api, and what modules may use, but never a denied class. */
private Resolution resolveFromPart(ToolingPart sourcePart, String className) {
var targetPart = partition.partOf(className);
if (targetPart.isPresent()) return sourcePart.inSamePartAs(targetPart.get()) ? Resolution.PROVIDED : Resolution.PART_USES_OTHER_PART;
if (packClasses.contains(className)) return Resolution.PROVIDED;
var platform = partition.runningPlatform();
if (isDeniedToParts(platform.platform(), className)) return Resolution.PART_USES_DENIED_CLASS;
if (platform.platform().hasApiPackageOf(className)) return platform.hasClass(className) ? Resolution.PROVIDED : Resolution.MISSING_PLATFORM_CLASS;
return resolve(className);
}
/** A class modules may use is not denied: {@code art.arcane.iris.builtin} lies in the denied {@code art.arcane.iris}. */
private boolean isDeniedToParts(ToolingPlatform platform, String className) {
return platform.deniesPackageOf(className) && !host.exposed().exposes(className);
}
private Resolution resolve(String className) { private Resolution resolve(String className) {
if (packClasses.contains(className)) return Resolution.PROVIDED; if (packClasses.contains(className)) return Resolution.PROVIDED;
return outsidePack.computeIfAbsent(className, this::resolveOutsidePack); return outsidePack.computeIfAbsent(className, this::resolveOutsidePack);
@@ -125,14 +192,24 @@ final class PackReferenceCheck {
throw ModuleLoadException.ofPack(String.join("\n", failures)); throw ModuleLoadException.ofPack(String.join("\n", failures));
} }
/** One group per platform for the failures that name one; the others have a single group without a platform. */
private static String describeFailure(Resolution failure, List<JarReferences> jars) { private static String describeFailure(Resolution failure, List<JarReferences> jars) {
var text = new StringBuilder(); var platforms = jars.stream()
for (var jar : jars) jar.describeTo(failure, text); .flatMap(jar -> jar.with(failure).stream())
if (text.isEmpty()) return ""; .map(Reference::platform)
return text.append(failure.advice).toString(); .collect(Collectors.toCollection(TreeSet::new));
return platforms.stream()
.map(platform -> describeFailure(failure, platform, jars))
.collect(Collectors.joining("\n"));
} }
private record Reference(String source, String target, Resolution resolution) { private static String describeFailure(Resolution failure, String platform, List<JarReferences> jars) {
var text = new StringBuilder();
for (var jar : jars) jar.describeTo(failure, platform, text);
return text.append(failure.advice(platform)).toString();
}
private record Reference(String source, String target, Resolution resolution, String platform) {
String describe() { String describe() {
var text = source + " -> " + target; var text = source + " -> " + target;
return switch (resolution) { return switch (resolution) {
@@ -159,17 +236,17 @@ final class PackReferenceCheck {
return new MissingClasses(jar.origin(), List.copyOf(classNames)); return new MissingClasses(jar.origin(), List.copyOf(classNames));
} }
void describeTo(Resolution failure, StringBuilder text) { void describeTo(Resolution failure, String platform, StringBuilder text) {
var references = with(failure); var references = with(failure).stream().filter(reference -> reference.platform().equals(platform)).toList();
if (references.isEmpty()) return; if (references.isEmpty()) return;
text.append("Module jar ").append(jar.origin()).append(' ').append(failure.header).append('\n'); text.append("Module jar ").append(jar.origin()).append(' ').append(failure.header(platform)).append('\n');
references.stream().limit(MAX_REPORTED_REFERENCES_PER_JAR) references.stream().limit(MAX_REPORTED_REFERENCES_PER_JAR)
.forEach(reference -> text.append(INDENT).append(reference.describe()).append('\n')); .forEach(reference -> text.append(INDENT).append(reference.describe()).append('\n'));
int hidden = references.size() - MAX_REPORTED_REFERENCES_PER_JAR; int hidden = references.size() - MAX_REPORTED_REFERENCES_PER_JAR;
if (hidden > 0) text.append(INDENT).append("and ").append(hidden).append(" more\n"); if (hidden > 0) text.append(INDENT).append("and ").append(hidden).append(" more\n");
} }
private List<Reference> with(Resolution resolution) { List<Reference> with(Resolution resolution) {
return unresolved.stream().filter(reference -> reference.resolution() == resolution).toList(); return unresolved.stream().filter(reference -> reference.resolution() == resolution).toList();
} }
} }
@@ -0,0 +1,20 @@
package com.volmit.host;
import java.util.Objects;
/** The platform a host runs on: its {@link ToolingPlatform description} and the loader that defines its api classes, such
* as the Iris plugin's. The host checks the parts of that platform against the loader's classes, by class file so that
* nothing is loaded, and a {@link ToolingPartLoader} delegates the platform's api packages to it.
*/
public record PlatformApi(ToolingPlatform platform, ClassLoader classes) {
private static final String CLASS_FILE_SUFFIX = ".class";
public PlatformApi {
Objects.requireNonNull(platform, "platform");
Objects.requireNonNull(classes, "classes");
}
boolean hasClass(String binaryName) {
return classes.getResource(binaryName.replace('.', '/') + CLASS_FILE_SUFFIX) != null;
}
}
@@ -60,6 +60,11 @@ public record ToolingPart(String platform, String entryClass, PackageName packag
return packageName.contains(binaryName); return packageName.contains(binaryName);
} }
/** Whether both entries start the same part: the same platform and the same package. */
boolean inSamePartAs(ToolingPart other) {
return platform.equals(other.platform) && packageName.equals(other.packageName);
}
String declaration() { String declaration() {
return platform + PLATFORM_SEPARATOR + entryClass; return platform + PLATFORM_SEPARATOR + entryClass;
} }
@@ -92,11 +97,7 @@ public record ToolingPart(String platform, String entryClass, PackageName packag
private boolean sharesClassesWithoutBeingOnePart(ToolingPart other) { private boolean sharesClassesWithoutBeingOnePart(ToolingPart other) {
boolean packagesOverlap = contains(other.entryClass) || other.contains(entryClass); boolean packagesOverlap = contains(other.entryClass) || other.contains(entryClass);
return packagesOverlap && !samePackageOfSamePlatform(other); return packagesOverlap && !inSamePartAs(other);
}
private boolean samePackageOfSamePlatform(ToolingPart other) {
return platform.equals(other.platform) && packageName.equals(other.packageName);
} }
private static ModuleLoadException overlappingParts(String origin, ToolingPart first, ToolingPart second) { private static ModuleLoadException overlappingParts(String origin, ToolingPart first, ToolingPart second) {
@@ -0,0 +1,116 @@
package com.volmit.host;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Objects;
/** The class loader of one {@link ToolingPart}, a child of its pack's class loader. Open it with
* {@link PackModules#openToolingPart}, close it before the pack closes: closing it never closes the pack's loader.
*
* <p>Where a class comes from:
* <ul>
* <li>The part's own packages: defined by this loader from the same jar copy as the pack's classes, child first, so the
* part sees the platform and the pack's loader never defines it.
* <li>A denied package of the platform, unless the host exposes the class to modules: refused with a
* {@link ClassNotFoundException}.
* <li>The platform's api packages: the platform's loader.
* <li>Everything else: the pack's loader, which gives the very {@code Class} objects the pack's modules registered, so a part
* can cast what the pack returns, such as a resource of a type the jar defines.
* </ul>
*/
public final class ToolingPartLoader implements AutoCloseable {
private final ToolingPart part;
private final PartClassLoader loader;
private ToolingPartLoader(ToolingPart part, PartClassLoader loader) {
this.part = part;
this.loader = loader;
}
static ToolingPartLoader open(ToolingPart part, ClassLoader packLoader, ExposedPackages exposed, PlatformApi platformApi) {
Objects.requireNonNull(part, "part");
var view = new PlatformView(part, exposed, platformApi);
return new ToolingPartLoader(part, new PartClassLoader(urlOf(part), packLoader, view));
}
/** Loads the part's entry class without initializing it, defined by this loader.
*
* @throws ModuleLoadException naming the jar when the class cannot be loaded
*/
public Class<?> loadEntryClass() {
try {
return Class.forName(part.entryClass(), false, loader);
} catch (ClassNotFoundException | LinkageError exception) {
throw new ModuleLoadException(null, part.jarOrigin(), "Module jar " + part.jarOrigin() + " has a tooling part "
+ part.declaration() + " whose entry class cannot be loaded: " + exception, exception);
}
}
/** Closes this loader and the jar file it opened; the pack's loader and the platform's stay open. */
@Override
public void close() {
try {
loader.close();
} catch (IOException exception) {
throw new UncheckedIOException("Cannot close tooling part class loader " + loader.getName(), exception);
}
}
private static URL urlOf(ToolingPart part) {
try {
return part.jar().toUri().toURL();
} catch (MalformedURLException exception) {
throw new ModuleLoadException(null, part.jarOrigin(), "Module jar " + part.jarOrigin() + " has no URL form", exception);
}
}
/** What decides which loader a class name goes to. */
private record PlatformView(ToolingPart part, ExposedPackages exposed, PlatformApi platformApi) {
boolean isOwnClass(String name) {
return part.contains(name);
}
boolean isDenied(String name) {
return platformApi.platform().deniesPackageOf(name) && !exposed.exposes(name);
}
boolean isPlatformApi(String name) {
return platformApi.platform().hasApiPackageOf(name);
}
}
private static final class PartClassLoader extends URLClassLoader {
static {
registerAsParallelCapable();
}
private final PlatformView view;
PartClassLoader(URL jar, ClassLoader packLoader, PlatformView view) {
super("tooling-part:" + view.part().declaration(), new URL[] {jar}, packLoader);
this.view = view;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
var type = findLoadedClass(name);
if (type == null) type = loadFromWhereItBelongs(name);
if (resolve) resolveClass(type);
return type;
}
}
private Class<?> loadFromWhereItBelongs(String name) throws ClassNotFoundException {
if (view.isOwnClass(name)) return findClass(name);
if (view.isDenied(name)) {
throw new ClassNotFoundException(name + " is not visible to a " + view.platformApi().platform().name() + " tooling part");
}
if (view.isPlatformApi(name)) return view.platformApi().classes().loadClass(name);
return getParent().loadClass(name);
}
}
}
@@ -0,0 +1,40 @@
package com.volmit.host;
import java.util.List;
import java.util.Optional;
/** Which classes of a pack are tooling parts, and which of them this host checks. A class is a part class when it lies in
* a package of a part any jar of the pack declares; every other class is generation code. Generation code and the parts
* of the platform the host runs on are checked, the parts of other platforms are skipped unread.
*/
final class ToolingPartition {
private final List<ToolingPart> parts;
private final Optional<PlatformApi> runningPlatform;
ToolingPartition(List<ModuleJar> jars, Optional<PlatformApi> runningPlatform) {
this.parts = jars.stream().flatMap(jar -> jar.toolingParts().stream()).toList();
this.runningPlatform = runningPlatform;
}
Optional<ToolingPart> partOf(String className) {
return parts.stream().filter(part -> part.contains(className)).findFirst();
}
/** Whether the class is checked: generation code, or a part of the platform the host runs on. */
boolean isChecked(String className) {
return partOf(className).map(this::runsOnThisPlatform).orElse(true);
}
/** The platform of the part a reference between these classes involves, or empty when it involves none. */
String platformInvolvedIn(String source, String target) {
return partOf(source).or(() -> partOf(target)).map(ToolingPart::platform).orElse("");
}
PlatformApi runningPlatform() {
return runningPlatform.orElseThrow(() -> new IllegalStateException("No tooling part is checked without a running platform"));
}
private boolean runsOnThisPlatform(ToolingPart part) {
return runningPlatform.map(running -> running.platform().name().equals(part.platform())).orElse(false);
}
}
@@ -0,0 +1,52 @@
package com.volmit.host;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/** A platform that tooling parts can target, described by what its parts may use: the packages of the platform's api,
* which its loader provides, and the packages parts must never see. The description is the same on every server; the
* classes behind it come from the {@link PlatformApi} the host runs on.
*
* <p>A part may use its own packages, the platform's api packages and what pack modules may use. A denied package wins
* over an api package it lies in, and applies unless the host exposes the class to pack modules, so
* {@code art.arcane.iris.builtin} stays usable while the rest of {@code art.arcane.iris} does not.
*
* @param name lower case letters and digits, such as {@code bukkit}; the platform's api package is
* {@code com.volmit.tooling.<name>}
*/
public record ToolingPlatform(String name, List<PackageName> apiPackages, List<PackageName> deniedPackages) {
/** Paper and the servers built on it: Bukkit, Paper and Adventure through the Iris plugin's loader; Iris internals, the
* server's own classes and the host side of IrisApi stay out of reach.
*/
public static final ToolingPlatform BUKKIT = new ToolingPlatform("bukkit",
packages("com.volmit.tooling.bukkit", "org.bukkit", "io.papermc.paper", "com.destroystokyo.paper", "net.kyori"),
packages("art.arcane.iris", "net.minecraft", "org.bukkit.craftbukkit", "com.mojang", ExposedPackages.HOST_PACKAGE));
public ToolingPlatform {
Objects.requireNonNull(name, "name");
if (!ToolingPart.isPlatformName(name)) {
throw new IllegalArgumentException("Tooling platform '" + name + "' is not a platform name; use lower case letters and digits");
}
apiPackages = List.copyOf(apiPackages);
deniedPackages = List.copyOf(deniedPackages);
}
/** The platform of the given name that this host describes. */
static ToolingPlatform named(String name) {
if (BUKKIT.name.equals(name)) return BUKKIT;
throw new IllegalArgumentException("Unknown tooling platform '" + name + "'; this host knows " + BUKKIT.name);
}
boolean hasApiPackageOf(String binaryName) {
return apiPackages.stream().anyMatch(name -> name.contains(binaryName));
}
boolean deniesPackageOf(String binaryName) {
return deniedPackages.stream().anyMatch(name -> name.contains(binaryName));
}
private static List<PackageName> packages(String... names) {
return Arrays.stream(names).map(PackageName::new).toList();
}
}
@@ -0,0 +1,249 @@
package com.volmit.host;
import com.volmit.support.FakePlatformApi;
import com.volmit.support.TestModuleJar;
import example.builtin.CarveModule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import static com.volmit.support.TestModuleJar.module;
import static org.junit.jupiter.api.Assertions.*;
class ToolingPartCheckTest {
private static final String BUKKIT_PART = "pack.tools.bukkit.StudioPart";
private static final String MODDED_PART = "pack.tools.modded.ModdedPart";
private static final String BUKKIT_PART_DECLARATION = "bukkit=" + BUKKIT_PART;
private static final String GENERATION_CLASS = "pack.model.Thing";
private static final String PART_PACKAGE_NOTICE = "Generation code cannot use the bukkit part; move the call into the part.";
@TempDir
Path pack;
@TempDir
Path work;
private FakePlatformApi platform;
@AfterEach
void closePlatform() {
if (platform != null) platform.close();
}
private PlatformApi bukkitApi(String... classNames) {
platform = FakePlatformApi.of(work, classNames);
return platform.asApiOf(ToolingPlatform.BUKKIT);
}
private static String classWith(String className, String body) {
int dot = className.lastIndexOf('.');
return "package " + className.substring(0, dot) + "; public final class " + className.substring(dot + 1) + " { " + body + " }";
}
private static String using(String className) {
return "static final Class<?> " + className.replace('.', '_') + " = " + className + ".class; ";
}
private static TestModuleJar jar(String generationMembers) {
return module("pack.User", "user:core", generationMembers, "")
.source(GENERATION_CLASS, classWith(GENERATION_CLASS, ""));
}
private PackModules load(TestModuleJar jar, Optional<PlatformApi> runningPlatform) {
jar.writeInto(pack, "user.jar");
return PackModules.load(pack, List.of(), List.of(), work, PackModules.DEFAULT_LOGGER, runningPlatform);
}
private String loadFailure(TestModuleJar jar, Optional<PlatformApi> runningPlatform) {
return assertThrows(ModuleLoadException.class, () -> load(jar, runningPlatform)).getMessage();
}
@Test
void partOfTheRunningPlatformMayUseItsPackagesGenerationClassesAndThePlatformApi() {
var api = bukkitApi("org.bukkit.Bukkit", "io.papermc.paper.Paper");
var jar = jar("")
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("org.bukkit.Bukkit") + using("io.papermc.paper.Paper")
+ using("pack.tools.bukkit.deep.Helper") + using(GENERATION_CLASS)))
.source("pack.tools.bukkit.deep.Helper", classWith("pack.tools.bukkit.deep.Helper", ""))
.compileAgainst(platform.jar())
.toolingParts(BUKKIT_PART_DECLARATION);
try (var modules = load(jar, Optional.of(api))) {
assertEquals(List.of(BUKKIT_PART_DECLARATION), modules.toolingParts().stream().map(ToolingPart::declaration).toList());
}
}
@Test
void generationClassUsingAPartClassFailsNamingBothClassesAndTheMove() {
var api = bukkitApi("org.bukkit.Bukkit");
var jar = jar("static Object leak() { return new " + BUKKIT_PART + "(); }")
.source(BUKKIT_PART, classWith(BUKKIT_PART, "public StudioPart() {}"))
.toolingParts(BUKKIT_PART_DECLARATION);
var message = loadFailure(jar, Optional.of(api));
assertTrue(message.contains("modules/user.jar"), message);
assertTrue(message.contains("pack.User -> " + BUKKIT_PART), message);
assertTrue(message.contains(PART_PACKAGE_NOTICE), message);
}
@Test
void generationClassUsingAPartClassFailsWhateverPlatformTheHostRunsOn() {
var jar = jar("static Object leak() { return new " + MODDED_PART + "(); }")
.source(MODDED_PART, classWith(MODDED_PART, "public ModdedPart() {}"))
.toolingParts("modded=" + MODDED_PART);
var message = loadFailure(jar, Optional.empty());
assertTrue(message.contains("pack.User -> " + MODDED_PART), message);
assertTrue(message.contains("Generation code cannot use the modded part; move the call into the part."), message);
}
@ParameterizedTest
@ValueSource(strings = {"org.bukkit.craftbukkit.CraftServer", "net.minecraft.MinecraftServer", "com.mojang.Brigadier",
"art.arcane.iris.Engine", "art.arcane.iris.engine.Deep"})
void partClassUsingADeniedPackageFailsNamingBothClasses(String denied) {
var api = bukkitApi("org.bukkit.craftbukkit.CraftServer", "net.minecraft.MinecraftServer", "com.mojang.Brigadier",
"art.arcane.iris.Engine", "art.arcane.iris.engine.Deep");
var jar = jar("")
.source(BUKKIT_PART, classWith(BUKKIT_PART, using(denied)))
.compileAgainst(platform.jar())
.toolingParts(BUKKIT_PART_DECLARATION);
var message = loadFailure(jar, Optional.of(api));
assertTrue(message.contains("bukkit part classes that use classes parts cannot see"), message);
assertTrue(message.contains(BUKKIT_PART + " -> " + denied), message);
}
@Test
void partClassUsingTheHostSideOfIrisApiFails() {
var api = bukkitApi("org.bukkit.Bukkit");
var jar = jar("")
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("com.volmit.host.ModuleHost")))
.compileAgainstHostOf(ModuleHost.class)
.toolingParts(BUKKIT_PART_DECLARATION);
var message = loadFailure(jar, Optional.of(api));
assertTrue(message.contains(BUKKIT_PART + " -> com.volmit.host.ModuleHost"), message);
}
/** A platform that denies all of {@code example}, where the built-in module classes of the tests live. */
private PlatformApi platformDenyingExample() {
platform = FakePlatformApi.of(work, "org.bukkit.Bukkit");
var denied = List.of(new PackageName("example"));
return platform.asApiOf(new ToolingPlatform("bukkit", List.of(new PackageName("org.bukkit")), denied));
}
private TestModuleJar partUsingTheBuiltInModule() {
return jar("")
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("example.builtin.CarveModule")))
.compileAgainstHostOf(CarveModule.class)
.toolingParts(BUKKIT_PART_DECLARATION);
}
@Test
void deniedPackageStaysDeniedWhenTheHostDoesNotExposeIt() {
var message = loadFailure(partUsingTheBuiltInModule(), Optional.of(platformDenyingExample()));
assertTrue(message.contains(BUKKIT_PART + " -> example.builtin.CarveModule"), message);
}
@Test
void deniedPackageIsUsableWhenTheHostExposesTheClassToModules() {
partUsingTheBuiltInModule().writeInto(pack, "user.jar");
var exposed = List.of(CarveModule.class.getPackageName());
try (var modules = PackModules.load(pack, exposed, List.of(), work, PackModules.DEFAULT_LOGGER, Optional.of(platformDenyingExample()))) {
assertEquals(1, modules.toolingParts().size());
}
}
@Test
void platformApiClassThePlatformLacksFailsNamingBothClasses() {
var buildApi = FakePlatformApi.of(work, "org.bukkit.Bukkit", "org.bukkit.entity.Player");
var jar = jar("")
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("org.bukkit.entity.Player")))
.compileAgainst(buildApi.jar())
.toolingParts(BUKKIT_PART_DECLARATION);
buildApi.close();
var message = loadFailure(jar, Optional.of(bukkitApi("org.bukkit.Bukkit")));
assertTrue(message.contains("bukkit API classes this server does not have"), message);
assertTrue(message.contains(BUKKIT_PART + " -> org.bukkit.entity.Player"), message);
}
@Test
void partClassUsingAClassOfAnotherPartFails() {
var api = bukkitApi("org.bukkit.Bukkit");
var otherPart = "pack.other.bukkit.ImportPart";
var jar = jar("")
.source(BUKKIT_PART, classWith(BUKKIT_PART, using(otherPart)))
.source(otherPart, classWith(otherPart, ""))
.toolingParts(BUKKIT_PART_DECLARATION + " bukkit=" + otherPart);
var message = loadFailure(jar, Optional.of(api));
assertTrue(message.contains("bukkit part classes that use classes of another part"), message);
assertTrue(message.contains(BUKKIT_PART + " -> " + otherPart), message);
}
@Test
void partOfAnotherPlatformIsSkippedUnread() {
var api = bukkitApi("org.bukkit.Bukkit");
var jar = jar("")
.source(MODDED_PART, classWith(MODDED_PART, using("org.junit.jupiter.api.Test") + using("net.minecraft.MinecraftServer")))
.compileAgainstHostOf(org.junit.jupiter.api.Test.class)
.source("net.minecraft.MinecraftServer", classWith("net.minecraft.MinecraftServer", ""))
.toolingParts("modded=" + MODDED_PART);
try (var modules = load(jar, Optional.of(api))) {
assertEquals(List.of(), modules.toolingParts());
assertEquals(List.of(), modules.missingClasses());
}
}
@Test
void partsAreSkippedWhenTheHostRunsOnNoPlatform() {
var jar = jar("")
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("org.junit.jupiter.api.Test")))
.compileAgainstHostOf(org.junit.jupiter.api.Test.class)
.toolingParts(BUKKIT_PART_DECLARATION);
try (var modules = load(jar, Optional.empty())) {
assertEquals(List.of(), modules.toolingParts());
}
}
@Test
void sameClassOutsideAPartIsStillCheckedAsGenerationCode() {
var api = bukkitApi("org.bukkit.Bukkit");
var jar = jar(using("org.junit.jupiter.api.Test"))
.compileAgainstHostOf(org.junit.jupiter.api.Test.class)
.source(MODDED_PART, classWith(MODDED_PART, ""))
.toolingParts("modded=" + MODDED_PART);
var message = loadFailure(jar, Optional.of(api));
assertTrue(message.contains("pack.User -> org.junit.jupiter.api.Test"), message);
}
@Test
void partClassUsingAHiddenClassFailsLikeGenerationCode() {
var api = bukkitApi("org.bukkit.Bukkit");
var jar = jar("")
.source(BUKKIT_PART, classWith(BUKKIT_PART, using("org.junit.jupiter.api.Test")))
.compileAgainstHostOf(org.junit.jupiter.api.Test.class)
.toolingParts(BUKKIT_PART_DECLARATION);
var message = loadFailure(jar, Optional.of(api));
assertTrue(message.contains("hidden from modules"), message);
assertTrue(message.contains(BUKKIT_PART + " -> org.junit.jupiter.api.Test"), message);
}
}
@@ -0,0 +1,166 @@
package com.volmit.host;
import com.volmit.support.FakePlatformApi;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import static com.volmit.support.TestModuleJar.module;
import static org.junit.jupiter.api.Assertions.*;
class ToolingPartLoaderTest {
private static final String PART = "pack.tools.bukkit.StudioPart";
private static final String PART_HELPER = "pack.tools.bukkit.deep.Helper";
private static final String GENERATION_CLASS = "pack.model.Thing";
private static final String PLATFORM_CLASS = "org.bukkit.Bukkit";
@TempDir
Path pack;
@TempDir
Path work;
private FakePlatformApi platform;
private PackModules modules;
@BeforeEach
void loadPackWithABukkitPart() {
platform = FakePlatformApi.of(work, PLATFORM_CLASS, "org.bukkit.craftbukkit.CraftServer", "net.minecraft.MinecraftServer",
"com.mojang.Brigadier", "art.arcane.iris.Engine");
module("pack.User", "user:core", "", "")
.source(GENERATION_CLASS, "package pack.model; public final class Thing {}")
.source(PART, """
package pack.tools.bukkit;
public final class StudioPart {
public static Class<?> thing() { return pack.model.Thing.class; }
public static Class<?> platform() { return org.bukkit.Bukkit.class; }
public static Class<?> helper() { return pack.tools.bukkit.deep.Helper.class; }
}
""")
.source(PART_HELPER, "package pack.tools.bukkit.deep; public final class Helper {}")
.compileAgainst(platform.jar())
.toolingParts("bukkit=" + PART)
.writeInto(pack, "user.jar");
modules = PackModules.load(pack, List.of(), List.of(), work, PackModules.DEFAULT_LOGGER,
Optional.of(platform.asApiOf(ToolingPlatform.BUKKIT)));
}
@AfterEach
void close() {
modules.close();
platform.close();
}
private ClassLoader packLoader() {
return modules.modules().getFirst().module().getClass().getClassLoader();
}
private ToolingPartLoader openThePart() {
return modules.openToolingPart(modules.toolingParts().getFirst());
}
private static Class<?> call(Class<?> type, String method) throws ReflectiveOperationException {
return (Class<?>) type.getMethod(method).invoke(null);
}
@Test
void definesTheEntryClassAndTheRestOfThePartItselfFromTheSameJarCopy() throws Exception {
try (var loader = openThePart()) {
var entry = loader.loadEntryClass();
var helper = call(entry, "helper");
assertEquals(PART, entry.getName());
assertNotSame(packLoader(), entry.getClassLoader());
assertSame(entry.getClassLoader(), helper.getClassLoader());
assertNotSame(packLoader().loadClass(PART), entry);
assertEquals(modules.toolingParts().getFirst().jar().toUri().toURL(), entry.getProtectionDomain().getCodeSource().getLocation());
}
}
@Test
void childOfThePackLoader() throws Exception {
try (var loader = openThePart()) {
assertSame(packLoader(), loader.loadEntryClass().getClassLoader().getParent());
}
}
@Test
void delegatesPlatformPackagesToThePlatformLoader() throws Exception {
try (var loader = openThePart()) {
var fromPart = call(loader.loadEntryClass(), "platform");
assertSame(platform.classes().loadClass(PLATFORM_CLASS), fromPart);
}
}
@Test
void returnsTheClassObjectsTheModuleRegisteredForGenerationClasses() throws Exception {
try (var loader = openThePart()) {
var fromPart = call(loader.loadEntryClass(), "thing");
assertSame(packLoader().loadClass(GENERATION_CLASS), fromPart);
}
}
@ParameterizedTest
@ValueSource(strings = {"org.bukkit.craftbukkit.CraftServer", "net.minecraft.MinecraftServer", "com.mojang.Brigadier",
"art.arcane.iris.Engine", "com.volmit.host.ModuleHost"})
void refusesWhatAPartMustNotSee(String denied) {
try (var loader = openThePart()) {
var partLoader = loader.loadEntryClass().getClassLoader();
assertThrows(ClassNotFoundException.class, () -> partLoader.loadClass(denied));
}
}
@Test
void closingItLeavesThePackLoaderAndThePlatformOpen() throws Exception {
var loader = openThePart();
var partLoader = loader.loadEntryClass().getClassLoader();
loader.close();
assertSame(packLoader().loadClass(GENERATION_CLASS), packLoader().loadClass(GENERATION_CLASS));
assertNotNull(platform.classes().loadClass(PLATFORM_CLASS));
assertThrows(ClassNotFoundException.class, () -> partLoader.loadClass(PART_HELPER));
}
@Test
void entryClassThatCannotBeLoadedIsReportedNamingTheJarAndThePart() {
var unlisted = new ToolingPart("bukkit", "pack.tools.bukkit.Nowhere", new PackageName("pack.tools.bukkit"),
"modules/user.jar", modules.toolingParts().getFirst().jar());
try (var loader = ToolingPartLoader.open(unlisted, packLoader(), ExposedPackages.apiOnly(), platform.asApiOf(ToolingPlatform.BUKKIT))) {
var failure = assertThrows(ModuleLoadException.class, loader::loadEntryClass);
assertTrue(failure.getMessage().contains("modules/user.jar"), failure.getMessage());
assertTrue(failure.getMessage().contains("bukkit=pack.tools.bukkit.Nowhere"), failure.getMessage());
}
}
@Test
void openingAPartThePackDoesNotListFails() {
var stranger = new ToolingPart("bukkit", PART, new PackageName("pack.tools.bukkit"), "modules/other.jar", pack);
assertThrows(IllegalArgumentException.class, () -> modules.openToolingPart(stranger));
}
@Test
void loadedPackListsAndOpensThePartsOfTheHostsPlatform() throws Exception {
var host = ModuleHost.of(List.of()).runningOn(platform.asApiOf(ToolingPlatform.BUKKIT));
try (var loaded = LoadedPack.load(pack, host); var loader = loaded.openToolingPart(loaded.toolingParts().getFirst())) {
assertEquals(PART, loader.loadEntryClass().getName());
}
}
@Test
void hostWithoutAPlatformHasNoPartsToOpen() {
try (var loaded = LoadedPack.load(pack, ModuleHost.of(List.of()))) {
assertEquals(List.of(), loaded.toolingParts());
}
}
}
@@ -0,0 +1,49 @@
package com.volmit.host;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ToolingPlatformTest {
@ParameterizedTest
@ValueSource(strings = {"com.volmit.tooling.bukkit.BukkitToolPart", "org.bukkit.Bukkit", "org.bukkit.entity.Player", "io.papermc.paper.Paper",
"com.destroystokyo.paper.Event", "net.kyori.adventure.text.Component"})
void bukkitApiPackagesAreThePlatformsApi(String className) {
assertTrue(ToolingPlatform.BUKKIT.hasApiPackageOf(className));
}
@ParameterizedTest
@ValueSource(strings = {"org.bukkitx.Other", "com.volmit.tooling.Command", "com.google.gson.Gson", "java.lang.String"})
void otherClassesAreNotBukkitApi(String className) {
assertFalse(ToolingPlatform.BUKKIT.hasApiPackageOf(className));
}
@ParameterizedTest
@ValueSource(strings = {"art.arcane.iris.Iris", "art.arcane.iris.builtin.Thing", "net.minecraft.world.level.Level", "org.bukkit.craftbukkit.CraftServer",
"org.bukkit.craftbukkit.v26.CraftWorld", "com.mojang.brigadier.Command", "com.volmit.host.PackModules"})
void bukkitDeniesIrisInternalsTheServerAndTheHost(String className) {
assertTrue(ToolingPlatform.BUKKIT.deniesPackageOf(className));
}
@Test
void bukkitDoesNotDenyItsOwnApiOrTheIrisApi() {
assertFalse(ToolingPlatform.BUKKIT.deniesPackageOf("org.bukkit.Bukkit"));
assertFalse(ToolingPlatform.BUKKIT.deniesPackageOf("com.volmit.IrisModule"));
assertFalse(ToolingPlatform.BUKKIT.deniesPackageOf("art.arcane.irisx.Other"));
}
@Test
void namedFindsTheDescriptionsTheHostKnows() {
assertSame(ToolingPlatform.BUKKIT, ToolingPlatform.named("bukkit"));
assertTrue(assertThrows(IllegalArgumentException.class, () -> ToolingPlatform.named("modded")).getMessage()
.contains("Unknown tooling platform 'modded'"));
}
@ParameterizedTest
@ValueSource(strings = {"", "Bukkit", "1bukkit", "bu-kkit", "bukkit.paper"})
void platformNameIsLowerCaseLettersAndDigits(String name) {
assertThrows(IllegalArgumentException.class, () -> new ToolingPlatform(name, List.of(), List.of()));
}
}
@@ -0,0 +1,59 @@
package com.volmit.support;
import com.volmit.host.PlatformApi;
import com.volmit.host.ToolingPlatform;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
/** A tiny stand-in for a platform's api jar, such as paper-api: a jar of empty public classes, and a loader that defines
* only them, like the platform plugin's loader would. Close it to release the jar.
*/
public final class FakePlatformApi implements AutoCloseable {
private final Path jar;
private final URLClassLoader classes;
private FakePlatformApi(Path jar, URLClassLoader classes) {
this.jar = jar;
this.classes = classes;
}
/** Writes a jar below {@code workDirectory} that holds one empty public class per name, such as {@code org.bukkit.Bukkit}. */
public static FakePlatformApi of(Path workDirectory, String... classNames) {
try {
var jarSource = new TestModuleJar();
for (var className : classNames) {
int dot = className.lastIndexOf('.');
jarSource.source(className, "package " + className.substring(0, dot) + "; public class " + className.substring(dot + 1) + " {}");
}
var jar = jarSource.writeInto(Files.createTempDirectory(workDirectory, "platform"), "platform-api.jar");
return new FakePlatformApi(jar, new URLClassLoader("fake-platform", new URL[] {jar.toUri().toURL()}, null));
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
public Path jar() {
return jar;
}
public ClassLoader classes() {
return classes;
}
public PlatformApi asApiOf(ToolingPlatform platform) {
return new PlatformApi(platform, classes);
}
@Override
public void close() {
try {
classes.close();
} catch (IOException exception) {
throw new UncheckedIOException(exception);
}
}
}