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