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