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