1 /* 2 * Copyright (c) 1997, 2024, 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 "cds/cds_globals.hpp" 27 #include "cds/cdsConfig.hpp" 28 #include "cds/filemap.hpp" 29 #include "classfile/classFileStream.hpp" 30 #include "classfile/classLoader.inline.hpp" 31 #include "classfile/classLoaderData.inline.hpp" 32 #include "classfile/classLoaderExt.hpp" 33 #include "classfile/classLoadInfo.hpp" 34 #include "classfile/javaClasses.hpp" 35 #include "classfile/moduleEntry.hpp" 36 #include "classfile/modules.hpp" 37 #include "classfile/packageEntry.hpp" 38 #include "classfile/klassFactory.hpp" 39 #include "classfile/symbolTable.hpp" 40 #include "classfile/systemDictionary.hpp" 41 #include "classfile/systemDictionaryShared.hpp" 42 #include "classfile/vmClasses.hpp" 43 #include "classfile/vmSymbols.hpp" 44 #include "compiler/compileBroker.hpp" 45 #include "interpreter/bytecodeStream.hpp" 46 #include "interpreter/oopMapCache.hpp" 47 #include "jimage.hpp" 48 #include "jvm.h" 49 #include "logging/log.hpp" 50 #include "logging/logStream.hpp" 51 #include "logging/logTag.hpp" 52 #include "memory/allocation.inline.hpp" 53 #include "memory/oopFactory.hpp" 54 #include "memory/resourceArea.hpp" 55 #include "memory/universe.hpp" 56 #include "oops/instanceKlass.hpp" 57 #include "oops/instanceRefKlass.hpp" 58 #include "oops/klass.inline.hpp" 59 #include "oops/method.inline.hpp" 60 #include "oops/objArrayOop.inline.hpp" 61 #include "oops/oop.inline.hpp" 62 #include "oops/symbol.hpp" 63 #include "prims/jvm_misc.hpp" 64 #include "runtime/arguments.hpp" 65 #include "runtime/handles.inline.hpp" 66 #include "runtime/init.hpp" 67 #include "runtime/interfaceSupport.inline.hpp" 68 #include "runtime/java.hpp" 69 #include "runtime/javaCalls.hpp" 70 #include "runtime/os.hpp" 71 #include "runtime/perfData.hpp" 72 #include "runtime/threadCritical.hpp" 73 #include "runtime/timer.hpp" 74 #include "runtime/vm_version.hpp" 75 #include "services/management.hpp" 76 #include "services/threadService.hpp" 77 #include "utilities/checkedCast.hpp" 78 #include "utilities/classpathStream.hpp" 79 #include "utilities/events.hpp" 80 #include "utilities/macros.hpp" 81 #include "utilities/utf8.hpp" 82 83 // Entry point in java.dll for path canonicalization 84 85 typedef int (*canonicalize_fn_t)(const char *orig, char *out, int len); 86 87 static canonicalize_fn_t CanonicalizeEntry = nullptr; 88 89 // Entry points for jimage.dll for loading jimage file entries 90 91 static JImageOpen_t JImageOpen = nullptr; 92 static JImageClose_t JImageClose = nullptr; 93 static JImageFindResource_t JImageFindResource = nullptr; 94 static JImageGetResource_t JImageGetResource = nullptr; 95 96 // JimageFile pointer, or null if exploded JDK build. 97 static JImageFile* JImage_file = nullptr; 98 99 // Globals 100 101 PerfCounter* ClassLoader::_perf_accumulated_time = nullptr; 102 PerfCounter* ClassLoader::_perf_classes_inited = nullptr; 103 PerfCounter* ClassLoader::_perf_class_init_time = nullptr; 104 PerfCounter* ClassLoader::_perf_class_init_selftime = nullptr; 105 PerfCounter* ClassLoader::_perf_classes_verified = nullptr; 106 PerfCounter* ClassLoader::_perf_class_verify_time = nullptr; 107 PerfCounter* ClassLoader::_perf_class_verify_selftime = nullptr; 108 PerfCounter* ClassLoader::_perf_classes_linked = nullptr; 109 PerfCounter* ClassLoader::_perf_class_link_time = nullptr; 110 PerfCounter* ClassLoader::_perf_class_link_selftime = nullptr; 111 PerfCounter* ClassLoader::_perf_shared_classload_time = nullptr; 112 PerfCounter* ClassLoader::_perf_sys_classload_time = nullptr; 113 PerfCounter* ClassLoader::_perf_app_classload_time = nullptr; 114 PerfCounter* ClassLoader::_perf_app_classload_selftime = nullptr; 115 PerfCounter* ClassLoader::_perf_app_classload_count = nullptr; 116 PerfCounter* ClassLoader::_perf_define_appclasses = nullptr; 117 PerfCounter* ClassLoader::_perf_define_appclass_time = nullptr; 118 PerfCounter* ClassLoader::_perf_define_appclass_selftime = nullptr; 119 PerfCounter* ClassLoader::_perf_app_classfile_bytes_read = nullptr; 120 PerfCounter* ClassLoader::_perf_sys_classfile_bytes_read = nullptr; 121 PerfCounter* ClassLoader::_unsafe_defineClassCallCounter = nullptr; 122 123 GrowableArray<ModuleClassPathList*>* ClassLoader::_patch_mod_entries = nullptr; 124 GrowableArray<ModuleClassPathList*>* ClassLoader::_exploded_entries = nullptr; 125 ClassPathEntry* ClassLoader::_jrt_entry = nullptr; 126 127 ClassPathEntry* volatile ClassLoader::_first_append_entry_list = nullptr; 128 ClassPathEntry* volatile ClassLoader::_last_append_entry = nullptr; 129 #if INCLUDE_CDS 130 ClassPathEntry* ClassLoader::_app_classpath_entries = nullptr; 131 ClassPathEntry* ClassLoader::_last_app_classpath_entry = nullptr; 132 ClassPathEntry* ClassLoader::_module_path_entries = nullptr; 133 ClassPathEntry* ClassLoader::_last_module_path_entry = nullptr; 134 #endif 135 136 // helper routines 137 bool string_starts_with(const char* str, const char* str_to_find) { 138 size_t str_len = strlen(str); 139 size_t str_to_find_len = strlen(str_to_find); 140 if (str_to_find_len > str_len) { 141 return false; 142 } 143 return (strncmp(str, str_to_find, str_to_find_len) == 0); 144 } 145 146 static const char* get_jimage_version_string() { 147 static char version_string[10] = ""; 148 if (version_string[0] == '\0') { 149 jio_snprintf(version_string, sizeof(version_string), "%d.%d", 150 VM_Version::vm_major_version(), VM_Version::vm_minor_version()); 151 } 152 return (const char*)version_string; 153 } 154 155 bool ClassLoader::string_ends_with(const char* str, const char* str_to_find) { 156 size_t str_len = strlen(str); 157 size_t str_to_find_len = strlen(str_to_find); 158 if (str_to_find_len > str_len) { 159 return false; 160 } 161 return (strncmp(str + (str_len - str_to_find_len), str_to_find, str_to_find_len) == 0); 162 } 163 164 // Used to obtain the package name from a fully qualified class name. 165 Symbol* ClassLoader::package_from_class_name(const Symbol* name, bool* bad_class_name) { 166 if (name == nullptr) { 167 if (bad_class_name != nullptr) { 168 *bad_class_name = true; 169 } 170 return nullptr; 171 } 172 173 int utf_len = name->utf8_length(); 174 const jbyte* base = (const jbyte*)name->base(); 175 const jbyte* start = base; 176 const jbyte* end = UTF8::strrchr(start, utf_len, JVM_SIGNATURE_SLASH); 177 if (end == nullptr) { 178 return nullptr; 179 } 180 // Skip over '['s 181 if (*start == JVM_SIGNATURE_ARRAY) { 182 do { 183 start++; 184 } while (start < end && *start == JVM_SIGNATURE_ARRAY); 185 186 // Fully qualified class names should not contain a 'L'. 187 // Set bad_class_name to true to indicate that the package name 188 // could not be obtained due to an error condition. 189 // In this situation, is_same_class_package returns false. 190 if (*start == JVM_SIGNATURE_CLASS) { 191 if (bad_class_name != nullptr) { 192 *bad_class_name = true; 193 } 194 return nullptr; 195 } 196 } 197 // A class name could have just the slash character in the name, 198 // in which case start > end 199 if (start >= end) { 200 // No package name 201 if (bad_class_name != nullptr) { 202 *bad_class_name = true; 203 } 204 return nullptr; 205 } 206 return SymbolTable::new_symbol(name, pointer_delta_as_int(start, base), pointer_delta_as_int(end, base)); 207 } 208 209 // Given a fully qualified package name, find its defining package in the class loader's 210 // package entry table. 211 PackageEntry* ClassLoader::get_package_entry(Symbol* pkg_name, ClassLoaderData* loader_data) { 212 if (pkg_name == nullptr) { 213 return nullptr; 214 } 215 PackageEntryTable* pkgEntryTable = loader_data->packages(); 216 return pkgEntryTable->lookup_only(pkg_name); 217 } 218 219 const char* ClassPathEntry::copy_path(const char* path) { 220 char* copy = NEW_C_HEAP_ARRAY(char, strlen(path)+1, mtClass); 221 strcpy(copy, path); 222 return copy; 223 } 224 225 ClassPathDirEntry::~ClassPathDirEntry() { 226 FREE_C_HEAP_ARRAY(char, _dir); 227 } 228 229 ClassFileStream* ClassPathDirEntry::open_stream(JavaThread* current, const char* name) { 230 // construct full path name 231 assert((_dir != nullptr) && (name != nullptr), "sanity"); 232 size_t path_len = strlen(_dir) + strlen(name) + strlen(os::file_separator()) + 1; 233 char* path = NEW_RESOURCE_ARRAY_IN_THREAD(current, char, path_len); 234 int len = jio_snprintf(path, path_len, "%s%s%s", _dir, os::file_separator(), name); 235 assert(len == (int)(path_len - 1), "sanity"); 236 // check if file exists 237 struct stat st; 238 if (os::stat(path, &st) == 0) { 239 // found file, open it 240 int file_handle = os::open(path, 0, 0); 241 if (file_handle != -1) { 242 // read contents into resource array 243 u1* buffer = NEW_RESOURCE_ARRAY_IN_THREAD(current, u1, st.st_size); 244 size_t num_read = ::read(file_handle, (char*) buffer, st.st_size); 245 // close file 246 ::close(file_handle); 247 // construct ClassFileStream 248 if (num_read == (size_t)st.st_size) { 249 if (UsePerfData) { 250 ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read); 251 } 252 #ifdef ASSERT 253 // Freeing path is a no-op here as buffer prevents it from being reclaimed. But we keep it for 254 // debug builds so that we guard against use-after-free bugs. 255 FREE_RESOURCE_ARRAY_IN_THREAD(current, char, path, path_len); 256 #endif 257 // We don't verify the length of the classfile stream fits in an int, but this is the 258 // bootloader so we have control of this. 259 // Resource allocated 260 return new ClassFileStream(buffer, 261 checked_cast<int>(st.st_size), 262 _dir, 263 ClassFileStream::verify); 264 } 265 } 266 } 267 FREE_RESOURCE_ARRAY_IN_THREAD(current, char, path, path_len); 268 return nullptr; 269 } 270 271 ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name, 272 bool is_boot_append, bool from_class_path_attr) : ClassPathEntry() { 273 _zip = zip; 274 _zip_name = copy_path(zip_name); 275 _from_class_path_attr = from_class_path_attr; 276 } 277 278 ClassPathZipEntry::~ClassPathZipEntry() { 279 ZipLibrary::close(_zip); 280 FREE_C_HEAP_ARRAY(char, _zip_name); 281 } 282 283 u1* ClassPathZipEntry::open_entry(JavaThread* current, const char* name, jint* filesize, bool nul_terminate) { 284 // enable call to C land 285 ThreadToNativeFromVM ttn(current); 286 // check whether zip archive contains name 287 jint name_len; 288 jzentry* entry = ZipLibrary::find_entry(_zip, name, filesize, &name_len); 289 if (entry == nullptr) return nullptr; 290 u1* buffer; 291 char name_buf[128]; 292 char* filename; 293 if (name_len < 128) { 294 filename = name_buf; 295 } else { 296 filename = NEW_RESOURCE_ARRAY(char, name_len + 1); 297 } 298 299 // read contents into resource array 300 size_t size = (uint32_t)(*filesize); 301 if (nul_terminate) { 302 if (sizeof(size) == sizeof(uint32_t) && size == UINT_MAX) { 303 return nullptr; // 32-bit integer overflow will occur. 304 } 305 size++; 306 } 307 buffer = NEW_RESOURCE_ARRAY(u1, size); 308 if (!ZipLibrary::read_entry(_zip, entry, buffer, filename)) { 309 return nullptr; 310 } 311 312 // return result 313 if (nul_terminate) { 314 buffer[size - 1] = 0; 315 } 316 return buffer; 317 } 318 319 ClassFileStream* ClassPathZipEntry::open_stream(JavaThread* current, const char* name) { 320 jint filesize; 321 u1* buffer = open_entry(current, name, &filesize, false); 322 if (buffer == nullptr) { 323 return nullptr; 324 } 325 if (UsePerfData) { 326 ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize); 327 } 328 // Resource allocated 329 return new ClassFileStream(buffer, 330 filesize, 331 _zip_name, 332 ClassFileStream::verify); 333 } 334 335 DEBUG_ONLY(ClassPathImageEntry* ClassPathImageEntry::_singleton = nullptr;) 336 337 JImageFile* ClassPathImageEntry::jimage() const { 338 return JImage_file; 339 } 340 341 JImageFile* ClassPathImageEntry::jimage_non_null() const { 342 assert(ClassLoader::has_jrt_entry(), "must be"); 343 assert(jimage() != nullptr, "should have been opened by ClassLoader::lookup_vm_options " 344 "and remained throughout normal JVM lifetime"); 345 return jimage(); 346 } 347 348 void ClassPathImageEntry::close_jimage() { 349 if (jimage() != nullptr) { 350 (*JImageClose)(jimage()); 351 JImage_file = nullptr; 352 } 353 } 354 355 ClassPathImageEntry::ClassPathImageEntry(JImageFile* jimage, const char* name) : 356 ClassPathEntry() { 357 guarantee(jimage != nullptr, "jimage file is null"); 358 guarantee(name != nullptr, "jimage file name is null"); 359 assert(_singleton == nullptr, "VM supports only one jimage"); 360 DEBUG_ONLY(_singleton = this); 361 size_t len = strlen(name) + 1; 362 _name = copy_path(name); 363 } 364 365 ClassFileStream* ClassPathImageEntry::open_stream(JavaThread* current, const char* name) { 366 return open_stream_for_loader(current, name, ClassLoaderData::the_null_class_loader_data()); 367 } 368 369 // For a class in a named module, look it up in the jimage file using this syntax: 370 // /<module-name>/<package-name>/<base-class> 371 // 372 // Assumptions: 373 // 1. There are no unnamed modules in the jimage file. 374 // 2. A package is in at most one module in the jimage file. 375 // 376 ClassFileStream* ClassPathImageEntry::open_stream_for_loader(JavaThread* current, const char* name, ClassLoaderData* loader_data) { 377 jlong size; 378 JImageLocationRef location = (*JImageFindResource)(jimage_non_null(), "", get_jimage_version_string(), name, &size); 379 380 if (location == 0) { 381 TempNewSymbol class_name = SymbolTable::new_symbol(name); 382 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name); 383 384 if (pkg_name != nullptr) { 385 if (!Universe::is_module_initialized()) { 386 location = (*JImageFindResource)(jimage_non_null(), JAVA_BASE_NAME, get_jimage_version_string(), name, &size); 387 } else { 388 PackageEntry* package_entry = ClassLoader::get_package_entry(pkg_name, loader_data); 389 if (package_entry != nullptr) { 390 ResourceMark rm(current); 391 // Get the module name 392 ModuleEntry* module = package_entry->module(); 393 assert(module != nullptr, "Boot classLoader package missing module"); 394 assert(module->is_named(), "Boot classLoader package is in unnamed module"); 395 const char* module_name = module->name()->as_C_string(); 396 if (module_name != nullptr) { 397 location = (*JImageFindResource)(jimage_non_null(), module_name, get_jimage_version_string(), name, &size); 398 } 399 } 400 } 401 } 402 } 403 if (location != 0) { 404 if (UsePerfData) { 405 ClassLoader::perf_sys_classfile_bytes_read()->inc(size); 406 } 407 char* data = NEW_RESOURCE_ARRAY(char, size); 408 (*JImageGetResource)(jimage_non_null(), location, data, size); 409 // Resource allocated 410 assert(this == (ClassPathImageEntry*)ClassLoader::get_jrt_entry(), "must be"); 411 return new ClassFileStream((u1*)data, 412 checked_cast<int>(size), 413 _name, 414 ClassFileStream::verify, 415 true); // from_boot_loader_modules_image 416 } 417 418 return nullptr; 419 } 420 421 JImageLocationRef ClassLoader::jimage_find_resource(JImageFile* jf, 422 const char* module_name, 423 const char* file_name, 424 jlong &size) { 425 return ((*JImageFindResource)(jf, module_name, get_jimage_version_string(), file_name, &size)); 426 } 427 428 bool ClassPathImageEntry::is_modules_image() const { 429 assert(this == _singleton, "VM supports a single jimage"); 430 assert(this == (ClassPathImageEntry*)ClassLoader::get_jrt_entry(), "must be used for jrt entry"); 431 return true; 432 } 433 434 #if INCLUDE_CDS 435 void ClassLoader::exit_with_path_failure(const char* error, const char* message) { 436 assert(CDSConfig::is_dumping_archive(), "sanity"); 437 tty->print_cr("Hint: enable -Xlog:class+path=info to diagnose the failure"); 438 vm_exit_during_initialization(error, message); 439 } 440 #endif 441 442 ModuleClassPathList::ModuleClassPathList(Symbol* module_name) { 443 _module_name = module_name; 444 _module_first_entry = nullptr; 445 _module_last_entry = nullptr; 446 } 447 448 ModuleClassPathList::~ModuleClassPathList() { 449 // Clean out each ClassPathEntry on list 450 ClassPathEntry* e = _module_first_entry; 451 while (e != nullptr) { 452 ClassPathEntry* next_entry = e->next(); 453 delete e; 454 e = next_entry; 455 } 456 } 457 458 void ModuleClassPathList::add_to_list(ClassPathEntry* new_entry) { 459 if (new_entry != nullptr) { 460 if (_module_last_entry == nullptr) { 461 _module_first_entry = _module_last_entry = new_entry; 462 } else { 463 _module_last_entry->set_next(new_entry); 464 _module_last_entry = new_entry; 465 } 466 } 467 } 468 469 void ClassLoader::trace_class_path(const char* msg, const char* name) { 470 LogTarget(Info, class, path) lt; 471 if (lt.is_enabled()) { 472 LogStream ls(lt); 473 if (msg) { 474 ls.print("%s", msg); 475 } 476 if (name) { 477 if (strlen(name) < 256) { 478 ls.print("%s", name); 479 } else { 480 // For very long paths, we need to print each character separately, 481 // as print_cr() has a length limit 482 while (name[0] != '\0') { 483 ls.print("%c", name[0]); 484 name++; 485 } 486 } 487 } 488 ls.cr(); 489 } 490 } 491 492 void ClassLoader::setup_bootstrap_search_path(JavaThread* current) { 493 const char* bootcp = Arguments::get_boot_class_path(); 494 assert(bootcp != nullptr, "Boot class path must not be nullptr"); 495 if (PrintSharedArchiveAndExit) { 496 // Don't print bootcp - this is the bootcp of this current VM process, not necessarily 497 // the same as the boot classpath of the shared archive. 498 } else { 499 trace_class_path("bootstrap loader class path=", bootcp); 500 } 501 setup_bootstrap_search_path_impl(current, bootcp); 502 } 503 504 #if INCLUDE_CDS 505 void ClassLoader::setup_app_search_path(JavaThread* current, const char *class_path) { 506 assert(CDSConfig::is_dumping_archive(), "sanity"); 507 508 ResourceMark rm(current); 509 ClasspathStream cp_stream(class_path); 510 511 while (cp_stream.has_next()) { 512 const char* path = cp_stream.get_next(); 513 update_class_path_entry_list(current, path, /* check_for_duplicates */ true, 514 /* is_boot_append */ false, /* from_class_path_attr */ false); 515 } 516 } 517 518 void ClassLoader::add_to_module_path_entries(const char* path, 519 ClassPathEntry* entry) { 520 assert(entry != nullptr, "ClassPathEntry should not be nullptr"); 521 assert(CDSConfig::is_dumping_archive(), "sanity"); 522 523 // The entry does not exist, add to the list 524 if (_module_path_entries == nullptr) { 525 assert(_last_module_path_entry == nullptr, "Sanity"); 526 _module_path_entries = _last_module_path_entry = entry; 527 } else { 528 _last_module_path_entry->set_next(entry); 529 _last_module_path_entry = entry; 530 } 531 } 532 533 // Add a module path to the _module_path_entries list. 534 void ClassLoader::setup_module_search_path(JavaThread* current, const char* path) { 535 assert(CDSConfig::is_dumping_archive(), "sanity"); 536 struct stat st; 537 if (os::stat(path, &st) != 0) { 538 tty->print_cr("os::stat error %d (%s). CDS dump aborted (path was \"%s\").", 539 errno, os::errno_name(errno), path); 540 vm_exit_during_initialization(); 541 } 542 // File or directory found 543 ClassPathEntry* new_entry = nullptr; 544 new_entry = create_class_path_entry(current, path, &st, 545 false /*is_boot_append */, false /* from_class_path_attr */); 546 if (new_entry != nullptr) { 547 add_to_module_path_entries(path, new_entry); 548 } 549 } 550 551 #endif // INCLUDE_CDS 552 553 void ClassLoader::close_jrt_image() { 554 // Not applicable for exploded builds 555 if (!ClassLoader::has_jrt_entry()) return; 556 _jrt_entry->close_jimage(); 557 } 558 559 // Construct the array of module/path pairs as specified to --patch-module 560 // for the boot loader to search ahead of the jimage, if the class being 561 // loaded is defined to a module that has been specified to --patch-module. 562 void ClassLoader::setup_patch_mod_entries() { 563 JavaThread* current = JavaThread::current(); 564 GrowableArray<ModulePatchPath*>* patch_mod_args = Arguments::get_patch_mod_prefix(); 565 int num_of_entries = patch_mod_args->length(); 566 567 // Set up the boot loader's _patch_mod_entries list 568 _patch_mod_entries = new (mtModule) GrowableArray<ModuleClassPathList*>(num_of_entries, mtModule); 569 570 for (int i = 0; i < num_of_entries; i++) { 571 const char* module_name = (patch_mod_args->at(i))->module_name(); 572 Symbol* const module_sym = SymbolTable::new_symbol(module_name); 573 assert(module_sym != nullptr, "Failed to obtain Symbol for module name"); 574 ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym); 575 576 char* class_path = (patch_mod_args->at(i))->path_string(); 577 ResourceMark rm(current); 578 ClasspathStream cp_stream(class_path); 579 580 while (cp_stream.has_next()) { 581 const char* path = cp_stream.get_next(); 582 struct stat st; 583 if (os::stat(path, &st) == 0) { 584 // File or directory found 585 ClassPathEntry* new_entry = create_class_path_entry(current, path, &st, false, false); 586 // If the path specification is valid, enter it into this module's list 587 if (new_entry != nullptr) { 588 module_cpl->add_to_list(new_entry); 589 } 590 } 591 } 592 593 // Record the module into the list of --patch-module entries only if 594 // valid ClassPathEntrys have been created 595 if (module_cpl->module_first_entry() != nullptr) { 596 _patch_mod_entries->push(module_cpl); 597 } 598 } 599 } 600 601 // Determine whether the module has been patched via the command-line 602 // option --patch-module 603 bool ClassLoader::is_in_patch_mod_entries(Symbol* module_name) { 604 if (_patch_mod_entries != nullptr && _patch_mod_entries->is_nonempty()) { 605 int table_len = _patch_mod_entries->length(); 606 for (int i = 0; i < table_len; i++) { 607 ModuleClassPathList* patch_mod = _patch_mod_entries->at(i); 608 if (module_name->fast_compare(patch_mod->module_name()) == 0) { 609 return true; 610 } 611 } 612 } 613 return false; 614 } 615 616 // Set up the _jrt_entry if present and boot append path 617 void ClassLoader::setup_bootstrap_search_path_impl(JavaThread* current, const char *class_path) { 618 ResourceMark rm(current); 619 ClasspathStream cp_stream(class_path); 620 bool set_base_piece = true; 621 622 #if INCLUDE_CDS 623 if (CDSConfig::is_dumping_archive()) { 624 if (!Arguments::has_jimage()) { 625 vm_exit_during_initialization("CDS is not supported in exploded JDK build", nullptr); 626 } 627 } 628 #endif 629 630 while (cp_stream.has_next()) { 631 const char* path = cp_stream.get_next(); 632 633 if (set_base_piece) { 634 // The first time through the bootstrap_search setup, it must be determined 635 // what the base or core piece of the boot loader search is. Either a java runtime 636 // image is present or this is an exploded module build situation. 637 assert(string_ends_with(path, MODULES_IMAGE_NAME) || string_ends_with(path, JAVA_BASE_NAME), 638 "Incorrect boot loader search path, no java runtime image or " JAVA_BASE_NAME " exploded build"); 639 struct stat st; 640 if (os::stat(path, &st) == 0) { 641 // Directory found 642 if (JImage_file != nullptr) { 643 assert(Arguments::has_jimage(), "sanity check"); 644 const char* canonical_path = get_canonical_path(path, current); 645 assert(canonical_path != nullptr, "canonical_path issue"); 646 647 _jrt_entry = new ClassPathImageEntry(JImage_file, canonical_path); 648 assert(_jrt_entry != nullptr && _jrt_entry->is_modules_image(), "No java runtime image present"); 649 assert(_jrt_entry->jimage() != nullptr, "No java runtime image"); 650 } // else it's an exploded build. 651 } else { 652 // If path does not exist, exit 653 vm_exit_during_initialization("Unable to establish the boot loader search path", path); 654 } 655 set_base_piece = false; 656 } else { 657 // Every entry on the boot class path after the initial base piece, 658 // which is set by os::set_boot_path(), is considered an appended entry. 659 update_class_path_entry_list(current, path, /* check_for_duplicates */ false, 660 /* is_boot_append */ true, /* from_class_path_attr */ false); 661 } 662 } 663 } 664 665 // Gets the exploded path for the named module. The memory for the path 666 // is allocated on the C heap if `c_heap` is true otherwise in the resource area. 667 static const char* get_exploded_module_path(const char* module_name, bool c_heap) { 668 const char *home = Arguments::get_java_home(); 669 const char file_sep = os::file_separator()[0]; 670 // 10 represents the length of "modules" + 2 file separators + \0 671 size_t len = strlen(home) + strlen(module_name) + 10; 672 char *path = c_heap ? NEW_C_HEAP_ARRAY(char, len, mtModule) : NEW_RESOURCE_ARRAY(char, len); 673 jio_snprintf(path, len, "%s%cmodules%c%s", home, file_sep, file_sep, module_name); 674 return path; 675 } 676 677 // During an exploded modules build, each module defined to the boot loader 678 // will be added to the ClassLoader::_exploded_entries array. 679 void ClassLoader::add_to_exploded_build_list(JavaThread* current, Symbol* module_sym) { 680 assert(!ClassLoader::has_jrt_entry(), "Exploded build not applicable"); 681 assert(_exploded_entries != nullptr, "_exploded_entries was not initialized"); 682 683 // Find the module's symbol 684 ResourceMark rm(current); 685 const char *module_name = module_sym->as_C_string(); 686 const char *path = get_exploded_module_path(module_name, false); 687 688 struct stat st; 689 if (os::stat(path, &st) == 0) { 690 // Directory found 691 ClassPathEntry* new_entry = create_class_path_entry(current, path, &st, false, false); 692 693 // If the path specification is valid, enter it into this module's list. 694 // There is no need to check for duplicate modules in the exploded entry list, 695 // since no two modules with the same name can be defined to the boot loader. 696 // This is checked at module definition time in Modules::define_module. 697 if (new_entry != nullptr) { 698 ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym); 699 module_cpl->add_to_list(new_entry); 700 { 701 MutexLocker ml(current, Module_lock); 702 _exploded_entries->push(module_cpl); 703 } 704 log_info(class, load)("path: %s", path); 705 } 706 } 707 } 708 709 jzfile* ClassLoader::open_zip_file(const char* canonical_path, char** error_msg, JavaThread* thread) { 710 // enable call to C land 711 ThreadToNativeFromVM ttn(thread); 712 HandleMark hm(thread); 713 return ZipLibrary::open(canonical_path, error_msg); 714 } 715 716 ClassPathEntry* ClassLoader::create_class_path_entry(JavaThread* current, 717 const char *path, const struct stat* st, 718 bool is_boot_append, 719 bool from_class_path_attr) { 720 ClassPathEntry* new_entry = nullptr; 721 if ((st->st_mode & S_IFMT) == S_IFREG) { 722 ResourceMark rm(current); 723 // Regular file, should be a zip file 724 // Canonicalized filename 725 const char* canonical_path = get_canonical_path(path, current); 726 if (canonical_path == nullptr) { 727 return nullptr; 728 } 729 char* error_msg = nullptr; 730 jzfile* zip = open_zip_file(canonical_path, &error_msg, current); 731 if (zip != nullptr && error_msg == nullptr) { 732 new_entry = new ClassPathZipEntry(zip, path, is_boot_append, from_class_path_attr); 733 } else { 734 #if INCLUDE_CDS 735 ClassLoaderExt::set_has_non_jar_in_classpath(); 736 #endif 737 return nullptr; 738 } 739 log_info(class, path)("opened: %s", path); 740 log_info(class, load)("opened: %s", path); 741 } else { 742 // Directory 743 new_entry = new ClassPathDirEntry(path); 744 log_info(class, load)("path: %s", path); 745 } 746 return new_entry; 747 } 748 749 750 // Create a class path zip entry for a given path (return null if not found 751 // or zip/JAR file cannot be opened) 752 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path, bool is_boot_append) { 753 // check for a regular file 754 struct stat st; 755 if (os::stat(path, &st) == 0) { 756 if ((st.st_mode & S_IFMT) == S_IFREG) { 757 JavaThread* thread = JavaThread::current(); 758 ResourceMark rm(thread); 759 const char* canonical_path = get_canonical_path(path, thread); 760 if (canonical_path != nullptr) { 761 char* error_msg = nullptr; 762 jzfile* zip = open_zip_file(canonical_path, &error_msg, thread); 763 if (zip != nullptr && error_msg == nullptr) { 764 // create using canonical path 765 return new ClassPathZipEntry(zip, canonical_path, is_boot_append, false); 766 } 767 } 768 } 769 } 770 return nullptr; 771 } 772 773 // The boot append entries are added with a lock, and read lock free. 774 void ClassLoader::add_to_boot_append_entries(ClassPathEntry *new_entry) { 775 if (new_entry != nullptr) { 776 MutexLocker ml(Bootclasspath_lock, Mutex::_no_safepoint_check_flag); 777 if (_last_append_entry == nullptr) { 778 _last_append_entry = new_entry; 779 assert(first_append_entry() == nullptr, "boot loader's append class path entry list not empty"); 780 Atomic::release_store(&_first_append_entry_list, new_entry); 781 } else { 782 _last_append_entry->set_next(new_entry); 783 _last_append_entry = new_entry; 784 } 785 } 786 } 787 788 // Record the path entries specified in -cp during dump time. The recorded 789 // information will be used at runtime for loading the archived app classes. 790 // 791 // Note that at dump time, ClassLoader::_app_classpath_entries are NOT used for 792 // loading app classes. Instead, the app class are loaded by the 793 // jdk/internal/loader/ClassLoaders$AppClassLoader instance. 794 bool ClassLoader::add_to_app_classpath_entries(JavaThread* current, 795 ClassPathEntry* entry, 796 bool check_for_duplicates) { 797 #if INCLUDE_CDS 798 assert(entry != nullptr, "ClassPathEntry should not be nullptr"); 799 ClassPathEntry* e = _app_classpath_entries; 800 if (check_for_duplicates) { 801 while (e != nullptr) { 802 if (strcmp(e->name(), entry->name()) == 0) { 803 // entry already exists 804 return false; 805 } 806 e = e->next(); 807 } 808 } 809 810 // The entry does not exist, add to the list 811 if (_app_classpath_entries == nullptr) { 812 assert(_last_app_classpath_entry == nullptr, "Sanity"); 813 _app_classpath_entries = _last_app_classpath_entry = entry; 814 } else { 815 _last_app_classpath_entry->set_next(entry); 816 _last_app_classpath_entry = entry; 817 } 818 819 if (entry->is_jar_file()) { 820 ClassLoaderExt::process_jar_manifest(current, entry); 821 } 822 #endif 823 return true; 824 } 825 826 // Returns true IFF the file/dir exists and the entry was successfully created. 827 bool ClassLoader::update_class_path_entry_list(JavaThread* current, 828 const char *path, 829 bool check_for_duplicates, 830 bool is_boot_append, 831 bool from_class_path_attr) { 832 struct stat st; 833 if (os::stat(path, &st) == 0) { 834 // File or directory found 835 ClassPathEntry* new_entry = nullptr; 836 new_entry = create_class_path_entry(current, path, &st, is_boot_append, from_class_path_attr); 837 if (new_entry == nullptr) { 838 return false; 839 } 840 841 // Do not reorder the bootclasspath which would break get_system_package(). 842 // Add new entry to linked list 843 if (is_boot_append) { 844 add_to_boot_append_entries(new_entry); 845 } else { 846 if (!add_to_app_classpath_entries(current, new_entry, check_for_duplicates)) { 847 // new_entry is not saved, free it now 848 delete new_entry; 849 } 850 } 851 return true; 852 } else { 853 return false; 854 } 855 } 856 857 static void print_module_entry_table(const GrowableArray<ModuleClassPathList*>* const module_list) { 858 ResourceMark rm; 859 int num_of_entries = module_list->length(); 860 for (int i = 0; i < num_of_entries; i++) { 861 ClassPathEntry* e; 862 ModuleClassPathList* mpl = module_list->at(i); 863 tty->print("%s=", mpl->module_name()->as_C_string()); 864 e = mpl->module_first_entry(); 865 while (e != nullptr) { 866 tty->print("%s", e->name()); 867 e = e->next(); 868 if (e != nullptr) { 869 tty->print("%s", os::path_separator()); 870 } 871 } 872 tty->print(" ;"); 873 } 874 } 875 876 void ClassLoader::print_bootclasspath() { 877 ClassPathEntry* e; 878 tty->print("[bootclasspath= "); 879 880 // Print --patch-module module/path specifications first 881 if (_patch_mod_entries != nullptr) { 882 print_module_entry_table(_patch_mod_entries); 883 } 884 885 // [jimage | exploded modules build] 886 if (has_jrt_entry()) { 887 // Print the location of the java runtime image 888 tty->print("%s ;", _jrt_entry->name()); 889 } else { 890 // Print exploded module build path specifications 891 if (_exploded_entries != nullptr) { 892 print_module_entry_table(_exploded_entries); 893 } 894 } 895 896 // appended entries 897 e = first_append_entry(); 898 while (e != nullptr) { 899 tty->print("%s ;", e->name()); 900 e = e->next(); 901 } 902 tty->print_cr("]"); 903 } 904 905 void* ClassLoader::dll_lookup(void* lib, const char* name, const char* path) { 906 void* func = os::dll_lookup(lib, name); 907 if (func == nullptr) { 908 char msg[256] = ""; 909 jio_snprintf(msg, sizeof(msg), "Could not resolve \"%s\"", name); 910 vm_exit_during_initialization(msg, path); 911 } 912 return func; 913 } 914 915 void ClassLoader::load_java_library() { 916 assert(CanonicalizeEntry == nullptr, "should not load java library twice"); 917 void *javalib_handle = os::native_java_library(); 918 if (javalib_handle == nullptr) { 919 vm_exit_during_initialization("Unable to load java library", nullptr); 920 } 921 922 CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, dll_lookup(javalib_handle, "JDK_Canonicalize", nullptr)); 923 } 924 925 void ClassLoader::load_jimage_library() { 926 assert(JImageOpen == nullptr, "should not load jimage library twice"); 927 char path[JVM_MAXPATHLEN]; 928 char ebuf[1024]; 929 void* handle = nullptr; 930 if (os::dll_locate_lib(path, sizeof(path), Arguments::get_dll_dir(), "jimage")) { 931 handle = os::dll_load(path, ebuf, sizeof ebuf); 932 } 933 if (handle == nullptr) { 934 vm_exit_during_initialization("Unable to load jimage library", path); 935 } 936 937 JImageOpen = CAST_TO_FN_PTR(JImageOpen_t, dll_lookup(handle, "JIMAGE_Open", path)); 938 JImageClose = CAST_TO_FN_PTR(JImageClose_t, dll_lookup(handle, "JIMAGE_Close", path)); 939 JImageFindResource = CAST_TO_FN_PTR(JImageFindResource_t, dll_lookup(handle, "JIMAGE_FindResource", path)); 940 JImageGetResource = CAST_TO_FN_PTR(JImageGetResource_t, dll_lookup(handle, "JIMAGE_GetResource", path)); 941 } 942 943 int ClassLoader::crc32(int crc, const char* buf, int len) { 944 return ZipLibrary::crc32(crc, (const jbyte*)buf, len); 945 } 946 947 oop ClassLoader::get_system_package(const char* name, TRAPS) { 948 // Look up the name in the boot loader's package entry table. 949 if (name != nullptr) { 950 TempNewSymbol package_sym = SymbolTable::new_symbol(name); 951 // Look for the package entry in the boot loader's package entry table. 952 PackageEntry* package = 953 ClassLoaderData::the_null_class_loader_data()->packages()->lookup_only(package_sym); 954 955 // Return null if package does not exist or if no classes in that package 956 // have been loaded. 957 if (package != nullptr && package->has_loaded_class()) { 958 ModuleEntry* module = package->module(); 959 if (module->location() != nullptr) { 960 ResourceMark rm(THREAD); 961 Handle ml = java_lang_String::create_from_str( 962 module->location()->as_C_string(), THREAD); 963 return ml(); 964 } 965 // Return entry on boot loader class path. 966 Handle cph = java_lang_String::create_from_str( 967 ClassLoader::classpath_entry(package->classpath_index())->name(), THREAD); 968 return cph(); 969 } 970 } 971 return nullptr; 972 } 973 974 objArrayOop ClassLoader::get_system_packages(TRAPS) { 975 ResourceMark rm(THREAD); 976 // List of pointers to PackageEntrys that have loaded classes. 977 PackageEntryTable* pe_table = 978 ClassLoaderData::the_null_class_loader_data()->packages(); 979 GrowableArray<PackageEntry*>* loaded_class_pkgs = pe_table->get_system_packages(); 980 981 // Allocate objArray and fill with java.lang.String 982 objArrayOop r = oopFactory::new_objArray(vmClasses::String_klass(), 983 loaded_class_pkgs->length(), CHECK_NULL); 984 objArrayHandle result(THREAD, r); 985 for (int x = 0; x < loaded_class_pkgs->length(); x++) { 986 PackageEntry* package_entry = loaded_class_pkgs->at(x); 987 Handle str = java_lang_String::create_from_symbol(package_entry->name(), CHECK_NULL); 988 result->obj_at_put(x, str()); 989 } 990 return result(); 991 } 992 993 // caller needs ResourceMark 994 const char* ClassLoader::file_name_for_class_name(const char* class_name, 995 int class_name_len) { 996 assert(class_name != nullptr, "invariant"); 997 assert((int)strlen(class_name) == class_name_len, "invariant"); 998 999 static const char class_suffix[] = ".class"; 1000 size_t class_suffix_len = sizeof(class_suffix); 1001 1002 char* const file_name = NEW_RESOURCE_ARRAY(char, 1003 class_name_len + 1004 class_suffix_len); // includes term null 1005 1006 strncpy(file_name, class_name, class_name_len); 1007 strncpy(&file_name[class_name_len], class_suffix, class_suffix_len); 1008 1009 return file_name; 1010 } 1011 1012 ClassPathEntry* find_first_module_cpe(ModuleEntry* mod_entry, 1013 const GrowableArray<ModuleClassPathList*>* const module_list) { 1014 int num_of_entries = module_list->length(); 1015 const Symbol* class_module_name = mod_entry->name(); 1016 1017 // Loop through all the modules in either the patch-module or exploded entries looking for module 1018 for (int i = 0; i < num_of_entries; i++) { 1019 ModuleClassPathList* module_cpl = module_list->at(i); 1020 Symbol* module_cpl_name = module_cpl->module_name(); 1021 1022 if (module_cpl_name->fast_compare(class_module_name) == 0) { 1023 // Class' module has been located. 1024 return module_cpl->module_first_entry(); 1025 } 1026 } 1027 return nullptr; 1028 } 1029 1030 1031 // Search either the patch-module or exploded build entries for class. 1032 ClassFileStream* ClassLoader::search_module_entries(JavaThread* current, 1033 const GrowableArray<ModuleClassPathList*>* const module_list, 1034 const char* const class_name, 1035 const char* const file_name) { 1036 ClassFileStream* stream = nullptr; 1037 1038 // Find the class' defining module in the boot loader's module entry table 1039 TempNewSymbol class_name_symbol = SymbolTable::new_symbol(class_name); 1040 TempNewSymbol pkg_name = package_from_class_name(class_name_symbol); 1041 PackageEntry* pkg_entry = get_package_entry(pkg_name, ClassLoaderData::the_null_class_loader_data()); 1042 ModuleEntry* mod_entry = (pkg_entry != nullptr) ? pkg_entry->module() : nullptr; 1043 1044 // If the module system has not defined java.base yet, then 1045 // classes loaded are assumed to be defined to java.base. 1046 // When java.base is eventually defined by the module system, 1047 // all packages of classes that have been previously loaded 1048 // are verified in ModuleEntryTable::verify_javabase_packages(). 1049 if (!Universe::is_module_initialized() && 1050 !ModuleEntryTable::javabase_defined() && 1051 mod_entry == nullptr) { 1052 mod_entry = ModuleEntryTable::javabase_moduleEntry(); 1053 } 1054 1055 // The module must be a named module 1056 ClassPathEntry* e = nullptr; 1057 if (mod_entry != nullptr && mod_entry->is_named()) { 1058 if (module_list == _exploded_entries) { 1059 // The exploded build entries can be added to at any time so a lock is 1060 // needed when searching them. 1061 assert(!ClassLoader::has_jrt_entry(), "Must be exploded build"); 1062 MutexLocker ml(current, Module_lock); 1063 e = find_first_module_cpe(mod_entry, module_list); 1064 } else { 1065 e = find_first_module_cpe(mod_entry, module_list); 1066 } 1067 } 1068 1069 // Try to load the class from the module's ClassPathEntry list. 1070 while (e != nullptr) { 1071 stream = e->open_stream(current, file_name); 1072 // No context.check is required since CDS is not supported 1073 // for an exploded modules build or if --patch-module is specified. 1074 if (nullptr != stream) { 1075 return stream; 1076 } 1077 e = e->next(); 1078 } 1079 // If the module was located, break out even if the class was not 1080 // located successfully from that module's ClassPathEntry list. 1081 // There will not be another valid entry for that module. 1082 return nullptr; 1083 } 1084 1085 // Called by the boot classloader to load classes 1086 InstanceKlass* ClassLoader::load_class(Symbol* name, bool search_append_only, TRAPS) { 1087 assert(name != nullptr, "invariant"); 1088 1089 ResourceMark rm(THREAD); 1090 HandleMark hm(THREAD); 1091 1092 const char* const class_name = name->as_C_string(); 1093 1094 EventMarkClassLoading m("Loading class %s", class_name); 1095 1096 const char* const file_name = file_name_for_class_name(class_name, 1097 name->utf8_length()); 1098 assert(file_name != nullptr, "invariant"); 1099 1100 // Lookup stream for parsing .class file 1101 ClassFileStream* stream = nullptr; 1102 s2 classpath_index = 0; 1103 ClassPathEntry* e = nullptr; 1104 bool is_patched = false; 1105 1106 // If search_append_only is true, boot loader visibility boundaries are 1107 // set to be _first_append_entry to the end. This includes: 1108 // [-Xbootclasspath/a]; [jvmti appended entries] 1109 // 1110 // If search_append_only is false, boot loader visibility boundaries are 1111 // set to be the --patch-module entries plus the base piece. This includes: 1112 // [--patch-module=<module>=<file>(<pathsep><file>)*]; [jimage | exploded module build] 1113 // 1114 1115 // Load Attempt #1: --patch-module 1116 // Determine the class' defining module. If it appears in the _patch_mod_entries, 1117 // attempt to load the class from those locations specific to the module. 1118 // Specifications to --patch-module can contain a partial number of classes 1119 // that are part of the overall module definition. So if a particular class is not 1120 // found within its module specification, the search should continue to Load Attempt #2. 1121 // Note: The --patch-module entries are never searched if the boot loader's 1122 // visibility boundary is limited to only searching the append entries. 1123 if (_patch_mod_entries != nullptr && !search_append_only) { 1124 // At CDS dump time, the --patch-module entries are ignored. That means a 1125 // class is still loaded from the runtime image even if it might 1126 // appear in the _patch_mod_entries. The runtime shared class visibility 1127 // check will determine if a shared class is visible based on the runtime 1128 // environment, including the runtime --patch-module setting. 1129 if (!CDSConfig::is_valhalla_preview()) { 1130 // Dynamic dumping requires UseSharedSpaces to be enabled. Since --patch-module 1131 // is not supported with UseSharedSpaces, we can never come here during dynamic dumping. 1132 assert(!CDSConfig::is_dumping_dynamic_archive(), "sanity"); 1133 } 1134 if (CDSConfig::is_valhalla_preview() || !CDSConfig::is_dumping_static_archive()) { 1135 stream = search_module_entries(THREAD, _patch_mod_entries, class_name, file_name); 1136 if (stream != nullptr) { 1137 is_patched = true; 1138 } 1139 } 1140 } 1141 1142 // Load Attempt #2: [jimage | exploded build] 1143 if (!search_append_only && (nullptr == stream)) { 1144 if (has_jrt_entry()) { 1145 e = _jrt_entry; 1146 stream = _jrt_entry->open_stream(THREAD, file_name); 1147 } else { 1148 // Exploded build - attempt to locate class in its defining module's location. 1149 assert(_exploded_entries != nullptr, "No exploded build entries present"); 1150 stream = search_module_entries(THREAD, _exploded_entries, class_name, file_name); 1151 } 1152 } 1153 1154 // Load Attempt #3: [-Xbootclasspath/a]; [jvmti appended entries] 1155 if (search_append_only && (nullptr == stream)) { 1156 // For the boot loader append path search, the starting classpath_index 1157 // for the appended piece is always 1 to account for either the 1158 // _jrt_entry or the _exploded_entries. 1159 assert(classpath_index == 0, "The classpath_index has been incremented incorrectly"); 1160 classpath_index = 1; 1161 1162 e = first_append_entry(); 1163 while (e != nullptr) { 1164 stream = e->open_stream(THREAD, file_name); 1165 if (nullptr != stream) { 1166 break; 1167 } 1168 e = e->next(); 1169 ++classpath_index; 1170 } 1171 } 1172 1173 if (nullptr == stream) { 1174 return nullptr; 1175 } 1176 1177 stream->set_verify(ClassLoaderExt::should_verify(classpath_index)); 1178 1179 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 1180 Handle protection_domain; 1181 ClassLoadInfo cl_info(protection_domain); 1182 1183 InstanceKlass* result = KlassFactory::create_from_stream(stream, 1184 name, 1185 loader_data, 1186 cl_info, 1187 CHECK_NULL); 1188 result->set_classpath_index(classpath_index); 1189 if (is_patched) { 1190 result->set_shared_classpath_index(0); 1191 result->set_shared_class_loader_type(ClassLoader::BOOT_LOADER); 1192 } 1193 return result; 1194 } 1195 1196 #if INCLUDE_CDS 1197 char* ClassLoader::skip_uri_protocol(char* source) { 1198 if (strncmp(source, "file:", 5) == 0) { 1199 // file: protocol path could start with file:/ or file:/// 1200 // locate the char after all the forward slashes 1201 int offset = 5; 1202 while (*(source + offset) == '/') { 1203 offset++; 1204 } 1205 source += offset; 1206 // for non-windows platforms, move back one char as the path begins with a '/' 1207 #ifndef _WINDOWS 1208 source -= 1; 1209 #endif 1210 } else if (strncmp(source, "jrt:/", 5) == 0) { 1211 source += 5; 1212 } 1213 return source; 1214 } 1215 1216 // Record the shared classpath index and loader type for classes loaded 1217 // by the builtin loaders at dump time. 1218 void ClassLoader::record_result(JavaThread* current, InstanceKlass* ik, 1219 const ClassFileStream* stream, bool redefined) { 1220 assert(CDSConfig::is_dumping_archive(), "sanity"); 1221 assert(stream != nullptr, "sanity"); 1222 1223 if (ik->is_hidden()) { 1224 // We do not archive hidden classes. 1225 return; 1226 } 1227 1228 if (ik->shared_classpath_index() == 0 && ik->is_shared_boot_class()) { 1229 return; 1230 } 1231 1232 oop loader = ik->class_loader(); 1233 char* src = (char*)stream->source(); 1234 if (src == nullptr) { 1235 if (loader == nullptr) { 1236 // JFR classes 1237 ik->set_shared_classpath_index(0); 1238 ik->set_shared_class_loader_type(ClassLoader::BOOT_LOADER); 1239 } 1240 return; 1241 } 1242 1243 assert(has_jrt_entry(), "CDS dumping does not support exploded JDK build"); 1244 1245 ResourceMark rm(current); 1246 int classpath_index = -1; 1247 PackageEntry* pkg_entry = ik->package(); 1248 1249 if (FileMapInfo::get_number_of_shared_paths() > 0) { 1250 // Save the path from the file: protocol or the module name from the jrt: protocol 1251 // if no protocol prefix is found, path is the same as stream->source(). This path 1252 // must be valid since the class has been successfully parsed. 1253 char* path = skip_uri_protocol(src); 1254 assert(path != nullptr, "sanity"); 1255 for (int i = 0; i < FileMapInfo::get_number_of_shared_paths(); i++) { 1256 SharedClassPathEntry* ent = FileMapInfo::shared_path(i); 1257 // A shared path has been validated during its creation in ClassLoader::create_class_path_entry(), 1258 // it must be valid here. 1259 assert(ent->name() != nullptr, "sanity"); 1260 // If the path (from the class stream source) is the same as the shared 1261 // class or module path, then we have a match. 1262 // src may come from the App/Platform class loaders, which would canonicalize 1263 // the file name. We cannot use strcmp to check for equality against ent->name(). 1264 // We must use os::same_files (which is faster than canonicalizing ent->name()). 1265 if (os::same_files(ent->name(), path)) { 1266 // null pkg_entry and pkg_entry in an unnamed module implies the class 1267 // is from the -cp or boot loader append path which consists of -Xbootclasspath/a 1268 // and jvmti appended entries. 1269 if ((pkg_entry == nullptr) || (pkg_entry->in_unnamed_module())) { 1270 // Ensure the index is within the -cp range before assigning 1271 // to the classpath_index. 1272 if (SystemDictionary::is_system_class_loader(loader) && 1273 (i >= ClassLoaderExt::app_class_paths_start_index()) && 1274 (i < ClassLoaderExt::app_module_paths_start_index())) { 1275 classpath_index = i; 1276 break; 1277 } else { 1278 if ((i >= 1) && 1279 (i < ClassLoaderExt::app_class_paths_start_index())) { 1280 // The class must be from boot loader append path which consists of 1281 // -Xbootclasspath/a and jvmti appended entries. 1282 assert(loader == nullptr, "sanity"); 1283 classpath_index = i; 1284 break; 1285 } 1286 } 1287 } else { 1288 // A class from a named module from the --module-path. Ensure the index is 1289 // within the --module-path range before assigning to the classpath_index. 1290 if ((pkg_entry != nullptr) && !(pkg_entry->in_unnamed_module()) && (i > 0)) { 1291 if (i >= ClassLoaderExt::app_module_paths_start_index() && 1292 i < FileMapInfo::get_number_of_shared_paths()) { 1293 classpath_index = i; 1294 break; 1295 } 1296 } 1297 } 1298 } 1299 // for index 0 and the stream->source() is the modules image or has the jrt: protocol. 1300 // The class must be from the runtime modules image. 1301 if (i == 0 && (stream->from_boot_loader_modules_image() || string_starts_with(src, "jrt:"))) { 1302 classpath_index = i; 1303 break; 1304 } 1305 } 1306 1307 // No path entry found for this class: most likely a shared class loaded by the 1308 // user defined classloader. 1309 if (classpath_index < 0 && !SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) { 1310 assert(ik->shared_classpath_index() < 0, "not assigned yet"); 1311 ik->set_shared_classpath_index(UNREGISTERED_INDEX); 1312 SystemDictionaryShared::set_shared_class_misc_info(ik, (ClassFileStream*)stream); 1313 return; 1314 } 1315 } else { 1316 // The shared path table is set up after module system initialization. 1317 // The path table contains no entry before that. Any classes loaded prior 1318 // to the setup of the shared path table must be from the modules image. 1319 if (!CDSConfig::is_valhalla_preview()) { 1320 assert(stream->from_boot_loader_modules_image(), "stream must be loaded by boot loader from modules image"); 1321 } 1322 assert(FileMapInfo::get_number_of_shared_paths() == 0, "shared path table must not have been setup"); 1323 classpath_index = 0; 1324 } 1325 1326 const char* const class_name = ik->name()->as_C_string(); 1327 const char* const file_name = file_name_for_class_name(class_name, 1328 ik->name()->utf8_length()); 1329 assert(file_name != nullptr, "invariant"); 1330 ClassLoaderExt::record_result(checked_cast<s2>(classpath_index), ik, redefined); 1331 } 1332 #endif // INCLUDE_CDS 1333 1334 // Initialize the class loader's access to methods in libzip. Parse and 1335 // process the boot classpath into a list ClassPathEntry objects. Once 1336 // this list has been created, it must not change order (see class PackageInfo) 1337 // it can be appended to and is by jvmti. 1338 1339 void ClassLoader::initialize(TRAPS) { 1340 if (UsePerfData) { 1341 // jvmstat performance counters 1342 NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time"); 1343 NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime"); 1344 NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self"); 1345 NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime"); 1346 NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self"); 1347 NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime"); 1348 NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self"); 1349 NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses"); 1350 NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses"); 1351 NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses"); 1352 1353 NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime"); 1354 NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime"); 1355 NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime"); 1356 NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self"); 1357 NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount"); 1358 NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses"); 1359 NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime"); 1360 NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self"); 1361 NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes"); 1362 NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes"); 1363 1364 NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS, "unsafeDefineClassCalls"); 1365 } 1366 1367 // lookup java library entry points 1368 load_java_library(); 1369 // jimage library entry points are loaded below, in lookup_vm_options 1370 setup_bootstrap_search_path(THREAD); 1371 } 1372 1373 char* lookup_vm_resource(JImageFile *jimage, const char *jimage_version, const char *path) { 1374 jlong size; 1375 JImageLocationRef location = (*JImageFindResource)(jimage, "java.base", jimage_version, path, &size); 1376 if (location == 0) 1377 return nullptr; 1378 char *val = NEW_C_HEAP_ARRAY(char, size+1, mtClass); 1379 (*JImageGetResource)(jimage, location, val, size); 1380 val[size] = '\0'; 1381 return val; 1382 } 1383 1384 // Lookup VM options embedded in the modules jimage file 1385 char* ClassLoader::lookup_vm_options() { 1386 jint error; 1387 char modules_path[JVM_MAXPATHLEN]; 1388 const char* fileSep = os::file_separator(); 1389 1390 // Initialize jimage library entry points 1391 load_jimage_library(); 1392 1393 jio_snprintf(modules_path, JVM_MAXPATHLEN, "%s%slib%smodules", Arguments::get_java_home(), fileSep, fileSep); 1394 JImage_file =(*JImageOpen)(modules_path, &error); 1395 if (JImage_file == nullptr) { 1396 return nullptr; 1397 } 1398 1399 const char *jimage_version = get_jimage_version_string(); 1400 char *options = lookup_vm_resource(JImage_file, jimage_version, "jdk/internal/vm/options"); 1401 return options; 1402 } 1403 1404 bool ClassLoader::is_module_observable(const char* module_name) { 1405 assert(JImageOpen != nullptr, "jimage library should have been opened"); 1406 if (JImage_file == nullptr) { 1407 struct stat st; 1408 const char *path = get_exploded_module_path(module_name, true); 1409 bool res = os::stat(path, &st) == 0; 1410 FREE_C_HEAP_ARRAY(char, path); 1411 return res; 1412 } 1413 jlong size; 1414 const char *jimage_version = get_jimage_version_string(); 1415 return (*JImageFindResource)(JImage_file, module_name, jimage_version, "module-info.class", &size) != 0; 1416 } 1417 1418 #if INCLUDE_CDS 1419 void ClassLoader::initialize_shared_path(JavaThread* current) { 1420 if (CDSConfig::is_dumping_archive()) { 1421 ClassLoaderExt::setup_search_paths(current); 1422 } 1423 } 1424 1425 void ClassLoader::initialize_module_path(TRAPS) { 1426 if (CDSConfig::is_dumping_archive()) { 1427 ClassLoaderExt::setup_module_paths(THREAD); 1428 FileMapInfo::allocate_shared_path_table(CHECK); 1429 } 1430 } 1431 1432 // Helper function used by CDS code to get the number of module path 1433 // entries during shared classpath setup time. 1434 int ClassLoader::num_module_path_entries() { 1435 assert(CDSConfig::is_dumping_archive(), "sanity"); 1436 int num_entries = 0; 1437 ClassPathEntry* e= ClassLoader::_module_path_entries; 1438 while (e != nullptr) { 1439 num_entries ++; 1440 e = e->next(); 1441 } 1442 return num_entries; 1443 } 1444 #endif 1445 1446 jlong ClassLoader::classloader_time_ms() { 1447 return UsePerfData ? 1448 Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1; 1449 } 1450 1451 jlong ClassLoader::class_init_count() { 1452 return UsePerfData ? _perf_classes_inited->get_value() : -1; 1453 } 1454 1455 jlong ClassLoader::class_init_time_ms() { 1456 return UsePerfData ? 1457 Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1; 1458 } 1459 1460 jlong ClassLoader::class_verify_time_ms() { 1461 return UsePerfData ? 1462 Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1; 1463 } 1464 1465 jlong ClassLoader::class_link_count() { 1466 return UsePerfData ? _perf_classes_linked->get_value() : -1; 1467 } 1468 1469 jlong ClassLoader::class_link_time_ms() { 1470 return UsePerfData ? 1471 Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1; 1472 } 1473 1474 int ClassLoader::compute_Object_vtable() { 1475 // hardwired for JDK1.2 -- would need to duplicate class file parsing 1476 // code to determine actual value from file 1477 // Would be value '11' if finals were in vtable 1478 int JDK_1_2_Object_vtable_size = 5; 1479 return JDK_1_2_Object_vtable_size * vtableEntry::size(); 1480 } 1481 1482 1483 void classLoader_init1() { 1484 EXCEPTION_MARK; 1485 ClassLoader::initialize(THREAD); 1486 if (HAS_PENDING_EXCEPTION) { 1487 vm_exit_during_initialization("ClassLoader::initialize() failed unexpectedly"); 1488 } 1489 } 1490 1491 // Complete the ClassPathEntry setup for the boot loader 1492 void ClassLoader::classLoader_init2(JavaThread* current) { 1493 // Setup the list of module/path pairs for --patch-module processing 1494 // This must be done after the SymbolTable is created in order 1495 // to use fast_compare on module names instead of a string compare. 1496 if (Arguments::get_patch_mod_prefix() != nullptr) { 1497 setup_patch_mod_entries(); 1498 } 1499 1500 // Create the ModuleEntry for java.base (must occur after setup_patch_mod_entries 1501 // to successfully determine if java.base has been patched) 1502 create_javabase(); 1503 1504 // Setup the initial java.base/path pair for the exploded build entries. 1505 // As more modules are defined during module system initialization, more 1506 // entries will be added to the exploded build array. 1507 if (!has_jrt_entry()) { 1508 assert(!CDSConfig::is_dumping_archive(), "not supported with exploded module builds"); 1509 assert(!UseSharedSpaces, "UsedSharedSpaces not supported with exploded module builds"); 1510 // Set up the boot loader's _exploded_entries list. Note that this gets 1511 // done before loading any classes, by the same thread that will 1512 // subsequently do the first class load. So, no lock is needed for this. 1513 assert(_exploded_entries == nullptr, "Should only get initialized once"); 1514 _exploded_entries = new (mtModule) 1515 GrowableArray<ModuleClassPathList*>(EXPLODED_ENTRY_SIZE, mtModule); 1516 add_to_exploded_build_list(current, vmSymbols::java_base()); 1517 } 1518 } 1519 1520 char* ClassLoader::get_canonical_path(const char* orig, Thread* thread) { 1521 assert(orig != nullptr, "bad arguments"); 1522 // caller needs to allocate ResourceMark for the following output buffer 1523 char* canonical_path = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, JVM_MAXPATHLEN); 1524 ResourceMark rm(thread); 1525 // os::native_path writes into orig_copy 1526 char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, strlen(orig)+1); 1527 strcpy(orig_copy, orig); 1528 if ((CanonicalizeEntry)(os::native_path(orig_copy), canonical_path, JVM_MAXPATHLEN) < 0) { 1529 return nullptr; 1530 } 1531 return canonical_path; 1532 } 1533 1534 void ClassLoader::create_javabase() { 1535 JavaThread* current = JavaThread::current(); 1536 1537 // Create java.base's module entry for the boot 1538 // class loader prior to loading j.l.Object. 1539 ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data(); 1540 1541 // Get module entry table 1542 ModuleEntryTable* null_cld_modules = null_cld->modules(); 1543 if (null_cld_modules == nullptr) { 1544 vm_exit_during_initialization("No ModuleEntryTable for the boot class loader"); 1545 } 1546 1547 { 1548 MutexLocker ml(current, Module_lock); 1549 if (ModuleEntryTable::javabase_moduleEntry() == nullptr) { // may have been inited by CDS. 1550 ModuleEntry* jb_module = null_cld_modules->locked_create_entry(Handle(), 1551 false, vmSymbols::java_base(), nullptr, nullptr, null_cld); 1552 if (jb_module == nullptr) { 1553 vm_exit_during_initialization("Unable to create ModuleEntry for " JAVA_BASE_NAME); 1554 } 1555 ModuleEntryTable::set_javabase_moduleEntry(jb_module); 1556 } 1557 } 1558 } 1559 1560 // Please keep following two functions at end of this file. With them placed at top or in middle of the file, 1561 // they could get inlined by aggressive compiler, an unknown trick, see bug 6966589. 1562 void PerfClassTraceTime::initialize() { 1563 if (!UsePerfData) return; 1564 1565 if (_eventp != nullptr) { 1566 // increment the event counter 1567 _eventp->inc(); 1568 } 1569 1570 // stop the current active thread-local timer to measure inclusive time 1571 _prev_active_event = -1; 1572 for (int i=0; i < EVENT_TYPE_COUNT; i++) { 1573 if (_timers[i].is_active()) { 1574 assert(_prev_active_event == -1, "should have only one active timer"); 1575 _prev_active_event = i; 1576 _timers[i].stop(); 1577 } 1578 } 1579 1580 if (_recursion_counters == nullptr || (_recursion_counters[_event_type])++ == 0) { 1581 // start the inclusive timer if not recursively called 1582 _t.start(); 1583 } 1584 1585 // start thread-local timer of the given event type 1586 if (!_timers[_event_type].is_active()) { 1587 _timers[_event_type].start(); 1588 } 1589 } 1590 1591 PerfClassTraceTime::~PerfClassTraceTime() { 1592 if (!UsePerfData) return; 1593 1594 // stop the thread-local timer as the event completes 1595 // and resume the thread-local timer of the event next on the stack 1596 _timers[_event_type].stop(); 1597 jlong selftime = _timers[_event_type].ticks(); 1598 1599 if (_prev_active_event >= 0) { 1600 _timers[_prev_active_event].start(); 1601 } 1602 1603 if (_recursion_counters != nullptr && --(_recursion_counters[_event_type]) > 0) return; 1604 1605 // increment the counters only on the leaf call 1606 _t.stop(); 1607 _timep->inc(_t.ticks()); 1608 if (_selftimep != nullptr) { 1609 _selftimep->inc(selftime); 1610 } 1611 // add all class loading related event selftime to the accumulated time counter 1612 ClassLoader::perf_accumulated_time()->inc(selftime); 1613 1614 // reset the timer 1615 _timers[_event_type].reset(); 1616 }