1 /*
2 * Copyright (c) 2003, 2023, 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 "precompiled.hpp"
26 #include "cds/archiveBuilder.hpp"
27 #include "cds/archiveHeapLoader.inline.hpp"
28 #include "cds/archiveHeapWriter.hpp"
29 #include "cds/archiveUtils.inline.hpp"
30 #include "cds/cds_globals.hpp"
31 #include "cds/dynamicArchive.hpp"
32 #include "cds/filemap.hpp"
33 #include "cds/heapShared.hpp"
34 #include "cds/metaspaceShared.hpp"
35 #include "classfile/altHashing.hpp"
36 #include "classfile/classFileStream.hpp"
37 #include "classfile/classLoader.hpp"
38 #include "classfile/classLoader.inline.hpp"
39 #include "classfile/classLoaderData.inline.hpp"
40 #include "classfile/classLoaderExt.hpp"
41 #include "classfile/symbolTable.hpp"
42 #include "classfile/systemDictionaryShared.hpp"
43 #include "classfile/vmClasses.hpp"
44 #include "classfile/vmSymbols.hpp"
45 #include "jvm.h"
46 #include "logging/log.hpp"
47 #include "logging/logStream.hpp"
48 #include "logging/logMessage.hpp"
49 #include "memory/iterator.inline.hpp"
50 #include "memory/metadataFactory.hpp"
51 #include "memory/metaspaceClosure.hpp"
52 #include "memory/oopFactory.hpp"
53 #include "memory/universe.hpp"
54 #include "oops/compressedOops.hpp"
55 #include "oops/compressedOops.inline.hpp"
56 #include "oops/objArrayOop.hpp"
57 #include "oops/oop.inline.hpp"
58 #include "prims/jvmtiExport.hpp"
59 #include "runtime/arguments.hpp"
60 #include "runtime/globals_extension.hpp"
61 #include "runtime/java.hpp"
62 #include "runtime/mutexLocker.hpp"
63 #include "runtime/os.hpp"
64 #include "runtime/vm_version.hpp"
65 #include "services/memTracker.hpp"
66 #include "utilities/align.hpp"
67 #include "utilities/bitMap.inline.hpp"
68 #include "utilities/classpathStream.hpp"
69 #include "utilities/defaultStream.hpp"
70 #include "utilities/ostream.hpp"
71 #if INCLUDE_G1GC
72 #include "gc/g1/g1CollectedHeap.hpp"
73 #include "gc/g1/heapRegion.hpp"
74 #endif
75
76 # include <sys/stat.h>
77 # include <errno.h>
78
79 #ifndef O_BINARY // if defined (Win32) use binary files.
80 #define O_BINARY 0 // otherwise do nothing.
81 #endif
82
83 // Fill in the fileMapInfo structure with data about this VM instance.
84
85 // This method copies the vm version info into header_version. If the version is too
86 // long then a truncated version, which has a hash code appended to it, is copied.
87 //
88 // Using a template enables this method to verify that header_version is an array of
89 // length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and
90 // the code that reads the CDS file will both use the same size buffer. Hence, will
91 // use identical truncation. This is necessary for matching of truncated versions.
92 template <int N> static void get_header_version(char (&header_version) [N]) {
93 assert(N == JVM_IDENT_MAX, "Bad header_version size");
94
95 const char *vm_version = VM_Version::internal_vm_info_string();
96 const int version_len = (int)strlen(vm_version);
97
98 memset(header_version, 0, JVM_IDENT_MAX);
99
100 if (version_len < (JVM_IDENT_MAX-1)) {
101 strcpy(header_version, vm_version);
102
103 } else {
104 // Get the hash value. Use a static seed because the hash needs to return the same
105 // value over multiple jvm invocations.
106 uint32_t hash = AltHashing::halfsiphash_32(8191, (const uint8_t*)vm_version, version_len);
107
108 // Truncate the ident, saving room for the 8 hex character hash value.
109 strncpy(header_version, vm_version, JVM_IDENT_MAX-9);
110
111 // Append the hash code as eight hex digits.
112 os::snprintf_checked(&header_version[JVM_IDENT_MAX-9], 9, "%08x", hash);
113 header_version[JVM_IDENT_MAX-1] = 0; // Null terminate.
114 }
115
116 assert(header_version[JVM_IDENT_MAX-1] == 0, "must be");
117 }
118
119 FileMapInfo::FileMapInfo(const char* full_path, bool is_static) :
120 _is_static(is_static), _file_open(false), _is_mapped(false), _fd(-1), _file_offset(0),
121 _full_path(full_path), _base_archive_name(nullptr), _header(nullptr) {
122 if (_is_static) {
123 assert(_current_info == nullptr, "must be singleton"); // not thread safe
124 _current_info = this;
125 } else {
126 assert(_dynamic_archive_info == nullptr, "must be singleton"); // not thread safe
127 _dynamic_archive_info = this;
128 }
129 }
130
131 FileMapInfo::~FileMapInfo() {
132 if (_is_static) {
133 assert(_current_info == this, "must be singleton"); // not thread safe
134 _current_info = nullptr;
135 } else {
136 assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe
137 _dynamic_archive_info = nullptr;
138 }
139
140 if (_header != nullptr) {
141 os::free(_header);
142 }
143
144 if (_file_open) {
145 ::close(_fd);
146 }
147 }
148
149 void FileMapInfo::populate_header(size_t core_region_alignment) {
150 assert(_header == nullptr, "Sanity check");
151 size_t c_header_size;
152 size_t header_size;
153 size_t base_archive_name_size = 0;
154 size_t base_archive_name_offset = 0;
155 size_t longest_common_prefix_size = 0;
156 if (is_static()) {
157 c_header_size = sizeof(FileMapHeader);
158 header_size = c_header_size;
159 } else {
160 // dynamic header including base archive name for non-default base archive
161 c_header_size = sizeof(DynamicArchiveHeader);
162 header_size = c_header_size;
163
164 const char* default_base_archive_name = Arguments::get_default_shared_archive_path();
165 const char* current_base_archive_name = Arguments::GetSharedArchivePath();
166 if (!os::same_files(current_base_archive_name, default_base_archive_name)) {
167 base_archive_name_size = strlen(current_base_archive_name) + 1;
168 header_size += base_archive_name_size;
169 base_archive_name_offset = c_header_size;
170 }
171 }
172 ResourceMark rm;
173 GrowableArray<const char*>* app_cp_array = create_dumptime_app_classpath_array();
174 int len = app_cp_array->length();
175 longest_common_prefix_size = longest_common_app_classpath_prefix_len(len, app_cp_array);
176 _header = (FileMapHeader*)os::malloc(header_size, mtInternal);
177 memset((void*)_header, 0, header_size);
178 _header->populate(this,
179 core_region_alignment,
180 header_size,
181 base_archive_name_size,
182 base_archive_name_offset,
183 longest_common_prefix_size);
184 }
185
186 void FileMapHeader::populate(FileMapInfo *info, size_t core_region_alignment,
187 size_t header_size, size_t base_archive_name_size,
188 size_t base_archive_name_offset, size_t common_app_classpath_prefix_size) {
189 // 1. We require _generic_header._magic to be at the beginning of the file
190 // 2. FileMapHeader also assumes that _generic_header is at the beginning of the file
191 assert(offset_of(FileMapHeader, _generic_header) == 0, "must be");
192 set_header_size((unsigned int)header_size);
193 set_base_archive_name_offset((unsigned int)base_archive_name_offset);
194 set_base_archive_name_size((unsigned int)base_archive_name_size);
195 set_common_app_classpath_prefix_size((unsigned int)common_app_classpath_prefix_size);
196 set_magic(DynamicDumpSharedSpaces ? CDS_DYNAMIC_ARCHIVE_MAGIC : CDS_ARCHIVE_MAGIC);
197 set_version(CURRENT_CDS_ARCHIVE_VERSION);
198
199 if (!info->is_static() && base_archive_name_size != 0) {
200 // copy base archive name
201 copy_base_archive_name(Arguments::GetSharedArchivePath());
202 }
203 _core_region_alignment = core_region_alignment;
204 _obj_alignment = ObjectAlignmentInBytes;
205 _compact_strings = CompactStrings;
206 _compact_headers = UseCompactObjectHeaders;
207 if (DumpSharedSpaces && HeapShared::can_write()) {
208 _narrow_oop_mode = CompressedOops::mode();
209 _narrow_oop_base = CompressedOops::base();
210 _narrow_oop_shift = CompressedOops::shift();
211 if (UseCompressedOops) {
212 _heap_begin = CompressedOops::begin();
213 _heap_end = CompressedOops::end();
214 } else {
215 #if INCLUDE_G1GC
216 address start = (address)G1CollectedHeap::heap()->reserved().start();
217 address end = (address)G1CollectedHeap::heap()->reserved().end();
218 _heap_begin = HeapShared::to_requested_address(start);
219 _heap_end = HeapShared::to_requested_address(end);
220 #endif
221 }
222 }
223 _compressed_oops = UseCompressedOops;
224 _compressed_class_ptrs = UseCompressedClassPointers;
225 _max_heap_size = MaxHeapSize;
226 _narrow_klass_shift = CompressedKlassPointers::shift();
227 _use_optimized_module_handling = MetaspaceShared::use_optimized_module_handling();
228 _use_full_module_graph = MetaspaceShared::use_full_module_graph();
229
230 // The following fields are for sanity checks for whether this archive
231 // will function correctly with this JVM and the bootclasspath it's
232 // invoked with.
233
234 // JVM version string ... changes on each build.
235 get_header_version(_jvm_ident);
236
237 _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index();
238 _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index();
239 _num_module_paths = ClassLoader::num_module_path_entries();
240 _max_used_path_index = ClassLoaderExt::max_used_path_index();
241
242 _verify_local = BytecodeVerificationLocal;
243 _verify_remote = BytecodeVerificationRemote;
244 _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes();
245 _has_non_jar_in_classpath = ClassLoaderExt::has_non_jar_in_classpath();
246 _requested_base_address = (char*)SharedBaseAddress;
247 _mapped_base_address = (char*)SharedBaseAddress;
248 _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent;
249
250 if (!DynamicDumpSharedSpaces) {
251 set_shared_path_table(info->_shared_path_table);
252 }
253 }
254
255 void FileMapHeader::copy_base_archive_name(const char* archive) {
256 assert(base_archive_name_size() != 0, "_base_archive_name_size not set");
257 assert(base_archive_name_offset() != 0, "_base_archive_name_offset not set");
258 assert(header_size() > sizeof(*this), "_base_archive_name_size not included in header size?");
259 memcpy((char*)this + base_archive_name_offset(), archive, base_archive_name_size());
260 }
261
262 void FileMapHeader::print(outputStream* st) {
263 ResourceMark rm;
264
265 st->print_cr("- magic: 0x%08x", magic());
266 st->print_cr("- crc: 0x%08x", crc());
267 st->print_cr("- version: 0x%x", version());
268 st->print_cr("- header_size: " UINT32_FORMAT, header_size());
269 st->print_cr("- common_app_classpath_size: " UINT32_FORMAT, common_app_classpath_prefix_size());
270 st->print_cr("- base_archive_name_offset: " UINT32_FORMAT, base_archive_name_offset());
271 st->print_cr("- base_archive_name_size: " UINT32_FORMAT, base_archive_name_size());
272
273 for (int i = 0; i < NUM_CDS_REGIONS; i++) {
274 FileMapRegion* r = region_at(i);
275 r->print(st, i);
276 }
277 st->print_cr("============ end regions ======== ");
278
279 st->print_cr("- core_region_alignment: " SIZE_FORMAT, _core_region_alignment);
280 st->print_cr("- obj_alignment: %d", _obj_alignment);
281 st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));
282 st->print_cr("- narrow_oop_base: " INTPTR_FORMAT, p2i(_narrow_oop_base));
283 st->print_cr("- narrow_oop_shift %d", _narrow_oop_shift);
284 st->print_cr("- compact_strings: %d", _compact_strings);
285 st->print_cr("- compact_headers: %d", _compact_headers);
286 st->print_cr("- max_heap_size: " UINTX_FORMAT, _max_heap_size);
287 st->print_cr("- narrow_oop_mode: %d", _narrow_oop_mode);
288 st->print_cr("- narrow_klass_shift: %d", _narrow_klass_shift);
289 st->print_cr("- compressed_oops: %d", _compressed_oops);
290 st->print_cr("- compressed_class_ptrs: %d", _compressed_class_ptrs);
291 st->print_cr("- cloned_vtables_offset: " SIZE_FORMAT_X, _cloned_vtables_offset);
292 st->print_cr("- serialized_data_offset: " SIZE_FORMAT_X, _serialized_data_offset);
293 st->print_cr("- heap_begin: " INTPTR_FORMAT, p2i(_heap_begin));
294 st->print_cr("- heap_end: " INTPTR_FORMAT, p2i(_heap_end));
295 st->print_cr("- jvm_ident: %s", _jvm_ident);
296 st->print_cr("- shared_path_table_offset: " SIZE_FORMAT_X, _shared_path_table_offset);
297 st->print_cr("- app_class_paths_start_index: %d", _app_class_paths_start_index);
298 st->print_cr("- app_module_paths_start_index: %d", _app_module_paths_start_index);
299 st->print_cr("- num_module_paths: %d", _num_module_paths);
300 st->print_cr("- max_used_path_index: %d", _max_used_path_index);
301 st->print_cr("- verify_local: %d", _verify_local);
302 st->print_cr("- verify_remote: %d", _verify_remote);
303 st->print_cr("- has_platform_or_app_classes: %d", _has_platform_or_app_classes);
304 st->print_cr("- has_non_jar_in_classpath: %d", _has_non_jar_in_classpath);
305 st->print_cr("- requested_base_address: " INTPTR_FORMAT, p2i(_requested_base_address));
306 st->print_cr("- mapped_base_address: " INTPTR_FORMAT, p2i(_mapped_base_address));
307 st->print_cr("- allow_archiving_with_java_agent:%d", _allow_archiving_with_java_agent);
308 st->print_cr("- use_optimized_module_handling: %d", _use_optimized_module_handling);
309 st->print_cr("- use_full_module_graph %d", _use_full_module_graph);
310 st->print_cr("- ptrmap_size_in_bits: " SIZE_FORMAT, _ptrmap_size_in_bits);
311 }
312
313 void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) {
314 _type = non_existent_entry;
315 set_name(path, CHECK);
316 }
317
318 void SharedClassPathEntry::init(bool is_modules_image,
319 bool is_module_path,
320 ClassPathEntry* cpe, TRAPS) {
321 Arguments::assert_is_dumping_archive();
322 _timestamp = 0;
323 _filesize = 0;
324 _from_class_path_attr = false;
325
326 struct stat st;
327 if (os::stat(cpe->name(), &st) == 0) {
328 if ((st.st_mode & S_IFMT) == S_IFDIR) {
329 _type = dir_entry;
330 } else {
331 // The timestamp of the modules_image is not checked at runtime.
332 if (is_modules_image) {
333 _type = modules_image_entry;
334 } else {
335 _type = jar_entry;
336 _timestamp = st.st_mtime;
337 _from_class_path_attr = cpe->from_class_path_attr();
338 }
339 _filesize = st.st_size;
340 _is_module_path = is_module_path;
341 }
342 } else {
343 // The file/dir must exist, or it would not have been added
344 // into ClassLoader::classpath_entry().
345 //
346 // If we can't access a jar file in the boot path, then we can't
347 // make assumptions about where classes get loaded from.
348 log_error(cds)("Unable to open file %s.", cpe->name());
349 MetaspaceShared::unrecoverable_loading_error();
350 }
351
352 // No need to save the name of the module file, as it will be computed at run time
353 // to allow relocation of the JDK directory.
354 const char* name = is_modules_image ? "" : cpe->name();
355 set_name(name, CHECK);
356 }
357
358 void SharedClassPathEntry::set_name(const char* name, TRAPS) {
359 size_t len = strlen(name) + 1;
360 _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, CHECK);
361 strcpy(_name->data(), name);
362 }
363
364 void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) {
365 assert(ent != nullptr, "sanity");
366 _type = ent->_type;
367 _is_module_path = ent->_is_module_path;
368 _timestamp = ent->_timestamp;
369 _filesize = ent->_filesize;
370 _from_class_path_attr = ent->_from_class_path_attr;
371 set_name(ent->name(), CHECK);
372
373 if (ent->is_jar() && ent->manifest() != nullptr) {
374 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
375 ent->manifest_size(),
376 CHECK);
377 char* p = (char*)(buf->data());
378 memcpy(p, ent->manifest(), ent->manifest_size());
379 set_manifest(buf);
380 }
381 }
382
383 const char* SharedClassPathEntry::name() const {
384 if (UseSharedSpaces && is_modules_image()) {
385 // In order to validate the runtime modules image file size against the archived
386 // size information, we need to obtain the runtime modules image path. The recorded
387 // dump time modules image path in the archive may be different from the runtime path
388 // if the JDK image has beed moved after generating the archive.
389 return ClassLoader::get_jrt_entry()->name();
390 } else {
391 return _name->data();
392 }
393 }
394
395 bool SharedClassPathEntry::validate(bool is_class_path) const {
396 assert(UseSharedSpaces, "runtime only");
397
398 struct stat st;
399 const char* name = this->name();
400
401 bool ok = true;
402 log_info(class, path)("checking shared classpath entry: %s", name);
403 if (os::stat(name, &st) != 0 && is_class_path) {
404 // If the archived module path entry does not exist at runtime, it is not fatal
405 // (no need to invalid the shared archive) because the shared runtime visibility check
406 // filters out any archived module classes that do not have a matching runtime
407 // module path location.
408 log_warning(cds)("Required classpath entry does not exist: %s", name);
409 ok = false;
410 } else if (is_dir()) {
411 if (!os::dir_is_empty(name)) {
412 log_warning(cds)("directory is not empty: %s", name);
413 ok = false;
414 }
415 } else if ((has_timestamp() && _timestamp != st.st_mtime) ||
416 _filesize != st.st_size) {
417 ok = false;
418 if (PrintSharedArchiveAndExit) {
419 log_warning(cds)(_timestamp != st.st_mtime ?
420 "Timestamp mismatch" :
421 "File size mismatch");
422 } else {
423 const char* bad_jar_msg = "A jar file is not the one used while building the shared archive file:";
424 log_warning(cds)("%s %s", bad_jar_msg, name);
425 if (!log_is_enabled(Info, cds)) {
426 log_warning(cds)("%s %s", bad_jar_msg, name);
427 }
428 if (_timestamp != st.st_mtime) {
429 log_warning(cds)("%s timestamp has changed.", name);
430 } else {
431 log_warning(cds)("%s size has changed.", name);
432 }
433 }
434 }
435
436 if (PrintSharedArchiveAndExit && !ok) {
437 // If PrintSharedArchiveAndExit is enabled, don't report failure to the
438 // caller. Please see above comments for more details.
439 ok = true;
440 MetaspaceShared::set_archive_loading_failed();
441 }
442 return ok;
443 }
444
445 bool SharedClassPathEntry::check_non_existent() const {
446 assert(_type == non_existent_entry, "must be");
447 log_info(class, path)("should be non-existent: %s", name());
448 struct stat st;
449 if (os::stat(name(), &st) != 0) {
450 log_info(class, path)("ok");
451 return true; // file doesn't exist
452 } else {
453 return false;
454 }
455 }
456
457 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) {
458 it->push(&_name);
459 it->push(&_manifest);
460 }
461
462 void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) {
463 it->push(&_entries);
464 }
465
466 void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, TRAPS) {
467 const int num_entries =
468 ClassLoader::num_boot_classpath_entries() +
469 ClassLoader::num_app_classpath_entries() +
470 ClassLoader::num_module_path_entries() +
471 FileMapInfo::num_non_existent_class_paths();
472 _entries = MetadataFactory::new_array<SharedClassPathEntry*>(loader_data, num_entries, CHECK);
473 for (int i = 0; i < num_entries; i++) {
474 SharedClassPathEntry* ent =
475 new (loader_data, SharedClassPathEntry::size(), MetaspaceObj::SharedClassPathEntryType, THREAD) SharedClassPathEntry;
476 _entries->at_put(i, ent);
477 }
478 }
479
480 void FileMapInfo::allocate_shared_path_table(TRAPS) {
481 Arguments::assert_is_dumping_archive();
482
483 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
484 ClassPathEntry* jrt = ClassLoader::get_jrt_entry();
485
486 assert(jrt != nullptr,
487 "No modular java runtime image present when allocating the CDS classpath entry table");
488
489 _shared_path_table.dumptime_init(loader_data, CHECK);
490
491 // 1. boot class path
492 int i = 0;
493 i = add_shared_classpaths(i, "boot", jrt, CHECK);
494 i = add_shared_classpaths(i, "app", ClassLoader::app_classpath_entries(), CHECK);
495 i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), CHECK);
496
497 for (int x = 0; x < num_non_existent_class_paths(); x++, i++) {
498 const char* path = _non_existent_class_paths->at(x);
499 shared_path(i)->init_as_non_existent(path, CHECK);
500 }
501
502 assert(i == _shared_path_table.size(), "number of shared path entry mismatch");
503 }
504
505 int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) {
506 while (cpe != nullptr) {
507 bool is_jrt = (cpe == ClassLoader::get_jrt_entry());
508 bool is_module_path = i >= ClassLoaderExt::app_module_paths_start_index();
509 const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir"));
510 log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name());
511 SharedClassPathEntry* ent = shared_path(i);
512 ent->init(is_jrt, is_module_path, cpe, CHECK_0);
513 if (cpe->is_jar_file()) {
514 update_jar_manifest(cpe, ent, CHECK_0);
515 }
516 if (is_jrt) {
517 cpe = ClassLoader::get_next_boot_classpath_entry(cpe);
518 } else {
519 cpe = cpe->next();
520 }
521 i++;
522 }
523
524 return i;
525 }
526
527 void FileMapInfo::check_nonempty_dir_in_shared_path_table() {
528 Arguments::assert_is_dumping_archive();
529
530 bool has_nonempty_dir = false;
531
532 int last = _shared_path_table.size() - 1;
533 if (last > ClassLoaderExt::max_used_path_index()) {
534 // no need to check any path beyond max_used_path_index
535 last = ClassLoaderExt::max_used_path_index();
536 }
537
538 for (int i = 0; i <= last; i++) {
539 SharedClassPathEntry *e = shared_path(i);
540 if (e->is_dir()) {
541 const char* path = e->name();
542 if (!os::dir_is_empty(path)) {
543 log_error(cds)("Error: non-empty directory '%s'", path);
544 has_nonempty_dir = true;
545 }
546 }
547 }
548
549 if (has_nonempty_dir) {
550 ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", nullptr);
551 }
552 }
553
554 void FileMapInfo::record_non_existent_class_path_entry(const char* path) {
555 Arguments::assert_is_dumping_archive();
556 log_info(class, path)("non-existent Class-Path entry %s", path);
557 if (_non_existent_class_paths == nullptr) {
558 _non_existent_class_paths = new (mtClass) GrowableArray<const char*>(10, mtClass);
559 }
560 _non_existent_class_paths->append(os::strdup(path));
561 }
562
563 int FileMapInfo::num_non_existent_class_paths() {
564 Arguments::assert_is_dumping_archive();
565 if (_non_existent_class_paths != nullptr) {
566 return _non_existent_class_paths->length();
567 } else {
568 return 0;
569 }
570 }
571
572 int FileMapInfo::get_module_shared_path_index(Symbol* location) {
573 if (location->starts_with("jrt:", 4) && get_number_of_shared_paths() > 0) {
574 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
575 return 0;
576 }
577
578 if (ClassLoaderExt::app_module_paths_start_index() >= get_number_of_shared_paths()) {
579 // The archive(s) were created without --module-path option
580 return -1;
581 }
582
583 if (!location->starts_with("file:", 5)) {
584 return -1;
585 }
586
587 // skip_uri_protocol was also called during dump time -- see ClassLoaderExt::process_module_table()
588 ResourceMark rm;
589 const char* file = ClassLoader::skip_uri_protocol(location->as_C_string());
590 for (int i = ClassLoaderExt::app_module_paths_start_index(); i < get_number_of_shared_paths(); i++) {
591 SharedClassPathEntry* ent = shared_path(i);
592 assert(ent->in_named_module(), "must be");
593 bool cond = strcmp(file, ent->name()) == 0;
594 log_debug(class, path)("get_module_shared_path_index (%d) %s : %s = %s", i,
595 location->as_C_string(), ent->name(), cond ? "same" : "different");
596 if (cond) {
597 return i;
598 }
599 }
600
601 return -1;
602 }
603
604 class ManifestStream: public ResourceObj {
605 private:
606 u1* _buffer_start; // Buffer bottom
607 u1* _buffer_end; // Buffer top (one past last element)
608 u1* _current; // Current buffer position
609
610 public:
611 // Constructor
612 ManifestStream(u1* buffer, int length) : _buffer_start(buffer),
613 _current(buffer) {
614 _buffer_end = buffer + length;
615 }
616
617 static bool is_attr(u1* attr, const char* name) {
618 return strncmp((const char*)attr, name, strlen(name)) == 0;
619 }
620
621 static char* copy_attr(u1* value, size_t len) {
622 char* buf = NEW_RESOURCE_ARRAY(char, len + 1);
623 strncpy(buf, (char*)value, len);
624 buf[len] = 0;
625 return buf;
626 }
627 };
628
629 void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) {
630 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
631 ResourceMark rm(THREAD);
632 jint manifest_size;
633
634 assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file");
635 char* manifest = ClassLoaderExt::read_manifest(THREAD, cpe, &manifest_size);
636 if (manifest != nullptr) {
637 ManifestStream* stream = new ManifestStream((u1*)manifest,
638 manifest_size);
639 // Copy the manifest into the shared archive
640 manifest = ClassLoaderExt::read_raw_manifest(THREAD, cpe, &manifest_size);
641 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data,
642 manifest_size,
643 CHECK);
644 char* p = (char*)(buf->data());
645 memcpy(p, manifest, manifest_size);
646 ent->set_manifest(buf);
647 }
648 }
649
650 char* FileMapInfo::skip_first_path_entry(const char* path) {
651 size_t path_sep_len = strlen(os::path_separator());
652 char* p = strstr((char*)path, os::path_separator());
653 if (p != nullptr) {
654 debug_only( {
655 size_t image_name_len = strlen(MODULES_IMAGE_NAME);
656 assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0,
657 "first entry must be the modules image");
658 } );
659 p += path_sep_len;
660 } else {
661 debug_only( {
662 assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME),
663 "first entry must be the modules image");
664 } );
665 }
666 return p;
667 }
668
669 int FileMapInfo::num_paths(const char* path) {
670 if (path == nullptr) {
671 return 0;
672 }
673 int npaths = 1;
674 char* p = (char*)path;
675 while (p != nullptr) {
676 char* prev = p;
677 p = strstr((char*)p, os::path_separator());
678 if (p != nullptr) {
679 p++;
680 // don't count empty path
681 if ((p - prev) > 1) {
682 npaths++;
683 }
684 }
685 }
686 return npaths;
687 }
688
689 // Returns true if a path within the paths exists and has non-zero size.
690 bool FileMapInfo::check_paths_existence(const char* paths) {
691 ClasspathStream cp_stream(paths);
692 bool exist = false;
693 struct stat st;
694 while (cp_stream.has_next()) {
695 const char* path = cp_stream.get_next();
696 if (os::stat(path, &st) == 0 && st.st_size > 0) {
697 exist = true;
698 break;
699 }
700 }
701 return exist;
702 }
703
704 GrowableArray<const char*>* FileMapInfo::create_dumptime_app_classpath_array() {
705 Arguments::assert_is_dumping_archive();
706 GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);
707 ClassPathEntry* cpe = ClassLoader::app_classpath_entries();
708 while (cpe != nullptr) {
709 path_array->append(cpe->name());
710 cpe = cpe->next();
711 }
712 return path_array;
713 }
714
715 GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) {
716 GrowableArray<const char*>* path_array = new GrowableArray<const char*>(10);
717 JavaThread* current = JavaThread::current();
718 ClasspathStream cp_stream(paths);
719 bool non_jar_in_cp = header()->has_non_jar_in_classpath();
720 while (cp_stream.has_next()) {
721 const char* path = cp_stream.get_next();
722 if (!non_jar_in_cp) {
723 struct stat st;
724 if (os::stat(path, &st) == 0) {
725 path_array->append(path);
726 }
727 } else {
728 const char* canonical_path = ClassLoader::get_canonical_path(path, current);
729 if (canonical_path != nullptr) {
730 char* error_msg = nullptr;
731 jzfile* zip = ClassLoader::open_zip_file(canonical_path, &error_msg, current);
732 if (zip != nullptr && error_msg == nullptr) {
733 path_array->append(path);
734 }
735 }
736 }
737 }
738 return path_array;
739 }
740
741 bool FileMapInfo::classpath_failure(const char* msg, const char* name) {
742 ClassLoader::trace_class_path(msg, name);
743 if (PrintSharedArchiveAndExit) {
744 MetaspaceShared::set_archive_loading_failed();
745 }
746 return false;
747 }
748
749 unsigned int FileMapInfo::longest_common_app_classpath_prefix_len(int num_paths,
750 GrowableArray<const char*>* rp_array) {
751 if (num_paths == 0) {
752 return 0;
753 }
754 unsigned int pos;
755 for (pos = 0; ; pos++) {
756 for (int i = 0; i < num_paths; i++) {
757 if (rp_array->at(i)[pos] != '\0' && rp_array->at(i)[pos] == rp_array->at(0)[pos]) {
758 continue;
759 }
760 // search backward for the pos before the file separator char
761 while (pos > 0) {
762 if (rp_array->at(0)[--pos] == *os::file_separator()) {
763 return pos + 1;
764 }
765 }
766 return 0;
767 }
768 }
769 return 0;
770 }
771
772 bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array,
773 unsigned int dumptime_prefix_len, unsigned int runtime_prefix_len) {
774 int i = 0;
775 int j = shared_path_start_idx;
776 while (i < num_paths) {
777 while (shared_path(j)->from_class_path_attr()) {
778 // shared_path(j) was expanded from the JAR file attribute "Class-Path:"
779 // during dump time. It's not included in the -classpath VM argument.
780 j++;
781 }
782 assert(strlen(shared_path(j)->name()) > (size_t)dumptime_prefix_len, "sanity");
783 const char* dumptime_path = shared_path(j)->name() + dumptime_prefix_len;
784 assert(strlen(rp_array->at(i)) > (size_t)runtime_prefix_len, "sanity");
785 const char* runtime_path = rp_array->at(i) + runtime_prefix_len;
786 if (!os::same_files(dumptime_path, runtime_path)) {
787 return true;
788 }
789 i++;
790 j++;
791 }
792 return false;
793 }
794
795 bool FileMapInfo::validate_boot_class_paths() {
796 //
797 // - Archive contains boot classes only - relaxed boot path check:
798 // Extra path elements appended to the boot path at runtime are allowed.
799 //
800 // - Archive contains application or platform classes - strict boot path check:
801 // Validate the entire runtime boot path, which must be compatible
802 // with the dump time boot path. Appending boot path at runtime is not
803 // allowed.
804 //
805
806 // The first entry in boot path is the modules_image (guaranteed by
807 // ClassLoader::setup_boot_search_path()). Skip the first entry. The
808 // path of the runtime modules_image may be different from the dump
809 // time path (e.g. the JDK image is copied to a different location
810 // after generating the shared archive), which is acceptable. For most
811 // common cases, the dump time boot path might contain modules_image only.
812 char* runtime_boot_path = Arguments::get_boot_class_path();
813 char* rp = skip_first_path_entry(runtime_boot_path);
814 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
815 int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image
816 bool mismatch = false;
817
818 bool relaxed_check = !header()->has_platform_or_app_classes();
819 if (dp_len == 0 && rp == nullptr) {
820 return true; // ok, both runtime and dump time boot paths have modules_images only
821 } else if (dp_len == 0 && rp != nullptr) {
822 if (relaxed_check) {
823 return true; // ok, relaxed check, runtime has extra boot append path entries
824 } else {
825 ResourceMark rm;
826 if (check_paths_existence(rp)) {
827 // If a path exists in the runtime boot paths, it is considered a mismatch
828 // since there's no boot path specified during dump time.
829 mismatch = true;
830 }
831 }
832 } else if (dp_len > 0 && rp != nullptr) {
833 int num;
834 ResourceMark rm;
835 GrowableArray<const char*>* rp_array = create_path_array(rp);
836 int rp_len = rp_array->length();
837 if (rp_len >= dp_len) {
838 if (relaxed_check) {
839 // only check the leading entries in the runtime boot path, up to
840 // the length of the dump time boot path
841 num = dp_len;
842 } else {
843 // check the full runtime boot path, must match with dump time
844 num = rp_len;
845 }
846 mismatch = check_paths(1, num, rp_array, 0, 0);
847 } else {
848 // create_path_array() ignores non-existing paths. Although the dump time and runtime boot classpath lengths
849 // are the same initially, after the call to create_path_array(), the runtime boot classpath length could become
850 // shorter. We consider boot classpath mismatch in this case.
851 mismatch = true;
852 }
853 }
854
855 if (mismatch) {
856 // The paths are different
857 return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path);
858 }
859 return true;
860 }
861
862 bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) {
863 const char *appcp = Arguments::get_appclasspath();
864 assert(appcp != nullptr, "null app classpath");
865 int rp_len = num_paths(appcp);
866 bool mismatch = false;
867 if (rp_len < shared_app_paths_len) {
868 return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp);
869 }
870 if (shared_app_paths_len != 0 && rp_len != 0) {
871 // Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar.
872 ResourceMark rm;
873 GrowableArray<const char*>* rp_array = create_path_array(appcp);
874 if (rp_array->length() == 0) {
875 // None of the jar file specified in the runtime -cp exists.
876 return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp);
877 }
878 if (rp_array->length() < shared_app_paths_len) {
879 // create_path_array() ignores non-existing paths. Although the dump time and runtime app classpath lengths
880 // are the same initially, after the call to create_path_array(), the runtime app classpath length could become
881 // shorter. We consider app classpath mismatch in this case.
882 return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
883 }
884
885 // Handling of non-existent entries in the classpath: we eliminate all the non-existent
886 // entries from both the dump time classpath (ClassLoader::update_class_path_entry_list)
887 // and the runtime classpath (FileMapInfo::create_path_array), and check the remaining
888 // entries. E.g.:
889 //
890 // dump : -cp a.jar:NE1:NE2:b.jar -> a.jar:b.jar -> recorded in archive.
891 // run 1: -cp NE3:a.jar:NE4:b.jar -> a.jar:b.jar -> matched
892 // run 2: -cp x.jar:NE4:b.jar -> x.jar:b.jar -> mismatched
893
894 int j = header()->app_class_paths_start_index();
895 mismatch = check_paths(j, shared_app_paths_len, rp_array, 0, 0);
896 if (mismatch) {
897 // To facilitate app deployment, we allow the JAR files to be moved *together* to
898 // a different location, as long as they are still stored under the same directory
899 // structure. E.g., the following is OK.
900 // java -Xshare:dump -cp /a/Foo.jar:/a/b/Bar.jar ...
901 // java -Xshare:auto -cp /x/y/Foo.jar:/x/y/b/Bar.jar ...
902 unsigned int dumptime_prefix_len = header()->common_app_classpath_prefix_size();
903 unsigned int runtime_prefix_len = longest_common_app_classpath_prefix_len(shared_app_paths_len, rp_array);
904 if (dumptime_prefix_len != 0 || runtime_prefix_len != 0) {
905 log_info(class, path)("LCP length for app classpath (dumptime: %u, runtime: %u)",
906 dumptime_prefix_len, runtime_prefix_len);
907 mismatch = check_paths(j, shared_app_paths_len, rp_array,
908 dumptime_prefix_len, runtime_prefix_len);
909 }
910 if (mismatch) {
911 return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp);
912 }
913 }
914 }
915 return true;
916 }
917
918 void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) {
919 LogTarget(Info, class, path) lt;
920 if (lt.is_enabled()) {
921 LogStream ls(lt);
922 ls.print("%s", msg);
923 const char* prefix = "";
924 for (int i = start_idx; i < end_idx; i++) {
925 ls.print("%s%s", prefix, shared_path(i)->name());
926 prefix = os::path_separator();
927 }
928 ls.cr();
929 }
930 }
931
932 bool FileMapInfo::check_module_paths() {
933 const char* rp = Arguments::get_property("jdk.module.path");
934 int num_paths = Arguments::num_archives(rp);
935 if (num_paths != header()->num_module_paths()) {
936 return false;
937 }
938 ResourceMark rm;
939 GrowableArray<const char*>* rp_array = create_path_array(rp);
940 return check_paths(header()->app_module_paths_start_index(), num_paths, rp_array, 0, 0);
941 }
942
943 bool FileMapInfo::validate_shared_path_table() {
944 assert(UseSharedSpaces, "runtime only");
945
946 _validating_shared_path_table = true;
947
948 // Load the shared path table info from the archive header
949 _shared_path_table = header()->shared_path_table();
950 if (DynamicDumpSharedSpaces) {
951 // Only support dynamic dumping with the usage of the default CDS archive
952 // or a simple base archive.
953 // If the base layer archive contains additional path component besides
954 // the runtime image and the -cp, dynamic dumping is disabled.
955 //
956 // When dynamic archiving is enabled, the _shared_path_table is overwritten
957 // to include the application path and stored in the top layer archive.
958 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
959 if (header()->app_class_paths_start_index() > 1) {
960 DynamicDumpSharedSpaces = false;
961 log_warning(cds)(
962 "Dynamic archiving is disabled because base layer archive has appended boot classpath");
963 }
964 if (header()->num_module_paths() > 0) {
965 if (!check_module_paths()) {
966 DynamicDumpSharedSpaces = false;
967 log_warning(cds)(
968 "Dynamic archiving is disabled because base layer archive has a different module path");
969 }
970 }
971 }
972
973 log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index());
974 log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index());
975
976 int module_paths_start_index = header()->app_module_paths_start_index();
977 int shared_app_paths_len = 0;
978
979 // validate the path entries up to the _max_used_path_index
980 for (int i=0; i < header()->max_used_path_index() + 1; i++) {
981 if (i < module_paths_start_index) {
982 if (shared_path(i)->validate()) {
983 // Only count the app class paths not from the "Class-path" attribute of a jar manifest.
984 if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) {
985 shared_app_paths_len++;
986 }
987 log_info(class, path)("ok");
988 } else {
989 if (_dynamic_archive_info != nullptr && _dynamic_archive_info->_is_static) {
990 assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
991 }
992 return false;
993 }
994 } else if (i >= module_paths_start_index) {
995 if (shared_path(i)->validate(false /* not a class path entry */)) {
996 log_info(class, path)("ok");
997 } else {
998 if (_dynamic_archive_info != nullptr && _dynamic_archive_info->_is_static) {
999 assert(!UseSharedSpaces, "UseSharedSpaces should be disabled");
1000 }
1001 return false;
1002 }
1003 }
1004 }
1005
1006 if (header()->max_used_path_index() == 0) {
1007 // default archive only contains the module image in the bootclasspath
1008 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image");
1009 } else {
1010 if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) {
1011 const char* mismatch_msg = "shared class paths mismatch";
1012 const char* hint_msg = log_is_enabled(Info, class, path) ?
1013 "" : " (hint: enable -Xlog:class+path=info to diagnose the failure)";
1014 if (RequireSharedSpaces) {
1015 log_error(cds)("%s%s", mismatch_msg, hint_msg);
1016 MetaspaceShared::unrecoverable_loading_error();
1017 } else {
1018 log_warning(cds)("%s%s", mismatch_msg, hint_msg);
1019 }
1020 return false;
1021 }
1022 }
1023
1024 validate_non_existent_class_paths();
1025
1026 _validating_shared_path_table = false;
1027
1028 #if INCLUDE_JVMTI
1029 if (_classpath_entries_for_jvmti != nullptr) {
1030 os::free(_classpath_entries_for_jvmti);
1031 }
1032 size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths();
1033 _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass);
1034 memset((void*)_classpath_entries_for_jvmti, 0, sz);
1035 #endif
1036
1037 return true;
1038 }
1039
1040 void FileMapInfo::validate_non_existent_class_paths() {
1041 // All of the recorded non-existent paths came from the Class-Path: attribute from the JAR
1042 // files on the app classpath. If any of these are found to exist during runtime,
1043 // it will change how classes are loading for the app loader. For safety, disable
1044 // loading of archived platform/app classes (currently there's no way to disable just the
1045 // app classes).
1046
1047 assert(UseSharedSpaces, "runtime only");
1048 for (int i = header()->app_module_paths_start_index() + header()->num_module_paths();
1049 i < get_number_of_shared_paths();
1050 i++) {
1051 SharedClassPathEntry* ent = shared_path(i);
1052 if (!ent->check_non_existent()) {
1053 log_warning(cds)("Archived non-system classes are disabled because the "
1054 "file %s exists", ent->name());
1055 header()->set_has_platform_or_app_classes(false);
1056 }
1057 }
1058 }
1059
1060 // A utility class for reading/validating the GenericCDSFileMapHeader portion of
1061 // a CDS archive's header. The file header of all CDS archives with versions from
1062 // CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION (12) are guaranteed to always start
1063 // with GenericCDSFileMapHeader. This makes it possible to read important information
1064 // from a CDS archive created by a different version of HotSpot, so that we can
1065 // automatically regenerate the archive as necessary (JDK-8261455).
1066 class FileHeaderHelper {
1067 int _fd;
1068 bool _is_valid;
1069 bool _is_static;
1070 GenericCDSFileMapHeader* _header;
1071 const char* _archive_name;
1072 const char* _base_archive_name;
1073
1074 public:
1075 FileHeaderHelper(const char* archive_name, bool is_static) {
1076 _fd = -1;
1077 _is_valid = false;
1078 _header = nullptr;
1079 _base_archive_name = nullptr;
1080 _archive_name = archive_name;
1081 _is_static = is_static;
1082 }
1083
1084 ~FileHeaderHelper() {
1085 if (_header != nullptr) {
1086 FREE_C_HEAP_ARRAY(char, _header);
1087 }
1088 if (_fd != -1) {
1089 ::close(_fd);
1090 }
1091 }
1092
1093 bool initialize() {
1094 assert(_archive_name != nullptr, "Archive name is null");
1095 _fd = os::open(_archive_name, O_RDONLY | O_BINARY, 0);
1096 if (_fd < 0) {
1097 log_info(cds)("Specified shared archive not found (%s)", _archive_name);
1098 return false;
1099 }
1100 return initialize(_fd);
1101 }
1102
1103 // for an already opened file, do not set _fd
1104 bool initialize(int fd) {
1105 assert(_archive_name != nullptr, "Archive name is null");
1106 assert(fd != -1, "Archive must be opened already");
1107 // First read the generic header so we know the exact size of the actual header.
1108 GenericCDSFileMapHeader gen_header;
1109 size_t size = sizeof(GenericCDSFileMapHeader);
1110 os::lseek(fd, 0, SEEK_SET);
1111 size_t n = ::read(fd, (void*)&gen_header, (unsigned int)size);
1112 if (n != size) {
1113 log_warning(cds)("Unable to read generic CDS file map header from shared archive");
1114 return false;
1115 }
1116
1117 if (gen_header._magic != CDS_ARCHIVE_MAGIC &&
1118 gen_header._magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1119 log_warning(cds)("The shared archive file has a bad magic number: %#x", gen_header._magic);
1120 return false;
1121 }
1122
1123 if (gen_header._version < CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION) {
1124 log_warning(cds)("Cannot handle shared archive file version 0x%x. Must be at least 0x%x.",
1125 gen_header._version, CDS_GENERIC_HEADER_SUPPORTED_MIN_VERSION);
1126 return false;
1127 }
1128
1129 if (gen_header._version != CURRENT_CDS_ARCHIVE_VERSION) {
1130 log_warning(cds)("The shared archive file version 0x%x does not match the required version 0x%x.",
1131 gen_header._version, CURRENT_CDS_ARCHIVE_VERSION);
1132 }
1133
1134 size_t filelen = os::lseek(fd, 0, SEEK_END);
1135 if (gen_header._header_size >= filelen) {
1136 log_warning(cds)("Archive file header larger than archive file");
1137 return false;
1138 }
1139
1140 // Read the actual header and perform more checks
1141 size = gen_header._header_size;
1142 _header = (GenericCDSFileMapHeader*)NEW_C_HEAP_ARRAY(char, size, mtInternal);
1143 os::lseek(fd, 0, SEEK_SET);
1144 n = ::read(fd, (void*)_header, (unsigned int)size);
1145 if (n != size) {
1146 log_warning(cds)("Unable to read actual CDS file map header from shared archive");
1147 return false;
1148 }
1149
1150 if (!check_header_crc()) {
1151 return false;
1152 }
1153
1154 if (!check_and_init_base_archive_name()) {
1155 return false;
1156 }
1157
1158 // All fields in the GenericCDSFileMapHeader has been validated.
1159 _is_valid = true;
1160 return true;
1161 }
1162
1163 GenericCDSFileMapHeader* get_generic_file_header() {
1164 assert(_header != nullptr && _is_valid, "must be a valid archive file");
1165 return _header;
1166 }
1167
1168 const char* base_archive_name() {
1169 assert(_header != nullptr && _is_valid, "must be a valid archive file");
1170 return _base_archive_name;
1171 }
1172
1173 private:
1174 bool check_header_crc() const {
1175 if (VerifySharedSpaces) {
1176 FileMapHeader* header = (FileMapHeader*)_header;
1177 int actual_crc = header->compute_crc();
1178 if (actual_crc != header->crc()) {
1179 log_info(cds)("_crc expected: %d", header->crc());
1180 log_info(cds)(" actual: %d", actual_crc);
1181 log_warning(cds)("Header checksum verification failed.");
1182 return false;
1183 }
1184 }
1185 return true;
1186 }
1187
1188 bool check_and_init_base_archive_name() {
1189 unsigned int name_offset = _header->_base_archive_name_offset;
1190 unsigned int name_size = _header->_base_archive_name_size;
1191 unsigned int header_size = _header->_header_size;
1192
1193 if (name_offset + name_size < name_offset) {
1194 log_warning(cds)("base_archive_name offset/size overflow: " UINT32_FORMAT "/" UINT32_FORMAT,
1195 name_offset, name_size);
1196 return false;
1197 }
1198 if (_header->_magic == CDS_ARCHIVE_MAGIC) {
1199 if (name_offset != 0) {
1200 log_warning(cds)("static shared archive must have zero _base_archive_name_offset");
1201 return false;
1202 }
1203 if (name_size != 0) {
1204 log_warning(cds)("static shared archive must have zero _base_archive_name_size");
1205 return false;
1206 }
1207 } else {
1208 assert(_header->_magic == CDS_DYNAMIC_ARCHIVE_MAGIC, "must be");
1209 if ((name_size == 0 && name_offset != 0) ||
1210 (name_size != 0 && name_offset == 0)) {
1211 // If either is zero, both must be zero. This indicates that we are using the default base archive.
1212 log_warning(cds)("Invalid base_archive_name offset/size: " UINT32_FORMAT "/" UINT32_FORMAT,
1213 name_offset, name_size);
1214 return false;
1215 }
1216 if (name_size > 0) {
1217 if (name_offset + name_size > header_size) {
1218 log_warning(cds)("Invalid base_archive_name offset/size (out of range): "
1219 UINT32_FORMAT " + " UINT32_FORMAT " > " UINT32_FORMAT ,
1220 name_offset, name_size, header_size);
1221 return false;
1222 }
1223 const char* name = ((const char*)_header) + _header->_base_archive_name_offset;
1224 if (name[name_size - 1] != '\0' || strlen(name) != name_size - 1) {
1225 log_warning(cds)("Base archive name is damaged");
1226 return false;
1227 }
1228 if (!os::file_exists(name)) {
1229 log_warning(cds)("Base archive %s does not exist", name);
1230 return false;
1231 }
1232 _base_archive_name = name;
1233 }
1234 }
1235
1236 return true;
1237 }
1238 };
1239
1240 // Return value:
1241 // false:
1242 // <archive_name> is not a valid archive. *base_archive_name is set to null.
1243 // true && (*base_archive_name) == nullptr:
1244 // <archive_name> is a valid static archive.
1245 // true && (*base_archive_name) != nullptr:
1246 // <archive_name> is a valid dynamic archive.
1247 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name,
1248 char** base_archive_name) {
1249 FileHeaderHelper file_helper(archive_name, false);
1250 *base_archive_name = nullptr;
1251
1252 if (!file_helper.initialize()) {
1253 return false;
1254 }
1255 GenericCDSFileMapHeader* header = file_helper.get_generic_file_header();
1256 if (header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1257 assert(header->_magic == CDS_ARCHIVE_MAGIC, "must be");
1258 if (AutoCreateSharedArchive) {
1259 log_warning(cds)("AutoCreateSharedArchive is ignored because %s is a static archive", archive_name);
1260 }
1261 return true;
1262 }
1263
1264 const char* base = file_helper.base_archive_name();
1265 if (base == nullptr) {
1266 *base_archive_name = Arguments::get_default_shared_archive_path();
1267 } else {
1268 *base_archive_name = os::strdup_check_oom(base);
1269 }
1270
1271 return true;
1272 }
1273
1274 // Read the FileMapInfo information from the file.
1275
1276 bool FileMapInfo::init_from_file(int fd) {
1277 FileHeaderHelper file_helper(_full_path, _is_static);
1278 if (!file_helper.initialize(fd)) {
1279 log_warning(cds)("Unable to read the file header.");
1280 return false;
1281 }
1282 GenericCDSFileMapHeader* gen_header = file_helper.get_generic_file_header();
1283
1284 if (_is_static) {
1285 if (gen_header->_magic != CDS_ARCHIVE_MAGIC) {
1286 log_warning(cds)("Not a base shared archive: %s", _full_path);
1287 return false;
1288 }
1289 } else {
1290 if (gen_header->_magic != CDS_DYNAMIC_ARCHIVE_MAGIC) {
1291 log_warning(cds)("Not a top shared archive: %s", _full_path);
1292 return false;
1293 }
1294 }
1295
1296 _header = (FileMapHeader*)os::malloc(gen_header->_header_size, mtInternal);
1297 os::lseek(fd, 0, SEEK_SET); // reset to begin of the archive
1298 size_t size = gen_header->_header_size;
1299 size_t n = ::read(fd, (void*)_header, (unsigned int)size);
1300 if (n != size) {
1301 log_warning(cds)("Failed to read file header from the top archive file\n");
1302 return false;
1303 }
1304
1305 if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) {
1306 log_info(cds)("_version expected: 0x%x", CURRENT_CDS_ARCHIVE_VERSION);
1307 log_info(cds)(" actual: 0x%x", header()->version());
1308 log_warning(cds)("The shared archive file has the wrong version.");
1309 return false;
1310 }
1311
1312 int common_path_size = header()->common_app_classpath_prefix_size();
1313 if (common_path_size < 0) {
1314 log_warning(cds)("common app classpath prefix len < 0");
1315 return false;
1316 }
1317
1318 unsigned int base_offset = header()->base_archive_name_offset();
1319 unsigned int name_size = header()->base_archive_name_size();
1320 unsigned int header_size = header()->header_size();
1321 if (base_offset != 0 && name_size != 0) {
1322 if (header_size != base_offset + name_size) {
1323 log_info(cds)("_header_size: " UINT32_FORMAT, header_size);
1324 log_info(cds)("common_app_classpath_size: " UINT32_FORMAT, header()->common_app_classpath_prefix_size());
1325 log_info(cds)("base_archive_name_size: " UINT32_FORMAT, header()->base_archive_name_size());
1326 log_info(cds)("base_archive_name_offset: " UINT32_FORMAT, header()->base_archive_name_offset());
1327 log_warning(cds)("The shared archive file has an incorrect header size.");
1328 return false;
1329 }
1330 }
1331
1332 const char* actual_ident = header()->jvm_ident();
1333
1334 if (actual_ident[JVM_IDENT_MAX-1] != 0) {
1335 log_warning(cds)("JVM version identifier is corrupted.");
1336 return false;
1337 }
1338
1339 char expected_ident[JVM_IDENT_MAX];
1340 get_header_version(expected_ident);
1341 if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) {
1342 log_info(cds)("_jvm_ident expected: %s", expected_ident);
1343 log_info(cds)(" actual: %s", actual_ident);
1344 log_warning(cds)("The shared archive file was created by a different"
1345 " version or build of HotSpot");
1346 return false;
1347 }
1348
1349 _file_offset = header()->header_size(); // accounts for the size of _base_archive_name
1350
1351 size_t len = os::lseek(fd, 0, SEEK_END);
1352
1353 for (int i = 0; i < MetaspaceShared::n_regions; i++) {
1354 FileMapRegion* r = region_at(i);
1355 if (r->file_offset() > len || len - r->file_offset() < r->used()) {
1356 log_warning(cds)("The shared archive file has been truncated.");
1357 return false;
1358 }
1359 }
1360
1361 return true;
1362 }
1363
1364 void FileMapInfo::seek_to_position(size_t pos) {
1365 if (os::lseek(_fd, (long)pos, SEEK_SET) < 0) {
1366 log_error(cds)("Unable to seek to position " SIZE_FORMAT, pos);
1367 MetaspaceShared::unrecoverable_loading_error();
1368 }
1369 }
1370
1371 // Read the FileMapInfo information from the file.
1372 bool FileMapInfo::open_for_read() {
1373 if (_file_open) {
1374 return true;
1375 }
1376 log_info(cds)("trying to map %s", _full_path);
1377 int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0);
1378 if (fd < 0) {
1379 if (errno == ENOENT) {
1380 log_info(cds)("Specified shared archive not found (%s)", _full_path);
1381 } else {
1382 log_warning(cds)("Failed to open shared archive file (%s)",
1383 os::strerror(errno));
1384 }
1385 return false;
1386 } else {
1387 log_info(cds)("Opened archive %s.", _full_path);
1388 }
1389
1390 _fd = fd;
1391 _file_open = true;
1392 return true;
1393 }
1394
1395 // Write the FileMapInfo information to the file.
1396
1397 void FileMapInfo::open_for_write() {
1398 LogMessage(cds) msg;
1399 if (msg.is_info()) {
1400 msg.info("Dumping shared data to file: ");
1401 msg.info(" %s", _full_path);
1402 }
1403
1404 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file.
1405 chmod(_full_path, _S_IREAD | _S_IWRITE);
1406 #endif
1407
1408 // Use remove() to delete the existing file because, on Unix, this will
1409 // allow processes that have it open continued access to the file.
1410 remove(_full_path);
1411 int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
1412 if (fd < 0) {
1413 log_error(cds)("Unable to create shared archive file %s: (%s).", _full_path,
1414 os::strerror(errno));
1415 MetaspaceShared::unrecoverable_writing_error();
1416 }
1417 _fd = fd;
1418 _file_open = true;
1419
1420 // Seek past the header. We will write the header after all regions are written
1421 // and their CRCs computed.
1422 size_t header_bytes = header()->header_size();
1423
1424 header_bytes = align_up(header_bytes, MetaspaceShared::core_region_alignment());
1425 _file_offset = header_bytes;
1426 seek_to_position(_file_offset);
1427 }
1428
1429 // Write the header to the file, seek to the next allocation boundary.
1430
1431 void FileMapInfo::write_header() {
1432 _file_offset = 0;
1433 seek_to_position(_file_offset);
1434 assert(is_file_position_aligned(), "must be");
1435 write_bytes(header(), header()->header_size());
1436 }
1437
1438 size_t FileMapRegion::used_aligned() const {
1439 return align_up(used(), MetaspaceShared::core_region_alignment());
1440 }
1441
1442 void FileMapRegion::init(int region_index, size_t mapping_offset, size_t size, bool read_only,
1443 bool allow_exec, int crc) {
1444 _is_heap_region = HeapShared::is_heap_region(region_index);
1445 _is_bitmap_region = (region_index == MetaspaceShared::bm);
1446 _mapping_offset = mapping_offset;
1447 _used = size;
1448 _read_only = read_only;
1449 _allow_exec = allow_exec;
1450 _crc = crc;
1451 _mapped_from_file = false;
1452 _mapped_base = nullptr;
1453 }
1454
1455 void FileMapRegion::init_oopmap(size_t offset, size_t size_in_bits) {
1456 _oopmap_offset = offset;
1457 _oopmap_size_in_bits = size_in_bits;
1458 }
1459
1460 void FileMapRegion::init_ptrmap(size_t offset, size_t size_in_bits) {
1461 _ptrmap_offset = offset;
1462 _ptrmap_size_in_bits = size_in_bits;
1463 }
1464
1465 BitMapView FileMapRegion::bitmap_view(bool is_oopmap) {
1466 char* bitmap_base = FileMapInfo::current_info()->map_bitmap_region();
1467 bitmap_base += is_oopmap ? _oopmap_offset : _ptrmap_offset;
1468 size_t size_in_bits = is_oopmap ? _oopmap_size_in_bits : _ptrmap_size_in_bits;
1469 return BitMapView((BitMap::bm_word_t*)(bitmap_base), size_in_bits);
1470 }
1471
1472 BitMapView FileMapRegion::oopmap_view() {
1473 return bitmap_view(true);
1474 }
1475
1476 BitMapView FileMapRegion::ptrmap_view() {
1477 assert(has_ptrmap(), "must be");
1478 return bitmap_view(false);
1479 }
1480
1481 bool FileMapRegion::check_region_crc() const {
1482 // This function should be called after the region has been properly
1483 // loaded into memory via FileMapInfo::map_region() or FileMapInfo::read_region().
1484 // I.e., this->mapped_base() must be valid.
1485 size_t sz = used();
1486 if (sz == 0) {
1487 return true;
1488 }
1489
1490 assert(mapped_base() != nullptr, "must be initialized");
1491 int crc = ClassLoader::crc32(0, mapped_base(), (jint)sz);
1492 if (crc != this->crc()) {
1493 log_warning(cds)("Checksum verification failed.");
1494 return false;
1495 }
1496 return true;
1497 }
1498
1499 static const char* region_name(int region_index) {
1500 static const char* names[] = {
1501 "rw", "ro", "bm", "hp"
1502 };
1503 const int num_regions = sizeof(names)/sizeof(names[0]);
1504 assert(0 <= region_index && region_index < num_regions, "sanity");
1505
1506 return names[region_index];
1507 }
1508
1509 void FileMapRegion::print(outputStream* st, int region_index) {
1510 st->print_cr("============ region ============= %d \"%s\"", region_index, region_name(region_index));
1511 st->print_cr("- crc: 0x%08x", _crc);
1512 st->print_cr("- read_only: %d", _read_only);
1513 st->print_cr("- allow_exec: %d", _allow_exec);
1514 st->print_cr("- is_heap_region: %d", _is_heap_region);
1515 st->print_cr("- is_bitmap_region: %d", _is_bitmap_region);
1516 st->print_cr("- mapped_from_file: %d", _mapped_from_file);
1517 st->print_cr("- file_offset: " SIZE_FORMAT_X, _file_offset);
1518 st->print_cr("- mapping_offset: " SIZE_FORMAT_X, _mapping_offset);
1519 st->print_cr("- used: " SIZE_FORMAT, _used);
1520 st->print_cr("- oopmap_offset: " SIZE_FORMAT_X, _oopmap_offset);
1521 st->print_cr("- oopmap_size_in_bits: " SIZE_FORMAT, _oopmap_size_in_bits);
1522 st->print_cr("- mapped_base: " INTPTR_FORMAT, p2i(_mapped_base));
1523 }
1524
1525 void FileMapInfo::write_region(int region, char* base, size_t size,
1526 bool read_only, bool allow_exec) {
1527 Arguments::assert_is_dumping_archive();
1528
1529 FileMapRegion* r = region_at(region);
1530 char* requested_base;
1531 size_t mapping_offset = 0;
1532
1533 if (region == MetaspaceShared::bm) {
1534 requested_base = nullptr; // always null for bm region
1535 } else if (size == 0) {
1536 // This is an unused region (e.g., a heap region when !INCLUDE_CDS_JAVA_HEAP)
1537 requested_base = nullptr;
1538 } else if (HeapShared::is_heap_region(region)) {
1539 assert(HeapShared::can_write(), "sanity");
1540 #if INCLUDE_CDS_JAVA_HEAP
1541 assert(!DynamicDumpSharedSpaces, "must be");
1542 requested_base = (char*)ArchiveHeapWriter::requested_address();
1543 if (UseCompressedOops) {
1544 mapping_offset = (size_t)((address)requested_base - CompressedOops::base());
1545 assert((mapping_offset >> CompressedOops::shift()) << CompressedOops::shift() == mapping_offset, "must be");
1546 } else {
1547 #if INCLUDE_G1GC
1548 mapping_offset = requested_base - (char*)G1CollectedHeap::heap()->reserved().start();
1549 #endif
1550 }
1551 #endif // INCLUDE_CDS_JAVA_HEAP
1552 } else {
1553 char* requested_SharedBaseAddress = (char*)MetaspaceShared::requested_base_address();
1554 requested_base = ArchiveBuilder::current()->to_requested(base);
1555 assert(requested_base >= requested_SharedBaseAddress, "must be");
1556 mapping_offset = requested_base - requested_SharedBaseAddress;
1557 }
1558
1559 r->set_file_offset(_file_offset);
1560 int crc = ClassLoader::crc32(0, base, (jint)size);
1561 if (size > 0) {
1562 log_info(cds)("Shared file region (%s) %d: " SIZE_FORMAT_W(8)
1563 " bytes, addr " INTPTR_FORMAT " file offset 0x%08" PRIxPTR
1564 " crc 0x%08x",
1565 region_name(region), region, size, p2i(requested_base), _file_offset, crc);
1566 }
1567
1568 r->init(region, mapping_offset, size, read_only, allow_exec, crc);
1569
1570 if (base != nullptr) {
1571 write_bytes_aligned(base, size);
1572 }
1573 }
1574
1575 static size_t write_bitmap(const CHeapBitMap* map, char* output, size_t offset) {
1576 size_t size_in_bytes = map->size_in_bytes();
1577 map->write_to((BitMap::bm_word_t*)(output + offset), size_in_bytes);
1578 return offset + size_in_bytes;
1579 }
1580
1581 char* FileMapInfo::write_bitmap_region(const CHeapBitMap* ptrmap, ArchiveHeapInfo* heap_info,
1582 size_t &size_in_bytes) {
1583 size_in_bytes = ptrmap->size_in_bytes();
1584
1585 if (heap_info->is_used()) {
1586 size_in_bytes += heap_info->oopmap()->size_in_bytes();
1587 size_in_bytes += heap_info->ptrmap()->size_in_bytes();
1588 }
1589
1590 // The bitmap region contains up to 3 parts:
1591 // ptrmap: metaspace pointers inside the ro/rw regions
1592 // heap_info->oopmap(): Java oop pointers in the heap region
1593 // heap_info->ptrmap(): metaspace pointers in the heap region
1594 char* buffer = NEW_C_HEAP_ARRAY(char, size_in_bytes, mtClassShared);
1595 size_t written = 0;
1596 written = write_bitmap(ptrmap, buffer, written);
1597 header()->set_ptrmap_size_in_bits(ptrmap->size());
1598
1599 if (heap_info->is_used()) {
1600 FileMapRegion* r = region_at(MetaspaceShared::hp);
1601
1602 r->init_oopmap(written, heap_info->oopmap()->size());
1603 written = write_bitmap(heap_info->oopmap(), buffer, written);
1604
1605 r->init_ptrmap(written, heap_info->ptrmap()->size());
1606 written = write_bitmap(heap_info->ptrmap(), buffer, written);
1607 }
1608
1609 write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false);
1610 return buffer;
1611 }
1612
1613 size_t FileMapInfo::write_heap_region(ArchiveHeapInfo* heap_info) {
1614 char* start = heap_info->start();
1615 size_t size = heap_info->byte_size();
1616 write_region(MetaspaceShared::hp, start, size, false, false);
1617 return size;
1618 }
1619
1620 // Dump bytes to file -- at the current file position.
1621
1622 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) {
1623 assert(_file_open, "must be");
1624 if (!os::write(_fd, buffer, nbytes)) {
1625 // If the shared archive is corrupted, close it and remove it.
1626 close();
1627 remove(_full_path);
1628 MetaspaceShared::unrecoverable_writing_error("Unable to write to shared archive file.");
1629 }
1630 _file_offset += nbytes;
1631 }
1632
1633 bool FileMapInfo::is_file_position_aligned() const {
1634 return _file_offset == align_up(_file_offset,
1635 MetaspaceShared::core_region_alignment());
1636 }
1637
1638 // Align file position to an allocation unit boundary.
1639
1640 void FileMapInfo::align_file_position() {
1641 assert(_file_open, "must be");
1642 size_t new_file_offset = align_up(_file_offset,
1643 MetaspaceShared::core_region_alignment());
1644 if (new_file_offset != _file_offset) {
1645 _file_offset = new_file_offset;
1646 // Seek one byte back from the target and write a byte to insure
1647 // that the written file is the correct length.
1648 _file_offset -= 1;
1649 seek_to_position(_file_offset);
1650 char zero = 0;
1651 write_bytes(&zero, 1);
1652 }
1653 }
1654
1655
1656 // Dump bytes to file -- at the current file position.
1657
1658 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) {
1659 align_file_position();
1660 write_bytes(buffer, nbytes);
1661 align_file_position();
1662 }
1663
1664 // Close the shared archive file. This does NOT unmap mapped regions.
1665
1666 void FileMapInfo::close() {
1667 if (_file_open) {
1668 if (::close(_fd) < 0) {
1669 MetaspaceShared::unrecoverable_loading_error("Unable to close the shared archive file.");
1670 }
1671 _file_open = false;
1672 _fd = -1;
1673 }
1674 }
1675
1676
1677 // JVM/TI RedefineClasses() support:
1678 // Remap the shared readonly space to shared readwrite, private.
1679 bool FileMapInfo::remap_shared_readonly_as_readwrite() {
1680 int idx = MetaspaceShared::ro;
1681 FileMapRegion* r = region_at(idx);
1682 if (!r->read_only()) {
1683 // the space is already readwrite so we are done
1684 return true;
1685 }
1686 size_t size = r->used_aligned();
1687 if (!open_for_read()) {
1688 return false;
1689 }
1690 char *addr = r->mapped_base();
1691 char *base = os::remap_memory(_fd, _full_path, r->file_offset(),
1692 addr, size, false /* !read_only */,
1693 r->allow_exec());
1694 close();
1695 // These have to be errors because the shared region is now unmapped.
1696 if (base == nullptr) {
1697 log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1698 vm_exit(1);
1699 }
1700 if (base != addr) {
1701 log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno);
1702 vm_exit(1);
1703 }
1704 r->set_read_only(false);
1705 return true;
1706 }
1707
1708 // Memory map a region in the address space.
1709 static const char* shared_region_name[] = { "ReadWrite", "ReadOnly", "Bitmap", "Heap" };
1710
1711 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) {
1712 DEBUG_ONLY(FileMapRegion* last_region = nullptr);
1713 intx addr_delta = mapped_base_address - header()->requested_base_address();
1714
1715 // Make sure we don't attempt to use header()->mapped_base_address() unless
1716 // it's been successfully mapped.
1717 DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);)
1718
1719 for (int i = 0; i < num_regions; i++) {
1720 int idx = regions[i];
1721 MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs);
1722 if (result != MAP_ARCHIVE_SUCCESS) {
1723 return result;
1724 }
1725 FileMapRegion* r = region_at(idx);
1726 DEBUG_ONLY(if (last_region != nullptr) {
1727 // Ensure that the OS won't be able to allocate new memory spaces between any mapped
1728 // regions, or else it would mess up the simple comparison in MetaspaceObj::is_shared().
1729 assert(r->mapped_base() == last_region->mapped_end(), "must have no gaps");
1730 }
1731 last_region = r;)
1732 log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic",
1733 idx, p2i(r->mapped_base()), p2i(r->mapped_end()),
1734 shared_region_name[idx]);
1735
1736 }
1737
1738 header()->set_mapped_base_address(header()->requested_base_address() + addr_delta);
1739 if (addr_delta != 0 && !relocate_pointers_in_core_regions(addr_delta)) {
1740 return MAP_ARCHIVE_OTHER_FAILURE;
1741 }
1742
1743 return MAP_ARCHIVE_SUCCESS;
1744 }
1745
1746 bool FileMapInfo::read_region(int i, char* base, size_t size, bool do_commit) {
1747 FileMapRegion* r = region_at(i);
1748 if (do_commit) {
1749 log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s",
1750 is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size),
1751 shared_region_name[i], r->allow_exec() ? " exec" : "");
1752 if (!os::commit_memory(base, size, r->allow_exec())) {
1753 log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic",
1754 i, shared_region_name[i]);
1755 return false;
1756 }
1757 }
1758 if (os::lseek(_fd, (long)r->file_offset(), SEEK_SET) != (int)r->file_offset() ||
1759 read_bytes(base, size) != size) {
1760 return false;
1761 }
1762
1763 r->set_mapped_from_file(false);
1764 r->set_mapped_base(base);
1765
1766 if (VerifySharedSpaces && !r->check_region_crc()) {
1767 return false;
1768 }
1769
1770 return true;
1771 }
1772
1773 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) {
1774 assert(!HeapShared::is_heap_region(i), "sanity");
1775 FileMapRegion* r = region_at(i);
1776 size_t size = r->used_aligned();
1777 char *requested_addr = mapped_base_address + r->mapping_offset();
1778 assert(r->mapped_base() == nullptr, "must be not mapped yet");
1779 assert(requested_addr != nullptr, "must be specified");
1780
1781 r->set_mapped_from_file(false);
1782
1783 if (MetaspaceShared::use_windows_memory_mapping()) {
1784 // Windows cannot remap read-only shared memory to read-write when required for
1785 // RedefineClasses, which is also used by JFR. Always map windows regions as RW.
1786 r->set_read_only(false);
1787 } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() ||
1788 Arguments::has_jfr_option()) {
1789 // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW
1790 r->set_read_only(false);
1791 } else if (addr_delta != 0) {
1792 r->set_read_only(false); // Need to patch the pointers
1793 }
1794
1795 if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) {
1796 // This is the second time we try to map the archive(s). We have already created a ReservedSpace
1797 // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows
1798 // can't mmap into a ReservedSpace, so we just ::read() the data. We're going to patch all the
1799 // regions anyway, so there's no benefit for mmap anyway.
1800 if (!read_region(i, requested_addr, size, /* do_commit = */ true)) {
1801 log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT,
1802 shared_region_name[i], p2i(requested_addr));
1803 return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error.
1804 } else {
1805 assert(r->mapped_base() != nullptr, "must be initialized");
1806 }
1807 } else {
1808 // Note that this may either be a "fresh" mapping into unreserved address
1809 // space (Windows, first mapping attempt), or a mapping into pre-reserved
1810 // space (Posix). See also comment in MetaspaceShared::map_archives().
1811 char* base = os::map_memory(_fd, _full_path, r->file_offset(),
1812 requested_addr, size, r->read_only(),
1813 r->allow_exec(), mtClassShared);
1814 if (base != requested_addr) {
1815 log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT,
1816 shared_region_name[i], p2i(requested_addr));
1817 _memory_mapping_failed = true;
1818 return MAP_ARCHIVE_MMAP_FAILURE;
1819 }
1820 r->set_mapped_from_file(true);
1821 r->set_mapped_base(requested_addr);
1822 }
1823
1824 if (VerifySharedSpaces && !r->check_region_crc()) {
1825 return MAP_ARCHIVE_OTHER_FAILURE;
1826 }
1827
1828 return MAP_ARCHIVE_SUCCESS;
1829 }
1830
1831 // The return value is the location of the archive relocation bitmap.
1832 char* FileMapInfo::map_bitmap_region() {
1833 FileMapRegion* r = region_at(MetaspaceShared::bm);
1834 if (r->mapped_base() != nullptr) {
1835 return r->mapped_base();
1836 }
1837 bool read_only = true, allow_exec = false;
1838 char* requested_addr = nullptr; // allow OS to pick any location
1839 char* bitmap_base = os::map_memory(_fd, _full_path, r->file_offset(),
1840 requested_addr, r->used_aligned(), read_only, allow_exec, mtClassShared);
1841 if (bitmap_base == nullptr) {
1842 log_info(cds)("failed to map relocation bitmap");
1843 return nullptr;
1844 }
1845
1846 r->set_mapped_base(bitmap_base);
1847 if (VerifySharedSpaces && !r->check_region_crc()) {
1848 log_error(cds)("relocation bitmap CRC error");
1849 if (!os::unmap_memory(bitmap_base, r->used_aligned())) {
1850 fatal("os::unmap_memory of relocation bitmap failed");
1851 }
1852 return nullptr;
1853 }
1854
1855 r->set_mapped_from_file(true);
1856 log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)",
1857 is_static() ? "static " : "dynamic",
1858 MetaspaceShared::bm, p2i(r->mapped_base()), p2i(r->mapped_end()),
1859 shared_region_name[MetaspaceShared::bm]);
1860 return bitmap_base;
1861 }
1862
1863 // This is called when we cannot map the archive at the requested[ base address (usually 0x800000000).
1864 // We relocate all pointers in the 2 core regions (ro, rw).
1865 bool FileMapInfo::relocate_pointers_in_core_regions(intx addr_delta) {
1866 log_debug(cds, reloc)("runtime archive relocation start");
1867 char* bitmap_base = map_bitmap_region();
1868
1869 if (bitmap_base == nullptr) {
1870 return false; // OOM, or CRC check failure
1871 } else {
1872 size_t ptrmap_size_in_bits = header()->ptrmap_size_in_bits();
1873 log_debug(cds, reloc)("mapped relocation bitmap @ " INTPTR_FORMAT " (" SIZE_FORMAT " bits)",
1874 p2i(bitmap_base), ptrmap_size_in_bits);
1875
1876 BitMapView ptrmap((BitMap::bm_word_t*)bitmap_base, ptrmap_size_in_bits);
1877
1878 // Patch all pointers in the mapped region that are marked by ptrmap.
1879 address patch_base = (address)mapped_base();
1880 address patch_end = (address)mapped_end();
1881
1882 // the current value of the pointers to be patched must be within this
1883 // range (i.e., must be between the requested base address and the address of the current archive).
1884 // Note: top archive may point to objects in the base archive, but not the other way around.
1885 address valid_old_base = (address)header()->requested_base_address();
1886 address valid_old_end = valid_old_base + mapping_end_offset();
1887
1888 // after patching, the pointers must point inside this range
1889 // (the requested location of the archive, as mapped at runtime).
1890 address valid_new_base = (address)header()->mapped_base_address();
1891 address valid_new_end = (address)mapped_end();
1892
1893 SharedDataRelocator patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end,
1894 valid_new_base, valid_new_end, addr_delta);
1895 ptrmap.iterate(&patcher);
1896
1897 // The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces().
1898
1899 log_debug(cds, reloc)("runtime archive relocation done");
1900 return true;
1901 }
1902 }
1903
1904 size_t FileMapInfo::read_bytes(void* buffer, size_t count) {
1905 assert(_file_open, "Archive file is not open");
1906 size_t n = ::read(_fd, buffer, (unsigned int)count);
1907 if (n != count) {
1908 // Close the file if there's a problem reading it.
1909 close();
1910 return 0;
1911 }
1912 _file_offset += count;
1913 return count;
1914 }
1915
1916 // Get the total size in bytes of a read only region
1917 size_t FileMapInfo::readonly_total() {
1918 size_t total = 0;
1919 if (current_info() != nullptr) {
1920 FileMapRegion* r = FileMapInfo::current_info()->region_at(MetaspaceShared::ro);
1921 if (r->read_only()) total += r->used();
1922 }
1923 if (dynamic_info() != nullptr) {
1924 FileMapRegion* r = FileMapInfo::dynamic_info()->region_at(MetaspaceShared::ro);
1925 if (r->read_only()) total += r->used();
1926 }
1927 return total;
1928 }
1929
1930 #if INCLUDE_CDS_JAVA_HEAP
1931 MemRegion FileMapInfo::_mapped_heap_memregion;
1932
1933 bool FileMapInfo::has_heap_region() {
1934 return (region_at(MetaspaceShared::hp)->used() > 0);
1935 }
1936
1937 // Returns the address range of the archived heap region computed using the
1938 // current oop encoding mode. This range may be different than the one seen at
1939 // dump time due to encoding mode differences. The result is used in determining
1940 // if/how these regions should be relocated at run time.
1941 MemRegion FileMapInfo::get_heap_region_requested_range() {
1942 FileMapRegion* r = region_at(MetaspaceShared::hp);
1943 size_t size = r->used();
1944 assert(size > 0, "must have non-empty heap region");
1945
1946 address start = heap_region_requested_address();
1947 address end = start + size;
1948 log_info(cds)("Requested heap region [" INTPTR_FORMAT " - " INTPTR_FORMAT "] = " SIZE_FORMAT_W(8) " bytes",
1949 p2i(start), p2i(end), size);
1950
1951 return MemRegion((HeapWord*)start, (HeapWord*)end);
1952 }
1953
1954 void FileMapInfo::map_or_load_heap_region() {
1955 bool success = false;
1956
1957 if (can_use_heap_region()) {
1958 if (ArchiveHeapLoader::can_map()) {
1959 success = map_heap_region();
1960 } else if (ArchiveHeapLoader::can_load()) {
1961 success = ArchiveHeapLoader::load_heap_region(this);
1962 } else {
1963 if (!UseCompressedOops && !ArchiveHeapLoader::can_map()) {
1964 // TODO - remove implicit knowledge of G1
1965 log_info(cds)("Cannot use CDS heap data. UseG1GC is required for -XX:-UseCompressedOops");
1966 } else {
1967 log_info(cds)("Cannot use CDS heap data. UseEpsilonGC, UseG1GC, UseSerialGC or UseParallelGC are required.");
1968 }
1969 }
1970 }
1971
1972 if (!success) {
1973 MetaspaceShared::disable_full_module_graph();
1974 }
1975 }
1976
1977 bool FileMapInfo::can_use_heap_region() {
1978 if (!has_heap_region()) {
1979 return false;
1980 }
1981 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
1982 ShouldNotReachHere(); // CDS should have been disabled.
1983 // The archived objects are mapped at JVM start-up, but we don't know if
1984 // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook,
1985 // which would make the archived String or mirror objects invalid. Let's be safe and not
1986 // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage.
1987 //
1988 // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects
1989 // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK
1990 // because we won't install an archived object subgraph if the klass of any of the
1991 // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph().
1992 }
1993
1994 log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:",
1995 max_heap_size()/M);
1996 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
1997 p2i(narrow_klass_base()), narrow_klass_shift());
1998 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
1999 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift());
2000 log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",
2001 p2i(header()->heap_begin()), p2i(header()->heap_end()));
2002
2003 log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT,
2004 MaxHeapSize/M, HeapRegion::GrainBytes);
2005 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d",
2006 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift());
2007 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d",
2008 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift());
2009 log_info(cds)(" heap range = [" PTR_FORMAT " - " PTR_FORMAT "]",
2010 UseCompressedOops ? p2i(CompressedOops::begin()) :
2011 UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().start()) : 0L,
2012 UseCompressedOops ? p2i(CompressedOops::end()) :
2013 UseG1GC ? p2i((address)G1CollectedHeap::heap()->reserved().end()) : 0L);
2014
2015 if (narrow_klass_base() != CompressedKlassPointers::base() ||
2016 narrow_klass_shift() != CompressedKlassPointers::shift()) {
2017 log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode.");
2018 return false;
2019 }
2020 return true;
2021 }
2022
2023 // The actual address of this region during dump time.
2024 address FileMapInfo::heap_region_dumptime_address() {
2025 FileMapRegion* r = region_at(MetaspaceShared::hp);
2026 assert(UseSharedSpaces, "runtime only");
2027 assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be");
2028 if (UseCompressedOops) {
2029 return /*dumptime*/ narrow_oop_base() + r->mapping_offset();
2030 } else {
2031 return heap_region_requested_address();
2032 }
2033 }
2034
2035 // The address where this region can be mapped into the runtime heap without
2036 // patching any of the pointers that are embedded in this region.
2037 address FileMapInfo::heap_region_requested_address() {
2038 assert(UseSharedSpaces, "runtime only");
2039 FileMapRegion* r = region_at(MetaspaceShared::hp);
2040 assert(is_aligned(r->mapping_offset(), sizeof(HeapWord)), "must be");
2041 assert(ArchiveHeapLoader::can_map(), "cannot be used by ArchiveHeapLoader::can_load() mode");
2042 if (UseCompressedOops) {
2043 // We can avoid relocation if each region's offset from the runtime CompressedOops::base()
2044 // is the same as its offset from the CompressedOops::base() during dumptime.
2045 // Note that CompressedOops::base() may be different between dumptime and runtime.
2046 //
2047 // Example:
2048 // Dumptime base = 0x1000 and shift is 0. We have a region at address 0x2000. There's a
2049 // narrowOop P stored in this region that points to an object at address 0x2200.
2050 // P's encoded value is 0x1200.
2051 //
2052 // Runtime base = 0x4000 and shift is also 0. If we map this region at 0x5000, then
2053 // the value P can remain 0x1200. The decoded address = (0x4000 + (0x1200 << 0)) = 0x5200,
2054 // which is the runtime location of the referenced object.
2055 return /*runtime*/ CompressedOops::base() + r->mapping_offset();
2056 } else {
2057 // We can avoid relocation if each region is mapped into the exact same address
2058 // where it was at dump time.
2059 return /*dumptime*/header()->heap_begin() + r->mapping_offset();
2060 }
2061 }
2062
2063 // The address where this shared heap region is actually mapped at runtime. This function
2064 // can be called only after we have determined the value for ArchiveHeapLoader::mapped_heap_delta().
2065 address FileMapInfo::heap_region_mapped_address() {
2066 assert(UseSharedSpaces, "runtime only");
2067 assert(ArchiveHeapLoader::can_map(), "cannot be used by ArchiveHeapLoader::can_load() mode");
2068 return heap_region_requested_address() + ArchiveHeapLoader::mapped_heap_delta();
2069 }
2070
2071 bool FileMapInfo::map_heap_region() {
2072 init_heap_region_relocation();
2073
2074 if (_heap_pointers_need_patching) {
2075 char* bitmap_base = map_bitmap_region();
2076 if (bitmap_base == nullptr) {
2077 log_info(cds)("CDS heap cannot be used because bitmap region cannot be mapped");
2078 _heap_pointers_need_patching = false;
2079 return false;
2080 }
2081 }
2082
2083 if (map_heap_region_impl()) {
2084 #ifdef ASSERT
2085 // The "old" regions must be parsable -- we cannot have any unused space
2086 // at the start of the lowest G1 region that contains archived objects.
2087 assert(is_aligned(_mapped_heap_memregion.start(), HeapRegion::GrainBytes), "must be");
2088
2089 // Make sure we map at the very top of the heap - see comments in
2090 // init_heap_region_relocation().
2091 MemRegion heap_range = G1CollectedHeap::heap()->reserved();
2092 assert(heap_range.contains(_mapped_heap_memregion), "must be");
2093
2094 address heap_end = (address)heap_range.end();
2095 address mapped_heap_region_end = (address)_mapped_heap_memregion.end();
2096 assert(heap_end >= mapped_heap_region_end, "must be");
2097 assert(heap_end - mapped_heap_region_end < (intx)(HeapRegion::GrainBytes),
2098 "must be at the top of the heap to avoid fragmentation");
2099 #endif
2100
2101 ArchiveHeapLoader::set_mapped();
2102 return true;
2103 } else {
2104 return false;
2105 }
2106 }
2107
2108 void FileMapInfo::init_heap_region_relocation() {
2109 assert(UseG1GC, "the following code assumes G1");
2110 _heap_pointers_need_patching = false;
2111
2112 MemRegion heap_range = G1CollectedHeap::heap()->reserved();
2113 MemRegion archive_range = get_heap_region_requested_range();
2114
2115 address requested_bottom = (address)archive_range.start();
2116 address heap_end = (address)heap_range.end();
2117 assert(is_aligned(heap_end, HeapRegion::GrainBytes), "must be");
2118
2119 // We map the archive heap region at the very top of the heap to avoid fragmentation.
2120 // To do that, we make sure that the bottom of the archived region is at the same
2121 // address as the bottom of the highest possible G1 region.
2122 address mapped_bottom = heap_end - align_up(archive_range.byte_size(), HeapRegion::GrainBytes);
2123
2124 if (UseCompressedOops &&
2125 (narrow_oop_mode() != CompressedOops::mode() ||
2126 narrow_oop_shift() != CompressedOops::shift())) {
2127 log_info(cds)("CDS heap data needs to be relocated because the archive was created with an incompatible oop encoding mode.");
2128 _heap_pointers_need_patching = true;
2129 } else if (requested_bottom != mapped_bottom) {
2130 log_info(cds)("CDS heap data needs to be relocated because it is mapped at a different address @ " INTPTR_FORMAT,
2131 p2i(mapped_bottom));
2132 _heap_pointers_need_patching = true;
2133 }
2134
2135 ptrdiff_t delta = 0;
2136 if (_heap_pointers_need_patching) {
2137 delta = mapped_bottom - requested_bottom;
2138 }
2139
2140 log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta);
2141 ArchiveHeapLoader::init_mapped_heap_relocation(delta, narrow_oop_shift());
2142 }
2143
2144 bool FileMapInfo::map_heap_region_impl() {
2145 FileMapRegion* r = region_at(MetaspaceShared::hp);
2146 size_t size = r->used();
2147
2148 if (size > 0) {
2149 HeapWord* start = (HeapWord*)heap_region_mapped_address();
2150 _mapped_heap_memregion = MemRegion(start, size / HeapWordSize);
2151 log_info(cds)("Trying to map heap data at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes",
2152 p2i(start), size);
2153 } else {
2154 return false; // no archived java heap data
2155 }
2156
2157 // Check that the region is within the java heap
2158 if (!G1CollectedHeap::heap()->check_archive_addresses(_mapped_heap_memregion)) {
2159 log_info(cds)("Unable to allocate region, range is not within java heap.");
2160 return false;
2161 }
2162
2163 // allocate from java heap
2164 if (!G1CollectedHeap::heap()->alloc_archive_regions(_mapped_heap_memregion)) {
2165 log_info(cds)("Unable to allocate region, java heap range is already in use.");
2166 return false;
2167 }
2168
2169 // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type()
2170 // for mapped region as it is part of the reserved java heap, which is already recorded.
2171 char* addr = (char*)_mapped_heap_memregion.start();
2172 char* base = os::map_memory(_fd, _full_path, r->file_offset(),
2173 addr, _mapped_heap_memregion.byte_size(), r->read_only(),
2174 r->allow_exec());
2175 if (base == nullptr || base != addr) {
2176 dealloc_heap_region();
2177 log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. "
2178 INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes",
2179 p2i(addr), _mapped_heap_memregion.byte_size());
2180 return false;
2181 }
2182
2183 r->set_mapped_base(base);
2184 if (VerifySharedSpaces && !r->check_region_crc()) {
2185 dealloc_heap_region();
2186 log_info(cds)("mapped heap region is corrupt");
2187 return false;
2188 }
2189
2190 return true;
2191 }
2192
2193 narrowOop FileMapInfo::encoded_heap_region_dumptime_address() {
2194 assert(UseSharedSpaces, "runtime only");
2195 assert(UseCompressedOops, "sanity");
2196 FileMapRegion* r = region_at(MetaspaceShared::hp);
2197 return CompressedOops::narrow_oop_cast(r->mapping_offset() >> narrow_oop_shift());
2198 }
2199
2200 void FileMapInfo::patch_heap_embedded_pointers() {
2201 if (!ArchiveHeapLoader::is_mapped() || !_heap_pointers_need_patching) {
2202 return;
2203 }
2204
2205 char* bitmap_base = map_bitmap_region();
2206 assert(bitmap_base != nullptr, "must have already been mapped");
2207
2208 FileMapRegion* r = region_at(MetaspaceShared::hp);
2209 ArchiveHeapLoader::patch_embedded_pointers(
2210 this, _mapped_heap_memregion,
2211 (address)(region_at(MetaspaceShared::bm)->mapped_base()) + r->oopmap_offset(),
2212 r->oopmap_size_in_bits());
2213 }
2214
2215 void FileMapInfo::fixup_mapped_heap_region() {
2216 if (ArchiveHeapLoader::is_mapped()) {
2217 assert(!_mapped_heap_memregion.is_empty(), "sanity");
2218
2219 // Populate the archive regions' G1BlockOffsetTableParts. That ensures
2220 // fast G1BlockOffsetTablePart::block_start operations for any given address
2221 // within the archive regions when trying to find start of an object
2222 // (e.g. during card table scanning).
2223 G1CollectedHeap::heap()->populate_archive_regions_bot_part(_mapped_heap_memregion);
2224 }
2225 }
2226
2227 // dealloc the archive regions from java heap
2228 void FileMapInfo::dealloc_heap_region() {
2229 G1CollectedHeap::heap()->dealloc_archive_regions(_mapped_heap_memregion);
2230 }
2231 #endif // INCLUDE_CDS_JAVA_HEAP
2232
2233 void FileMapInfo::unmap_regions(int regions[], int num_regions) {
2234 for (int r = 0; r < num_regions; r++) {
2235 int idx = regions[r];
2236 unmap_region(idx);
2237 }
2238 }
2239
2240 // Unmap a memory region in the address space.
2241
2242 void FileMapInfo::unmap_region(int i) {
2243 assert(!HeapShared::is_heap_region(i), "sanity");
2244 FileMapRegion* r = region_at(i);
2245 char* mapped_base = r->mapped_base();
2246 size_t size = r->used_aligned();
2247
2248 if (mapped_base != nullptr) {
2249 if (size > 0 && r->mapped_from_file()) {
2250 log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base),
2251 shared_region_name[i]);
2252 if (!os::unmap_memory(mapped_base, size)) {
2253 fatal("os::unmap_memory failed");
2254 }
2255 }
2256 r->set_mapped_base(nullptr);
2257 }
2258 }
2259
2260 void FileMapInfo::assert_mark(bool check) {
2261 if (!check) {
2262 MetaspaceShared::unrecoverable_loading_error("Mark mismatch while restoring from shared file.");
2263 }
2264 }
2265
2266 FileMapInfo* FileMapInfo::_current_info = nullptr;
2267 FileMapInfo* FileMapInfo::_dynamic_archive_info = nullptr;
2268 bool FileMapInfo::_heap_pointers_need_patching = false;
2269 SharedPathTable FileMapInfo::_shared_path_table;
2270 bool FileMapInfo::_validating_shared_path_table = false;
2271 bool FileMapInfo::_memory_mapping_failed = false;
2272 GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = nullptr;
2273
2274 // Open the shared archive file, read and validate the header
2275 // information (version, boot classpath, etc.). If initialization
2276 // fails, shared spaces are disabled and the file is closed.
2277 //
2278 // Validation of the archive is done in two steps:
2279 //
2280 // [1] validate_header() - done here.
2281 // [2] validate_shared_path_table - this is done later, because the table is in the RW
2282 // region of the archive, which is not mapped yet.
2283 bool FileMapInfo::initialize() {
2284 assert(UseSharedSpaces, "UseSharedSpaces expected.");
2285 assert(Arguments::has_jimage(), "The shared archive file cannot be used with an exploded module build.");
2286
2287 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) {
2288 // CDS assumes that no classes resolved in vmClasses::resolve_all()
2289 // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved
2290 // during the JVMTI "early" stage, so we can still use CDS if
2291 // JvmtiExport::has_early_class_hook_env() is false.
2292 log_info(cds)("CDS is disabled because early JVMTI ClassFileLoadHook is in use.");
2293 return false;
2294 }
2295
2296 if (!open_for_read() || !init_from_file(_fd) || !validate_header()) {
2297 if (_is_static) {
2298 log_info(cds)("Initialize static archive failed.");
2299 return false;
2300 } else {
2301 log_info(cds)("Initialize dynamic archive failed.");
2302 if (AutoCreateSharedArchive) {
2303 DynamicDumpSharedSpaces = true;
2304 ArchiveClassesAtExit = Arguments::GetSharedDynamicArchivePath();
2305 }
2306 return false;
2307 }
2308 }
2309
2310 return true;
2311 }
2312
2313 // The 2 core spaces are RW->RO
2314 FileMapRegion* FileMapInfo::first_core_region() const {
2315 return region_at(MetaspaceShared::rw);
2316 }
2317
2318 FileMapRegion* FileMapInfo::last_core_region() const {
2319 return region_at(MetaspaceShared::ro);
2320 }
2321
2322 void FileMapInfo::print(outputStream* st) const {
2323 header()->print(st);
2324 if (!is_static()) {
2325 dynamic_header()->print(st);
2326 }
2327 }
2328
2329 void FileMapHeader::set_as_offset(char* p, size_t *offset) {
2330 *offset = ArchiveBuilder::current()->any_to_offset((address)p);
2331 }
2332
2333 int FileMapHeader::compute_crc() {
2334 char* start = (char*)this;
2335 // start computing from the field after _header_size to end of base archive name.
2336 char* buf = (char*)&(_generic_header._header_size) + sizeof(_generic_header._header_size);
2337 size_t sz = header_size() - (buf - start);
2338 int crc = ClassLoader::crc32(0, buf, (jint)sz);
2339 return crc;
2340 }
2341
2342 // This function should only be called during run time with UseSharedSpaces enabled.
2343 bool FileMapHeader::validate() {
2344 if (_obj_alignment != ObjectAlignmentInBytes) {
2345 log_info(cds)("The shared archive file's ObjectAlignmentInBytes of %d"
2346 " does not equal the current ObjectAlignmentInBytes of %d.",
2347 _obj_alignment, ObjectAlignmentInBytes);
2348 return false;
2349 }
2350 if (_compact_strings != CompactStrings) {
2351 log_info(cds)("The shared archive file's CompactStrings setting (%s)"
2352 " does not equal the current CompactStrings setting (%s).",
2353 _compact_strings ? "enabled" : "disabled",
2354 CompactStrings ? "enabled" : "disabled");
2355 return false;
2356 }
2357
2358 // This must be done after header validation because it might change the
2359 // header data
2360 const char* prop = Arguments::get_property("java.system.class.loader");
2361 if (prop != nullptr) {
2362 log_warning(cds)("Archived non-system classes are disabled because the "
2363 "java.system.class.loader property is specified (value = \"%s\"). "
2364 "To use archived non-system classes, this property must not be set", prop);
2365 _has_platform_or_app_classes = false;
2366 }
2367
2368
2369 if (!_verify_local && BytecodeVerificationLocal) {
2370 // we cannot load boot classes, so there's no point of using the CDS archive
2371 log_info(cds)("The shared archive file's BytecodeVerificationLocal setting (%s)"
2372 " does not equal the current BytecodeVerificationLocal setting (%s).",
2373 _verify_local ? "enabled" : "disabled",
2374 BytecodeVerificationLocal ? "enabled" : "disabled");
2375 return false;
2376 }
2377
2378 // For backwards compatibility, we don't check the BytecodeVerificationRemote setting
2379 // if the archive only contains system classes.
2380 if (_has_platform_or_app_classes
2381 && !_verify_remote // we didn't verify the archived platform/app classes
2382 && BytecodeVerificationRemote) { // but we want to verify all loaded platform/app classes
2383 log_info(cds)("The shared archive file was created with less restrictive "
2384 "verification setting than the current setting.");
2385 // Pretend that we didn't have any archived platform/app classes, so they won't be loaded
2386 // by SystemDictionaryShared.
2387 _has_platform_or_app_classes = false;
2388 }
2389
2390 // Java agents are allowed during run time. Therefore, the following condition is not
2391 // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent)
2392 // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time
2393 // while AllowArchivingWithJavaAgent is set during the current run.
2394 if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) {
2395 log_warning(cds)("The setting of the AllowArchivingWithJavaAgent is different "
2396 "from the setting in the shared archive.");
2397 return false;
2398 }
2399
2400 if (_allow_archiving_with_java_agent) {
2401 log_warning(cds)("This archive was created with AllowArchivingWithJavaAgent. It should be used "
2402 "for testing purposes only and should not be used in a production environment");
2403 }
2404
2405 log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d",
2406 compressed_oops(), compressed_class_pointers());
2407 if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) {
2408 log_info(cds)("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is "
2409 "different from runtime, CDS will be disabled.");
2410 return false;
2411 }
2412
2413 if (compact_headers() != UseCompactObjectHeaders) {
2414 log_info(cds)("The shared archive file's UseCompactObjectHeaders setting (%s)"
2415 " does not equal the current UseCompactObjectHeaders setting (%s).",
2416 _compact_headers ? "enabled" : "disabled",
2417 UseCompactObjectHeaders ? "enabled" : "disabled");
2418 return false;
2419 }
2420
2421 if (!_use_optimized_module_handling) {
2422 MetaspaceShared::disable_optimized_module_handling();
2423 log_info(cds)("optimized module handling: disabled because archive was created without optimized module handling");
2424 }
2425
2426 if (!_use_full_module_graph) {
2427 MetaspaceShared::disable_full_module_graph();
2428 log_info(cds)("full module graph: disabled because archive was created without full module graph");
2429 }
2430
2431 return true;
2432 }
2433
2434 bool FileMapInfo::validate_header() {
2435 if (!header()->validate()) {
2436 return false;
2437 }
2438 if (_is_static) {
2439 return true;
2440 } else {
2441 return DynamicArchive::validate(this);
2442 }
2443 }
2444
2445 #if INCLUDE_JVMTI
2446 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = nullptr;
2447
2448 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) {
2449 if (i == 0) {
2450 // index 0 corresponds to the ClassPathImageEntry which is a globally shared object
2451 // and should never be deleted.
2452 return ClassLoader::get_jrt_entry();
2453 }
2454 ClassPathEntry* ent = _classpath_entries_for_jvmti[i];
2455 if (ent == nullptr) {
2456 SharedClassPathEntry* scpe = shared_path(i);
2457 assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes
2458
2459 const char* path = scpe->name();
2460 struct stat st;
2461 if (os::stat(path, &st) != 0) {
2462 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2463 jio_snprintf(msg, strlen(path) + 127, "error in finding JAR file %s", path);
2464 THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2465 } else {
2466 ent = ClassLoader::create_class_path_entry(THREAD, path, &st, false, false);
2467 if (ent == nullptr) {
2468 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128);
2469 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
2470 THROW_MSG_(vmSymbols::java_io_IOException(), msg, nullptr);
2471 }
2472 }
2473
2474 MutexLocker mu(THREAD, CDSClassFileStream_lock);
2475 if (_classpath_entries_for_jvmti[i] == nullptr) {
2476 _classpath_entries_for_jvmti[i] = ent;
2477 } else {
2478 // Another thread has beat me to creating this entry
2479 delete ent;
2480 ent = _classpath_entries_for_jvmti[i];
2481 }
2482 }
2483
2484 return ent;
2485 }
2486
2487 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) {
2488 int path_index = ik->shared_classpath_index();
2489 assert(path_index >= 0, "should be called for shared built-in classes only");
2490 assert(path_index < (int)get_number_of_shared_paths(), "sanity");
2491
2492 ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL);
2493 assert(cpe != nullptr, "must be");
2494
2495 Symbol* name = ik->name();
2496 const char* const class_name = name->as_C_string();
2497 const char* const file_name = ClassLoader::file_name_for_class_name(class_name,
2498 name->utf8_length());
2499 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
2500 ClassFileStream* cfs = cpe->open_stream_for_loader(THREAD, file_name, loader_data);
2501 assert(cfs != nullptr, "must be able to read the classfile data of shared classes for built-in loaders.");
2502 log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index,
2503 cfs->source(), cfs->length());
2504 return cfs;
2505 }
2506
2507 #endif