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