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