1 /* 2 * Copyright (c) 2003, 2020, 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 "jvm.h" 27 #include "classfile/classFileStream.hpp" 28 #include "classfile/classLoader.inline.hpp" 29 #include "classfile/classLoaderData.inline.hpp" 30 #include "classfile/classLoaderExt.hpp" 31 #include "classfile/symbolTable.hpp" 32 #include "classfile/systemDictionaryShared.hpp" 33 #include "classfile/altHashing.hpp" 34 #include "logging/log.hpp" 35 #include "logging/logStream.hpp" 36 #include "logging/logMessage.hpp" 37 #include "memory/archiveUtils.inline.hpp" 38 #include "memory/dynamicArchive.hpp" 39 #include "memory/filemap.hpp" 40 #include "memory/heapShared.inline.hpp" 41 #include "memory/iterator.inline.hpp" 42 #include "memory/metadataFactory.hpp" 43 #include "memory/metaspaceClosure.hpp" 44 #include "memory/metaspaceShared.hpp" 45 #include "memory/oopFactory.hpp" 46 #include "memory/universe.hpp" 47 #include "oops/compressedOops.hpp" 48 #include "oops/compressedOops.inline.hpp" 49 #include "oops/objArrayOop.hpp" 50 #include "oops/oop.inline.hpp" 51 #include "prims/jvmtiExport.hpp" 52 #include "runtime/arguments.hpp" 53 #include "runtime/java.hpp" 54 #include "runtime/mutexLocker.hpp" 55 #include "runtime/os.inline.hpp" 56 #include "runtime/vm_version.hpp" 57 #include "services/memTracker.hpp" 58 #include "utilities/align.hpp" 59 #include "utilities/bitMap.inline.hpp" 60 #include "utilities/classpathStream.hpp" 61 #include "utilities/defaultStream.hpp" 62 #if INCLUDE_G1GC 63 #include "gc/g1/g1CollectedHeap.hpp" 64 #include "gc/g1/heapRegion.hpp" 65 #endif 66 67 # include <sys/stat.h> 68 # include <errno.h> 69 70 #ifndef O_BINARY // if defined (Win32) use binary files. 71 #define O_BINARY 0 // otherwise do nothing. 72 #endif 73 74 // Complain and stop. All error conditions occurring during the writing of 75 // an archive file should stop the process. Unrecoverable errors during 76 // the reading of the archive file should stop the process. 77 78 static void fail_exit(const char *msg, va_list ap) { 79 // This occurs very early during initialization: tty is not initialized. 80 jio_fprintf(defaultStream::error_stream(), 81 "An error has occurred while processing the" 82 " shared archive file.\n"); 83 jio_vfprintf(defaultStream::error_stream(), msg, ap); 84 jio_fprintf(defaultStream::error_stream(), "\n"); 85 // Do not change the text of the below message because some tests check for it. 86 vm_exit_during_initialization("Unable to use shared archive.", NULL); 87 } 88 89 90 void FileMapInfo::fail_stop(const char *msg, ...) { 91 va_list ap; 92 va_start(ap, msg); 93 fail_exit(msg, ap); // Never returns. 94 va_end(ap); // for completeness. 95 } 96 97 98 // Complain and continue. Recoverable errors during the reading of the 99 // archive file may continue (with sharing disabled). 100 // 101 // If we continue, then disable shared spaces and close the file. 102 103 void FileMapInfo::fail_continue(const char *msg, ...) { 104 va_list ap; 105 va_start(ap, msg); 106 if (PrintSharedArchiveAndExit && _validating_shared_path_table) { 107 // If we are doing PrintSharedArchiveAndExit and some of the classpath entries 108 // do not validate, we can still continue "limping" to validate the remaining 109 // entries. No need to quit. 110 tty->print("["); 111 tty->vprint(msg, ap); 112 tty->print_cr("]"); 113 } else { 114 if (RequireSharedSpaces) { 115 fail_exit(msg, ap); 116 } else { 117 if (log_is_enabled(Info, cds)) { 118 ResourceMark rm; 119 LogStream ls(Log(cds)::info()); 120 ls.print("UseSharedSpaces: "); 121 ls.vprint_cr(msg, ap); 122 } 123 } 124 } 125 va_end(ap); 126 } 127 128 // Fill in the fileMapInfo structure with data about this VM instance. 129 130 // This method copies the vm version info into header_version. If the version is too 131 // long then a truncated version, which has a hash code appended to it, is copied. 132 // 133 // Using a template enables this method to verify that header_version is an array of 134 // length JVM_IDENT_MAX. This ensures that the code that writes to the CDS file and 135 // the code that reads the CDS file will both use the same size buffer. Hence, will 136 // use identical truncation. This is necessary for matching of truncated versions. 137 template <int N> static void get_header_version(char (&header_version) [N]) { 138 assert(N == JVM_IDENT_MAX, "Bad header_version size"); 139 140 const char *vm_version = VM_Version::internal_vm_info_string(); 141 const int version_len = (int)strlen(vm_version); 142 143 memset(header_version, 0, JVM_IDENT_MAX); 144 145 if (version_len < (JVM_IDENT_MAX-1)) { 146 strcpy(header_version, vm_version); 147 148 } else { 149 // Get the hash value. Use a static seed because the hash needs to return the same 150 // value over multiple jvm invocations. 151 unsigned int hash = AltHashing::murmur3_32(8191, (const jbyte*)vm_version, version_len); 152 153 // Truncate the ident, saving room for the 8 hex character hash value. 154 strncpy(header_version, vm_version, JVM_IDENT_MAX-9); 155 156 // Append the hash code as eight hex digits. 157 sprintf(&header_version[JVM_IDENT_MAX-9], "%08x", hash); 158 header_version[JVM_IDENT_MAX-1] = 0; // Null terminate. 159 } 160 161 assert(header_version[JVM_IDENT_MAX-1] == 0, "must be"); 162 } 163 164 FileMapInfo::FileMapInfo(bool is_static) { 165 memset((void*)this, 0, sizeof(FileMapInfo)); 166 _is_static = is_static; 167 size_t header_size; 168 if (is_static) { 169 assert(_current_info == NULL, "must be singleton"); // not thread safe 170 _current_info = this; 171 header_size = sizeof(FileMapHeader); 172 } else { 173 assert(_dynamic_archive_info == NULL, "must be singleton"); // not thread safe 174 _dynamic_archive_info = this; 175 header_size = sizeof(DynamicArchiveHeader); 176 } 177 _header = (FileMapHeader*)os::malloc(header_size, mtInternal); 178 memset((void*)_header, 0, header_size); 179 _header->set_header_size(header_size); 180 _header->set_version(INVALID_CDS_ARCHIVE_VERSION); 181 _header->set_has_platform_or_app_classes(true); 182 _file_offset = 0; 183 _file_open = false; 184 } 185 186 FileMapInfo::~FileMapInfo() { 187 if (_is_static) { 188 assert(_current_info == this, "must be singleton"); // not thread safe 189 _current_info = NULL; 190 } else { 191 assert(_dynamic_archive_info == this, "must be singleton"); // not thread safe 192 _dynamic_archive_info = NULL; 193 } 194 } 195 196 void FileMapInfo::populate_header(size_t alignment) { 197 header()->populate(this, alignment); 198 } 199 200 void FileMapHeader::populate(FileMapInfo* mapinfo, size_t alignment) { 201 if (DynamicDumpSharedSpaces) { 202 _magic = CDS_DYNAMIC_ARCHIVE_MAGIC; 203 } else { 204 _magic = CDS_ARCHIVE_MAGIC; 205 } 206 _version = CURRENT_CDS_ARCHIVE_VERSION; 207 _alignment = alignment; 208 _obj_alignment = ObjectAlignmentInBytes; 209 _compact_strings = CompactStrings; 210 _narrow_oop_mode = CompressedOops::mode(); 211 _narrow_oop_base = CompressedOops::base(); 212 _narrow_oop_shift = CompressedOops::shift(); 213 _compressed_oops = UseCompressedOops; 214 _compressed_class_ptrs = UseCompressedClassPointers; 215 _max_heap_size = MaxHeapSize; 216 _narrow_klass_shift = CompressedKlassPointers::shift(); 217 if (HeapShared::is_heap_object_archiving_allowed()) { 218 _heap_end = CompressedOops::end(); 219 } 220 221 // The following fields are for sanity checks for whether this archive 222 // will function correctly with this JVM and the bootclasspath it's 223 // invoked with. 224 225 // JVM version string ... changes on each build. 226 get_header_version(_jvm_ident); 227 228 _app_class_paths_start_index = ClassLoaderExt::app_class_paths_start_index(); 229 _app_module_paths_start_index = ClassLoaderExt::app_module_paths_start_index(); 230 _num_module_paths = ClassLoader::num_module_path_entries(); 231 _max_used_path_index = ClassLoaderExt::max_used_path_index(); 232 233 _verify_local = BytecodeVerificationLocal; 234 _verify_remote = BytecodeVerificationRemote; 235 _has_platform_or_app_classes = ClassLoaderExt::has_platform_or_app_classes(); 236 _requested_base_address = (char*)SharedBaseAddress; 237 _mapped_base_address = (char*)SharedBaseAddress; 238 _allow_archiving_with_java_agent = AllowArchivingWithJavaAgent; 239 // the following 2 fields will be set in write_header for dynamic archive header 240 _base_archive_name_size = 0; 241 _base_archive_is_default = false; 242 243 if (!DynamicDumpSharedSpaces) { 244 set_shared_path_table(mapinfo->_shared_path_table); 245 } 246 } 247 248 void SharedClassPathEntry::init_as_non_existent(const char* path, TRAPS) { 249 _type = non_existent_entry; 250 set_name(path, THREAD); 251 } 252 253 void SharedClassPathEntry::init(bool is_modules_image, 254 ClassPathEntry* cpe, TRAPS) { 255 Arguments::assert_is_dumping_archive(); 256 _timestamp = 0; 257 _filesize = 0; 258 _from_class_path_attr = false; 259 260 struct stat st; 261 if (os::stat(cpe->name(), &st) == 0) { 262 if ((st.st_mode & S_IFMT) == S_IFDIR) { 263 _type = dir_entry; 264 } else { 265 // The timestamp of the modules_image is not checked at runtime. 266 if (is_modules_image) { 267 _type = modules_image_entry; 268 } else { 269 _type = jar_entry; 270 _timestamp = st.st_mtime; 271 _from_class_path_attr = cpe->from_class_path_attr(); 272 } 273 _filesize = st.st_size; 274 } 275 } else { 276 // The file/dir must exist, or it would not have been added 277 // into ClassLoader::classpath_entry(). 278 // 279 // If we can't access a jar file in the boot path, then we can't 280 // make assumptions about where classes get loaded from. 281 FileMapInfo::fail_stop("Unable to open file %s.", cpe->name()); 282 } 283 284 // No need to save the name of the module file, as it will be computed at run time 285 // to allow relocation of the JDK directory. 286 const char* name = is_modules_image ? "" : cpe->name(); 287 set_name(name, THREAD); 288 } 289 290 void SharedClassPathEntry::set_name(const char* name, TRAPS) { 291 size_t len = strlen(name) + 1; 292 _name = MetadataFactory::new_array<char>(ClassLoaderData::the_null_class_loader_data(), (int)len, THREAD); 293 strcpy(_name->data(), name); 294 } 295 296 void SharedClassPathEntry::copy_from(SharedClassPathEntry* ent, ClassLoaderData* loader_data, TRAPS) { 297 _type = ent->_type; 298 _timestamp = ent->_timestamp; 299 _filesize = ent->_filesize; 300 _from_class_path_attr = ent->_from_class_path_attr; 301 set_name(ent->name(), THREAD); 302 303 if (ent->is_jar() && !ent->is_signed() && ent->manifest() != NULL) { 304 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data, 305 ent->manifest_size(), 306 THREAD); 307 char* p = (char*)(buf->data()); 308 memcpy(p, ent->manifest(), ent->manifest_size()); 309 set_manifest(buf); 310 } 311 } 312 313 const char* SharedClassPathEntry::name() const { 314 if (UseSharedSpaces && is_modules_image()) { 315 // In order to validate the runtime modules image file size against the archived 316 // size information, we need to obtain the runtime modules image path. The recorded 317 // dump time modules image path in the archive may be different from the runtime path 318 // if the JDK image has beed moved after generating the archive. 319 return ClassLoader::get_jrt_entry()->name(); 320 } else { 321 return _name->data(); 322 } 323 } 324 325 bool SharedClassPathEntry::validate(bool is_class_path) const { 326 assert(UseSharedSpaces, "runtime only"); 327 328 struct stat st; 329 const char* name = this->name(); 330 331 bool ok = true; 332 log_info(class, path)("checking shared classpath entry: %s", name); 333 if (os::stat(name, &st) != 0 && is_class_path) { 334 // If the archived module path entry does not exist at runtime, it is not fatal 335 // (no need to invalid the shared archive) because the shared runtime visibility check 336 // filters out any archived module classes that do not have a matching runtime 337 // module path location. 338 FileMapInfo::fail_continue("Required classpath entry does not exist: %s", name); 339 ok = false; 340 } else if (is_dir()) { 341 if (!os::dir_is_empty(name)) { 342 FileMapInfo::fail_continue("directory is not empty: %s", name); 343 ok = false; 344 } 345 } else if ((has_timestamp() && _timestamp != st.st_mtime) || 346 _filesize != st.st_size) { 347 ok = false; 348 if (PrintSharedArchiveAndExit) { 349 FileMapInfo::fail_continue(_timestamp != st.st_mtime ? 350 "Timestamp mismatch" : 351 "File size mismatch"); 352 } else { 353 FileMapInfo::fail_continue("A jar file is not the one used while building" 354 " the shared archive file: %s", name); 355 } 356 } 357 358 if (PrintSharedArchiveAndExit && !ok) { 359 // If PrintSharedArchiveAndExit is enabled, don't report failure to the 360 // caller. Please see above comments for more details. 361 ok = true; 362 MetaspaceShared::set_archive_loading_failed(); 363 } 364 return ok; 365 } 366 367 bool SharedClassPathEntry::check_non_existent() const { 368 assert(_type == non_existent_entry, "must be"); 369 log_info(class, path)("should be non-existent: %s", name()); 370 struct stat st; 371 if (os::stat(name(), &st) != 0) { 372 log_info(class, path)("ok"); 373 return true; // file doesn't exist 374 } else { 375 return false; 376 } 377 } 378 379 380 void SharedClassPathEntry::metaspace_pointers_do(MetaspaceClosure* it) { 381 it->push(&_name); 382 it->push(&_manifest); 383 } 384 385 void SharedPathTable::metaspace_pointers_do(MetaspaceClosure* it) { 386 it->push(&_table); 387 for (int i=0; i<_size; i++) { 388 path_at(i)->metaspace_pointers_do(it); 389 } 390 } 391 392 void SharedPathTable::dumptime_init(ClassLoaderData* loader_data, Thread* THREAD) { 393 size_t entry_size = sizeof(SharedClassPathEntry); 394 int num_entries = 0; 395 num_entries += ClassLoader::num_boot_classpath_entries(); 396 num_entries += ClassLoader::num_app_classpath_entries(); 397 num_entries += ClassLoader::num_module_path_entries(); 398 num_entries += FileMapInfo::num_non_existent_class_paths(); 399 size_t bytes = entry_size * num_entries; 400 401 _table = MetadataFactory::new_array<u8>(loader_data, (int)bytes, THREAD); 402 _size = num_entries; 403 } 404 405 // Make a copy of the _shared_path_table for use during dynamic CDS dump. 406 // It is needed because some Java code continues to execute after dynamic dump has finished. 407 // However, during dynamic dump, we have modified FileMapInfo::_shared_path_table so 408 // FileMapInfo::shared_path(i) returns incorrect information in ClassLoader::record_result(). 409 void FileMapInfo::copy_shared_path_table(ClassLoaderData* loader_data, Thread* THREAD) { 410 size_t entry_size = sizeof(SharedClassPathEntry); 411 size_t bytes = entry_size * _shared_path_table.size(); 412 413 _saved_shared_path_table = SharedPathTable(MetadataFactory::new_array<u8>(loader_data, (int)bytes, THREAD), 414 _shared_path_table.size()); 415 416 for (int i = 0; i < _shared_path_table.size(); i++) { 417 _saved_shared_path_table.path_at(i)->copy_from(shared_path(i), loader_data, THREAD); 418 } 419 } 420 421 void FileMapInfo::allocate_shared_path_table() { 422 Arguments::assert_is_dumping_archive(); 423 424 EXCEPTION_MARK; // The following calls should never throw, but would exit VM on error. 425 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 426 ClassPathEntry* jrt = ClassLoader::get_jrt_entry(); 427 428 assert(jrt != NULL, 429 "No modular java runtime image present when allocating the CDS classpath entry table"); 430 431 _shared_path_table.dumptime_init(loader_data, THREAD); 432 433 // 1. boot class path 434 int i = 0; 435 i = add_shared_classpaths(i, "boot", jrt, THREAD); 436 i = add_shared_classpaths(i, "app", ClassLoader::app_classpath_entries(), THREAD); 437 i = add_shared_classpaths(i, "module", ClassLoader::module_path_entries(), THREAD); 438 439 for (int x = 0; x < num_non_existent_class_paths(); x++, i++) { 440 const char* path = _non_existent_class_paths->at(x); 441 shared_path(i)->init_as_non_existent(path, THREAD); 442 } 443 444 assert(i == _shared_path_table.size(), "number of shared path entry mismatch"); 445 446 copy_shared_path_table(loader_data, THREAD); 447 } 448 449 int FileMapInfo::add_shared_classpaths(int i, const char* which, ClassPathEntry *cpe, TRAPS) { 450 while (cpe != NULL) { 451 bool is_jrt = (cpe == ClassLoader::get_jrt_entry()); 452 const char* type = (is_jrt ? "jrt" : (cpe->is_jar_file() ? "jar" : "dir")); 453 log_info(class, path)("add %s shared path (%s) %s", which, type, cpe->name()); 454 SharedClassPathEntry* ent = shared_path(i); 455 ent->init(is_jrt, cpe, THREAD); 456 if (cpe->is_jar_file()) { 457 update_jar_manifest(cpe, ent, THREAD); 458 } 459 if (is_jrt) { 460 cpe = ClassLoader::get_next_boot_classpath_entry(cpe); 461 } else { 462 cpe = cpe->next(); 463 } 464 i++; 465 } 466 467 return i; 468 } 469 470 void FileMapInfo::check_nonempty_dir_in_shared_path_table() { 471 Arguments::assert_is_dumping_archive(); 472 473 bool has_nonempty_dir = false; 474 475 int last = _shared_path_table.size() - 1; 476 if (last > ClassLoaderExt::max_used_path_index()) { 477 // no need to check any path beyond max_used_path_index 478 last = ClassLoaderExt::max_used_path_index(); 479 } 480 481 for (int i = 0; i <= last; i++) { 482 SharedClassPathEntry *e = shared_path(i); 483 if (e->is_dir()) { 484 const char* path = e->name(); 485 if (!os::dir_is_empty(path)) { 486 log_error(cds)("Error: non-empty directory '%s'", path); 487 has_nonempty_dir = true; 488 } 489 } 490 } 491 492 if (has_nonempty_dir) { 493 ClassLoader::exit_with_path_failure("Cannot have non-empty directory in paths", NULL); 494 } 495 } 496 497 void FileMapInfo::record_non_existent_class_path_entry(const char* path) { 498 Arguments::assert_is_dumping_archive(); 499 log_info(class, path)("non-existent Class-Path entry %s", path); 500 if (_non_existent_class_paths == NULL) { 501 _non_existent_class_paths = new (ResourceObj::C_HEAP, mtInternal)GrowableArray<const char*>(10, true); 502 } 503 _non_existent_class_paths->append(os::strdup(path)); 504 } 505 506 int FileMapInfo::num_non_existent_class_paths() { 507 Arguments::assert_is_dumping_archive(); 508 if (_non_existent_class_paths != NULL) { 509 return _non_existent_class_paths->length(); 510 } else { 511 return 0; 512 } 513 } 514 515 class ManifestStream: public ResourceObj { 516 private: 517 u1* _buffer_start; // Buffer bottom 518 u1* _buffer_end; // Buffer top (one past last element) 519 u1* _current; // Current buffer position 520 521 public: 522 // Constructor 523 ManifestStream(u1* buffer, int length) : _buffer_start(buffer), 524 _current(buffer) { 525 _buffer_end = buffer + length; 526 } 527 528 static bool is_attr(u1* attr, const char* name) { 529 return strncmp((const char*)attr, name, strlen(name)) == 0; 530 } 531 532 static char* copy_attr(u1* value, size_t len) { 533 char* buf = NEW_RESOURCE_ARRAY(char, len + 1); 534 strncpy(buf, (char*)value, len); 535 buf[len] = 0; 536 return buf; 537 } 538 539 // The return value indicates if the JAR is signed or not 540 bool check_is_signed() { 541 u1* attr = _current; 542 bool isSigned = false; 543 while (_current < _buffer_end) { 544 if (*_current == '\n') { 545 *_current = '\0'; 546 u1* value = (u1*)strchr((char*)attr, ':'); 547 if (value != NULL) { 548 assert(*(value+1) == ' ', "Unrecognized format" ); 549 if (strstr((char*)attr, "-Digest") != NULL) { 550 isSigned = true; 551 break; 552 } 553 } 554 *_current = '\n'; // restore 555 attr = _current + 1; 556 } 557 _current ++; 558 } 559 return isSigned; 560 } 561 }; 562 563 void FileMapInfo::update_jar_manifest(ClassPathEntry *cpe, SharedClassPathEntry* ent, TRAPS) { 564 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 565 ResourceMark rm(THREAD); 566 jint manifest_size; 567 568 assert(cpe->is_jar_file() && ent->is_jar(), "the shared class path entry is not a JAR file"); 569 char* manifest = ClassLoaderExt::read_manifest(cpe, &manifest_size, CHECK); 570 if (manifest != NULL) { 571 ManifestStream* stream = new ManifestStream((u1*)manifest, 572 manifest_size); 573 if (stream->check_is_signed()) { 574 ent->set_is_signed(); 575 } else { 576 // Copy the manifest into the shared archive 577 manifest = ClassLoaderExt::read_raw_manifest(cpe, &manifest_size, CHECK); 578 Array<u1>* buf = MetadataFactory::new_array<u1>(loader_data, 579 manifest_size, 580 THREAD); 581 char* p = (char*)(buf->data()); 582 memcpy(p, manifest, manifest_size); 583 ent->set_manifest(buf); 584 } 585 } 586 } 587 588 char* FileMapInfo::skip_first_path_entry(const char* path) { 589 size_t path_sep_len = strlen(os::path_separator()); 590 char* p = strstr((char*)path, os::path_separator()); 591 if (p != NULL) { 592 debug_only( { 593 size_t image_name_len = strlen(MODULES_IMAGE_NAME); 594 assert(strncmp(p - image_name_len, MODULES_IMAGE_NAME, image_name_len) == 0, 595 "first entry must be the modules image"); 596 } ); 597 p += path_sep_len; 598 } else { 599 debug_only( { 600 assert(ClassLoader::string_ends_with(path, MODULES_IMAGE_NAME), 601 "first entry must be the modules image"); 602 } ); 603 } 604 return p; 605 } 606 607 int FileMapInfo::num_paths(const char* path) { 608 if (path == NULL) { 609 return 0; 610 } 611 int npaths = 1; 612 char* p = (char*)path; 613 while (p != NULL) { 614 char* prev = p; 615 p = strstr((char*)p, os::path_separator()); 616 if (p != NULL) { 617 p++; 618 // don't count empty path 619 if ((p - prev) > 1) { 620 npaths++; 621 } 622 } 623 } 624 return npaths; 625 } 626 627 GrowableArray<const char*>* FileMapInfo::create_path_array(const char* paths) { 628 GrowableArray<const char*>* path_array = new(ResourceObj::RESOURCE_AREA, mtInternal) 629 GrowableArray<const char*>(10); 630 631 ClasspathStream cp_stream(paths); 632 while (cp_stream.has_next()) { 633 const char* path = cp_stream.get_next(); 634 struct stat st; 635 if (os::stat(path, &st) == 0) { 636 path_array->append(path); 637 } 638 } 639 return path_array; 640 } 641 642 bool FileMapInfo::classpath_failure(const char* msg, const char* name) { 643 ClassLoader::trace_class_path(msg, name); 644 if (PrintSharedArchiveAndExit) { 645 MetaspaceShared::set_archive_loading_failed(); 646 } 647 return false; 648 } 649 650 bool FileMapInfo::check_paths(int shared_path_start_idx, int num_paths, GrowableArray<const char*>* rp_array) { 651 int i = 0; 652 int j = shared_path_start_idx; 653 bool mismatch = false; 654 while (i < num_paths && !mismatch) { 655 while (shared_path(j)->from_class_path_attr()) { 656 // shared_path(j) was expanded from the JAR file attribute "Class-Path:" 657 // during dump time. It's not included in the -classpath VM argument. 658 j++; 659 } 660 if (!os::same_files(shared_path(j)->name(), rp_array->at(i))) { 661 mismatch = true; 662 } 663 i++; 664 j++; 665 } 666 return mismatch; 667 } 668 669 bool FileMapInfo::validate_boot_class_paths() { 670 // 671 // - Archive contains boot classes only - relaxed boot path check: 672 // Extra path elements appended to the boot path at runtime are allowed. 673 // 674 // - Archive contains application or platform classes - strict boot path check: 675 // Validate the entire runtime boot path, which must be compatible 676 // with the dump time boot path. Appending boot path at runtime is not 677 // allowed. 678 // 679 680 // The first entry in boot path is the modules_image (guaranteed by 681 // ClassLoader::setup_boot_search_path()). Skip the first entry. The 682 // path of the runtime modules_image may be different from the dump 683 // time path (e.g. the JDK image is copied to a different location 684 // after generating the shared archive), which is acceptable. For most 685 // common cases, the dump time boot path might contain modules_image only. 686 char* runtime_boot_path = Arguments::get_sysclasspath(); 687 char* rp = skip_first_path_entry(runtime_boot_path); 688 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image"); 689 int dp_len = header()->app_class_paths_start_index() - 1; // ignore the first path to the module image 690 bool mismatch = false; 691 692 bool relaxed_check = !header()->has_platform_or_app_classes(); 693 if (dp_len == 0 && rp == NULL) { 694 return true; // ok, both runtime and dump time boot paths have modules_images only 695 } else if (dp_len == 0 && rp != NULL) { 696 if (relaxed_check) { 697 return true; // ok, relaxed check, runtime has extra boot append path entries 698 } else { 699 mismatch = true; 700 } 701 } else if (dp_len > 0 && rp != NULL) { 702 int num; 703 ResourceMark rm; 704 GrowableArray<const char*>* rp_array = create_path_array(rp); 705 int rp_len = rp_array->length(); 706 if (rp_len >= dp_len) { 707 if (relaxed_check) { 708 // only check the leading entries in the runtime boot path, up to 709 // the length of the dump time boot path 710 num = dp_len; 711 } else { 712 // check the full runtime boot path, must match with dump time 713 num = rp_len; 714 } 715 mismatch = check_paths(1, num, rp_array); 716 } 717 } 718 719 if (mismatch) { 720 // The paths are different 721 return classpath_failure("[BOOT classpath mismatch, actual =", runtime_boot_path); 722 } 723 return true; 724 } 725 726 bool FileMapInfo::validate_app_class_paths(int shared_app_paths_len) { 727 const char *appcp = Arguments::get_appclasspath(); 728 assert(appcp != NULL, "NULL app classpath"); 729 int rp_len = num_paths(appcp); 730 bool mismatch = false; 731 if (rp_len < shared_app_paths_len) { 732 return classpath_failure("Run time APP classpath is shorter than the one at dump time: ", appcp); 733 } 734 if (shared_app_paths_len != 0 && rp_len != 0) { 735 // Prefix is OK: E.g., dump with -cp foo.jar, but run with -cp foo.jar:bar.jar. 736 ResourceMark rm; 737 GrowableArray<const char*>* rp_array = create_path_array(appcp); 738 if (rp_array->length() == 0) { 739 // None of the jar file specified in the runtime -cp exists. 740 return classpath_failure("None of the jar file specified in the runtime -cp exists: -Djava.class.path=", appcp); 741 } 742 743 // Handling of non-existent entries in the classpath: we eliminate all the non-existent 744 // entries from both the dump time classpath (ClassLoader::update_class_path_entry_list) 745 // and the runtime classpath (FileMapInfo::create_path_array), and check the remaining 746 // entries. E.g.: 747 // 748 // dump : -cp a.jar:NE1:NE2:b.jar -> a.jar:b.jar -> recorded in archive. 749 // run 1: -cp NE3:a.jar:NE4:b.jar -> a.jar:b.jar -> matched 750 // run 2: -cp x.jar:NE4:b.jar -> x.jar:b.jar -> mismatched 751 752 int j = header()->app_class_paths_start_index(); 753 mismatch = check_paths(j, shared_app_paths_len, rp_array); 754 if (mismatch) { 755 return classpath_failure("[APP classpath mismatch, actual: -Djava.class.path=", appcp); 756 } 757 } 758 return true; 759 } 760 761 void FileMapInfo::log_paths(const char* msg, int start_idx, int end_idx) { 762 LogTarget(Info, class, path) lt; 763 if (lt.is_enabled()) { 764 LogStream ls(lt); 765 ls.print("%s", msg); 766 const char* prefix = ""; 767 for (int i = start_idx; i < end_idx; i++) { 768 ls.print("%s%s", prefix, shared_path(i)->name()); 769 prefix = os::path_separator(); 770 } 771 ls.cr(); 772 } 773 } 774 775 bool FileMapInfo::validate_shared_path_table() { 776 assert(UseSharedSpaces, "runtime only"); 777 778 _validating_shared_path_table = true; 779 780 // Load the shared path table info from the archive header 781 _shared_path_table = header()->shared_path_table(); 782 if (DynamicDumpSharedSpaces) { 783 // Only support dynamic dumping with the usage of the default CDS archive 784 // or a simple base archive. 785 // If the base layer archive contains additional path component besides 786 // the runtime image and the -cp, dynamic dumping is disabled. 787 // 788 // When dynamic archiving is enabled, the _shared_path_table is overwritten 789 // to include the application path and stored in the top layer archive. 790 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image"); 791 if (header()->app_class_paths_start_index() > 1) { 792 DynamicDumpSharedSpaces = false; 793 warning( 794 "Dynamic archiving is disabled because base layer archive has appended boot classpath"); 795 } 796 if (header()->num_module_paths() > 0) { 797 DynamicDumpSharedSpaces = false; 798 warning( 799 "Dynamic archiving is disabled because base layer archive has module path"); 800 } 801 } 802 803 log_paths("Expecting BOOT path=", 0, header()->app_class_paths_start_index()); 804 log_paths("Expecting -Djava.class.path=", header()->app_class_paths_start_index(), header()->app_module_paths_start_index()); 805 806 int module_paths_start_index = header()->app_module_paths_start_index(); 807 int shared_app_paths_len = 0; 808 809 // validate the path entries up to the _max_used_path_index 810 for (int i=0; i < header()->max_used_path_index() + 1; i++) { 811 if (i < module_paths_start_index) { 812 if (shared_path(i)->validate()) { 813 // Only count the app class paths not from the "Class-path" attribute of a jar manifest. 814 if (!shared_path(i)->from_class_path_attr() && i >= header()->app_class_paths_start_index()) { 815 shared_app_paths_len++; 816 } 817 log_info(class, path)("ok"); 818 } else { 819 if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) { 820 assert(!UseSharedSpaces, "UseSharedSpaces should be disabled"); 821 } 822 return false; 823 } 824 } else if (i >= module_paths_start_index) { 825 if (shared_path(i)->validate(false /* not a class path entry */)) { 826 log_info(class, path)("ok"); 827 } else { 828 if (_dynamic_archive_info != NULL && _dynamic_archive_info->_is_static) { 829 assert(!UseSharedSpaces, "UseSharedSpaces should be disabled"); 830 } 831 return false; 832 } 833 } 834 } 835 836 if (header()->max_used_path_index() == 0) { 837 // default archive only contains the module image in the bootclasspath 838 assert(shared_path(0)->is_modules_image(), "first shared_path must be the modules image"); 839 } else { 840 if (!validate_boot_class_paths() || !validate_app_class_paths(shared_app_paths_len)) { 841 fail_continue("shared class paths mismatch (hint: enable -Xlog:class+path=info to diagnose the failure)"); 842 return false; 843 } 844 } 845 846 validate_non_existent_class_paths(); 847 848 _validating_shared_path_table = false; 849 850 #if INCLUDE_JVMTI 851 if (_classpath_entries_for_jvmti != NULL) { 852 os::free(_classpath_entries_for_jvmti); 853 } 854 size_t sz = sizeof(ClassPathEntry*) * get_number_of_shared_paths(); 855 _classpath_entries_for_jvmti = (ClassPathEntry**)os::malloc(sz, mtClass); 856 memset((void*)_classpath_entries_for_jvmti, 0, sz); 857 #endif 858 859 return true; 860 } 861 862 void FileMapInfo::validate_non_existent_class_paths() { 863 // All of the recorded non-existent paths came from the Class-Path: attribute from the JAR 864 // files on the app classpath. If any of these are found to exist during runtime, 865 // it will change how classes are loading for the app loader. For safety, disable 866 // loading of archived platform/app classes (currently there's no way to disable just the 867 // app classes). 868 869 assert(UseSharedSpaces, "runtime only"); 870 for (int i = header()->app_module_paths_start_index() + header()->num_module_paths(); 871 i < get_number_of_shared_paths(); 872 i++) { 873 SharedClassPathEntry* ent = shared_path(i); 874 if (!ent->check_non_existent()) { 875 warning("Archived non-system classes are disabled because the " 876 "file %s exists", ent->name()); 877 header()->set_has_platform_or_app_classes(false); 878 } 879 } 880 } 881 882 bool FileMapInfo::check_archive(const char* archive_name, bool is_static) { 883 int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0); 884 if (fd < 0) { 885 // do not vm_exit_during_initialization here because Arguments::init_shared_archive_paths() 886 // requires a shared archive name. The open_for_read() function will log a message regarding 887 // failure in opening a shared archive. 888 return false; 889 } 890 891 size_t sz = is_static ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader); 892 void* header = os::malloc(sz, mtInternal); 893 memset(header, 0, sz); 894 size_t n = os::read(fd, header, (unsigned int)sz); 895 if (n != sz) { 896 os::free(header); 897 os::close(fd); 898 vm_exit_during_initialization("Unable to read header from shared archive", archive_name); 899 return false; 900 } 901 if (is_static) { 902 FileMapHeader* static_header = (FileMapHeader*)header; 903 if (static_header->magic() != CDS_ARCHIVE_MAGIC) { 904 os::free(header); 905 os::close(fd); 906 vm_exit_during_initialization("Not a base shared archive", archive_name); 907 return false; 908 } 909 } else { 910 DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)header; 911 if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) { 912 os::free(header); 913 os::close(fd); 914 vm_exit_during_initialization("Not a top shared archive", archive_name); 915 return false; 916 } 917 } 918 os::free(header); 919 os::close(fd); 920 return true; 921 } 922 923 bool FileMapInfo::get_base_archive_name_from_header(const char* archive_name, 924 int* size, char** base_archive_name) { 925 int fd = os::open(archive_name, O_RDONLY | O_BINARY, 0); 926 if (fd < 0) { 927 *size = 0; 928 return false; 929 } 930 931 // read the header as a dynamic archive header 932 size_t sz = sizeof(DynamicArchiveHeader); 933 DynamicArchiveHeader* dynamic_header = (DynamicArchiveHeader*)os::malloc(sz, mtInternal); 934 size_t n = os::read(fd, dynamic_header, (unsigned int)sz); 935 if (n != sz) { 936 fail_continue("Unable to read the file header."); 937 os::free(dynamic_header); 938 os::close(fd); 939 return false; 940 } 941 if (dynamic_header->magic() != CDS_DYNAMIC_ARCHIVE_MAGIC) { 942 // Not a dynamic header, no need to proceed further. 943 *size = 0; 944 os::free(dynamic_header); 945 os::close(fd); 946 return false; 947 } 948 if (dynamic_header->base_archive_is_default()) { 949 *base_archive_name = Arguments::get_default_shared_archive_path(); 950 } else { 951 // read the base archive name 952 size_t name_size = dynamic_header->base_archive_name_size(); 953 if (name_size == 0) { 954 os::free(dynamic_header); 955 os::close(fd); 956 return false; 957 } 958 *base_archive_name = NEW_C_HEAP_ARRAY(char, name_size, mtInternal); 959 n = os::read(fd, *base_archive_name, (unsigned int)name_size); 960 if (n != name_size) { 961 fail_continue("Unable to read the base archive name from the header."); 962 FREE_C_HEAP_ARRAY(char, *base_archive_name); 963 *base_archive_name = NULL; 964 os::free(dynamic_header); 965 os::close(fd); 966 return false; 967 } 968 } 969 970 os::free(dynamic_header); 971 os::close(fd); 972 return true; 973 } 974 975 // Read the FileMapInfo information from the file. 976 977 bool FileMapInfo::init_from_file(int fd) { 978 size_t sz = is_static() ? sizeof(FileMapHeader) : sizeof(DynamicArchiveHeader); 979 size_t n = os::read(fd, header(), (unsigned int)sz); 980 if (n != sz) { 981 fail_continue("Unable to read the file header."); 982 return false; 983 } 984 985 if (!Arguments::has_jimage()) { 986 FileMapInfo::fail_continue("The shared archive file cannot be used with an exploded module build."); 987 return false; 988 } 989 990 unsigned int expected_magic = is_static() ? CDS_ARCHIVE_MAGIC : CDS_DYNAMIC_ARCHIVE_MAGIC; 991 if (header()->magic() != expected_magic) { 992 log_info(cds)("_magic expected: 0x%08x", expected_magic); 993 log_info(cds)(" actual: 0x%08x", header()->magic()); 994 FileMapInfo::fail_continue("The shared archive file has a bad magic number."); 995 return false; 996 } 997 998 if (header()->version() != CURRENT_CDS_ARCHIVE_VERSION) { 999 log_info(cds)("_version expected: %d", CURRENT_CDS_ARCHIVE_VERSION); 1000 log_info(cds)(" actual: %d", header()->version()); 1001 fail_continue("The shared archive file has the wrong version."); 1002 return false; 1003 } 1004 1005 if (header()->header_size() != sz) { 1006 log_info(cds)("_header_size expected: " SIZE_FORMAT, sz); 1007 log_info(cds)(" actual: " SIZE_FORMAT, header()->header_size()); 1008 FileMapInfo::fail_continue("The shared archive file has an incorrect header size."); 1009 return false; 1010 } 1011 1012 const char* actual_ident = header()->jvm_ident(); 1013 1014 if (actual_ident[JVM_IDENT_MAX-1] != 0) { 1015 FileMapInfo::fail_continue("JVM version identifier is corrupted."); 1016 return false; 1017 } 1018 1019 char expected_ident[JVM_IDENT_MAX]; 1020 get_header_version(expected_ident); 1021 if (strncmp(actual_ident, expected_ident, JVM_IDENT_MAX-1) != 0) { 1022 log_info(cds)("_jvm_ident expected: %s", expected_ident); 1023 log_info(cds)(" actual: %s", actual_ident); 1024 FileMapInfo::fail_continue("The shared archive file was created by a different" 1025 " version or build of HotSpot"); 1026 return false; 1027 } 1028 1029 if (VerifySharedSpaces) { 1030 int expected_crc = header()->compute_crc(); 1031 if (expected_crc != header()->crc()) { 1032 log_info(cds)("_crc expected: %d", expected_crc); 1033 log_info(cds)(" actual: %d", header()->crc()); 1034 FileMapInfo::fail_continue("Header checksum verification failed."); 1035 return false; 1036 } 1037 } 1038 1039 _file_offset = n + header()->base_archive_name_size(); // accounts for the size of _base_archive_name 1040 1041 if (is_static()) { 1042 // just checking the last region is sufficient since the archive is written 1043 // in sequential order 1044 size_t len = lseek(fd, 0, SEEK_END); 1045 FileMapRegion* si = space_at(MetaspaceShared::last_valid_region); 1046 // The last space might be empty 1047 if (si->file_offset() > len || len - si->file_offset() < si->used()) { 1048 fail_continue("The shared archive file has been truncated."); 1049 return false; 1050 } 1051 } 1052 1053 return true; 1054 } 1055 1056 void FileMapInfo::seek_to_position(size_t pos) { 1057 if (lseek(_fd, (long)pos, SEEK_SET) < 0) { 1058 fail_stop("Unable to seek to position " SIZE_FORMAT, pos); 1059 } 1060 } 1061 1062 // Read the FileMapInfo information from the file. 1063 bool FileMapInfo::open_for_read() { 1064 if (_file_open) { 1065 return true; 1066 } 1067 if (is_static()) { 1068 _full_path = Arguments::GetSharedArchivePath(); 1069 } else { 1070 _full_path = Arguments::GetSharedDynamicArchivePath(); 1071 } 1072 int fd = os::open(_full_path, O_RDONLY | O_BINARY, 0); 1073 if (fd < 0) { 1074 if (errno == ENOENT) { 1075 fail_continue("Specified shared archive not found (%s).", _full_path); 1076 } else { 1077 fail_continue("Failed to open shared archive file (%s).", 1078 os::strerror(errno)); 1079 } 1080 return false; 1081 } 1082 1083 _fd = fd; 1084 _file_open = true; 1085 return true; 1086 } 1087 1088 // Write the FileMapInfo information to the file. 1089 1090 void FileMapInfo::open_for_write(const char* path) { 1091 if (path == NULL) { 1092 _full_path = Arguments::GetSharedArchivePath(); 1093 } else { 1094 _full_path = path; 1095 } 1096 LogMessage(cds) msg; 1097 if (msg.is_info()) { 1098 msg.info("Dumping shared data to file: "); 1099 msg.info(" %s", _full_path); 1100 } 1101 1102 #ifdef _WINDOWS // On Windows, need WRITE permission to remove the file. 1103 chmod(_full_path, _S_IREAD | _S_IWRITE); 1104 #endif 1105 1106 // Use remove() to delete the existing file because, on Unix, this will 1107 // allow processes that have it open continued access to the file. 1108 remove(_full_path); 1109 int fd = os::open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444); 1110 if (fd < 0) { 1111 fail_stop("Unable to create shared archive file %s: (%s).", _full_path, 1112 os::strerror(errno)); 1113 } 1114 _fd = fd; 1115 _file_open = true; 1116 1117 // Seek past the header. We will write the header after all regions are written 1118 // and their CRCs computed. 1119 size_t header_bytes = header()->header_size(); 1120 if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) { 1121 header_bytes += strlen(Arguments::GetSharedArchivePath()) + 1; 1122 } 1123 1124 header_bytes = align_up(header_bytes, os::vm_allocation_granularity()); 1125 _file_offset = header_bytes; 1126 seek_to_position(_file_offset); 1127 } 1128 1129 1130 // Write the header to the file, seek to the next allocation boundary. 1131 1132 void FileMapInfo::write_header() { 1133 _file_offset = 0; 1134 seek_to_position(_file_offset); 1135 char* base_archive_name = NULL; 1136 if (header()->magic() == CDS_DYNAMIC_ARCHIVE_MAGIC) { 1137 base_archive_name = (char*)Arguments::GetSharedArchivePath(); 1138 header()->set_base_archive_name_size(strlen(base_archive_name) + 1); 1139 header()->set_base_archive_is_default(FLAG_IS_DEFAULT(SharedArchiveFile)); 1140 } 1141 1142 assert(is_file_position_aligned(), "must be"); 1143 write_bytes(header(), header()->header_size()); 1144 if (base_archive_name != NULL) { 1145 write_bytes(base_archive_name, header()->base_archive_name_size()); 1146 } 1147 } 1148 1149 size_t FileMapRegion::used_aligned() const { 1150 return align_up(used(), os::vm_allocation_granularity()); 1151 } 1152 1153 void FileMapRegion::init(int region_index, char* base, size_t size, bool read_only, 1154 bool allow_exec, int crc) { 1155 _is_heap_region = HeapShared::is_heap_region(region_index); 1156 _is_bitmap_region = (region_index == MetaspaceShared::bm); 1157 _mapping_offset = 0; 1158 1159 if (_is_heap_region) { 1160 assert(!DynamicDumpSharedSpaces, "must be"); 1161 assert((base - (char*)CompressedKlassPointers::base()) % HeapWordSize == 0, "Sanity"); 1162 if (base != NULL) { 1163 _mapping_offset = (size_t)CompressedOops::encode_not_null((oop)base); 1164 assert(_mapping_offset == (size_t)(uint32_t)_mapping_offset, "must be 32-bit only"); 1165 } 1166 } else { 1167 if (base != NULL) { 1168 assert(base >= (char*)SharedBaseAddress, "must be"); 1169 _mapping_offset = base - (char*)SharedBaseAddress; 1170 } 1171 } 1172 _used = size; 1173 _read_only = read_only; 1174 _allow_exec = allow_exec; 1175 _crc = crc; 1176 _mapped_from_file = false; 1177 _mapped_base = NULL; 1178 } 1179 1180 void FileMapInfo::write_region(int region, char* base, size_t size, 1181 bool read_only, bool allow_exec) { 1182 Arguments::assert_is_dumping_archive(); 1183 1184 FileMapRegion* si = space_at(region); 1185 char* target_base; 1186 1187 if (region == MetaspaceShared::bm) { 1188 target_base = NULL; // always NULL for bm region. 1189 } else { 1190 if (DynamicDumpSharedSpaces) { 1191 assert(!HeapShared::is_heap_region(region), "dynamic archive doesn't support heap regions"); 1192 target_base = DynamicArchive::buffer_to_target(base); 1193 } else { 1194 target_base = base; 1195 } 1196 } 1197 1198 si->set_file_offset(_file_offset); 1199 char* requested_base = (target_base == NULL) ? NULL : target_base + MetaspaceShared::final_delta(); 1200 log_debug(cds)("Shared file region %d: " SIZE_FORMAT_HEX_W(08) 1201 " bytes, addr " INTPTR_FORMAT " file offset " SIZE_FORMAT_HEX_W(08), 1202 region, size, p2i(requested_base), _file_offset); 1203 1204 int crc = ClassLoader::crc32(0, base, (jint)size); 1205 si->init(region, target_base, size, read_only, allow_exec, crc); 1206 1207 if (base != NULL) { 1208 write_bytes_aligned(base, size); 1209 } 1210 } 1211 1212 size_t FileMapInfo::set_oopmaps_offset(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_size) { 1213 for (int i = 0; i < oopmaps->length(); i++) { 1214 oopmaps->at(i)._offset = curr_size; 1215 curr_size += oopmaps->at(i)._oopmap_size_in_bytes; 1216 } 1217 return curr_size; 1218 } 1219 1220 size_t FileMapInfo::write_oopmaps(GrowableArray<ArchiveHeapOopmapInfo>* oopmaps, size_t curr_offset, uintptr_t* buffer) { 1221 for (int i = 0; i < oopmaps->length(); i++) { 1222 memcpy(((char*)buffer) + curr_offset, oopmaps->at(i)._oopmap, oopmaps->at(i)._oopmap_size_in_bytes); 1223 curr_offset += oopmaps->at(i)._oopmap_size_in_bytes; 1224 } 1225 return curr_offset; 1226 } 1227 1228 void FileMapInfo::write_bitmap_region(const CHeapBitMap* ptrmap, 1229 GrowableArray<ArchiveHeapOopmapInfo>* closed_oopmaps, 1230 GrowableArray<ArchiveHeapOopmapInfo>* open_oopmaps) { 1231 ResourceMark rm; 1232 size_t size_in_bits = ptrmap->size(); 1233 size_t size_in_bytes = ptrmap->size_in_bytes(); 1234 1235 if (closed_oopmaps != NULL && open_oopmaps != NULL) { 1236 size_in_bytes = set_oopmaps_offset(closed_oopmaps, size_in_bytes); 1237 size_in_bytes = set_oopmaps_offset(open_oopmaps, size_in_bytes); 1238 } 1239 1240 uintptr_t* buffer = (uintptr_t*)NEW_RESOURCE_ARRAY(char, size_in_bytes); 1241 ptrmap->write_to(buffer, ptrmap->size_in_bytes()); 1242 header()->set_ptrmap_size_in_bits(size_in_bits); 1243 1244 if (closed_oopmaps != NULL && open_oopmaps != NULL) { 1245 size_t curr_offset = write_oopmaps(closed_oopmaps, ptrmap->size_in_bytes(), buffer); 1246 write_oopmaps(open_oopmaps, curr_offset, buffer); 1247 } 1248 1249 log_debug(cds)("ptrmap = " INTPTR_FORMAT " (" SIZE_FORMAT " bytes)", 1250 p2i(buffer), size_in_bytes); 1251 write_region(MetaspaceShared::bm, (char*)buffer, size_in_bytes, /*read_only=*/true, /*allow_exec=*/false); 1252 } 1253 1254 // Write out the given archive heap memory regions. GC code combines multiple 1255 // consecutive archive GC regions into one MemRegion whenever possible and 1256 // produces the 'heap_mem' array. 1257 // 1258 // If the archive heap memory size is smaller than a single dump time GC region 1259 // size, there is only one MemRegion in the array. 1260 // 1261 // If the archive heap memory size is bigger than one dump time GC region size, 1262 // the 'heap_mem' array may contain more than one consolidated MemRegions. When 1263 // the first/bottom archive GC region is a partial GC region (with the empty 1264 // portion at the higher address within the region), one MemRegion is used for 1265 // the bottom partial archive GC region. The rest of the consecutive archive 1266 // GC regions are combined into another MemRegion. 1267 // 1268 // Here's the mapping from (archive heap GC regions) -> (GrowableArray<MemRegion> *regions). 1269 // + We have 1 or more archive heap regions: ah0, ah1, ah2 ..... ahn 1270 // + We have 1 or 2 consolidated heap memory regions: r0 and r1 1271 // 1272 // If there's a single archive GC region (ah0), then r0 == ah0, and r1 is empty. 1273 // Otherwise: 1274 // 1275 // "X" represented space that's occupied by heap objects. 1276 // "_" represented unused spaced in the heap region. 1277 // 1278 // 1279 // |ah0 | ah1 | ah2| ...... | ahn| 1280 // |XXXXXX|__ |XXXXX|XXXX|XXXXXXXX|XXXX| 1281 // |<-r0->| |<- r1 ----------------->| 1282 // ^^^ 1283 // | 1284 // +-- gap 1285 size_t FileMapInfo::write_archive_heap_regions(GrowableArray<MemRegion> *heap_mem, 1286 GrowableArray<ArchiveHeapOopmapInfo> *oopmaps, 1287 int first_region_id, int max_num_regions) { 1288 assert(max_num_regions <= 2, "Only support maximum 2 memory regions"); 1289 1290 int arr_len = heap_mem == NULL ? 0 : heap_mem->length(); 1291 if(arr_len > max_num_regions) { 1292 fail_stop("Unable to write archive heap memory regions: " 1293 "number of memory regions exceeds maximum due to fragmentation. " 1294 "Please increase java heap size " 1295 "(current MaxHeapSize is " SIZE_FORMAT ", InitialHeapSize is " SIZE_FORMAT ").", 1296 MaxHeapSize, InitialHeapSize); 1297 } 1298 1299 size_t total_size = 0; 1300 for (int i = first_region_id, arr_idx = 0; 1301 i < first_region_id + max_num_regions; 1302 i++, arr_idx++) { 1303 char* start = NULL; 1304 size_t size = 0; 1305 if (arr_idx < arr_len) { 1306 start = (char*)heap_mem->at(arr_idx).start(); 1307 size = heap_mem->at(arr_idx).byte_size(); 1308 total_size += size; 1309 } 1310 1311 log_debug(cds)("Archive heap region %d: " INTPTR_FORMAT " - " INTPTR_FORMAT " = " SIZE_FORMAT_W(8) " bytes", 1312 i, p2i(start), p2i(start + size), size); 1313 write_region(i, start, size, false, false); 1314 if (size > 0) { 1315 space_at(i)->init_oopmap(oopmaps->at(arr_idx)._offset, 1316 oopmaps->at(arr_idx)._oopmap_size_in_bits); 1317 } 1318 } 1319 return total_size; 1320 } 1321 1322 // Dump bytes to file -- at the current file position. 1323 1324 void FileMapInfo::write_bytes(const void* buffer, size_t nbytes) { 1325 assert(_file_open, "must be"); 1326 size_t n = os::write(_fd, buffer, (unsigned int)nbytes); 1327 if (n != nbytes) { 1328 // If the shared archive is corrupted, close it and remove it. 1329 close(); 1330 remove(_full_path); 1331 fail_stop("Unable to write to shared archive file."); 1332 } 1333 _file_offset += nbytes; 1334 } 1335 1336 bool FileMapInfo::is_file_position_aligned() const { 1337 return _file_offset == align_up(_file_offset, 1338 os::vm_allocation_granularity()); 1339 } 1340 1341 // Align file position to an allocation unit boundary. 1342 1343 void FileMapInfo::align_file_position() { 1344 assert(_file_open, "must be"); 1345 size_t new_file_offset = align_up(_file_offset, 1346 os::vm_allocation_granularity()); 1347 if (new_file_offset != _file_offset) { 1348 _file_offset = new_file_offset; 1349 // Seek one byte back from the target and write a byte to insure 1350 // that the written file is the correct length. 1351 _file_offset -= 1; 1352 seek_to_position(_file_offset); 1353 char zero = 0; 1354 write_bytes(&zero, 1); 1355 } 1356 } 1357 1358 1359 // Dump bytes to file -- at the current file position. 1360 1361 void FileMapInfo::write_bytes_aligned(const void* buffer, size_t nbytes) { 1362 align_file_position(); 1363 write_bytes(buffer, nbytes); 1364 align_file_position(); 1365 } 1366 1367 void FileMapInfo::set_final_requested_base(char* b) { 1368 header()->set_final_requested_base(b); 1369 } 1370 1371 // Close the shared archive file. This does NOT unmap mapped regions. 1372 1373 void FileMapInfo::close() { 1374 if (_file_open) { 1375 if (::close(_fd) < 0) { 1376 fail_stop("Unable to close the shared archive file."); 1377 } 1378 _file_open = false; 1379 _fd = -1; 1380 } 1381 } 1382 1383 1384 // JVM/TI RedefineClasses() support: 1385 // Remap the shared readonly space to shared readwrite, private. 1386 bool FileMapInfo::remap_shared_readonly_as_readwrite() { 1387 int idx = MetaspaceShared::ro; 1388 FileMapRegion* si = space_at(idx); 1389 if (!si->read_only()) { 1390 // the space is already readwrite so we are done 1391 return true; 1392 } 1393 size_t used = si->used(); 1394 size_t size = align_up(used, os::vm_allocation_granularity()); 1395 if (!open_for_read()) { 1396 return false; 1397 } 1398 char *addr = region_addr(idx); 1399 char *base = os::remap_memory(_fd, _full_path, si->file_offset(), 1400 addr, size, false /* !read_only */, 1401 si->allow_exec()); 1402 close(); 1403 // These have to be errors because the shared region is now unmapped. 1404 if (base == NULL) { 1405 log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno); 1406 vm_exit(1); 1407 } 1408 if (base != addr) { 1409 log_error(cds)("Unable to remap shared readonly space (errno=%d).", errno); 1410 vm_exit(1); 1411 } 1412 si->set_read_only(false); 1413 return true; 1414 } 1415 1416 // Memory map a region in the address space. 1417 static const char* shared_region_name[] = { "MiscCode", "ReadWrite", "ReadOnly", "Bitmap", 1418 "String1", "String2", "OpenArchive1", "OpenArchive2" }; 1419 1420 MapArchiveResult FileMapInfo::map_regions(int regions[], int num_regions, char* mapped_base_address, ReservedSpace rs) { 1421 DEBUG_ONLY(FileMapRegion* last_region = NULL); 1422 intx addr_delta = mapped_base_address - header()->requested_base_address(); 1423 1424 // Make sure we don't attempt to use header()->mapped_base_address() unless 1425 // it's been successfully mapped. 1426 DEBUG_ONLY(header()->set_mapped_base_address((char*)(uintptr_t)0xdeadbeef);) 1427 1428 for (int r = 0; r < num_regions; r++) { 1429 int idx = regions[r]; 1430 MapArchiveResult result = map_region(idx, addr_delta, mapped_base_address, rs); 1431 if (result != MAP_ARCHIVE_SUCCESS) { 1432 return result; 1433 } 1434 FileMapRegion* si = space_at(idx); 1435 DEBUG_ONLY(if (last_region != NULL) { 1436 // Ensure that the OS won't be able to allocate new memory spaces between any mapped 1437 // regions, or else it would mess up the simple comparision in MetaspaceObj::is_shared(). 1438 assert(si->mapped_base() == last_region->mapped_end(), "must have no gaps"); 1439 } 1440 last_region = si;) 1441 log_info(cds)("Mapped %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)", is_static() ? "static " : "dynamic", 1442 idx, p2i(si->mapped_base()), p2i(si->mapped_end()), 1443 shared_region_name[idx]); 1444 1445 } 1446 1447 header()->set_mapped_base_address(header()->requested_base_address() + addr_delta); 1448 if (addr_delta != 0 && !relocate_pointers(addr_delta)) { 1449 return MAP_ARCHIVE_OTHER_FAILURE; 1450 } 1451 1452 return MAP_ARCHIVE_SUCCESS; 1453 } 1454 1455 bool FileMapInfo::read_region(int i, char* base, size_t size) { 1456 assert(MetaspaceShared::use_windows_memory_mapping(), "used by windows only"); 1457 FileMapRegion* si = space_at(i); 1458 log_info(cds)("Commit %s region #%d at base " INTPTR_FORMAT " top " INTPTR_FORMAT " (%s)%s", 1459 is_static() ? "static " : "dynamic", i, p2i(base), p2i(base + size), 1460 shared_region_name[i], si->allow_exec() ? " exec" : ""); 1461 if (!os::commit_memory(base, size, si->allow_exec())) { 1462 log_error(cds)("Failed to commit %s region #%d (%s)", is_static() ? "static " : "dynamic", 1463 i, shared_region_name[i]); 1464 return false; 1465 } 1466 if (lseek(_fd, (long)si->file_offset(), SEEK_SET) != (int)si->file_offset() || 1467 read_bytes(base, size) != size) { 1468 return false; 1469 } 1470 return true; 1471 } 1472 1473 MapArchiveResult FileMapInfo::map_region(int i, intx addr_delta, char* mapped_base_address, ReservedSpace rs) { 1474 assert(!HeapShared::is_heap_region(i), "sanity"); 1475 FileMapRegion* si = space_at(i); 1476 size_t size = si->used_aligned(); 1477 char *requested_addr = mapped_base_address + si->mapping_offset(); 1478 assert(si->mapped_base() == NULL, "must be not mapped yet"); 1479 assert(requested_addr != NULL, "must be specified"); 1480 1481 si->set_mapped_from_file(false); 1482 1483 if (MetaspaceShared::use_windows_memory_mapping()) { 1484 // Windows cannot remap read-only shared memory to read-write when required for 1485 // RedefineClasses, which is also used by JFR. Always map windows regions as RW. 1486 si->set_read_only(false); 1487 } else if (JvmtiExport::can_modify_any_class() || JvmtiExport::can_walk_any_space() || 1488 Arguments::has_jfr_option()) { 1489 // If a tool agent is in use (debugging enabled), or JFR, we must map the address space RW 1490 si->set_read_only(false); 1491 } else if (addr_delta != 0) { 1492 si->set_read_only(false); // Need to patch the pointers 1493 } 1494 1495 if (rs.is_reserved()) { 1496 assert(rs.contains(requested_addr) && rs.contains(requested_addr + size - 1), "must be"); 1497 MemTracker::record_virtual_memory_type((address)requested_addr, mtClassShared); 1498 } 1499 1500 if (MetaspaceShared::use_windows_memory_mapping() && rs.is_reserved()) { 1501 // This is the second time we try to map the archive(s). We have already created a ReservedSpace 1502 // that covers all the FileMapRegions to ensure all regions can be mapped. However, Windows 1503 // can't mmap into a ReservedSpace, so we just os::read() the data. We're going to patch all the 1504 // regions anyway, so there's no benefit for mmap anyway. 1505 if (!read_region(i, requested_addr, size)) { 1506 log_info(cds)("Failed to read %s shared space into reserved space at " INTPTR_FORMAT, 1507 shared_region_name[i], p2i(requested_addr)); 1508 return MAP_ARCHIVE_OTHER_FAILURE; // oom or I/O error. 1509 } 1510 } else { 1511 char* base = os::map_memory(_fd, _full_path, si->file_offset(), 1512 requested_addr, size, si->read_only(), 1513 si->allow_exec()); 1514 if (base != requested_addr) { 1515 log_info(cds)("Unable to map %s shared space at " INTPTR_FORMAT, 1516 shared_region_name[i], p2i(requested_addr)); 1517 _memory_mapping_failed = true; 1518 return MAP_ARCHIVE_MMAP_FAILURE; 1519 } 1520 si->set_mapped_from_file(true); 1521 } 1522 si->set_mapped_base(requested_addr); 1523 1524 if (!rs.is_reserved()) { 1525 // When mapping on Windows for the first attempt, we don't reserve the address space for the regions 1526 // (Windows can't mmap into a ReservedSpace). In this case, NMT requires we call it after 1527 // os::map_memory has succeeded. 1528 assert(MetaspaceShared::use_windows_memory_mapping(), "Windows memory mapping only"); 1529 MemTracker::record_virtual_memory_type((address)requested_addr, mtClassShared); 1530 } 1531 1532 if (VerifySharedSpaces && !verify_region_checksum(i)) { 1533 return MAP_ARCHIVE_OTHER_FAILURE; 1534 } 1535 1536 return MAP_ARCHIVE_SUCCESS; 1537 } 1538 1539 // The return value is the location of the archive relocation bitmap. 1540 char* FileMapInfo::map_bitmap_region() { 1541 FileMapRegion* si = space_at(MetaspaceShared::bm); 1542 if (si->mapped_base() != NULL) { 1543 return si->mapped_base(); 1544 } 1545 bool read_only = true, allow_exec = false; 1546 char* requested_addr = NULL; // allow OS to pick any location 1547 char* bitmap_base = os::map_memory(_fd, _full_path, si->file_offset(), 1548 requested_addr, si->used_aligned(), read_only, allow_exec); 1549 if (bitmap_base == NULL) { 1550 log_error(cds)("failed to map relocation bitmap"); 1551 return NULL; 1552 } 1553 1554 if (VerifySharedSpaces && !region_crc_check(bitmap_base, si->used_aligned(), si->crc())) { 1555 log_error(cds)("relocation bitmap CRC error"); 1556 if (!os::unmap_memory(bitmap_base, si->used_aligned())) { 1557 fatal("os::unmap_memory of relocation bitmap failed"); 1558 } 1559 return NULL; 1560 } 1561 1562 si->set_mapped_base(bitmap_base); 1563 si->set_mapped_from_file(true); 1564 return bitmap_base; 1565 } 1566 1567 bool FileMapInfo::relocate_pointers(intx addr_delta) { 1568 log_debug(cds, reloc)("runtime archive relocation start"); 1569 char* bitmap_base = map_bitmap_region(); 1570 1571 if (bitmap_base == NULL) { 1572 return false; 1573 } else { 1574 size_t ptrmap_size_in_bits = header()->ptrmap_size_in_bits(); 1575 log_debug(cds, reloc)("mapped relocation bitmap @ " INTPTR_FORMAT " (" SIZE_FORMAT " bits)", 1576 p2i(bitmap_base), ptrmap_size_in_bits); 1577 1578 BitMapView ptrmap((BitMap::bm_word_t*)bitmap_base, ptrmap_size_in_bits); 1579 1580 // Patch all pointers in the the mapped region that are marked by ptrmap. 1581 address patch_base = (address)mapped_base(); 1582 address patch_end = (address)mapped_end(); 1583 1584 // the current value of the pointers to be patched must be within this 1585 // range (i.e., must be between the requesed base address, and the of the current archive). 1586 // Note: top archive may point to objects in the base archive, but not the other way around. 1587 address valid_old_base = (address)header()->requested_base_address(); 1588 address valid_old_end = valid_old_base + mapping_end_offset(); 1589 1590 // after patching, the pointers must point inside this range 1591 // (the requested location of the archive, as mapped at runtime). 1592 address valid_new_base = (address)header()->mapped_base_address(); 1593 address valid_new_end = (address)mapped_end(); 1594 1595 SharedDataRelocator<false> patcher((address*)patch_base, (address*)patch_end, valid_old_base, valid_old_end, 1596 valid_new_base, valid_new_end, addr_delta); 1597 ptrmap.iterate(&patcher); 1598 1599 // The MetaspaceShared::bm region will be unmapped in MetaspaceShared::initialize_shared_spaces(). 1600 1601 log_debug(cds, reloc)("runtime archive relocation done"); 1602 return true; 1603 } 1604 } 1605 1606 size_t FileMapInfo::read_bytes(void* buffer, size_t count) { 1607 assert(_file_open, "Archive file is not open"); 1608 size_t n = os::read(_fd, buffer, (unsigned int)count); 1609 if (n != count) { 1610 // Close the file if there's a problem reading it. 1611 close(); 1612 return 0; 1613 } 1614 _file_offset += count; 1615 return count; 1616 } 1617 1618 address FileMapInfo::decode_start_address(FileMapRegion* spc, bool with_current_oop_encoding_mode) { 1619 size_t offset = spc->mapping_offset(); 1620 assert(offset == (size_t)(uint32_t)offset, "must be 32-bit only"); 1621 uint n = (uint)offset; 1622 if (with_current_oop_encoding_mode) { 1623 return cast_from_oop<address>(CompressedOops::decode_not_null(n)); 1624 } else { 1625 return cast_from_oop<address>(HeapShared::decode_from_archive(n)); 1626 } 1627 } 1628 1629 static MemRegion *closed_archive_heap_ranges = NULL; 1630 static MemRegion *open_archive_heap_ranges = NULL; 1631 static int num_closed_archive_heap_ranges = 0; 1632 static int num_open_archive_heap_ranges = 0; 1633 1634 #if INCLUDE_CDS_JAVA_HEAP 1635 bool FileMapInfo::has_heap_regions() { 1636 return (space_at(MetaspaceShared::first_closed_archive_heap_region)->used() > 0); 1637 } 1638 1639 // Returns the address range of the archived heap regions computed using the 1640 // current oop encoding mode. This range may be different than the one seen at 1641 // dump time due to encoding mode differences. The result is used in determining 1642 // if/how these regions should be relocated at run time. 1643 MemRegion FileMapInfo::get_heap_regions_range_with_current_oop_encoding_mode() { 1644 address start = (address) max_uintx; 1645 address end = NULL; 1646 1647 for (int i = MetaspaceShared::first_closed_archive_heap_region; 1648 i <= MetaspaceShared::last_valid_region; 1649 i++) { 1650 FileMapRegion* si = space_at(i); 1651 size_t size = si->used(); 1652 if (size > 0) { 1653 address s = start_address_as_decoded_with_current_oop_encoding_mode(si); 1654 address e = s + size; 1655 if (start > s) { 1656 start = s; 1657 } 1658 if (end < e) { 1659 end = e; 1660 } 1661 } 1662 } 1663 assert(end != NULL, "must have at least one used heap region"); 1664 return MemRegion((HeapWord*)start, (HeapWord*)end); 1665 } 1666 1667 // 1668 // Map the closed and open archive heap objects to the runtime java heap. 1669 // 1670 // The shared objects are mapped at (or close to ) the java heap top in 1671 // closed archive regions. The mapped objects contain no out-going 1672 // references to any other java heap regions. GC does not write into the 1673 // mapped closed archive heap region. 1674 // 1675 // The open archive heap objects are mapped below the shared objects in 1676 // the runtime java heap. The mapped open archive heap data only contains 1677 // references to the shared objects and open archive objects initially. 1678 // During runtime execution, out-going references to any other java heap 1679 // regions may be added. GC may mark and update references in the mapped 1680 // open archive objects. 1681 void FileMapInfo::map_heap_regions_impl() { 1682 if (!HeapShared::is_heap_object_archiving_allowed()) { 1683 log_info(cds)("CDS heap data is being ignored. UseG1GC, " 1684 "UseCompressedOops and UseCompressedClassPointers are required."); 1685 return; 1686 } 1687 1688 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) { 1689 ShouldNotReachHere(); // CDS should have been disabled. 1690 // The archived objects are mapped at JVM start-up, but we don't know if 1691 // j.l.String or j.l.Class might be replaced by the ClassFileLoadHook, 1692 // which would make the archived String or mirror objects invalid. Let's be safe and not 1693 // use the archived objects. These 2 classes are loaded during the JVMTI "early" stage. 1694 // 1695 // If JvmtiExport::has_early_class_hook_env() is false, the classes of some objects 1696 // in the archived subgraphs may be replaced by the ClassFileLoadHook. But that's OK 1697 // because we won't install an archived object subgraph if the klass of any of the 1698 // referenced objects are replaced. See HeapShared::initialize_from_archived_subgraph(). 1699 } 1700 1701 log_info(cds)("CDS archive was created with max heap size = " SIZE_FORMAT "M, and the following configuration:", 1702 max_heap_size()/M); 1703 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 1704 p2i(narrow_klass_base()), narrow_klass_shift()); 1705 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 1706 narrow_oop_mode(), p2i(narrow_oop_base()), narrow_oop_shift()); 1707 1708 log_info(cds)("The current max heap size = " SIZE_FORMAT "M, HeapRegion::GrainBytes = " SIZE_FORMAT, 1709 MaxHeapSize/M, HeapRegion::GrainBytes); 1710 log_info(cds)(" narrow_klass_base = " PTR_FORMAT ", narrow_klass_shift = %d", 1711 p2i(CompressedKlassPointers::base()), CompressedKlassPointers::shift()); 1712 log_info(cds)(" narrow_oop_mode = %d, narrow_oop_base = " PTR_FORMAT ", narrow_oop_shift = %d", 1713 CompressedOops::mode(), p2i(CompressedOops::base()), CompressedOops::shift()); 1714 1715 if (narrow_klass_base() != CompressedKlassPointers::base() || 1716 narrow_klass_shift() != CompressedKlassPointers::shift()) { 1717 log_info(cds)("CDS heap data cannot be used because the archive was created with an incompatible narrow klass encoding mode."); 1718 return; 1719 } 1720 1721 if (narrow_oop_mode() != CompressedOops::mode() || 1722 narrow_oop_base() != CompressedOops::base() || 1723 narrow_oop_shift() != CompressedOops::shift()) { 1724 log_info(cds)("CDS heap data need to be relocated because the archive was created with an incompatible oop encoding mode."); 1725 _heap_pointers_need_patching = true; 1726 } else { 1727 MemRegion range = get_heap_regions_range_with_current_oop_encoding_mode(); 1728 if (!CompressedOops::is_in(range)) { 1729 log_info(cds)("CDS heap data need to be relocated because"); 1730 log_info(cds)("the desired range " PTR_FORMAT " - " PTR_FORMAT, p2i(range.start()), p2i(range.end())); 1731 log_info(cds)("is outside of the heap " PTR_FORMAT " - " PTR_FORMAT, p2i(CompressedOops::begin()), p2i(CompressedOops::end())); 1732 _heap_pointers_need_patching = true; 1733 } 1734 } 1735 1736 ptrdiff_t delta = 0; 1737 if (_heap_pointers_need_patching) { 1738 // dumptime heap end ------------v 1739 // [ |archived heap regions| ] runtime heap end ------v 1740 // [ |archived heap regions| ] 1741 // |<-----delta-------------------->| 1742 // 1743 // At dump time, the archived heap regions were near the top of the heap. 1744 // At run time, they may not be inside the heap, so we move them so 1745 // that they are now near the top of the runtime time. This can be done by 1746 // the simple math of adding the delta as shown above. 1747 address dumptime_heap_end = header()->heap_end(); 1748 address runtime_heap_end = (address)CompressedOops::end(); 1749 delta = runtime_heap_end - dumptime_heap_end; 1750 } 1751 1752 log_info(cds)("CDS heap data relocation delta = " INTX_FORMAT " bytes", delta); 1753 HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift()); 1754 1755 FileMapRegion* si = space_at(MetaspaceShared::first_closed_archive_heap_region); 1756 address relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si); 1757 if (!is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes)) { 1758 // Align the bottom of the closed archive heap regions at G1 region boundary. 1759 // This will avoid the situation where the highest open region and the lowest 1760 // closed region sharing the same G1 region. Otherwise we will fail to map the 1761 // open regions. 1762 size_t align = size_t(relocated_closed_heap_region_bottom) % HeapRegion::GrainBytes; 1763 delta -= align; 1764 log_info(cds)("CDS heap data need to be relocated lower by a further " SIZE_FORMAT 1765 " bytes to " INTX_FORMAT " to be aligned with HeapRegion::GrainBytes", 1766 align, delta); 1767 HeapShared::init_narrow_oop_decoding(narrow_oop_base() + delta, narrow_oop_shift()); 1768 _heap_pointers_need_patching = true; 1769 relocated_closed_heap_region_bottom = start_address_as_decoded_from_archive(si); 1770 } 1771 assert(is_aligned(relocated_closed_heap_region_bottom, HeapRegion::GrainBytes), 1772 "must be"); 1773 1774 // Map the closed_archive_heap regions, GC does not write into the regions. 1775 if (map_heap_data(&closed_archive_heap_ranges, 1776 MetaspaceShared::first_closed_archive_heap_region, 1777 MetaspaceShared::max_closed_archive_heap_region, 1778 &num_closed_archive_heap_ranges)) { 1779 HeapShared::set_closed_archive_heap_region_mapped(); 1780 1781 // Now, map open_archive heap regions, GC can write into the regions. 1782 if (map_heap_data(&open_archive_heap_ranges, 1783 MetaspaceShared::first_open_archive_heap_region, 1784 MetaspaceShared::max_open_archive_heap_region, 1785 &num_open_archive_heap_ranges, 1786 true /* open */)) { 1787 HeapShared::set_open_archive_heap_region_mapped(); 1788 } 1789 } 1790 } 1791 1792 void FileMapInfo::map_heap_regions() { 1793 if (has_heap_regions()) { 1794 map_heap_regions_impl(); 1795 } 1796 1797 if (!HeapShared::closed_archive_heap_region_mapped()) { 1798 assert(closed_archive_heap_ranges == NULL && 1799 num_closed_archive_heap_ranges == 0, "sanity"); 1800 } 1801 1802 if (!HeapShared::open_archive_heap_region_mapped()) { 1803 assert(open_archive_heap_ranges == NULL && num_open_archive_heap_ranges == 0, "sanity"); 1804 } 1805 } 1806 1807 bool FileMapInfo::map_heap_data(MemRegion **heap_mem, int first, 1808 int max, int* num, bool is_open_archive) { 1809 MemRegion* regions = MemRegion::create_array(max, mtInternal); 1810 1811 struct Cleanup { 1812 MemRegion* _regions; 1813 uint _length; 1814 bool _aborted; 1815 Cleanup(MemRegion* regions, uint length) : _regions(regions), _length(length), _aborted(true) { } 1816 ~Cleanup() { if (_aborted) { MemRegion::destroy_array(_regions, _length); } } 1817 } cleanup(regions, max); 1818 1819 FileMapRegion* si; 1820 int region_num = 0; 1821 1822 for (int i = first; 1823 i < first + max; i++) { 1824 si = space_at(i); 1825 size_t size = si->used(); 1826 if (size > 0) { 1827 HeapWord* start = (HeapWord*)start_address_as_decoded_from_archive(si); 1828 regions[region_num] = MemRegion(start, size / HeapWordSize); 1829 region_num ++; 1830 log_info(cds)("Trying to map heap data: region[%d] at " INTPTR_FORMAT ", size = " SIZE_FORMAT_W(8) " bytes", 1831 i, p2i(start), size); 1832 } 1833 } 1834 1835 if (region_num == 0) { 1836 return false; // no archived java heap data 1837 } 1838 1839 // Check that ranges are within the java heap 1840 if (!G1CollectedHeap::heap()->check_archive_addresses(regions, region_num)) { 1841 log_info(cds)("UseSharedSpaces: Unable to allocate region, range is not within java heap."); 1842 return false; 1843 } 1844 1845 // allocate from java heap 1846 if (!G1CollectedHeap::heap()->alloc_archive_regions( 1847 regions, region_num, is_open_archive)) { 1848 log_info(cds)("UseSharedSpaces: Unable to allocate region, java heap range is already in use."); 1849 return false; 1850 } 1851 1852 // Map the archived heap data. No need to call MemTracker::record_virtual_memory_type() 1853 // for mapped regions as they are part of the reserved java heap, which is 1854 // already recorded. 1855 for (int i = 0; i < region_num; i++) { 1856 si = space_at(first + i); 1857 char* addr = (char*)regions[i].start(); 1858 char* base = os::map_memory(_fd, _full_path, si->file_offset(), 1859 addr, regions[i].byte_size(), si->read_only(), 1860 si->allow_exec()); 1861 if (base == NULL || base != addr) { 1862 // dealloc the regions from java heap 1863 dealloc_archive_heap_regions(regions, region_num); 1864 log_info(cds)("UseSharedSpaces: Unable to map at required address in java heap. " 1865 INTPTR_FORMAT ", size = " SIZE_FORMAT " bytes", 1866 p2i(addr), regions[i].byte_size()); 1867 return false; 1868 } 1869 1870 if (VerifySharedSpaces && !region_crc_check(addr, regions[i].byte_size(), si->crc())) { 1871 // dealloc the regions from java heap 1872 dealloc_archive_heap_regions(regions, region_num); 1873 log_info(cds)("UseSharedSpaces: mapped heap regions are corrupt"); 1874 return false; 1875 } 1876 } 1877 1878 cleanup._aborted = false; 1879 // the shared heap data is mapped successfully 1880 *heap_mem = regions; 1881 *num = region_num; 1882 return true; 1883 } 1884 1885 void FileMapInfo::patch_archived_heap_embedded_pointers() { 1886 if (!_heap_pointers_need_patching) { 1887 return; 1888 } 1889 1890 patch_archived_heap_embedded_pointers(closed_archive_heap_ranges, 1891 num_closed_archive_heap_ranges, 1892 MetaspaceShared::first_closed_archive_heap_region); 1893 1894 patch_archived_heap_embedded_pointers(open_archive_heap_ranges, 1895 num_open_archive_heap_ranges, 1896 MetaspaceShared::first_open_archive_heap_region); 1897 } 1898 1899 void FileMapInfo::patch_archived_heap_embedded_pointers(MemRegion* ranges, int num_ranges, 1900 int first_region_idx) { 1901 char* bitmap_base = map_bitmap_region(); 1902 if (bitmap_base == NULL) { 1903 return; 1904 } 1905 for (int i=0; i<num_ranges; i++) { 1906 FileMapRegion* si = space_at(i + first_region_idx); 1907 HeapShared::patch_archived_heap_embedded_pointers( 1908 ranges[i], 1909 (address)(space_at(MetaspaceShared::bm)->mapped_base()) + si->oopmap_offset(), 1910 si->oopmap_size_in_bits()); 1911 } 1912 } 1913 1914 // This internally allocates objects using SystemDictionary::Object_klass(), so it 1915 // must be called after the well-known classes are resolved. 1916 void FileMapInfo::fixup_mapped_heap_regions() { 1917 // If any closed regions were found, call the fill routine to make them parseable. 1918 // Note that closed_archive_heap_ranges may be non-NULL even if no ranges were found. 1919 if (num_closed_archive_heap_ranges != 0) { 1920 assert(closed_archive_heap_ranges != NULL, 1921 "Null closed_archive_heap_ranges array with non-zero count"); 1922 G1CollectedHeap::heap()->fill_archive_regions(closed_archive_heap_ranges, 1923 num_closed_archive_heap_ranges); 1924 } 1925 1926 // do the same for mapped open archive heap regions 1927 if (num_open_archive_heap_ranges != 0) { 1928 assert(open_archive_heap_ranges != NULL, "NULL open_archive_heap_ranges array with non-zero count"); 1929 G1CollectedHeap::heap()->fill_archive_regions(open_archive_heap_ranges, 1930 num_open_archive_heap_ranges); 1931 } 1932 } 1933 1934 // dealloc the archive regions from java heap 1935 void FileMapInfo::dealloc_archive_heap_regions(MemRegion* regions, int num) { 1936 if (num > 0) { 1937 assert(regions != NULL, "Null archive ranges array with non-zero count"); 1938 G1CollectedHeap::heap()->dealloc_archive_regions(regions, num); 1939 } 1940 } 1941 #endif // INCLUDE_CDS_JAVA_HEAP 1942 1943 bool FileMapInfo::region_crc_check(char* buf, size_t size, int expected_crc) { 1944 int crc = ClassLoader::crc32(0, buf, (jint)size); 1945 if (crc != expected_crc) { 1946 fail_continue("Checksum verification failed."); 1947 return false; 1948 } 1949 return true; 1950 } 1951 1952 bool FileMapInfo::verify_region_checksum(int i) { 1953 assert(VerifySharedSpaces, "sanity"); 1954 size_t sz = space_at(i)->used(); 1955 1956 if (sz == 0) { 1957 return true; // no data 1958 } else { 1959 return region_crc_check(region_addr(i), sz, space_at(i)->crc()); 1960 } 1961 } 1962 1963 void FileMapInfo::unmap_regions(int regions[], int num_regions) { 1964 for (int r = 0; r < num_regions; r++) { 1965 int idx = regions[r]; 1966 unmap_region(idx); 1967 } 1968 } 1969 1970 // Unmap a memory region in the address space. 1971 1972 void FileMapInfo::unmap_region(int i) { 1973 assert(!HeapShared::is_heap_region(i), "sanity"); 1974 FileMapRegion* si = space_at(i); 1975 char* mapped_base = si->mapped_base(); 1976 size_t used = si->used(); 1977 size_t size = align_up(used, os::vm_allocation_granularity()); 1978 1979 if (mapped_base != NULL && size > 0 && si->mapped_from_file()) { 1980 log_info(cds)("Unmapping region #%d at base " INTPTR_FORMAT " (%s)", i, p2i(mapped_base), 1981 shared_region_name[i]); 1982 if (!os::unmap_memory(mapped_base, size)) { 1983 fatal("os::unmap_memory failed"); 1984 } 1985 si->set_mapped_base(NULL); 1986 } 1987 } 1988 1989 void FileMapInfo::assert_mark(bool check) { 1990 if (!check) { 1991 fail_stop("Mark mismatch while restoring from shared file."); 1992 } 1993 } 1994 1995 void FileMapInfo::metaspace_pointers_do(MetaspaceClosure* it, bool use_copy) { 1996 if (use_copy) { 1997 _saved_shared_path_table.metaspace_pointers_do(it); 1998 } else { 1999 _shared_path_table.metaspace_pointers_do(it); 2000 } 2001 } 2002 2003 FileMapInfo* FileMapInfo::_current_info = NULL; 2004 FileMapInfo* FileMapInfo::_dynamic_archive_info = NULL; 2005 bool FileMapInfo::_heap_pointers_need_patching = false; 2006 SharedPathTable FileMapInfo::_shared_path_table; 2007 SharedPathTable FileMapInfo::_saved_shared_path_table; 2008 bool FileMapInfo::_validating_shared_path_table = false; 2009 bool FileMapInfo::_memory_mapping_failed = false; 2010 GrowableArray<const char*>* FileMapInfo::_non_existent_class_paths = NULL; 2011 2012 // Open the shared archive file, read and validate the header 2013 // information (version, boot classpath, etc.). If initialization 2014 // fails, shared spaces are disabled and the file is closed. [See 2015 // fail_continue.] 2016 // 2017 // Validation of the archive is done in two steps: 2018 // 2019 // [1] validate_header() - done here. 2020 // [2] validate_shared_path_table - this is done later, because the table is in the RW 2021 // region of the archive, which is not mapped yet. 2022 bool FileMapInfo::initialize() { 2023 assert(UseSharedSpaces, "UseSharedSpaces expected."); 2024 2025 if (JvmtiExport::should_post_class_file_load_hook() && JvmtiExport::has_early_class_hook_env()) { 2026 // CDS assumes that no classes resolved in SystemDictionary::resolve_well_known_classes 2027 // are replaced at runtime by JVMTI ClassFileLoadHook. All of those classes are resolved 2028 // during the JVMTI "early" stage, so we can still use CDS if 2029 // JvmtiExport::has_early_class_hook_env() is false. 2030 FileMapInfo::fail_continue("CDS is disabled because early JVMTI ClassFileLoadHook is in use."); 2031 return false; 2032 } 2033 2034 if (!open_for_read()) { 2035 return false; 2036 } 2037 if (!init_from_file(_fd)) { 2038 return false; 2039 } 2040 if (!validate_header()) { 2041 return false; 2042 } 2043 return true; 2044 } 2045 2046 char* FileMapInfo::region_addr(int idx) { 2047 FileMapRegion* si = space_at(idx); 2048 if (HeapShared::is_heap_region(idx)) { 2049 assert(DumpSharedSpaces, "The following doesn't work at runtime"); 2050 return si->used() > 0 ? 2051 (char*)start_address_as_decoded_with_current_oop_encoding_mode(si) : NULL; 2052 } else { 2053 return si->mapped_base(); 2054 } 2055 } 2056 2057 // The 3 core spaces are MC->RW->RO 2058 FileMapRegion* FileMapInfo::first_core_space() const { 2059 return space_at(MetaspaceShared::mc); 2060 } 2061 2062 FileMapRegion* FileMapInfo::last_core_space() const { 2063 return space_at(MetaspaceShared::ro); 2064 } 2065 2066 int FileMapHeader::compute_crc() { 2067 char* start = (char*)this; 2068 // start computing from the field after _crc 2069 char* buf = (char*)&_crc + sizeof(_crc); 2070 size_t sz = _header_size - (buf - start); 2071 int crc = ClassLoader::crc32(0, buf, (jint)sz); 2072 return crc; 2073 } 2074 2075 // This function should only be called during run time with UseSharedSpaces enabled. 2076 bool FileMapHeader::validate() { 2077 if (_obj_alignment != ObjectAlignmentInBytes) { 2078 FileMapInfo::fail_continue("The shared archive file's ObjectAlignmentInBytes of %d" 2079 " does not equal the current ObjectAlignmentInBytes of " INTX_FORMAT ".", 2080 _obj_alignment, ObjectAlignmentInBytes); 2081 return false; 2082 } 2083 if (_compact_strings != CompactStrings) { 2084 FileMapInfo::fail_continue("The shared archive file's CompactStrings setting (%s)" 2085 " does not equal the current CompactStrings setting (%s).", 2086 _compact_strings ? "enabled" : "disabled", 2087 CompactStrings ? "enabled" : "disabled"); 2088 return false; 2089 } 2090 2091 // This must be done after header validation because it might change the 2092 // header data 2093 const char* prop = Arguments::get_property("java.system.class.loader"); 2094 if (prop != NULL) { 2095 warning("Archived non-system classes are disabled because the " 2096 "java.system.class.loader property is specified (value = \"%s\"). " 2097 "To use archived non-system classes, this property must not be set", prop); 2098 _has_platform_or_app_classes = false; 2099 } 2100 2101 // For backwards compatibility, we don't check the verification setting 2102 // if the archive only contains system classes. 2103 if (_has_platform_or_app_classes && 2104 ((!_verify_local && BytecodeVerificationLocal) || 2105 (!_verify_remote && BytecodeVerificationRemote))) { 2106 FileMapInfo::fail_continue("The shared archive file was created with less restrictive " 2107 "verification setting than the current setting."); 2108 return false; 2109 } 2110 2111 // Java agents are allowed during run time. Therefore, the following condition is not 2112 // checked: (!_allow_archiving_with_java_agent && AllowArchivingWithJavaAgent) 2113 // Note: _allow_archiving_with_java_agent is set in the shared archive during dump time 2114 // while AllowArchivingWithJavaAgent is set during the current run. 2115 if (_allow_archiving_with_java_agent && !AllowArchivingWithJavaAgent) { 2116 FileMapInfo::fail_continue("The setting of the AllowArchivingWithJavaAgent is different " 2117 "from the setting in the shared archive."); 2118 return false; 2119 } 2120 2121 if (_allow_archiving_with_java_agent) { 2122 warning("This archive was created with AllowArchivingWithJavaAgent. It should be used " 2123 "for testing purposes only and should not be used in a production environment"); 2124 } 2125 2126 log_info(cds)("Archive was created with UseCompressedOops = %d, UseCompressedClassPointers = %d", 2127 compressed_oops(), compressed_class_pointers()); 2128 if (compressed_oops() != UseCompressedOops || compressed_class_pointers() != UseCompressedClassPointers) { 2129 FileMapInfo::fail_continue("Unable to use shared archive.\nThe saved state of UseCompressedOops and UseCompressedClassPointers is " 2130 "different from runtime, CDS will be disabled."); 2131 return false; 2132 } 2133 2134 return true; 2135 } 2136 2137 bool FileMapInfo::validate_header() { 2138 return header()->validate(); 2139 } 2140 2141 // Check if a given address is within one of the shared regions 2142 bool FileMapInfo::is_in_shared_region(const void* p, int idx) { 2143 assert(idx == MetaspaceShared::ro || 2144 idx == MetaspaceShared::rw || 2145 idx == MetaspaceShared::mc, "invalid region index"); 2146 char* base = region_addr(idx); 2147 if (p >= base && p < base + space_at(idx)->used()) { 2148 return true; 2149 } 2150 return false; 2151 } 2152 2153 // Unmap mapped regions of shared space. 2154 void FileMapInfo::stop_sharing_and_unmap(const char* msg) { 2155 MetaspaceShared::set_shared_metaspace_range(NULL, NULL, NULL); 2156 2157 FileMapInfo *map_info = FileMapInfo::current_info(); 2158 if (map_info) { 2159 map_info->fail_continue("%s", msg); 2160 for (int i = 0; i < MetaspaceShared::num_non_heap_spaces; i++) { 2161 if (!HeapShared::is_heap_region(i)) { 2162 map_info->unmap_region(i); 2163 } 2164 } 2165 // Dealloc the archive heap regions only without unmapping. The regions are part 2166 // of the java heap. Unmapping of the heap regions are managed by GC. 2167 map_info->dealloc_archive_heap_regions(open_archive_heap_ranges, 2168 num_open_archive_heap_ranges); 2169 map_info->dealloc_archive_heap_regions(closed_archive_heap_ranges, 2170 num_closed_archive_heap_ranges); 2171 } else if (DumpSharedSpaces) { 2172 fail_stop("%s", msg); 2173 } 2174 } 2175 2176 #if INCLUDE_JVMTI 2177 ClassPathEntry** FileMapInfo::_classpath_entries_for_jvmti = NULL; 2178 2179 ClassPathEntry* FileMapInfo::get_classpath_entry_for_jvmti(int i, TRAPS) { 2180 ClassPathEntry* ent = _classpath_entries_for_jvmti[i]; 2181 if (ent == NULL) { 2182 if (i == 0) { 2183 ent = ClassLoader::get_jrt_entry(); 2184 assert(ent != NULL, "must be"); 2185 } else { 2186 SharedClassPathEntry* scpe = shared_path(i); 2187 assert(scpe->is_jar(), "must be"); // other types of scpe will not produce archived classes 2188 2189 const char* path = scpe->name(); 2190 struct stat st; 2191 if (os::stat(path, &st) != 0) { 2192 char *msg = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(path) + 128); ; 2193 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path); 2194 THROW_MSG_(vmSymbols::java_io_IOException(), msg, NULL); 2195 } else { 2196 ent = ClassLoader::create_class_path_entry(path, &st, /*throw_exception=*/true, false, false, CHECK_NULL); 2197 } 2198 } 2199 2200 MutexLocker mu(THREAD, CDSClassFileStream_lock); 2201 if (_classpath_entries_for_jvmti[i] == NULL) { 2202 _classpath_entries_for_jvmti[i] = ent; 2203 } else { 2204 // Another thread has beat me to creating this entry 2205 delete ent; 2206 ent = _classpath_entries_for_jvmti[i]; 2207 } 2208 } 2209 2210 return ent; 2211 } 2212 2213 ClassFileStream* FileMapInfo::open_stream_for_jvmti(InstanceKlass* ik, Handle class_loader, TRAPS) { 2214 int path_index = ik->shared_classpath_index(); 2215 assert(path_index >= 0, "should be called for shared built-in classes only"); 2216 assert(path_index < (int)get_number_of_shared_paths(), "sanity"); 2217 2218 ClassPathEntry* cpe = get_classpath_entry_for_jvmti(path_index, CHECK_NULL); 2219 assert(cpe != NULL, "must be"); 2220 2221 Symbol* name = ik->name(); 2222 const char* const class_name = name->as_C_string(); 2223 const char* const file_name = ClassLoader::file_name_for_class_name(class_name, 2224 name->utf8_length()); 2225 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader()); 2226 ClassFileStream* cfs = cpe->open_stream_for_loader(file_name, loader_data, THREAD); 2227 assert(cfs != NULL, "must be able to read the classfile data of shared classes for built-in loaders."); 2228 log_debug(cds, jvmti)("classfile data for %s [%d: %s] = %d bytes", class_name, path_index, 2229 cfs->source(), cfs->length()); 2230 return cfs; 2231 } 2232 2233 #endif