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