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