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