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