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