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