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