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