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