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