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