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