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