1 /*
   2  * Copyright (c) 1997, 2016, 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 "classfile/classFileStream.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/classLoaderData.inline.hpp"
  29 #include "classfile/classLoaderExt.hpp"
  30 #include "classfile/javaClasses.hpp"
  31 #include "classfile/jimage.hpp"
  32 #include "classfile/moduleEntry.hpp"
  33 #include "classfile/modules.hpp"
  34 #include "classfile/packageEntry.hpp"
  35 #include "classfile/klassFactory.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/vmSymbols.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "gc/shared/collectedHeap.inline.hpp"
  40 #include "gc/shared/generation.hpp"
  41 #include "interpreter/bytecodeStream.hpp"
  42 #include "interpreter/oopMapCache.hpp"
  43 #include "logging/logTag.hpp"
  44 #include "memory/allocation.inline.hpp"
  45 #include "memory/filemap.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/resourceArea.hpp"
  48 #include "memory/universe.inline.hpp"
  49 #include "oops/instanceKlass.hpp"
  50 #include "oops/instanceRefKlass.hpp"
  51 #include "oops/objArrayOop.inline.hpp"
  52 #include "oops/oop.inline.hpp"
  53 #include "oops/symbol.hpp"
  54 #include "prims/jvm_misc.hpp"
  55 #include "runtime/arguments.hpp"
  56 #include "runtime/compilationPolicy.hpp"
  57 #include "runtime/fprofiler.hpp"
  58 #include "runtime/handles.hpp"
  59 #include "runtime/handles.inline.hpp"
  60 #include "runtime/init.hpp"
  61 #include "runtime/interfaceSupport.hpp"
  62 #include "runtime/java.hpp"
  63 #include "runtime/javaCalls.hpp"
  64 #include "runtime/os.hpp"
  65 #include "runtime/threadCritical.hpp"
  66 #include "runtime/timer.hpp"
  67 #include "runtime/vm_version.hpp"
  68 #include "services/management.hpp"
  69 #include "services/threadService.hpp"
  70 #include "utilities/events.hpp"
  71 #include "utilities/hashtable.inline.hpp"
  72 #include "utilities/macros.hpp"
  73 #if INCLUDE_CDS
  74 #include "classfile/sharedClassUtil.hpp"
  75 #include "classfile/sharedPathsMiscInfo.hpp"
  76 #endif
  77 
  78 // Entry points in zip.dll for loading zip/jar file entries
  79 
  80 typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg);
  81 typedef void (JNICALL *ZipClose_t)(jzfile *zip);
  82 typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen);
  83 typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);
  84 typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf);
  85 typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);
  86 typedef jboolean (JNICALL *ZipInflateFully_t)(void *inBuf, jlong inLen, void *outBuf, jlong outLen, char **pmsg);
  87 typedef jint     (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);
  88 
  89 static ZipOpen_t         ZipOpen            = NULL;
  90 static ZipClose_t        ZipClose           = NULL;
  91 static FindEntry_t       FindEntry          = NULL;
  92 static ReadEntry_t       ReadEntry          = NULL;
  93 static ReadMappedEntry_t ReadMappedEntry    = NULL;
  94 static GetNextEntry_t    GetNextEntry       = NULL;
  95 static canonicalize_fn_t CanonicalizeEntry  = NULL;
  96 static ZipInflateFully_t ZipInflateFully    = NULL;
  97 static Crc32_t           Crc32              = NULL;
  98 
  99 // Entry points for jimage.dll for loading jimage file entries
 100 
 101 static JImageOpen_t                    JImageOpen             = NULL;
 102 static JImageClose_t                   JImageClose            = NULL;
 103 static JImagePackageToModule_t         JImagePackageToModule  = NULL;
 104 static JImageFindResource_t            JImageFindResource     = NULL;
 105 static JImageGetResource_t             JImageGetResource      = NULL;
 106 static JImageResourceIterator_t        JImageResourceIterator = NULL;
 107 static JImage_ResourcePath_t           JImageResourcePath     = NULL;
 108 
 109 // Globals
 110 
 111 PerfCounter*    ClassLoader::_perf_accumulated_time = NULL;
 112 PerfCounter*    ClassLoader::_perf_classes_inited = NULL;
 113 PerfCounter*    ClassLoader::_perf_class_init_time = NULL;
 114 PerfCounter*    ClassLoader::_perf_class_init_selftime = NULL;
 115 PerfCounter*    ClassLoader::_perf_classes_verified = NULL;
 116 PerfCounter*    ClassLoader::_perf_class_verify_time = NULL;
 117 PerfCounter*    ClassLoader::_perf_class_verify_selftime = NULL;
 118 PerfCounter*    ClassLoader::_perf_classes_linked = NULL;
 119 PerfCounter*    ClassLoader::_perf_class_link_time = NULL;
 120 PerfCounter*    ClassLoader::_perf_class_link_selftime = NULL;
 121 PerfCounter*    ClassLoader::_perf_class_parse_time = NULL;
 122 PerfCounter*    ClassLoader::_perf_class_parse_selftime = NULL;
 123 PerfCounter*    ClassLoader::_perf_sys_class_lookup_time = NULL;
 124 PerfCounter*    ClassLoader::_perf_shared_classload_time = NULL;
 125 PerfCounter*    ClassLoader::_perf_sys_classload_time = NULL;
 126 PerfCounter*    ClassLoader::_perf_app_classload_time = NULL;
 127 PerfCounter*    ClassLoader::_perf_app_classload_selftime = NULL;
 128 PerfCounter*    ClassLoader::_perf_app_classload_count = NULL;
 129 PerfCounter*    ClassLoader::_perf_define_appclasses = NULL;
 130 PerfCounter*    ClassLoader::_perf_define_appclass_time = NULL;
 131 PerfCounter*    ClassLoader::_perf_define_appclass_selftime = NULL;
 132 PerfCounter*    ClassLoader::_perf_app_classfile_bytes_read = NULL;
 133 PerfCounter*    ClassLoader::_perf_sys_classfile_bytes_read = NULL;
 134 PerfCounter*    ClassLoader::_sync_systemLoaderLockContentionRate = NULL;
 135 PerfCounter*    ClassLoader::_sync_nonSystemLoaderLockContentionRate = NULL;
 136 PerfCounter*    ClassLoader::_sync_JVMFindLoadedClassLockFreeCounter = NULL;
 137 PerfCounter*    ClassLoader::_sync_JVMDefineClassLockFreeCounter = NULL;
 138 PerfCounter*    ClassLoader::_sync_JNIDefineClassLockFreeCounter = NULL;
 139 PerfCounter*    ClassLoader::_unsafe_defineClassCallCounter = NULL;
 140 PerfCounter*    ClassLoader::_isUnsyncloadClass = NULL;
 141 PerfCounter*    ClassLoader::_load_instance_class_failCounter = NULL;
 142 
 143 GrowableArray<ModuleClassPathList*>* ClassLoader::_patch_mod_entries = NULL;
 144 GrowableArray<ModuleClassPathList*>* ClassLoader::_exploded_entries = NULL;
 145 ClassPathEntry* ClassLoader::_jrt_entry = NULL;
 146 ClassPathEntry* ClassLoader::_first_append_entry = NULL;
 147 ClassPathEntry* ClassLoader::_last_append_entry  = NULL;
 148 int             ClassLoader::_num_entries        = 0;
 149 #if INCLUDE_CDS
 150 GrowableArray<char*>* ClassLoader::_boot_modules_array = NULL;
 151 GrowableArray<char*>* ClassLoader::_platform_modules_array = NULL;
 152 SharedPathsMiscInfo* ClassLoader::_shared_paths_misc_info = NULL;
 153 #endif
 154 
 155 // helper routines
 156 bool string_starts_with(const char* str, const char* str_to_find) {
 157   size_t str_len = strlen(str);
 158   size_t str_to_find_len = strlen(str_to_find);
 159   if (str_to_find_len > str_len) {
 160     return false;
 161   }
 162   return (strncmp(str, str_to_find, str_to_find_len) == 0);
 163 }
 164 
 165 static const char* get_jimage_version_string() {
 166   static char version_string[10] = "";
 167   if (version_string[0] == '\0') {
 168     jio_snprintf(version_string, sizeof(version_string), "%d.%d",
 169                  Abstract_VM_Version::vm_major_version(), Abstract_VM_Version::vm_minor_version());
 170   }
 171   return (const char*)version_string;
 172 }
 173 
 174 bool ClassLoader::string_ends_with(const char* str, const char* str_to_find) {
 175   size_t str_len = strlen(str);
 176   size_t str_to_find_len = strlen(str_to_find);
 177   if (str_to_find_len > str_len) {
 178     return false;
 179   }
 180   return (strncmp(str + (str_len - str_to_find_len), str_to_find, str_to_find_len) == 0);
 181 }
 182 
 183 // Used to obtain the package name from a fully qualified class name.
 184 // It is the responsibility of the caller to establish a ResourceMark.
 185 const char* ClassLoader::package_from_name(const char* const class_name, bool* bad_class_name) {
 186   if (class_name == NULL) {
 187     if (bad_class_name != NULL) {
 188       *bad_class_name = true;
 189     }
 190     return NULL;
 191   }
 192 
 193   if (bad_class_name != NULL) {
 194     *bad_class_name = false;
 195   }
 196 
 197   const char* const last_slash = strrchr(class_name, '/');
 198   if (last_slash == NULL) {
 199     // No package name
 200     return NULL;
 201   }
 202 
 203   char* class_name_ptr = (char*) class_name;
 204   // Skip over '['s
 205   if (*class_name_ptr == '[') {
 206     do {
 207       class_name_ptr++;
 208     } while (*class_name_ptr == '[');
 209 
 210     // Fully qualified class names should not contain a 'L'.
 211     // Set bad_class_name to true to indicate that the package name
 212     // could not be obtained due to an error condition.
 213     // In this situation, is_same_class_package returns false.
 214     if (*class_name_ptr == 'L') {
 215       if (bad_class_name != NULL) {
 216         *bad_class_name = true;
 217       }
 218       return NULL;
 219     }
 220   }
 221 
 222   int length = last_slash - class_name_ptr;
 223 
 224   // A class name could have just the slash character in the name.
 225   if (length <= 0) {
 226     // No package name
 227     if (bad_class_name != NULL) {
 228       *bad_class_name = true;
 229     }
 230     return NULL;
 231   }
 232 
 233   // drop name after last slash (including slash)
 234   // Ex., "java/lang/String.class" => "java/lang"
 235   char* pkg_name = NEW_RESOURCE_ARRAY(char, length + 1);
 236   strncpy(pkg_name, class_name_ptr, length);
 237   *(pkg_name+length) = '\0';
 238 
 239   return (const char *)pkg_name;
 240 }
 241 
 242 // Given a fully qualified class name, find its defining package in the class loader's
 243 // package entry table.
 244 static PackageEntry* get_package_entry(const char* class_name, ClassLoaderData* loader_data, TRAPS) {
 245   ResourceMark rm(THREAD);
 246   const char *pkg_name = ClassLoader::package_from_name(class_name);
 247   if (pkg_name == NULL) {
 248     return NULL;
 249   }
 250   PackageEntryTable* pkgEntryTable = loader_data->packages();
 251   TempNewSymbol pkg_symbol = SymbolTable::new_symbol(pkg_name, CHECK_NULL);
 252   return pkgEntryTable->lookup_only(pkg_symbol);
 253 }
 254 
 255 ClassPathDirEntry::ClassPathDirEntry(const char* dir) : ClassPathEntry() {
 256   char* copy = NEW_C_HEAP_ARRAY(char, strlen(dir)+1, mtClass);
 257   strcpy(copy, dir);
 258   _dir = copy;
 259 }
 260 
 261 
 262 ClassFileStream* ClassPathDirEntry::open_stream(const char* name, TRAPS) {
 263   // construct full path name
 264   char* path = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, JVM_MAXPATHLEN);
 265   if (jio_snprintf(path, JVM_MAXPATHLEN, "%s%s%s", _dir, os::file_separator(), name) == -1) {
 266     FREE_RESOURCE_ARRAY(char, path, JVM_MAXPATHLEN);
 267     return NULL;
 268   }
 269   // check if file exists
 270   struct stat st;
 271   if (os::stat(path, &st) == 0) {
 272 #if INCLUDE_CDS
 273     if (DumpSharedSpaces) {
 274       // We have already check in ClassLoader::check_shared_classpath() that the directory is empty, so
 275       // we should never find a file underneath it -- unless user has added a new file while we are running
 276       // the dump, in which case let's quit!
 277       ShouldNotReachHere();
 278     }
 279 #endif
 280     // found file, open it
 281     int file_handle = os::open(path, 0, 0);
 282     if (file_handle != -1) {
 283       // read contents into resource array
 284       u1* buffer = NEW_RESOURCE_ARRAY(u1, st.st_size);
 285       size_t num_read = os::read(file_handle, (char*) buffer, st.st_size);
 286       // close file
 287       os::close(file_handle);
 288       // construct ClassFileStream
 289       if (num_read == (size_t)st.st_size) {
 290         if (UsePerfData) {
 291           ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read);
 292         }
 293         FREE_RESOURCE_ARRAY(char, path, JVM_MAXPATHLEN);
 294         // Resource allocated
 295         return new ClassFileStream(buffer,
 296                                    st.st_size,
 297                                    _dir,
 298                                    ClassFileStream::verify);
 299       }
 300     }
 301   }
 302   FREE_RESOURCE_ARRAY(char, path, JVM_MAXPATHLEN);
 303   return NULL;
 304 }
 305 
 306 ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name, bool is_boot_append) : ClassPathEntry() {
 307   _zip = zip;
 308   char *copy = NEW_C_HEAP_ARRAY(char, strlen(zip_name)+1, mtClass);
 309   strcpy(copy, zip_name);
 310   _zip_name = copy;
 311   _is_boot_append = is_boot_append;
 312   _multi_versioned = _unknown;
 313 }
 314 
 315 ClassPathZipEntry::~ClassPathZipEntry() {
 316   if (ZipClose != NULL) {
 317     (*ZipClose)(_zip);
 318   }
 319   FREE_C_HEAP_ARRAY(char, _zip_name);
 320 }
 321 
 322 u1* ClassPathZipEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {
 323     // enable call to C land
 324   JavaThread* thread = JavaThread::current();
 325   ThreadToNativeFromVM ttn(thread);
 326   // check whether zip archive contains name
 327   jint name_len;
 328   jzentry* entry = (*FindEntry)(_zip, name, filesize, &name_len);
 329   if (entry == NULL) return NULL;
 330   u1* buffer;
 331   char name_buf[128];
 332   char* filename;
 333   if (name_len < 128) {
 334     filename = name_buf;
 335   } else {
 336     filename = NEW_RESOURCE_ARRAY(char, name_len + 1);
 337   }
 338 
 339   // file found, get pointer to the entry in mmapped jar file.
 340   if (ReadMappedEntry == NULL ||
 341       !(*ReadMappedEntry)(_zip, entry, &buffer, filename)) {
 342       // mmapped access not available, perhaps due to compression,
 343       // read contents into resource array
 344       int size = (*filesize) + ((nul_terminate) ? 1 : 0);
 345       buffer = NEW_RESOURCE_ARRAY(u1, size);
 346       if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL;
 347   }
 348 
 349   // return result
 350   if (nul_terminate) {
 351     buffer[*filesize] = 0;
 352   }
 353   return buffer;
 354 }
 355 
 356 #if INCLUDE_CDS
 357 u1* ClassPathZipEntry::open_versioned_entry(const char* name, jint* filesize, TRAPS) {
 358   u1* buffer = NULL;
 359   if (DumpSharedSpaces && !_is_boot_append) {
 360     // We presume default is multi-release enabled
 361     const char* multi_ver = Arguments::get_property("jdk.util.jar.enableMultiRelease");
 362     const char* verstr = Arguments::get_property("jdk.util.jar.version");
 363     bool is_multi_ver = (multi_ver == NULL ||
 364                          strcmp(multi_ver, "true") == 0 ||
 365                          strcmp(multi_ver, "force")  == 0) &&
 366                          is_multiple_versioned(THREAD);
 367     // command line version setting
 368     int version = 0;
 369     const int base_version = 8; // JDK8
 370     int cur_ver = JDK_Version::current().major_version();
 371     if (verstr != NULL) {
 372       version = atoi(verstr);
 373       if (version < base_version || version > cur_ver) {
 374         is_multi_ver = false;
 375         // print out warning, do not use assertion here since it will continue to look
 376         // for proper version.
 377         warning("JDK%d is not supported in multiple version jars", version);
 378       }
 379     }
 380 
 381     if (is_multi_ver) {
 382       int n;
 383       char* entry_name = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, JVM_MAXPATHLEN);
 384       if (version > 0) {
 385         n = jio_snprintf(entry_name, JVM_MAXPATHLEN, "META-INF/versions/%d/%s", version, name);
 386         entry_name[n] = '\0';
 387         buffer = open_entry((const char*)entry_name, filesize, false, CHECK_NULL);
 388         if (buffer == NULL) {
 389           warning("Could not find %s in %s, try to find highest version instead", entry_name, _zip_name);
 390         }
 391       }
 392       if (buffer == NULL) {
 393         for (int i = cur_ver; i >= base_version; i--) {
 394           n = jio_snprintf(entry_name, JVM_MAXPATHLEN, "META-INF/versions/%d/%s", i, name);
 395           entry_name[n] = '\0';
 396           buffer = open_entry((const char*)entry_name, filesize, false, CHECK_NULL);
 397           if (buffer != NULL) {
 398             break;
 399           }
 400         }
 401       }
 402       FREE_RESOURCE_ARRAY(char, entry_name, JVM_MAXPATHLEN);
 403     }
 404   }
 405   return buffer;
 406 }
 407 
 408 bool ClassPathZipEntry::is_multiple_versioned(TRAPS) {
 409   assert(DumpSharedSpaces, "called only at dump time");
 410   if (_multi_versioned != _unknown) {
 411     return (_multi_versioned == _yes) ? true : false;
 412   }
 413   jint size;
 414   char* buffer = (char*)open_entry("META-INF/MANIFEST.MF", &size, true, CHECK_false);
 415   if (buffer != NULL) {
 416     char* p = buffer;
 417     for ( ; *p; ++p) *p = tolower(*p);
 418     if (strstr(buffer, "multi-release: true") != NULL) {
 419       _multi_versioned = _yes;
 420       return true;
 421     }
 422   }
 423   _multi_versioned = _no;
 424   return false;
 425 }
 426 #endif // INCLUDE_CDS
 427 
 428 ClassFileStream* ClassPathZipEntry::open_stream(const char* name, TRAPS) {
 429   jint filesize;
 430   u1* buffer = open_versioned_entry(name, &filesize, CHECK_NULL);
 431   if (buffer == NULL) {
 432     buffer = open_entry(name, &filesize, false, CHECK_NULL);
 433     if (buffer == NULL) {
 434       return NULL;
 435     }
 436   }
 437   if (UsePerfData) {
 438     ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize);
 439   }
 440   // Resource allocated
 441   return new ClassFileStream(buffer,
 442                              filesize,
 443                              _zip_name,
 444                              ClassFileStream::verify);
 445 }
 446 
 447 // invoke function for each entry in the zip file
 448 void ClassPathZipEntry::contents_do(void f(const char* name, void* context), void* context) {
 449   JavaThread* thread = JavaThread::current();
 450   HandleMark  handle_mark(thread);
 451   ThreadToNativeFromVM ttn(thread);
 452   for (int n = 0; ; n++) {
 453     jzentry * ze = ((*GetNextEntry)(_zip, n));
 454     if (ze == NULL) break;
 455     (*f)(ze->name, context);
 456   }
 457 }
 458 
 459 ClassPathImageEntry::ClassPathImageEntry(JImageFile* jimage, const char* name) :
 460   ClassPathEntry(),
 461   _jimage(jimage) {
 462   guarantee(jimage != NULL, "jimage file is null");
 463   guarantee(name != NULL, "jimage file name is null");
 464   size_t len = strlen(name) + 1;
 465   _name = NEW_C_HEAP_ARRAY(const char, len, mtClass);
 466   strncpy((char *)_name, name, len);
 467 }
 468 
 469 ClassPathImageEntry::~ClassPathImageEntry() {
 470   if (_name != NULL) {
 471     FREE_C_HEAP_ARRAY(const char, _name);
 472     _name = NULL;
 473   }
 474   if (_jimage != NULL) {
 475     (*JImageClose)(_jimage);
 476     _jimage = NULL;
 477   }
 478 }
 479 
 480 // For a class in a named module, look it up in the jimage file using this syntax:
 481 //    /<module-name>/<package-name>/<base-class>
 482 //
 483 // Assumptions:
 484 //     1. There are no unnamed modules in the jimage file.
 485 //     2. A package is in at most one module in the jimage file.
 486 //
 487 ClassFileStream* ClassPathImageEntry::open_stream(const char* name, TRAPS) {
 488   jlong size;
 489   JImageLocationRef location = (*JImageFindResource)(_jimage, "", get_jimage_version_string(), name, &size);
 490 
 491   if (location == 0) {
 492     ResourceMark rm;
 493     const char* pkg_name = ClassLoader::package_from_name(name);
 494 
 495     if (pkg_name != NULL) {
 496       if (!Universe::is_module_initialized()) {
 497         location = (*JImageFindResource)(_jimage, "java.base", get_jimage_version_string(), name, &size);
 498 #if INCLUDE_CDS
 499         // CDS uses the boot class loader to load classes whose packages are in
 500         // modules defined for other class loaders.  So, for now, get their module
 501         // names from the "modules" jimage file.
 502         if (DumpSharedSpaces && location == 0) {
 503           const char* module_name = (*JImagePackageToModule)(_jimage, pkg_name);
 504           if (module_name != NULL) {
 505             location = (*JImageFindResource)(_jimage, module_name, get_jimage_version_string(), name, &size);
 506           }
 507         }
 508 #endif
 509 
 510       } else {
 511         PackageEntry* package_entry = get_package_entry(name, ClassLoaderData::the_null_class_loader_data(), CHECK_NULL);
 512         if (package_entry != NULL) {
 513           ResourceMark rm;
 514           // Get the module name
 515           ModuleEntry* module = package_entry->module();
 516           assert(module != NULL, "Boot classLoader package missing module");
 517           assert(module->is_named(), "Boot classLoader package is in unnamed module");
 518           const char* module_name = module->name()->as_C_string();
 519           if (module_name != NULL) {
 520             location = (*JImageFindResource)(_jimage, module_name, get_jimage_version_string(), name, &size);
 521           }
 522         }
 523       }
 524     }
 525   }
 526   if (location != 0) {
 527     if (UsePerfData) {
 528       ClassLoader::perf_sys_classfile_bytes_read()->inc(size);
 529     }
 530     char* data = NEW_RESOURCE_ARRAY(char, size);
 531     (*JImageGetResource)(_jimage, location, data, size);
 532     // Resource allocated
 533     return new ClassFileStream((u1*)data,
 534                                (int)size,
 535                                _name,
 536                                ClassFileStream::verify);
 537   }
 538 
 539   return NULL;
 540 }
 541 
 542 #ifndef PRODUCT
 543 bool ctw_visitor(JImageFile* jimage,
 544         const char* module_name, const char* version, const char* package,
 545         const char* name, const char* extension, void* arg) {
 546   if (strcmp(extension, "class") == 0) {
 547     Thread* THREAD = Thread::current();
 548     ResourceMark rm(THREAD);
 549     char* path = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, JIMAGE_MAX_PATH);
 550     jio_snprintf(path, JIMAGE_MAX_PATH - 1, "%s/%s.class", package, name);
 551     ClassLoader::compile_the_world_in(path, *(Handle*)arg, THREAD);
 552     return !HAS_PENDING_EXCEPTION;
 553   }
 554   return true;
 555 }
 556 
 557 void ClassPathImageEntry::compile_the_world(Handle loader, TRAPS) {
 558   tty->print_cr("CompileTheWorld : Compiling all classes in %s", name());
 559   tty->cr();
 560   (*JImageResourceIterator)(_jimage, (JImageResourceVisitor_t)ctw_visitor, (void *)&loader);
 561   if (HAS_PENDING_EXCEPTION) {
 562     if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
 563       CLEAR_PENDING_EXCEPTION;
 564       tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
 565       tty->print_cr("Increase class metadata storage if a limit was set");
 566     } else {
 567       tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
 568     }
 569   }
 570 }
 571 #endif
 572 
 573 bool ClassPathImageEntry::is_jrt() {
 574   return ClassLoader::is_jrt(name());
 575 }
 576 
 577 #if INCLUDE_CDS
 578 void ClassLoader::exit_with_path_failure(const char* error, const char* message) {
 579   assert(DumpSharedSpaces, "only called at dump time");
 580   tty->print_cr("Hint: enable -Xlog:class+path=info to diagnose the failure");
 581   vm_exit_during_initialization(error, message);
 582 }
 583 #endif
 584 
 585 ModuleClassPathList::ModuleClassPathList(Symbol* module_name) {
 586   _module_name = module_name;
 587   _module_first_entry = NULL;
 588   _module_last_entry = NULL;
 589 }
 590 
 591 ModuleClassPathList::~ModuleClassPathList() {
 592   // Clean out each ClassPathEntry on list
 593   ClassPathEntry* e = _module_first_entry;
 594   while (e != NULL) {
 595     ClassPathEntry* next_entry = e->next();
 596     delete e;
 597     e = next_entry;
 598   }
 599 }
 600 
 601 void ModuleClassPathList::add_to_list(ClassPathEntry* new_entry) {
 602   if (new_entry != NULL) {
 603     if (_module_last_entry == NULL) {
 604       _module_first_entry = _module_last_entry = new_entry;
 605     } else {
 606       _module_last_entry->set_next(new_entry);
 607       _module_last_entry = new_entry;
 608     }
 609   }
 610 }
 611 
 612 void ClassLoader::trace_class_path(const char* msg, const char* name) {
 613   if (log_is_enabled(Info, class, path)) {
 614     ResourceMark rm;
 615     outputStream* out = Log(class, path)::info_stream();
 616     if (msg) {
 617       out->print("%s", msg);
 618     }
 619     if (name) {
 620       if (strlen(name) < 256) {
 621         out->print("%s", name);
 622       } else {
 623         // For very long paths, we need to print each character separately,
 624         // as print_cr() has a length limit
 625         while (name[0] != '\0') {
 626           out->print("%c", name[0]);
 627           name++;
 628         }
 629       }
 630     }
 631     out->cr();
 632   }
 633 }
 634 
 635 #if INCLUDE_CDS
 636 void ClassLoader::check_shared_classpath(const char *path) {
 637   if (strcmp(path, "") == 0) {
 638     exit_with_path_failure("Cannot have empty path in archived classpaths", NULL);
 639   }
 640 
 641   struct stat st;
 642   if (os::stat(path, &st) == 0) {
 643     if ((st.st_mode & S_IFREG) != S_IFREG) { // is directory
 644       if (!os::dir_is_empty(path)) {
 645         tty->print_cr("Error: non-empty directory '%s'", path);
 646         exit_with_path_failure("CDS allows only empty directories in archived classpaths", NULL);
 647       }
 648     }
 649   }
 650 }
 651 #endif
 652 
 653 void ClassLoader::setup_bootstrap_search_path() {
 654   const char* sys_class_path = Arguments::get_sysclasspath();
 655   const char* java_class_path = Arguments::get_appclasspath();
 656   if (PrintSharedArchiveAndExit) {
 657     // Don't print sys_class_path - this is the bootcp of this current VM process, not necessarily
 658     // the same as the bootcp of the shared archive.
 659   } else {
 660     trace_class_path("bootstrap loader class path=", sys_class_path);
 661     trace_class_path("classpath: ", java_class_path);
 662   }
 663 #if INCLUDE_CDS
 664   if (DumpSharedSpaces) {
 665     _shared_paths_misc_info->add_boot_classpath(sys_class_path);
 666   }
 667 #endif
 668   setup_search_path(sys_class_path, true);
 669 }
 670 
 671 #if INCLUDE_CDS
 672 int ClassLoader::get_shared_paths_misc_info_size() {
 673   return _shared_paths_misc_info->get_used_bytes();
 674 }
 675 
 676 void* ClassLoader::get_shared_paths_misc_info() {
 677   return _shared_paths_misc_info->buffer();
 678 }
 679 
 680 bool ClassLoader::check_shared_paths_misc_info(void *buf, int size) {
 681   SharedPathsMiscInfo* checker = SharedClassUtil::allocate_shared_paths_misc_info((char*)buf, size);
 682   bool result = checker->check();
 683   delete checker;
 684   return result;
 685 }
 686 #endif
 687 
 688 // Construct the array of module/path pairs as specified to --patch-module
 689 // for the boot loader to search ahead of the jimage, if the class being
 690 // loaded is defined to a module that has been specified to --patch-module.
 691 void ClassLoader::setup_patch_mod_entries() {
 692   Thread* THREAD = Thread::current();
 693   GrowableArray<ModulePatchPath*>* patch_mod_args = Arguments::get_patch_mod_prefix();
 694   int num_of_entries = patch_mod_args->length();
 695 
 696   assert(!DumpSharedSpaces, "DumpSharedSpaces not supported with --patch-module");
 697   assert(!UseSharedSpaces, "UseSharedSpaces not supported with --patch-module");
 698 
 699   // Set up the boot loader's _patch_mod_entries list
 700   _patch_mod_entries = new (ResourceObj::C_HEAP, mtModule) GrowableArray<ModuleClassPathList*>(num_of_entries, true);
 701 
 702   for (int i = 0; i < num_of_entries; i++) {
 703     const char* module_name = (patch_mod_args->at(i))->module_name();
 704     Symbol* const module_sym = SymbolTable::lookup(module_name, (int)strlen(module_name), CHECK);
 705     assert(module_sym != NULL, "Failed to obtain Symbol for module name");
 706     ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym);
 707 
 708     char* class_path = (patch_mod_args->at(i))->path_string();
 709     int len = (int)strlen(class_path);
 710     int end = 0;
 711     // Iterate over the module's class path entries
 712     for (int start = 0; start < len; start = end) {
 713       while (class_path[end] && class_path[end] != os::path_separator()[0]) {
 714         end++;
 715       }
 716       EXCEPTION_MARK;
 717       ResourceMark rm(THREAD);
 718       char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);
 719       strncpy(path, &class_path[start], end - start);
 720       path[end - start] = '\0';
 721 
 722       struct stat st;
 723       if (os::stat(path, &st) == 0) {
 724         // File or directory found
 725         Thread* THREAD = Thread::current();
 726         ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK);
 727         // If the path specification is valid, enter it into this module's list
 728         if (new_entry != NULL) {
 729           module_cpl->add_to_list(new_entry);
 730         }
 731       }
 732 
 733       while (class_path[end] == os::path_separator()[0]) {
 734         end++;
 735       }
 736     }
 737 
 738     // Record the module into the list of --patch-module entries only if
 739     // valid ClassPathEntrys have been created
 740     if (module_cpl->module_first_entry() != NULL) {
 741       _patch_mod_entries->push(module_cpl);
 742     }
 743   }
 744 }
 745 
 746 void ClassLoader::setup_search_path(const char *class_path, bool bootstrap_search) {
 747   int len = (int)strlen(class_path);
 748   int end = 0;
 749   bool set_base_piece = bootstrap_search;
 750 
 751   // Iterate over class path entries
 752   for (int start = 0; start < len; start = end) {
 753     while (class_path[end] && class_path[end] != os::path_separator()[0]) {
 754       end++;
 755     }
 756     EXCEPTION_MARK;
 757     ResourceMark rm(THREAD);
 758     char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);
 759     strncpy(path, &class_path[start], end - start);
 760     path[end - start] = '\0';
 761 
 762     // The first time through the bootstrap_search setup, it must be determined
 763     // what the base or core piece of the boot loader search is.  Either a java runtime
 764     // image is present or this is an exploded module build situation.
 765     if (set_base_piece) {
 766       assert(string_ends_with(path, MODULES_IMAGE_NAME) || string_ends_with(path, "java.base"),
 767              "Incorrect boot loader search path, no java runtime image or java.base exploded build");
 768       struct stat st;
 769       if (os::stat(path, &st) == 0) {
 770         // Directory found
 771         Thread* THREAD = Thread::current();
 772         ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK);
 773 
 774         // Check for a jimage
 775         if (Arguments::has_jimage()) {
 776           assert(_jrt_entry == NULL, "should not setup bootstrap class search path twice");
 777           assert(new_entry != NULL && new_entry->is_jrt(), "No java runtime image present");
 778           _jrt_entry = new_entry;
 779           ++_num_entries;
 780 #if INCLUDE_CDS
 781           if (DumpSharedSpaces) {
 782             JImageFile *jimage = _jrt_entry->jimage();
 783             assert(jimage != NULL, "No java runtime image file present");
 784             ClassLoader::initialize_module_loader_map(jimage);
 785           }
 786 #endif
 787         }
 788       } else {
 789         // If path does not exist, exit
 790         vm_exit_during_initialization("Unable to establish the boot loader search path", path);
 791       }
 792       set_base_piece = false;
 793     } else {
 794       // Every entry on the system boot class path after the initial base piece,
 795       // which is set by os::set_boot_path(), is considered an appended entry.
 796       update_class_path_entry_list(path, false, bootstrap_search);
 797     }
 798 
 799 #if INCLUDE_CDS
 800     if (DumpSharedSpaces) {
 801       check_shared_classpath(path);
 802     }
 803 #endif
 804     while (class_path[end] == os::path_separator()[0]) {
 805       end++;
 806     }
 807   }
 808 }
 809 
 810 // During an exploded modules build, each module defined to the boot loader
 811 // will be added to the ClassLoader::_exploded_entries array.
 812 void ClassLoader::add_to_exploded_build_list(Symbol* module_sym, TRAPS) {
 813   assert(!ClassLoader::has_jrt_entry(), "Exploded build not applicable");
 814 
 815   // Set up the boot loader's _exploded_entries list
 816   if (_exploded_entries == NULL) {
 817     _exploded_entries = new (ResourceObj::C_HEAP, mtModule) GrowableArray<ModuleClassPathList*>(EXPLODED_ENTRY_SIZE, true);
 818   }
 819 
 820   // Find the module's symbol
 821   ResourceMark rm(THREAD);
 822   const char *module_name = module_sym->as_C_string();
 823   const char *home = Arguments::get_java_home();
 824   const char file_sep = os::file_separator()[0];
 825   // 10 represents the length of "modules" + 2 file separators + \0
 826   size_t len = strlen(home) + strlen(module_name) + 10;
 827   char *path = NEW_C_HEAP_ARRAY(char, len, mtModule);
 828   jio_snprintf(path, len, "%s%cmodules%c%s", home, file_sep, file_sep, module_name);
 829 
 830   struct stat st;
 831   if (os::stat(path, &st) == 0) {
 832     // Directory found
 833     ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK);
 834 
 835     // If the path specification is valid, enter it into this module's list.
 836     // There is no need to check for duplicate modules in the exploded entry list,
 837     // since no two modules with the same name can be defined to the boot loader.
 838     // This is checked at module definition time in Modules::define_module.
 839     if (new_entry != NULL) {
 840       ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym);
 841       module_cpl->add_to_list(new_entry);
 842       _exploded_entries->push(module_cpl);
 843       log_info(class, load)("path: %s", path);
 844     }
 845   }
 846   FREE_C_HEAP_ARRAY(char, path);
 847 }
 848 
 849 ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st,
 850                                                      bool throw_exception,
 851                                                      bool is_boot_append, TRAPS) {
 852   JavaThread* thread = JavaThread::current();
 853   ClassPathEntry* new_entry = NULL;
 854   if ((st->st_mode & S_IFREG) == S_IFREG) {
 855     ResourceMark rm(thread);
 856     // Regular file, should be a zip or jimage file
 857     // Canonicalized filename
 858     char* canonical_path = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, JVM_MAXPATHLEN);
 859     if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
 860       // This matches the classic VM
 861       if (throw_exception) {
 862         THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL);
 863       } else {
 864         return NULL;
 865       }
 866     }
 867     jint error;
 868     JImageFile* jimage =(*JImageOpen)(canonical_path, &error);
 869     if (jimage != NULL) {
 870       new_entry = new ClassPathImageEntry(jimage, canonical_path);
 871     } else {
 872       char* error_msg = NULL;
 873       jzfile* zip;
 874       {
 875         // enable call to C land
 876         ThreadToNativeFromVM ttn(thread);
 877         HandleMark hm(thread);
 878         zip = (*ZipOpen)(canonical_path, &error_msg);
 879       }
 880       if (zip != NULL && error_msg == NULL) {
 881         new_entry = new ClassPathZipEntry(zip, path, is_boot_append);
 882       } else {
 883         char *msg;
 884         if (error_msg == NULL) {
 885           msg = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, strlen(path) + 128); ;
 886           jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
 887         } else {
 888           int len = (int)(strlen(path) + strlen(error_msg) + 128);
 889           msg = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, len); ;
 890           jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path);
 891         }
 892         // Don't complain about bad jar files added via -Xbootclasspath/a:.
 893         if (throw_exception && is_init_completed()) {
 894           THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL);
 895         } else {
 896           return NULL;
 897         }
 898       }
 899     }
 900     log_info(class, path)("opened: %s", path);
 901     log_info(class, load)("opened: %s", path);
 902   } else {
 903     // Directory
 904     new_entry = new ClassPathDirEntry(path);
 905     log_info(class, load)("path: %s", path);
 906   }
 907   return new_entry;
 908 }
 909 
 910 
 911 // Create a class path zip entry for a given path (return NULL if not found
 912 // or zip/JAR file cannot be opened)
 913 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path, bool is_boot_append) {
 914   // check for a regular file
 915   struct stat st;
 916   if (os::stat(path, &st) == 0) {
 917     if ((st.st_mode & S_IFREG) == S_IFREG) {
 918       char canonical_path[JVM_MAXPATHLEN];
 919       if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
 920         char* error_msg = NULL;
 921         jzfile* zip;
 922         {
 923           // enable call to C land
 924           JavaThread* thread = JavaThread::current();
 925           ThreadToNativeFromVM ttn(thread);
 926           HandleMark hm(thread);
 927           zip = (*ZipOpen)(canonical_path, &error_msg);
 928         }
 929         if (zip != NULL && error_msg == NULL) {
 930           // create using canonical path
 931           return new ClassPathZipEntry(zip, canonical_path, is_boot_append);
 932         }
 933       }
 934     }
 935   }
 936   return NULL;
 937 }
 938 
 939 // returns true if entry already on class path
 940 bool ClassLoader::contains_entry(ClassPathEntry *entry) {
 941   ClassPathEntry* e = _first_append_entry;
 942   while (e != NULL) {
 943     // assume zip entries have been canonicalized
 944     if (strcmp(entry->name(), e->name()) == 0) {
 945       return true;
 946     }
 947     e = e->next();
 948   }
 949   return false;
 950 }
 951 
 952 void ClassLoader::add_to_list(ClassPathEntry *new_entry) {
 953   if (new_entry != NULL) {
 954     if (_last_append_entry == NULL) {
 955       assert(_first_append_entry == NULL, "boot loader's append class path entry list not empty");
 956       _first_append_entry = _last_append_entry = new_entry;
 957     } else {
 958       _last_append_entry->set_next(new_entry);
 959       _last_append_entry = new_entry;
 960     }
 961   }
 962   _num_entries++;
 963 }
 964 
 965 void ClassLoader::add_to_list(const char *apath) {
 966   update_class_path_entry_list((char*)apath, false, false);
 967 }
 968 
 969 // Returns true IFF the file/dir exists and the entry was successfully created.
 970 bool ClassLoader::update_class_path_entry_list(const char *path,
 971                                                bool check_for_duplicates,
 972                                                bool is_boot_append,
 973                                                bool throw_exception) {
 974   struct stat st;
 975   if (os::stat(path, &st) == 0) {
 976     // File or directory found
 977     ClassPathEntry* new_entry = NULL;
 978     Thread* THREAD = Thread::current();
 979     new_entry = create_class_path_entry(path, &st, throw_exception, is_boot_append, CHECK_(false));
 980     if (new_entry == NULL) {
 981       return false;
 982     }
 983 
 984     // Do not reorder the bootclasspath which would break get_system_package().
 985     // Add new entry to linked list
 986     if (!check_for_duplicates || !contains_entry(new_entry)) {
 987       ClassLoaderExt::add_class_path_entry(path, check_for_duplicates, new_entry);
 988     }
 989     return true;
 990   } else {
 991 #if INCLUDE_CDS
 992     if (DumpSharedSpaces) {
 993       _shared_paths_misc_info->add_nonexist_path(path);
 994     }
 995 #endif
 996     return false;
 997   }
 998 }
 999 
1000 static void print_module_entry_table(const GrowableArray<ModuleClassPathList*>* const module_list) {
1001   ResourceMark rm;
1002   int num_of_entries = module_list->length();
1003   for (int i = 0; i < num_of_entries; i++) {
1004     ClassPathEntry* e;
1005     ModuleClassPathList* mpl = module_list->at(i);
1006     tty->print("%s=", mpl->module_name()->as_C_string());
1007     e = mpl->module_first_entry();
1008     while (e != NULL) {
1009       tty->print("%s", e->name());
1010       e = e->next();
1011       if (e != NULL) {
1012         tty->print("%s", os::path_separator());
1013       }
1014     }
1015     tty->print(" ;");
1016   }
1017 }
1018 
1019 void ClassLoader::print_bootclasspath() {
1020   ClassPathEntry* e;
1021   tty->print("[bootclasspath= ");
1022 
1023   // Print --patch-module module/path specifications first
1024   if (_patch_mod_entries != NULL) {
1025     print_module_entry_table(_patch_mod_entries);
1026   }
1027 
1028   // [jimage | exploded modules build]
1029   if (has_jrt_entry()) {
1030     // Print the location of the java runtime image
1031     tty->print("%s ;", _jrt_entry->name());
1032   } else {
1033     // Print exploded module build path specifications
1034     if (_exploded_entries != NULL) {
1035       print_module_entry_table(_exploded_entries);
1036     }
1037   }
1038 
1039   // appended entries
1040   e = _first_append_entry;
1041   while (e != NULL) {
1042     tty->print("%s ;", e->name());
1043     e = e->next();
1044   }
1045   tty->print_cr("]");
1046 }
1047 
1048 void ClassLoader::load_zip_library() {
1049   assert(ZipOpen == NULL, "should not load zip library twice");
1050   // First make sure native library is loaded
1051   os::native_java_library();
1052   // Load zip library
1053   char path[JVM_MAXPATHLEN];
1054   char ebuf[1024];
1055   void* handle = NULL;
1056   if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {
1057     handle = os::dll_load(path, ebuf, sizeof ebuf);
1058   }
1059   if (handle == NULL) {
1060     vm_exit_during_initialization("Unable to load ZIP library", path);
1061   }
1062   // Lookup zip entry points
1063   ZipOpen      = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));
1064   ZipClose     = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));
1065   FindEntry    = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));
1066   ReadEntry    = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
1067   ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));
1068   GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));
1069   ZipInflateFully = CAST_TO_FN_PTR(ZipInflateFully_t, os::dll_lookup(handle, "ZIP_InflateFully"));
1070   Crc32        = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));
1071 
1072   // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
1073   if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||
1074       GetNextEntry == NULL || Crc32 == NULL) {
1075     vm_exit_during_initialization("Corrupted ZIP library", path);
1076   }
1077 
1078   if (ZipInflateFully == NULL) {
1079     vm_exit_during_initialization("Corrupted ZIP library ZIP_InflateFully missing", path);
1080   }
1081 
1082   // Lookup canonicalize entry in libjava.dll
1083   void *javalib_handle = os::native_java_library();
1084   CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));
1085   // This lookup only works on 1.3. Do not check for non-null here
1086 }
1087 
1088 void ClassLoader::load_jimage_library() {
1089   // First make sure native library is loaded
1090   os::native_java_library();
1091   // Load jimage library
1092   char path[JVM_MAXPATHLEN];
1093   char ebuf[1024];
1094   void* handle = NULL;
1095   if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "jimage")) {
1096     handle = os::dll_load(path, ebuf, sizeof ebuf);
1097   }
1098   if (handle == NULL) {
1099     vm_exit_during_initialization("Unable to load jimage library", path);
1100   }
1101 
1102   // Lookup jimage entry points
1103   JImageOpen = CAST_TO_FN_PTR(JImageOpen_t, os::dll_lookup(handle, "JIMAGE_Open"));
1104   guarantee(JImageOpen != NULL, "function JIMAGE_Open not found");
1105   JImageClose = CAST_TO_FN_PTR(JImageClose_t, os::dll_lookup(handle, "JIMAGE_Close"));
1106   guarantee(JImageClose != NULL, "function JIMAGE_Close not found");
1107   JImagePackageToModule = CAST_TO_FN_PTR(JImagePackageToModule_t, os::dll_lookup(handle, "JIMAGE_PackageToModule"));
1108   guarantee(JImagePackageToModule != NULL, "function JIMAGE_PackageToModule not found");
1109   JImageFindResource = CAST_TO_FN_PTR(JImageFindResource_t, os::dll_lookup(handle, "JIMAGE_FindResource"));
1110   guarantee(JImageFindResource != NULL, "function JIMAGE_FindResource not found");
1111   JImageGetResource = CAST_TO_FN_PTR(JImageGetResource_t, os::dll_lookup(handle, "JIMAGE_GetResource"));
1112   guarantee(JImageGetResource != NULL, "function JIMAGE_GetResource not found");
1113   JImageResourceIterator = CAST_TO_FN_PTR(JImageResourceIterator_t, os::dll_lookup(handle, "JIMAGE_ResourceIterator"));
1114   guarantee(JImageResourceIterator != NULL, "function JIMAGE_ResourceIterator not found");
1115   JImageResourcePath = CAST_TO_FN_PTR(JImage_ResourcePath_t, os::dll_lookup(handle, "JIMAGE_ResourcePath"));
1116   guarantee(JImageResourcePath != NULL, "function JIMAGE_ResourcePath not found");
1117 }
1118 
1119 jboolean ClassLoader::decompress(void *in, u8 inSize, void *out, u8 outSize, char **pmsg) {
1120   return (*ZipInflateFully)(in, inSize, out, outSize, pmsg);
1121 }
1122 
1123 int ClassLoader::crc32(int crc, const char* buf, int len) {
1124   assert(Crc32 != NULL, "ZIP_CRC32 is not found");
1125   return (*Crc32)(crc, (const jbyte*)buf, len);
1126 }
1127 
1128 #if INCLUDE_CDS
1129 void ClassLoader::initialize_module_loader_map(JImageFile* jimage) {
1130   if (!DumpSharedSpaces) {
1131     return; // only needed for CDS dump time
1132   }
1133 
1134   ResourceMark rm;
1135   jlong size;
1136   JImageLocationRef location = (*JImageFindResource)(jimage, "java.base", get_jimage_version_string(), MODULE_LOADER_MAP, &size);
1137   if (location == 0) {
1138     vm_exit_during_initialization(
1139       "Cannot find ModuleLoaderMap location from modules jimage.", NULL);
1140   }
1141   char* buffer = NEW_RESOURCE_ARRAY(char, size + 1);
1142   buffer[size] = '\0';
1143   jlong read = (*JImageGetResource)(jimage, location, buffer, size);
1144   if (read != size) {
1145     vm_exit_during_initialization(
1146       "Cannot find ModuleLoaderMap resource from modules jimage.", NULL);
1147   }
1148   char* char_buf = (char*)buffer;
1149   int buflen = (int)strlen(char_buf);
1150   char* begin_ptr = char_buf;
1151   char* end_ptr = strchr(begin_ptr, '\n');
1152   bool process_boot_modules = false;
1153   _boot_modules_array = new (ResourceObj::C_HEAP, mtModule)
1154     GrowableArray<char*>(INITIAL_BOOT_MODULES_ARRAY_SIZE, true);
1155   _platform_modules_array = new (ResourceObj::C_HEAP, mtModule)
1156     GrowableArray<char*>(INITIAL_PLATFORM_MODULES_ARRAY_SIZE, true);
1157   while (end_ptr != NULL && (end_ptr - char_buf) < buflen) {
1158     // Allocate a buffer from the C heap to be appended to the _boot_modules_array
1159     // or the _platform_modules_array.
1160     char* temp_name = NEW_C_HEAP_ARRAY(char, (size_t)(end_ptr - begin_ptr + 1), mtInternal);
1161     strncpy(temp_name, begin_ptr, end_ptr - begin_ptr);
1162     temp_name[end_ptr - begin_ptr] = '\0';
1163     if (strncmp(temp_name, "BOOT", 4) == 0) {
1164       process_boot_modules = true;
1165       FREE_C_HEAP_ARRAY(char, temp_name);
1166     } else if (strncmp(temp_name, "PLATFORM", 8) == 0) {
1167       process_boot_modules = false;
1168       FREE_C_HEAP_ARRAY(char, temp_name);
1169     } else {
1170       // module name
1171       if (process_boot_modules) {
1172         _boot_modules_array->append(temp_name);
1173       } else {
1174         _platform_modules_array->append(temp_name);
1175       }
1176     }
1177     begin_ptr = ++end_ptr;
1178     end_ptr = strchr(begin_ptr, '\n');
1179   }
1180 }
1181 #endif
1182 
1183 // Function add_package extracts the package from the fully qualified class name
1184 // and checks if the package is in the boot loader's package entry table.  If so,
1185 // then it sets the classpath_index in the package entry record.
1186 //
1187 // The classpath_index field is used to find the entry on the boot loader class
1188 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a
1189 // in an unnamed module.  It is also used to indicate (for all packages whose
1190 // classes are loaded by the boot loader) that at least one of the package's
1191 // classes has been loaded.
1192 bool ClassLoader::add_package(const char *fullq_class_name, s2 classpath_index, TRAPS) {
1193   assert(fullq_class_name != NULL, "just checking");
1194 
1195   // Get package name from fully qualified class name.
1196   ResourceMark rm;
1197   const char *cp = package_from_name(fullq_class_name);
1198   if (cp != NULL) {
1199     PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();
1200     TempNewSymbol pkg_symbol = SymbolTable::new_symbol(cp, CHECK_false);
1201     PackageEntry* pkg_entry = pkg_entry_tbl->lookup_only(pkg_symbol);
1202     if (pkg_entry != NULL) {
1203       assert(classpath_index != -1, "Unexpected classpath_index");
1204       pkg_entry->set_classpath_index(classpath_index);
1205     } else {
1206       return false;
1207     }
1208   }
1209   return true;
1210 }
1211 
1212 oop ClassLoader::get_system_package(const char* name, TRAPS) {
1213   // Look up the name in the boot loader's package entry table.
1214   if (name != NULL) {
1215     TempNewSymbol package_sym = SymbolTable::new_symbol(name, (int)strlen(name), CHECK_NULL);
1216     // Look for the package entry in the boot loader's package entry table.
1217     PackageEntry* package =
1218       ClassLoaderData::the_null_class_loader_data()->packages()->lookup_only(package_sym);
1219 
1220     // Return NULL if package does not exist or if no classes in that package
1221     // have been loaded.
1222     if (package != NULL && package->has_loaded_class()) {
1223       ModuleEntry* module = package->module();
1224       if (module->location() != NULL) {
1225         ResourceMark rm(THREAD);
1226         Handle ml = java_lang_String::create_from_str(
1227           module->location()->as_C_string(), THREAD);
1228         return ml();
1229       }
1230       // Return entry on boot loader class path.
1231       Handle cph = java_lang_String::create_from_str(
1232         ClassLoader::classpath_entry(package->classpath_index())->name(), THREAD);
1233       return cph();
1234     }
1235   }
1236   return NULL;
1237 }
1238 
1239 objArrayOop ClassLoader::get_system_packages(TRAPS) {
1240   ResourceMark rm(THREAD);
1241   // List of pointers to PackageEntrys that have loaded classes.
1242   GrowableArray<PackageEntry*>* loaded_class_pkgs = new GrowableArray<PackageEntry*>(50);
1243   {
1244     MutexLocker ml(Module_lock, THREAD);
1245 
1246     PackageEntryTable* pe_table =
1247       ClassLoaderData::the_null_class_loader_data()->packages();
1248 
1249     // Collect the packages that have at least one loaded class.
1250     for (int x = 0; x < pe_table->table_size(); x++) {
1251       for (PackageEntry* package_entry = pe_table->bucket(x);
1252            package_entry != NULL;
1253            package_entry = package_entry->next()) {
1254         if (package_entry->has_loaded_class()) {
1255           loaded_class_pkgs->append(package_entry);
1256         }
1257       }
1258     }
1259   }
1260 
1261 
1262   // Allocate objArray and fill with java.lang.String
1263   objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
1264                                            loaded_class_pkgs->length(), CHECK_NULL);
1265   objArrayHandle result(THREAD, r);
1266   for (int x = 0; x < loaded_class_pkgs->length(); x++) {
1267     PackageEntry* package_entry = loaded_class_pkgs->at(x);
1268     Handle str = java_lang_String::create_from_symbol(package_entry->name(), CHECK_NULL);
1269     result->obj_at_put(x, str());
1270   }
1271   return result();
1272 }
1273 
1274 #if INCLUDE_CDS
1275 s2 ClassLoader::module_to_classloader(const char* module_name) {
1276 
1277   assert(DumpSharedSpaces, "dump time only");
1278   assert(_boot_modules_array != NULL, "_boot_modules_array is NULL");
1279   assert(_platform_modules_array != NULL, "_platform_modules_array is NULL");
1280 
1281   int array_size = _boot_modules_array->length();
1282   for (int i = 0; i < array_size; i++) {
1283     if (strcmp(module_name, _boot_modules_array->at(i)) == 0) {
1284       return BOOT_LOADER;
1285     }
1286   }
1287 
1288   array_size = _platform_modules_array->length();
1289   for (int i = 0; i < array_size; i++) {
1290     if (strcmp(module_name, _platform_modules_array->at(i)) == 0) {
1291       return PLATFORM_LOADER;
1292     }
1293   }
1294 
1295   return APP_LOADER;
1296 }
1297 
1298 s2 ClassLoader::classloader_type(Symbol* class_name, ClassPathEntry* e, int classpath_index, TRAPS) {
1299   assert(DumpSharedSpaces, "Only used for CDS dump time");
1300 
1301   // obtain the classloader type based on the class name.
1302   // First obtain the package name based on the class name. Then obtain
1303   // the classloader type based on the package name from the jimage using
1304   // a jimage API. If the classloader type cannot be found from the
1305   // jimage, it is determined by the class path entry.
1306   jshort loader_type = ClassLoader::APP_LOADER;
1307   if (e->is_jrt()) {
1308     ResourceMark rm;
1309     TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_0);
1310     if (pkg_name != NULL) {
1311       const char* pkg_name_C_string = (const char*)(pkg_name->as_C_string());
1312       ClassPathImageEntry* cpie = (ClassPathImageEntry*)e;
1313       JImageFile* jimage = cpie->jimage();
1314       char* module_name = (char*)(*JImagePackageToModule)(jimage, pkg_name_C_string);
1315       if (module_name != NULL) {
1316         loader_type = ClassLoader::module_to_classloader(module_name);
1317       }
1318     }
1319   } else if (ClassLoaderExt::is_boot_classpath(classpath_index)) {
1320     loader_type = ClassLoader::BOOT_LOADER;
1321   }
1322   return loader_type;
1323 }
1324 #endif
1325 
1326 // caller needs ResourceMark
1327 const char* ClassLoader::file_name_for_class_name(const char* class_name,
1328                                                   int class_name_len) {
1329   assert(class_name != NULL, "invariant");
1330   assert((int)strlen(class_name) == class_name_len, "invariant");
1331 
1332   static const char class_suffix[] = ".class";
1333 
1334   char* const file_name = NEW_RESOURCE_ARRAY(char,
1335                                              class_name_len +
1336                                              sizeof(class_suffix)); // includes term NULL
1337 
1338   strncpy(file_name, class_name, class_name_len);
1339   strncpy(&file_name[class_name_len], class_suffix, sizeof(class_suffix));
1340 
1341   return file_name;
1342 }
1343 
1344 // Search either the patch-module or exploded build entries for class
1345 ClassFileStream* ClassLoader::search_module_entries(const GrowableArray<ModuleClassPathList*>* const module_list,
1346                                                     const char* const class_name, const char* const file_name, TRAPS) {
1347   ClassFileStream* stream = NULL;
1348 
1349   // Find the class' defining module in the boot loader's module entry table
1350   PackageEntry* pkg_entry = get_package_entry(class_name, ClassLoaderData::the_null_class_loader_data(), CHECK_NULL);
1351   ModuleEntry* mod_entry = (pkg_entry != NULL) ? pkg_entry->module() : NULL;
1352 
1353   // If the module system has not defined java.base yet, then
1354   // classes loaded are assumed to be defined to java.base.
1355   // When java.base is eventually defined by the module system,
1356   // all packages of classes that have been previously loaded
1357   // are verified in ModuleEntryTable::verify_javabase_packages().
1358   if (!Universe::is_module_initialized() &&
1359       !ModuleEntryTable::javabase_defined() &&
1360       mod_entry == NULL) {
1361     mod_entry = ModuleEntryTable::javabase_module();
1362   }
1363 
1364   // The module must be a named module
1365   if (mod_entry != NULL && mod_entry->is_named()) {
1366     int num_of_entries = module_list->length();
1367     const Symbol* class_module_name = mod_entry->name();
1368 
1369     // Loop through all the modules in either the patch-module or exploded entries looking for module
1370     for (int i = 0; i < num_of_entries; i++) {
1371       ModuleClassPathList* module_cpl = module_list->at(i);
1372       Symbol* module_cpl_name = module_cpl->module_name();
1373 
1374       if (module_cpl_name->fast_compare(class_module_name) == 0) {
1375         // Class' module has been located, attempt to load
1376         // the class from the module's ClassPathEntry list.
1377         ClassPathEntry* e = module_cpl->module_first_entry();
1378         while (e != NULL) {
1379           stream = e->open_stream(file_name, CHECK_NULL);
1380           // No context.check is required since CDS is not supported
1381           // for an exploded modules build or if --patch-module is specified.
1382           if (NULL != stream) {
1383             return stream;
1384           }
1385           e = e->next();
1386         }
1387         // If the module was located, break out even if the class was not
1388         // located successfully from that module's ClassPathEntry list.
1389         // There will not be another valid entry for that module.
1390         return NULL;
1391       }
1392     }
1393   }
1394 
1395   return NULL;
1396 }
1397 
1398 instanceKlassHandle ClassLoader::load_class(Symbol* name, bool search_append_only, TRAPS) {
1399   assert(name != NULL, "invariant");
1400   assert(THREAD->is_Java_thread(), "must be a JavaThread");
1401 
1402   ResourceMark rm(THREAD);
1403   HandleMark hm(THREAD);
1404 
1405   const char* const class_name = name->as_C_string();
1406 
1407   EventMark m("loading class %s", class_name);
1408   ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion);
1409 
1410   const char* const file_name = file_name_for_class_name(class_name,
1411                                                          name->utf8_length());
1412   assert(file_name != NULL, "invariant");
1413 
1414   ClassLoaderExt::Context context(class_name, file_name, THREAD);
1415 
1416   // Lookup stream for parsing .class file
1417   ClassFileStream* stream = NULL;
1418   s2 classpath_index = 0;
1419   ClassPathEntry* e = NULL;
1420 
1421   // If DumpSharedSpaces is true boot loader visibility boundaries are set to:
1422   //   - [jimage] + [_first_append_entry to _last_append_entry] (all path entries).
1423   // No --patch-module entries or exploded module builds are included since CDS
1424   // is not supported if --patch-module or exploded module builds are used.
1425   //
1426   // If search_append_only is true, boot loader visibility boundaries are
1427   // set to be _first_append_entry to the end. This includes:
1428   //   [-Xbootclasspath/a]; [jvmti appended entries]
1429   //
1430   // If both DumpSharedSpaces and search_append_only are false, boot loader
1431   // visibility boundaries are set to be the --patch-module entries plus the base piece.
1432   // This would include:
1433   //   [--patch-module=<module>=<file>(<pathsep><file>)*]; [jimage | exploded module build]
1434   //
1435   // DumpSharedSpaces and search_append_only are mutually exclusive and cannot
1436   // be true at the same time.
1437   assert(!(DumpSharedSpaces && search_append_only), "DumpSharedSpaces and search_append_only are both true");
1438 
1439   // Load Attempt #1: --patch-module
1440   // Determine the class' defining module.  If it appears in the _patch_mod_entries,
1441   // attempt to load the class from those locations specific to the module.
1442   // Specifications to --patch-module can contain a partial number of classes
1443   // that are part of the overall module definition.  So if a particular class is not
1444   // found within its module specification, the search should continue to Load Attempt #2.
1445   // Note: The --patch-module entries are never searched if the boot loader's
1446   //       visibility boundary is limited to only searching the append entries.
1447   if (_patch_mod_entries != NULL && !search_append_only && !DumpSharedSpaces) {
1448     stream = search_module_entries(_patch_mod_entries, class_name, file_name, CHECK_NULL);
1449   }
1450 
1451   // Load Attempt #2: [jimage | exploded build]
1452   if (!search_append_only && (NULL == stream)) {
1453     if (has_jrt_entry()) {
1454       e = _jrt_entry;
1455       stream = _jrt_entry->open_stream(file_name, CHECK_NULL);
1456       if (!context.check(stream, classpath_index)) {
1457         return NULL;
1458       }
1459     } else {
1460       // Exploded build - attempt to locate class in its defining module's location.
1461       assert(_exploded_entries != NULL, "No exploded build entries present");
1462       stream = search_module_entries(_exploded_entries, class_name, file_name, CHECK_NULL);
1463     }
1464   }
1465 
1466   // Load Attempt #3: [-Xbootclasspath/a]; [jvmti appended entries]
1467   if ((search_append_only || DumpSharedSpaces) && (NULL == stream)) {
1468     // For the boot loader append path search, the starting classpath_index
1469     // for the appended piece is always 1 to account for either the
1470     // _jrt_entry or the _exploded_entries.
1471     assert(classpath_index == 0, "The classpath_index has been incremented incorrectly");
1472     classpath_index = 1;
1473 
1474     e = _first_append_entry;
1475     while (e != NULL) {
1476       stream = e->open_stream(file_name, CHECK_NULL);
1477       if (!context.check(stream, classpath_index)) {
1478         return NULL;
1479       }
1480       if (NULL != stream) {
1481         break;
1482       }
1483       e = e->next();
1484       ++classpath_index;
1485     }
1486   }
1487 
1488   if (NULL == stream) {
1489     if (DumpSharedSpaces) {
1490       tty->print_cr("Preload Warning: Cannot find %s", class_name);
1491     }
1492     return NULL;
1493   }
1494 
1495   stream->set_verify(context.should_verify(classpath_index));
1496 
1497   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
1498   Handle protection_domain;
1499 
1500   instanceKlassHandle result = KlassFactory::create_from_stream(stream,
1501                                                                 name,
1502                                                                 loader_data,
1503                                                                 protection_domain,
1504                                                                 NULL, // host_klass
1505                                                                 NULL, // cp_patches
1506                                                                 THREAD);
1507   if (HAS_PENDING_EXCEPTION) {
1508     if (DumpSharedSpaces) {
1509       tty->print_cr("Preload Error: Failed to load %s", class_name);
1510     }
1511     return NULL;
1512   }
1513 
1514   return context.record_result(name, e, classpath_index, result, THREAD);
1515 }
1516 
1517 // Initialize the class loader's access to methods in libzip.  Parse and
1518 // process the boot classpath into a list ClassPathEntry objects.  Once
1519 // this list has been created, it must not change order (see class PackageInfo)
1520 // it can be appended to and is by jvmti and the kernel vm.
1521 
1522 void ClassLoader::initialize() {
1523   EXCEPTION_MARK;
1524 
1525   if (UsePerfData) {
1526     // jvmstat performance counters
1527     NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");
1528     NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");
1529     NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");
1530     NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");
1531     NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");
1532     NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");
1533     NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");
1534     NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");
1535     NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");
1536     NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");
1537 
1538     NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime");
1539     NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self");
1540     NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime");
1541     NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");
1542     NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");
1543     NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");
1544     NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");
1545     NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");
1546     NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");
1547     NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");
1548     NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");
1549     NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");
1550     NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");
1551 
1552 
1553     // The following performance counters are added for measuring the impact
1554     // of the bug fix of 6365597. They are mainly focused on finding out
1555     // the behavior of system & user-defined classloader lock, whether
1556     // ClassLoader.loadClass/findClass is being called synchronized or not.
1557     // Also two additional counters are created to see whether 'UnsyncloadClass'
1558     // flag is being set or not and how many times load_instance_class call
1559     // fails with linkageError etc.
1560     NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS,
1561                         "systemLoaderLockContentionRate");
1562     NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS,
1563                         "nonSystemLoaderLockContentionRate");
1564     NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS,
1565                         "jvmFindLoadedClassNoLockCalls");
1566     NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS,
1567                         "jvmDefineClassNoLockCalls");
1568 
1569     NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS,
1570                         "jniDefineClassNoLockCalls");
1571 
1572     NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS,
1573                         "unsafeDefineClassCalls");
1574 
1575     NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet");
1576     NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS,
1577                         "loadInstanceClassFailRate");
1578 
1579     // increment the isUnsyncloadClass counter if UnsyncloadClass is set.
1580     if (UnsyncloadClass) {
1581       _isUnsyncloadClass->inc();
1582     }
1583   }
1584 
1585   // lookup zip library entry points
1586   load_zip_library();
1587   // lookup jimage library entry points
1588   load_jimage_library();
1589 #if INCLUDE_CDS
1590   // initialize search path
1591   if (DumpSharedSpaces) {
1592     _shared_paths_misc_info = SharedClassUtil::allocate_shared_paths_misc_info();
1593   }
1594 #endif
1595   setup_bootstrap_search_path();
1596 }
1597 
1598 #if INCLUDE_CDS
1599 void ClassLoader::initialize_shared_path() {
1600   if (DumpSharedSpaces) {
1601     ClassLoaderExt::setup_search_paths();
1602     _shared_paths_misc_info->write_jint(0); // see comments in SharedPathsMiscInfo::check()
1603   }
1604 }
1605 #endif
1606 
1607 jlong ClassLoader::classloader_time_ms() {
1608   return UsePerfData ?
1609     Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;
1610 }
1611 
1612 jlong ClassLoader::class_init_count() {
1613   return UsePerfData ? _perf_classes_inited->get_value() : -1;
1614 }
1615 
1616 jlong ClassLoader::class_init_time_ms() {
1617   return UsePerfData ?
1618     Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;
1619 }
1620 
1621 jlong ClassLoader::class_verify_time_ms() {
1622   return UsePerfData ?
1623     Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;
1624 }
1625 
1626 jlong ClassLoader::class_link_count() {
1627   return UsePerfData ? _perf_classes_linked->get_value() : -1;
1628 }
1629 
1630 jlong ClassLoader::class_link_time_ms() {
1631   return UsePerfData ?
1632     Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;
1633 }
1634 
1635 int ClassLoader::compute_Object_vtable() {
1636   // hardwired for JDK1.2 -- would need to duplicate class file parsing
1637   // code to determine actual value from file
1638   // Would be value '11' if finals were in vtable
1639   int JDK_1_2_Object_vtable_size = 5;
1640   return JDK_1_2_Object_vtable_size * vtableEntry::size();
1641 }
1642 
1643 
1644 void classLoader_init1() {
1645   ClassLoader::initialize();
1646 }
1647 
1648 // Complete the ClassPathEntry setup for the boot loader
1649 void ClassLoader::classLoader_init2(TRAPS) {
1650   // Create the moduleEntry for java.base
1651   create_javabase();
1652 
1653   // Setup the list of module/path pairs for --patch-module processing
1654   // This must be done after the SymbolTable is created in order
1655   // to use fast_compare on module names instead of a string compare.
1656   if (Arguments::get_patch_mod_prefix() != NULL) {
1657     setup_patch_mod_entries();
1658   }
1659 
1660   // Setup the initial java.base/path pair for the exploded build entries.
1661   // As more modules are defined during module system initialization, more
1662   // entries will be added to the exploded build array.
1663   if (!has_jrt_entry()) {
1664     assert(!DumpSharedSpaces, "DumpSharedSpaces not supported with exploded module builds");
1665     assert(!UseSharedSpaces, "UsedSharedSpaces not supported with exploded module builds");
1666     add_to_exploded_build_list(vmSymbols::java_base(), CHECK);
1667   }
1668 }
1669 
1670 
1671 bool ClassLoader::get_canonical_path(const char* orig, char* out, int len) {
1672   assert(orig != NULL && out != NULL && len > 0, "bad arguments");
1673   if (CanonicalizeEntry != NULL) {
1674     JavaThread* THREAD = JavaThread::current();
1675     JNIEnv* env = THREAD->jni_environment();
1676     ResourceMark rm(THREAD);
1677 
1678     // os::native_path writes into orig_copy
1679     char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(orig)+1);
1680     strcpy(orig_copy, orig);
1681     if ((CanonicalizeEntry)(env, os::native_path(orig_copy), out, len) < 0) {
1682       return false;
1683     }
1684   } else {
1685     // On JDK 1.2.2 the Canonicalize does not exist, so just do nothing
1686     strncpy(out, orig, len);
1687     out[len - 1] = '\0';
1688   }
1689   return true;
1690 }
1691 
1692 void ClassLoader::create_javabase() {
1693   Thread* THREAD = Thread::current();
1694 
1695   // Create java.base's module entry for the boot
1696   // class loader prior to loading j.l.Ojbect.
1697   ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
1698 
1699   // Get module entry table
1700   ModuleEntryTable* null_cld_modules = null_cld->modules();
1701   if (null_cld_modules == NULL) {
1702     vm_exit_during_initialization("No ModuleEntryTable for the boot class loader");
1703   }
1704 
1705   {
1706     MutexLocker ml(Module_lock, THREAD);
1707     ModuleEntry* jb_module = null_cld_modules->locked_create_entry_or_null(Handle(NULL), vmSymbols::java_base(), NULL, NULL, null_cld);
1708     if (jb_module == NULL) {
1709       vm_exit_during_initialization("Unable to create ModuleEntry for java.base");
1710     }
1711     ModuleEntryTable::set_javabase_module(jb_module);
1712   }
1713 }
1714 
1715 #ifndef PRODUCT
1716 
1717 // CompileTheWorld
1718 //
1719 // Iterates over all class path entries and forces compilation of all methods
1720 // in all classes found. Currently, only zip/jar archives are searched.
1721 //
1722 // The classes are loaded by the Java level bootstrap class loader, and the
1723 // initializer is called. If DelayCompilationDuringStartup is true (default),
1724 // the interpreter will run the initialization code. Note that forcing
1725 // initialization in this way could potentially lead to initialization order
1726 // problems, in which case we could just force the initialization bit to be set.
1727 
1728 
1729 // We need to iterate over the contents of a zip/jar file, so we replicate the
1730 // jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile,
1731 // since jzfile already has a void* definition.
1732 //
1733 // Note that this is only used in debug mode.
1734 //
1735 // HotSpot integration note:
1736 // Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build
1737 
1738 
1739 // JDK 1.3 version
1740 typedef struct real_jzentry {         /* Zip file entry */
1741     char *name;                 /* entry name */
1742     jint time;                  /* modification time */
1743     jint size;                  /* size of uncompressed data */
1744     jint csize;                 /* size of compressed data (zero if uncompressed) */
1745     jint crc;                   /* crc of uncompressed data */
1746     char *comment;              /* optional zip file comment */
1747     jbyte *extra;               /* optional extra data */
1748     jint pos;                   /* position of LOC header (if negative) or data */
1749 } real_jzentry;
1750 
1751 typedef struct real_jzfile {  /* Zip file */
1752     char *name;                 /* zip file name */
1753     jint refs;                  /* number of active references */
1754     jint fd;                    /* open file descriptor */
1755     void *lock;                 /* read lock */
1756     char *comment;              /* zip file comment */
1757     char *msg;                  /* zip error message */
1758     void *entries;              /* array of hash cells */
1759     jint total;                 /* total number of entries */
1760     unsigned short *table;      /* Hash chain heads: indexes into entries */
1761     jint tablelen;              /* number of hash eads */
1762     real_jzfile *next;        /* next zip file in search list */
1763     jzentry *cache;             /* we cache the most recently freed jzentry */
1764     /* Information on metadata names in META-INF directory */
1765     char **metanames;           /* array of meta names (may have null names) */
1766     jint metacount;             /* number of slots in metanames array */
1767     /* If there are any per-entry comments, they are in the comments array */
1768     char **comments;
1769 } real_jzfile;
1770 
1771 void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {
1772   // For now we only compile all methods in all classes in zip/jar files
1773   tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);
1774   tty->cr();
1775 }
1776 
1777 void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {
1778   real_jzfile* zip = (real_jzfile*) _zip;
1779   tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
1780   tty->cr();
1781   // Iterate over all entries in zip file
1782   for (int n = 0; ; n++) {
1783     real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n));
1784     if (ze == NULL) break;
1785     ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
1786   }
1787   if (HAS_PENDING_EXCEPTION) {
1788     if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1789       CLEAR_PENDING_EXCEPTION;
1790       tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
1791       tty->print_cr("Increase class metadata storage if a limit was set");
1792     } else {
1793       tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
1794     }
1795   }
1796 }
1797 
1798 void ClassLoader::compile_the_world() {
1799   EXCEPTION_MARK;
1800   HandleMark hm(THREAD);
1801   ResourceMark rm(THREAD);
1802 
1803   assert(has_jrt_entry(), "Compile The World not supported with exploded module build");
1804 
1805   // Find bootstrap loader
1806   Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
1807   jlong start = os::javaTimeMillis();
1808 
1809   // Compile the world for the modular java runtime image
1810   _jrt_entry->compile_the_world(system_class_loader, CATCH);
1811 
1812   // Iterate over all bootstrap class path appended entries
1813   ClassPathEntry* e = _first_append_entry;
1814   while (e != NULL) {
1815     assert(!e->is_jrt(), "A modular java runtime image is present on the list of appended entries");
1816     e->compile_the_world(system_class_loader, CATCH);
1817     e = e->next();
1818   }
1819   jlong end = os::javaTimeMillis();
1820   tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)",
1821                 _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));
1822   {
1823     // Print statistics as if before normal exit:
1824     extern void print_statistics();
1825     print_statistics();
1826   }
1827   vm_exit(0);
1828 }
1829 
1830 int ClassLoader::_compile_the_world_class_counter = 0;
1831 int ClassLoader::_compile_the_world_method_counter = 0;
1832 static int _codecache_sweep_counter = 0;
1833 
1834 // Filter out all exceptions except OOMs
1835 static void clear_pending_exception_if_not_oom(TRAPS) {
1836   if (HAS_PENDING_EXCEPTION &&
1837       !PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1838     CLEAR_PENDING_EXCEPTION;
1839   }
1840   // The CHECK at the caller will propagate the exception out
1841 }
1842 
1843 /**
1844  * Returns if the given method should be compiled when doing compile-the-world.
1845  *
1846  * TODO:  This should be a private method in a CompileTheWorld class.
1847  */
1848 static bool can_be_compiled(methodHandle m, int comp_level) {
1849   assert(CompileTheWorld, "must be");
1850 
1851   // It's not valid to compile a native wrapper for MethodHandle methods
1852   // that take a MemberName appendix since the bytecode signature is not
1853   // correct.
1854   vmIntrinsics::ID iid = m->intrinsic_id();
1855   if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) {
1856     return false;
1857   }
1858 
1859   return CompilationPolicy::can_be_compiled(m, comp_level);
1860 }
1861 
1862 void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {
1863   if (string_ends_with(name, ".class")) {
1864     // We have a .class file
1865     int len = (int)strlen(name);
1866     char buffer[2048];
1867     strncpy(buffer, name, len - 6);
1868     buffer[len-6] = 0;
1869     // If the file has a period after removing .class, it's not really a
1870     // valid class file.  The class loader will check everything else.
1871     if (strchr(buffer, '.') == NULL) {
1872       _compile_the_world_class_counter++;
1873       if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;
1874 
1875       // Construct name without extension
1876       TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
1877       // Use loader to load and initialize class
1878       Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);
1879       instanceKlassHandle k (THREAD, ik);
1880       if (k.not_null() && !HAS_PENDING_EXCEPTION) {
1881         k->initialize(THREAD);
1882       }
1883       bool exception_occurred = HAS_PENDING_EXCEPTION;
1884       clear_pending_exception_if_not_oom(CHECK);
1885       if (CompileTheWorldPreloadClasses && k.not_null()) {
1886         ConstantPool::preload_and_initialize_all_classes(k->constants(), THREAD);
1887         if (HAS_PENDING_EXCEPTION) {
1888           // If something went wrong in preloading we just ignore it
1889           clear_pending_exception_if_not_oom(CHECK);
1890           tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer);
1891         }
1892       }
1893 
1894       if (_compile_the_world_class_counter >= CompileTheWorldStartAt) {
1895         if (k.is_null() || exception_occurred) {
1896           // If something went wrong (e.g. ExceptionInInitializerError) we skip this class
1897           tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer);
1898         } else {
1899           tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer);
1900           // Preload all classes to get around uncommon traps
1901           // Iterate over all methods in class
1902           int comp_level = CompilationPolicy::policy()->initial_compile_level();
1903           for (int n = 0; n < k->methods()->length(); n++) {
1904             methodHandle m (THREAD, k->methods()->at(n));
1905             if (can_be_compiled(m, comp_level)) {
1906               if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) {
1907                 // Give sweeper a chance to keep up with CTW
1908                 VM_ForceSafepoint op;
1909                 VMThread::execute(&op);
1910                 _codecache_sweep_counter = 0;
1911               }
1912               // Force compilation
1913               CompileBroker::compile_method(m, InvocationEntryBci, comp_level,
1914                                             methodHandle(), 0, CompileTask::Reason_CTW, THREAD);
1915               if (HAS_PENDING_EXCEPTION) {
1916                 clear_pending_exception_if_not_oom(CHECK);
1917                 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1918               } else {
1919                 _compile_the_world_method_counter++;
1920               }
1921               if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) {
1922                 // Clobber the first compile and force second tier compilation
1923                 CompiledMethod* nm = m->code();
1924                 if (nm != NULL && !m->is_method_handle_intrinsic()) {
1925                   // Throw out the code so that the code cache doesn't fill up
1926                   nm->make_not_entrant();
1927                   m->clear_code();
1928                 }
1929                 CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization,
1930                                               methodHandle(), 0, CompileTask::Reason_CTW, THREAD);
1931                 if (HAS_PENDING_EXCEPTION) {
1932                   clear_pending_exception_if_not_oom(CHECK);
1933                   tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1934                 } else {
1935                   _compile_the_world_method_counter++;
1936                 }
1937               }
1938             } else {
1939               tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1940             }
1941 
1942             CompiledMethod* nm = m->code();
1943             if (nm != NULL && !m->is_method_handle_intrinsic()) {
1944               // Throw out the code so that the code cache doesn't fill up
1945               nm->make_not_entrant();
1946               m->clear_code();
1947             }
1948           }
1949         }
1950       }
1951     }
1952   }
1953 }
1954 
1955 #endif //PRODUCT
1956 
1957 // Please keep following two functions at end of this file. With them placed at top or in middle of the file,
1958 // they could get inlined by agressive compiler, an unknown trick, see bug 6966589.
1959 void PerfClassTraceTime::initialize() {
1960   if (!UsePerfData) return;
1961 
1962   if (_eventp != NULL) {
1963     // increment the event counter
1964     _eventp->inc();
1965   }
1966 
1967   // stop the current active thread-local timer to measure inclusive time
1968   _prev_active_event = -1;
1969   for (int i=0; i < EVENT_TYPE_COUNT; i++) {
1970      if (_timers[i].is_active()) {
1971        assert(_prev_active_event == -1, "should have only one active timer");
1972        _prev_active_event = i;
1973        _timers[i].stop();
1974      }
1975   }
1976 
1977   if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) {
1978     // start the inclusive timer if not recursively called
1979     _t.start();
1980   }
1981 
1982   // start thread-local timer of the given event type
1983    if (!_timers[_event_type].is_active()) {
1984     _timers[_event_type].start();
1985   }
1986 }
1987 
1988 PerfClassTraceTime::~PerfClassTraceTime() {
1989   if (!UsePerfData) return;
1990 
1991   // stop the thread-local timer as the event completes
1992   // and resume the thread-local timer of the event next on the stack
1993   _timers[_event_type].stop();
1994   jlong selftime = _timers[_event_type].ticks();
1995 
1996   if (_prev_active_event >= 0) {
1997     _timers[_prev_active_event].start();
1998   }
1999 
2000   if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return;
2001 
2002   // increment the counters only on the leaf call
2003   _t.stop();
2004   _timep->inc(_t.ticks());
2005   if (_selftimep != NULL) {
2006     _selftimep->inc(selftime);
2007   }
2008   // add all class loading related event selftime to the accumulated time counter
2009   ClassLoader::perf_accumulated_time()->inc(selftime);
2010 
2011   // reset the timer
2012   _timers[_event_type].reset();
2013 }