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