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