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