1 /*
  2  * Copyright (c) 2014, 2026, 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.nio.ByteBuffer;
 29 import java.nio.ByteOrder;
 30 import java.nio.IntBuffer;
 31 import java.nio.file.Files;
 32 import java.nio.file.Path;
 33 import java.nio.file.attribute.BasicFileAttributes;
 34 import java.util.ArrayList;
 35 import java.util.Arrays;
 36 import java.util.Collections;
 37 import java.util.HashMap;
 38 import java.util.HashSet;
 39 import java.util.List;
 40 import java.util.Map;
 41 import java.util.Objects;
 42 import java.util.Set;
 43 import java.util.function.Function;
 44 import java.util.function.Supplier;
 45 import java.util.stream.Stream;
 46 
 47 /**
 48  * A view over the entries of a jimage file with a unified namespace suitable
 49  * for file system use. The jimage entries (resources, module and package
 50  * information) are mapped into a unified hierarchy of named nodes, which serve
 51  * as the underlying structure for {@code JrtFileSystem} and other utilities.
 52  *
 53  * <p>Entries in jimage are expressed as one of three {@link Node} types;
 54  * resource nodes, directory nodes and link nodes.
 55  *
 56  * <p>When remapping jimage entries, jimage location names (e.g. {@code
 57  * "/java.base/java/lang/Integer.class"}) are prefixed with {@code "/modules"}
 58  * to form the names of resource nodes. This aligns with the naming of module
 59  * entries in jimage (e.g. "/modules/java.base/java/lang"), which appear as
 60  * directory nodes in {@code ImageReader}.
 61  *
 62  * <p>Package entries (e.g. {@code "/packages/java.lang"} appear as directory
 63  * nodes containing link nodes, which resolve back to the root directory of the
 64  * module in which that package exists (e.g. {@code "/modules/java.base"}).
 65  * Unlike other nodes, the jimage file does not contain explicit entries for
 66  * link nodes, and their existence is derived only from the contents of the
 67  * parent directory.
 68  *
 69  * <p>While similar to {@code BasicImageReader}, this class is not a conceptual
 70  * subtype of it, and deliberately hides types such as {@code ImageLocation} to
 71  * give a focused API based only on nodes.
 72  *
 73  * @implNote This class needs to maintain JDK 8 source compatibility.
 74  *
 75  * It is used internally in the JDK to implement jimage/jrtfs access,
 76  * but also compiled and delivered as part of the jrtfs.jar to support access
 77  * to the jimage file provided by the shipped JDK by tools running on JDK 8.
 78  */
 79 public final class ImageReader implements AutoCloseable {
 80     private final SharedImageReader reader;
 81 
 82     private volatile boolean closed;
 83 
 84     private ImageReader(SharedImageReader reader) {
 85         this.reader = reader;
 86     }
 87 
 88     /**
 89      * Opens an image reader for a jimage file at the specified path, using the
 90      * given byte order.
 91      */
 92     public static ImageReader open(Path imagePath, ByteOrder byteOrder) throws IOException {
 93         Objects.requireNonNull(imagePath);
 94         Objects.requireNonNull(byteOrder);
 95 
 96         return SharedImageReader.open(imagePath, byteOrder);
 97     }
 98 
 99     /**
100      * Opens an image reader for a jimage file at the specified path, using the
101      * platform native byte order.
102      */
103     public static ImageReader open(Path imagePath) throws IOException {
104         return open(imagePath, ByteOrder.nativeOrder());
105     }
106 
107     @Override
108     public void close() throws IOException {
109         if (closed) {
110             throw new IOException("image file already closed");
111         }
112         reader.close(this);
113         closed = true;
114     }
115 
116     private void ensureOpen() throws IOException {
117         if (closed) {
118             throw new IOException("image file closed");
119         }
120     }
121 
122     private void requireOpen() {
123         if (closed) {
124             throw new IllegalStateException("image file closed");
125         }
126     }
127 
128     /**
129      * Finds the node with the given name.
130      *
131      * @param name a node name of the form {@code "/modules/<module>/...} or
132      *     {@code "/packages/<package>/...}.
133      * @return a node representing a resource, directory or symbolic link.
134      */
135     public Node findNode(String name) throws IOException {
136         ensureOpen();
137         return reader.findNode(name);
138     }
139 
140     /**
141      * Returns a resource node in the given module, or null if no resource of
142      * that name exists.
143      *
144      * <p>This is equivalent to:
145      * <pre>{@code
146      * findNode("/modules/" + moduleName + "/" + resourcePath)
147      * }</pre>
148      * but more performant, and returns {@code null} for directories.
149      *
150      * @param moduleName The module name of the requested resource.
151      * @param resourcePath Trailing module-relative resource path, not starting
152      *     with {@code '/'}.
153      */
154     public Node findResourceNode(String moduleName, String resourcePath)
155             throws IOException {
156         ensureOpen();
157         return reader.findResourceNode(moduleName, resourcePath);
158     }
159 
160     /**
161      * Returns whether a resource exists in the given module.
162      *
163      * <p>This is equivalent to:
164      * <pre>{@code
165      * findResourceNode(moduleName, resourcePath) != null
166      * }</pre>
167      * but more performant, and will not create or cache new nodes.
168      *
169      * @param moduleName The module name of the resource being tested for.
170      * @param resourcePath Trailing module-relative resource path, not starting
171      *     with {@code '/'}.
172      */
173     public boolean containsResource(String moduleName, String resourcePath)
174             throws IOException {
175         ensureOpen();
176         return reader.containsResource(moduleName, resourcePath);
177     }
178 
179     /**
180      * Returns a copy of the content of a resource node. The buffer returned by
181      * this method is not cached by the node, and each call returns a new array
182      * instance.
183      *
184      * @throws IOException if the content cannot be returned (including if the
185      * given node is not a resource node).
186      */
187     public byte[] getResource(Node node) throws IOException {
188         ensureOpen();
189         return reader.getResource(node);
190     }
191 
192     /**
193      * Returns the content of a resource node in a newly allocated byte buffer.
194      */
195     public ByteBuffer getResourceBuffer(Node node) {
196         requireOpen();
197         if (!node.isResource()) {
198             throw new IllegalArgumentException("Not a resource node: " + node);
199         }
200         return reader.getResourceBuffer(node.getLocation());
201     }
202 
203     private static final class SharedImageReader extends BasicImageReader {
204         private static final Map<Path, SharedImageReader> OPEN_FILES = new HashMap<>();
205         private static final String MODULES_ROOT = "/modules";
206         private static final String PACKAGES_ROOT = "/packages";
207         // There are >30,000 nodes in a complete jimage tree, and even relatively
208         // common tasks (e.g. starting up javac) load somewhere in the region of
209         // 1000 classes. Thus, an initial capacity of 2000 is a reasonable guess.
210         private static final int INITIAL_NODE_CACHE_CAPACITY = 2000;
211 
212         // List of openers for this shared image.
213         private final Set<ImageReader> openers = new HashSet<>();
214 
215         // Attributes of the jimage file. The jimage file does not contain
216         // attributes for the individual resources (yet). We use attributes
217         // of the jimage file itself (creation, modification, access times).
218         private final BasicFileAttributes imageFileAttributes;
219 
220         // Cache of all user visible nodes, guarded by synchronizing 'this' instance.
221         private final Map<String, Node> nodes;
222         // Used to classify ImageLocation instances without string comparison.
223         private final int modulesStringOffset;
224         private final int packagesStringOffset;
225 
226         private SharedImageReader(Path imagePath, ByteOrder byteOrder) throws IOException {
227             super(imagePath, byteOrder);
228             this.imageFileAttributes = Files.readAttributes(imagePath, BasicFileAttributes.class);
229             this.nodes = new HashMap<>(INITIAL_NODE_CACHE_CAPACITY);
230             // Pick stable jimage names from which to extract string offsets (we cannot
231             // use "/modules" or "/packages", since those have a module offset of zero).
232             this.modulesStringOffset = getModuleOffset("/modules/java.base");
233             this.packagesStringOffset = getModuleOffset("/packages/java.lang");
234 
235             // Node creation is very lazy, so we can just make the top-level directories
236             // now without the risk of triggering the building of lots of other nodes.
237             Directory packages = newDirectory(PACKAGES_ROOT);
238             nodes.put(packages.getName(), packages);
239             Directory modules = newDirectory(MODULES_ROOT);
240             nodes.put(modules.getName(), modules);
241 
242             Directory root = newDirectory("/");
243             root.setChildren(Arrays.asList(packages, modules));
244             nodes.put(root.getName(), root);
245         }
246 
247         /**
248          * Returns the offset of the string denoting the leading "module" segment in
249          * the given path (e.g. {@code <module>/<path>}). We can't just pass in the
250          * {@code /<module>} string here because that has a module offset of zero.
251          */
252         private int getModuleOffset(String path) {
253             ImageLocation location = findLocation(path);
254             assert location != null : "Cannot find expected jimage location: " + path;
255             int offset = location.getModuleOffset();
256             assert offset != 0 : "Invalid module offset for jimage location: " + path;
257             return offset;
258         }
259 
260         private static ImageReader open(Path imagePath, ByteOrder byteOrder) throws IOException {
261             Objects.requireNonNull(imagePath);
262             Objects.requireNonNull(byteOrder);
263 
264             synchronized (OPEN_FILES) {
265                 SharedImageReader reader = OPEN_FILES.get(imagePath);
266 
267                 if (reader == null) {
268                     // Will fail with an IOException if wrong byteOrder.
269                     reader =  new SharedImageReader(imagePath, byteOrder);
270                     OPEN_FILES.put(imagePath, reader);
271                 } else if (reader.getByteOrder() != byteOrder) {
272                     throw new IOException("\"" + reader.getName() + "\" is not an image file");
273                 }
274 
275                 ImageReader image = new ImageReader(reader);
276                 reader.openers.add(image);
277 
278                 return image;
279             }
280         }
281 
282         public void close(ImageReader image) throws IOException {
283             Objects.requireNonNull(image);
284 
285             synchronized (OPEN_FILES) {
286                 if (!openers.remove(image)) {
287                     throw new IOException("image file already closed");
288                 }
289 
290                 if (openers.isEmpty()) {
291                     close();
292                     nodes.clear();
293 
294                     if (!OPEN_FILES.remove(this.getImagePath(), this)) {
295                         throw new IOException("image file not found in open list");
296                     }
297                 }
298             }
299         }
300 
301         /**
302          * Returns a node with the given name, or null if no resource or directory of
303          * that name exists.
304          *
305          * <p>Note that there is no reentrant calling back to this method from within
306          * the node handling code.
307          *
308          * @param name an absolute, {@code /}-separated path string, prefixed with either
309          *     "/modules" or "/packages".
310          */
311         synchronized Node findNode(String name) {
312             Node node = nodes.get(name);
313             if (node == null) {
314                 // We cannot get the root paths ("/modules" or "/packages") here
315                 // because those nodes are already in the nodes cache.
316                 if (name.startsWith(MODULES_ROOT + "/")) {
317                     // This may perform two lookups, one for a directory (in
318                     // "/modules/...") and one for a non-prefixed resource
319                     // (with "/modules" removed).
320                     node = buildModulesNode(name);
321                 } else if (name.startsWith(PACKAGES_ROOT + "/")) {
322                     node = buildPackagesNode(name);
323                 }
324                 if (node != null) {
325                     nodes.put(node.getName(), node);
326                 }
327             } else if (!node.isCompleted()) {
328                 // Only directories can be incomplete.
329                 assert node instanceof Directory : "Invalid incomplete node: " + node;
330                 completeDirectory((Directory) node);
331             }
332             assert node == null || node.isCompleted() : "Incomplete node: " + node;
333             return node;
334         }
335 
336         /**
337          * Returns a resource node in the given module, or null if no resource of
338          * that name exists.
339          *
340          * <p>Note that there is no reentrant calling back to this method from within
341          * the node handling code.
342          */
343         Node findResourceNode(String moduleName, String resourcePath) {
344             // Unlike findNode(), this method makes only one lookup in the
345             // underlying jimage, but can only reliably return resource nodes.
346             if (moduleName.indexOf('/') >= 0) {
347                 throw new IllegalArgumentException("invalid module name: " + moduleName);
348             }
349             String nodeName = MODULES_ROOT + "/" + moduleName + "/" + resourcePath;
350             // Synchronize as tightly as possible to reduce locking contention.
351             synchronized (this) {
352                 Node node = nodes.get(nodeName);
353                 if (node == null) {
354                     ImageLocation loc = findLocation(moduleName, resourcePath);
355                     if (loc != null && isResource(loc)) {
356                         node = newResource(nodeName, loc);
357                         nodes.put(node.getName(), node);
358                     }
359                     return node;
360                 } else {
361                     return node.isResource() ? node : null;
362                 }
363             }
364         }
365 
366         /**
367          * Returns whether a resource exists in the given module.
368          *
369          * <p>This method is expected to be called frequently for resources
370          * which do not exist in the given module (e.g. as part of classpath
371          * search). As such, it skips checking the nodes cache and only checks
372          * for an entry in the jimage file, as this is faster if the resource
373          * is not present. This also means it doesn't need synchronization.
374          */
375         boolean containsResource(String moduleName, String resourcePath) {
376             if (moduleName.indexOf('/') >= 0) {
377                 throw new IllegalArgumentException("invalid module name: " + moduleName);
378             }
379             // If the given module name is 'modules', then 'isResource()'
380             // returns false to prevent false positives.
381             ImageLocation loc = findLocation(moduleName, resourcePath);
382             return loc != null && isResource(loc);
383         }
384 
385         /**
386          * Builds a node in the "/modules/..." namespace.
387          *
388          * <p>Called by {@link #findNode(String)} if a {@code /modules/...} node
389          * is not present in the cache.
390          */
391         private Node buildModulesNode(String name) {
392             assert name.startsWith(MODULES_ROOT + "/") : "Invalid module node name: " + name;
393             // Returns null for non-directory resources, since the jimage name does not
394             // start with "/modules" (e.g. "/java.base/java/lang/Object.class").
395             ImageLocation loc = findLocation(name);
396             if (loc != null) {
397                 assert name.equals(loc.getFullName()) : "Mismatched location for directory: " + name;
398                 assert isModulesSubdirectory(loc) : "Invalid modules directory: " + name;
399                 return completeModuleDirectory(newDirectory(name), loc);
400             }
401             // Now try the non-prefixed resource name, but be careful to avoid false
402             // positives for names like "/modules/modules/xxx" which could return a
403             // location of a directory entry.
404             loc = findLocation(name.substring(MODULES_ROOT.length()));
405             return loc != null && isResource(loc) ? newResource(name, loc) : null;
406         }
407 
408         /**
409          * Builds a node in the "/packages/..." namespace.
410          *
411          * <p>Called by {@link #findNode(String)} if a {@code /packages/...} node
412          * is not present in the cache.
413          */
414         private Node buildPackagesNode(String name) {
415             // There are only locations for the root "/packages" or "/packages/xxx"
416             // directories, but not the symbolic links below them (the links can be
417             // entirely derived from the name information in the parent directory).
418             // However, unlike resources this means that we do not have a constant
419             // time lookup for link nodes when creating them.
420             int packageStart = PACKAGES_ROOT.length() + 1;
421             int packageEnd = name.indexOf('/', packageStart);
422             if (packageEnd == -1) {
423                 ImageLocation loc = findLocation(name);
424                 return loc != null ? completePackageDirectory(newDirectory(name), loc) : null;
425             } else {
426                 // We cannot assume that the parent directory exists for a link node, since
427                 // the given name is untrusted and could reference a non-existent link.
428                 // However, if the parent directory is present, we can conclude that the
429                 // given name was not a valid link (or else it would already be cached).
430                 String dirName = name.substring(0, packageEnd);
431                 if (!nodes.containsKey(dirName)) {
432                     ImageLocation loc = findLocation(dirName);
433                     // If the parent location doesn't exist, the link node cannot exist.
434                     if (loc != null) {
435                         nodes.put(dirName, completePackageDirectory(newDirectory(dirName), loc));
436                         // When the parent is created its child nodes are created and cached,
437                         // but this can still return null if given name wasn't a valid link.
438                         return nodes.get(name);
439                     }
440                 }
441             }
442             return null;
443         }
444 
445         /** Completes a directory by ensuring its child list is populated correctly. */
446         private void completeDirectory(Directory dir) {
447             String name = dir.getName();
448             // Since the node exists, we can assert that its name starts with
449             // either "/modules" or "/packages", making differentiation easy.
450             // It also means that the name is valid, so it must yield a location.
451             assert name.startsWith(MODULES_ROOT) || name.startsWith(PACKAGES_ROOT);
452             ImageLocation loc = findLocation(name);
453             assert loc != null && name.equals(loc.getFullName()) : "Invalid location for name: " + name;
454             // We cannot use 'isXxxSubdirectory()' methods here since we could
455             // be given a top-level directory (for which that test doesn't work).
456             // The string MUST start "/modules" or "/packages" here.
457             if (name.charAt(1) == 'm') {
458                 completeModuleDirectory(dir, loc);
459             } else {
460                 completePackageDirectory(dir, loc);
461             }
462             assert dir.isCompleted() : "Directory must be complete by now: " + dir;
463         }
464 
465         /**
466          * Completes a modules directory by setting the list of child nodes.
467          *
468          * <p>The given directory can be the top level {@code /modules} directory,
469          * so it is NOT safe to use {@code isModulesSubdirectory(loc)} here.
470          */
471         private Directory completeModuleDirectory(Directory dir, ImageLocation loc) {
472             assert dir.getName().equals(loc.getFullName()) : "Mismatched location for directory: " + dir;
473             List<Node> children = createChildNodes(loc, childLoc -> {
474                 if (isModulesSubdirectory(childLoc)) {
475                     return nodes.computeIfAbsent(childLoc.getFullName(), this::newDirectory);
476                 } else {
477                     // Add "/modules" prefix to image location paths to get node names.
478                     String resourceName = childLoc.getFullName(true);
479                     return nodes.computeIfAbsent(resourceName, n -> newResource(n, childLoc));
480                 }
481             });
482             dir.setChildren(children);
483             return dir;
484         }
485 
486         /**
487          * Completes a package directory by setting the list of child nodes.
488          *
489          * <p>The given directory can be the top level {@code /packages} directory,
490          * so it is NOT safe to use {@code isPackagesSubdirectory(loc)} here.
491          */
492         private Directory completePackageDirectory(Directory dir, ImageLocation loc) {
493             assert dir.getName().equals(loc.getFullName()) : "Mismatched location for directory: " + dir;
494             // The only directories in the "/packages" namespace are "/packages" or
495             // "/packages/<package>". However, unlike "/modules" directories, the
496             // location offsets mean different things.
497             List<Node> children;
498             if (dir.getName().equals(PACKAGES_ROOT)) {
499                 // Top-level directory just contains a list of subdirectories.
500                 children = createChildNodes(loc, c -> nodes.computeIfAbsent(c.getFullName(), this::newDirectory));
501             } else {
502                 // A package directory's content is array of offset PAIRS in the
503                 // Strings table, but we only need the 2nd value of each pair.
504                 IntBuffer intBuffer = getOffsetBuffer(loc);
505                 int offsetCount = intBuffer.capacity();
506                 assert (offsetCount & 0x1) == 0 : "Offset count must be even: " + offsetCount;
507                 children = new ArrayList<>(offsetCount / 2);
508                 // Iterate the 2nd offset in each pair (odd indices).
509                 for (int i = 1; i < offsetCount; i += 2) {
510                     String moduleName = getString(intBuffer.get(i));
511                     children.add(nodes.computeIfAbsent(
512                             dir.getName() + "/" + moduleName,
513                             n -> newLinkNode(n, MODULES_ROOT + "/" + moduleName)));
514                 }
515             }
516             // This only happens once and "completes" the directory.
517             dir.setChildren(children);
518             return dir;
519         }
520 
521         /**
522          * Creates the list of child nodes for a {@code Directory} based on a given
523          *
524          * <p>Note: This cannot be used for package subdirectories as they have
525          * child offsets stored differently to other directories.
526          */
527         private List<Node> createChildNodes(ImageLocation loc, Function<ImageLocation, Node> newChildFn) {
528             IntBuffer offsets = getOffsetBuffer(loc);
529             int childCount = offsets.capacity();
530             List<Node> children = new ArrayList<>(childCount);
531             for (int i = 0; i < childCount; i++) {
532                 children.add(newChildFn.apply(getLocation(offsets.get(i))));
533             }
534             return children;
535         }
536 
537         /** Helper to extract the integer offset buffer from a directory location. */
538         private IntBuffer getOffsetBuffer(ImageLocation dir) {
539             assert !isResource(dir) : "Not a directory: " + dir.getFullName();
540             byte[] offsets = getResource(dir);
541             ByteBuffer buffer = ByteBuffer.wrap(offsets);
542             buffer.order(getByteOrder());
543             return buffer.asIntBuffer();
544         }
545 
546         /**
547          * Efficiently determines if an image location is a resource.
548          *
549          * <p>A resource must have a valid module associated with it, so its
550          * module offset must be non-zero, and not equal to the offsets for
551          * "/modules/..." or "/packages/..." entries.
552          */
553         private boolean isResource(ImageLocation loc) {
554             int moduleOffset = loc.getModuleOffset();
555             return moduleOffset != 0
556                     && moduleOffset != modulesStringOffset
557                     && moduleOffset != packagesStringOffset;
558         }
559 
560         /**
561          * Determines if an image location is a directory in the {@code /modules}
562          * namespace (if so, the location name is the node name).
563          *
564          * <p>In jimage, every {@code ImageLocation} under {@code /modules/} is a
565          * directory and has the same value for {@code getModule()}, and {@code
566          * getModuleOffset()}.
567          */
568         private boolean isModulesSubdirectory(ImageLocation loc) {
569             return loc.getModuleOffset() == modulesStringOffset;
570         }
571 
572         /**
573          * Creates an "incomplete" directory node with no child nodes set.
574          * Directories need to be "completed" before they are returned by
575          * {@link #findNode(String)}.
576          */
577         private Directory newDirectory(String name) {
578             return new Directory(name, imageFileAttributes);
579         }
580 
581         /**
582          * Creates a new resource from an image location. This is the only case
583          * where the image location name does not match the requested node name.
584          * In image files, resource locations are NOT prefixed by {@code /modules}.
585          */
586         private Resource newResource(String name, ImageLocation loc) {
587             assert name.equals(loc.getFullName(true)) : "Mismatched location for resource: " + name;
588             return new Resource(name, loc, imageFileAttributes);
589         }
590 
591         /**
592          * Creates a new link node pointing at the given target name.
593          *
594          * <p>Note that target node is resolved each time {@code resolve()} is called,
595          * so if a link node is retained after its reader is closed, it will fail.
596          */
597         private LinkNode newLinkNode(String name, String targetName) {
598             return new LinkNode(name, () -> findNode(targetName), imageFileAttributes);
599         }
600 
601         /** Returns the content of a resource node. */
602         private byte[] getResource(Node node) throws IOException {
603             // We could have been given a non-resource node here.
604             if (node.isResource()) {
605                 return super.getResource(node.getLocation());
606             }
607             throw new IOException("Not a resource: " + node);
608         }
609     }
610 
611     /**
612      * A directory, resource or symbolic link.
613      *
614      * <h3 id="node_equality">Node Equality</h3>
615      *
616      * Nodes are identified solely by their name, and it is not valid to attempt
617      * to compare nodes from different reader instances. Different readers may
618      * produce nodes with the same names, but different contents.
619      *
620      * <p>Furthermore, since a {@link ImageReader} provides "perfect" caching of
621      * nodes, equality of nodes from the same reader is equivalent to instance
622      * identity.
623      */
624     public abstract static class Node {
625         private final String name;
626         private final BasicFileAttributes fileAttrs;
627 
628         /**
629          * Creates an abstract {@code Node}, which is either a resource, directory
630          * or symbolic link.
631          *
632          * <p>This constructor is only non-private so it can be used by the
633          * {@code ExplodedImage} class, and must not be used otherwise.
634          */
635         protected Node(String name, BasicFileAttributes fileAttrs) {
636             this.name = Objects.requireNonNull(name);
637             this.fileAttrs = Objects.requireNonNull(fileAttrs);
638         }
639 
640         // A node is completed when all its direct children have been built.
641         // As such, non-directory nodes are always complete.
642         boolean isCompleted() {
643             return true;
644         }
645 
646         // Only resources can return a location.
647         ImageLocation getLocation() {
648             throw new IllegalStateException("not a resource: " + getName());
649         }
650 
651         /**
652          * Returns the name of this node (e.g. {@code
653          * "/modules/java.base/java/lang/Object.class"} or {@code
654          * "/packages/java.lang"}).
655          *
656          * <p>Note that for resource nodes this is NOT the underlying jimage
657          * resource name (it is prefixed with {@code "/modules"}).
658          */
659         public final String getName() {
660             return name;
661         }
662 
663         /**
664          * Returns file attributes for this node. The value returned may be the
665          * same for all nodes, and should not be relied upon for accuracy.
666          */
667         public final BasicFileAttributes getFileAttributes() {
668             return fileAttrs;
669         }
670 
671         /**
672          * Resolves a symbolic link to its target node. If this code is not a
673          * symbolic link, then it resolves to itself.
674          */
675         public final Node resolveLink() {
676             return resolveLink(false);
677         }
678 
679         /**
680          * Resolves a symbolic link to its target node. If this code is not a
681          * symbolic link, then it resolves to itself.
682          */
683         public Node resolveLink(boolean recursive) {
684             return this;
685         }
686 
687         /** Returns whether this node is a symbolic link. */
688         public boolean isLink() {
689             return false;
690         }
691 
692         /**
693          * Returns whether this node is a directory. Directory nodes can have
694          * {@link #getChildNames()} invoked to get the fully qualified names
695          * of any child nodes.
696          */
697         public boolean isDirectory() {
698             return false;
699         }
700 
701         /**
702          * Returns whether this node is a resource. Resource nodes can have
703          * their contents obtained via {@link ImageReader#getResource(Node)}
704          * or {@link ImageReader#getResourceBuffer(Node)}.
705          */
706         public boolean isResource() {
707             return false;
708         }
709 
710         /**
711          * Returns the fully qualified names of any child nodes for a directory.
712          *
713          * <p>By default, this method throws {@link IllegalStateException} and
714          * is overridden for directories.
715          */
716         public Stream<String> getChildNames() {
717             throw new IllegalStateException("not a directory: " + getName());
718         }
719 
720         /**
721          * Returns the uncompressed size of this node's content. If this node is
722          * not a resource, this method returns zero.
723          */
724         public long size() {
725             return 0L;
726         }
727 
728         /**
729          * Returns the compressed size of this node's content. If this node is
730          * not a resource, this method returns zero.
731          */
732         public long compressedSize() {
733             return 0L;
734         }
735 
736         /**
737          * Returns the extension string of a resource node. If this node is not
738          * a resource, this method returns null.
739          */
740         public String extension() {
741             return null;
742         }
743 
744         @Override
745         public final String toString() {
746             return getName();
747         }
748 
749         /** See <a href="#node_equality">Node Equality</a>. */
750         @Override
751         public final int hashCode() {
752             return name.hashCode();
753         }
754 
755         /** See <a href="#node_equality">Node Equality</a>. */
756         @Override
757         public final boolean equals(Object other) {
758             if (this == other) {
759                 return true;
760             }
761 
762             if (other instanceof Node) {
763                 return name.equals(((Node) other).name);
764             }
765 
766             return false;
767         }
768     }
769 
770     /**
771      * Directory node (referenced from a full path, without a trailing '/').
772      *
773      * <p>Directory nodes have two distinct states:
774      * <ul>
775      *     <li>Incomplete: The child list has not been set.
776      *     <li>Complete: The child list has been set.
777      * </ul>
778      *
779      * <p>When a directory node is returned by {@link ImageReader#findNode(String)}
780      * it is always complete, but this DOES NOT mean that its child nodes are
781      * complete yet.
782      *
783      * <p>To avoid users being able to access incomplete child nodes, the
784      * {@code Node} API offers only a way to obtain child node names, forcing
785      * callers to invoke {@code findNode()} if they need to access the child
786      * node itself.
787      *
788      * <p>This approach allows directories to be implemented lazily with respect
789      * to child nodes, while retaining efficiency when child nodes are accessed
790      * (since any incomplete nodes will be created and placed in the node cache
791      * when the parent was first returned to the user).
792      */
793     private static final class Directory extends Node {
794         // Monotonic reference, will be set to the unmodifiable child list exactly once.
795         private List<Node> children = null;
796 
797         private Directory(String name, BasicFileAttributes fileAttrs) {
798             super(name, fileAttrs);
799         }
800 
801         @Override
802         boolean isCompleted() {
803             return children != null;
804         }
805 
806         @Override
807         public boolean isDirectory() {
808             return true;
809         }
810 
811         @Override
812         public Stream<String> getChildNames() {
813             if (children != null) {
814                 return children.stream().map(Node::getName);
815             }
816             throw new IllegalStateException("Cannot get child nodes of an incomplete directory: " + getName());
817         }
818 
819         private void setChildren(List<Node> children) {
820             assert this.children == null : this + ": Cannot set child nodes twice!";
821             this.children = Collections.unmodifiableList(children);
822         }
823     }
824     /**
825      * Resource node (e.g. a ".class" entry, or any other data resource).
826      *
827      * <p>Resources are leaf nodes referencing an underlying image location. They
828      * are lightweight, and do not cache their contents.
829      *
830      * <p>Unlike directories (where the node name matches the jimage path for the
831      * corresponding {@code ImageLocation}), resource node names are NOT the same
832      * as the corresponding jimage path. The difference is that node names for
833      * resources are prefixed with "/modules", which is missing from the
834      * equivalent jimage path.
835      */
836     private static class Resource extends Node {
837         private final ImageLocation loc;
838 
839         private Resource(String name, ImageLocation loc, BasicFileAttributes fileAttrs) {
840             super(name, fileAttrs);
841             this.loc = loc;
842         }
843 
844         @Override
845         ImageLocation getLocation() {
846             return loc;
847         }
848 
849         @Override
850         public boolean isResource() {
851             return true;
852         }
853 
854         @Override
855         public long size() {
856             return loc.getUncompressedSize();
857         }
858 
859         @Override
860         public long compressedSize() {
861             return loc.getCompressedSize();
862         }
863 
864         @Override
865         public String extension() {
866             return loc.getExtension();
867         }
868     }
869 
870     /**
871      * Link node (a symbolic link to a top-level modules directory).
872      *
873      * <p>Link nodes resolve their target by invoking a given supplier, and do
874      * not cache the result. Since nodes are cached by the {@code ImageReader},
875      * this means that only the first call to {@link #resolveLink(boolean)}
876      * could do any significant work.
877      */
878     private static class LinkNode extends Node {
879         private final Supplier<Node> link;
880 
881         private LinkNode(String name, Supplier<Node> link, BasicFileAttributes fileAttrs) {
882             super(name, fileAttrs);
883             this.link = link;
884         }
885 
886         @Override
887         public Node resolveLink(boolean recursive) {
888             // No need to use or propagate the recursive flag, since the target
889             // cannot possibly be a link node (links only point to directories).
890             return link.get();
891         }
892 
893         @Override
894         public boolean isLink() {
895             return true;
896         }
897     }
898 }