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