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 IOException("The image file \"" + name + "\" is not " +
200 "the correct version. Major: " + result.getMajorVersion() +
201 ". Minor: " + result.getMinorVersion());
202 }
203
204 return result;
205 }
206
207 private static ByteBuffer slice(ByteBuffer buffer, int position, int capacity) {
208 // Note that this is the only limit and position manipulation of
209 // BasicImageReader private ByteBuffers. The synchronize could be avoided
210 // by cloning the buffer to make a local copy, but at the cost of creating
211 // a new object.
212 synchronized(buffer) {
213 buffer.limit(position + capacity);
214 buffer.position(position);
215 return buffer.slice();
216 }
217 }
218
219 private IntBuffer intBuffer(ByteBuffer buffer, int offset, int size) {
220 return slice(buffer, offset, size).order(byteOrder).asIntBuffer();
221 }
222
223 public String getName() {
224 return name;
225 }
226
227 public ByteOrder getByteOrder() {
228 return byteOrder;
229 }
230
231 public Path getImagePath() {
232 return imagePath;
233 }
234
235 @Override
236 public void close() throws IOException {
237 if (channel != null) {
238 channel.close();
239 }
240 }
241
242 public ImageStringsReader getStrings() {
243 return stringsReader;
244 }
245
246 public ImageLocation findLocation(String module, String name) {
247 int index = getLocationIndex(module, name);
248 if (index < 0) {
249 return null;
250 }
251 long[] attributes = getAttributes(offsets.get(index));
252 if (!ImageLocation.verify(module, name, attributes, stringsReader)) {
253 return null;
254 }
255 return new ImageLocation(attributes, stringsReader);
256 }
257
258 public ImageLocation findLocation(String name) {
259 int index = getLocationIndex(name);
260 if (index < 0) {
261 return null;
262 }
263 long[] attributes = getAttributes(offsets.get(index));
264 if (!ImageLocation.verify(name, attributes, stringsReader)) {
265 return null;
266 }
267 return new ImageLocation(attributes, stringsReader);
268 }
269
270 public boolean verifyLocation(String module, String name) {
271 int index = getLocationIndex(module, name);
272 if (index < 0) {
273 return false;
274 }
275 int locationOffset = offsets.get(index);
276 return ImageLocation.verify(module, name, locations, locationOffset, stringsReader);
277 }
278
279 // Details of the algorithm used here can be found in
280 // jdk.tools.jlink.internal.PerfectHashBuilder.
281 public int getLocationIndex(String name) {
282 int count = header.getTableLength();
283 int index = redirect.get(ImageStringsReader.hashCode(name) % count);
284 if (index < 0) {
285 // index is twos complement of location attributes index.
286 return -index - 1;
287 } else if (index > 0) {
288 // index is hash seed needed to compute location attributes index.
289 return ImageStringsReader.hashCode(name, index) % count;
290 } else {
291 // No entry.
292 return -1;
293 }
294 }
295
296 private int getLocationIndex(String module, String name) {
297 int count = header.getTableLength();
298 int index = redirect.get(ImageStringsReader.hashCode(module, name) % count);
299 if (index < 0) {
300 // index is twos complement of location attributes index.
301 return -index - 1;
302 } else if (index > 0) {
303 // index is hash seed needed to compute location attributes index.
304 return ImageStringsReader.hashCode(module, name, index) % count;
305 } else {
306 // No entry.
307 return -1;
308 }
309 }
310
311 public String[] getEntryNames() {
312 return IntStream.range(0, offsets.capacity())
313 .map(offsets::get)
314 .filter(o -> o != 0)
315 .mapToObj(o -> ImageLocation.readFrom(this, o).getFullName())
316 .sorted()
317 .toArray(String[]::new);
318 }
319
320 ImageLocation getLocation(int offset) {
321 return ImageLocation.readFrom(this, offset);
322 }
323
324 public long[] getAttributes(int offset) {
325 if (offset < 0 || offset >= locations.limit()) {
326 throw new IndexOutOfBoundsException("offset");
327 }
328 return ImageLocation.decompress(locations, offset);
329 }
330
331 public String getString(int offset) {
332 if (offset < 0 || offset >= strings.limit()) {
333 throw new IndexOutOfBoundsException("offset");
334 }
335 return ImageStringsReader.stringFromByteBuffer(strings, offset);
336 }
337
338 public int match(int offset, String string, int stringOffset) {
339 if (offset < 0 || offset >= strings.limit()) {
340 throw new IndexOutOfBoundsException("offset");
341 }
342 return ImageStringsReader.stringFromByteBufferMatches(strings, offset, string, stringOffset);
343 }
344
345 private byte[] getBufferBytes(ByteBuffer buffer) {
346 Objects.requireNonNull(buffer);
347 byte[] bytes = new byte[buffer.limit()];
348 buffer.get(bytes);
349
350 return bytes;
351 }
352
353 private ByteBuffer readBuffer(long offset, long size) {
354 if (offset < 0 || Integer.MAX_VALUE <= offset) {
355 throw new IndexOutOfBoundsException("Bad offset: " + offset);
356 }
357 int checkedOffset = (int) offset;
358
359 if (size < 0 || Integer.MAX_VALUE <= size) {
360 throw new IllegalArgumentException("Bad size: " + size);
361 }
362 int checkedSize = (int) size;
363
364 if (MAP_ALL) {
365 ByteBuffer buffer = slice(memoryMap, checkedOffset, checkedSize);
366 buffer.order(ByteOrder.BIG_ENDIAN);
367
368 return buffer;
369 } else {
370 if (channel == null) {
371 throw new InternalError("Image file channel not open");
372 }
373 ByteBuffer buffer = ByteBuffer.allocate(checkedSize);
374 int read;
375 try {
376 read = channel.read(buffer, checkedOffset);
377 buffer.rewind();
378 } catch (IOException ex) {
379 throw new RuntimeException(ex);
380 }
381
382 if (read != checkedSize) {
383 throw new RuntimeException("Short read: " + read +
384 " instead of " + checkedSize + " bytes");
385 }
386
387 return buffer;
388 }
389 }
390
391 public byte[] getResource(String name) {
392 Objects.requireNonNull(name);
393 ImageLocation location = findLocation(name);
394
395 return location != null ? getResource(location) : null;
396 }
397
398 public byte[] getResource(ImageLocation loc) {
399 ByteBuffer buffer = getResourceBuffer(loc);
400 return buffer != null ? getBufferBytes(buffer) : null;
401 }
402
403 /**
404 * Returns the content of jimage location in a newly allocated byte buffer.
405 */
406 public ByteBuffer getResourceBuffer(ImageLocation loc) {
407 Objects.requireNonNull(loc);
408 long offset = loc.getContentOffset() + indexSize;
409 long compressedSize = loc.getCompressedSize();
410 long uncompressedSize = loc.getUncompressedSize();
411
412 if (compressedSize < 0 || Integer.MAX_VALUE < compressedSize) {
413 throw new IndexOutOfBoundsException(
414 "Bad compressed size: " + compressedSize);
415 }
416
417 if (uncompressedSize < 0 || Integer.MAX_VALUE < uncompressedSize) {
418 throw new IndexOutOfBoundsException(
419 "Bad uncompressed size: " + uncompressedSize);
420 }
421
422 if (compressedSize == 0) {
423 return readBuffer(offset, uncompressedSize);
424 } else {
425 ByteBuffer buffer = readBuffer(offset, compressedSize);
426 if (buffer != null) {
427 byte[] bytesIn = getBufferBytes(buffer);
428 byte[] bytesOut;
429
430 try {
431 bytesOut = decompressor.decompressResource(byteOrder,
432 (int strOffset) -> getString(strOffset), bytesIn);
433 } catch (IOException ex) {
434 throw new RuntimeException(ex);
435 }
436
437 return ByteBuffer.wrap(bytesOut);
438 }
439 }
440
441 return null;
442 }
443
444 public InputStream getResourceStream(ImageLocation loc) {
445 Objects.requireNonNull(loc);
446 byte[] bytes = getResource(loc);
447
448 return new ByteArrayInputStream(bytes);
449 }
450 }