1 /*
   2  * Copyright (c) 1997, 2017, 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/log.hpp"
  44 #include "logging/logStream.hpp"
  45 #include "logging/logTag.hpp"
  46 #include "memory/allocation.inline.hpp"
  47 #include "memory/filemap.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.inline.hpp"
  51 #include "oops/instanceKlass.hpp"
  52 #include "oops/instanceRefKlass.hpp"
  53 #include "oops/objArrayOop.inline.hpp"
  54 #include "oops/oop.inline.hpp"
  55 #include "oops/symbol.hpp"
  56 #include "prims/jvm_misc.hpp"
  57 #include "runtime/arguments.hpp"
  58 #include "runtime/compilationPolicy.hpp"
  59 #include "runtime/fprofiler.hpp"
  60 #include "runtime/handles.hpp"
  61 #include "runtime/handles.inline.hpp"
  62 #include "runtime/init.hpp"
  63 #include "runtime/interfaceSupport.hpp"
  64 #include "runtime/java.hpp"
  65 #include "runtime/javaCalls.hpp"
  66 #include "runtime/os.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/events.hpp"
  73 #include "utilities/hashtable.inline.hpp"
  74 #include "utilities/macros.hpp"
  75 #if INCLUDE_CDS
  76 #include "classfile/sharedClassUtil.hpp"
  77 #include "classfile/sharedPathsMiscInfo.hpp"
  78 #endif
  79 
  80 // Entry points in zip.dll for loading zip/jar file entries
  81 
  82 typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg);
  83 typedef void (JNICALL *ZipClose_t)(jzfile *zip);
  84 typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen);
  85 typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);
  86 typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);
  87 typedef jboolean (JNICALL *ZipInflateFully_t)(void *inBuf, jlong inLen, void *outBuf, jlong outLen, char **pmsg);
  88 typedef jint     (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);
  89 
  90 static ZipOpen_t         ZipOpen            = NULL;
  91 static ZipClose_t        ZipClose           = NULL;
  92 static FindEntry_t       FindEntry          = NULL;
  93 static ReadEntry_t       ReadEntry          = 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   // read contents into resource array
 340   int size = (*filesize) + ((nul_terminate) ? 1 : 0);
 341   buffer = NEW_RESOURCE_ARRAY(u1, size);
 342   if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL;
 343 
 344   // return result
 345   if (nul_terminate) {
 346     buffer[*filesize] = 0;
 347   }
 348   return buffer;
 349 }
 350 
 351 #if INCLUDE_CDS
 352 u1* ClassPathZipEntry::open_versioned_entry(const char* name, jint* filesize, TRAPS) {
 353   u1* buffer = NULL;
 354   if (DumpSharedSpaces && !_is_boot_append) {
 355     // We presume default is multi-release enabled
 356     const char* multi_ver = Arguments::get_property("jdk.util.jar.enableMultiRelease");
 357     const char* verstr = Arguments::get_property("jdk.util.jar.version");
 358     bool is_multi_ver = (multi_ver == NULL ||
 359                          strcmp(multi_ver, "true") == 0 ||
 360                          strcmp(multi_ver, "force")  == 0) &&
 361                          is_multiple_versioned(THREAD);
 362     // command line version setting
 363     int version = 0;
 364     const int base_version = 8; // JDK8
 365     int cur_ver = JDK_Version::current().major_version();
 366     if (verstr != NULL) {
 367       version = atoi(verstr);
 368       if (version < base_version || version > cur_ver) {
 369         // If the specified version is lower than the base version, the base
 370         // entry will be used; if the version is higher than the current
 371         // jdk version, the highest versioned entry will be used.
 372         if (version < base_version) {
 373           is_multi_ver = false;
 374         }
 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_NAME, 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   LogTarget(Info, class, path) lt;
 614   if (lt.is_enabled()) {
 615     LogStream ls(lt);
 616     if (msg) {
 617       ls.print("%s", msg);
 618     }
 619     if (name) {
 620       if (strlen(name) < 256) {
 621         ls.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           ls.print("%c", name[0]);
 627           name++;
 628         }
 629       }
 630     }
 631     ls.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_IFMT) != S_IFREG) { // is not a regular file
 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 
 697   // Set up the boot loader's _patch_mod_entries list
 698   _patch_mod_entries = new (ResourceObj::C_HEAP, mtModule) GrowableArray<ModuleClassPathList*>(num_of_entries, true);
 699 
 700   for (int i = 0; i < num_of_entries; i++) {
 701     const char* module_name = (patch_mod_args->at(i))->module_name();
 702     Symbol* const module_sym = SymbolTable::lookup(module_name, (int)strlen(module_name), CHECK);
 703     assert(module_sym != NULL, "Failed to obtain Symbol for module name");
 704     ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym);
 705 
 706     char* class_path = (patch_mod_args->at(i))->path_string();
 707     int len = (int)strlen(class_path);
 708     int end = 0;
 709     // Iterate over the module's class path entries
 710     for (int start = 0; start < len; start = end) {
 711       while (class_path[end] && class_path[end] != os::path_separator()[0]) {
 712         end++;
 713       }
 714       EXCEPTION_MARK;
 715       ResourceMark rm(THREAD);
 716       char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);
 717       strncpy(path, &class_path[start], end - start);
 718       path[end - start] = '\0';
 719 
 720       struct stat st;
 721       if (os::stat(path, &st) == 0) {
 722         // File or directory found
 723         Thread* THREAD = Thread::current();
 724         ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK);
 725         // If the path specification is valid, enter it into this module's list
 726         if (new_entry != NULL) {
 727           module_cpl->add_to_list(new_entry);
 728         }
 729       }
 730 
 731       while (class_path[end] == os::path_separator()[0]) {
 732         end++;
 733       }
 734     }
 735 
 736     // Record the module into the list of --patch-module entries only if
 737     // valid ClassPathEntrys have been created
 738     if (module_cpl->module_first_entry() != NULL) {
 739       _patch_mod_entries->push(module_cpl);
 740     }
 741   }
 742 }
 743 
 744 // Determine whether the module has been patched via the command-line
 745 // option --patch-module
 746 bool ClassLoader::is_in_patch_mod_entries(Symbol* module_name) {
 747   if (_patch_mod_entries != NULL && _patch_mod_entries->is_nonempty()) {
 748     int table_len = _patch_mod_entries->length();
 749     for (int i = 0; i < table_len; i++) {
 750       ModuleClassPathList* patch_mod = _patch_mod_entries->at(i);
 751       if (module_name->fast_compare(patch_mod->module_name()) == 0) {
 752         return true;
 753       }
 754     }
 755   }
 756   return false;
 757 }
 758 
 759 void ClassLoader::setup_search_path(const char *class_path, bool bootstrap_search) {
 760   int len = (int)strlen(class_path);
 761   int end = 0;
 762   bool set_base_piece = bootstrap_search;
 763 
 764   // Iterate over class path entries
 765   for (int start = 0; start < len; start = end) {
 766     while (class_path[end] && class_path[end] != os::path_separator()[0]) {
 767       end++;
 768     }
 769     EXCEPTION_MARK;
 770     ResourceMark rm(THREAD);
 771     char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);
 772     strncpy(path, &class_path[start], end - start);
 773     path[end - start] = '\0';
 774 
 775     // The first time through the bootstrap_search setup, it must be determined
 776     // what the base or core piece of the boot loader search is.  Either a java runtime
 777     // image is present or this is an exploded module build situation.
 778     if (set_base_piece) {
 779       assert(string_ends_with(path, MODULES_IMAGE_NAME) || string_ends_with(path, JAVA_BASE_NAME),
 780              "Incorrect boot loader search path, no java runtime image or " JAVA_BASE_NAME " exploded build");
 781       struct stat st;
 782       if (os::stat(path, &st) == 0) {
 783         // Directory found
 784         Thread* THREAD = Thread::current();
 785         ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK);
 786 
 787         // Check for a jimage
 788         if (Arguments::has_jimage()) {
 789           assert(_jrt_entry == NULL, "should not setup bootstrap class search path twice");
 790           assert(new_entry != NULL && new_entry->is_jrt(), "No java runtime image present");
 791           _jrt_entry = new_entry;
 792           ++_num_entries;
 793 #if INCLUDE_CDS
 794           if (DumpSharedSpaces) {
 795             JImageFile *jimage = _jrt_entry->jimage();
 796             assert(jimage != NULL, "No java runtime image file present");
 797             ClassLoader::initialize_module_loader_map(jimage);
 798           }
 799 #endif
 800         }
 801       } else {
 802         // If path does not exist, exit
 803         vm_exit_during_initialization("Unable to establish the boot loader search path", path);
 804       }
 805       set_base_piece = false;
 806     } else {
 807       // Every entry on the system boot class path after the initial base piece,
 808       // which is set by os::set_boot_path(), is considered an appended entry.
 809       update_class_path_entry_list(path, false, bootstrap_search);
 810     }
 811 
 812 #if INCLUDE_CDS
 813     if (DumpSharedSpaces) {
 814       check_shared_classpath(path);
 815     }
 816 #endif
 817     while (class_path[end] == os::path_separator()[0]) {
 818       end++;
 819     }
 820   }
 821 }
 822 
 823 // During an exploded modules build, each module defined to the boot loader
 824 // will be added to the ClassLoader::_exploded_entries array.
 825 void ClassLoader::add_to_exploded_build_list(Symbol* module_sym, TRAPS) {
 826   assert(!ClassLoader::has_jrt_entry(), "Exploded build not applicable");
 827   assert(_exploded_entries != NULL, "_exploded_entries was not initialized");
 828 
 829   // Find the module's symbol
 830   ResourceMark rm(THREAD);
 831   const char *module_name = module_sym->as_C_string();
 832   const char *home = Arguments::get_java_home();
 833   const char file_sep = os::file_separator()[0];
 834   // 10 represents the length of "modules" + 2 file separators + \0
 835   size_t len = strlen(home) + strlen(module_name) + 10;
 836   char *path = NEW_C_HEAP_ARRAY(char, len, mtModule);
 837   jio_snprintf(path, len, "%s%cmodules%c%s", home, file_sep, file_sep, module_name);
 838 
 839   struct stat st;
 840   if (os::stat(path, &st) == 0) {
 841     // Directory found
 842     ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK);
 843 
 844     // If the path specification is valid, enter it into this module's list.
 845     // There is no need to check for duplicate modules in the exploded entry list,
 846     // since no two modules with the same name can be defined to the boot loader.
 847     // This is checked at module definition time in Modules::define_module.
 848     if (new_entry != NULL) {
 849       ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym);
 850       module_cpl->add_to_list(new_entry);
 851       {
 852         MutexLocker ml(Module_lock, THREAD);
 853         _exploded_entries->push(module_cpl);
 854       }
 855       log_info(class, load)("path: %s", path);
 856     }
 857   }
 858   FREE_C_HEAP_ARRAY(char, path);
 859 }
 860 
 861 ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st,
 862                                                      bool throw_exception,
 863                                                      bool is_boot_append, TRAPS) {
 864   JavaThread* thread = JavaThread::current();
 865   ClassPathEntry* new_entry = NULL;
 866   if ((st->st_mode & S_IFMT) == S_IFREG) {
 867     ResourceMark rm(thread);
 868     // Regular file, should be a zip or jimage file
 869     // Canonicalized filename
 870     char* canonical_path = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, JVM_MAXPATHLEN);
 871     if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
 872       // This matches the classic VM
 873       if (throw_exception) {
 874         THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL);
 875       } else {
 876         return NULL;
 877       }
 878     }
 879     jint error;
 880     JImageFile* jimage =(*JImageOpen)(canonical_path, &error);
 881     if (jimage != NULL) {
 882       new_entry = new ClassPathImageEntry(jimage, canonical_path);
 883     } else {
 884       char* error_msg = NULL;
 885       jzfile* zip;
 886       {
 887         // enable call to C land
 888         ThreadToNativeFromVM ttn(thread);
 889         HandleMark hm(thread);
 890         zip = (*ZipOpen)(canonical_path, &error_msg);
 891       }
 892       if (zip != NULL && error_msg == NULL) {
 893         new_entry = new ClassPathZipEntry(zip, path, is_boot_append);
 894       } else {
 895         char *msg;
 896         if (error_msg == NULL) {
 897           msg = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, strlen(path) + 128); ;
 898           jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
 899         } else {
 900           int len = (int)(strlen(path) + strlen(error_msg) + 128);
 901           msg = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, len); ;
 902           jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path);
 903         }
 904         // Don't complain about bad jar files added via -Xbootclasspath/a:.
 905         if (throw_exception && is_init_completed()) {
 906           THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL);
 907         } else {
 908           return NULL;
 909         }
 910       }
 911     }
 912     log_info(class, path)("opened: %s", path);
 913     log_info(class, load)("opened: %s", path);
 914   } else {
 915     // Directory
 916     new_entry = new ClassPathDirEntry(path);
 917     log_info(class, load)("path: %s", path);
 918   }
 919   return new_entry;
 920 }
 921 
 922 
 923 // Create a class path zip entry for a given path (return NULL if not found
 924 // or zip/JAR file cannot be opened)
 925 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path, bool is_boot_append) {
 926   // check for a regular file
 927   struct stat st;
 928   if (os::stat(path, &st) == 0) {
 929     if ((st.st_mode & S_IFMT) == S_IFREG) {
 930       char canonical_path[JVM_MAXPATHLEN];
 931       if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
 932         char* error_msg = NULL;
 933         jzfile* zip;
 934         {
 935           // enable call to C land
 936           JavaThread* thread = JavaThread::current();
 937           ThreadToNativeFromVM ttn(thread);
 938           HandleMark hm(thread);
 939           zip = (*ZipOpen)(canonical_path, &error_msg);
 940         }
 941         if (zip != NULL && error_msg == NULL) {
 942           // create using canonical path
 943           return new ClassPathZipEntry(zip, canonical_path, is_boot_append);
 944         }
 945       }
 946     }
 947   }
 948   return NULL;
 949 }
 950 
 951 // returns true if entry already on class path
 952 bool ClassLoader::contains_append_entry(const char* name) {
 953   ClassPathEntry* e = _first_append_entry;
 954   while (e != NULL) {
 955     // assume zip entries have been canonicalized
 956     if (strcmp(name, e->name()) == 0) {
 957       return true;
 958     }
 959     e = e->next();
 960   }
 961   return false;
 962 }
 963 
 964 void ClassLoader::add_to_list(ClassPathEntry *new_entry) {
 965   if (new_entry != NULL) {
 966     if (_last_append_entry == NULL) {
 967       assert(_first_append_entry == NULL, "boot loader's append class path entry list not empty");
 968       _first_append_entry = _last_append_entry = new_entry;
 969     } else {
 970       _last_append_entry->set_next(new_entry);
 971       _last_append_entry = new_entry;
 972     }
 973   }
 974   _num_entries++;
 975 }
 976 
 977 void ClassLoader::add_to_list(const char *apath) {
 978   update_class_path_entry_list((char*)apath, false, false);
 979 }
 980 
 981 // Returns true IFF the file/dir exists and the entry was successfully created.
 982 bool ClassLoader::update_class_path_entry_list(const char *path,
 983                                                bool check_for_duplicates,
 984                                                bool is_boot_append,
 985                                                bool throw_exception) {
 986   struct stat st;
 987   if (os::stat(path, &st) == 0) {
 988     // File or directory found
 989     ClassPathEntry* new_entry = NULL;
 990     Thread* THREAD = Thread::current();
 991     new_entry = create_class_path_entry(path, &st, throw_exception, is_boot_append, CHECK_(false));
 992     if (new_entry == NULL) {
 993       return false;
 994     }
 995 
 996     // Do not reorder the bootclasspath which would break get_system_package().
 997     // Add new entry to linked list
 998     if (!check_for_duplicates || !contains_append_entry(new_entry->name())) {
 999       ClassLoaderExt::add_class_path_entry(path, check_for_duplicates, new_entry);
1000     }
1001     return true;
1002   } else {
1003 #if INCLUDE_CDS
1004     if (DumpSharedSpaces) {
1005       _shared_paths_misc_info->add_nonexist_path(path);
1006     }
1007 #endif
1008     return false;
1009   }
1010 }
1011 
1012 static void print_module_entry_table(const GrowableArray<ModuleClassPathList*>* const module_list) {
1013   ResourceMark rm;
1014   int num_of_entries = module_list->length();
1015   for (int i = 0; i < num_of_entries; i++) {
1016     ClassPathEntry* e;
1017     ModuleClassPathList* mpl = module_list->at(i);
1018     tty->print("%s=", mpl->module_name()->as_C_string());
1019     e = mpl->module_first_entry();
1020     while (e != NULL) {
1021       tty->print("%s", e->name());
1022       e = e->next();
1023       if (e != NULL) {
1024         tty->print("%s", os::path_separator());
1025       }
1026     }
1027     tty->print(" ;");
1028   }
1029 }
1030 
1031 void ClassLoader::print_bootclasspath() {
1032   ClassPathEntry* e;
1033   tty->print("[bootclasspath= ");
1034 
1035   // Print --patch-module module/path specifications first
1036   if (_patch_mod_entries != NULL) {
1037     print_module_entry_table(_patch_mod_entries);
1038   }
1039 
1040   // [jimage | exploded modules build]
1041   if (has_jrt_entry()) {
1042     // Print the location of the java runtime image
1043     tty->print("%s ;", _jrt_entry->name());
1044   } else {
1045     // Print exploded module build path specifications
1046     if (_exploded_entries != NULL) {
1047       print_module_entry_table(_exploded_entries);
1048     }
1049   }
1050 
1051   // appended entries
1052   e = _first_append_entry;
1053   while (e != NULL) {
1054     tty->print("%s ;", e->name());
1055     e = e->next();
1056   }
1057   tty->print_cr("]");
1058 }
1059 
1060 void ClassLoader::load_zip_library() {
1061   assert(ZipOpen == NULL, "should not load zip library twice");
1062   // First make sure native library is loaded
1063   os::native_java_library();
1064   // Load zip library
1065   char path[JVM_MAXPATHLEN];
1066   char ebuf[1024];
1067   void* handle = NULL;
1068   if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {
1069     handle = os::dll_load(path, ebuf, sizeof ebuf);
1070   }
1071   if (handle == NULL) {
1072     vm_exit_during_initialization("Unable to load ZIP library", path);
1073   }
1074   // Lookup zip entry points
1075   ZipOpen      = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));
1076   ZipClose     = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));
1077   FindEntry    = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));
1078   ReadEntry    = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
1079   GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));
1080   ZipInflateFully = CAST_TO_FN_PTR(ZipInflateFully_t, os::dll_lookup(handle, "ZIP_InflateFully"));
1081   Crc32        = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));
1082 
1083   // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
1084   if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||
1085       GetNextEntry == NULL || Crc32 == NULL) {
1086     vm_exit_during_initialization("Corrupted ZIP library", path);
1087   }
1088 
1089   if (ZipInflateFully == NULL) {
1090     vm_exit_during_initialization("Corrupted ZIP library ZIP_InflateFully missing", path);
1091   }
1092 
1093   // Lookup canonicalize entry in libjava.dll
1094   void *javalib_handle = os::native_java_library();
1095   CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));
1096   // This lookup only works on 1.3. Do not check for non-null here
1097 }
1098 
1099 void ClassLoader::load_jimage_library() {
1100   // First make sure native library is loaded
1101   os::native_java_library();
1102   // Load jimage library
1103   char path[JVM_MAXPATHLEN];
1104   char ebuf[1024];
1105   void* handle = NULL;
1106   if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "jimage")) {
1107     handle = os::dll_load(path, ebuf, sizeof ebuf);
1108   }
1109   if (handle == NULL) {
1110     vm_exit_during_initialization("Unable to load jimage library", path);
1111   }
1112 
1113   // Lookup jimage entry points
1114   JImageOpen = CAST_TO_FN_PTR(JImageOpen_t, os::dll_lookup(handle, "JIMAGE_Open"));
1115   guarantee(JImageOpen != NULL, "function JIMAGE_Open not found");
1116   JImageClose = CAST_TO_FN_PTR(JImageClose_t, os::dll_lookup(handle, "JIMAGE_Close"));
1117   guarantee(JImageClose != NULL, "function JIMAGE_Close not found");
1118   JImagePackageToModule = CAST_TO_FN_PTR(JImagePackageToModule_t, os::dll_lookup(handle, "JIMAGE_PackageToModule"));
1119   guarantee(JImagePackageToModule != NULL, "function JIMAGE_PackageToModule not found");
1120   JImageFindResource = CAST_TO_FN_PTR(JImageFindResource_t, os::dll_lookup(handle, "JIMAGE_FindResource"));
1121   guarantee(JImageFindResource != NULL, "function JIMAGE_FindResource not found");
1122   JImageGetResource = CAST_TO_FN_PTR(JImageGetResource_t, os::dll_lookup(handle, "JIMAGE_GetResource"));
1123   guarantee(JImageGetResource != NULL, "function JIMAGE_GetResource not found");
1124   JImageResourceIterator = CAST_TO_FN_PTR(JImageResourceIterator_t, os::dll_lookup(handle, "JIMAGE_ResourceIterator"));
1125   guarantee(JImageResourceIterator != NULL, "function JIMAGE_ResourceIterator not found");
1126   JImageResourcePath = CAST_TO_FN_PTR(JImage_ResourcePath_t, os::dll_lookup(handle, "JIMAGE_ResourcePath"));
1127   guarantee(JImageResourcePath != NULL, "function JIMAGE_ResourcePath not found");
1128 }
1129 
1130 jboolean ClassLoader::decompress(void *in, u8 inSize, void *out, u8 outSize, char **pmsg) {
1131   return (*ZipInflateFully)(in, inSize, out, outSize, pmsg);
1132 }
1133 
1134 int ClassLoader::crc32(int crc, const char* buf, int len) {
1135   assert(Crc32 != NULL, "ZIP_CRC32 is not found");
1136   return (*Crc32)(crc, (const jbyte*)buf, len);
1137 }
1138 
1139 #if INCLUDE_CDS
1140 void ClassLoader::initialize_module_loader_map(JImageFile* jimage) {
1141   if (!DumpSharedSpaces) {
1142     return; // only needed for CDS dump time
1143   }
1144 
1145   ResourceMark rm;
1146   jlong size;
1147   JImageLocationRef location = (*JImageFindResource)(jimage, JAVA_BASE_NAME, get_jimage_version_string(), MODULE_LOADER_MAP, &size);
1148   if (location == 0) {
1149     vm_exit_during_initialization(
1150       "Cannot find ModuleLoaderMap location from modules jimage.", NULL);
1151   }
1152   char* buffer = NEW_RESOURCE_ARRAY(char, size + 1);
1153   buffer[size] = '\0';
1154   jlong read = (*JImageGetResource)(jimage, location, buffer, size);
1155   if (read != size) {
1156     vm_exit_during_initialization(
1157       "Cannot find ModuleLoaderMap resource from modules jimage.", NULL);
1158   }
1159   char* char_buf = (char*)buffer;
1160   int buflen = (int)strlen(char_buf);
1161   char* begin_ptr = char_buf;
1162   char* end_ptr = strchr(begin_ptr, '\n');
1163   bool process_boot_modules = false;
1164   _boot_modules_array = new (ResourceObj::C_HEAP, mtModule)
1165     GrowableArray<char*>(INITIAL_BOOT_MODULES_ARRAY_SIZE, true);
1166   _platform_modules_array = new (ResourceObj::C_HEAP, mtModule)
1167     GrowableArray<char*>(INITIAL_PLATFORM_MODULES_ARRAY_SIZE, true);
1168   while (end_ptr != NULL && (end_ptr - char_buf) < buflen) {
1169     // Allocate a buffer from the C heap to be appended to the _boot_modules_array
1170     // or the _platform_modules_array.
1171     char* temp_name = NEW_C_HEAP_ARRAY(char, (size_t)(end_ptr - begin_ptr + 1), mtInternal);
1172     strncpy(temp_name, begin_ptr, end_ptr - begin_ptr);
1173     temp_name[end_ptr - begin_ptr] = '\0';
1174     if (strncmp(temp_name, "BOOT", 4) == 0) {
1175       process_boot_modules = true;
1176       FREE_C_HEAP_ARRAY(char, temp_name);
1177     } else if (strncmp(temp_name, "PLATFORM", 8) == 0) {
1178       process_boot_modules = false;
1179       FREE_C_HEAP_ARRAY(char, temp_name);
1180     } else {
1181       // module name
1182       if (process_boot_modules) {
1183         _boot_modules_array->append(temp_name);
1184       } else {
1185         _platform_modules_array->append(temp_name);
1186       }
1187     }
1188     begin_ptr = ++end_ptr;
1189     end_ptr = strchr(begin_ptr, '\n');
1190   }
1191 }
1192 #endif
1193 
1194 // Function add_package extracts the package from the fully qualified class name
1195 // and checks if the package is in the boot loader's package entry table.  If so,
1196 // then it sets the classpath_index in the package entry record.
1197 //
1198 // The classpath_index field is used to find the entry on the boot loader class
1199 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a
1200 // in an unnamed module.  It is also used to indicate (for all packages whose
1201 // classes are loaded by the boot loader) that at least one of the package's
1202 // classes has been loaded.
1203 bool ClassLoader::add_package(const char *fullq_class_name, s2 classpath_index, TRAPS) {
1204   assert(fullq_class_name != NULL, "just checking");
1205 
1206   // Get package name from fully qualified class name.
1207   ResourceMark rm;
1208   const char *cp = package_from_name(fullq_class_name);
1209   if (cp != NULL) {
1210     PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();
1211     TempNewSymbol pkg_symbol = SymbolTable::new_symbol(cp, CHECK_false);
1212     PackageEntry* pkg_entry = pkg_entry_tbl->lookup_only(pkg_symbol);
1213     if (pkg_entry != NULL) {
1214       assert(classpath_index != -1, "Unexpected classpath_index");
1215       pkg_entry->set_classpath_index(classpath_index);
1216     } else {
1217       return false;
1218     }
1219   }
1220   return true;
1221 }
1222 
1223 oop ClassLoader::get_system_package(const char* name, TRAPS) {
1224   // Look up the name in the boot loader's package entry table.
1225   if (name != NULL) {
1226     TempNewSymbol package_sym = SymbolTable::new_symbol(name, (int)strlen(name), CHECK_NULL);
1227     // Look for the package entry in the boot loader's package entry table.
1228     PackageEntry* package =
1229       ClassLoaderData::the_null_class_loader_data()->packages()->lookup_only(package_sym);
1230 
1231     // Return NULL if package does not exist or if no classes in that package
1232     // have been loaded.
1233     if (package != NULL && package->has_loaded_class()) {
1234       ModuleEntry* module = package->module();
1235       if (module->location() != NULL) {
1236         ResourceMark rm(THREAD);
1237         Handle ml = java_lang_String::create_from_str(
1238           module->location()->as_C_string(), THREAD);
1239         return ml();
1240       }
1241       // Return entry on boot loader class path.
1242       Handle cph = java_lang_String::create_from_str(
1243         ClassLoader::classpath_entry(package->classpath_index())->name(), THREAD);
1244       return cph();
1245     }
1246   }
1247   return NULL;
1248 }
1249 
1250 objArrayOop ClassLoader::get_system_packages(TRAPS) {
1251   ResourceMark rm(THREAD);
1252   // List of pointers to PackageEntrys that have loaded classes.
1253   GrowableArray<PackageEntry*>* loaded_class_pkgs = new GrowableArray<PackageEntry*>(50);
1254   {
1255     MutexLocker ml(Module_lock, THREAD);
1256 
1257     PackageEntryTable* pe_table =
1258       ClassLoaderData::the_null_class_loader_data()->packages();
1259 
1260     // Collect the packages that have at least one loaded class.
1261     for (int x = 0; x < pe_table->table_size(); x++) {
1262       for (PackageEntry* package_entry = pe_table->bucket(x);
1263            package_entry != NULL;
1264            package_entry = package_entry->next()) {
1265         if (package_entry->has_loaded_class()) {
1266           loaded_class_pkgs->append(package_entry);
1267         }
1268       }
1269     }
1270   }
1271 
1272 
1273   // Allocate objArray and fill with java.lang.String
1274   objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
1275                                            loaded_class_pkgs->length(), CHECK_NULL);
1276   objArrayHandle result(THREAD, r);
1277   for (int x = 0; x < loaded_class_pkgs->length(); x++) {
1278     PackageEntry* package_entry = loaded_class_pkgs->at(x);
1279     Handle str = java_lang_String::create_from_symbol(package_entry->name(), CHECK_NULL);
1280     result->obj_at_put(x, str());
1281   }
1282   return result();
1283 }
1284 
1285 #if INCLUDE_CDS
1286 s2 ClassLoader::module_to_classloader(const char* module_name) {
1287 
1288   assert(DumpSharedSpaces, "dump time only");
1289   assert(_boot_modules_array != NULL, "_boot_modules_array is NULL");
1290   assert(_platform_modules_array != NULL, "_platform_modules_array is NULL");
1291 
1292   int array_size = _boot_modules_array->length();
1293   for (int i = 0; i < array_size; i++) {
1294     if (strcmp(module_name, _boot_modules_array->at(i)) == 0) {
1295       return BOOT_LOADER;
1296     }
1297   }
1298 
1299   array_size = _platform_modules_array->length();
1300   for (int i = 0; i < array_size; i++) {
1301     if (strcmp(module_name, _platform_modules_array->at(i)) == 0) {
1302       return PLATFORM_LOADER;
1303     }
1304   }
1305 
1306   return APP_LOADER;
1307 }
1308 
1309 s2 ClassLoader::classloader_type(Symbol* class_name, ClassPathEntry* e, int classpath_index, TRAPS) {
1310   assert(DumpSharedSpaces, "Only used for CDS dump time");
1311 
1312   // obtain the classloader type based on the class name.
1313   // First obtain the package name based on the class name. Then obtain
1314   // the classloader type based on the package name from the jimage using
1315   // a jimage API. If the classloader type cannot be found from the
1316   // jimage, it is determined by the class path entry.
1317   jshort loader_type = ClassLoader::APP_LOADER;
1318   if (e->is_jrt()) {
1319     ResourceMark rm;
1320     TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_0);
1321     if (pkg_name != NULL) {
1322       const char* pkg_name_C_string = (const char*)(pkg_name->as_C_string());
1323       ClassPathImageEntry* cpie = (ClassPathImageEntry*)e;
1324       JImageFile* jimage = cpie->jimage();
1325       char* module_name = (char*)(*JImagePackageToModule)(jimage, pkg_name_C_string);
1326       if (module_name != NULL) {
1327         loader_type = ClassLoader::module_to_classloader(module_name);
1328       }
1329     }
1330   } else if (ClassLoaderExt::is_boot_classpath(classpath_index)) {
1331     loader_type = ClassLoader::BOOT_LOADER;
1332   }
1333   return loader_type;
1334 }
1335 #endif
1336 
1337 // caller needs ResourceMark
1338 const char* ClassLoader::file_name_for_class_name(const char* class_name,
1339                                                   int class_name_len) {
1340   assert(class_name != NULL, "invariant");
1341   assert((int)strlen(class_name) == class_name_len, "invariant");
1342 
1343   static const char class_suffix[] = ".class";
1344 
1345   char* const file_name = NEW_RESOURCE_ARRAY(char,
1346                                              class_name_len +
1347                                              sizeof(class_suffix)); // includes term NULL
1348 
1349   strncpy(file_name, class_name, class_name_len);
1350   strncpy(&file_name[class_name_len], class_suffix, sizeof(class_suffix));
1351 
1352   return file_name;
1353 }
1354 
1355 ClassPathEntry* find_first_module_cpe(ModuleEntry* mod_entry,
1356                                       const GrowableArray<ModuleClassPathList*>* const module_list) {
1357   int num_of_entries = module_list->length();
1358   const Symbol* class_module_name = mod_entry->name();
1359 
1360   // Loop through all the modules in either the patch-module or exploded entries looking for module
1361   for (int i = 0; i < num_of_entries; i++) {
1362     ModuleClassPathList* module_cpl = module_list->at(i);
1363     Symbol* module_cpl_name = module_cpl->module_name();
1364 
1365     if (module_cpl_name->fast_compare(class_module_name) == 0) {
1366       // Class' module has been located.
1367       return module_cpl->module_first_entry();
1368     }
1369   }
1370   return NULL;
1371 }
1372 
1373 
1374 // Search either the patch-module or exploded build entries for class.
1375 ClassFileStream* ClassLoader::search_module_entries(const GrowableArray<ModuleClassPathList*>* const module_list,
1376                                                     const char* const class_name,
1377                                                     const char* const file_name,
1378                                                     TRAPS) {
1379   ClassFileStream* stream = NULL;
1380 
1381   // Find the class' defining module in the boot loader's module entry table
1382   PackageEntry* pkg_entry = get_package_entry(class_name, ClassLoaderData::the_null_class_loader_data(), CHECK_NULL);
1383   ModuleEntry* mod_entry = (pkg_entry != NULL) ? pkg_entry->module() : NULL;
1384 
1385   // If the module system has not defined java.base yet, then
1386   // classes loaded are assumed to be defined to java.base.
1387   // When java.base is eventually defined by the module system,
1388   // all packages of classes that have been previously loaded
1389   // are verified in ModuleEntryTable::verify_javabase_packages().
1390   if (!Universe::is_module_initialized() &&
1391       !ModuleEntryTable::javabase_defined() &&
1392       mod_entry == NULL) {
1393     mod_entry = ModuleEntryTable::javabase_moduleEntry();
1394   }
1395 
1396   // The module must be a named module
1397   ClassPathEntry* e = NULL;
1398   if (mod_entry != NULL && mod_entry->is_named()) {
1399     if (module_list == _exploded_entries) {
1400       // The exploded build entries can be added to at any time so a lock is
1401       // needed when searching them.
1402       assert(!ClassLoader::has_jrt_entry(), "Must be exploded build");
1403       MutexLocker ml(Module_lock, THREAD);
1404       e = find_first_module_cpe(mod_entry, module_list);
1405     } else {
1406       e = find_first_module_cpe(mod_entry, module_list);
1407     }
1408   }
1409 
1410   // Try to load the class from the module's ClassPathEntry list.
1411   while (e != NULL) {
1412     stream = e->open_stream(file_name, CHECK_NULL);
1413     // No context.check is required since CDS is not supported
1414     // for an exploded modules build or if --patch-module is specified.
1415     if (NULL != stream) {
1416       return stream;
1417     }
1418     e = e->next();
1419   }
1420   // If the module was located, break out even if the class was not
1421   // located successfully from that module's ClassPathEntry list.
1422   // There will not be another valid entry for that module.
1423   return NULL;
1424 }
1425 
1426 InstanceKlass* ClassLoader::load_class(Symbol* name, bool search_append_only, TRAPS) {
1427   assert(name != NULL, "invariant");
1428   assert(THREAD->is_Java_thread(), "must be a JavaThread");
1429 
1430   ResourceMark rm(THREAD);
1431   HandleMark hm(THREAD);
1432 
1433   const char* const class_name = name->as_C_string();
1434 
1435   EventMark m("loading class %s", class_name);
1436   ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion);
1437 
1438   const char* const file_name = file_name_for_class_name(class_name,
1439                                                          name->utf8_length());
1440   assert(file_name != NULL, "invariant");
1441 
1442   ClassLoaderExt::Context context(class_name, file_name, THREAD);
1443 
1444   // Lookup stream for parsing .class file
1445   ClassFileStream* stream = NULL;
1446   s2 classpath_index = 0;
1447   ClassPathEntry* e = NULL;
1448 
1449   // If DumpSharedSpaces is true boot loader visibility boundaries are set to:
1450   //   - [jimage] + [_first_append_entry to _last_append_entry] (all path entries).
1451   //
1452   // If search_append_only is true, boot loader visibility boundaries are
1453   // set to be _first_append_entry to the end. This includes:
1454   //   [-Xbootclasspath/a]; [jvmti appended entries]
1455   //
1456   // If both DumpSharedSpaces and search_append_only are false, boot loader
1457   // visibility boundaries are set to be the --patch-module entries plus the base piece.
1458   // This would include:
1459   //   [--patch-module=<module>=<file>(<pathsep><file>)*]; [jimage | exploded module build]
1460   //
1461   // DumpSharedSpaces and search_append_only are mutually exclusive and cannot
1462   // be true at the same time.
1463   assert(!(DumpSharedSpaces && search_append_only), "DumpSharedSpaces and search_append_only are both true");
1464 
1465   // Load Attempt #1: --patch-module
1466   // Determine the class' defining module.  If it appears in the _patch_mod_entries,
1467   // attempt to load the class from those locations specific to the module.
1468   // Specifications to --patch-module can contain a partial number of classes
1469   // that are part of the overall module definition.  So if a particular class is not
1470   // found within its module specification, the search should continue to Load Attempt #2.
1471   // Note: The --patch-module entries are never searched if the boot loader's
1472   //       visibility boundary is limited to only searching the append entries.
1473   if (_patch_mod_entries != NULL && !search_append_only) {
1474     // At CDS dump time, the --patch-module entries are ignored. That means a
1475     // class is still loaded from the runtime image even if it might
1476     // appear in the _patch_mod_entries. The runtime shared class visibility
1477     // check will determine if a shared class is visible based on the runtime
1478     // environemnt, including the runtime --patch-module setting.
1479     if (!DumpSharedSpaces) {
1480       stream = search_module_entries(_patch_mod_entries, class_name, file_name, CHECK_NULL);
1481     }
1482   }
1483 
1484   // Load Attempt #2: [jimage | exploded build]
1485   if (!search_append_only && (NULL == stream)) {
1486     if (has_jrt_entry()) {
1487       e = _jrt_entry;
1488       stream = _jrt_entry->open_stream(file_name, CHECK_NULL);
1489       if (!context.check(stream, classpath_index)) {
1490         return NULL;
1491       }
1492     } else {
1493       // Exploded build - attempt to locate class in its defining module's location.
1494       assert(_exploded_entries != NULL, "No exploded build entries present");
1495       stream = search_module_entries(_exploded_entries, class_name, file_name, CHECK_NULL);
1496     }
1497   }
1498 
1499   // Load Attempt #3: [-Xbootclasspath/a]; [jvmti appended entries]
1500   if ((search_append_only || DumpSharedSpaces) && (NULL == stream)) {
1501     // For the boot loader append path search, the starting classpath_index
1502     // for the appended piece is always 1 to account for either the
1503     // _jrt_entry or the _exploded_entries.
1504     assert(classpath_index == 0, "The classpath_index has been incremented incorrectly");
1505     classpath_index = 1;
1506 
1507     e = _first_append_entry;
1508     while (e != NULL) {
1509       stream = e->open_stream(file_name, CHECK_NULL);
1510       if (!context.check(stream, classpath_index)) {
1511         return NULL;
1512       }
1513       if (NULL != stream) {
1514         break;
1515       }
1516       e = e->next();
1517       ++classpath_index;
1518     }
1519   }
1520 
1521   if (NULL == stream) {
1522     if (DumpSharedSpaces) {
1523       tty->print_cr("Preload Warning: Cannot find %s", class_name);
1524     }
1525     return NULL;
1526   }
1527 
1528   stream->set_verify(context.should_verify(classpath_index));
1529 
1530   ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
1531   Handle protection_domain;
1532 
1533   InstanceKlass* result = KlassFactory::create_from_stream(stream,
1534                                                            name,
1535                                                            loader_data,
1536                                                            protection_domain,
1537                                                            NULL, // host_klass
1538                                                            NULL, // cp_patches
1539                                                            THREAD);
1540   if (HAS_PENDING_EXCEPTION) {
1541     if (DumpSharedSpaces) {
1542       tty->print_cr("Preload Error: Failed to load %s", class_name);
1543     }
1544     return NULL;
1545   }
1546 
1547   return context.record_result(name, e, classpath_index, result, THREAD);
1548 }
1549 
1550 // Initialize the class loader's access to methods in libzip.  Parse and
1551 // process the boot classpath into a list ClassPathEntry objects.  Once
1552 // this list has been created, it must not change order (see class PackageInfo)
1553 // it can be appended to and is by jvmti and the kernel vm.
1554 
1555 void ClassLoader::initialize() {
1556   EXCEPTION_MARK;
1557 
1558   if (UsePerfData) {
1559     // jvmstat performance counters
1560     NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");
1561     NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");
1562     NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");
1563     NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");
1564     NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");
1565     NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");
1566     NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");
1567     NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");
1568     NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");
1569     NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");
1570 
1571     NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime");
1572     NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self");
1573     NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime");
1574     NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");
1575     NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");
1576     NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");
1577     NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");
1578     NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");
1579     NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");
1580     NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");
1581     NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");
1582     NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");
1583     NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");
1584 
1585 
1586     // The following performance counters are added for measuring the impact
1587     // of the bug fix of 6365597. They are mainly focused on finding out
1588     // the behavior of system & user-defined classloader lock, whether
1589     // ClassLoader.loadClass/findClass is being called synchronized or not.
1590     // Also two additional counters are created to see whether 'UnsyncloadClass'
1591     // flag is being set or not and how many times load_instance_class call
1592     // fails with linkageError etc.
1593     NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS,
1594                         "systemLoaderLockContentionRate");
1595     NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS,
1596                         "nonSystemLoaderLockContentionRate");
1597     NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS,
1598                         "jvmFindLoadedClassNoLockCalls");
1599     NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS,
1600                         "jvmDefineClassNoLockCalls");
1601 
1602     NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS,
1603                         "jniDefineClassNoLockCalls");
1604 
1605     NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS,
1606                         "unsafeDefineClassCalls");
1607 
1608     NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet");
1609     NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS,
1610                         "loadInstanceClassFailRate");
1611 
1612     // increment the isUnsyncloadClass counter if UnsyncloadClass is set.
1613     if (UnsyncloadClass) {
1614       _isUnsyncloadClass->inc();
1615     }
1616   }
1617 
1618   // lookup zip library entry points
1619   load_zip_library();
1620   // lookup jimage library entry points
1621   load_jimage_library();
1622 #if INCLUDE_CDS
1623   // initialize search path
1624   if (DumpSharedSpaces) {
1625     _shared_paths_misc_info = SharedClassUtil::allocate_shared_paths_misc_info();
1626   }
1627 #endif
1628   setup_bootstrap_search_path();
1629 }
1630 
1631 #if INCLUDE_CDS
1632 void ClassLoader::initialize_shared_path() {
1633   if (DumpSharedSpaces) {
1634     ClassLoaderExt::setup_search_paths();
1635     _shared_paths_misc_info->write_jint(0); // see comments in SharedPathsMiscInfo::check()
1636   }
1637 }
1638 #endif
1639 
1640 jlong ClassLoader::classloader_time_ms() {
1641   return UsePerfData ?
1642     Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;
1643 }
1644 
1645 jlong ClassLoader::class_init_count() {
1646   return UsePerfData ? _perf_classes_inited->get_value() : -1;
1647 }
1648 
1649 jlong ClassLoader::class_init_time_ms() {
1650   return UsePerfData ?
1651     Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;
1652 }
1653 
1654 jlong ClassLoader::class_verify_time_ms() {
1655   return UsePerfData ?
1656     Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;
1657 }
1658 
1659 jlong ClassLoader::class_link_count() {
1660   return UsePerfData ? _perf_classes_linked->get_value() : -1;
1661 }
1662 
1663 jlong ClassLoader::class_link_time_ms() {
1664   return UsePerfData ?
1665     Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;
1666 }
1667 
1668 int ClassLoader::compute_Object_vtable() {
1669   // hardwired for JDK1.2 -- would need to duplicate class file parsing
1670   // code to determine actual value from file
1671   // Would be value '11' if finals were in vtable
1672   int JDK_1_2_Object_vtable_size = 5;
1673   return JDK_1_2_Object_vtable_size * vtableEntry::size();
1674 }
1675 
1676 
1677 void classLoader_init1() {
1678   ClassLoader::initialize();
1679 }
1680 
1681 // Complete the ClassPathEntry setup for the boot loader
1682 void ClassLoader::classLoader_init2(TRAPS) {
1683   // Setup the list of module/path pairs for --patch-module processing
1684   // This must be done after the SymbolTable is created in order
1685   // to use fast_compare on module names instead of a string compare.
1686   if (Arguments::get_patch_mod_prefix() != NULL) {
1687     setup_patch_mod_entries();
1688   }
1689 
1690   // Create the ModuleEntry for java.base (must occur after setup_patch_mod_entries
1691   // to successfully determine if java.base has been patched)
1692   create_javabase();
1693 
1694   // Setup the initial java.base/path pair for the exploded build entries.
1695   // As more modules are defined during module system initialization, more
1696   // entries will be added to the exploded build array.
1697   if (!has_jrt_entry()) {
1698     assert(!DumpSharedSpaces, "DumpSharedSpaces not supported with exploded module builds");
1699     assert(!UseSharedSpaces, "UsedSharedSpaces not supported with exploded module builds");
1700     // Set up the boot loader's _exploded_entries list.  Note that this gets
1701     // done before loading any classes, by the same thread that will
1702     // subsequently do the first class load. So, no lock is needed for this.
1703     assert(_exploded_entries == NULL, "Should only get initialized once");
1704     _exploded_entries = new (ResourceObj::C_HEAP, mtModule)
1705       GrowableArray<ModuleClassPathList*>(EXPLODED_ENTRY_SIZE, true);
1706     add_to_exploded_build_list(vmSymbols::java_base(), CHECK);
1707   }
1708 }
1709 
1710 
1711 bool ClassLoader::get_canonical_path(const char* orig, char* out, int len) {
1712   assert(orig != NULL && out != NULL && len > 0, "bad arguments");
1713   if (CanonicalizeEntry != NULL) {
1714     JavaThread* THREAD = JavaThread::current();
1715     JNIEnv* env = THREAD->jni_environment();
1716     ResourceMark rm(THREAD);
1717 
1718     // os::native_path writes into orig_copy
1719     char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(orig)+1);
1720     strcpy(orig_copy, orig);
1721     if ((CanonicalizeEntry)(env, os::native_path(orig_copy), out, len) < 0) {
1722       return false;
1723     }
1724   } else {
1725     // On JDK 1.2.2 the Canonicalize does not exist, so just do nothing
1726     strncpy(out, orig, len);
1727     out[len - 1] = '\0';
1728   }
1729   return true;
1730 }
1731 
1732 void ClassLoader::create_javabase() {
1733   Thread* THREAD = Thread::current();
1734 
1735   // Create java.base's module entry for the boot
1736   // class loader prior to loading j.l.Ojbect.
1737   ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
1738 
1739   // Get module entry table
1740   ModuleEntryTable* null_cld_modules = null_cld->modules();
1741   if (null_cld_modules == NULL) {
1742     vm_exit_during_initialization("No ModuleEntryTable for the boot class loader");
1743   }
1744 
1745   {
1746     MutexLocker ml(Module_lock, THREAD);
1747     ModuleEntry* jb_module = null_cld_modules->locked_create_entry_or_null(Handle(),
1748                                false, vmSymbols::java_base(), NULL, NULL, null_cld);
1749     if (jb_module == NULL) {
1750       vm_exit_during_initialization("Unable to create ModuleEntry for " JAVA_BASE_NAME);
1751     }
1752     ModuleEntryTable::set_javabase_moduleEntry(jb_module);
1753   }
1754 }
1755 
1756 #ifndef PRODUCT
1757 
1758 // CompileTheWorld
1759 //
1760 // Iterates over all class path entries and forces compilation of all methods
1761 // in all classes found. Currently, only zip/jar archives are searched.
1762 //
1763 // The classes are loaded by the Java level bootstrap class loader, and the
1764 // initializer is called. If DelayCompilationDuringStartup is true (default),
1765 // the interpreter will run the initialization code. Note that forcing
1766 // initialization in this way could potentially lead to initialization order
1767 // problems, in which case we could just force the initialization bit to be set.
1768 
1769 
1770 // We need to iterate over the contents of a zip/jar file, so we replicate the
1771 // jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile,
1772 // since jzfile already has a void* definition.
1773 //
1774 // Note that this is only used in debug mode.
1775 //
1776 // HotSpot integration note:
1777 // Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build
1778 
1779 
1780 // JDK 1.3 version
1781 typedef struct real_jzentry {         /* Zip file entry */
1782     char *name;                 /* entry name */
1783     jint time;                  /* modification time */
1784     jint size;                  /* size of uncompressed data */
1785     jint csize;                 /* size of compressed data (zero if uncompressed) */
1786     jint crc;                   /* crc of uncompressed data */
1787     char *comment;              /* optional zip file comment */
1788     jbyte *extra;               /* optional extra data */
1789     jint pos;                   /* position of LOC header (if negative) or data */
1790 } real_jzentry;
1791 
1792 typedef struct real_jzfile {  /* Zip file */
1793     char *name;                 /* zip file name */
1794     jint refs;                  /* number of active references */
1795     jint fd;                    /* open file descriptor */
1796     void *lock;                 /* read lock */
1797     char *comment;              /* zip file comment */
1798     char *msg;                  /* zip error message */
1799     void *entries;              /* array of hash cells */
1800     jint total;                 /* total number of entries */
1801     unsigned short *table;      /* Hash chain heads: indexes into entries */
1802     jint tablelen;              /* number of hash eads */
1803     real_jzfile *next;        /* next zip file in search list */
1804     jzentry *cache;             /* we cache the most recently freed jzentry */
1805     /* Information on metadata names in META-INF directory */
1806     char **metanames;           /* array of meta names (may have null names) */
1807     jint metacount;             /* number of slots in metanames array */
1808     /* If there are any per-entry comments, they are in the comments array */
1809     char **comments;
1810 } real_jzfile;
1811 
1812 void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {
1813   // For now we only compile all methods in all classes in zip/jar files
1814   tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);
1815   tty->cr();
1816 }
1817 
1818 void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {
1819   real_jzfile* zip = (real_jzfile*) _zip;
1820   tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
1821   tty->cr();
1822   // Iterate over all entries in zip file
1823   for (int n = 0; ; n++) {
1824     real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n));
1825     if (ze == NULL) break;
1826     ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
1827   }
1828   if (HAS_PENDING_EXCEPTION) {
1829     if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1830       CLEAR_PENDING_EXCEPTION;
1831       tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
1832       tty->print_cr("Increase class metadata storage if a limit was set");
1833     } else {
1834       tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
1835     }
1836   }
1837 }
1838 
1839 void ClassLoader::compile_the_world() {
1840   EXCEPTION_MARK;
1841   HandleMark hm(THREAD);
1842   ResourceMark rm(THREAD);
1843 
1844   assert(has_jrt_entry(), "Compile The World not supported with exploded module build");
1845 
1846   // Find bootstrap loader
1847   Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
1848   jlong start = os::javaTimeMillis();
1849 
1850   // Compile the world for the modular java runtime image
1851   _jrt_entry->compile_the_world(system_class_loader, CATCH);
1852 
1853   // Iterate over all bootstrap class path appended entries
1854   ClassPathEntry* e = _first_append_entry;
1855   while (e != NULL) {
1856     assert(!e->is_jrt(), "A modular java runtime image is present on the list of appended entries");
1857     e->compile_the_world(system_class_loader, CATCH);
1858     e = e->next();
1859   }
1860   jlong end = os::javaTimeMillis();
1861   tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)",
1862                 _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));
1863   {
1864     // Print statistics as if before normal exit:
1865     extern void print_statistics();
1866     print_statistics();
1867   }
1868   vm_exit(0);
1869 }
1870 
1871 int ClassLoader::_compile_the_world_class_counter = 0;
1872 int ClassLoader::_compile_the_world_method_counter = 0;
1873 static int _codecache_sweep_counter = 0;
1874 
1875 // Filter out all exceptions except OOMs
1876 static void clear_pending_exception_if_not_oom(TRAPS) {
1877   if (HAS_PENDING_EXCEPTION &&
1878       !PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1879     CLEAR_PENDING_EXCEPTION;
1880   }
1881   // The CHECK at the caller will propagate the exception out
1882 }
1883 
1884 /**
1885  * Returns if the given method should be compiled when doing compile-the-world.
1886  *
1887  * TODO:  This should be a private method in a CompileTheWorld class.
1888  */
1889 static bool can_be_compiled(methodHandle m, int comp_level) {
1890   assert(CompileTheWorld, "must be");
1891 
1892   // It's not valid to compile a native wrapper for MethodHandle methods
1893   // that take a MemberName appendix since the bytecode signature is not
1894   // correct.
1895   vmIntrinsics::ID iid = m->intrinsic_id();
1896   if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) {
1897     return false;
1898   }
1899 
1900   return CompilationPolicy::can_be_compiled(m, comp_level);
1901 }
1902 
1903 void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {
1904   if (string_ends_with(name, ".class")) {
1905     // We have a .class file
1906     int len = (int)strlen(name);
1907     char buffer[2048];
1908     strncpy(buffer, name, len - 6);
1909     buffer[len-6] = 0;
1910     // If the file has a period after removing .class, it's not really a
1911     // valid class file.  The class loader will check everything else.
1912     if (strchr(buffer, '.') == NULL) {
1913       _compile_the_world_class_counter++;
1914       if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;
1915 
1916       // Construct name without extension
1917       TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
1918       // Use loader to load and initialize class
1919       Klass* k = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);
1920       if (k != NULL && !HAS_PENDING_EXCEPTION) {
1921         k->initialize(THREAD);
1922       }
1923       bool exception_occurred = HAS_PENDING_EXCEPTION;
1924       clear_pending_exception_if_not_oom(CHECK);
1925       if (CompileTheWorldPreloadClasses && k != NULL) {
1926         InstanceKlass* ik = InstanceKlass::cast(k);
1927         ConstantPool::preload_and_initialize_all_classes(ik->constants(), THREAD);
1928         if (HAS_PENDING_EXCEPTION) {
1929           // If something went wrong in preloading we just ignore it
1930           clear_pending_exception_if_not_oom(CHECK);
1931           tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer);
1932         }
1933       }
1934 
1935       if (_compile_the_world_class_counter >= CompileTheWorldStartAt) {
1936         if (k == NULL || exception_occurred) {
1937           // If something went wrong (e.g. ExceptionInInitializerError) we skip this class
1938           tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer);
1939         } else {
1940           tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer);
1941           // Preload all classes to get around uncommon traps
1942           // Iterate over all methods in class
1943           int comp_level = CompilationPolicy::policy()->initial_compile_level();
1944           InstanceKlass* ik = InstanceKlass::cast(k);
1945           for (int n = 0; n < ik->methods()->length(); n++) {
1946             methodHandle m (THREAD, ik->methods()->at(n));
1947             if (can_be_compiled(m, comp_level)) {
1948               if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) {
1949                 // Give sweeper a chance to keep up with CTW
1950                 VM_CTWThreshold op;
1951                 VMThread::execute(&op);
1952                 _codecache_sweep_counter = 0;
1953               }
1954               // Force compilation
1955               CompileBroker::compile_method(m, InvocationEntryBci, comp_level,
1956                                             methodHandle(), 0, CompileTask::Reason_CTW, THREAD);
1957               if (HAS_PENDING_EXCEPTION) {
1958                 clear_pending_exception_if_not_oom(CHECK);
1959                 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1960               } else {
1961                 _compile_the_world_method_counter++;
1962               }
1963               if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) {
1964                 // Clobber the first compile and force second tier compilation
1965                 CompiledMethod* nm = m->code();
1966                 if (nm != NULL && !m->is_method_handle_intrinsic()) {
1967                   // Throw out the code so that the code cache doesn't fill up
1968                   nm->make_not_entrant();
1969                 }
1970                 CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization,
1971                                               methodHandle(), 0, CompileTask::Reason_CTW, THREAD);
1972                 if (HAS_PENDING_EXCEPTION) {
1973                   clear_pending_exception_if_not_oom(CHECK);
1974                   tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1975                 } else {
1976                   _compile_the_world_method_counter++;
1977                 }
1978               }
1979             } else {
1980               tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1981             }
1982 
1983             CompiledMethod* nm = m->code();
1984             if (nm != NULL && !m->is_method_handle_intrinsic()) {
1985               // Throw out the code so that the code cache doesn't fill up
1986               nm->make_not_entrant();
1987             }
1988           }
1989         }
1990       }
1991     }
1992   }
1993 }
1994 
1995 #endif //PRODUCT
1996 
1997 // Please keep following two functions at end of this file. With them placed at top or in middle of the file,
1998 // they could get inlined by agressive compiler, an unknown trick, see bug 6966589.
1999 void PerfClassTraceTime::initialize() {
2000   if (!UsePerfData) return;
2001 
2002   if (_eventp != NULL) {
2003     // increment the event counter
2004     _eventp->inc();
2005   }
2006 
2007   // stop the current active thread-local timer to measure inclusive time
2008   _prev_active_event = -1;
2009   for (int i=0; i < EVENT_TYPE_COUNT; i++) {
2010      if (_timers[i].is_active()) {
2011        assert(_prev_active_event == -1, "should have only one active timer");
2012        _prev_active_event = i;
2013        _timers[i].stop();
2014      }
2015   }
2016 
2017   if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) {
2018     // start the inclusive timer if not recursively called
2019     _t.start();
2020   }
2021 
2022   // start thread-local timer of the given event type
2023    if (!_timers[_event_type].is_active()) {
2024     _timers[_event_type].start();
2025   }
2026 }
2027 
2028 PerfClassTraceTime::~PerfClassTraceTime() {
2029   if (!UsePerfData) return;
2030 
2031   // stop the thread-local timer as the event completes
2032   // and resume the thread-local timer of the event next on the stack
2033   _timers[_event_type].stop();
2034   jlong selftime = _timers[_event_type].ticks();
2035 
2036   if (_prev_active_event >= 0) {
2037     _timers[_prev_active_event].start();
2038   }
2039 
2040   if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return;
2041 
2042   // increment the counters only on the leaf call
2043   _t.stop();
2044   _timep->inc(_t.ticks());
2045   if (_selftimep != NULL) {
2046     _selftimep->inc(selftime);
2047   }
2048   // add all class loading related event selftime to the accumulated time counter
2049   ClassLoader::perf_accumulated_time()->inc(selftime);
2050 
2051   // reset the timer
2052   _timers[_event_type].reset();
2053 }