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