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.ByteArrayInputStream;
 28 import java.io.IOException;
 29 import java.io.InputStream;
 30 import java.lang.reflect.InvocationTargetException;
 31 import java.lang.reflect.Method;
 32 import java.nio.ByteBuffer;
 33 import java.nio.ByteOrder;
 34 import java.nio.IntBuffer;
 35 import java.nio.channels.FileChannel;
 36 import java.nio.file.Path;
 37 import java.nio.file.StandardOpenOption;
 38 import java.security.AccessController;
 39 import java.security.PrivilegedAction;
 40 import java.util.NoSuchElementException;
 41 import java.util.Objects;
 42 import java.util.Random;
 43 import java.util.stream.IntStream;
 44 import java.util.stream.Stream;
 45 
 46 import jdk.internal.jimage.decompressor.Decompressor;
 47 
 48 /**
 49  * @implNote This class needs to maintain JDK 8 source compatibility.
 50  *
 51  * It is used internally in the JDK to implement jimage/jrtfs access,
 52  * but also compiled and delivered as part of the jrtfs.jar to support access
 53  * to the jimage file provided by the shipped JDK by tools running on JDK 8.
 54  */
 55 public class BasicImageReader implements AutoCloseable {
 56     @SuppressWarnings({ "removal", "suppression" })
 57     private static boolean isSystemProperty(String key, String value, String def) {
 58         // No lambdas during bootstrap
 59         return AccessController.doPrivileged(
 60             new PrivilegedAction<Boolean>() {
 61                 @Override
 62                 public Boolean run() {
 63                     return value.equals(System.getProperty(key, def));
 64                 }
 65             });
 66     }
 67 
 68     private static final boolean IS_64_BIT =
 69             isSystemProperty("sun.arch.data.model", "64", "32");
 70     private static final boolean USE_JVM_MAP =
 71             isSystemProperty("jdk.image.use.jvm.map", "true", "true");
 72     private static final boolean MAP_ALL =
 73             isSystemProperty("jdk.image.map.all", "true", IS_64_BIT ? "true" : "false");
 74 
 75     private final Path imagePath;
 76     private final ByteOrder byteOrder;
 77     private final String name;
 78     private final ByteBuffer memoryMap;
 79     private final FileChannel channel;
 80     private final ImageHeader header;
 81     private final long indexSize;
 82     private final IntBuffer redirect;
 83     private final IntBuffer offsets;
 84     private final ByteBuffer locations;
 85     private final ByteBuffer strings;
 86     private final ImageStringsReader stringsReader;
 87     private final Decompressor decompressor;
 88 
 89     @SuppressWarnings({ "removal", "this-escape", "suppression" })
 90     protected BasicImageReader(Path path, ByteOrder byteOrder)
 91             throws IOException {
 92         this.imagePath = Objects.requireNonNull(path);
 93         this.byteOrder = Objects.requireNonNull(byteOrder);
 94         this.name = this.imagePath.toString();
 95 
 96         ByteBuffer map;
 97 
 98         if (USE_JVM_MAP && BasicImageReader.class.getClassLoader() == null) {
 99             // Check to see if the jvm has opened the file using libjimage
100             // native entry when loading the image for this runtime
101             map = NativeImageBuffer.getNativeMap(name);
102          } else {
103             map = null;
104         }
105 
106         // Open the file only if no memory map yet or is 32 bit jvm
107         if (map != null && MAP_ALL) {
108             channel = null;
109         } else {
110             channel = FileChannel.open(imagePath, StandardOpenOption.READ);
111             // No lambdas during bootstrap
112             AccessController.doPrivileged(new PrivilegedAction<Void>() {
113                 @Override
114                 public Void run() {
115                     if (BasicImageReader.class.getClassLoader() == null) {
116                         try {
117                             Class<?> fileChannelImpl =
118                                 Class.forName("sun.nio.ch.FileChannelImpl");
119                             Method setUninterruptible =
120                                     fileChannelImpl.getMethod("setUninterruptible");
121                             setUninterruptible.invoke(channel);
122                         } catch (ClassNotFoundException |
123                                  NoSuchMethodException |
124                                  IllegalAccessException |
125                                  InvocationTargetException ex) {
126                             // fall thru - will only happen on JDK-8 systems where this code
127                             // is only used by tools using jrt-fs (non-critical.)
128                         }
129                     }
130 
131                     return null;
132                 }
133             });
134         }
135 
136         // If no memory map yet and 64 bit jvm then memory map entire file
137         if (MAP_ALL && map == null) {
138             map = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
139         }
140 
141         // Assume we have a memory map to read image file header
142         ByteBuffer headerBuffer = map;
143         int headerSize = ImageHeader.getHeaderSize();
144 
145         // If no memory map then read header from image file
146         if (headerBuffer == null) {
147             headerBuffer = ByteBuffer.allocateDirect(headerSize);
148             if (channel.read(headerBuffer, 0L) == headerSize) {
149                 headerBuffer.rewind();
150             } else {
151                 throw new IOException("\"" + name + "\" is not an image file");
152             }
153         } else if (headerBuffer.capacity() < headerSize) {
154             throw new IOException("\"" + name + "\" is not an image file");
155         }
156 
157         // Interpret the image file header
158         header = readHeader(intBuffer(headerBuffer, 0, headerSize));
159         indexSize = header.getIndexSize();
160 
161         // If no memory map yet then must be 32 bit jvm not previously mapped
162         if (map == null) {
163             // Just map the image index
164             map = channel.map(FileChannel.MapMode.READ_ONLY, 0, indexSize);
165         }
166 
167         memoryMap = map.asReadOnlyBuffer();
168 
169         // Interpret the image index
170         if (memoryMap.capacity() < indexSize) {
171             throw new IOException("The image file \"" + name + "\" is corrupted");
172         }
173         redirect = intBuffer(memoryMap, header.getRedirectOffset(), header.getRedirectSize());
174         offsets = intBuffer(memoryMap, header.getOffsetsOffset(), header.getOffsetsSize());
175         locations = slice(memoryMap, header.getLocationsOffset(), header.getLocationsSize());
176         strings = slice(memoryMap, header.getStringsOffset(), header.getStringsSize());
177 
178         stringsReader = new ImageStringsReader(this);
179         decompressor = new Decompressor();
180     }
181 
182     protected BasicImageReader(Path imagePath) throws IOException {
183         this(imagePath, ByteOrder.nativeOrder());
184     }
185 
186     public static BasicImageReader open(Path imagePath) throws IOException {
187         return new BasicImageReader(imagePath, ByteOrder.nativeOrder());
188     }
189 
190     public ImageHeader getHeader() {
191         return header;
192     }
193 
194     private ImageHeader readHeader(IntBuffer buffer) throws IOException {
195         ImageHeader result = ImageHeader.readFrom(buffer);
196 
197         if (result.getMagic() != ImageHeader.MAGIC) {
198             throw new IOException("\"" + name + "\" is not an image file");
199         }
200 
201         if (result.getMajorVersion() != ImageHeader.MAJOR_VERSION ||
202                 result.getMinorVersion() != ImageHeader.MINOR_VERSION) {
203             throw new ImageVersionMismatchException(
204                     name, result.getMajorVersion(), result.getMinorVersion());
205         }
206 
207         return result;
208     }
209 
210     private static ByteBuffer slice(ByteBuffer buffer, int position, int capacity) {
211         // Note that this is the only limit and position manipulation of
212         // BasicImageReader private ByteBuffers.  The synchronize could be avoided
213         // by cloning the buffer to make a local copy, but at the cost of creating
214         // a new object.
215         synchronized(buffer) {
216             buffer.limit(position + capacity);
217             buffer.position(position);
218             return buffer.slice();
219         }
220     }
221 
222     private IntBuffer intBuffer(ByteBuffer buffer, int offset, int size) {
223         return slice(buffer, offset, size).order(byteOrder).asIntBuffer();
224     }
225 
226     public String getName() {
227         return name;
228     }
229 
230     public ByteOrder getByteOrder() {
231         return byteOrder;
232     }
233 
234     public Path getImagePath() {
235         return imagePath;
236     }
237 
238     @Override
239     public void close() throws IOException {
240         if (channel != null) {
241             channel.close();
242         }
243     }
244 
245     public ImageStringsReader getStrings() {
246         return stringsReader;
247     }
248 
249     public ImageLocation findLocation(String module, String name) {
250         int index = getLocationIndex(module, name);
251         if (index < 0) {
252             return null;
253         }
254         long[] attributes = getAttributes(offsets.get(index));
255         if (!ImageLocation.verify(module, name, attributes, stringsReader)) {
256             return null;
257         }
258         return new ImageLocation(attributes, stringsReader);
259     }
260 
261     public ImageLocation findLocation(String name) {
262         int index = getLocationIndex(name);
263         if (index < 0) {
264             return null;
265         }
266         long[] attributes = getAttributes(offsets.get(index));
267         if (!ImageLocation.verify(name, attributes, stringsReader)) {
268             return null;
269         }
270         return new ImageLocation(attributes, stringsReader);
271     }
272 
273     public boolean verifyLocation(String module, String name) {
274         int index = getLocationIndex(module, name);
275         if (index < 0) {
276             return false;
277         }
278         int locationOffset = offsets.get(index);
279         return ImageLocation.verify(module, name, locations, locationOffset, stringsReader);
280     }
281 
282     // Details of the algorithm used here can be found in
283     // jdk.tools.jlink.internal.PerfectHashBuilder.
284     public int getLocationIndex(String name) {
285         int count = header.getTableLength();
286         int index = redirect.get(ImageStringsReader.hashCode(name) % count);
287         if (index < 0) {
288             // index is twos complement of location attributes index.
289             return -index - 1;
290         } else if (index > 0) {
291             // index is hash seed needed to compute location attributes index.
292             return ImageStringsReader.hashCode(name, index) % count;
293         } else {
294             // No entry.
295             return -1;
296         }
297     }
298 
299     private int getLocationIndex(String module, String name) {
300         int count = header.getTableLength();
301         int index = redirect.get(ImageStringsReader.hashCode(module, name) % count);
302         if (index < 0) {
303             // index is twos complement of location attributes index.
304             return -index - 1;
305         } else if (index > 0) {
306             // index is hash seed needed to compute location attributes index.
307             return ImageStringsReader.hashCode(module, name, index) % count;
308         } else {
309             // No entry.
310             return -1;
311         }
312     }
313 
314     public String[] getEntryNames() {
315         return IntStream.range(0, offsets.capacity())
316                 .map(offsets::get)
317                 .filter(o -> o != 0)
318                 .mapToObj(o -> ImageLocation.readFrom(this, o).getFullName())
319                 .sorted()
320                 .toArray(String[]::new);
321     }
322 
323     /**
324      * Returns the "raw" API for accessing underlying jimage resource entries.
325      *
326      * <p>This is only meaningful for use by code dealing directly with jimage
327      * files, and cannot be used to reliably lookup resources used at runtime.
328      *
329      * <p>This API remains valid until the image reader from which it was
330      * obtained is closed.
331      */
332     // Package visible for use by ImageReader.
333     ResourceEntries getResourceEntries() {
334         return new ResourceEntries() {
335             @Override
336             public Stream<String> getEntryNames(String module) {
337                 if (module.isEmpty() || module.equals("modules") || module.equals("packages")) {
338                     throw new IllegalArgumentException("Invalid module name: " + module);
339                 }
340                 return IntStream.range(0, offsets.capacity())
341                         .map(offsets::get)
342                         .filter(offset -> offset != 0)
343                         // Reusing a location instance or getting the module
344                         // offset directly would save a lot of allocations here.
345                         .mapToObj(offset -> ImageLocation.readFrom(BasicImageReader.this, offset))
346                         // Reverse lookup of module offset would be faster here.
347                         .filter(loc -> module.equals(loc.getModule()))
348                         .map(ImageLocation::getFullName);
349             }
350 
351             private ImageLocation getResourceLocation(String name) {
352                 if (!name.startsWith("/modules/") && !name.startsWith("/packages/")) {
353                     ImageLocation location = BasicImageReader.this.findLocation(name);
354                     if (location != null) {
355                         return location;
356                     }
357                 }
358                 throw new NoSuchElementException("No such resource entry: " + name);
359             }
360 
361             @Override
362             public long getSize(String name) {
363                 return getResourceLocation(name).getUncompressedSize();
364             }
365 
366             @Override
367             public byte[] getBytes(String name) {
368                 return BasicImageReader.this.getResource(getResourceLocation(name));
369             }
370         };
371     }
372 
373     ImageLocation getLocation(int offset) {
374         return ImageLocation.readFrom(this, offset);
375     }
376 
377     public long[] getAttributes(int offset) {
378         if (offset < 0 || offset >= locations.limit()) {
379             throw new IndexOutOfBoundsException("offset");
380         }
381         return ImageLocation.decompress(locations, offset);
382     }
383 
384     public String getString(int offset) {
385         if (offset < 0 || offset >= strings.limit()) {
386             throw new IndexOutOfBoundsException("offset");
387         }
388         return ImageStringsReader.stringFromByteBuffer(strings, offset);
389     }
390 
391     public int match(int offset, String string, int stringOffset) {
392         if (offset < 0 || offset >= strings.limit()) {
393             throw new IndexOutOfBoundsException("offset");
394         }
395         return ImageStringsReader.stringFromByteBufferMatches(strings, offset, string, stringOffset);
396     }
397 
398     private byte[] getBufferBytes(ByteBuffer buffer) {
399         Objects.requireNonNull(buffer);
400         byte[] bytes = new byte[buffer.limit()];
401         buffer.get(bytes);
402 
403         return bytes;
404     }
405 
406     private ByteBuffer readBuffer(long offset, long size) {
407         if (offset < 0 || Integer.MAX_VALUE <= offset) {
408             throw new IndexOutOfBoundsException("Bad offset: " + offset);
409         }
410         int checkedOffset = (int) offset;
411 
412         if (size < 0 || Integer.MAX_VALUE <= size) {
413             throw new IllegalArgumentException("Bad size: " + size);
414         }
415         int checkedSize = (int) size;
416 
417         if (MAP_ALL) {
418             ByteBuffer buffer = slice(memoryMap, checkedOffset, checkedSize);
419             buffer.order(ByteOrder.BIG_ENDIAN);
420 
421             return buffer;
422         } else {
423             if (channel == null) {
424                 throw new InternalError("Image file channel not open");
425             }
426             ByteBuffer buffer = ByteBuffer.allocate(checkedSize);
427             int read;
428             try {
429                 read = channel.read(buffer, checkedOffset);
430                 buffer.rewind();
431             } catch (IOException ex) {
432                 throw new RuntimeException(ex);
433             }
434 
435             if (read != checkedSize) {
436                 throw new RuntimeException("Short read: " + read +
437                         " instead of " + checkedSize + " bytes");
438             }
439 
440             return buffer;
441         }
442     }
443 
444     public byte[] getResource(String name) {
445         Objects.requireNonNull(name);
446         ImageLocation location = findLocation(name);
447 
448         return location != null ? getResource(location) : null;
449     }
450 
451     public byte[] getResource(ImageLocation loc) {
452         ByteBuffer buffer = getResourceBuffer(loc);
453         return buffer != null ? getBufferBytes(buffer) : null;
454     }
455 
456     /**
457      * Returns the content of jimage location in a newly allocated byte buffer.
458      */
459     public ByteBuffer getResourceBuffer(ImageLocation loc) {
460         Objects.requireNonNull(loc);
461         long offset = loc.getContentOffset() + indexSize;
462         long compressedSize = loc.getCompressedSize();
463         long uncompressedSize = loc.getUncompressedSize();
464 
465         if (compressedSize < 0 || Integer.MAX_VALUE < compressedSize) {
466             throw new IndexOutOfBoundsException(
467                 "Bad compressed size: " + compressedSize);
468         }
469 
470         if (uncompressedSize < 0 || Integer.MAX_VALUE < uncompressedSize) {
471             throw new IndexOutOfBoundsException(
472                 "Bad uncompressed size: " + uncompressedSize);
473         }
474 
475         if (compressedSize == 0) {
476             return readBuffer(offset, uncompressedSize);
477         } else {
478             ByteBuffer buffer = readBuffer(offset, compressedSize);
479             if (buffer != null) {
480                 byte[] bytesIn = getBufferBytes(buffer);
481                 byte[] bytesOut;
482 
483                 try {
484                     bytesOut = decompressor.decompressResource(byteOrder,
485                             (int strOffset) -> getString(strOffset), bytesIn);
486                 } catch (IOException ex) {
487                     throw new RuntimeException(ex);
488                 }
489 
490                 return ByteBuffer.wrap(bytesOut);
491             }
492         }
493 
494         return null;
495     }
496 
497     public InputStream getResourceStream(ImageLocation loc) {
498         Objects.requireNonNull(loc);
499         byte[] bytes = getResource(loc);
500 
501         return new ByteArrayInputStream(bytes);
502     }
503 
504     public static final class ImageVersionMismatchException extends IOException {
505         @Deprecated
506         private static final long serialVersionUID = 1L;
507         // If needed we could capture major/minor version for use by JImageTask.
508         ImageVersionMismatchException(String name, int majorVersion, int minorVersion) {
509             super("The image file \"" + name + "\" is not the correct version. " +
510                     "Major: " + majorVersion + ". Minor: " + minorVersion);
511         }
512     }
513 }