package com.volmit.host; import com.volmit.IrisModule; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.System.Logger.Level; 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; import java.util.function.Predicate; import java.util.stream.Collectors; /** The module jars of one pack: every {@code /modules/*.jar}, one module per jar, ordered * by file name so the result never depends on directory listing order. Hosts normally load packs * through {@link LoadedPack}, which uses this. * *

The load first copies the jars into a fresh temporary directory ({@link JarSnapshot}) and works * only on the copies, so the originals stay free to be replaced, even on Windows, and the load sees one * consistent set of jars. Messages and origins name the originals ({@code modules/moss.jar}). Copies * are deleted when the pack closes or its load fails; copies a crashed process left behind are removed * by a later load ({@link StaleJarSnapshots}). * *

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 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()}, except those in the optional packages * the jar's module declares in its {@link com.volmit.ModuleInfo}. * *

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, and one WARNING listing the missing classes, if any. * *

Close this when the pack unloads, after dropping everything built from its modules, such as * {@link LoadedModules}. Classes not loaded before then can no longer be loaded. */ public final class PackModules implements AutoCloseable { public static final String MODULES_DIRECTORY = "modules"; static final String JAR_EXTENSION = ".jar"; private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir"; private static final System.Logger LOGGER = System.getLogger(PackModules.class.getName()); private final List modules; private final List missingClasses; private final URLClassLoader loader; private final JarSnapshot snapshot; private PackModules( List modules, List missingClasses, URLClassLoader loader, JarSnapshot snapshot) { this.modules = List.copyOf(modules); this.missingClasses = List.copyOf(missingClasses); this.loader = loader; this.snapshot = snapshot; } /** 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, Collection exposedHostPackages) { return load(packRoot, exposedHostPackages, systemTemporaryDirectory()); } /** Like {@link #load(Path, Collection)}, copying the jars below {@code temporaryRoot}. */ static PackModules load(Path packRoot, Collection exposedHostPackages, Path temporaryRoot) { Objects.requireNonNull(packRoot, "packRoot"); var host = new ExposedHostClassLoader(IrisModule.class.getClassLoader(), ExposedPackages.apiAnd(exposedHostPackages)); StaleJarSnapshots.remove(temporaryRoot); var snapshot = JarSnapshot.take(packRoot, findModuleJars(packRoot), temporaryRoot); try { var packModules = loadSnapshot(packRoot, snapshot, host); logLoad(packName(packRoot), packModules); return packModules; } catch (RuntimeException | Error failure) { snapshot.deleteAfterFailure(failure); throw failure; } } /** One module per jar, in jar file name order. */ public List modules() { return modules; } /** Per jar that uses any, in jar file name order, the classes that neither the pack, Iris nor the * JDK has and that are outside the optional packages the jar's module declares. Empty when every * class the jars use exists or is declared optional. */ public List missingClasses() { return missingClasses; } /** Closes the class loader, then deletes the jar copies, which an open loader would keep locked on Windows. */ @Override public void close() { try { loader.close(); } catch (IOException exception) { var failure = new UncheckedIOException("Cannot close module class loader " + loader.getName(), exception); snapshot.deleteAfterFailure(failure); throw failure; } snapshot.delete(); } private static Path systemTemporaryDirectory() { return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY)); } private static PackModules loadSnapshot(Path packRoot, JarSnapshot snapshot, ExposedHostClassLoader host) { var jars = snapshot.jars().stream().map(ModuleJar::read).toList(); var missingClasses = PackClassCheck.requireLinkable(jars, host); return defineModules(packRoot, jars, missingClasses, host, snapshot); } private static List findModuleJars(Path packRoot) { var directory = packRoot.resolve(MODULES_DIRECTORY); if (!Files.isDirectory(directory)) return List.of(); try (var entries = Files.list(directory)) { return entries .filter(PackModules::isJar) .sorted(Comparator.comparing(jar -> jar.getFileName().toString())) .toList(); } catch (IOException exception) { throw new UncheckedIOException("Cannot list module jars in " + directory, exception); } } private static boolean isJar(Path path) { return Files.isRegularFile(path) && path.getFileName().toString().endsWith(JAR_EXTENSION); } private static PackModules defineModules( Path packRoot, List jars, List missingClasses, ClassLoader host, JarSnapshot snapshot) { var loader = newPackClassLoader(packRoot, jars, host); try { var modules = createModules(jars, loader, snapshot); return new PackModules(modules, withoutDeclaredOptional(missingClasses, modules), loader, snapshot); } catch (RuntimeException | Error failure) { closeAfterFailure(loader, failure); throw failure; } } private static URLClassLoader newPackClassLoader(Path packRoot, List jars, ClassLoader host) { var urls = jars.stream().map(ModuleJar::url).toArray(URL[]::new); return new URLClassLoader("pack:" + packName(packRoot), urls, host); } private static void logLoad(String packName, PackModules packModules) { LOGGER.log(Level.INFO, () -> PackModulesSummary.describe(packName, packModules.modules())); if (packModules.missingClasses().isEmpty()) return; LOGGER.log(Level.WARNING, () -> MissingClassesWarning.describe(packName, packModules.missingClasses())); } private static String packName(Path packRoot) { var name = packRoot.getFileName(); return name == null ? packRoot.toString() : name.toString(); } private static List createModules(List jars, ClassLoader loader, JarSnapshot snapshot) { return jars.stream().map(jar -> jar.createModule(loader, snapshot)).toList(); } /** A module's optional packages excuse only its own jar's missing classes. They are read from * {@code info()}, so this runs after the entry classes exist; errors were decided before that and * never depend on them. */ private static List withoutDeclaredOptional(List missingClasses, List modules) { var optionalPackages = modules.stream() .collect(Collectors.toMap(DiscoveredModule::origin, found -> found.info().optionalPackages())); return missingClasses.stream() .map(jar -> jar.outside(optionalPackages.get(jar.origin()))) .filter(Predicate.not(MissingClasses::isEmpty)) .toList(); } private static void closeAfterFailure(URLClassLoader loader, Throwable failure) { try { loader.close(); } catch (IOException exception) { failure.addSuppressed(exception); } } }