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