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