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