jdk/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java
changeset 27565 729f9700483a
child 31673 135283550686
equal deleted inserted replaced
27564:eaaa79b68cd5 27565:729f9700483a
       
     1 /*
       
     2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 package jdk.internal.jimage;
       
    26 
       
    27 import java.io.IOException;
       
    28 import java.io.UncheckedIOException;
       
    29 import java.net.URI;
       
    30 import java.nio.ByteBuffer;
       
    31 import java.nio.ByteOrder;
       
    32 import java.nio.IntBuffer;
       
    33 import java.nio.file.Files;
       
    34 import java.nio.file.FileSystem;
       
    35 import java.nio.file.attribute.BasicFileAttributes;
       
    36 import java.nio.file.attribute.FileTime;
       
    37 import java.nio.file.Paths;
       
    38 import java.nio.file.Path;
       
    39 import java.util.ArrayList;
       
    40 import java.util.Collections;
       
    41 import java.util.HashMap;
       
    42 import java.util.List;
       
    43 import java.util.Map;
       
    44 import java.util.function.Consumer;
       
    45 import java.util.function.Supplier;
       
    46 
       
    47 public class ImageReader extends BasicImageReader {
       
    48     // well-known strings needed for image file system.
       
    49     static final UTF8String ROOT = new UTF8String("/");
       
    50     static final UTF8String META_INF = new UTF8String("/META-INF");
       
    51     static final UTF8String PACKAGES_OFFSETS = new UTF8String("packages.offsets");
       
    52 
       
    53     // attributes of the .jimage file. jimage file does not contain
       
    54     // attributes for the individual resources (yet). We use attributes
       
    55     // of the jimage file itself (creation, modification, access times).
       
    56     // Iniitalized lazily, see {@link #imageFileAttributes()}.
       
    57     private BasicFileAttributes imageFileAttributes;
       
    58 
       
    59     private final Map<String, String> packageMap;
       
    60 
       
    61     // directory management implementation
       
    62     private final Map<UTF8String, Node> nodes;
       
    63     private volatile Directory rootDir;
       
    64 
       
    65     ImageReader(String imagePath, ByteOrder byteOrder) throws IOException {
       
    66         super(imagePath, byteOrder);
       
    67         this.packageMap = PackageModuleMap.readFrom(this);
       
    68         this.nodes = Collections.synchronizedMap(new HashMap<>());
       
    69     }
       
    70 
       
    71     ImageReader(String imagePath) throws IOException {
       
    72         this(imagePath, ByteOrder.nativeOrder());
       
    73     }
       
    74 
       
    75     public static ImageReader open(String imagePath, ByteOrder byteOrder) throws IOException {
       
    76         return new ImageReader(imagePath, byteOrder);
       
    77     }
       
    78 
       
    79     /**
       
    80      * Opens the given file path as an image file, returning an {@code ImageReader}.
       
    81      */
       
    82     public static ImageReader open(String imagePath) throws IOException {
       
    83         return open(imagePath, ByteOrder.nativeOrder());
       
    84     }
       
    85 
       
    86     @Override
       
    87     public synchronized void close() throws IOException {
       
    88         super.close();
       
    89         clearNodes();
       
    90     }
       
    91 
       
    92     /**
       
    93      * Return the module name that contains the given package name.
       
    94      */
       
    95     public String getModule(String pkg) {
       
    96         return packageMap.get(pkg);
       
    97     }
       
    98 
       
    99     // jimage file does not store directory structure. We build nodes
       
   100     // using the "path" strings found in the jimage file.
       
   101     // Node can be a directory or a resource
       
   102     public static abstract class Node {
       
   103         private static final int ROOT_DIR = 0b0000_0000_0000_0001;
       
   104         private static final int MODULE_DIR = 0b0000_0000_0000_0010;
       
   105         private static final int METAINF_DIR = 0b0000_0000_0000_0100;
       
   106         private static final int TOPLEVEL_PKG_DIR = 0b0000_0000_0000_1000;
       
   107         private static final int HIDDEN = 0b0000_0000_0001_0000;
       
   108 
       
   109         private int flags;
       
   110         private final UTF8String name;
       
   111         private final BasicFileAttributes fileAttrs;
       
   112 
       
   113         Node(UTF8String name, BasicFileAttributes fileAttrs) {
       
   114             assert name != null;
       
   115             assert fileAttrs != null;
       
   116             this.name = name;
       
   117             this.fileAttrs = fileAttrs;
       
   118         }
       
   119 
       
   120         public final void setIsRootDir() {
       
   121             flags |= ROOT_DIR;
       
   122         }
       
   123 
       
   124         public final boolean isRootDir() {
       
   125             return (flags & ROOT_DIR) != 0;
       
   126         }
       
   127 
       
   128         public final void setIsModuleDir() {
       
   129             flags |= MODULE_DIR;
       
   130         }
       
   131 
       
   132         public final boolean isModuleDir() {
       
   133             return (flags & MODULE_DIR) != 0;
       
   134         }
       
   135 
       
   136         public final void setIsMetaInfDir() {
       
   137             flags |= METAINF_DIR;
       
   138         }
       
   139 
       
   140         public final boolean isMetaInfDir() {
       
   141             return (flags & METAINF_DIR) != 0;
       
   142         }
       
   143 
       
   144         public final void setIsTopLevelPackageDir() {
       
   145             flags |= TOPLEVEL_PKG_DIR;
       
   146         }
       
   147 
       
   148         public final boolean isTopLevelPackageDir() {
       
   149             return (flags & TOPLEVEL_PKG_DIR) != 0;
       
   150         }
       
   151 
       
   152         public final void setIsHidden() {
       
   153             flags |= HIDDEN;
       
   154         }
       
   155 
       
   156         public final boolean isHidden() {
       
   157             return (flags & HIDDEN) != 0;
       
   158         }
       
   159 
       
   160         public final boolean isVisible() {
       
   161             return !isHidden();
       
   162         }
       
   163 
       
   164         public final UTF8String getName() {
       
   165             return name;
       
   166         }
       
   167 
       
   168         public final BasicFileAttributes getFileAttributes() {
       
   169             return fileAttrs;
       
   170         }
       
   171 
       
   172         public boolean isDirectory() {
       
   173             return false;
       
   174         }
       
   175 
       
   176         public List<Node> getChildren() {
       
   177             throw new IllegalArgumentException("not a directory: " + getNameString());
       
   178         }
       
   179 
       
   180         public boolean isResource() {
       
   181             return false;
       
   182         }
       
   183 
       
   184         public ImageLocation getLocation() {
       
   185             throw new IllegalArgumentException("not a resource: " + getNameString());
       
   186         }
       
   187 
       
   188         public long size() {
       
   189             return 0L;
       
   190         }
       
   191 
       
   192         public long compressedSize() {
       
   193             return 0L;
       
   194         }
       
   195 
       
   196         public String extension() {
       
   197             return null;
       
   198         }
       
   199 
       
   200         public long contentOffset() {
       
   201             return 0L;
       
   202         }
       
   203 
       
   204         public final FileTime creationTime() {
       
   205             return fileAttrs.creationTime();
       
   206         }
       
   207 
       
   208         public final FileTime lastAccessTime() {
       
   209             return fileAttrs.lastAccessTime();
       
   210         }
       
   211 
       
   212         public final FileTime lastModifiedTime() {
       
   213             return fileAttrs.lastModifiedTime();
       
   214         }
       
   215 
       
   216         public final String getNameString() {
       
   217             return name.toString();
       
   218         }
       
   219 
       
   220         @Override
       
   221         public final String toString() {
       
   222             return getNameString();
       
   223         }
       
   224 
       
   225         @Override
       
   226         public final int hashCode() {
       
   227             return name.hashCode();
       
   228         }
       
   229 
       
   230         @Override
       
   231         public final boolean equals(Object other) {
       
   232             if (this == other) {
       
   233                 return true;
       
   234             }
       
   235 
       
   236             if (other instanceof Node) {
       
   237                 return name.equals(((Node) other).name);
       
   238             }
       
   239 
       
   240             return false;
       
   241         }
       
   242     }
       
   243 
       
   244     // directory node - directory has full path name without '/' at end.
       
   245     public static final class Directory extends Node {
       
   246         private final List<Node> children;
       
   247 
       
   248         @SuppressWarnings("LeakingThisInConstructor")
       
   249         Directory(Directory parent, UTF8String name, BasicFileAttributes fileAttrs) {
       
   250             super(name, fileAttrs);
       
   251             children = new ArrayList<>();
       
   252             if (parent != null) {
       
   253                 parent.addChild(this);
       
   254             }
       
   255         }
       
   256 
       
   257         @Override
       
   258         public boolean isDirectory() {
       
   259             return true;
       
   260         }
       
   261 
       
   262         public List<Node> getChildren() {
       
   263             return Collections.unmodifiableList(children);
       
   264         }
       
   265 
       
   266         void addChild(Node node) {
       
   267             children.add(node);
       
   268         }
       
   269 
       
   270         public void walk(Consumer<? super Node> consumer) {
       
   271             consumer.accept(this);
       
   272             for ( Node child : children ) {
       
   273                 if (child.isDirectory()) {
       
   274                     ((Directory)child).walk(consumer);
       
   275                 } else {
       
   276                     consumer.accept(child);
       
   277                 }
       
   278             }
       
   279         }
       
   280     }
       
   281 
       
   282     // "resource" is .class or any other resource (compressed/uncompressed) in a jimage.
       
   283     // full path of the resource is the "name" of the resource.
       
   284     public static class Resource extends Node {
       
   285         private final ImageLocation loc;
       
   286 
       
   287         @SuppressWarnings("LeakingThisInConstructor")
       
   288         Resource(Directory parent, ImageLocation loc, BasicFileAttributes fileAttrs) {
       
   289             this(parent, ROOT.concat(loc.getFullname()), loc, fileAttrs);
       
   290         }
       
   291 
       
   292         @SuppressWarnings("LeakingThisInConstructor")
       
   293         Resource(Directory parent, UTF8String name, ImageLocation loc, BasicFileAttributes fileAttrs) {
       
   294             super(name, fileAttrs);
       
   295             this.loc = loc;
       
   296             parent.addChild(this);
       
   297         }
       
   298 
       
   299         @Override
       
   300         public boolean isResource() {
       
   301             return true;
       
   302         }
       
   303 
       
   304         @Override
       
   305         public ImageLocation getLocation() {
       
   306             return loc;
       
   307         }
       
   308 
       
   309         @Override
       
   310         public long size() {
       
   311             return loc.getUncompressedSize();
       
   312         }
       
   313 
       
   314         @Override
       
   315         public long compressedSize() {
       
   316             return loc.getCompressedSize();
       
   317         }
       
   318 
       
   319         @Override
       
   320         public String extension() {
       
   321             return loc.getExtensionString();
       
   322         }
       
   323 
       
   324         @Override
       
   325         public long contentOffset() {
       
   326             return loc.getContentOffset();
       
   327         }
       
   328     }
       
   329 
       
   330     // directory management interface
       
   331     public Directory getRootDirectory() {
       
   332         return buildRootDirectory();
       
   333     }
       
   334 
       
   335     public Node findNode(String name) {
       
   336         return findNode(new UTF8String(name));
       
   337     }
       
   338 
       
   339     public Node findNode(byte[] name) {
       
   340         return findNode(new UTF8String(name));
       
   341     }
       
   342 
       
   343     public synchronized Node findNode(UTF8String name) {
       
   344         buildRootDirectory();
       
   345         return nodes.get(name);
       
   346     }
       
   347 
       
   348     private synchronized void clearNodes() {
       
   349         nodes.clear();
       
   350         rootDir = null;
       
   351     }
       
   352 
       
   353     /**
       
   354      * Returns the file attributes of the image file.
       
   355      */
       
   356     private BasicFileAttributes imageFileAttributes() {
       
   357         BasicFileAttributes attrs = imageFileAttributes;
       
   358         if (attrs == null) {
       
   359             try {
       
   360                 Path file = Paths.get(imagePath());
       
   361                 attrs = Files.readAttributes(file, BasicFileAttributes.class);
       
   362             } catch (IOException ioe) {
       
   363                 throw new UncheckedIOException(ioe);
       
   364             }
       
   365             imageFileAttributes = attrs;
       
   366         }
       
   367         return attrs;
       
   368     }
       
   369 
       
   370     private synchronized Directory buildRootDirectory() {
       
   371         if (rootDir != null) {
       
   372             return rootDir;
       
   373         }
       
   374 
       
   375         // FIXME no time information per resource in jimage file (yet?)
       
   376         // we use file attributes of jimage itself.
       
   377         // root directory
       
   378         rootDir = new Directory(null, ROOT, imageFileAttributes());
       
   379         rootDir.setIsRootDir();
       
   380         nodes.put(rootDir.getName(), rootDir);
       
   381 
       
   382         ImageLocation[] locs = getAllLocations(true);
       
   383         for (ImageLocation loc : locs) {
       
   384             UTF8String parent = loc.getParent();
       
   385             // directory where this location goes as child
       
   386             Directory dir;
       
   387             if (parent == null || parent.isEmpty()) {
       
   388                 // top level entry under root
       
   389                 dir = rootDir;
       
   390             } else {
       
   391                 int idx = parent.lastIndexOf('/');
       
   392                 assert idx != -1 : "invalid parent string";
       
   393                 UTF8String name = ROOT.concat(parent.substring(0, idx));
       
   394                 dir = (Directory) nodes.get(name);
       
   395                 if (dir == null) {
       
   396                     // make all parent directories (as needed)
       
   397                     dir = makeDirectories(parent);
       
   398                 }
       
   399             }
       
   400             Resource entry = new Resource(dir, loc, imageFileAttributes());
       
   401             nodes.put(entry.getName(), entry);
       
   402         }
       
   403 
       
   404         Node metaInf = nodes.get(META_INF);
       
   405         if (metaInf instanceof Directory) {
       
   406             metaInf.setIsMetaInfDir();
       
   407             ((Directory)metaInf).walk(Node::setIsHidden);
       
   408         }
       
   409 
       
   410         fillPackageModuleInfo();
       
   411 
       
   412         return rootDir;
       
   413     }
       
   414 
       
   415     private Directory newDirectory(Directory parent, UTF8String name) {
       
   416         Directory dir = new Directory(parent, name, imageFileAttributes());
       
   417         nodes.put(dir.getName(), dir);
       
   418         return dir;
       
   419     }
       
   420 
       
   421     private Directory makeDirectories(UTF8String parent) {
       
   422         assert !parent.isEmpty() : "non empty parent expected";
       
   423 
       
   424         int idx = parent.indexOf('/');
       
   425         assert idx != -1 : "invalid parent string";
       
   426         UTF8String name = ROOT.concat(parent.substring(0, idx));
       
   427         Directory top = (Directory) nodes.get(name);
       
   428         if (top == null) {
       
   429             top = newDirectory(rootDir, name);
       
   430         }
       
   431         Directory last = top;
       
   432         while ((idx = parent.indexOf('/', idx + 1)) != -1) {
       
   433             name = ROOT.concat(parent.substring(0, idx));
       
   434             Directory nextDir = (Directory) nodes.get(name);
       
   435             if (nextDir == null) {
       
   436                 nextDir = newDirectory(last, name);
       
   437             }
       
   438             last = nextDir;
       
   439         }
       
   440 
       
   441         return last;
       
   442     }
       
   443 
       
   444     private void fillPackageModuleInfo() {
       
   445         assert rootDir != null;
       
   446 
       
   447         packageMap.entrySet().stream().sorted((x, y)->x.getKey().compareTo(y.getKey())).forEach((entry) -> {
       
   448               UTF8String moduleName = new UTF8String("/" + entry.getValue());
       
   449               UTF8String fullName = moduleName.concat(new UTF8String(entry.getKey() + "/"));
       
   450               if (! nodes.containsKey(fullName)) {
       
   451                   Directory module = (Directory) nodes.get(moduleName);
       
   452                   assert module != null : "module directory missing " + moduleName;
       
   453                   module.setIsModuleDir();
       
   454 
       
   455                   // hide "packages.offsets" in module directories
       
   456                   Node packagesOffsets = nodes.get(moduleName.concat(ROOT, PACKAGES_OFFSETS));
       
   457                   if (packagesOffsets != null) {
       
   458                       packagesOffsets.setIsHidden();
       
   459                   }
       
   460 
       
   461                   // package name without front '/'
       
   462                   UTF8String pkgName = new UTF8String(entry.getKey() + "/");
       
   463                   int idx = -1;
       
   464                   Directory moduleSubDir = module;
       
   465                   while ((idx = pkgName.indexOf('/', idx + 1)) != -1) {
       
   466                       UTF8String subPkg = pkgName.substring(0, idx);
       
   467                       UTF8String moduleSubDirName = moduleName.concat(ROOT, subPkg);
       
   468                       Directory tmp = (Directory) nodes.get(moduleSubDirName);
       
   469                       if (tmp == null) {
       
   470                           moduleSubDir = newDirectory(moduleSubDir, moduleSubDirName);
       
   471                       } else {
       
   472                           moduleSubDir = tmp;
       
   473                       }
       
   474                   }
       
   475                   // copy pkgDir "resources"
       
   476                   Directory pkgDir = (Directory) nodes.get(ROOT.concat(pkgName.substring(0, pkgName.length() - 1)));
       
   477                   pkgDir.setIsTopLevelPackageDir();
       
   478                   pkgDir.walk(n -> n.setIsHidden());
       
   479                   for (Node child : pkgDir.getChildren()) {
       
   480                       if (child.isResource()) {
       
   481                           ImageLocation loc = child.getLocation();
       
   482                           BasicFileAttributes imageFileAttrs = child.getFileAttributes();
       
   483                           UTF8String rsName = moduleName.concat(child.getName());
       
   484                           Resource rs = new Resource(moduleSubDir, rsName, loc, imageFileAttrs);
       
   485                           nodes.put(rs.getName(), rs);
       
   486                       }
       
   487                   }
       
   488               }
       
   489         });
       
   490     }
       
   491 
       
   492     public byte[] getResource(Node node) throws IOException {
       
   493         if (node.isResource()) {
       
   494             return super.getResource(node.getLocation());
       
   495         }
       
   496         throw new IOException("Not a resource: " + node);
       
   497     }
       
   498 
       
   499     public byte[] getResource(Resource rs) throws IOException {
       
   500         return super.getResource(rs.getLocation());
       
   501     }
       
   502 }