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 the module list for the class file stream based on the file name and java package
1034 ClassFileStream* ClassLoader::search_module_entries(JavaThread* current,
1035                                                     const GrowableArray<ModuleClassPathList*>* const module_list,
1036                                                     PackageEntry* pkg_entry, // Java package entry derived from the class name
1037                                                     const char* const file_name) {
1038   ClassFileStream* stream = nullptr;
1039 
1040   // Find the defining module in the boot loader's module entry table
1041   ModuleEntry* mod_entry = (pkg_entry != nullptr) ? pkg_entry->module() : nullptr;
1042 
1043   // If the module system has not defined java.base yet, then
1044   // classes loaded are assumed to be defined to java.base.
1045   // When java.base is eventually defined by the module system,
1046   // all packages of classes that have been previously loaded
1047   // are verified in ModuleEntryTable::verify_javabase_packages().
1048   if (!Universe::is_module_initialized() &&
1049       !ModuleEntryTable::javabase_defined() &&
1050       mod_entry == nullptr) {
1051     mod_entry = ModuleEntryTable::javabase_moduleEntry();
1052   }
1053 
1054   // The module must be a named module
1055   ClassPathEntry* e = nullptr;
1056   if (mod_entry != nullptr && mod_entry->is_named()) {
1057     if (module_list == _exploded_entries) {
1058       // The exploded build entries can be added to at any time so a lock is
1059       // needed when searching them.
1060       assert(!ClassLoader::has_jrt_entry(), "Must be exploded build");
1061       MutexLocker ml(current, Module_lock);
1062       e = find_first_module_cpe(mod_entry, module_list);
1063     } else {
1064       e = find_first_module_cpe(mod_entry, module_list);
1065     }
1066   }
1067 
1068   // Try to load the class from the module's ClassPathEntry list.
1069   while (e != nullptr) {
1070     stream = e->open_stream(current, file_name);
1071     // No context.check is required since CDS is not supported
1072     // for an exploded modules build or if --patch-module is specified.
1073     if (nullptr != stream) {
1074       return stream;
1075     }
1076     e = e->next();
1077   }
1078   // If the module was located, break out even if the class was not
1079   // located successfully from that module's ClassPathEntry list.
1080   // There will not be another valid entry for that module.
1081   return nullptr;
1082 }
1083 
1084 // Called by the boot classloader to load classes
1085 InstanceKlass* ClassLoader::load_class(Symbol* name, PackageEntry* pkg_entry, bool search_append_only, TRAPS) {
1086   assert(name != nullptr, "invariant");
1087 
1088   ResourceMark rm(THREAD);
1089   HandleMark hm(THREAD);
1090 
1091   const char* const class_name = name->as_C_string();
1092 
1093   EventMarkClassLoading m("Loading class %s", class_name);
1094 
1095   const char* const file_name = file_name_for_class_name(class_name,
1096                                                          name->utf8_length());
1097   assert(file_name != nullptr, "invariant");
1098 
1099   // Lookup stream for parsing .class file
1100   ClassFileStream* stream = nullptr;
1101   s2 classpath_index = 0;
1102   ClassPathEntry* e = nullptr;
1103 
1104   // If search_append_only is true, boot loader visibility boundaries are
1105   // set to be _first_append_entry to the end. This includes:
1106   //   [-Xbootclasspath/a]; [jvmti appended entries]
1107   //
1108   // If search_append_only is false, boot loader visibility boundaries are
1109   // set to be the --patch-module entries plus the base piece. This includes:
1110   //   [--patch-module=<module>=<file>(<pathsep><file>)*]; [jimage | exploded module build]
1111   //
1112 
1113   // Load Attempt #1: --patch-module
1114   // Determine the class' defining module.  If it appears in the _patch_mod_entries,
1115   // attempt to load the class from those locations specific to the module.
1116   // Specifications to --patch-module can contain a partial number of classes
1117   // that are part of the overall module definition.  So if a particular class is not
1118   // found within its module specification, the search should continue to Load Attempt #2.
1119   // Note: The --patch-module entries are never searched if the boot loader's
1120   //       visibility boundary is limited to only searching the append entries.
1121   if (_patch_mod_entries != nullptr && !search_append_only) {
1122     // At CDS dump time, the --patch-module entries are ignored. That means a
1123     // class is still loaded from the runtime image even if it might
1124     // appear in the _patch_mod_entries. The runtime shared class visibility
1125     // check will determine if a shared class is visible based on the runtime
1126     // environment, including the runtime --patch-module setting.
1127     //
1128     // Dynamic dumping requires UseSharedSpaces to be enabled. Since --patch-module
1129     // is not supported with UseSharedSpaces, we can never come here during dynamic dumping.
1130     assert(!CDSConfig::is_dumping_dynamic_archive(), "sanity");
1131     if (!CDSConfig::is_dumping_static_archive()) {
1132       stream = search_module_entries(THREAD, _patch_mod_entries, pkg_entry, file_name);
1133     }
1134   }
1135 
1136   // Load Attempt #2: [jimage | exploded build]
1137   if (!search_append_only && (nullptr == stream)) {
1138     if (has_jrt_entry()) {
1139       e = _jrt_entry;
1140       stream = _jrt_entry->open_stream(THREAD, file_name);
1141     } else {
1142       // Exploded build - attempt to locate class in its defining module's location.
1143       assert(_exploded_entries != nullptr, "No exploded build entries present");
1144       stream = search_module_entries(THREAD, _exploded_entries, pkg_entry, file_name);
1145     }
1146   }
1147 
1148   // Load Attempt #3: [-Xbootclasspath/a]; [jvmti appended entries]
1149   if (search_append_only && (nullptr == stream)) {
1150     // For the boot loader append path search, the starting classpath_index
1151     // for the appended piece is always 1 to account for either the
1152     // _jrt_entry or the _exploded_entries.
1153     assert(classpath_index == 0, "The classpath_index has been incremented incorrectly");
1154     classpath_index = 1;
1155 
1156     e = first_append_entry();
1157     while (e != nullptr) {
1158       stream = e->open_stream(THREAD, file_name);
1159       if (nullptr != stream) {
1160         break;
1161       }
1162       e = e->next();
1163       ++classpath_index;
1164     }
1165   }
1166 
1167   if (nullptr == stream) {
1168     return nullptr;
1169   }
1170 
1171   stream->set_verify(ClassLoaderExt::should_verify(classpath_index));
1172 
1173   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
1174   Handle protection_domain;
1175   ClassLoadInfo cl_info(protection_domain);
1176 
1177   InstanceKlass* result = KlassFactory::create_from_stream(stream,
1178                                                            name,
1179                                                            loader_data,
1180                                                            cl_info,
1181                                                            CHECK_NULL);
1182   result->set_classpath_index(classpath_index);
1183   return result;
1184 }
1185 
1186 #if INCLUDE_CDS
1187 char* ClassLoader::skip_uri_protocol(char* source) {
1188   if (strncmp(source, "file:", 5) == 0) {
1189     // file: protocol path could start with file:/ or file:///
1190     // locate the char after all the forward slashes
1191     int offset = 5;
1192     while (*(source + offset) == '/') {
1193         offset++;
1194     }
1195     source += offset;
1196   // for non-windows platforms, move back one char as the path begins with a '/'
1197 #ifndef _WINDOWS
1198     source -= 1;
1199 #endif
1200   } else if (strncmp(source, "jrt:/", 5) == 0) {
1201     source += 5;
1202   }
1203   return source;
1204 }
1205 
1206 // Record the shared classpath index and loader type for classes loaded
1207 // by the builtin loaders at dump time.
1208 void ClassLoader::record_result(JavaThread* current, InstanceKlass* ik,
1209                                 const ClassFileStream* stream, bool redefined) {
1210   assert(CDSConfig::is_dumping_archive(), "sanity");
1211   assert(stream != nullptr, "sanity");
1212 
1213   if (ik->is_hidden()) {
1214     // We do not archive hidden classes.
1215     return;
1216   }
1217 
1218   oop loader = ik->class_loader();
1219   char* src = (char*)stream->source();
1220   if (src == nullptr) {
1221     if (loader == nullptr) {
1222       // JFR classes
1223       ik->set_shared_classpath_index(0);
1224       ik->set_shared_class_loader_type(ClassLoader::BOOT_LOADER);
1225     }
1226     return;
1227   }
1228 
1229   assert(has_jrt_entry(), "CDS dumping does not support exploded JDK build");
1230 
1231   ResourceMark rm(current);
1232   int classpath_index = -1;
1233   PackageEntry* pkg_entry = ik->package();
1234 
1235   if (FileMapInfo::get_number_of_shared_paths() > 0) {
1236     // Save the path from the file: protocol or the module name from the jrt: protocol
1237     // if no protocol prefix is found, path is the same as stream->source(). This path
1238     // must be valid since the class has been successfully parsed.
1239     char* path = skip_uri_protocol(src);
1240     assert(path != nullptr, "sanity");
1241     for (int i = 0; i < FileMapInfo::get_number_of_shared_paths(); i++) {
1242       SharedClassPathEntry* ent = FileMapInfo::shared_path(i);
1243       // A shared path has been validated during its creation in ClassLoader::create_class_path_entry(),
1244       // it must be valid here.
1245       assert(ent->name() != nullptr, "sanity");
1246       // If the path (from the class stream source) is the same as the shared
1247       // class or module path, then we have a match.
1248       // src may come from the App/Platform class loaders, which would canonicalize
1249       // the file name. We cannot use strcmp to check for equality against ent->name().
1250       // We must use os::same_files (which is faster than canonicalizing ent->name()).
1251       if (os::same_files(ent->name(), path)) {
1252         // null pkg_entry and pkg_entry in an unnamed module implies the class
1253         // is from the -cp or boot loader append path which consists of -Xbootclasspath/a
1254         // and jvmti appended entries.
1255         if ((pkg_entry == nullptr) || (pkg_entry->in_unnamed_module())) {
1256           // Ensure the index is within the -cp range before assigning
1257           // to the classpath_index.
1258           if (SystemDictionary::is_system_class_loader(loader) &&
1259               (i >= ClassLoaderExt::app_class_paths_start_index()) &&
1260               (i < ClassLoaderExt::app_module_paths_start_index())) {
1261             classpath_index = i;
1262             break;
1263           } else {
1264             if ((i >= 1) &&
1265                 (i < ClassLoaderExt::app_class_paths_start_index())) {
1266               // The class must be from boot loader append path which consists of
1267               // -Xbootclasspath/a and jvmti appended entries.
1268               assert(loader == nullptr, "sanity");
1269               classpath_index = i;
1270               break;
1271             }
1272           }
1273         } else {
1274           // A class from a named module from the --module-path. Ensure the index is
1275           // within the --module-path range before assigning to the classpath_index.
1276           if ((pkg_entry != nullptr) && !(pkg_entry->in_unnamed_module()) && (i > 0)) {
1277             if (i >= ClassLoaderExt::app_module_paths_start_index() &&
1278                 i < FileMapInfo::get_number_of_shared_paths()) {
1279               classpath_index = i;
1280               break;
1281             }
1282           }
1283         }
1284       }
1285       // for index 0 and the stream->source() is the modules image or has the jrt: protocol.
1286       // The class must be from the runtime modules image.
1287       if (i == 0 && (stream->from_boot_loader_modules_image() || string_starts_with(src, "jrt:"))) {
1288         classpath_index = i;
1289         break;
1290       }
1291     }
1292 
1293     // No path entry found for this class: most likely a shared class loaded by the
1294     // user defined classloader.
1295     if (classpath_index < 0 && !SystemDictionaryShared::is_builtin_loader(ik->class_loader_data())) {
1296       assert(ik->shared_classpath_index() < 0, "not assigned yet");
1297       ik->set_shared_classpath_index(UNREGISTERED_INDEX);
1298       SystemDictionaryShared::set_shared_class_misc_info(ik, (ClassFileStream*)stream);
1299       return;
1300     }
1301   } else {
1302     // The shared path table is set up after module system initialization.
1303     // The path table contains no entry before that. Any classes loaded prior
1304     // to the setup of the shared path table must be from the modules image.
1305     assert(stream->from_boot_loader_modules_image(), "stream must be loaded by boot loader from modules image");
1306     assert(FileMapInfo::get_number_of_shared_paths() == 0, "shared path table must not have been setup");
1307     classpath_index = 0;
1308   }
1309 
1310   const char* const class_name = ik->name()->as_C_string();
1311   const char* const file_name = file_name_for_class_name(class_name,
1312                                                          ik->name()->utf8_length());
1313   assert(file_name != nullptr, "invariant");
1314   ClassLoaderExt::record_result(checked_cast<s2>(classpath_index), ik, redefined);
1315 }
1316 #endif // INCLUDE_CDS
1317 
1318 // Initialize the class loader's access to methods in libzip.  Parse and
1319 // process the boot classpath into a list ClassPathEntry objects.  Once
1320 // this list has been created, it must not change order (see class PackageInfo)
1321 // it can be appended to and is by jvmti.
1322 
1323 void ClassLoader::initialize(TRAPS) {
1324   if (UsePerfData) {
1325     // jvmstat performance counters
1326     NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");
1327     NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");
1328     NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");
1329     NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");
1330     NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");
1331     NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");
1332     NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");
1333     NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");
1334     NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");
1335     NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");
1336 
1337     NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");
1338     NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");
1339     NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");
1340     NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");
1341     NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");
1342     NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");
1343     NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");
1344     NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");
1345     NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");
1346     NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");
1347 
1348     NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS, "unsafeDefineClassCalls");
1349   }
1350 
1351   // lookup java library entry points
1352   load_java_library();
1353   // jimage library entry points are loaded below, in lookup_vm_options
1354   setup_bootstrap_search_path(THREAD);
1355 }
1356 
1357 static char* lookup_vm_resource(JImageFile *jimage, const char *jimage_version, const char *path) {
1358   jlong size;
1359   JImageLocationRef location = (*JImageFindResource)(jimage, "java.base", jimage_version, path, &size);
1360   if (location == 0)
1361     return nullptr;
1362   char *val = NEW_C_HEAP_ARRAY(char, size+1, mtClass);
1363   (*JImageGetResource)(jimage, location, val, size);
1364   val[size] = '\0';
1365   return val;
1366 }
1367 
1368 // Lookup VM options embedded in the modules jimage file
1369 char* ClassLoader::lookup_vm_options() {
1370   jint error;
1371   char modules_path[JVM_MAXPATHLEN];
1372   const char* fileSep = os::file_separator();
1373 
1374   // Initialize jimage library entry points
1375   load_jimage_library();
1376 
1377   jio_snprintf(modules_path, JVM_MAXPATHLEN, "%s%slib%smodules", Arguments::get_java_home(), fileSep, fileSep);
1378   JImage_file =(*JImageOpen)(modules_path, &error);
1379   if (JImage_file == nullptr) {
1380     return nullptr;
1381   }
1382 
1383   const char *jimage_version = get_jimage_version_string();
1384   char *options = lookup_vm_resource(JImage_file, jimage_version, "jdk/internal/vm/options");
1385   return options;
1386 }
1387 
1388 bool ClassLoader::is_module_observable(const char* module_name) {
1389   assert(JImageOpen != nullptr, "jimage library should have been opened");
1390   if (JImage_file == nullptr) {
1391     struct stat st;
1392     const char *path = get_exploded_module_path(module_name, true);
1393     bool res = os::stat(path, &st) == 0;
1394     FREE_C_HEAP_ARRAY(char, path);
1395     return res;
1396   }
1397   jlong size;
1398   const char *jimage_version = get_jimage_version_string();
1399   return (*JImageFindResource)(JImage_file, module_name, jimage_version, "module-info.class", &size) != 0;
1400 }
1401 
1402 #if INCLUDE_CDS
1403 void ClassLoader::initialize_shared_path(JavaThread* current) {
1404   if (CDSConfig::is_dumping_archive()) {
1405     ClassLoaderExt::setup_search_paths(current);
1406   }
1407 }
1408 
1409 void ClassLoader::initialize_module_path(TRAPS) {
1410   if (CDSConfig::is_dumping_archive()) {
1411     ClassLoaderExt::setup_module_paths(THREAD);
1412     FileMapInfo::allocate_shared_path_table(CHECK);
1413   }
1414 }
1415 
1416 // Helper function used by CDS code to get the number of module path
1417 // entries during shared classpath setup time.
1418 int ClassLoader::num_module_path_entries() {
1419   assert(CDSConfig::is_dumping_archive(), "sanity");
1420   int num_entries = 0;
1421   ClassPathEntry* e= ClassLoader::_module_path_entries;
1422   while (e != nullptr) {
1423     num_entries ++;
1424     e = e->next();
1425   }
1426   return num_entries;
1427 }
1428 #endif
1429 
1430 jlong ClassLoader::classloader_time_ms() {
1431   return UsePerfData ?
1432     Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;
1433 }
1434 
1435 jlong ClassLoader::class_init_count() {
1436   return UsePerfData ? _perf_classes_inited->get_value() : -1;
1437 }
1438 
1439 jlong ClassLoader::class_init_time_ms() {
1440   return UsePerfData ?
1441     Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;
1442 }
1443 
1444 jlong ClassLoader::class_verify_time_ms() {
1445   return UsePerfData ?
1446     Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;
1447 }
1448 
1449 jlong ClassLoader::class_link_count() {
1450   return UsePerfData ? _perf_classes_linked->get_value() : -1;
1451 }
1452 
1453 jlong ClassLoader::class_link_time_ms() {
1454   return UsePerfData ?
1455     Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;
1456 }
1457 
1458 int ClassLoader::compute_Object_vtable() {
1459   // hardwired for JDK1.2 -- would need to duplicate class file parsing
1460   // code to determine actual value from file
1461   // Would be value '11' if finals were in vtable
1462   int JDK_1_2_Object_vtable_size = 5;
1463   return JDK_1_2_Object_vtable_size * vtableEntry::size();
1464 }
1465 
1466 
1467 void classLoader_init1() {
1468   EXCEPTION_MARK;
1469   ClassLoader::initialize(THREAD);
1470   if (HAS_PENDING_EXCEPTION) {
1471     vm_exit_during_initialization("ClassLoader::initialize() failed unexpectedly");
1472   }
1473 }
1474 
1475 // Complete the ClassPathEntry setup for the boot loader
1476 void ClassLoader::classLoader_init2(JavaThread* current) {
1477   // Setup the list of module/path pairs for --patch-module processing
1478   // This must be done after the SymbolTable is created in order
1479   // to use fast_compare on module names instead of a string compare.
1480   if (Arguments::get_patch_mod_prefix() != nullptr) {
1481     setup_patch_mod_entries();
1482   }
1483 
1484   // Create the ModuleEntry for java.base (must occur after setup_patch_mod_entries
1485   // to successfully determine if java.base has been patched)
1486   create_javabase();
1487 
1488   // Setup the initial java.base/path pair for the exploded build entries.
1489   // As more modules are defined during module system initialization, more
1490   // entries will be added to the exploded build array.
1491   if (!has_jrt_entry()) {
1492     assert(!CDSConfig::is_dumping_archive(), "not supported with exploded module builds");
1493     assert(!UseSharedSpaces, "UsedSharedSpaces not supported with exploded module builds");
1494     // Set up the boot loader's _exploded_entries list.  Note that this gets
1495     // done before loading any classes, by the same thread that will
1496     // subsequently do the first class load. So, no lock is needed for this.
1497     assert(_exploded_entries == nullptr, "Should only get initialized once");
1498     _exploded_entries = new (mtModule)
1499       GrowableArray<ModuleClassPathList*>(EXPLODED_ENTRY_SIZE, mtModule);
1500     add_to_exploded_build_list(current, vmSymbols::java_base());
1501   }
1502 }
1503 
1504 char* ClassLoader::get_canonical_path(const char* orig, Thread* thread) {
1505   assert(orig != nullptr, "bad arguments");
1506   // caller needs to allocate ResourceMark for the following output buffer
1507   char* canonical_path = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, JVM_MAXPATHLEN);
1508   ResourceMark rm(thread);
1509   // os::native_path writes into orig_copy
1510   char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, strlen(orig)+1);
1511   strcpy(orig_copy, orig);
1512   if ((CanonicalizeEntry)(os::native_path(orig_copy), canonical_path, JVM_MAXPATHLEN) < 0) {
1513     return nullptr;
1514   }
1515   return canonical_path;
1516 }
1517 
1518 void ClassLoader::create_javabase() {
1519   JavaThread* current = JavaThread::current();
1520 
1521   // Create java.base's module entry for the boot
1522   // class loader prior to loading j.l.Object.
1523   ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
1524 
1525   // Get module entry table
1526   ModuleEntryTable* null_cld_modules = null_cld->modules();
1527   if (null_cld_modules == nullptr) {
1528     vm_exit_during_initialization("No ModuleEntryTable for the boot class loader");
1529   }
1530 
1531   {
1532     MutexLocker ml(current, Module_lock);
1533     if (ModuleEntryTable::javabase_moduleEntry() == nullptr) {  // may have been inited by CDS.
1534       ModuleEntry* jb_module = null_cld_modules->locked_create_entry(Handle(),
1535                                false, vmSymbols::java_base(), nullptr, nullptr, null_cld);
1536       if (jb_module == nullptr) {
1537         vm_exit_during_initialization("Unable to create ModuleEntry for " JAVA_BASE_NAME);
1538       }
1539       ModuleEntryTable::set_javabase_moduleEntry(jb_module);
1540     }
1541   }
1542 }
1543 
1544 // Please keep following two functions at end of this file. With them placed at top or in middle of the file,
1545 // they could get inlined by aggressive compiler, an unknown trick, see bug 6966589.
1546 void PerfClassTraceTime::initialize() {
1547   if (!UsePerfData) return;
1548 
1549   if (_eventp != nullptr) {
1550     // increment the event counter
1551     _eventp->inc();
1552   }
1553 
1554   // stop the current active thread-local timer to measure inclusive time
1555   _prev_active_event = -1;
1556   for (int i=0; i < EVENT_TYPE_COUNT; i++) {
1557      if (_timers[i].is_active()) {
1558        assert(_prev_active_event == -1, "should have only one active timer");
1559        _prev_active_event = i;
1560        _timers[i].stop();
1561      }
1562   }
1563 
1564   if (_recursion_counters == nullptr || (_recursion_counters[_event_type])++ == 0) {
1565     // start the inclusive timer if not recursively called
1566     _t.start();
1567   }
1568 
1569   // start thread-local timer of the given event type
1570    if (!_timers[_event_type].is_active()) {
1571     _timers[_event_type].start();
1572   }
1573 }
1574 
1575 PerfClassTraceTime::~PerfClassTraceTime() {
1576   if (!UsePerfData) return;
1577 
1578   // stop the thread-local timer as the event completes
1579   // and resume the thread-local timer of the event next on the stack
1580   _timers[_event_type].stop();
1581   jlong selftime = _timers[_event_type].ticks();
1582 
1583   if (_prev_active_event >= 0) {
1584     _timers[_prev_active_event].start();
1585   }
1586 
1587   if (_recursion_counters != nullptr && --(_recursion_counters[_event_type]) > 0) return;
1588 
1589   // increment the counters only on the leaf call
1590   _t.stop();
1591   _timep->inc(_t.ticks());
1592   if (_selftimep != nullptr) {
1593     _selftimep->inc(selftime);
1594   }
1595   // add all class loading related event selftime to the accumulated time counter
1596   ClassLoader::perf_accumulated_time()->inc(selftime);
1597 
1598   // reset the timer
1599   _timers[_event_type].reset();
1600 }