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