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