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