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