Path: blob/master/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java
41159 views
/*1* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package jdk.internal.module;2526import java.io.Closeable;27import java.io.File;28import java.io.IOError;29import java.io.IOException;30import java.io.InputStream;31import java.io.UncheckedIOException;32import java.lang.module.ModuleDescriptor;33import java.lang.module.ModuleDescriptor.Builder;34import java.lang.module.ModuleReader;35import java.lang.module.ModuleReference;36import java.net.MalformedURLException;37import java.net.URI;38import java.net.URL;39import java.nio.ByteBuffer;40import java.nio.file.Files;41import java.nio.file.Path;42import java.nio.file.Paths;43import java.util.ArrayList;44import java.util.HashMap;45import java.util.HashSet;46import java.util.List;47import java.util.Map;48import java.util.Optional;49import java.util.Set;50import java.util.jar.JarEntry;51import java.util.jar.JarFile;52import java.util.stream.Stream;5354import jdk.internal.loader.Resource;55import jdk.internal.access.JavaLangModuleAccess;56import jdk.internal.access.SharedSecrets;57import sun.net.www.ParseUtil;585960/**61* Provides support for patching modules, mostly the boot layer.62*/6364public final class ModulePatcher {6566private static final JavaLangModuleAccess JLMA67= SharedSecrets.getJavaLangModuleAccess();6869// module name -> sequence of patches (directories or JAR files)70private final Map<String, List<Path>> map;7172/**73* Initialize the module patcher with the given map. The map key is74* the module name, the value is a list of path strings.75*/76public ModulePatcher(Map<String, List<String>> input) {77if (input.isEmpty()) {78this.map = Map.of();79} else {80Map<String, List<Path>> map = new HashMap<>();81for (Map.Entry<String, List<String>> e : input.entrySet()) {82String mn = e.getKey();83List<Path> paths = e.getValue().stream()84.map(Paths::get)85.toList();86map.put(mn, paths);87}88this.map = map;89}90}9192/**93* Returns a module reference that interposes on the given module if94* needed. If there are no patches for the given module then the module95* reference is simply returned. Otherwise the patches for the module96* are scanned (to find any new packages) and a new module reference is97* returned.98*99* @throws UncheckedIOException if an I/O error is detected100*/101public ModuleReference patchIfNeeded(ModuleReference mref) {102// if there are no patches for the module then nothing to do103ModuleDescriptor descriptor = mref.descriptor();104String mn = descriptor.name();105List<Path> paths = map.get(mn);106if (paths == null)107return mref;108109// Scan the JAR file or directory tree to get the set of packages.110// For automatic modules then packages that do not contain class files111// must be ignored.112Set<String> packages = new HashSet<>();113boolean isAutomatic = descriptor.isAutomatic();114try {115for (Path file : paths) {116if (Files.isRegularFile(file)) {117118// JAR file - do not open as a multi-release JAR as this119// is not supported by the boot class loader120try (JarFile jf = new JarFile(file.toString())) {121jf.stream()122.filter(e -> !e.isDirectory()123&& (!isAutomatic || e.getName().endsWith(".class")))124.map(e -> toPackageName(file, e))125.filter(Checks::isPackageName)126.forEach(packages::add);127}128129} else if (Files.isDirectory(file)) {130131// exploded directory without following sym links132Path top = file;133Files.find(top, Integer.MAX_VALUE,134((path, attrs) -> attrs.isRegularFile()))135.filter(path -> (!isAutomatic136|| path.toString().endsWith(".class"))137&& !isHidden(path))138.map(path -> toPackageName(top, path))139.filter(Checks::isPackageName)140.forEach(packages::add);141142}143}144145} catch (IOException ioe) {146throw new UncheckedIOException(ioe);147}148149// if there are new packages then we need a new ModuleDescriptor150packages.removeAll(descriptor.packages());151if (!packages.isEmpty()) {152Builder builder = JLMA.newModuleBuilder(descriptor.name(),153/*strict*/ descriptor.isAutomatic(),154descriptor.modifiers());155if (!descriptor.isAutomatic()) {156descriptor.requires().forEach(builder::requires);157descriptor.exports().forEach(builder::exports);158descriptor.opens().forEach(builder::opens);159descriptor.uses().forEach(builder::uses);160}161descriptor.provides().forEach(builder::provides);162163descriptor.version().ifPresent(builder::version);164descriptor.mainClass().ifPresent(builder::mainClass);165166// original + new packages167builder.packages(descriptor.packages());168builder.packages(packages);169170descriptor = builder.build();171}172173// return a module reference to the patched module174URI location = mref.location().orElse(null);175176ModuleTarget target = null;177ModuleHashes recordedHashes = null;178ModuleHashes.HashSupplier hasher = null;179ModuleResolution mres = null;180if (mref instanceof ModuleReferenceImpl) {181ModuleReferenceImpl impl = (ModuleReferenceImpl)mref;182target = impl.moduleTarget();183recordedHashes = impl.recordedHashes();184hasher = impl.hasher();185mres = impl.moduleResolution();186}187188return new ModuleReferenceImpl(descriptor,189location,190() -> new PatchedModuleReader(paths, mref),191this,192target,193recordedHashes,194hasher,195mres);196197}198199/**200* Returns true is this module patcher has patches.201*/202public boolean hasPatches() {203return !map.isEmpty();204}205206/*207* Returns the names of the patched modules.208*/209Set<String> patchedModules() {210return map.keySet();211}212213/**214* A ModuleReader that reads resources from a patched module.215*216* This class is public so as to expose the findResource method to the217* built-in class loaders and avoid locating the resource twice during218* class loading (once to locate the resource, the second to gets the219* URL for the CodeSource).220*/221public static class PatchedModuleReader implements ModuleReader {222private final List<ResourceFinder> finders;223private final ModuleReference mref;224private final URL delegateCodeSourceURL;225private volatile ModuleReader delegate;226227/**228* Creates the ModuleReader to reads resources in a patched module.229*/230PatchedModuleReader(List<Path> patches, ModuleReference mref) {231List<ResourceFinder> finders = new ArrayList<>();232boolean initialized = false;233try {234for (Path file : patches) {235if (Files.isRegularFile(file)) {236finders.add(new JarResourceFinder(file));237} else {238finders.add(new ExplodedResourceFinder(file));239}240}241initialized = true;242} catch (IOException ioe) {243throw new UncheckedIOException(ioe);244} finally {245// close all ResourceFinder in the event of an error246if (!initialized) closeAll(finders);247}248249this.finders = finders;250this.mref = mref;251this.delegateCodeSourceURL = codeSourceURL(mref);252}253254/**255* Closes all resource finders.256*/257private static void closeAll(List<ResourceFinder> finders) {258for (ResourceFinder finder : finders) {259try { finder.close(); } catch (IOException ioe) { }260}261}262263/**264* Returns the code source URL for the given module.265*/266private static URL codeSourceURL(ModuleReference mref) {267try {268Optional<URI> ouri = mref.location();269if (ouri.isPresent())270return ouri.get().toURL();271} catch (MalformedURLException e) { }272return null;273}274275/**276* Returns the ModuleReader to delegate to when the resource is not277* found in a patch location.278*/279private ModuleReader delegate() throws IOException {280ModuleReader r = delegate;281if (r == null) {282synchronized (this) {283r = delegate;284if (r == null) {285delegate = r = mref.open();286}287}288}289return r;290}291292/**293* Finds a resources in the patch locations. Returns null if not found294* or the name is "module-info.class" as that cannot be overridden.295*/296private Resource findResourceInPatch(String name) throws IOException {297if (!name.equals("module-info.class")) {298for (ResourceFinder finder : finders) {299Resource r = finder.find(name);300if (r != null)301return r;302}303}304return null;305}306307/**308* Finds a resource of the given name in the patched module.309*/310public Resource findResource(String name) throws IOException {311312// patch locations313Resource r = findResourceInPatch(name);314if (r != null)315return r;316317// original module318ByteBuffer bb = delegate().read(name).orElse(null);319if (bb == null)320return null;321322return new Resource() {323private <T> T shouldNotGetHere(Class<T> type) {324throw new InternalError("should not get here");325}326@Override327public String getName() {328return shouldNotGetHere(String.class);329}330@Override331public URL getURL() {332return shouldNotGetHere(URL.class);333}334@Override335public URL getCodeSourceURL() {336return delegateCodeSourceURL;337}338@Override339public ByteBuffer getByteBuffer() throws IOException {340return bb;341}342@Override343public InputStream getInputStream() throws IOException {344return shouldNotGetHere(InputStream.class);345}346@Override347public int getContentLength() throws IOException {348return shouldNotGetHere(int.class);349}350};351}352353@Override354public Optional<URI> find(String name) throws IOException {355Resource r = findResourceInPatch(name);356if (r != null) {357URI uri = URI.create(r.getURL().toString());358return Optional.of(uri);359} else {360return delegate().find(name);361}362}363364@Override365public Optional<InputStream> open(String name) throws IOException {366Resource r = findResourceInPatch(name);367if (r != null) {368return Optional.of(r.getInputStream());369} else {370return delegate().open(name);371}372}373374@Override375public Optional<ByteBuffer> read(String name) throws IOException {376Resource r = findResourceInPatch(name);377if (r != null) {378ByteBuffer bb = r.getByteBuffer();379assert !bb.isDirect();380return Optional.of(bb);381} else {382return delegate().read(name);383}384}385386@Override387public void release(ByteBuffer bb) {388if (bb.isDirect()) {389try {390delegate().release(bb);391} catch (IOException ioe) {392throw new InternalError(ioe);393}394}395}396397@Override398public Stream<String> list() throws IOException {399Stream<String> s = delegate().list();400for (ResourceFinder finder : finders) {401s = Stream.concat(s, finder.list());402}403return s.distinct();404}405406@Override407public void close() throws IOException {408closeAll(finders);409delegate().close();410}411}412413414/**415* A resource finder that find resources in a patch location.416*/417private static interface ResourceFinder extends Closeable {418Resource find(String name) throws IOException;419Stream<String> list() throws IOException;420}421422423/**424* A ResourceFinder that finds resources in a JAR file.425*/426private static class JarResourceFinder implements ResourceFinder {427private final JarFile jf;428private final URL csURL;429430JarResourceFinder(Path path) throws IOException {431this.jf = new JarFile(path.toString());432this.csURL = path.toUri().toURL();433}434435@Override436public void close() throws IOException {437jf.close();438}439440@Override441public Resource find(String name) throws IOException {442JarEntry entry = jf.getJarEntry(name);443if (entry == null)444return null;445446return new Resource() {447@Override448public String getName() {449return name;450}451@Override452public URL getURL() {453String encodedPath = ParseUtil.encodePath(name, false);454try {455return new URL("jar:" + csURL + "!/" + encodedPath);456} catch (MalformedURLException e) {457return null;458}459}460@Override461public URL getCodeSourceURL() {462return csURL;463}464@Override465public ByteBuffer getByteBuffer() throws IOException {466byte[] bytes = getInputStream().readAllBytes();467return ByteBuffer.wrap(bytes);468}469@Override470public InputStream getInputStream() throws IOException {471return jf.getInputStream(entry);472}473@Override474public int getContentLength() throws IOException {475long size = entry.getSize();476return (size > Integer.MAX_VALUE) ? -1 : (int) size;477}478};479}480481@Override482public Stream<String> list() throws IOException {483return jf.stream().map(JarEntry::getName);484}485}486487488/**489* A ResourceFinder that finds resources on the file system.490*/491private static class ExplodedResourceFinder implements ResourceFinder {492private final Path dir;493494ExplodedResourceFinder(Path dir) {495this.dir = dir;496}497498@Override499public void close() { }500501@Override502public Resource find(String name) throws IOException {503Path file = Resources.toFilePath(dir, name);504if (file != null) {505return newResource(name, dir, file);506} else {507return null;508}509}510511private Resource newResource(String name, Path top, Path file) {512return new Resource() {513@Override514public String getName() {515return name;516}517@Override518public URL getURL() {519try {520return file.toUri().toURL();521} catch (IOException | IOError e) {522return null;523}524}525@Override526public URL getCodeSourceURL() {527try {528return top.toUri().toURL();529} catch (IOException | IOError e) {530return null;531}532}533@Override534public ByteBuffer getByteBuffer() throws IOException {535return ByteBuffer.wrap(Files.readAllBytes(file));536}537@Override538public InputStream getInputStream() throws IOException {539return Files.newInputStream(file);540}541@Override542public int getContentLength() throws IOException {543long size = Files.size(file);544return (size > Integer.MAX_VALUE) ? -1 : (int)size;545}546};547}548549@Override550public Stream<String> list() throws IOException {551return Files.walk(dir, Integer.MAX_VALUE)552.map(f -> Resources.toResourceName(dir, f))553.filter(s -> !s.isEmpty());554}555}556557558/**559* Derives a package name from the file path of an entry in an exploded patch560*/561private static String toPackageName(Path top, Path file) {562Path entry = top.relativize(file);563Path parent = entry.getParent();564if (parent == null) {565return warnIfModuleInfo(top, entry.toString());566} else {567return parent.toString().replace(File.separatorChar, '.');568}569}570571/**572* Returns true if the given file exists and is a hidden file573*/574private boolean isHidden(Path file) {575try {576return Files.isHidden(file);577} catch (IOException ioe) {578return false;579}580}581582/**583* Derives a package name from the name of an entry in a JAR file.584*/585private static String toPackageName(Path file, JarEntry entry) {586String name = entry.getName();587int index = name.lastIndexOf("/");588if (index == -1) {589return warnIfModuleInfo(file, name);590} else {591return name.substring(0, index).replace('/', '.');592}593}594595private static String warnIfModuleInfo(Path file, String e) {596if (e.equals("module-info.class"))597System.err.println("WARNING: " + e + " ignored in patch: " + file);598return "";599}600}601602603