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