1 /*
2 * Copyright (c) 2003, 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.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "cds/aotClassLocation.hpp"
26 #include "cds/aotLogging.hpp"
27 #include "cds/aotMappedHeapLoader.hpp"
28 #include "cds/aotMappedHeapWriter.hpp"
29 #include "cds/aotMetaspace.hpp"
30 #include "cds/archiveBuilder.hpp"
31 #include "cds/archiveUtils.inline.hpp"
32 #include "cds/cds_globals.hpp"
33 #include "cds/cdsConfig.hpp"
34 #include "cds/dynamicArchive.hpp"
35 #include "cds/filemap.hpp"
36 #include "cds/heapShared.inline.hpp"
37 #include "classfile/altHashing.hpp"
38 #include "classfile/classFileStream.hpp"
39 #include "classfile/classLoader.hpp"
40 #include "classfile/classLoader.inline.hpp"
41 #include "classfile/classLoaderData.inline.hpp"
42 #include "classfile/symbolTable.hpp"
43 #include "classfile/systemDictionaryShared.hpp"
44 #include "classfile/vmClasses.hpp"
45 #include "classfile/vmSymbols.hpp"
46 #include "compiler/compilerDefinitions.inline.hpp"
47 #include "jvm.h"
48 #include "logging/log.hpp"
49 #include "logging/logMessage.hpp"
50 #include "logging/logStream.hpp"
51 #include "memory/iterator.inline.hpp"
52 #include "memory/metadataFactory.hpp"
53 #include "memory/metaspaceClosure.hpp"
54 #include "memory/oopFactory.hpp"
55 #include "memory/universe.hpp"
56 #include "nmt/memTracker.hpp"
57 #include "oops/access.hpp"
58 #include "oops/compressedKlass.hpp"
59 #include "oops/compressedOops.hpp"
60 #include "oops/compressedOops.inline.hpp"
61 #include "oops/objArrayOop.hpp"
62 #include "oops/oop.inline.hpp"
63 #include "oops/trainingData.hpp"
64 #include "oops/typeArrayKlass.hpp"
65 #include "prims/jvmtiExport.hpp"
66 #include "runtime/arguments.hpp"
67 #include "runtime/globals_extension.hpp"
68 #include "runtime/java.hpp"
69 #include "runtime/javaCalls.hpp"
70 #include "runtime/mutexLocker.hpp"
71 #include "runtime/os.hpp"
72 #include "runtime/vm_version.hpp"
73 #include "utilities/align.hpp"
74 #include "utilities/bitMap.inline.hpp"
75 #include "utilities/classpathStream.hpp"
76 #include "utilities/defaultStream.hpp"
77 #include "utilities/ostream.hpp"
78 #if INCLUDE_G1GC
79 #include "gc/g1/g1CollectedHeap.hpp"
80 #include "gc/g1/g1HeapRegion.hpp"
81 #endif
82
83 #include <errno.h>
84 #include <sys/stat.h>
85
86 #ifndef O_BINARY // if defined (Win32) use binary files.
87 #define O_BINARY 0 // otherwise do nothing.
88 #endif
89
90 inline void CDSMustMatchFlags::do_print(outputStream* st, bool v) {
91 st->print("%s", v ? "true" : "false");
92 }
93
94 inline void CDSMustMatchFlags::do_print(outputStream* st, intx v) {
95 st->print("%zd", v);
96 }
97
98 inline void CDSMustMatchFlags::do_print(outputStream* st, uintx v) {
99 st->print("%zu", v);
100 }
101
102 inline void CDSMustMatchFlags::do_print(outputStream* st, double v) {
103 st->print("%f", v);
104 }
105
106 void CDSMustMatchFlags::init() {
107 assert(CDSConfig::is_dumping_archive(), "sanity");
108 _max_name_width = 0;
109
110 #define INIT_CDS_MUST_MATCH_FLAG(n) \
111 _v_##n = n; \
112 _max_name_width = MAX2(_max_name_width,strlen(#n));
113 CDS_MUST_MATCH_FLAGS_DO(INIT_CDS_MUST_MATCH_FLAG);
114 #undef INIT_CDS_MUST_MATCH_FLAG
115 }
116
117 bool CDSMustMatchFlags::runtime_check() const {
118 #define CHECK_CDS_MUST_MATCH_FLAG(n) \
119 if (_v_##n != n) { \
120 ResourceMark rm; \
121 stringStream ss; \
122 ss.print("VM option %s is different between dumptime (", #n); \
123 do_print(&ss, _v_ ## n); \
124 ss.print(") and runtime ("); \
125 do_print(&ss, n); \
126 ss.print(")"); \
127 log_info(cds)("%s", ss.as_string()); \
128 return false; \
129 }
130 CDS_MUST_MATCH_FLAGS_DO(CHECK_CDS_MUST_MATCH_FLAG);
131 #undef CHECK_CDS_MUST_MATCH_FLAG
132
133 return true;
134 }
135
136 void CDSMustMatchFlags::print_info() const {
137 LogTarget(Info, cds) lt;
138 if (lt.is_enabled()) {
139 LogStream ls(lt);
140 ls.print_cr("Recorded VM flags during dumptime:");
141 print(&ls);
142 }
143 }
144
145 void CDSMustMatchFlags::print(outputStream* st) const {
146 #define PRINT_CDS_MUST_MATCH_FLAG(n) \
147 st->print("- %-s ", #n); \
148 st->sp(int(_max_name_width - strlen(#n))); \
149 do_print(st, _v_##n); \
150 st->cr();
151 CDS_MUST_MATCH_FLAGS_DO(PRINT_CDS_MUST_MATCH_FLAG);
152 #undef PRINT_CDS_MUST_MATCH_FLAG
153 }
154
155 // Fill in the fileMapInfo structure with data about this VM instance.
156
157 // This method copies the vm version info into header_version. If the version is too
158 // long then a truncated version, which has a hash code appended to it, is copied.
159 //
160 // Using a template enables this method to verify that header_version is an array of
161 // length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and
162 // the code that reads the CDS file will both use the same size buffer. Hence, will
163 // use identical truncation. This is necessary for matching of truncated versions.
164 template <int N> static void get_header_version(char (&header_version) [N]) {
165 assert(N == JVM_IDENT_MAX, "Bad header_version size");
166
167 const char *vm_version = VM_Version::internal_vm_info_string();
168 const int version_len = (int)strlen(vm_version);
169
170 memset(header_version, 0, JVM_IDENT_MAX);
171
172 if (version_len < (JVM_IDENT_MAX-1)) {
173 strcpy(header_version, vm_version);
174
175 } else {
176 // Get the hash value. Use a static seed because the hash needs to return the same
177 // value over multiple jvm invocations.
178 uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);
179
180 // Truncate the ident, saving room for the 8 hex character hash value.
181 strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
182
183 // Append the hash code as eight hex digits.
184 os::snprintf_checked(&header_version[JVM_IDENT_MAX-9], 9, "%08x", hash);
185 }
186
187 assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
188 }
189
190 FileMapInfo::FileMapInfo(const char* full_path, bool is_static) :
191 _is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0),
192 _full_path(full_path), _base_archive_name(nullptr), _header(nullptr) {
193 if (_is_static) {
194 assert(_current_info == nullptr, "must be singleton"); // not thread safe
195 _current_info = this;
196 } else {
197 assert(_dynamic_archive_info == nullptr, "must be singleton"); // not thread safe
198 _dynamic_archive_info = this;
199 }
200 }
201
202 FileMapInfo::~FileMapInfo() {
203 if (_is_static) {
204 assert(_current_info == this, "must be singleton"); // not thread safe
205 _current_info = nullptr;
206 } else {
207 assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
208 _dynamic_archive_info = nullptr;
209 }
210
211 if (_header != nullptr) {
212 os::free(_header);
213 }
214
215 if (_file_open) {
216 ::close(_fd);
217 }
218 }
219
220 void FileMapInfo::free_current_info() {
221 assert(CDSConfig::is_dumping_final_static_archive(), "only supported in this mode");
222 assert(_current_info != nullptr, "sanity");
223 delete _current_info;
224 assert(_current_info == nullptr, "sanity"); // Side effect expected from the above "delete" operator.
225 }
226
227 void FileMapInfo::populate_header(size_t core_region_alignment) {
228 assert(_header == nullptr, "Sanity check");
229 size_t c_header_size;
230 size_t header_size;
231 size_t base_archive_name_size = 0;
232 size_t base_archive_name_offset = 0;
233 if (is_static()) {
234 c_header_size = sizeof(FileMapHeader);
235 header_size = c_header_size;
236 } else {
237 // dynamic header including base archive name for non-default base archive
238 c_header_size = sizeof(DynamicArchiveHeader);
239 header_size = c_header_size;
240
241 const char* default_base_archive_name = CDSConfig::default_archive_path();
242 const char* current_base_archive_name = CDSConfig::input_static_archive_path();
243 if (!os::same_files(current_base_archive_name, default_base_archive_name)) {
244 base_archive_name_size = strlen(current_base_archive_name) + 1;
245 header_size += base_archive_name_size;
246 base_archive_name_offset = c_header_size;
247 }
248 }
249 _header = (FileMapHeader*)os::malloc(header_size, mtInternal);
250 memset((void*)_header, 0, header_size);
251 _header->populate(this,
252 core_region_alignment,
253 header_size,
254 base_archive_name_size,
255 base_archive_name_offset);
256 }
257
258 void FileMapHeader::populate(FileMapInfo *info, size_t core_region_alignment,
259 size_t header_size, size_t base_archive_name_size,
260 size_t base_archive_name_offset) {
261 // 1. We require _generic_header._magic to be at the beginning of the file
262 // 2. FileMapHeader also assumes that _generic_header is at the beginning of the file
263 assert(offset_of(FileMapHeader, _generic_header) == 0, "must be");
264 set_header_size((unsigned int)header_size);
265 set_base_archive_name_offset((unsigned int)base_archive_name_offset);
266 set_base_archive_name_size((unsigned int)base_archive_name_size);
267 if (CDSConfig::is_dumping_dynamic_archive()) {
268 set_magic(CDS_DYNAMIC_ARCHIVE_MAGIC);
269 } else if (CDSConfig::is_dumping_preimage_static_archive()) {
270 set_magic(CDS_PREIMAGE_ARCHIVE_MAGIC);
271 } else {
272 set_magic(CDS_ARCHIVE_MAGIC);
273 }
274 set_version(CURRENT_CDS_ARCHIVE_VERSION);
275
276 if (!info->is_static() && base_archive_name_size != 0) {
277 // copy base archive name
278 copy_base_archive_name(CDSConfig::input_static_archive_path());
279 }
280 _core_region_alignment = core_region_alignment;
281 _obj_alignment = ObjectAlignmentInBytes;
282 _compact_strings = CompactStrings;
283 _compact_headers = UseCompactObjectHeaders;
284 #if INCLUDE_CDS_JAVA_HEAP
285 if (CDSConfig::is_dumping_heap()) {
286 _object_streaming_mode = HeapShared::is_writing_streaming_mode();
287 _narrow_oop_mode = AOTMappedHeapWriter::narrow_oop_mode();
288 _narrow_oop_base = AOTMappedHeapWriter::narrow_oop_base();
289 _narrow_oop_shift = AOTMappedHeapWriter::narrow_oop_shift();
290 }
291 #endif
292 _compressed_oops = UseCompressedOops;
293 _narrow_klass_pointer_bits = CompressedKlassPointers::narrow_klass_pointer_bits();
294 _narrow_klass_shift = ArchiveBuilder::precomputed_narrow_klass_shift();
295
296 // Which JIT compier is used
297 _compiler_type = (u1)CompilerConfig::compiler_type();
298 _type_profile_level = TypeProfileLevel;
299 _type_profile_args_limit = TypeProfileArgsLimit;
300 _type_profile_parms_limit = TypeProfileParmsLimit;
301 _type_profile_width = TypeProfileWidth;
302 _bci_profile_width = BciProfileWidth;
303 _profile_traps = ProfileTraps;
304 _type_profile_casts = TypeProfileCasts;
305 _spec_trap_limit_extra_entries = SpecTrapLimitExtraEntries;
306 _max_heap_size = MaxHeapSize;
307 _use_optimized_module_handling = CDSConfig::is_using_optimized_module_handling();
308 _has_aot_linked_classes = CDSConfig::is_dumping_aot_linked_classes();
309 _has_full_module_graph = CDSConfig::is_dumping_full_module_graph();
310 _has_valhalla_patched_classes = Arguments::is_valhalla_enabled();
311
312 // The following fields are for sanity checks for whether this archive
313 // will function correctly with this JVM and the bootclasspath it's
314 // invoked with.
315
316 // JVM version string ... changes on each build.
317 get_header_version(_jvm_ident);
318
319 _verify_local = BytecodeVerificationLocal;
320 _verify_remote = BytecodeVerificationRemote;
321 _has_platform_or_app_classes = AOTClassLocationConfig::dumptime()->has_platform_or_app_classes();
322 _requested_base_address = (char*)SharedBaseAddress;
323 _mapped_base_address = (char*)SharedBaseAddress;
324 _must_match.init();
325 }
326
327 void FileMapHeader::copy_base_archive_name(const char* archive) {
328 assert(base_archive_name_size() != 0, "_base_archive_name_size not set");
329 assert(base_archive_name_offset() != 0, "_base_archive_name_offset not set");
330 assert(header_size() > sizeof(*this), "_base_archive_name_size not included in header size?");
331 memcpy((char*)this + base_archive_name_offset(), archive, base_archive_name_size());
332 }
333
334 void FileMapHeader::print(outputStream* st) {
335 ResourceMark rm;
336
337 st->print_cr("- magic: 0x%08x", magic());
338 st->print_cr("- crc: 0x%08x", crc());
339 st->print_cr("- version: 0x%x", version());
340 st->print_cr("- header_size: " UINT32_FORMAT, header_size());
341 st->print_cr("- base_archive_name_offset: " UINT32_FORMAT, base_archive_name_offset());
342 st->print_cr("- base_archive_name_size: " UINT32_FORMAT, base_archive_name_size());
343
344 for (int i = 0; i < NUM_CDS_REGIONS; i++) {
345 FileMapRegion* r = region_at(i);
346 r->print(st, i);
347 }
348 st->print_cr("============ end regions ======== ");
349
350 st->print_cr("- core_region_alignment: %zu", _core_region_alignment);
351 st->print_cr("- obj_alignment: %d", _obj_alignment);
352 st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));
353 st->print_cr("- narrow_oop_shift %d", _narrow_oop_shift);
354 st->print_cr("- compact_strings: %d", _compact_strings);
355 st->print_cr("- compact_headers: %d", _compact_headers);
356 st->print_cr("- max_heap_size: %zu", _max_heap_size);
357 st->print_cr("- narrow_oop_mode: %d", _narrow_oop_mode);
358 st->print_cr("- compressed_oops: %d", _compressed_oops);
359 st->print_cr("- narrow_klass_pointer_bits: %d", _narrow_klass_pointer_bits);
360 st->print_cr("- narrow_klass_shift: %d", _narrow_klass_shift);
361 st->print_cr("- cloned_vtables: %u", cast_to_u4(_cloned_vtables));
362 st->print_cr("- early_serialized_data: %u", cast_to_u4(_early_serialized_data));
363 st->print_cr("- serialized_data: %u", cast_to_u4(_serialized_data));
364 st->print_cr("- jvm_ident: %s", _jvm_ident);
365 st->print_cr("- class_location_config: %d", cast_to_u4(_class_location_config));
366 st->print_cr("- verify_local: %d", _verify_local);
367 st->print_cr("- verify_remote: %d", _verify_remote);
368 st->print_cr("- has_platform_or_app_classes: %d", _has_platform_or_app_classes);
369 st->print_cr("- requested_base_address: " INTPTR_FORMAT, p2i(_requested_base_address));
370 st->print_cr("- mapped_base_address: " INTPTR_FORMAT, p2i(_mapped_base_address));
371
372 st->print_cr("- object_streaming_mode: %d", _object_streaming_mode);
373 st->print_cr("- mapped_heap_header");
374 st->print_cr(" - root_segments");
375 st->print_cr(" - roots_count: %d", _mapped_heap_header.root_segments().roots_count());
376 st->print_cr(" - base_offset: 0x%zx", _mapped_heap_header.root_segments().base_offset());
377 st->print_cr(" - count: %zu", _mapped_heap_header.root_segments().count());
378 st->print_cr(" - max_size_elems: %d", _mapped_heap_header.root_segments().max_size_in_elems());
379 st->print_cr(" - max_size_bytes: %zu", _mapped_heap_header.root_segments().max_size_in_bytes());
380 st->print_cr(" - oopmap_start_pos: %zu", _mapped_heap_header.oopmap_start_pos());
381 st->print_cr(" - oopmap_ptrmap_pos: %zu", _mapped_heap_header.ptrmap_start_pos());
382 st->print_cr("- streamed_heap_header");
383 st->print_cr(" - forwarding_offset: %zu", _streamed_heap_header.forwarding_offset());
384 st->print_cr(" - roots_offset: %zu", _streamed_heap_header.roots_offset());
385 st->print_cr(" - num_roots: %zu", _streamed_heap_header.num_roots());
386 st->print_cr(" - root_highest_object_index_table_offset: %zu", _streamed_heap_header.root_highest_object_index_table_offset());
387 st->print_cr(" - num_archived_objects: %zu", _streamed_heap_header.num_archived_objects());
388
389 st->print_cr("- _rw_ptrmap_start_pos: %zu", _rw_ptrmap_start_pos);
390 st->print_cr("- _ro_ptrmap_start_pos: %zu", _ro_ptrmap_start_pos);
391 st->print_cr("- use_optimized_module_handling: %d", _use_optimized_module_handling);
392 st->print_cr("- has_full_module_graph %d", _has_full_module_graph);
393 st->print_cr("- has_valhalla_patched_classes %d", _has_valhalla_patched_classes);
394 _must_match.print(st);
395 st->print_cr("- has_aot_linked_classes %d", _has_aot_linked_classes);
396 }
397
398 bool FileMapInfo::validate_class_location() {
399 assert(CDSConfig::is_using_archive(), "runtime only");
400
401 AOTClassLocationConfig* config = header()->class_location_config();
402 bool has_extra_module_paths = false;
403 if (!config->validate(full_path(), header()->has_aot_linked_classes(), &has_extra_module_paths)) {
404 if (PrintSharedArchiveAndExit) {
405 AOTMetaspace::set_archive_loading_failed();
406 return true;
407 } else {
408 return false;
409 }
410 }
411
412 if (header()->has_full_module_graph() && has_extra_module_paths) {
413 CDSConfig::stop_using_optimized_module_handling();
414 AOTMetaspace::report_loading_error("optimized module handling: disabled because extra module path(s) are specified");
415 }
416
417 if (CDSConfig::is_dumping_dynamic_archive()) {
418 // Only support dynamic dumping with the usage of the default CDS archive
419 // or a simple base archive.
420 // If the base layer archive contains additional path component besides
421 // the runtime image and the -cp, dynamic dumping is disabled.
422 if (config->num_boot_classpaths() > 0) {
423 CDSConfig::disable_dumping_dynamic_archive();
424 aot_log_warning(aot)(
425 "Dynamic archiving is disabled because base layer archive has appended boot classpath");
426 }
427 if (config->num_module_paths() > 0) {
428 if (has_extra_module_paths) {
429 CDSConfig::disable_dumping_dynamic_archive();
430 aot_log_warning(aot)(
431 "Dynamic archiving is disabled because base layer archive has a different module path");
432 }
433 }
434 }
435
436 #if INCLUDE_JVMTI
437 if (_classpath_entries_for_jvmti != nullptr) {
438 os::free(_classpath_entries_for_jvmti);
439 }
440 size_t sz = sizeof(ClassPathEntry*) * AOTClassLocationConfig::runtime()->length();
441 _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
442 memset((void*)_classpath_entries_for_jvmti, 0, sz);
443 #endif
444
445 return true;
446 }
447
448 // A utility class for reading/validating the GenericCDSFileMapHeader portion of
449 // a CDS archive's header. The file header of all CDS archives with versions from
450 // CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION (12) are guaranteed to always start
451 // with GenericCDSFileMapHeader. This makes it possible to read important information
452 // from a CDS archive created by a different version of HotSpot, so that we can
453 // automatically regenerate the archive as necessary (JDK-8261455).
454 class FileHeaderHelper {
455 int _fd;
456 bool _is_valid;
457 bool _is_static;
458 GenericCDSFileMapHeader* _header;
459 const char* _archive_name;
460 const char* _base_archive_name;
461
462 public:
463 FileHeaderHelper(const char* archive_name, bool is_static) {
464 _fd = -1;
465 _is_valid = false;
466 _header = nullptr;
467 _base_archive_name = nullptr;
468 _archive_name = archive_name;
469 _is_static = is_static;
470 }
471
472 ~FileHeaderHelper() {
473 if (_header != nullptr) {
474 FREE_C_HEAP_ARRAY(char, _header);
475 }
476 if (_fd != -1) {
477 ::close(_fd);
478 }
479 }
480
481 bool initialize() {
482 assert(_archive_name != nullptr, "Archive name is null");
483 _fd = os::open(_archive_name, O_RDONLY | O_BINARY, 0);
484 if (_fd < 0) {
485 AOTMetaspace::report_loading_error("Specified %s not found (%s)", CDSConfig::type_of_archive_being_loaded(), _archive_name);
486 return false;
487 }
488 return initialize(_fd);
489 }
490
491 // for an already opened file, do not set _fd
492 bool initialize(int fd) {
493 assert(_archive_name != nullptr, "Archive name is null");
494 assert(fd != -1, "Archive must be opened already");
495 // First read the generic header so we know the exact size of the actual header.
496 const char* file_type = CDSConfig::type_of_archive_being_loaded();
497 GenericCDSFileMapHeader gen_header;
498 size_t size = sizeof(GenericCDSFileMapHeader);
499 os::lseek(fd, 0, SEEK_SET);
500 size_t n = ::read(fd, (void*)&gen_header, (unsigned int)size);
501 if (n != size) {
502 aot_log_warning(aot)("Unable to read generic CDS file map header from %s", file_type);
503 return false;
504 }
505
506 if (gen_header._magic != CDS_ARCHIVE_MAGIC &&
507 gen_header._magic != CDS_DYNAMIC_ARCHIVE_MAGIC &&
508 gen_header._magic != CDS_PREIMAGE_ARCHIVE_MAGIC) {
509 aot_log_warning(aot)("The %s has a bad magic number: %#x", file_type, gen_header._magic);
510 return false;
511 }
512
513 if (gen_header._version < CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION) {
514 aot_log_warning(aot)("Cannot handle %s version 0x%x. Must be at least 0x%x.",
515 file_type, gen_header._version, CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION);
516 return false;
517 }
518
519 if (gen_header._version != CURRENT_CDS_ARCHIVE_VERSION) {
520 aot_log_warning(aot)("The %s version 0x%x does not match the required version 0x%x.",
521 file_type, gen_header._version, CURRENT_CDS_ARCHIVE_VERSION);
522 }
523
524 size_t filelen = os::lseek(fd, 0, SEEK_END);
525 if (gen_header._header_size >= filelen) {
526 aot_log_warning(aot)("Archive file header larger than archive file");
527 return false;
528 }
529
530 // Read the actual header and perform more checks
531 size = gen_header._header_size;
532 _header = (GenericCDSFileMapHeader*)NEW_C_HEAP_ARRAY(char, size, mtInternal);
533 os::lseek(fd, 0, SEEK_SET);
534 n = ::read(fd, (void*)_header, (unsigned int)size);
535 if (n != size) {
536 aot_log_warning(aot)("Unable to read file map header from %s", file_type);
537 return false;
538 }
539
540 if (!check_header_crc()) {
541 return false;
542 }
543
544 if (!check_and_init_base_archive_name()) {
545 return false;
546 }
547
548 // All fields in the GenericCDSFileMapHeader has been validated.
549 _is_valid = true;
550 return true;
551 }
552
553 GenericCDSFileMapHeader* get_generic_file_header() {
554 assert(_header != nullptr && _is_valid, "must be a valid archive file");
555 return _header;
556 }
557
558 const char* base_archive_name() {
559 assert(_header != nullptr && _is_valid, "must be a valid archive file");
560 return _base_archive_name;
561 }
562
563 bool is_static_archive() const {
564 return _header->_magic == CDS_ARCHIVE_MAGIC;
565 }
566
567 bool is_dynamic_archive() const {
568 return _header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC;
569 }
570
571 bool is_preimage_static_archive() const {
572 return _header->_magic == CDS_PREIMAGE_ARCHIVE_MAGIC;
573 }
574
575 private:
576 bool check_header_crc() const {
577 if (VerifySharedSpaces) {
578 FileMapHeader* header = (FileMapHeader*)_header;
579 int actual_crc = header->compute_crc();
580 if (actual_crc != header->crc()) {
581 aot_log_info(aot)("_crc expected: %d", header->crc());
582 aot_log_info(aot)(" actual: %d", actual_crc);
583 aot_log_warning(aot)("Header checksum verification failed.");
584 return false;
585 }
586 }
587 return true;
588 }
589
590 bool check_and_init_base_archive_name() {
591 unsigned int name_offset = _header->_base_archive_name_offset;
592 unsigned int name_size = _header->_base_archive_name_size;
593 unsigned int header_size = _header->_header_size;
594
595 if (name_offset + name_size < name_offset) {
596 aot_log_warning(aot)("base_archive_name offset/size overflow: " UINT32_FORMAT "/" UINT32_FORMAT,
597 name_offset, name_size);
598 return false;
599 }
600
601 if (is_static_archive() || is_preimage_static_archive()) {
602 if (name_offset != 0) {
603 aot_log_warning(aot)("static shared archive must have zero _base_archive_name_offset");
604 return false;
605 }
606 if (name_size != 0) {
607 aot_log_warning(aot)("static shared archive must have zero _base_archive_name_size");
608 return false;
609 }
610 } else {
611 assert(is_dynamic_archive(), "must be");
612 if ((name_size == 0 && name_offset != 0) ||
613 (name_size != 0 && name_offset == 0)) {
614 // If either is zero, both must be zero. This indicates that we are using the default base archive.
615 aot_log_warning(aot)("Invalid base_archive_name offset/size: " UINT32_FORMAT "/" UINT32_FORMAT,
616 name_offset, name_size);
617 return false;
618 }
619 if (name_size > 0) {
620 if (name_offset + name_size > header_size) {
621 aot_log_warning(aot)("Invalid base_archive_name offset/size (out of range): "
622 UINT32_FORMAT " + " UINT32_FORMAT " > " UINT32_FORMAT ,
623 name_offset, name_size, header_size);
624 return false;
625 }
626 const char* name = ((const char*)_header) + _header->_base_archive_name_offset;
627 if (name[name_size - 1] != '\0' || strlen(name) != name_size - 1) {
628 aot_log_warning(aot)("Base archive name is damaged");
629 return false;
630 }
631 if (!os::file_exists(name)) {
632 aot_log_warning(aot)("Base archive %s does not exist", name);
633 return false;
634 }
635 _base_archive_name = name;
636 }
637 }
638
639 return true;
640 }
641 };
642
643 // Return value:
644 // false:
645 // <archive_name> is not a valid archive. *base_archive_name is set to null.
646 // true && (*base_archive_name) == nullptr:
647 // <archive_name> is a valid static archive.
648 // true && (*base_archive_name) != nullptr:
649 // <archive_name> is a valid dynamic archive.
650 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
651 const char** base_archive_name) {
652 FileHeaderHelper file_helper(archive_name, false);
653 *base_archive_name = nullptr;
654
655 if (!file_helper.initialize()) {
656 return false;
657 }
658 GenericCDSFileMapHeader* header = file_helper.get_generic_file_header();
659 switch (header->_magic) {
660 case CDS_PREIMAGE_ARCHIVE_MAGIC:
661 return false; // This is a binary config file, not a proper archive
662 case CDS_DYNAMIC_ARCHIVE_MAGIC:
663 break;
664 default:
665 assert(header->_magic == CDS_ARCHIVE_MAGIC, "must be");
666 if (AutoCreateSharedArchive) {
667 aot_log_warning(aot)("AutoCreateSharedArchive is ignored because %s is a static archive", archive_name);
668 }
669 return true;
670 }
671
672 const char* base = file_helper.base_archive_name();
673 if (base == nullptr) {
674 *base_archive_name = CDSConfig::default_archive_path();
675 } else {
676 *base_archive_name = os::strdup_check_oom(base);
677 }
678
679 return true;
680 }
681
682 bool FileMapInfo::is_preimage_static_archive(const char* file) {
683 FileHeaderHelper file_helper(file, false);
684 if (!file_helper.initialize()) {
685 return false;
686 }
687 return file_helper.is_preimage_static_archive();
688 }
689
690 // Read the FileMapInfo information from the file.
691
692 bool FileMapInfo::init_from_file(int fd) {
693 FileHeaderHelper file_helper(_full_path, _is_static);
694 if (!file_helper.initialize(fd)) {
695 aot_log_warning(aot)("Unable to read the file header.");
696 return false;
697 }
698 GenericCDSFileMapHeader* gen_header = file_helper.get_generic_file_header();
699
700 const char* file_type = CDSConfig::type_of_archive_being_loaded();
701 if (_is_static) {
702 if ((gen_header->_magic == CDS_ARCHIVE_MAGIC) ||
703 (gen_header->_magic == CDS_PREIMAGE_ARCHIVE_MAGIC && CDSConfig::is_dumping_final_static_archive())) {
704 // Good
705 } else {
706 if (CDSConfig::new_aot_flags_used()) {
707 aot_log_warning(aot)("Not a valid %s (%s)", file_type, _full_path);
708 } else {
709 aot_log_warning(aot)("Not a base shared archive: %s", _full_path);
710 }
711 return false;
712 }
713 } else {
714 if (gen_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
715 aot_log_warning(aot)("Not a top shared archive: %s", _full_path);
716 return false;
717 }
718 }
719
720 _header = (FileMapHeader*)os::malloc(gen_header->_header_size, mtInternal);
721 os::lseek(fd, 0, SEEK_SET); // reset to begin of the archive
722 size_t size = gen_header->_header_size;
723 size_t n = ::read(fd, (void*)_header, (unsigned int)size);
724 if (n != size) {
725 aot_log_warning(aot)("Failed to read file header from the top archive file\n");
726 return false;
727 }
728
729 if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {
730 aot_log_info(aot)("_version expected: 0x%x", CURRENT_CDS_ARCHIVE_VERSION);
731 aot_log_info(aot)(" actual: 0x%x", header()->version());
732 aot_log_warning(aot)("The %s has the wrong version.", file_type);
733 return false;
734 }
735
736 unsigned int base_offset = header()->base_archive_name_offset();
737 unsigned int name_size = header()->base_archive_name_size();
738 unsigned int header_size = header()->header_size();
739 if (base_offset != 0 && name_size != 0) {
740 if (header_size != base_offset + name_size) {
741 aot_log_info(aot)("_header_size: " UINT32_FORMAT, header_size);
742 aot_log_info(aot)("base_archive_name_size: " UINT32_FORMAT, header()->base_archive_name_size());
743 aot_log_info(aot)("base_archive_name_offset: " UINT32_FORMAT, header()->base_archive_name_offset());
744 aot_log_warning(aot)("The %s has an incorrect header size.", file_type);
745 return false;
746 }
747 }
748
749 const char* actual_ident = header()->jvm_ident();
750
751 if (actual_ident[JVM_IDENT_MAX-1] != 0) {
752 aot_log_warning(aot)("JVM version identifier is corrupted.");
753 return false;
754 }
755
756 char expected_ident[JVM_IDENT_MAX];
757 get_header_version(expected_ident);
758 if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {
759 aot_log_info(aot)("_jvm_ident expected: %s", expected_ident);
760 aot_log_info(aot)(" actual: %s", actual_ident);
761 aot_log_warning(aot)("The %s was created by a different"
762 " version or build of HotSpot", file_type);
763 return false;
764 }
765
766 _file_offset = header()->header_size(); // accounts for the size of _base_archive_name
767
768 size_t len = os::lseek(fd, 0, SEEK_END);
769
770 for (int i = 0; i < AOTMetaspace::n_regions; i++) {
771 FileMapRegion* r = region_at(i);
772 if (r->file_offset() > len || len - r->file_offset() < r->used()) {
773 aot_log_warning(aot)("The %s has been truncated.", file_type);
774 return false;
775 }
776 }
777
778 if (!header()->check_must_match_flags()) {
779 return false;
780 }
781
782 return true;
783 }
784
785 void FileMapInfo::seek_to_position(size_t pos) {
786 if (os::lseek(_fd, (jlong)pos, SEEK_SET) < 0) {
787 aot_log_error(aot)("Unable to seek to position %zu (errno=%d: %s)", pos, errno, os::strerror(errno));
788 AOTMetaspace::unrecoverable_loading_error();
789 }
790 }
791
792 // Read the FileMapInfo information from the file.
793 bool FileMapInfo::open_for_read() {
794 if (_file_open) {
795 return true;
796 }
797 const char* file_type = CDSConfig::type_of_archive_being_loaded();
798 const char* info = CDSConfig::is_dumping_final_static_archive() ?
799 "AOTConfiguration file " : "";
800 aot_log_info(aot)("trying to map %s%s", info, _full_path);
801 int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
802 if (fd < 0) {
803 if (errno == ENOENT) {
804 aot_log_info(aot)("Specified %s not found (%s)", file_type, _full_path);
805 } else {
806 aot_log_warning(aot)("Failed to open %s (%s)", file_type,
807 os::strerror(errno));
808 }
809 return false;
810 } else {
811 aot_log_info(aot)("Opened %s %s.", file_type, _full_path);
812 }
813
814 _fd = fd;
815 _file_open = true;
816 return true;
817 }
818
819 // Write the FileMapInfo information to the file.
820
821 void FileMapInfo::open_as_output() {
822 if (CDSConfig::new_aot_flags_used()) {
823 if (CDSConfig::is_dumping_preimage_static_archive()) {
824 log_info(aot)("Writing binary AOTConfiguration file: %s", _full_path);
825 } else {
826 log_info(aot)("Writing AOTCache file: %s", _full_path);
827 }
828 } else {
829 aot_log_info(aot)("Dumping shared data to file: %s", _full_path);
830 }
831
832 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file.
833 chmod(_full_path, _S_IREAD | _S_IWRITE);
834 #endif
835
836 // Use remove() to delete the existing file because, on Unix, this will
837 // allow processes that have it open continued access to the file.
838 remove(_full_path);
839 int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
840 if (fd < 0) {
841 aot_log_error(aot)("Unable to create %s %s: (%s).", CDSConfig::type_of_archive_being_written(), _full_path,
842 os::strerror(errno));
843 AOTMetaspace::writing_error();
844 return;
845 }
846 _fd = fd;
847 _file_open = true;
848 }
849
850 void FileMapInfo::prepare_for_writing() {
851 // Seek past the header. We will write the header after all regions are written
852 // and their CRCs computed.
853 size_t header_bytes = header()->header_size();
854
855 header_bytes = align_up(header_bytes, AOTMetaspace::core_region_alignment());
856 _file_offset = header_bytes;
857 seek_to_position(_file_offset);
858 }
859
860 // Write the header to the file, seek to the next allocation boundary.
861
862 void FileMapInfo::write_header() {
863 _file_offset = 0;
864 seek_to_position(_file_offset);
865 assert(is_file_position_aligned(), "must be");
866 write_bytes(header(), header()->header_size());
867 }
868
869 size_t FileMapRegion::used_aligned() const {
870 return align_up(used(), AOTMetaspace::core_region_alignment());
871 }
872
873 void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,
874 bool allow_exec, int crc) {
875 _is_heap_region = HeapShared::is_heap_region(region_index);
876 _is_bitmap_region = (region_index == AOTMetaspace::bm);
877 _mapping_offset = mapping_offset;
878 _used = size;
879 _read_only = read_only;
880 _allow_exec = allow_exec;
881 _crc = crc;
882 _mapped_from_file = false;
883 _mapped_base = nullptr;
884 _in_reserved_space = false;
885 }
886
887 void FileMapRegion::init_oopmap(size_t offset, size_t size_in_bits) {
888 _oopmap_offset = offset;
889 _oopmap_size_in_bits = size_in_bits;
890 }
891
892 void FileMapRegion::init_ptrmap(size_t offset, size_t size_in_bits) {
893 _ptrmap_offset = offset;
894 _ptrmap_size_in_bits = size_in_bits;
895 }
896
897 bool FileMapRegion::check_region_crc(char* base) const {
898 // This function should be called after the region has been properly
899 // loaded into memory via FileMapInfo::map_region() or FileMapInfo::read_region().
900 // I.e., this->mapped_base() must be valid.
901 size_t sz = used();
902 if (sz == 0) {
903 return true;
904 }
905
906 assert(base != nullptr, "must be initialized");
907 int crc = ClassLoader::crc32(0, base, (jint)sz);
908 if (crc != this->crc()) {
909 aot_log_warning(aot)("Checksum verification failed.");
910 return false;
911 }
912 return true;
913 }
914
915 static const char* region_name(int region_index) {
916 static const char* names[] = {
917 "rw", "ro", "bm", "hp", "ac"
918 };
919 const int num_regions = sizeof(names)/sizeof(names[0]);
920 assert(0 <= region_index && region_index < num_regions, "sanity");
921
922 return names[region_index];
923 }
924
925 BitMapView FileMapInfo::bitmap_view(int region_index, bool is_oopmap) {
926 FileMapRegion* r = region_at(region_index);
927 char* bitmap_base = is_static() ? FileMapInfo::current_info()->map_bitmap_region() : FileMapInfo::dynamic_info()->map_bitmap_region();
928 bitmap_base += is_oopmap ? r->oopmap_offset() : r->ptrmap_offset();
929 size_t size_in_bits = is_oopmap ? r->oopmap_size_in_bits() : r->ptrmap_size_in_bits();
930
931 aot_log_debug(aot, reloc)("mapped %s relocation %smap @ " INTPTR_FORMAT " (%zu bits)",
932 region_name(region_index), is_oopmap ? "oop" : "ptr",
933 p2i(bitmap_base), size_in_bits);
934
935 return BitMapView((BitMap::bm_word_t*)(bitmap_base), size_in_bits);
936 }
937
938 BitMapView FileMapInfo::oopmap_view(int region_index) {
939 return bitmap_view(region_index, /*is_oopmap*/true);
940 }
941
942 BitMapView FileMapInfo::ptrmap_view(int region_index) {
943 return bitmap_view(region_index, /*is_oopmap*/false);
944 }
945
946 void FileMapRegion::print(outputStream* st, int region_index) {
947 st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));
948 st->print_cr("- crc: 0x%08x", _crc);
949 st->print_cr("- read_only: %d", _read_only);
950 st->print_cr("- allow_exec: %d", _allow_exec);
951 st->print_cr("- is_heap_region: %d", _is_heap_region);
952 st->print_cr("- is_bitmap_region: %d", _is_bitmap_region);
953 st->print_cr("- mapped_from_file: %d", _mapped_from_file);
954 st->print_cr("- file_offset: 0x%zx", _file_offset);
955 st->print_cr("- mapping_offset: 0x%zx", _mapping_offset);
956 st->print_cr("- used: %zu", _used);
957 st->print_cr("- oopmap_offset: 0x%zx", _oopmap_offset);
958 st->print_cr("- oopmap_size_in_bits: %zu", _oopmap_size_in_bits);
959 st->print_cr("- ptrmap_offset: 0x%zx", _ptrmap_offset);
960 st->print_cr("- ptrmap_size_in_bits: %zu", _ptrmap_size_in_bits);
961 st->print_cr("- mapped_base: " INTPTR_FORMAT, p2i(_mapped_base));
962 }
963
964 void FileMapInfo::write_region(int region, char* base, size_t size,
965 bool read_only, bool allow_exec) {
966 assert(CDSConfig::is_dumping_archive(), "sanity");
967
968 FileMapRegion* r = region_at(region);
969 char* requested_base;
970 size_t mapping_offset = 0;
971
972 if (region == AOTMetaspace::bm) {
973 requested_base = nullptr; // always null for bm region
974 } else if (size == 0) {
975 // This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)
976 requested_base = nullptr;
977 } else if (HeapShared::is_heap_region(region)) {
978 assert(CDSConfig::is_dumping_heap(), "sanity");
979 #if INCLUDE_CDS_JAVA_HEAP
980 assert(!CDSConfig::is_dumping_dynamic_archive(), "must be");
981 if (HeapShared::is_writing_mapping_mode()) {
982 requested_base = (char*)AOTMappedHeapWriter::requested_address();
983 if (UseCompressedOops) {
984 mapping_offset = (size_t)((address)requested_base - AOTMappedHeapWriter::narrow_oop_base());
985 assert((mapping_offset >> CompressedOops::shift()) << CompressedOops::shift() == mapping_offset, "must be");
986 }
987 } else {
988 requested_base = nullptr;
989 }
990 #endif // INCLUDE_CDS_JAVA_HEAP
991 } else {
992 char* requested_SharedBaseAddress = (char*)AOTMetaspace::requested_base_address();
993 requested_base = ArchiveBuilder::current()->to_requested(base);
994 assert(requested_base >= requested_SharedBaseAddress, "must be");
995 mapping_offset = requested_base - requested_SharedBaseAddress;
996 }
997
998 r->set_file_offset(_file_offset);
999 int crc = ClassLoader::crc32(0, base, (jint)size);
1000 if (size > 0) {
1001 aot_log_info(aot)("Shared file region (%s) %d: %8zu"
1002 " bytes, addr " INTPTR_FORMAT " file offset 0x%08" PRIxPTR
1003 " crc 0x%08x",
1004 region_name(region), region, size, p2i(requested_base), _file_offset, crc);
1005 } else {
1006 aot_log_info(aot)("Shared file region (%s) %d: %8zu"
1007 " bytes", region_name(region), region, size);
1008 }
1009
1010 r->init(region, mapping_offset, size, read_only, allow_exec, crc);
1011
1012 if (base != nullptr) {
1013 write_bytes_aligned(base, size);
1014 }
1015 }
1016
1017 static size_t write_bitmap(const CHeapBitMap* map, char* output, size_t offset) {
1018 size_t size_in_bytes = map->size_in_bytes();
1019 map->write_to((BitMap::bm_word_t*)(output + offset), size_in_bytes);
1020 return offset + size_in_bytes;
1021 }
1022
1023 // The sorting code groups the objects with non-null oop/ptrs together.
1024 // Relevant bitmaps then have lots of leading and trailing zeros, which
1025 // we do not have to store.
1026 size_t FileMapInfo::remove_bitmap_zeros(CHeapBitMap* map) {
1027 BitMap::idx_t first_set = map->find_first_set_bit(0);
1028 BitMap::idx_t last_set = map->find_last_set_bit(0);
1029 size_t old_size = map->size();
1030
1031 // Slice and resize bitmap
1032 map->truncate(first_set, last_set + 1);
1033
1034 assert(map->at(0), "First bit should be set");
1035 assert(map->at(map->size() - 1), "Last bit should be set");
1036 assert(map->size() <= old_size, "sanity");
1037
1038 return first_set;
1039 }
1040
1041 char* FileMapInfo::write_bitmap_region(CHeapBitMap* rw_ptrmap,
1042 CHeapBitMap* ro_ptrmap,
1043 AOTMappedHeapInfo* mapped_heap_info,
1044 AOTStreamedHeapInfo* streamed_heap_info,
1045 size_t &size_in_bytes) {
1046 size_t removed_rw_leading_zeros = remove_bitmap_zeros(rw_ptrmap);
1047 size_t removed_ro_leading_zeros = remove_bitmap_zeros(ro_ptrmap);
1048 header()->set_rw_ptrmap_start_pos(removed_rw_leading_zeros);
1049 header()->set_ro_ptrmap_start_pos(removed_ro_leading_zeros);
1050 size_in_bytes = rw_ptrmap->size_in_bytes() + ro_ptrmap->size_in_bytes();
1051
1052 if (mapped_heap_info != nullptr && mapped_heap_info->is_used()) {
1053 // Remove leading and trailing zeros
1054 assert(HeapShared::is_writing_mapping_mode(), "unexpected dumping mode");
1055 size_t removed_oop_leading_zeros = remove_bitmap_zeros(mapped_heap_info->oopmap());
1056 size_t removed_ptr_leading_zeros = remove_bitmap_zeros(mapped_heap_info->ptrmap());
1057 mapped_heap_info->set_oopmap_start_pos(removed_oop_leading_zeros);
1058 mapped_heap_info->set_ptrmap_start_pos(removed_ptr_leading_zeros);
1059
1060 size_in_bytes += mapped_heap_info->oopmap()->size_in_bytes();
1061 size_in_bytes += mapped_heap_info->ptrmap()->size_in_bytes();
1062 } else if (streamed_heap_info != nullptr && streamed_heap_info->is_used()) {
1063 assert(HeapShared::is_writing_streaming_mode(), "unexpected dumping mode");
1064
1065 size_in_bytes += streamed_heap_info->oopmap()->size_in_bytes();
1066 }
1067
1068 // The bitmap region contains up to 4 parts:
1069 // rw_ptrmap: metaspace pointers inside the read-write region
1070 // ro_ptrmap: metaspace pointers inside the read-only region
1071 // *_heap_info->oopmap(): Java oop pointers in the heap region
1072 // mapped_heap_info->ptrmap(): metaspace pointers in the heap region
1073 char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);
1074 size_t written = 0;
1075
1076 region_at(AOTMetaspace::rw)->init_ptrmap(0, rw_ptrmap->size());
1077 written = write_bitmap(rw_ptrmap, buffer, written);
1078
1079 region_at(AOTMetaspace::ro)->init_ptrmap(written, ro_ptrmap->size());
1080 written = write_bitmap(ro_ptrmap, buffer, written);
1081
1082 if (mapped_heap_info != nullptr && mapped_heap_info->is_used()) {
1083 assert(HeapShared::is_writing_mapping_mode(), "unexpected dumping mode");
1084 FileMapRegion* r = region_at(AOTMetaspace::hp);
1085
1086 r->init_oopmap(written, mapped_heap_info->oopmap()->size());
1087 written = write_bitmap(mapped_heap_info->oopmap(), buffer, written);
1088
1089 r->init_ptrmap(written, mapped_heap_info->ptrmap()->size());
1090 written = write_bitmap(mapped_heap_info->ptrmap(), buffer, written);
1091 } else if (streamed_heap_info != nullptr && streamed_heap_info->is_used()) {
1092 assert(HeapShared::is_writing_streaming_mode(), "unexpected dumping mode");
1093 FileMapRegion* r = region_at(AOTMetaspace::hp);
1094
1095 r->init_oopmap(written, streamed_heap_info->oopmap()->size());
1096 written = write_bitmap(streamed_heap_info->oopmap(), buffer, written);
1097 }
1098
1099 write_region(AOTMetaspace::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);
1100 return buffer;
1101 }
1102
1103 #if INCLUDE_CDS_JAVA_HEAP
1104 size_t FileMapInfo::write_mapped_heap_region(AOTMappedHeapInfo* heap_info) {
1105 char* buffer_start = heap_info->buffer_start();
1106 size_t buffer_size = heap_info->buffer_byte_size();
1107 write_region(AOTMetaspace::hp, buffer_start, buffer_size, false, false);
1108 header()->set_mapped_heap_header(heap_info->create_header());
1109 return buffer_size;
1110 }
1111
1112 size_t FileMapInfo::write_streamed_heap_region(AOTStreamedHeapInfo* heap_info) {
1113 char* buffer_start = heap_info->buffer_start();
1114 size_t buffer_size = heap_info->buffer_byte_size();
1115 write_region(AOTMetaspace::hp, buffer_start, buffer_size, true, false);
1116 header()->set_streamed_heap_header(heap_info->create_header());
1117 return buffer_size;
1118 }
1119 #endif // INCLUDE_CDS_JAVA_HEAP
1120
1121 // Dump bytes to file -- at the current file position.
1122
1123 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1124 assert(_file_open, "must be");
1125 if (!os::write(_fd, buffer, nbytes)) {
1126 // If the shared archive is corrupted, close it and remove it.
1127 close();
1128 remove(_full_path);
1129
1130 if (CDSConfig::is_dumping_preimage_static_archive()) {
1131 AOTMetaspace::writing_error("Unable to write to AOT configuration file.");
1132 } else if (CDSConfig::new_aot_flags_used()) {
1133 AOTMetaspace::writing_error("Unable to write to AOT cache.");
1134 } else {
1135 AOTMetaspace::writing_error("Unable to write to shared archive.");
1136 }
1137 }
1138 _file_offset += nbytes;
1139 }
1140
1141 bool FileMapInfo::is_file_position_aligned() const {
1142 return _file_offset == align_up(_file_offset,
1143 AOTMetaspace::core_region_alignment());
1144 }
1145
1146 // Align file position to an allocation unit boundary.
1147
1148 void FileMapInfo::align_file_position() {
1149 assert(_file_open, "must be");
1150 size_t new_file_offset = align_up(_file_offset,
1151 AOTMetaspace::core_region_alignment());
1152 if (new_file_offset != _file_offset) {
1153 _file_offset = new_file_offset;
1154 // Seek one byte back from the target and write a byte to insure
1155 // that the written file is the correct length.
1156 _file_offset -= 1;
1157 seek_to_position(_file_offset);
1158 char zero = 0;
1159 write_bytes(&zero, 1);
1160 }
1161 }
1162
1163
1164 // Dump bytes to file -- at the current file position.
1165
1166 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1167 align_file_position();
1168 write_bytes(buffer, nbytes);
1169 align_file_position();
1170 }
1171
1172 // Close the shared archive file. This does NOT unmap mapped regions.
1173
1174 void FileMapInfo::close() {
1175 if (_file_open) {
1176 if (::close(_fd) < 0) {
1177 AOTMetaspace::unrecoverable_loading_error("Unable to close the shared archive file.");
1178 }
1179 _file_open = false;
1180 _fd = -1;
1181 }
1182 }
1183
1184 /*
1185 * Same as os::map_memory() but also pretouches if AlwaysPreTouch is enabled.
1186 */
1187 static char* map_memory(int fd, const char* file_name, size_t file_offset,
1188 char* addr, size_t bytes, bool read_only,
1189 bool allow_exec, MemTag mem_tag) {
1190 char* mem = os::map_memory(fd, file_name, file_offset, addr, bytes,
1191 mem_tag, AlwaysPreTouch ? false : read_only,
1192 allow_exec);
1193 if (mem != nullptr && AlwaysPreTouch) {
1194 os::pretouch_memory(mem, mem + bytes);
1195 }
1196 return mem;
1197 }
1198
1199 char* FileMapInfo::map_heap_region(FileMapRegion* r, char* addr, size_t bytes) {
1200 return ::map_memory(_fd,
1201 _full_path,
1202 r->file_offset(),
1203 addr,
1204 bytes,
1205 r->read_only(),
1206 r->allow_exec(),
1207 mtJavaHeap);
1208 }
1209
1210 // JVM/TI RedefineClasses() support:
1211 // Remap the shared readonly space to shared readwrite, private.
1212 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1213 int idx = AOTMetaspace::ro;
1214 FileMapRegion* r = region_at(idx);
1215 if (!r->read_only()) {
1216 // the space is already readwrite so we are done
1217 return true;
1218 }
1219 size_t size = r->used_aligned();
1220 if (!open_for_read()) {
1221 return false;
1222 }
1223 char *addr = r->mapped_base();
1224 // This path should not be reached for Windows; see JDK-8222379.
1225 assert(WINDOWS_ONLY(false) NOT_WINDOWS(true), "Don't call on Windows");
1226 // Replace old mapping with new one that is writable.
1227 char *base = os::map_memory(_fd, _full_path, r->file_offset(),
1228 addr, size, mtNone, false /* !read_only */,
1229 r->allow_exec());
1230 close();
1231 // These have to be errors because the shared region is now unmapped.
1232 if (base == nullptr) {
1233 aot_log_error(aot)("Unable to remap shared readonly space (errno=%d).", errno);
1234 vm_exit(1);
1235 }
1236 if (base != addr) {
1237 aot_log_error(aot)("Unable to remap shared readonly space (errno=%d).", errno);
1238 vm_exit(1);
1239 }
1240 r->set_read_only(false);
1241 return true;
1242 }
1243
1244 // Memory map a region in the address space.
1245 static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap", "Heap", "Code" };
1246
1247 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {
1248 DEBUG_ONLY(FileMapRegion* last_region = nullptr);
1249 intx addr_delta = mapped_base_address - header()->requested_base_address();
1250
1251 // Make sure we don't attempt to use header()->mapped_base_address() unless
1252 // it's been successfully mapped.
1253 DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)
1254
1255 for (int i = 0; i < num_regions; i++) {
1256 int idx = regions[i];
1257 MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);
1258 if (result != MAP_ARCHIVE_SUCCESS) {
1259 return result;
1260 }
1261 FileMapRegion* r = region_at(idx);
1262 DEBUG_ONLY(if (last_region != nullptr) {
1263 // Ensure that the OS won't be able to allocate new memory spaces between any mapped
1264 // regions, or else it would mess up the simple comparison in MetaspaceObj::in_aot_cache().
1265 assert(r->mapped_base() == last_region->mapped_end(), "must have no gaps");
1266 }
1267 last_region = r;)
1268 aot_log_info(aot)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",
1269 idx, p2i(r->mapped_base()), p2i(r->mapped_end()),
1270 shared_region_name[idx]);
1271
1272 }
1273
1274 header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);
1275 if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {
1276 return MAP_ARCHIVE_OTHER_FAILURE;
1277 }
1278
1279 return MAP_ARCHIVE_SUCCESS;
1280 }
1281
1282 bool FileMapInfo::read_region(int i, char* base, size_t size, bool do_commit) {
1283 FileMapRegion* r = region_at(i);
1284 if (do_commit) {
1285 aot_log_info(aot)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",
1286 is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),
1287 shared_region_name[i], r->allow_exec() ? " exec" : "");
1288 if (!os::commit_memory(base, size, r->allow_exec())) {
1289 aot_log_error(aot)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",
1290 i, shared_region_name[i]);
1291 return false;
1292 }
1293 }
1294 if (os::lseek(_fd, (long)r->file_offset(), SEEK_SET) != (int)r->file_offset() ||
1295 read_bytes(base, size) != size) {
1296 return false;
1297 }
1298
1299 if (VerifySharedSpaces && !r->check_region_crc(base)) {
1300 return false;
1301 }
1302
1303 r->set_mapped_from_file(false);
1304 r->set_mapped_base(base);
1305
1306 return true;
1307 }
1308
1309 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {
1310 assert(!HeapShared::is_heap_region(i), "sanity");
1311 FileMapRegion* r = region_at(i);
1312 size_t size = r->used_aligned();
1313 char *requested_addr = mapped_base_address + r->mapping_offset();
1314 assert(!is_mapped(), "must be not mapped yet");
1315 assert(requested_addr != nullptr, "must be specified");
1316
1317 r->set_mapped_from_file(false);
1318 r->set_in_reserved_space(false);
1319
1320 if (AOTMetaspace::use_windows_memory_mapping()) {
1321 // Windows cannot remap read-only shared memory to read-write when required for
1322 // RedefineClasses, which is also used by JFR. Always map windows regions as RW.
1323 r->set_read_only(false);
1324 } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1325 Arguments::has_jfr_option()) {
1326 // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1327 r->set_read_only(false);
1328 } else if (addr_delta != 0) {
1329 r->set_read_only(false); // Need to patch the pointers
1330 }
1331
1332 if (AOTMetaspace::use_windows_memory_mapping() && rs.is_reserved()) {
1333 // This is the second time we try to map the archive(s). We have already created a ReservedSpace
1334 // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows
1335 // can't mmap into a ReservedSpace, so we just ::read() the data. We're going to patch all the
1336 // regions anyway, so there's no benefit for mmap anyway.
1337 if (!read_region(i, requested_addr, size, /* do_commit = */ true)) {
1338 AOTMetaspace::report_loading_error("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,
1339 shared_region_name[i], p2i(requested_addr));
1340 return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.
1341 } else {
1342 assert(r->mapped_base() != nullptr, "must be initialized");
1343 }
1344 } else {
1345 // Note that this may either be a "fresh" mapping into unreserved address
1346 // space (Windows, first mapping attempt), or a mapping into pre-reserved
1347 // space (Posix). See also comment in AOTMetaspace::map_archives().
1348 char* base = map_memory(_fd, _full_path, r->file_offset(),
1349 requested_addr, size, r->read_only(),
1350 r->allow_exec(), mtClassShared);
1351 if (base != requested_addr) {
1352 AOTMetaspace::report_loading_error("Unable to map %s shared space at " INTPTR_FORMAT,
1353 shared_region_name[i], p2i(requested_addr));
1354 _memory_mapping_failed = true;
1355 return MAP_ARCHIVE_MMAP_FAILURE;
1356 }
1357
1358 if (VerifySharedSpaces && !r->check_region_crc(requested_addr)) {
1359 return MAP_ARCHIVE_OTHER_FAILURE;
1360 }
1361
1362 r->set_mapped_from_file(true);
1363 r->set_mapped_base(requested_addr);
1364 }
1365
1366 if (rs.is_reserved()) {
1367 char* mapped_base = r->mapped_base();
1368 assert(rs.base() <= mapped_base && mapped_base + size <= rs.end(),
1369 PTR_FORMAT " <= " PTR_FORMAT " < " PTR_FORMAT " <= " PTR_FORMAT,
1370 p2i(rs.base()), p2i(mapped_base), p2i(mapped_base + size), p2i(rs.end()));
1371 r->set_in_reserved_space(rs.is_reserved());
1372 }
1373 return MAP_ARCHIVE_SUCCESS;
1374 }
1375
1376 // The return value is the location of the archive relocation bitmap.
1377 char* FileMapInfo::map_auxiliary_region(int region_index, bool read_only) {
1378 FileMapRegion* r = region_at(region_index);
1379 if (r->mapped_base() != nullptr) {
1380 return r->mapped_base();
1381 }
1382 const char* region_name = shared_region_name[region_index];
1383 bool allow_exec = false;
1384 char* requested_addr = nullptr; // allow OS to pick any location
1385 char* mapped_base = map_memory(_fd, _full_path, r->file_offset(),
1386 requested_addr, r->used_aligned(), read_only, allow_exec, mtClassShared);
1387 if (mapped_base == nullptr) {
1388 AOTMetaspace::report_loading_error("failed to map %d region", region_index);
1389 return nullptr;
1390 }
1391
1392 if (VerifySharedSpaces && !r->check_region_crc(mapped_base)) {
1393 aot_log_error(aot)("region %d CRC error", region_index);
1394 os::unmap_memory(mapped_base, r->used_aligned());
1395 return nullptr;
1396 }
1397
1398 r->set_mapped_from_file(true);
1399 r->set_mapped_base(mapped_base);
1400 aot_log_info(aot)("Mapped %s region #%d at base %zu top %zu (%s)",
1401 is_static() ? "static " : "dynamic",
1402 region_index, p2i(r->mapped_base()), p2i(r->mapped_end()),
1403 region_name);
1404 return mapped_base;
1405 }
1406
1407 char* FileMapInfo::map_bitmap_region() {
1408 return map_auxiliary_region(AOTMetaspace::bm, false);
1409 }
1410
1411 bool FileMapInfo::map_aot_code_region(ReservedSpace rs) {
1412 FileMapRegion* r = region_at(AOTMetaspace::ac);
1413 assert(r->used() > 0 && r->used_aligned() == rs.size(), "must be");
1414
1415 char* requested_base = rs.base();
1416 assert(requested_base != nullptr, "should be inside code cache");
1417
1418 char* mapped_base;
1419 if (AOTMetaspace::use_windows_memory_mapping()) {
1420 if (!read_region(AOTMetaspace::ac, requested_base, r->used_aligned(), /* do_commit = */ true)) {
1421 AOTMetaspace::report_loading_error("Failed to read aot code shared space into reserved space at " INTPTR_FORMAT,
1422 p2i(requested_base));
1423 return false;
1424 }
1425 mapped_base = requested_base;
1426 } else {
1427 // We do not execute in-place in the AOT code region.
1428 // AOT code is copied to the CodeCache for execution.
1429 bool read_only = false, allow_exec = false;
1430 mapped_base = map_memory(_fd, _full_path, r->file_offset(),
1431 requested_base, r->used_aligned(), read_only, allow_exec, mtClassShared);
1432 }
1433 if (mapped_base == nullptr) {
1434 AOTMetaspace::report_loading_error("failed to map aot code region");
1435 return false;
1436 } else {
1437 assert(mapped_base == requested_base, "must be");
1438 r->set_mapped_from_file(true);
1439 r->set_mapped_base(mapped_base);
1440 aot_log_info(aot)("Mapped static region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",
1441 AOTMetaspace::ac, p2i(r->mapped_base()), p2i(r->mapped_end()),
1442 shared_region_name[AOTMetaspace::ac]);
1443 return true;
1444 }
1445 }
1446
1447 class SharedDataRelocationTask : public ArchiveWorkerTask {
1448 private:
1449 BitMapView* const _rw_bm;
1450 BitMapView* const _ro_bm;
1451 SharedDataRelocator* const _rw_reloc;
1452 SharedDataRelocator* const _ro_reloc;
1453
1454 public:
1455 SharedDataRelocationTask(BitMapView* rw_bm, BitMapView* ro_bm, SharedDataRelocator* rw_reloc, SharedDataRelocator* ro_reloc) :
1456 ArchiveWorkerTask("Shared Data Relocation"),
1457 _rw_bm(rw_bm), _ro_bm(ro_bm), _rw_reloc(rw_reloc), _ro_reloc(ro_reloc) {}
1458
1459 void work(int chunk, int max_chunks) override {
1460 work_on(chunk, max_chunks, _rw_bm, _rw_reloc);
1461 work_on(chunk, max_chunks, _ro_bm, _ro_reloc);
1462 }
1463
1464 void work_on(int chunk, int max_chunks, BitMapView* bm, SharedDataRelocator* reloc) {
1465 BitMap::idx_t size = bm->size();
1466 BitMap::idx_t start = MIN2(size, size * chunk / max_chunks);
1467 BitMap::idx_t end = MIN2(size, size * (chunk + 1) / max_chunks);
1468 assert(end > start, "Sanity: no empty slices");
1469 bm->iterate(reloc, start, end);
1470 }
1471 };
1472
1473 // This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).
1474 // We relocate all pointers in the 2 core regions (ro, rw).
1475 bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {
1476 aot_log_debug(aot, reloc)("runtime archive relocation start");
1477 char* bitmap_base = map_bitmap_region();
1478
1479 if (bitmap_base == nullptr) {
1480 return false; // OOM, or CRC check failure
1481 } else {
1482 BitMapView rw_ptrmap = ptrmap_view(AOTMetaspace::rw);
1483 BitMapView ro_ptrmap = ptrmap_view(AOTMetaspace::ro);
1484
1485 FileMapRegion* rw_region = first_core_region();
1486 FileMapRegion* ro_region = last_core_region();
1487
1488 // Patch all pointers inside the RW region
1489 address rw_patch_base = (address)rw_region->mapped_base();
1490 address rw_patch_end = (address)rw_region->mapped_end();
1491
1492 // Patch all pointers inside the RO region
1493 address ro_patch_base = (address)ro_region->mapped_base();
1494 address ro_patch_end = (address)ro_region->mapped_end();
1495
1496 // the current value of the pointers to be patched must be within this
1497 // range (i.e., must be between the requested base address and the address of the current archive).
1498 // Note: top archive may point to objects in the base archive, but not the other way around.
1499 address valid_old_base = (address)header()->requested_base_address();
1500 address valid_old_end = valid_old_base + mapping_end_offset();
1501
1502 // after patching, the pointers must point inside this range
1503 // (the requested location of the archive, as mapped at runtime).
1504 address valid_new_base = (address)header()->mapped_base_address();
1505 address valid_new_end = (address)mapped_end();
1506
1507 SharedDataRelocator rw_patcher((address*)rw_patch_base + header()->rw_ptrmap_start_pos(), (address*)rw_patch_end, valid_old_base, valid_old_end,
1508 valid_new_base, valid_new_end, addr_delta);
1509 SharedDataRelocator ro_patcher((address*)ro_patch_base + header()->ro_ptrmap_start_pos(), (address*)ro_patch_end, valid_old_base, valid_old_end,
1510 valid_new_base, valid_new_end, addr_delta);
1511
1512 if (AOTCacheParallelRelocation) {
1513 ArchiveWorkers workers;
1514 SharedDataRelocationTask task(&rw_ptrmap, &ro_ptrmap, &rw_patcher, &ro_patcher);
1515 workers.run_task(&task);
1516 } else {
1517 rw_ptrmap.iterate(&rw_patcher);
1518 ro_ptrmap.iterate(&ro_patcher);
1519 }
1520
1521 // The AOTMetaspace::bm region will be unmapped in AOTMetaspace::initialize_shared_spaces().
1522
1523 aot_log_debug(aot, reloc)("runtime archive relocation done");
1524 return true;
1525 }
1526 }
1527
1528 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
1529 assert(_file_open, "Archive file is not open");
1530 size_t n = ::read(_fd, buffer, (unsigned int)count);
1531 if (n != count) {
1532 // Close the file if there's a problem reading it.
1533 close();
1534 return 0;
1535 }
1536 _file_offset += count;
1537 return count;
1538 }
1539
1540 // Get the total size in bytes of a read only region
1541 size_t FileMapInfo::readonly_total() {
1542 size_t total = 0;
1543 if (current_info() != nullptr) {
1544 FileMapRegion* r = FileMapInfo::current_info()->region_at(AOTMetaspace::ro);
1545 if (r->read_only()) total += r->used();
1546 }
1547 if (dynamic_info() != nullptr) {
1548 FileMapRegion* r = FileMapInfo::dynamic_info()->region_at(AOTMetaspace::ro);
1549 if (r->read_only()) total += r->used();
1550 }
1551 return total;
1552 }
1553
1554 #if INCLUDE_CDS_JAVA_HEAP
1555
1556 bool FileMapInfo::has_heap_region() {
1557 return (region_at(AOTMetaspace::hp)->used() > 0);
1558 }
1559
1560 static void on_heap_region_loading_error() {
1561 if (CDSConfig::is_using_aot_linked_classes()) {
1562 // It's too late to recover -- we have already committed to use the archived metaspace objects, but
1563 // the archived heap objects cannot be loaded, so we don't have the archived FMG to guarantee that
1564 // all AOT-linked classes are visible.
1565 //
1566 // We get here because the heap is too small. The app will fail anyway. So let's quit.
1567 aot_log_error(aot)("%s has aot-linked classes but the archived "
1568 "heap objects cannot be loaded. Try increasing your heap size.",
1569 CDSConfig::type_of_archive_being_loaded());
1570 AOTMetaspace::unrecoverable_loading_error();
1571 }
1572 CDSConfig::stop_using_full_module_graph();
1573 }
1574
1575 void FileMapInfo::stream_heap_region() {
1576 assert(object_streaming_mode(), "This should only be done for the streaming approach");
1577
1578 if (map_auxiliary_region(AOTMetaspace::hp, /*readonly=*/true) != nullptr) {
1579 HeapShared::initialize_streaming();
1580 } else {
1581 on_heap_region_loading_error();
1582 }
1583 }
1584
1585 void FileMapInfo::map_or_load_heap_region() {
1586 assert(!object_streaming_mode(), "This should only be done for the mapping approach");
1587 bool success = false;
1588
1589 if (AOTMappedHeapLoader::can_map()) {
1590 success = AOTMappedHeapLoader::map_heap_region(this);
1591 } else if (AOTMappedHeapLoader::can_load()) {
1592 success = AOTMappedHeapLoader::load_heap_region(this);
1593 }
1594
1595 if (!success) {
1596 on_heap_region_loading_error();
1597 }
1598 }
1599
1600 bool FileMapInfo::can_use_heap_region() {
1601 if (!has_heap_region()) {
1602 return false;
1603 }
1604
1605 if (!object_streaming_mode() && !AOTMappedHeapLoader::can_use()) {
1606 // Currently this happens only when using ZGC with an AOT cache generated with -XX:-AOTStreamableObjects
1607 AOTMetaspace::report_loading_error("CDS heap data cannot be used by the selected GC. "
1608 "Please choose a different GC or rebuild AOT cache "
1609 "with -XX:+AOTStreamableObjects");
1610 return false;
1611 }
1612
1613 if (CDSConfig::is_using_aot_linked_classes()) {
1614 assert(!JvmtiExport::should_post_class_file_load_hook(), "already checked");
1615 assert(CDSConfig::is_using_full_module_graph(), "already checked");
1616 } else {
1617 if (JvmtiExport::should_post_class_file_load_hook()) {
1618 AOTMetaspace::report_loading_error("CDS heap data is disabled because JVMTI ClassFileLoadHook is in use.");
1619 return false;
1620 }
1621 if (!CDSConfig::is_using_full_module_graph()) {
1622 if (CDSConfig::is_dumping_final_static_archive()) {
1623 // We are loading the preimage static archive, which has no KlassSubGraphs.
1624 // See CDSConfig::is_dumping_klass_subgraphs()
1625 } else {
1626 AOTMetaspace::report_loading_error("CDS heap data is disabled because archived full module graph is not used.");
1627 return false;
1628 }
1629 }
1630 }
1631
1632 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1633 ShouldNotReachHere(); // CDS should have been disabled.
1634 // The archived objects are mapped at JVM start-up, but we don't know if
1635 // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
1636 // which would make the archived String or mirror objects invalid. Let's be safe and not
1637 // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
1638 //
1639 // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
1640 // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
1641 // because we won't install an archived object subgraph if the klass of any of the
1642 // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
1643 }
1644
1645 // We pre-compute narrow Klass IDs with the runtime mapping start intended to be the base, and a shift of
1646 // HeapShared::precomputed_narrow_klass_shift. We enforce this encoding at runtime (see
1647 // CompressedKlassPointers::initialize_for_given_encoding()). Therefore, the following assertions must
1648 // hold:
1649 address archive_narrow_klass_base = (address)header()->mapped_base_address();
1650 const int archive_narrow_klass_pointer_bits = header()->narrow_klass_pointer_bits();
1651 const int archive_narrow_klass_shift = header()->narrow_klass_shift();
1652
1653 aot_log_info(aot)("CDS archive was created with max heap size = %zuM, and the following configuration:",
1654 max_heap_size()/M);
1655
1656 aot_log_info(aot)(" narrow_klass_base at mapping start address, narrow_klass_pointer_bits = %d, narrow_klass_shift = %d",
1657 archive_narrow_klass_pointer_bits, archive_narrow_klass_shift);
1658 if (UseCompressedOops) {
1659 aot_log_info(aot)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1660 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
1661 }
1662 aot_log_info(aot)("The current max heap size = %zuM, G1HeapRegion::GrainBytes = %zu",
1663 MaxHeapSize/M, G1HeapRegion::GrainBytes);
1664 aot_log_info(aot)(" narrow_klass_base = " PTR_FORMAT ", arrow_klass_pointer_bits = %d, narrow_klass_shift = %d",
1665 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::narrow_klass_pointer_bits(), CompressedKlassPointers::shift());
1666 if (UseCompressedOops) {
1667 aot_log_info(aot)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1668 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
1669 }
1670 if (!object_streaming_mode()) {
1671 aot_log_info(aot)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",
1672 UseCompressedOops ? p2i(CompressedOops::begin()) :
1673 UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().start()) : 0L,
1674 UseCompressedOops ? p2i(CompressedOops::end()) :
1675 UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().end()) : 0L);
1676 }
1677
1678 int err = 0;
1679 if ( archive_narrow_klass_base != CompressedKlassPointers::base() ||
1680 (err = 1, archive_narrow_klass_pointer_bits != CompressedKlassPointers::narrow_klass_pointer_bits()) ||
1681 (err = 2, archive_narrow_klass_shift != CompressedKlassPointers::shift()) ) {
1682 stringStream ss;
1683 switch (err) {
1684 case 0:
1685 ss.print("Unexpected encoding base encountered (" PTR_FORMAT ", expected " PTR_FORMAT ")",
1686 p2i(CompressedKlassPointers::base()), p2i(archive_narrow_klass_base));
1687 break;
1688 case 1:
1689 ss.print("Unexpected narrow Klass bit length encountered (%d, expected %d)",
1690 CompressedKlassPointers::narrow_klass_pointer_bits(), archive_narrow_klass_pointer_bits);
1691 break;
1692 case 2:
1693 ss.print("Unexpected narrow Klass shift encountered (%d, expected %d)",
1694 CompressedKlassPointers::shift(), archive_narrow_klass_shift);
1695 break;
1696 default:
1697 ShouldNotReachHere();
1698 };
1699 if (CDSConfig::new_aot_flags_used()) {
1700 LogTarget(Info, aot) lt;
1701 if (lt.is_enabled()) {
1702 LogStream ls(lt);
1703 ls.print_raw(ss.base());
1704 header()->print(&ls);
1705 }
1706 } else {
1707 LogTarget(Info, cds) lt;
1708 if (lt.is_enabled()) {
1709 LogStream ls(lt);
1710 ls.print_raw(ss.base());
1711 header()->print(&ls);
1712 }
1713 }
1714 assert(false, "%s", ss.base());
1715 }
1716
1717 return true;
1718 }
1719
1720 #endif // INCLUDE_CDS_JAVA_HEAP
1721
1722 // Unmap a memory region in the address space.
1723
1724 void FileMapInfo::unmap_regions(int regions[], int num_regions) {
1725 for (int r = 0; r < num_regions; r++) {
1726 int idx = regions[r];
1727 unmap_region(idx);
1728 }
1729 }
1730
1731 void FileMapInfo::unmap_region(int i) {
1732 FileMapRegion* r = region_at(i);
1733 char* mapped_base = r->mapped_base();
1734 size_t size = r->used_aligned();
1735
1736 if (mapped_base != nullptr) {
1737 if (size > 0 && r->mapped_from_file()) {
1738 aot_log_info(aot)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),
1739 shared_region_name[i]);
1740 if (r->in_reserved_space()) {
1741 // This region was mapped inside a ReservedSpace. Its memory will be freed when the ReservedSpace
1742 // is released. Zero it so that we don't accidentally read its content.
1743 aot_log_info(aot)("Region #%d (%s) is in a reserved space, it will be freed when the space is released", i, shared_region_name[i]);
1744 } else {
1745 os::unmap_memory(mapped_base, size);
1746 }
1747 }
1748 r->set_mapped_base(nullptr);
1749 }
1750 }
1751
1752 void FileMapInfo::assert_mark(bool check) {
1753 if (!check) {
1754 AOTMetaspace::unrecoverable_loading_error("Mark mismatch while restoring from shared file.");
1755 }
1756 }
1757
1758 FileMapInfo* FileMapInfo::_current_info = nullptr;
1759 FileMapInfo* FileMapInfo::_dynamic_archive_info = nullptr;
1760 bool FileMapInfo::_memory_mapping_failed = false;
1761
1762 // Open the shared archive file, read and validate the header
1763 // information (version, boot classpath, etc.). If initialization
1764 // fails, shared spaces are disabled and the file is closed.
1765 //
1766 // Validation of the archive is done in two steps:
1767 //
1768 // [1] validate_header() - done here.
1769 // [2] validate_shared_path_table - this is done later, because the table is in the RO
1770 // region of the archive, which is not mapped yet.
1771 bool FileMapInfo::open_as_input() {
1772 assert(CDSConfig::is_using_archive(), "UseSharedSpaces expected.");
1773 assert(Arguments::has_jimage(), "The shared archive file cannot be used with an exploded module build.");
1774
1775 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1776 // CDS assumes that no classes resolved in vmClasses::resolve_all()
1777 // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
1778 // during the JVMTI "early" stage, so we can still use CDS if
1779 // JvmtiExport::has_early_class_hook_env() is false.
1780 AOTMetaspace::report_loading_error("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
1781 return false;
1782 }
1783
1784 if (!open_for_read() || !init_from_file(_fd) || !validate_header()) {
1785 if (_is_static) {
1786 AOTMetaspace::report_loading_error("Loading static archive failed.");
1787 return false;
1788 } else {
1789 AOTMetaspace::report_loading_error("Loading dynamic archive failed.");
1790 if (AutoCreateSharedArchive) {
1791 CDSConfig::enable_dumping_dynamic_archive(_full_path);
1792 }
1793 return false;
1794 }
1795 }
1796
1797 return true;
1798 }
1799
1800 bool FileMapInfo::validate_aot_class_linking() {
1801 // These checks need to be done after FileMapInfo::initialize(), which gets called before Universe::heap()
1802 // is available.
1803 if (header()->has_aot_linked_classes()) {
1804 const char* archive_type = CDSConfig::type_of_archive_being_loaded();
1805 CDSConfig::set_has_aot_linked_classes(true);
1806 if (JvmtiExport::should_post_class_file_load_hook()) {
1807 aot_log_error(aot)("%s has aot-linked classes. It cannot be used when JVMTI ClassFileLoadHook is in use.",
1808 archive_type);
1809 return false;
1810 }
1811 if (JvmtiExport::has_early_vmstart_env()) {
1812 aot_log_error(aot)("%s has aot-linked classes. It cannot be used when JVMTI early vm start is in use.",
1813 archive_type);
1814 return false;
1815 }
1816 if (!CDSConfig::is_using_full_module_graph()) {
1817 aot_log_error(aot)("%s has aot-linked classes. It cannot be used when archived full module graph is not used.",
1818 archive_type);
1819 return false;
1820 }
1821
1822 const char* prop = Arguments::get_property("java.security.manager");
1823 if (prop != nullptr && strcmp(prop, "disallow") != 0) {
1824 aot_log_error(aot)("%s has aot-linked classes. It cannot be used with -Djava.security.manager=%s.",
1825 archive_type, prop);
1826 return false;
1827 }
1828
1829 #if INCLUDE_JVMTI
1830 if (Arguments::has_jdwp_agent()) {
1831 aot_log_error(aot)("%s has aot-linked classes. It cannot be used with JDWP agent", archive_type);
1832 return false;
1833 }
1834 #endif
1835 }
1836
1837 return true;
1838 }
1839
1840 // The 2 core spaces are RW->RO
1841 FileMapRegion* FileMapInfo::first_core_region() const {
1842 return region_at(AOTMetaspace::rw);
1843 }
1844
1845 FileMapRegion* FileMapInfo::last_core_region() const {
1846 return region_at(AOTMetaspace::ro);
1847 }
1848
1849 void FileMapInfo::print(outputStream* st) const {
1850 header()->print(st);
1851 if (!is_static()) {
1852 dynamic_header()->print(st);
1853 }
1854 }
1855
1856 int FileMapHeader::compute_crc() {
1857 char* start = (char*)this;
1858 // start computing from the field after _header_size to end of base archive name.
1859 char* buf = (char*)&(_generic_header._header_size) + sizeof(_generic_header._header_size);
1860 size_t sz = header_size() - (buf - start);
1861 int crc = ClassLoader::crc32(0, buf, (jint)sz);
1862 return crc;
1863 }
1864
1865 // This function should only be called during run time with UseSharedSpaces enabled.
1866 bool FileMapHeader::validate() {
1867 const char* file_type = CDSConfig::type_of_archive_being_loaded();
1868 if (_obj_alignment != ObjectAlignmentInBytes) {
1869 AOTMetaspace::report_loading_error("The %s's ObjectAlignmentInBytes of %d"
1870 " does not equal the current ObjectAlignmentInBytes of %d.",
1871 file_type, _obj_alignment, ObjectAlignmentInBytes);
1872 return false;
1873 }
1874 if (_compact_strings != CompactStrings) {
1875 AOTMetaspace::report_loading_error("The %s's CompactStrings setting (%s)"
1876 " does not equal the current CompactStrings setting (%s).", file_type,
1877 _compact_strings ? "enabled" : "disabled",
1878 CompactStrings ? "enabled" : "disabled");
1879 return false;
1880 }
1881 bool jvmci_compiler_is_enabled = CompilerConfig::is_jvmci_compiler_enabled();
1882 CompilerType compiler_type = CompilerConfig::compiler_type();
1883 CompilerType archive_compiler_type = CompilerType(_compiler_type);
1884 // JVMCI compiler does different type profiling settigns and generate
1885 // different code. We can't use archive which was produced
1886 // without it and reverse.
1887 // Only allow mix when JIT compilation is disabled.
1888 // Interpreter is used by default when dumping archive.
1889 bool intepreter_is_used = (archive_compiler_type == CompilerType::compiler_none) ||
1890 (compiler_type == CompilerType::compiler_none);
1891 if (!intepreter_is_used &&
1892 jvmci_compiler_is_enabled != (archive_compiler_type == CompilerType::compiler_jvmci)) {
1893 AOTMetaspace::report_loading_error("The %s's JIT compiler setting (%s)"
1894 " does not equal the current setting (%s).", file_type,
1895 compilertype2name(archive_compiler_type), compilertype2name(compiler_type));
1896 return false;
1897 }
1898 if (TrainingData::have_data()) {
1899 if (_type_profile_level != TypeProfileLevel) {
1900 AOTMetaspace::report_loading_error("The %s's TypeProfileLevel setting (%d)"
1901 " does not equal the current TypeProfileLevel setting (%d).", file_type,
1902 _type_profile_level, TypeProfileLevel);
1903 return false;
1904 }
1905 if (_type_profile_args_limit != TypeProfileArgsLimit) {
1906 AOTMetaspace::report_loading_error("The %s's TypeProfileArgsLimit setting (%d)"
1907 " does not equal the current TypeProfileArgsLimit setting (%d).", file_type,
1908 _type_profile_args_limit, TypeProfileArgsLimit);
1909 return false;
1910 }
1911 if (_type_profile_parms_limit != TypeProfileParmsLimit) {
1912 AOTMetaspace::report_loading_error("The %s's TypeProfileParamsLimit setting (%d)"
1913 " does not equal the current TypeProfileParamsLimit setting (%d).", file_type,
1914 _type_profile_args_limit, TypeProfileArgsLimit);
1915 return false;
1916
1917 }
1918 if (_type_profile_width != TypeProfileWidth) {
1919 AOTMetaspace::report_loading_error("The %s's TypeProfileWidth setting (%d)"
1920 " does not equal the current TypeProfileWidth setting (%d).", file_type,
1921 (int)_type_profile_width, (int)TypeProfileWidth);
1922 return false;
1923
1924 }
1925 if (_bci_profile_width != BciProfileWidth) {
1926 AOTMetaspace::report_loading_error("The %s's BciProfileWidth setting (%d)"
1927 " does not equal the current BciProfileWidth setting (%d).", file_type,
1928 (int)_bci_profile_width, (int)BciProfileWidth);
1929 return false;
1930 }
1931 if (_type_profile_casts != TypeProfileCasts) {
1932 AOTMetaspace::report_loading_error("The %s's TypeProfileCasts setting (%s)"
1933 " does not equal the current TypeProfileCasts setting (%s).", file_type,
1934 _type_profile_casts ? "enabled" : "disabled",
1935 TypeProfileCasts ? "enabled" : "disabled");
1936
1937 return false;
1938
1939 }
1940 if (_profile_traps != ProfileTraps) {
1941 AOTMetaspace::report_loading_error("The %s's ProfileTraps setting (%s)"
1942 " does not equal the current ProfileTraps setting (%s).", file_type,
1943 _profile_traps ? "enabled" : "disabled",
1944 ProfileTraps ? "enabled" : "disabled");
1945
1946 return false;
1947 }
1948 if (_spec_trap_limit_extra_entries != SpecTrapLimitExtraEntries) {
1949 AOTMetaspace::report_loading_error("The %s's SpecTrapLimitExtraEntries setting (%d)"
1950 " does not equal the current SpecTrapLimitExtraEntries setting (%d).", file_type,
1951 _spec_trap_limit_extra_entries, SpecTrapLimitExtraEntries);
1952 return false;
1953
1954 }
1955 }
1956
1957 // This must be done after header validation because it might change the
1958 // header data
1959 const char* prop = Arguments::get_property("java.system.class.loader");
1960 if (prop != nullptr) {
1961 if (has_aot_linked_classes()) {
1962 AOTMetaspace::report_loading_error("%s has aot-linked classes. It cannot be used when the "
1963 "java.system.class.loader property is specified.",
1964 CDSConfig::type_of_archive_being_loaded());
1965 return false;
1966 }
1967 aot_log_warning(aot)("Archived non-system classes are disabled because the "
1968 "java.system.class.loader property is specified (value = \"%s\"). "
1969 "To use archived non-system classes, this property must not be set", prop);
1970 _has_platform_or_app_classes = false;
1971 }
1972
1973
1974 if (!_verify_local && BytecodeVerificationLocal) {
1975 // we cannot load boot classes, so there's no point of using the CDS archive
1976 AOTMetaspace::report_loading_error("The %s's BytecodeVerificationLocal setting (%s)"
1977 " does not equal the current BytecodeVerificationLocal setting (%s).", file_type,
1978 _verify_local ? "enabled" : "disabled",
1979 BytecodeVerificationLocal ? "enabled" : "disabled");
1980 return false;
1981 }
1982
1983 // For backwards compatibility, we don't check the BytecodeVerificationRemote setting
1984 // if the archive only contains system classes.
1985 if (_has_platform_or_app_classes
1986 && !_verify_remote // we didn't verify the archived platform/app classes
1987 && BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes
1988 aot_log_info(aot)("The %s was created with less restrictive "
1989 "verification setting than the current setting.", file_type);
1990 // Pretend that we didn't have any archived platform/app classes, so they won't be loaded
1991 // by SystemDictionaryShared.
1992 _has_platform_or_app_classes = false;
1993 }
1994
1995 aot_log_info(aot)("The %s was created with UseCompressedOops = %d, UseCompactObjectHeaders = %d",
1996 file_type, compressed_oops(), compact_headers());
1997 if (compressed_oops() != UseCompressedOops) {
1998 aot_log_warning(aot)("Unable to use %s.\nThe saved state of UseCompressedOops (%d) is "
1999 "different from runtime (%d), CDS will be disabled.", file_type,
2000 compressed_oops(), UseCompressedOops);
2001 return false;
2002 }
2003
2004 if (is_static()) {
2005 const char* err = nullptr;
2006 if (Arguments::is_valhalla_enabled()) {
2007 if (!_has_valhalla_patched_classes) {
2008 err = "not created";
2009 }
2010 } else {
2011 if (_has_valhalla_patched_classes) {
2012 err = "created";
2013 }
2014 }
2015 if (err != nullptr) {
2016 log_warning(cds)("This archive was %s with --enable-preview. It is "
2017 "incompatible with the current JVM setting", err);
2018 return false;
2019 }
2020 }
2021
2022 if (compact_headers() != UseCompactObjectHeaders) {
2023 aot_log_warning(aot)("Unable to use %s.\nThe %s's UseCompactObjectHeaders setting (%s)"
2024 " does not equal the current UseCompactObjectHeaders setting (%s).", file_type, file_type,
2025 _compact_headers ? "enabled" : "disabled",
2026 UseCompactObjectHeaders ? "enabled" : "disabled");
2027 return false;
2028 }
2029
2030 if (!_use_optimized_module_handling && !CDSConfig::is_dumping_final_static_archive()) {
2031 CDSConfig::stop_using_optimized_module_handling();
2032 aot_log_info(aot)("optimized module handling: disabled because archive was created without optimized module handling");
2033 }
2034
2035 if (is_static()) {
2036 // Only the static archive can contain the full module graph.
2037 if (!_has_full_module_graph) {
2038 CDSConfig::stop_using_full_module_graph("archive was created without full module graph");
2039 }
2040 }
2041
2042 return true;
2043 }
2044
2045 bool FileMapInfo::validate_header() {
2046 if (!header()->validate()) {
2047 return false;
2048 }
2049 if (_is_static) {
2050 return true;
2051 } else {
2052 return DynamicArchive::validate(this);
2053 }
2054 }
2055
2056 #if INCLUDE_JVMTI
2057 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = nullptr;
2058
2059 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
2060 if (i == 0) {
2061 // index 0 corresponds to the ClassPathImageEntry which is a globally shared object
2062 // and should never be deleted.
2063 return ClassLoader::get_jrt_entry();
2064 }
2065 ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
2066 if (ent == nullptr) {
2067 const AOTClassLocation* cl = AOTClassLocationConfig::runtime()->class_location_at(i);
2068 const char* path = cl->path();
2069 struct stat st;
2070 if (os::stat(path, &st) != 0) {
2071 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2072 jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);
2073 THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2074 } else {
2075 ent = ClassLoader::create_class_path_entry(THREAD, path, &st);
2076 if (ent == nullptr) {
2077 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2078 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
2079 THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2080 }
2081 }
2082
2083 MutexLocker mu(THREAD, CDSClassFileStream_lock);
2084 if (_classpath_entries_for_jvmti[i] == nullptr) {
2085 _classpath_entries_for_jvmti[i] = ent;
2086 } else {
2087 // Another thread has beat me to creating this entry
2088 delete ent;
2089 ent = _classpath_entries_for_jvmti[i];
2090 }
2091 }
2092
2093 return ent;
2094 }
2095
2096 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
2097 int path_index = ik->shared_classpath_index();
2098 assert(path_index >= 0, "should be called for shared built-in classes only");
2099 assert(path_index < AOTClassLocationConfig::runtime()->length(), "sanity");
2100
2101 ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
2102 assert(cpe != nullptr, "must be");
2103
2104 Symbol* name = ik->name();
2105 const char* const class_name = name->as_C_string();
2106 const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2107 name->utf8_length());
2108 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2109 const AOTClassLocation* cl = AOTClassLocationConfig::runtime()->class_location_at(path_index);
2110 ClassFileStream* cfs;
2111 if (class_loader() != nullptr && cl->is_multi_release_jar()) {
2112 // This class was loaded from a multi-release JAR file during dump time. The
2113 // process for finding its classfile is complex. Let's defer to the Java code
2114 // in java.lang.ClassLoader.
2115 cfs = get_stream_from_class_loader(class_loader, cpe, file_name, CHECK_NULL);
2116 } else {
2117 cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);
2118 }
2119 assert(cfs != nullptr, "must be able to read the classfile data of shared classes for built-in loaders.");
2120 log_debug(aot, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2121 cfs->source(), cfs->length());
2122 return cfs;
2123 }
2124
2125 ClassFileStream* FileMapInfo::get_stream_from_class_loader(Handle class_loader,
2126 ClassPathEntry* cpe,
2127 const char* file_name,
2128 TRAPS) {
2129 JavaValue result(T_OBJECT);
2130 oop class_name = java_lang_String::create_oop_from_str(file_name, THREAD);
2131 Handle h_class_name = Handle(THREAD, class_name);
2132
2133 // byte[] ClassLoader.getResourceAsByteArray(String name)
2134 JavaCalls::call_virtual(&result,
2135 class_loader,
2136 vmClasses::ClassLoader_klass(),
2137 vmSymbols::getResourceAsByteArray_name(),
2138 vmSymbols::getResourceAsByteArray_signature(),
2139 h_class_name,
2140 CHECK_NULL);
2141 assert(result.get_type() == T_OBJECT, "just checking");
2142 oop obj = result.get_oop();
2143 assert(obj != nullptr, "ClassLoader.getResourceAsByteArray should not return null");
2144
2145 // copy from byte[] to a buffer
2146 typeArrayOop ba = typeArrayOop(obj);
2147 jint len = ba->length();
2148 u1* buffer = NEW_RESOURCE_ARRAY(u1, len);
2149 ArrayAccess<>::arraycopy_to_native<>(ba, typeArrayOopDesc::element_offset<jbyte>(0), buffer, len);
2150
2151 return new ClassFileStream(buffer, len, cpe->name());
2152 }
2153 #endif