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 IOException("The image file \"" + name + "\" is not " +
204                 "the correct version. Major: " + result.getMajorVersion() +
205                 ". Minor: " + result.getMinorVersion());
206         }
207 
208         return result;
209     }
210 
211     private static ByteBuffer slice(ByteBuffer buffer, int position, int capacity) {
212         // Note that this is the only limit and position manipulation of
213         // BasicImageReader private ByteBuffers.  The synchronize could be avoided
214         // by cloning the buffer to make a local copy, but at the cost of creating
215         // a new object.
216         synchronized(buffer) {
217             buffer.limit(position + capacity);
218             buffer.position(position);
219             return buffer.slice();
220         }
221     }
222 
223     private IntBuffer intBuffer(ByteBuffer buffer, int offset, int size) {
224         return slice(buffer, offset, size).order(byteOrder).asIntBuffer();
225     }
226 
227     public String getName() {
228         return name;
229     }
230 
231     public ByteOrder getByteOrder() {
232         return byteOrder;
233     }
234 
235     public Path getImagePath() {
236         return imagePath;
237     }
238 
239     @Override
240     public void close() throws IOException {
241         if (channel != null) {
242             channel.close();
243         }
244     }
245 
246     public ImageStringsReader getStrings() {
247         return stringsReader;
248     }
249 
250     public ImageLocation findLocation(String module, String name) {
251         int index = getLocationIndex(module, name);
252         if (index < 0) {
253             return null;
254         }
255         long[] attributes = getAttributes(offsets.get(index));
256         if (!ImageLocation.verify(module, name, attributes, stringsReader)) {
257             return null;
258         }
259         return new ImageLocation(attributes, stringsReader);
260     }
261 
262     public ImageLocation findLocation(String name) {
263         int index = getLocationIndex(name);
264         if (index < 0) {
265             return null;
266         }
267         long[] attributes = getAttributes(offsets.get(index));
268         if (!ImageLocation.verify(name, attributes, stringsReader)) {
269             return null;
270         }
271         return new ImageLocation(attributes, stringsReader);
272     }
273 
274     public boolean verifyLocation(String module, String name) {
275         int index = getLocationIndex(module, name);
276         if (index < 0) {
277             return false;
278         }
279         int locationOffset = offsets.get(index);
280         return ImageLocation.verify(module, name, locations, locationOffset, stringsReader);
281     }
282 
283     // Details of the algorithm used here can be found in
284     // jdk.tools.jlink.internal.PerfectHashBuilder.
285     public int getLocationIndex(String name) {
286         int count = header.getTableLength();
287         int index = redirect.get(ImageStringsReader.hashCode(name) % count);
288         if (index < 0) {
289             // index is twos complement of location attributes index.
290             return -index - 1;
291         } else if (index > 0) {
292             // index is hash seed needed to compute location attributes index.
293             return ImageStringsReader.hashCode(name, index) % count;
294         } else {
295             // No entry.
296             return -1;
297         }
298     }
299 
300     private int getLocationIndex(String module, String name) {
301         int count = header.getTableLength();
302         int index = redirect.get(ImageStringsReader.hashCode(module, name) % count);
303         if (index < 0) {
304             // index is twos complement of location attributes index.
305             return -index - 1;
306         } else if (index > 0) {
307             // index is hash seed needed to compute location attributes index.
308             return ImageStringsReader.hashCode(module, name, index) % count;
309         } else {
310             // No entry.
311             return -1;
312         }
313     }
314 
315     public String[] getEntryNames() {
316         return IntStream.range(0, offsets.capacity())
317                 .map(offsets::get)
318                 .filter(o -> o != 0)
319                 .mapToObj(o -> ImageLocation.readFrom(this, o).getFullName())
320                 .sorted()
321                 .toArray(String[]::new);
322     }
323 
324     /**
325      * Returns the "raw" API for accessing underlying jimage resource entries.
326      *
327      * <p>This is only meaningful for use by code dealing directly with jimage
328      * files, and cannot be used to reliably lookup resources used at runtime.
329      *
330      * <p>This API remains valid until the image reader from which it was
331      * obtained is closed.
332      */
333     // Package visible for use by ImageReader.
334     ResourceEntries getResourceEntries() {
335         return new ResourceEntries() {
336             @Override
337             public Stream<String> getEntryNames(String module) {
338                 if (module.isEmpty() || module.equals("modules") || module.equals("packages")) {
339                     throw new IllegalArgumentException("Invalid module name: " + module);
340                 }
341                 return IntStream.range(0, offsets.capacity())
342                         .map(offsets::get)
343                         .filter(offset -> offset != 0)
344                         // Reusing a location instance or getting the module
345                         // offset directly would save a lot of allocations here.
346                         .mapToObj(offset -> ImageLocation.readFrom(BasicImageReader.this, offset))
347                         // Reverse lookup of module offset would be faster here.
348                         .filter(loc -> module.equals(loc.getModule()))
349                         .map(ImageLocation::getFullName);
350             }
351 
352             private ImageLocation getResourceLocation(String name) {
353                 if (!name.startsWith("/modules/") && !name.startsWith("/packages/")) {
354                     ImageLocation location = BasicImageReader.this.findLocation(name);
355                     if (location != null) {
356                         return location;
357                     }
358                 }
359                 throw new NoSuchElementException("No such resource entry: " + name);
360             }
361 
362             @Override
363             public long getSize(String name) {
364                 return getResourceLocation(name).getUncompressedSize();
365             }
366 
367             @Override
368             public byte[] getBytes(String name) {
369                 return BasicImageReader.this.getResource(getResourceLocation(name));
370             }
371         };
372     }
373 
374     ImageLocation getLocation(int offset) {
375         return ImageLocation.readFrom(this, offset);
376     }
377 
378     public long[] getAttributes(int offset) {
379         if (offset < 0 || offset >= locations.limit()) {
380             throw new IndexOutOfBoundsException("offset");
381         }
382         return ImageLocation.decompress(locations, offset);
383     }
384 
385     public String getString(int offset) {
386         if (offset < 0 || offset >= strings.limit()) {
387             throw new IndexOutOfBoundsException("offset");
388         }
389         return ImageStringsReader.stringFromByteBuffer(strings, offset);
390     }
391 
392     public int match(int offset, String string, int stringOffset) {
393         if (offset < 0 || offset >= strings.limit()) {
394             throw new IndexOutOfBoundsException("offset");
395         }
396         return ImageStringsReader.stringFromByteBufferMatches(strings, offset, string, stringOffset);
397     }
398 
399     private byte[] getBufferBytes(ByteBuffer buffer) {
400         Objects.requireNonNull(buffer);
401         byte[] bytes = new byte[buffer.limit()];
402         buffer.get(bytes);
403 
404         return bytes;
405     }
406 
407     private ByteBuffer readBuffer(long offset, long size) {
408         if (offset < 0 || Integer.MAX_VALUE <= offset) {
409             throw new IndexOutOfBoundsException("Bad offset: " + offset);
410         }
411         int checkedOffset = (int) offset;
412 
413         if (size < 0 || Integer.MAX_VALUE <= size) {
414             throw new IllegalArgumentException("Bad size: " + size);
415         }
416         int checkedSize = (int) size;
417 
418         if (MAP_ALL) {
419             ByteBuffer buffer = slice(memoryMap, checkedOffset, checkedSize);
420             buffer.order(ByteOrder.BIG_ENDIAN);
421 
422             return buffer;
423         } else {
424             if (channel == null) {
425                 throw new InternalError("Image file channel not open");
426             }
427             ByteBuffer buffer = ByteBuffer.allocate(checkedSize);
428             int read;
429             try {
430                 read = channel.read(buffer, checkedOffset);
431                 buffer.rewind();
432             } catch (IOException ex) {
433                 throw new RuntimeException(ex);
434             }
435 
436             if (read != checkedSize) {
437                 throw new RuntimeException("Short read: " + read +
438                         " instead of " + checkedSize + " bytes");
439             }
440 
441             return buffer;
442         }
443     }
444 
445     public byte[] getResource(String name) {
446         Objects.requireNonNull(name);
447         ImageLocation location = findLocation(name);
448 
449         return location != null ? getResource(location) : null;
450     }
451 
452     public byte[] getResource(ImageLocation loc) {
453         ByteBuffer buffer = getResourceBuffer(loc);
454         return buffer != null ? getBufferBytes(buffer) : null;
455     }
456 
457     /**
458      * Returns the content of jimage location in a newly allocated byte buffer.
459      */
460     public ByteBuffer getResourceBuffer(ImageLocation loc) {
461         Objects.requireNonNull(loc);
462         long offset = loc.getContentOffset() + indexSize;
463         long compressedSize = loc.getCompressedSize();
464         long uncompressedSize = loc.getUncompressedSize();
465 
466         if (compressedSize < 0 || Integer.MAX_VALUE < compressedSize) {
467             throw new IndexOutOfBoundsException(
468                 "Bad compressed size: " + compressedSize);
469         }
470 
471         if (uncompressedSize < 0 || Integer.MAX_VALUE < uncompressedSize) {
472             throw new IndexOutOfBoundsException(
473                 "Bad uncompressed size: " + uncompressedSize);
474         }
475 
476         if (compressedSize == 0) {
477             return readBuffer(offset, uncompressedSize);
478         } else {
479             ByteBuffer buffer = readBuffer(offset, compressedSize);
480             if (buffer != null) {
481                 byte[] bytesIn = getBufferBytes(buffer);
482                 byte[] bytesOut;
483 
484                 try {
485                     bytesOut = decompressor.decompressResource(byteOrder,
486                             (int strOffset) -> getString(strOffset), bytesIn);
487                 } catch (IOException ex) {
488                     throw new RuntimeException(ex);
489                 }
490 
491                 return ByteBuffer.wrap(bytesOut);
492             }
493         }
494 
495         return null;
496     }
497 
498     public InputStream getResourceStream(ImageLocation loc) {
499         Objects.requireNonNull(loc);
500         byte[] bytes = getResource(loc);
501 
502         return new ByteArrayInputStream(bytes);
503     }
504 }