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