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