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