1 /* 2 * Copyright (c) 1997, 2017, 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 "classfile/classFileStream.hpp" 27 #include "classfile/classLoader.hpp" 28 #include "classfile/classLoaderData.inline.hpp" 29 #include "classfile/classLoaderExt.hpp" 30 #include "classfile/javaClasses.hpp" 31 #include "classfile/jimage.hpp" 32 #include "classfile/moduleEntry.hpp" 33 #include "classfile/modules.hpp" 34 #include "classfile/packageEntry.hpp" 35 #include "classfile/klassFactory.hpp" 36 #include "classfile/systemDictionary.hpp" 37 #include "classfile/vmSymbols.hpp" 38 #include "compiler/compileBroker.hpp" 39 #include "gc/shared/collectedHeap.inline.hpp" 40 #include "gc/shared/generation.hpp" 41 #include "interpreter/bytecodeStream.hpp" 42 #include "interpreter/oopMapCache.hpp" 43 #include "logging/logTag.hpp" 44 #include "memory/allocation.inline.hpp" 45 #include "memory/filemap.hpp" 46 #include "memory/oopFactory.hpp" 47 #include "memory/resourceArea.hpp" 48 #include "memory/universe.inline.hpp" 49 #include "oops/instanceKlass.hpp" 50 #include "oops/instanceRefKlass.hpp" 51 #include "oops/objArrayOop.inline.hpp" 52 #include "oops/oop.inline.hpp" 53 #include "oops/symbol.hpp" 54 #include "prims/jvm_misc.hpp" 55 #include "runtime/arguments.hpp" 56 #include "runtime/compilationPolicy.hpp" 57 #include "runtime/fprofiler.hpp" 58 #include "runtime/handles.hpp" 59 #include "runtime/handles.inline.hpp" 60 #include "runtime/init.hpp" 61 #include "runtime/interfaceSupport.hpp" 62 #include "runtime/java.hpp" 63 #include "runtime/javaCalls.hpp" 64 #include "runtime/os.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/sharedClassUtil.hpp" 75 #include "classfile/sharedPathsMiscInfo.hpp" 76 #endif 77 78 // Entry points in zip.dll for loading zip/jar file entries 79 80 typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg); 81 typedef void (JNICALL *ZipClose_t)(jzfile *zip); 82 typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen); 83 typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf); 84 typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n); 85 typedef jboolean (JNICALL *ZipInflateFully_t)(void *inBuf, jlong inLen, void *outBuf, jlong outLen, char **pmsg); 86 typedef jint (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len); 87 88 static ZipOpen_t ZipOpen = NULL; 89 static ZipClose_t ZipClose = NULL; 90 static FindEntry_t FindEntry = NULL; 91 static ReadEntry_t ReadEntry = NULL; 92 static GetNextEntry_t GetNextEntry = NULL; 93 static canonicalize_fn_t CanonicalizeEntry = NULL; 94 static ZipInflateFully_t ZipInflateFully = NULL; 95 static Crc32_t Crc32 = NULL; 96 97 // Entry points for jimage.dll for loading jimage file entries 98 99 static JImageOpen_t JImageOpen = NULL; 100 static JImageClose_t JImageClose = NULL; 101 static JImagePackageToModule_t JImagePackageToModule = NULL; 102 static JImageFindResource_t JImageFindResource = NULL; 103 static JImageGetResource_t JImageGetResource = NULL; 104 static JImageResourceIterator_t JImageResourceIterator = NULL; 105 static JImage_ResourcePath_t JImageResourcePath = NULL; 106 107 // Globals 108 109 PerfCounter* ClassLoader::_perf_accumulated_time = NULL; 110 PerfCounter* ClassLoader::_perf_classes_inited = NULL; 111 PerfCounter* ClassLoader::_perf_class_init_time = NULL; 112 PerfCounter* ClassLoader::_perf_class_init_selftime = NULL; 113 PerfCounter* ClassLoader::_perf_classes_verified = NULL; 114 PerfCounter* ClassLoader::_perf_class_verify_time = NULL; 115 PerfCounter* ClassLoader::_perf_class_verify_selftime = NULL; 116 PerfCounter* ClassLoader::_perf_classes_linked = NULL; 117 PerfCounter* ClassLoader::_perf_class_link_time = NULL; 118 PerfCounter* ClassLoader::_perf_class_link_selftime = NULL; 119 PerfCounter* ClassLoader::_perf_class_parse_time = NULL; 120 PerfCounter* ClassLoader::_perf_class_parse_selftime = NULL; 121 PerfCounter* ClassLoader::_perf_sys_class_lookup_time = NULL; 122 PerfCounter* ClassLoader::_perf_shared_classload_time = NULL; 123 PerfCounter* ClassLoader::_perf_sys_classload_time = NULL; 124 PerfCounter* ClassLoader::_perf_app_classload_time = NULL; 125 PerfCounter* ClassLoader::_perf_app_classload_selftime = NULL; 126 PerfCounter* ClassLoader::_perf_app_classload_count = NULL; 127 PerfCounter* ClassLoader::_perf_define_appclasses = NULL; 128 PerfCounter* ClassLoader::_perf_define_appclass_time = NULL; 129 PerfCounter* ClassLoader::_perf_define_appclass_selftime = NULL; 130 PerfCounter* ClassLoader::_perf_app_classfile_bytes_read = NULL; 131 PerfCounter* ClassLoader::_perf_sys_classfile_bytes_read = NULL; 132 PerfCounter* ClassLoader::_sync_systemLoaderLockContentionRate = NULL; 133 PerfCounter* ClassLoader::_sync_nonSystemLoaderLockContentionRate = NULL; 134 PerfCounter* ClassLoader::_sync_JVMFindLoadedClassLockFreeCounter = NULL; 135 PerfCounter* ClassLoader::_sync_JVMDefineClassLockFreeCounter = NULL; 136 PerfCounter* ClassLoader::_sync_JNIDefineClassLockFreeCounter = NULL; 137 PerfCounter* ClassLoader::_unsafe_defineClassCallCounter = NULL; 138 PerfCounter* ClassLoader::_isUnsyncloadClass = NULL; 139 PerfCounter* ClassLoader::_load_instance_class_failCounter = NULL; 140 141 GrowableArray<ModuleClassPathList*>* ClassLoader::_patch_mod_entries = NULL; 142 GrowableArray<ModuleClassPathList*>* ClassLoader::_exploded_entries = NULL; 143 ClassPathEntry* ClassLoader::_jrt_entry = NULL; 144 ClassPathEntry* ClassLoader::_first_append_entry = NULL; 145 ClassPathEntry* ClassLoader::_last_append_entry = NULL; 146 int ClassLoader::_num_entries = 0; 147 #if INCLUDE_CDS 148 GrowableArray<char*>* ClassLoader::_boot_modules_array = NULL; 149 GrowableArray<char*>* ClassLoader::_platform_modules_array = NULL; 150 SharedPathsMiscInfo* ClassLoader::_shared_paths_misc_info = NULL; 151 #endif 152 153 // helper routines 154 bool string_starts_with(const char* str, const char* str_to_find) { 155 size_t str_len = strlen(str); 156 size_t str_to_find_len = strlen(str_to_find); 157 if (str_to_find_len > str_len) { 158 return false; 159 } 160 return (strncmp(str, str_to_find, str_to_find_len) == 0); 161 } 162 163 static const char* get_jimage_version_string() { 164 static char version_string[10] = ""; 165 if (version_string[0] == '\0') { 166 jio_snprintf(version_string, sizeof(version_string), "%d.%d", 167 Abstract_VM_Version::vm_major_version(), Abstract_VM_Version::vm_minor_version()); 168 } 169 return (const char*)version_string; 170 } 171 172 bool ClassLoader::string_ends_with(const char* str, const char* str_to_find) { 173 size_t str_len = strlen(str); 174 size_t str_to_find_len = strlen(str_to_find); 175 if (str_to_find_len > str_len) { 176 return false; 177 } 178 return (strncmp(str + (str_len - str_to_find_len), str_to_find, str_to_find_len) == 0); 179 } 180 181 // Used to obtain the package name from a fully qualified class name. 182 // It is the responsibility of the caller to establish a ResourceMark. 183 const char* ClassLoader::package_from_name(const char* const class_name, bool* bad_class_name) { 184 if (class_name == NULL) { 185 if (bad_class_name != NULL) { 186 *bad_class_name = true; 187 } 188 return NULL; 189 } 190 191 if (bad_class_name != NULL) { 192 *bad_class_name = false; 193 } 194 195 const char* const last_slash = strrchr(class_name, '/'); 196 if (last_slash == NULL) { 197 // No package name 198 return NULL; 199 } 200 201 char* class_name_ptr = (char*) class_name; 202 // Skip over '['s 203 if (*class_name_ptr == '[') { 204 do { 205 class_name_ptr++; 206 } while (*class_name_ptr == '['); 207 208 // Fully qualified class names should not contain a 'L'. 209 // Set bad_class_name to true to indicate that the package name 210 // could not be obtained due to an error condition. 211 // In this situation, is_same_class_package returns false. 212 if (*class_name_ptr == 'L') { 213 if (bad_class_name != NULL) { 214 *bad_class_name = true; 215 } 216 return NULL; 217 } 218 } 219 220 int length = last_slash - class_name_ptr; 221 222 // A class name could have just the slash character in the name. 223 if (length <= 0) { 224 // No package name 225 if (bad_class_name != NULL) { 226 *bad_class_name = true; 227 } 228 return NULL; 229 } 230 231 // drop name after last slash (including slash) 232 // Ex., "java/lang/String.class" => "java/lang" 233 char* pkg_name = NEW_RESOURCE_ARRAY(char, length + 1); 234 strncpy(pkg_name, class_name_ptr, length); 235 *(pkg_name+length) = '\0'; 236 237 return (const char *)pkg_name; 238 } 239 240 // Given a fully qualified class name, find its defining package in the class loader's 241 // package entry table. 242 static PackageEntry* get_package_entry(const char* class_name, ClassLoaderData* loader_data, TRAPS) { 243 ResourceMark rm(THREAD); 244 const char *pkg_name = ClassLoader::package_from_name(class_name); 245 if (pkg_name == NULL) { 246 return NULL; 247 } 248 PackageEntryTable* pkgEntryTable = loader_data->packages(); 249 TempNewSymbol pkg_symbol = SymbolTable::new_symbol(pkg_name, CHECK_NULL); 250 return pkgEntryTable->lookup_only(pkg_symbol); 251 } 252 253 ClassPathDirEntry::ClassPathDirEntry(const char* dir) : ClassPathEntry() { 254 char* copy = NEW_C_HEAP_ARRAY(char, strlen(dir)+1, mtClass); 255 strcpy(copy, dir); 256 _dir = copy; 257 } 258 259 260 ClassFileStream* ClassPathDirEntry::open_stream(const char* name, TRAPS) { 261 // construct full path name 262 char* path = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, JVM_MAXPATHLEN); 263 if (jio_snprintf(path, JVM_MAXPATHLEN, "%s%s%s", _dir, os::file_separator(), name) == -1) { 264 FREE_RESOURCE_ARRAY(char, path, JVM_MAXPATHLEN); 265 return NULL; 266 } 267 // check if file exists 268 struct stat st; 269 if (os::stat(path, &st) == 0) { 270 #if INCLUDE_CDS 271 if (DumpSharedSpaces) { 272 // We have already check in ClassLoader::check_shared_classpath() that the directory is empty, so 273 // we should never find a file underneath it -- unless user has added a new file while we are running 274 // the dump, in which case let's quit! 275 ShouldNotReachHere(); 276 } 277 #endif 278 // found file, open it 279 int file_handle = os::open(path, 0, 0); 280 if (file_handle != -1) { 281 // read contents into resource array 282 u1* buffer = NEW_RESOURCE_ARRAY(u1, st.st_size); 283 size_t num_read = os::read(file_handle, (char*) buffer, st.st_size); 284 // close file 285 os::close(file_handle); 286 // construct ClassFileStream 287 if (num_read == (size_t)st.st_size) { 288 if (UsePerfData) { 289 ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read); 290 } 291 FREE_RESOURCE_ARRAY(char, path, JVM_MAXPATHLEN); 292 // Resource allocated 293 return new ClassFileStream(buffer, 294 st.st_size, 295 _dir, 296 ClassFileStream::verify); 297 } 298 } 299 } 300 FREE_RESOURCE_ARRAY(char, path, JVM_MAXPATHLEN); 301 return NULL; 302 } 303 304 ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name, bool is_boot_append) : ClassPathEntry() { 305 _zip = zip; 306 char *copy = NEW_C_HEAP_ARRAY(char, strlen(zip_name)+1, mtClass); 307 strcpy(copy, zip_name); 308 _zip_name = copy; 309 _is_boot_append = is_boot_append; 310 _multi_versioned = _unknown; 311 } 312 313 ClassPathZipEntry::~ClassPathZipEntry() { 314 if (ZipClose != NULL) { 315 (*ZipClose)(_zip); 316 } 317 FREE_C_HEAP_ARRAY(char, _zip_name); 318 } 319 320 u1* ClassPathZipEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) { 321 // enable call to C land 322 JavaThread* thread = JavaThread::current(); 323 ThreadToNativeFromVM ttn(thread); 324 // check whether zip archive contains name 325 jint name_len; 326 jzentry* entry = (*FindEntry)(_zip, name, filesize, &name_len); 327 if (entry == NULL) return NULL; 328 u1* buffer; 329 char name_buf[128]; 330 char* filename; 331 if (name_len < 128) { 332 filename = name_buf; 333 } else { 334 filename = NEW_RESOURCE_ARRAY(char, name_len + 1); 335 } 336 337 // read contents into resource array 338 int size = (*filesize) + ((nul_terminate) ? 1 : 0); 339 buffer = NEW_RESOURCE_ARRAY(u1, size); 340 if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL; 341 342 // return result 343 if (nul_terminate) { 344 buffer[*filesize] = 0; 345 } 346 return buffer; 347 } 348 349 #if INCLUDE_CDS 350 u1* ClassPathZipEntry::open_versioned_entry(const char* name, jint* filesize, TRAPS) { 351 u1* buffer = NULL; 352 if (DumpSharedSpaces && !_is_boot_append) { 353 // We presume default is multi-release enabled 354 const char* multi_ver = Arguments::get_property("jdk.util.jar.enableMultiRelease"); 355 const char* verstr = Arguments::get_property("jdk.util.jar.version"); 356 bool is_multi_ver = (multi_ver == NULL || 357 strcmp(multi_ver, "true") == 0 || 358 strcmp(multi_ver, "force") == 0) && 359 is_multiple_versioned(THREAD); 360 // command line version setting 361 int version = 0; 362 const int base_version = 8; // JDK8 363 int cur_ver = JDK_Version::current().major_version(); 364 if (verstr != NULL) { 365 version = atoi(verstr); 366 if (version < base_version || version > cur_ver) { 367 // If the specified version is lower than the base version, the base 368 // entry will be used; if the version is higher than the current 369 // jdk version, the highest versioned entry will be used. 370 if (version < base_version) { 371 is_multi_ver = false; 372 } 373 // print out warning, do not use assertion here since it will continue to look 374 // for proper version. 375 warning("JDK%d is not supported in multiple version jars", version); 376 } 377 } 378 379 if (is_multi_ver) { 380 int n; 381 char* entry_name = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, JVM_MAXPATHLEN); 382 if (version > 0) { 383 n = jio_snprintf(entry_name, JVM_MAXPATHLEN, "META-INF/versions/%d/%s", version, name); 384 entry_name[n] = '\0'; 385 buffer = open_entry((const char*)entry_name, filesize, false, CHECK_NULL); 386 if (buffer == NULL) { 387 warning("Could not find %s in %s, try to find highest version instead", entry_name, _zip_name); 388 } 389 } 390 if (buffer == NULL) { 391 for (int i = cur_ver; i >= base_version; i--) { 392 n = jio_snprintf(entry_name, JVM_MAXPATHLEN, "META-INF/versions/%d/%s", i, name); 393 entry_name[n] = '\0'; 394 buffer = open_entry((const char*)entry_name, filesize, false, CHECK_NULL); 395 if (buffer != NULL) { 396 break; 397 } 398 } 399 } 400 FREE_RESOURCE_ARRAY(char, entry_name, JVM_MAXPATHLEN); 401 } 402 } 403 return buffer; 404 } 405 406 bool ClassPathZipEntry::is_multiple_versioned(TRAPS) { 407 assert(DumpSharedSpaces, "called only at dump time"); 408 if (_multi_versioned != _unknown) { 409 return (_multi_versioned == _yes) ? true : false; 410 } 411 jint size; 412 char* buffer = (char*)open_entry("META-INF/MANIFEST.MF", &size, true, CHECK_false); 413 if (buffer != NULL) { 414 char* p = buffer; 415 for ( ; *p; ++p) *p = tolower(*p); 416 if (strstr(buffer, "multi-release: true") != NULL) { 417 _multi_versioned = _yes; 418 return true; 419 } 420 } 421 _multi_versioned = _no; 422 return false; 423 } 424 #endif // INCLUDE_CDS 425 426 ClassFileStream* ClassPathZipEntry::open_stream(const char* name, TRAPS) { 427 jint filesize; 428 u1* buffer = open_versioned_entry(name, &filesize, CHECK_NULL); 429 if (buffer == NULL) { 430 buffer = open_entry(name, &filesize, false, CHECK_NULL); 431 if (buffer == NULL) { 432 return NULL; 433 } 434 } 435 if (UsePerfData) { 436 ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize); 437 } 438 // Resource allocated 439 return new ClassFileStream(buffer, 440 filesize, 441 _zip_name, 442 ClassFileStream::verify); 443 } 444 445 // invoke function for each entry in the zip file 446 void ClassPathZipEntry::contents_do(void f(const char* name, void* context), void* context) { 447 JavaThread* thread = JavaThread::current(); 448 HandleMark handle_mark(thread); 449 ThreadToNativeFromVM ttn(thread); 450 for (int n = 0; ; n++) { 451 jzentry * ze = ((*GetNextEntry)(_zip, n)); 452 if (ze == NULL) break; 453 (*f)(ze->name, context); 454 } 455 } 456 457 ClassPathImageEntry::ClassPathImageEntry(JImageFile* jimage, const char* name) : 458 ClassPathEntry(), 459 _jimage(jimage) { 460 guarantee(jimage != NULL, "jimage file is null"); 461 guarantee(name != NULL, "jimage file name is null"); 462 size_t len = strlen(name) + 1; 463 _name = NEW_C_HEAP_ARRAY(const char, len, mtClass); 464 strncpy((char *)_name, name, len); 465 } 466 467 ClassPathImageEntry::~ClassPathImageEntry() { 468 if (_name != NULL) { 469 FREE_C_HEAP_ARRAY(const char, _name); 470 _name = NULL; 471 } 472 if (_jimage != NULL) { 473 (*JImageClose)(_jimage); 474 _jimage = NULL; 475 } 476 } 477 478 // For a class in a named module, look it up in the jimage file using this syntax: 479 // /<module-name>/<package-name>/<base-class> 480 // 481 // Assumptions: 482 // 1. There are no unnamed modules in the jimage file. 483 // 2. A package is in at most one module in the jimage file. 484 // 485 ClassFileStream* ClassPathImageEntry::open_stream(const char* name, TRAPS) { 486 jlong size; 487 JImageLocationRef location = (*JImageFindResource)(_jimage, "", get_jimage_version_string(), name, &size); 488 489 if (location == 0) { 490 ResourceMark rm; 491 const char* pkg_name = ClassLoader::package_from_name(name); 492 493 if (pkg_name != NULL) { 494 if (!Universe::is_module_initialized()) { 495 location = (*JImageFindResource)(_jimage, JAVA_BASE_NAME, get_jimage_version_string(), name, &size); 496 #if INCLUDE_CDS 497 // CDS uses the boot class loader to load classes whose packages are in 498 // modules defined for other class loaders. So, for now, get their module 499 // names from the "modules" jimage file. 500 if (DumpSharedSpaces && location == 0) { 501 const char* module_name = (*JImagePackageToModule)(_jimage, pkg_name); 502 if (module_name != NULL) { 503 location = (*JImageFindResource)(_jimage, module_name, get_jimage_version_string(), name, &size); 504 } 505 } 506 #endif 507 508 } else { 509 PackageEntry* package_entry = get_package_entry(name, ClassLoaderData::the_null_class_loader_data(), CHECK_NULL); 510 if (package_entry != NULL) { 511 ResourceMark rm; 512 // Get the module name 513 ModuleEntry* module = package_entry->module(); 514 assert(module != NULL, "Boot classLoader package missing module"); 515 assert(module->is_named(), "Boot classLoader package is in unnamed module"); 516 const char* module_name = module->name()->as_C_string(); 517 if (module_name != NULL) { 518 location = (*JImageFindResource)(_jimage, module_name, get_jimage_version_string(), name, &size); 519 } 520 } 521 } 522 } 523 } 524 if (location != 0) { 525 if (UsePerfData) { 526 ClassLoader::perf_sys_classfile_bytes_read()->inc(size); 527 } 528 char* data = NEW_RESOURCE_ARRAY(char, size); 529 (*JImageGetResource)(_jimage, location, data, size); 530 // Resource allocated 531 return new ClassFileStream((u1*)data, 532 (int)size, 533 _name, 534 ClassFileStream::verify); 535 } 536 537 return NULL; 538 } 539 540 #ifndef PRODUCT 541 bool ctw_visitor(JImageFile* jimage, 542 const char* module_name, const char* version, const char* package, 543 const char* name, const char* extension, void* arg) { 544 if (strcmp(extension, "class") == 0) { 545 Thread* THREAD = Thread::current(); 546 ResourceMark rm(THREAD); 547 char* path = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, JIMAGE_MAX_PATH); 548 jio_snprintf(path, JIMAGE_MAX_PATH - 1, "%s/%s.class", package, name); 549 ClassLoader::compile_the_world_in(path, *(Handle*)arg, THREAD); 550 return !HAS_PENDING_EXCEPTION; 551 } 552 return true; 553 } 554 555 void ClassPathImageEntry::compile_the_world(Handle loader, TRAPS) { 556 tty->print_cr("CompileTheWorld : Compiling all classes in %s", name()); 557 tty->cr(); 558 (*JImageResourceIterator)(_jimage, (JImageResourceVisitor_t)ctw_visitor, (void *)&loader); 559 if (HAS_PENDING_EXCEPTION) { 560 if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) { 561 CLEAR_PENDING_EXCEPTION; 562 tty->print_cr("\nCompileTheWorld : Ran out of memory\n"); 563 tty->print_cr("Increase class metadata storage if a limit was set"); 564 } else { 565 tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n"); 566 } 567 } 568 } 569 #endif 570 571 bool ClassPathImageEntry::is_jrt() { 572 return ClassLoader::is_jrt(name()); 573 } 574 575 #if INCLUDE_CDS 576 void ClassLoader::exit_with_path_failure(const char* error, const char* message) { 577 assert(DumpSharedSpaces, "only called at dump time"); 578 tty->print_cr("Hint: enable -Xlog:class+path=info to diagnose the failure"); 579 vm_exit_during_initialization(error, message); 580 } 581 #endif 582 583 ModuleClassPathList::ModuleClassPathList(Symbol* module_name) { 584 _module_name = module_name; 585 _module_first_entry = NULL; 586 _module_last_entry = NULL; 587 } 588 589 ModuleClassPathList::~ModuleClassPathList() { 590 // Clean out each ClassPathEntry on list 591 ClassPathEntry* e = _module_first_entry; 592 while (e != NULL) { 593 ClassPathEntry* next_entry = e->next(); 594 delete e; 595 e = next_entry; 596 } 597 } 598 599 void ModuleClassPathList::add_to_list(ClassPathEntry* new_entry) { 600 if (new_entry != NULL) { 601 if (_module_last_entry == NULL) { 602 _module_first_entry = _module_last_entry = new_entry; 603 } else { 604 _module_last_entry->set_next(new_entry); 605 _module_last_entry = new_entry; 606 } 607 } 608 } 609 610 void ClassLoader::trace_class_path(const char* msg, const char* name) { 611 if (log_is_enabled(Info, class, path)) { 612 ResourceMark rm; 613 outputStream* out = Log(class, path)::info_stream(); 614 if (msg) { 615 out->print("%s", msg); 616 } 617 if (name) { 618 if (strlen(name) < 256) { 619 out->print("%s", name); 620 } else { 621 // For very long paths, we need to print each character separately, 622 // as print_cr() has a length limit 623 while (name[0] != '\0') { 624 out->print("%c", name[0]); 625 name++; 626 } 627 } 628 } 629 out->cr(); 630 } 631 } 632 633 #if INCLUDE_CDS 634 void ClassLoader::check_shared_classpath(const char *path) { 635 if (strcmp(path, "") == 0) { 636 exit_with_path_failure("Cannot have empty path in archived classpaths", NULL); 637 } 638 639 struct stat st; 640 if (os::stat(path, &st) == 0) { 641 if ((st.st_mode & S_IFMT) != S_IFREG) { // is not a regular file 642 if (!os::dir_is_empty(path)) { 643 tty->print_cr("Error: non-empty directory '%s'", path); 644 exit_with_path_failure("CDS allows only empty directories in archived classpaths", NULL); 645 } 646 } 647 } 648 } 649 #endif 650 651 void ClassLoader::setup_bootstrap_search_path() { 652 const char* sys_class_path = Arguments::get_sysclasspath(); 653 const char* java_class_path = Arguments::get_appclasspath(); 654 if (PrintSharedArchiveAndExit) { 655 // Don't print sys_class_path - this is the bootcp of this current VM process, not necessarily 656 // the same as the bootcp of the shared archive. 657 } else { 658 trace_class_path("bootstrap loader class path=", sys_class_path); 659 trace_class_path("classpath: ", java_class_path); 660 } 661 #if INCLUDE_CDS 662 if (DumpSharedSpaces) { 663 _shared_paths_misc_info->add_boot_classpath(sys_class_path); 664 } 665 #endif 666 setup_search_path(sys_class_path, true); 667 } 668 669 #if INCLUDE_CDS 670 int ClassLoader::get_shared_paths_misc_info_size() { 671 return _shared_paths_misc_info->get_used_bytes(); 672 } 673 674 void* ClassLoader::get_shared_paths_misc_info() { 675 return _shared_paths_misc_info->buffer(); 676 } 677 678 bool ClassLoader::check_shared_paths_misc_info(void *buf, int size) { 679 SharedPathsMiscInfo* checker = SharedClassUtil::allocate_shared_paths_misc_info((char*)buf, size); 680 bool result = checker->check(); 681 delete checker; 682 return result; 683 } 684 #endif 685 686 // Construct the array of module/path pairs as specified to --patch-module 687 // for the boot loader to search ahead of the jimage, if the class being 688 // loaded is defined to a module that has been specified to --patch-module. 689 void ClassLoader::setup_patch_mod_entries() { 690 Thread* THREAD = Thread::current(); 691 GrowableArray<ModulePatchPath*>* patch_mod_args = Arguments::get_patch_mod_prefix(); 692 int num_of_entries = patch_mod_args->length(); 693 694 695 // Set up the boot loader's _patch_mod_entries list 696 _patch_mod_entries = new (ResourceObj::C_HEAP, mtModule) GrowableArray<ModuleClassPathList*>(num_of_entries, true); 697 698 for (int i = 0; i < num_of_entries; i++) { 699 const char* module_name = (patch_mod_args->at(i))->module_name(); 700 Symbol* const module_sym = SymbolTable::lookup(module_name, (int)strlen(module_name), CHECK); 701 assert(module_sym != NULL, "Failed to obtain Symbol for module name"); 702 ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym); 703 704 char* class_path = (patch_mod_args->at(i))->path_string(); 705 int len = (int)strlen(class_path); 706 int end = 0; 707 // Iterate over the module's class path entries 708 for (int start = 0; start < len; start = end) { 709 while (class_path[end] && class_path[end] != os::path_separator()[0]) { 710 end++; 711 } 712 EXCEPTION_MARK; 713 ResourceMark rm(THREAD); 714 char* path = NEW_RESOURCE_ARRAY(char, end - start + 1); 715 strncpy(path, &class_path[start], end - start); 716 path[end - start] = '\0'; 717 718 struct stat st; 719 if (os::stat(path, &st) == 0) { 720 // File or directory found 721 Thread* THREAD = Thread::current(); 722 ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK); 723 // If the path specification is valid, enter it into this module's list 724 if (new_entry != NULL) { 725 module_cpl->add_to_list(new_entry); 726 } 727 } 728 729 while (class_path[end] == os::path_separator()[0]) { 730 end++; 731 } 732 } 733 734 // Record the module into the list of --patch-module entries only if 735 // valid ClassPathEntrys have been created 736 if (module_cpl->module_first_entry() != NULL) { 737 _patch_mod_entries->push(module_cpl); 738 } 739 } 740 } 741 742 // Determine whether the module has been patched via the command-line 743 // option --patch-module 744 bool ClassLoader::is_in_patch_mod_entries(Symbol* module_name) { 745 if (_patch_mod_entries != NULL && _patch_mod_entries->is_nonempty()) { 746 int table_len = _patch_mod_entries->length(); 747 for (int i = 0; i < table_len; i++) { 748 ModuleClassPathList* patch_mod = _patch_mod_entries->at(i); 749 if (module_name->fast_compare(patch_mod->module_name()) == 0) { 750 return true; 751 } 752 } 753 } 754 return false; 755 } 756 757 void ClassLoader::setup_search_path(const char *class_path, bool bootstrap_search) { 758 int len = (int)strlen(class_path); 759 int end = 0; 760 bool set_base_piece = bootstrap_search; 761 762 // Iterate over class path entries 763 for (int start = 0; start < len; start = end) { 764 while (class_path[end] && class_path[end] != os::path_separator()[0]) { 765 end++; 766 } 767 EXCEPTION_MARK; 768 ResourceMark rm(THREAD); 769 char* path = NEW_RESOURCE_ARRAY(char, end - start + 1); 770 strncpy(path, &class_path[start], end - start); 771 path[end - start] = '\0'; 772 773 // The first time through the bootstrap_search setup, it must be determined 774 // what the base or core piece of the boot loader search is. Either a java runtime 775 // image is present or this is an exploded module build situation. 776 if (set_base_piece) { 777 assert(string_ends_with(path, MODULES_IMAGE_NAME) || string_ends_with(path, JAVA_BASE_NAME), 778 "Incorrect boot loader search path, no java runtime image or " JAVA_BASE_NAME " exploded build"); 779 struct stat st; 780 if (os::stat(path, &st) == 0) { 781 // Directory found 782 Thread* THREAD = Thread::current(); 783 ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK); 784 785 // Check for a jimage 786 if (Arguments::has_jimage()) { 787 assert(_jrt_entry == NULL, "should not setup bootstrap class search path twice"); 788 assert(new_entry != NULL && new_entry->is_jrt(), "No java runtime image present"); 789 _jrt_entry = new_entry; 790 ++_num_entries; 791 #if INCLUDE_CDS 792 if (DumpSharedSpaces) { 793 JImageFile *jimage = _jrt_entry->jimage(); 794 assert(jimage != NULL, "No java runtime image file present"); 795 ClassLoader::initialize_module_loader_map(jimage); 796 } 797 #endif 798 } 799 } else { 800 // If path does not exist, exit 801 vm_exit_during_initialization("Unable to establish the boot loader search path", path); 802 } 803 set_base_piece = false; 804 } else { 805 // Every entry on the system boot class path after the initial base piece, 806 // which is set by os::set_boot_path(), is considered an appended entry. 807 update_class_path_entry_list(path, false, bootstrap_search); 808 } 809 810 #if INCLUDE_CDS 811 if (DumpSharedSpaces) { 812 check_shared_classpath(path); 813 } 814 #endif 815 while (class_path[end] == os::path_separator()[0]) { 816 end++; 817 } 818 } 819 } 820 821 // During an exploded modules build, each module defined to the boot loader 822 // will be added to the ClassLoader::_exploded_entries array. 823 void ClassLoader::add_to_exploded_build_list(Symbol* module_sym, TRAPS) { 824 assert(!ClassLoader::has_jrt_entry(), "Exploded build not applicable"); 825 assert(_exploded_entries != NULL, "_exploded_entries was not initialized"); 826 827 // Find the module's symbol 828 ResourceMark rm(THREAD); 829 const char *module_name = module_sym->as_C_string(); 830 const char *home = Arguments::get_java_home(); 831 const char file_sep = os::file_separator()[0]; 832 // 10 represents the length of "modules" + 2 file separators + \0 833 size_t len = strlen(home) + strlen(module_name) + 10; 834 char *path = NEW_C_HEAP_ARRAY(char, len, mtModule); 835 jio_snprintf(path, len, "%s%cmodules%c%s", home, file_sep, file_sep, module_name); 836 837 struct stat st; 838 if (os::stat(path, &st) == 0) { 839 // Directory found 840 ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK); 841 842 // If the path specification is valid, enter it into this module's list. 843 // There is no need to check for duplicate modules in the exploded entry list, 844 // since no two modules with the same name can be defined to the boot loader. 845 // This is checked at module definition time in Modules::define_module. 846 if (new_entry != NULL) { 847 ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym); 848 module_cpl->add_to_list(new_entry); 849 { 850 MutexLocker ml(Module_lock, THREAD); 851 _exploded_entries->push(module_cpl); 852 } 853 log_info(class, load)("path: %s", path); 854 } 855 } 856 FREE_C_HEAP_ARRAY(char, path); 857 } 858 859 ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st, 860 bool throw_exception, 861 bool is_boot_append, TRAPS) { 862 JavaThread* thread = JavaThread::current(); 863 ClassPathEntry* new_entry = NULL; 864 if ((st->st_mode & S_IFMT) == S_IFREG) { 865 ResourceMark rm(thread); 866 // Regular file, should be a zip or jimage file 867 // Canonicalized filename 868 char* canonical_path = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, JVM_MAXPATHLEN); 869 if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) { 870 // This matches the classic VM 871 if (throw_exception) { 872 THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL); 873 } else { 874 return NULL; 875 } 876 } 877 jint error; 878 JImageFile* jimage =(*JImageOpen)(canonical_path, &error); 879 if (jimage != NULL) { 880 new_entry = new ClassPathImageEntry(jimage, canonical_path); 881 } else { 882 char* error_msg = NULL; 883 jzfile* zip; 884 { 885 // enable call to C land 886 ThreadToNativeFromVM ttn(thread); 887 HandleMark hm(thread); 888 zip = (*ZipOpen)(canonical_path, &error_msg); 889 } 890 if (zip != NULL && error_msg == NULL) { 891 new_entry = new ClassPathZipEntry(zip, path, is_boot_append); 892 } else { 893 char *msg; 894 if (error_msg == NULL) { 895 msg = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, strlen(path) + 128); ; 896 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path); 897 } else { 898 int len = (int)(strlen(path) + strlen(error_msg) + 128); 899 msg = NEW_RESOURCE_ARRAY_IN_THREAD(thread, char, len); ; 900 jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path); 901 } 902 // Don't complain about bad jar files added via -Xbootclasspath/a:. 903 if (throw_exception && is_init_completed()) { 904 THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL); 905 } else { 906 return NULL; 907 } 908 } 909 } 910 log_info(class, path)("opened: %s", path); 911 log_info(class, load)("opened: %s", path); 912 } else { 913 // Directory 914 new_entry = new ClassPathDirEntry(path); 915 log_info(class, load)("path: %s", path); 916 } 917 return new_entry; 918 } 919 920 921 // Create a class path zip entry for a given path (return NULL if not found 922 // or zip/JAR file cannot be opened) 923 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path, bool is_boot_append) { 924 // check for a regular file 925 struct stat st; 926 if (os::stat(path, &st) == 0) { 927 if ((st.st_mode & S_IFMT) == S_IFREG) { 928 char canonical_path[JVM_MAXPATHLEN]; 929 if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) { 930 char* error_msg = NULL; 931 jzfile* zip; 932 { 933 // enable call to C land 934 JavaThread* thread = JavaThread::current(); 935 ThreadToNativeFromVM ttn(thread); 936 HandleMark hm(thread); 937 zip = (*ZipOpen)(canonical_path, &error_msg); 938 } 939 if (zip != NULL && error_msg == NULL) { 940 // create using canonical path 941 return new ClassPathZipEntry(zip, canonical_path, is_boot_append); 942 } 943 } 944 } 945 } 946 return NULL; 947 } 948 949 // returns true if entry already on class path 950 bool ClassLoader::contains_append_entry(const char* name) { 951 ClassPathEntry* e = _first_append_entry; 952 while (e != NULL) { 953 // assume zip entries have been canonicalized 954 if (strcmp(name, e->name()) == 0) { 955 return true; 956 } 957 e = e->next(); 958 } 959 return false; 960 } 961 962 void ClassLoader::add_to_list(ClassPathEntry *new_entry) { 963 if (new_entry != NULL) { 964 if (_last_append_entry == NULL) { 965 assert(_first_append_entry == NULL, "boot loader's append class path entry list not empty"); 966 _first_append_entry = _last_append_entry = new_entry; 967 } else { 968 _last_append_entry->set_next(new_entry); 969 _last_append_entry = new_entry; 970 } 971 } 972 _num_entries++; 973 } 974 975 void ClassLoader::add_to_list(const char *apath) { 976 update_class_path_entry_list((char*)apath, false, false); 977 } 978 979 // Returns true IFF the file/dir exists and the entry was successfully created. 980 bool ClassLoader::update_class_path_entry_list(const char *path, 981 bool check_for_duplicates, 982 bool is_boot_append, 983 bool throw_exception) { 984 struct stat st; 985 if (os::stat(path, &st) == 0) { 986 // File or directory found 987 ClassPathEntry* new_entry = NULL; 988 Thread* THREAD = Thread::current(); 989 new_entry = create_class_path_entry(path, &st, throw_exception, is_boot_append, CHECK_(false)); 990 if (new_entry == NULL) { 991 return false; 992 } 993 994 // Do not reorder the bootclasspath which would break get_system_package(). 995 // Add new entry to linked list 996 if (!check_for_duplicates || !contains_append_entry(new_entry->name())) { 997 ClassLoaderExt::add_class_path_entry(path, check_for_duplicates, new_entry); 998 } 999 return true; 1000 } else { 1001 #if INCLUDE_CDS 1002 if (DumpSharedSpaces) { 1003 _shared_paths_misc_info->add_nonexist_path(path); 1004 } 1005 #endif 1006 return false; 1007 } 1008 } 1009 1010 static void print_module_entry_table(const GrowableArray<ModuleClassPathList*>* const module_list) { 1011 ResourceMark rm; 1012 int num_of_entries = module_list->length(); 1013 for (int i = 0; i < num_of_entries; i++) { 1014 ClassPathEntry* e; 1015 ModuleClassPathList* mpl = module_list->at(i); 1016 tty->print("%s=", mpl->module_name()->as_C_string()); 1017 e = mpl->module_first_entry(); 1018 while (e != NULL) { 1019 tty->print("%s", e->name()); 1020 e = e->next(); 1021 if (e != NULL) { 1022 tty->print("%s", os::path_separator()); 1023 } 1024 } 1025 tty->print(" ;"); 1026 } 1027 } 1028 1029 void ClassLoader::print_bootclasspath() { 1030 ClassPathEntry* e; 1031 tty->print("[bootclasspath= "); 1032 1033 // Print --patch-module module/path specifications first 1034 if (_patch_mod_entries != NULL) { 1035 print_module_entry_table(_patch_mod_entries); 1036 } 1037 1038 // [jimage | exploded modules build] 1039 if (has_jrt_entry()) { 1040 // Print the location of the java runtime image 1041 tty->print("%s ;", _jrt_entry->name()); 1042 } else { 1043 // Print exploded module build path specifications 1044 if (_exploded_entries != NULL) { 1045 print_module_entry_table(_exploded_entries); 1046 } 1047 } 1048 1049 // appended entries 1050 e = _first_append_entry; 1051 while (e != NULL) { 1052 tty->print("%s ;", e->name()); 1053 e = e->next(); 1054 } 1055 tty->print_cr("]"); 1056 } 1057 1058 void ClassLoader::load_zip_library() { 1059 assert(ZipOpen == NULL, "should not load zip library twice"); 1060 // First make sure native library is loaded 1061 os::native_java_library(); 1062 // Load zip library 1063 char path[JVM_MAXPATHLEN]; 1064 char ebuf[1024]; 1065 void* handle = NULL; 1066 if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) { 1067 handle = os::dll_load(path, ebuf, sizeof ebuf); 1068 } 1069 if (handle == NULL) { 1070 vm_exit_during_initialization("Unable to load ZIP library", path); 1071 } 1072 // Lookup zip entry points 1073 ZipOpen = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open")); 1074 ZipClose = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close")); 1075 FindEntry = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry")); 1076 ReadEntry = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry")); 1077 GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry")); 1078 ZipInflateFully = CAST_TO_FN_PTR(ZipInflateFully_t, os::dll_lookup(handle, "ZIP_InflateFully")); 1079 Crc32 = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32")); 1080 1081 // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL 1082 if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL || 1083 GetNextEntry == NULL || Crc32 == NULL) { 1084 vm_exit_during_initialization("Corrupted ZIP library", path); 1085 } 1086 1087 if (ZipInflateFully == NULL) { 1088 vm_exit_during_initialization("Corrupted ZIP library ZIP_InflateFully missing", path); 1089 } 1090 1091 // Lookup canonicalize entry in libjava.dll 1092 void *javalib_handle = os::native_java_library(); 1093 CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize")); 1094 // This lookup only works on 1.3. Do not check for non-null here 1095 } 1096 1097 void ClassLoader::load_jimage_library() { 1098 // First make sure native library is loaded 1099 os::native_java_library(); 1100 // Load jimage library 1101 char path[JVM_MAXPATHLEN]; 1102 char ebuf[1024]; 1103 void* handle = NULL; 1104 if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "jimage")) { 1105 handle = os::dll_load(path, ebuf, sizeof ebuf); 1106 } 1107 if (handle == NULL) { 1108 vm_exit_during_initialization("Unable to load jimage library", path); 1109 } 1110 1111 // Lookup jimage entry points 1112 JImageOpen = CAST_TO_FN_PTR(JImageOpen_t, os::dll_lookup(handle, "JIMAGE_Open")); 1113 guarantee(JImageOpen != NULL, "function JIMAGE_Open not found"); 1114 JImageClose = CAST_TO_FN_PTR(JImageClose_t, os::dll_lookup(handle, "JIMAGE_Close")); 1115 guarantee(JImageClose != NULL, "function JIMAGE_Close not found"); 1116 JImagePackageToModule = CAST_TO_FN_PTR(JImagePackageToModule_t, os::dll_lookup(handle, "JIMAGE_PackageToModule")); 1117 guarantee(JImagePackageToModule != NULL, "function JIMAGE_PackageToModule not found"); 1118 JImageFindResource = CAST_TO_FN_PTR(JImageFindResource_t, os::dll_lookup(handle, "JIMAGE_FindResource")); 1119 guarantee(JImageFindResource != NULL, "function JIMAGE_FindResource not found"); 1120 JImageGetResource = CAST_TO_FN_PTR(JImageGetResource_t, os::dll_lookup(handle, "JIMAGE_GetResource")); 1121 guarantee(JImageGetResource != NULL, "function JIMAGE_GetResource not found"); 1122 JImageResourceIterator = CAST_TO_FN_PTR(JImageResourceIterator_t, os::dll_lookup(handle, "JIMAGE_ResourceIterator")); 1123 guarantee(JImageResourceIterator != NULL, "function JIMAGE_ResourceIterator not found"); 1124 JImageResourcePath = CAST_TO_FN_PTR(JImage_ResourcePath_t, os::dll_lookup(handle, "JIMAGE_ResourcePath")); 1125 guarantee(JImageResourcePath != NULL, "function JIMAGE_ResourcePath not found"); 1126 } 1127 1128 jboolean ClassLoader::decompress(void *in, u8 inSize, void *out, u8 outSize, char **pmsg) { 1129 return (*ZipInflateFully)(in, inSize, out, outSize, pmsg); 1130 } 1131 1132 int ClassLoader::crc32(int crc, const char* buf, int len) { 1133 assert(Crc32 != NULL, "ZIP_CRC32 is not found"); 1134 return (*Crc32)(crc, (const jbyte*)buf, len); 1135 } 1136 1137 #if INCLUDE_CDS 1138 void ClassLoader::initialize_module_loader_map(JImageFile* jimage) { 1139 if (!DumpSharedSpaces) { 1140 return; // only needed for CDS dump time 1141 } 1142 1143 ResourceMark rm; 1144 jlong size; 1145 JImageLocationRef location = (*JImageFindResource)(jimage, JAVA_BASE_NAME, get_jimage_version_string(), MODULE_LOADER_MAP, &size); 1146 if (location == 0) { 1147 vm_exit_during_initialization( 1148 "Cannot find ModuleLoaderMap location from modules jimage.", NULL); 1149 } 1150 char* buffer = NEW_RESOURCE_ARRAY(char, size + 1); 1151 buffer[size] = '\0'; 1152 jlong read = (*JImageGetResource)(jimage, location, buffer, size); 1153 if (read != size) { 1154 vm_exit_during_initialization( 1155 "Cannot find ModuleLoaderMap resource from modules jimage.", NULL); 1156 } 1157 char* char_buf = (char*)buffer; 1158 int buflen = (int)strlen(char_buf); 1159 char* begin_ptr = char_buf; 1160 char* end_ptr = strchr(begin_ptr, '\n'); 1161 bool process_boot_modules = false; 1162 _boot_modules_array = new (ResourceObj::C_HEAP, mtModule) 1163 GrowableArray<char*>(INITIAL_BOOT_MODULES_ARRAY_SIZE, true); 1164 _platform_modules_array = new (ResourceObj::C_HEAP, mtModule) 1165 GrowableArray<char*>(INITIAL_PLATFORM_MODULES_ARRAY_SIZE, true); 1166 while (end_ptr != NULL && (end_ptr - char_buf) < buflen) { 1167 // Allocate a buffer from the C heap to be appended to the _boot_modules_array 1168 // or the _platform_modules_array. 1169 char* temp_name = NEW_C_HEAP_ARRAY(char, (size_t)(end_ptr - begin_ptr + 1), mtInternal); 1170 strncpy(temp_name, begin_ptr, end_ptr - begin_ptr); 1171 temp_name[end_ptr - begin_ptr] = '\0'; 1172 if (strncmp(temp_name, "BOOT", 4) == 0) { 1173 process_boot_modules = true; 1174 FREE_C_HEAP_ARRAY(char, temp_name); 1175 } else if (strncmp(temp_name, "PLATFORM", 8) == 0) { 1176 process_boot_modules = false; 1177 FREE_C_HEAP_ARRAY(char, temp_name); 1178 } else { 1179 // module name 1180 if (process_boot_modules) { 1181 _boot_modules_array->append(temp_name); 1182 } else { 1183 _platform_modules_array->append(temp_name); 1184 } 1185 } 1186 begin_ptr = ++end_ptr; 1187 end_ptr = strchr(begin_ptr, '\n'); 1188 } 1189 } 1190 #endif 1191 1192 // Function add_package extracts the package from the fully qualified class name 1193 // and checks if the package is in the boot loader's package entry table. If so, 1194 // then it sets the classpath_index in the package entry record. 1195 // 1196 // The classpath_index field is used to find the entry on the boot loader class 1197 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a 1198 // in an unnamed module. It is also used to indicate (for all packages whose 1199 // classes are loaded by the boot loader) that at least one of the package's 1200 // classes has been loaded. 1201 bool ClassLoader::add_package(const char *fullq_class_name, s2 classpath_index, TRAPS) { 1202 assert(fullq_class_name != NULL, "just checking"); 1203 1204 // Get package name from fully qualified class name. 1205 ResourceMark rm; 1206 const char *cp = package_from_name(fullq_class_name); 1207 if (cp != NULL) { 1208 PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages(); 1209 TempNewSymbol pkg_symbol = SymbolTable::new_symbol(cp, CHECK_false); 1210 PackageEntry* pkg_entry = pkg_entry_tbl->lookup_only(pkg_symbol); 1211 if (pkg_entry != NULL) { 1212 assert(classpath_index != -1, "Unexpected classpath_index"); 1213 pkg_entry->set_classpath_index(classpath_index); 1214 } else { 1215 return false; 1216 } 1217 } 1218 return true; 1219 } 1220 1221 oop ClassLoader::get_system_package(const char* name, TRAPS) { 1222 // Look up the name in the boot loader's package entry table. 1223 if (name != NULL) { 1224 TempNewSymbol package_sym = SymbolTable::new_symbol(name, (int)strlen(name), CHECK_NULL); 1225 // Look for the package entry in the boot loader's package entry table. 1226 PackageEntry* package = 1227 ClassLoaderData::the_null_class_loader_data()->packages()->lookup_only(package_sym); 1228 1229 // Return NULL if package does not exist or if no classes in that package 1230 // have been loaded. 1231 if (package != NULL && package->has_loaded_class()) { 1232 ModuleEntry* module = package->module(); 1233 if (module->location() != NULL) { 1234 ResourceMark rm(THREAD); 1235 Handle ml = java_lang_String::create_from_str( 1236 module->location()->as_C_string(), THREAD); 1237 return ml(); 1238 } 1239 // Return entry on boot loader class path. 1240 Handle cph = java_lang_String::create_from_str( 1241 ClassLoader::classpath_entry(package->classpath_index())->name(), THREAD); 1242 return cph(); 1243 } 1244 } 1245 return NULL; 1246 } 1247 1248 objArrayOop ClassLoader::get_system_packages(TRAPS) { 1249 ResourceMark rm(THREAD); 1250 // List of pointers to PackageEntrys that have loaded classes. 1251 GrowableArray<PackageEntry*>* loaded_class_pkgs = new GrowableArray<PackageEntry*>(50); 1252 { 1253 MutexLocker ml(Module_lock, THREAD); 1254 1255 PackageEntryTable* pe_table = 1256 ClassLoaderData::the_null_class_loader_data()->packages(); 1257 1258 // Collect the packages that have at least one loaded class. 1259 for (int x = 0; x < pe_table->table_size(); x++) { 1260 for (PackageEntry* package_entry = pe_table->bucket(x); 1261 package_entry != NULL; 1262 package_entry = package_entry->next()) { 1263 if (package_entry->has_loaded_class()) { 1264 loaded_class_pkgs->append(package_entry); 1265 } 1266 } 1267 } 1268 } 1269 1270 1271 // Allocate objArray and fill with java.lang.String 1272 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(), 1273 loaded_class_pkgs->length(), CHECK_NULL); 1274 objArrayHandle result(THREAD, r); 1275 for (int x = 0; x < loaded_class_pkgs->length(); x++) { 1276 PackageEntry* package_entry = loaded_class_pkgs->at(x); 1277 Handle str = java_lang_String::create_from_symbol(package_entry->name(), CHECK_NULL); 1278 result->obj_at_put(x, str()); 1279 } 1280 return result(); 1281 } 1282 1283 #if INCLUDE_CDS 1284 s2 ClassLoader::module_to_classloader(const char* module_name) { 1285 1286 assert(DumpSharedSpaces, "dump time only"); 1287 assert(_boot_modules_array != NULL, "_boot_modules_array is NULL"); 1288 assert(_platform_modules_array != NULL, "_platform_modules_array is NULL"); 1289 1290 int array_size = _boot_modules_array->length(); 1291 for (int i = 0; i < array_size; i++) { 1292 if (strcmp(module_name, _boot_modules_array->at(i)) == 0) { 1293 return BOOT_LOADER; 1294 } 1295 } 1296 1297 array_size = _platform_modules_array->length(); 1298 for (int i = 0; i < array_size; i++) { 1299 if (strcmp(module_name, _platform_modules_array->at(i)) == 0) { 1300 return PLATFORM_LOADER; 1301 } 1302 } 1303 1304 return APP_LOADER; 1305 } 1306 1307 s2 ClassLoader::classloader_type(Symbol* class_name, ClassPathEntry* e, int classpath_index, TRAPS) { 1308 assert(DumpSharedSpaces, "Only used for CDS dump time"); 1309 1310 // obtain the classloader type based on the class name. 1311 // First obtain the package name based on the class name. Then obtain 1312 // the classloader type based on the package name from the jimage using 1313 // a jimage API. If the classloader type cannot be found from the 1314 // jimage, it is determined by the class path entry. 1315 jshort loader_type = ClassLoader::APP_LOADER; 1316 if (e->is_jrt()) { 1317 ResourceMark rm; 1318 TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_0); 1319 if (pkg_name != NULL) { 1320 const char* pkg_name_C_string = (const char*)(pkg_name->as_C_string()); 1321 ClassPathImageEntry* cpie = (ClassPathImageEntry*)e; 1322 JImageFile* jimage = cpie->jimage(); 1323 char* module_name = (char*)(*JImagePackageToModule)(jimage, pkg_name_C_string); 1324 if (module_name != NULL) { 1325 loader_type = ClassLoader::module_to_classloader(module_name); 1326 } 1327 } 1328 } else if (ClassLoaderExt::is_boot_classpath(classpath_index)) { 1329 loader_type = ClassLoader::BOOT_LOADER; 1330 } 1331 return loader_type; 1332 } 1333 #endif 1334 1335 // caller needs ResourceMark 1336 const char* ClassLoader::file_name_for_class_name(const char* class_name, 1337 int class_name_len) { 1338 assert(class_name != NULL, "invariant"); 1339 assert((int)strlen(class_name) == class_name_len, "invariant"); 1340 1341 static const char class_suffix[] = ".class"; 1342 1343 char* const file_name = NEW_RESOURCE_ARRAY(char, 1344 class_name_len + 1345 sizeof(class_suffix)); // includes term NULL 1346 1347 strncpy(file_name, class_name, class_name_len); 1348 strncpy(&file_name[class_name_len], class_suffix, sizeof(class_suffix)); 1349 1350 return file_name; 1351 } 1352 1353 ClassPathEntry* find_first_module_cpe(ModuleEntry* mod_entry, 1354 const GrowableArray<ModuleClassPathList*>* const module_list) { 1355 int num_of_entries = module_list->length(); 1356 const Symbol* class_module_name = mod_entry->name(); 1357 1358 // Loop through all the modules in either the patch-module or exploded entries looking for module 1359 for (int i = 0; i < num_of_entries; i++) { 1360 ModuleClassPathList* module_cpl = module_list->at(i); 1361 Symbol* module_cpl_name = module_cpl->module_name(); 1362 1363 if (module_cpl_name->fast_compare(class_module_name) == 0) { 1364 // Class' module has been located. 1365 return module_cpl->module_first_entry(); 1366 } 1367 } 1368 return NULL; 1369 } 1370 1371 1372 // Search either the patch-module or exploded build entries for class. 1373 ClassFileStream* ClassLoader::search_module_entries(const GrowableArray<ModuleClassPathList*>* const module_list, 1374 const char* const class_name, 1375 const char* const file_name, 1376 TRAPS) { 1377 ClassFileStream* stream = NULL; 1378 1379 // Find the class' defining module in the boot loader's module entry table 1380 PackageEntry* pkg_entry = get_package_entry(class_name, ClassLoaderData::the_null_class_loader_data(), CHECK_NULL); 1381 ModuleEntry* mod_entry = (pkg_entry != NULL) ? pkg_entry->module() : NULL; 1382 1383 // If the module system has not defined java.base yet, then 1384 // classes loaded are assumed to be defined to java.base. 1385 // When java.base is eventually defined by the module system, 1386 // all packages of classes that have been previously loaded 1387 // are verified in ModuleEntryTable::verify_javabase_packages(). 1388 if (!Universe::is_module_initialized() && 1389 !ModuleEntryTable::javabase_defined() && 1390 mod_entry == NULL) { 1391 mod_entry = ModuleEntryTable::javabase_moduleEntry(); 1392 } 1393 1394 // The module must be a named module 1395 ClassPathEntry* e = NULL; 1396 if (mod_entry != NULL && mod_entry->is_named()) { 1397 if (module_list == _exploded_entries) { 1398 // The exploded build entries can be added to at any time so a lock is 1399 // needed when searching them. 1400 assert(!ClassLoader::has_jrt_entry(), "Must be exploded build"); 1401 MutexLocker ml(Module_lock, THREAD); 1402 e = find_first_module_cpe(mod_entry, module_list); 1403 } else { 1404 e = find_first_module_cpe(mod_entry, module_list); 1405 } 1406 } 1407 1408 // Try to load the class from the module's ClassPathEntry list. 1409 while (e != NULL) { 1410 stream = e->open_stream(file_name, CHECK_NULL); 1411 // No context.check is required since CDS is not supported 1412 // for an exploded modules build or if --patch-module is specified. 1413 if (NULL != stream) { 1414 return stream; 1415 } 1416 e = e->next(); 1417 } 1418 // If the module was located, break out even if the class was not 1419 // located successfully from that module's ClassPathEntry list. 1420 // There will not be another valid entry for that module. 1421 return NULL; 1422 } 1423 1424 InstanceKlass* ClassLoader::load_class(Symbol* name, bool search_append_only, TRAPS) { 1425 assert(name != NULL, "invariant"); 1426 assert(THREAD->is_Java_thread(), "must be a JavaThread"); 1427 1428 ResourceMark rm(THREAD); 1429 HandleMark hm(THREAD); 1430 1431 const char* const class_name = name->as_C_string(); 1432 1433 EventMark m("loading class %s", class_name); 1434 ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion); 1435 1436 const char* const file_name = file_name_for_class_name(class_name, 1437 name->utf8_length()); 1438 assert(file_name != NULL, "invariant"); 1439 1440 ClassLoaderExt::Context context(class_name, file_name, THREAD); 1441 1442 // Lookup stream for parsing .class file 1443 ClassFileStream* stream = NULL; 1444 s2 classpath_index = 0; 1445 ClassPathEntry* e = NULL; 1446 1447 // If DumpSharedSpaces is true boot loader visibility boundaries are set to: 1448 // - [jimage] + [_first_append_entry to _last_append_entry] (all path entries). 1449 // 1450 // If search_append_only is true, boot loader visibility boundaries are 1451 // set to be _first_append_entry to the end. This includes: 1452 // [-Xbootclasspath/a]; [jvmti appended entries] 1453 // 1454 // If both DumpSharedSpaces and search_append_only are false, boot loader 1455 // visibility boundaries are set to be the --patch-module entries plus the base piece. 1456 // This would include: 1457 // [--patch-module=<module>=<file>(<pathsep><file>)*]; [jimage | exploded module build] 1458 // 1459 // DumpSharedSpaces and search_append_only are mutually exclusive and cannot 1460 // be true at the same time. 1461 assert(!(DumpSharedSpaces && search_append_only), "DumpSharedSpaces and search_append_only are both true"); 1462 1463 // Load Attempt #1: --patch-module 1464 // Determine the class' defining module. If it appears in the _patch_mod_entries, 1465 // attempt to load the class from those locations specific to the module. 1466 // Specifications to --patch-module can contain a partial number of classes 1467 // that are part of the overall module definition. So if a particular class is not 1468 // found within its module specification, the search should continue to Load Attempt #2. 1469 // Note: The --patch-module entries are never searched if the boot loader's 1470 // visibility boundary is limited to only searching the append entries. 1471 if (_patch_mod_entries != NULL && !search_append_only) { 1472 // At CDS dump time, the --patch-module entries are ignored. That means a 1473 // class is still loaded from the runtime image even if it might 1474 // appear in the _patch_mod_entries. The runtime shared class visibility 1475 // check will determine if a shared class is visible based on the runtime 1476 // environemnt, including the runtime --patch-module setting. 1477 if (!DumpSharedSpaces) { 1478 stream = search_module_entries(_patch_mod_entries, class_name, file_name, CHECK_NULL); 1479 } 1480 } 1481 1482 // Load Attempt #2: [jimage | exploded build] 1483 if (!search_append_only && (NULL == stream)) { 1484 if (has_jrt_entry()) { 1485 e = _jrt_entry; 1486 stream = _jrt_entry->open_stream(file_name, CHECK_NULL); 1487 if (!context.check(stream, classpath_index)) { 1488 return NULL; 1489 } 1490 } else { 1491 // Exploded build - attempt to locate class in its defining module's location. 1492 assert(_exploded_entries != NULL, "No exploded build entries present"); 1493 stream = search_module_entries(_exploded_entries, class_name, file_name, CHECK_NULL); 1494 } 1495 } 1496 1497 // Load Attempt #3: [-Xbootclasspath/a]; [jvmti appended entries] 1498 if ((search_append_only || DumpSharedSpaces) && (NULL == stream)) { 1499 // For the boot loader append path search, the starting classpath_index 1500 // for the appended piece is always 1 to account for either the 1501 // _jrt_entry or the _exploded_entries. 1502 assert(classpath_index == 0, "The classpath_index has been incremented incorrectly"); 1503 classpath_index = 1; 1504 1505 e = _first_append_entry; 1506 while (e != NULL) { 1507 stream = e->open_stream(file_name, CHECK_NULL); 1508 if (!context.check(stream, classpath_index)) { 1509 return NULL; 1510 } 1511 if (NULL != stream) { 1512 break; 1513 } 1514 e = e->next(); 1515 ++classpath_index; 1516 } 1517 } 1518 1519 if (NULL == stream) { 1520 if (DumpSharedSpaces) { 1521 tty->print_cr("Preload Warning: Cannot find %s", class_name); 1522 } 1523 return NULL; 1524 } 1525 1526 stream->set_verify(context.should_verify(classpath_index)); 1527 1528 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 1529 Handle protection_domain; 1530 1531 InstanceKlass* result = KlassFactory::create_from_stream(stream, 1532 name, 1533 loader_data, 1534 protection_domain, 1535 NULL, // host_klass 1536 NULL, // cp_patches 1537 THREAD); 1538 if (HAS_PENDING_EXCEPTION) { 1539 if (DumpSharedSpaces) { 1540 tty->print_cr("Preload Error: Failed to load %s", class_name); 1541 } 1542 return NULL; 1543 } 1544 1545 return context.record_result(name, e, classpath_index, result, THREAD); 1546 } 1547 1548 // Initialize the class loader's access to methods in libzip. Parse and 1549 // process the boot classpath into a list ClassPathEntry objects. Once 1550 // this list has been created, it must not change order (see class PackageInfo) 1551 // it can be appended to and is by jvmti and the kernel vm. 1552 1553 void ClassLoader::initialize() { 1554 EXCEPTION_MARK; 1555 1556 if (UsePerfData) { 1557 // jvmstat performance counters 1558 NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time"); 1559 NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime"); 1560 NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self"); 1561 NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime"); 1562 NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self"); 1563 NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime"); 1564 NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self"); 1565 NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses"); 1566 NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses"); 1567 NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses"); 1568 1569 NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime"); 1570 NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self"); 1571 NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime"); 1572 NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime"); 1573 NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime"); 1574 NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime"); 1575 NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self"); 1576 NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount"); 1577 NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses"); 1578 NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime"); 1579 NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self"); 1580 NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes"); 1581 NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes"); 1582 1583 1584 // The following performance counters are added for measuring the impact 1585 // of the bug fix of 6365597. They are mainly focused on finding out 1586 // the behavior of system & user-defined classloader lock, whether 1587 // ClassLoader.loadClass/findClass is being called synchronized or not. 1588 // Also two additional counters are created to see whether 'UnsyncloadClass' 1589 // flag is being set or not and how many times load_instance_class call 1590 // fails with linkageError etc. 1591 NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS, 1592 "systemLoaderLockContentionRate"); 1593 NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS, 1594 "nonSystemLoaderLockContentionRate"); 1595 NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS, 1596 "jvmFindLoadedClassNoLockCalls"); 1597 NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS, 1598 "jvmDefineClassNoLockCalls"); 1599 1600 NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS, 1601 "jniDefineClassNoLockCalls"); 1602 1603 NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS, 1604 "unsafeDefineClassCalls"); 1605 1606 NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet"); 1607 NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS, 1608 "loadInstanceClassFailRate"); 1609 1610 // increment the isUnsyncloadClass counter if UnsyncloadClass is set. 1611 if (UnsyncloadClass) { 1612 _isUnsyncloadClass->inc(); 1613 } 1614 } 1615 1616 // lookup zip library entry points 1617 load_zip_library(); 1618 // lookup jimage library entry points 1619 load_jimage_library(); 1620 #if INCLUDE_CDS 1621 // initialize search path 1622 if (DumpSharedSpaces) { 1623 _shared_paths_misc_info = SharedClassUtil::allocate_shared_paths_misc_info(); 1624 } 1625 #endif 1626 setup_bootstrap_search_path(); 1627 } 1628 1629 #if INCLUDE_CDS 1630 void ClassLoader::initialize_shared_path() { 1631 if (DumpSharedSpaces) { 1632 ClassLoaderExt::setup_search_paths(); 1633 _shared_paths_misc_info->write_jint(0); // see comments in SharedPathsMiscInfo::check() 1634 } 1635 } 1636 #endif 1637 1638 jlong ClassLoader::classloader_time_ms() { 1639 return UsePerfData ? 1640 Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1; 1641 } 1642 1643 jlong ClassLoader::class_init_count() { 1644 return UsePerfData ? _perf_classes_inited->get_value() : -1; 1645 } 1646 1647 jlong ClassLoader::class_init_time_ms() { 1648 return UsePerfData ? 1649 Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1; 1650 } 1651 1652 jlong ClassLoader::class_verify_time_ms() { 1653 return UsePerfData ? 1654 Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1; 1655 } 1656 1657 jlong ClassLoader::class_link_count() { 1658 return UsePerfData ? _perf_classes_linked->get_value() : -1; 1659 } 1660 1661 jlong ClassLoader::class_link_time_ms() { 1662 return UsePerfData ? 1663 Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1; 1664 } 1665 1666 int ClassLoader::compute_Object_vtable() { 1667 // hardwired for JDK1.2 -- would need to duplicate class file parsing 1668 // code to determine actual value from file 1669 // Would be value '11' if finals were in vtable 1670 int JDK_1_2_Object_vtable_size = 5; 1671 return JDK_1_2_Object_vtable_size * vtableEntry::size(); 1672 } 1673 1674 1675 void classLoader_init1() { 1676 ClassLoader::initialize(); 1677 } 1678 1679 // Complete the ClassPathEntry setup for the boot loader 1680 void ClassLoader::classLoader_init2(TRAPS) { 1681 // Setup the list of module/path pairs for --patch-module processing 1682 // This must be done after the SymbolTable is created in order 1683 // to use fast_compare on module names instead of a string compare. 1684 if (Arguments::get_patch_mod_prefix() != NULL) { 1685 setup_patch_mod_entries(); 1686 } 1687 1688 // Create the ModuleEntry for java.base (must occur after setup_patch_mod_entries 1689 // to successfully determine if java.base has been patched) 1690 create_javabase(); 1691 1692 // Setup the initial java.base/path pair for the exploded build entries. 1693 // As more modules are defined during module system initialization, more 1694 // entries will be added to the exploded build array. 1695 if (!has_jrt_entry()) { 1696 assert(!DumpSharedSpaces, "DumpSharedSpaces not supported with exploded module builds"); 1697 assert(!UseSharedSpaces, "UsedSharedSpaces not supported with exploded module builds"); 1698 // Set up the boot loader's _exploded_entries list. Note that this gets 1699 // done before loading any classes, by the same thread that will 1700 // subsequently do the first class load. So, no lock is needed for this. 1701 assert(_exploded_entries == NULL, "Should only get initialized once"); 1702 _exploded_entries = new (ResourceObj::C_HEAP, mtModule) 1703 GrowableArray<ModuleClassPathList*>(EXPLODED_ENTRY_SIZE, true); 1704 add_to_exploded_build_list(vmSymbols::java_base(), CHECK); 1705 } 1706 } 1707 1708 1709 bool ClassLoader::get_canonical_path(const char* orig, char* out, int len) { 1710 assert(orig != NULL && out != NULL && len > 0, "bad arguments"); 1711 if (CanonicalizeEntry != NULL) { 1712 JavaThread* THREAD = JavaThread::current(); 1713 JNIEnv* env = THREAD->jni_environment(); 1714 ResourceMark rm(THREAD); 1715 1716 // os::native_path writes into orig_copy 1717 char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(orig)+1); 1718 strcpy(orig_copy, orig); 1719 if ((CanonicalizeEntry)(env, os::native_path(orig_copy), out, len) < 0) { 1720 return false; 1721 } 1722 } else { 1723 // On JDK 1.2.2 the Canonicalize does not exist, so just do nothing 1724 strncpy(out, orig, len); 1725 out[len - 1] = '\0'; 1726 } 1727 return true; 1728 } 1729 1730 void ClassLoader::create_javabase() { 1731 Thread* THREAD = Thread::current(); 1732 1733 // Create java.base's module entry for the boot 1734 // class loader prior to loading j.l.Ojbect. 1735 ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data(); 1736 1737 // Get module entry table 1738 ModuleEntryTable* null_cld_modules = null_cld->modules(); 1739 if (null_cld_modules == NULL) { 1740 vm_exit_during_initialization("No ModuleEntryTable for the boot class loader"); 1741 } 1742 1743 { 1744 MutexLocker ml(Module_lock, THREAD); 1745 ModuleEntry* jb_module = null_cld_modules->locked_create_entry_or_null(Handle(), 1746 false, vmSymbols::java_base(), NULL, NULL, null_cld); 1747 if (jb_module == NULL) { 1748 vm_exit_during_initialization("Unable to create ModuleEntry for " JAVA_BASE_NAME); 1749 } 1750 ModuleEntryTable::set_javabase_moduleEntry(jb_module); 1751 } 1752 } 1753 1754 #ifndef PRODUCT 1755 1756 // CompileTheWorld 1757 // 1758 // Iterates over all class path entries and forces compilation of all methods 1759 // in all classes found. Currently, only zip/jar archives are searched. 1760 // 1761 // The classes are loaded by the Java level bootstrap class loader, and the 1762 // initializer is called. If DelayCompilationDuringStartup is true (default), 1763 // the interpreter will run the initialization code. Note that forcing 1764 // initialization in this way could potentially lead to initialization order 1765 // problems, in which case we could just force the initialization bit to be set. 1766 1767 1768 // We need to iterate over the contents of a zip/jar file, so we replicate the 1769 // jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile, 1770 // since jzfile already has a void* definition. 1771 // 1772 // Note that this is only used in debug mode. 1773 // 1774 // HotSpot integration note: 1775 // Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build 1776 1777 1778 // JDK 1.3 version 1779 typedef struct real_jzentry { /* Zip file entry */ 1780 char *name; /* entry name */ 1781 jint time; /* modification time */ 1782 jint size; /* size of uncompressed data */ 1783 jint csize; /* size of compressed data (zero if uncompressed) */ 1784 jint crc; /* crc of uncompressed data */ 1785 char *comment; /* optional zip file comment */ 1786 jbyte *extra; /* optional extra data */ 1787 jint pos; /* position of LOC header (if negative) or data */ 1788 } real_jzentry; 1789 1790 typedef struct real_jzfile { /* Zip file */ 1791 char *name; /* zip file name */ 1792 jint refs; /* number of active references */ 1793 jint fd; /* open file descriptor */ 1794 void *lock; /* read lock */ 1795 char *comment; /* zip file comment */ 1796 char *msg; /* zip error message */ 1797 void *entries; /* array of hash cells */ 1798 jint total; /* total number of entries */ 1799 unsigned short *table; /* Hash chain heads: indexes into entries */ 1800 jint tablelen; /* number of hash eads */ 1801 real_jzfile *next; /* next zip file in search list */ 1802 jzentry *cache; /* we cache the most recently freed jzentry */ 1803 /* Information on metadata names in META-INF directory */ 1804 char **metanames; /* array of meta names (may have null names) */ 1805 jint metacount; /* number of slots in metanames array */ 1806 /* If there are any per-entry comments, they are in the comments array */ 1807 char **comments; 1808 } real_jzfile; 1809 1810 void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) { 1811 // For now we only compile all methods in all classes in zip/jar files 1812 tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir); 1813 tty->cr(); 1814 } 1815 1816 void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) { 1817 real_jzfile* zip = (real_jzfile*) _zip; 1818 tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name); 1819 tty->cr(); 1820 // Iterate over all entries in zip file 1821 for (int n = 0; ; n++) { 1822 real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n)); 1823 if (ze == NULL) break; 1824 ClassLoader::compile_the_world_in(ze->name, loader, CHECK); 1825 } 1826 if (HAS_PENDING_EXCEPTION) { 1827 if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) { 1828 CLEAR_PENDING_EXCEPTION; 1829 tty->print_cr("\nCompileTheWorld : Ran out of memory\n"); 1830 tty->print_cr("Increase class metadata storage if a limit was set"); 1831 } else { 1832 tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n"); 1833 } 1834 } 1835 } 1836 1837 void ClassLoader::compile_the_world() { 1838 EXCEPTION_MARK; 1839 HandleMark hm(THREAD); 1840 ResourceMark rm(THREAD); 1841 1842 assert(has_jrt_entry(), "Compile The World not supported with exploded module build"); 1843 1844 // Find bootstrap loader 1845 Handle system_class_loader (THREAD, SystemDictionary::java_system_loader()); 1846 jlong start = os::javaTimeMillis(); 1847 1848 // Compile the world for the modular java runtime image 1849 _jrt_entry->compile_the_world(system_class_loader, CATCH); 1850 1851 // Iterate over all bootstrap class path appended entries 1852 ClassPathEntry* e = _first_append_entry; 1853 while (e != NULL) { 1854 assert(!e->is_jrt(), "A modular java runtime image is present on the list of appended entries"); 1855 e->compile_the_world(system_class_loader, CATCH); 1856 e = e->next(); 1857 } 1858 jlong end = os::javaTimeMillis(); 1859 tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)", 1860 _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start)); 1861 { 1862 // Print statistics as if before normal exit: 1863 extern void print_statistics(); 1864 print_statistics(); 1865 } 1866 vm_exit(0); 1867 } 1868 1869 int ClassLoader::_compile_the_world_class_counter = 0; 1870 int ClassLoader::_compile_the_world_method_counter = 0; 1871 static int _codecache_sweep_counter = 0; 1872 1873 // Filter out all exceptions except OOMs 1874 static void clear_pending_exception_if_not_oom(TRAPS) { 1875 if (HAS_PENDING_EXCEPTION && 1876 !PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) { 1877 CLEAR_PENDING_EXCEPTION; 1878 } 1879 // The CHECK at the caller will propagate the exception out 1880 } 1881 1882 /** 1883 * Returns if the given method should be compiled when doing compile-the-world. 1884 * 1885 * TODO: This should be a private method in a CompileTheWorld class. 1886 */ 1887 static bool can_be_compiled(methodHandle m, int comp_level) { 1888 assert(CompileTheWorld, "must be"); 1889 1890 // It's not valid to compile a native wrapper for MethodHandle methods 1891 // that take a MemberName appendix since the bytecode signature is not 1892 // correct. 1893 vmIntrinsics::ID iid = m->intrinsic_id(); 1894 if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) { 1895 return false; 1896 } 1897 1898 return CompilationPolicy::can_be_compiled(m, comp_level); 1899 } 1900 1901 void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) { 1902 if (string_ends_with(name, ".class")) { 1903 // We have a .class file 1904 int len = (int)strlen(name); 1905 char buffer[2048]; 1906 strncpy(buffer, name, len - 6); 1907 buffer[len-6] = 0; 1908 // If the file has a period after removing .class, it's not really a 1909 // valid class file. The class loader will check everything else. 1910 if (strchr(buffer, '.') == NULL) { 1911 _compile_the_world_class_counter++; 1912 if (_compile_the_world_class_counter > CompileTheWorldStopAt) return; 1913 1914 // Construct name without extension 1915 TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK); 1916 // Use loader to load and initialize class 1917 Klass* k = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD); 1918 if (k != NULL && !HAS_PENDING_EXCEPTION) { 1919 k->initialize(THREAD); 1920 } 1921 bool exception_occurred = HAS_PENDING_EXCEPTION; 1922 clear_pending_exception_if_not_oom(CHECK); 1923 if (CompileTheWorldPreloadClasses && k != NULL) { 1924 InstanceKlass* ik = InstanceKlass::cast(k); 1925 ConstantPool::preload_and_initialize_all_classes(ik->constants(), THREAD); 1926 if (HAS_PENDING_EXCEPTION) { 1927 // If something went wrong in preloading we just ignore it 1928 clear_pending_exception_if_not_oom(CHECK); 1929 tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer); 1930 } 1931 } 1932 1933 if (_compile_the_world_class_counter >= CompileTheWorldStartAt) { 1934 if (k == NULL || exception_occurred) { 1935 // If something went wrong (e.g. ExceptionInInitializerError) we skip this class 1936 tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer); 1937 } else { 1938 tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer); 1939 // Preload all classes to get around uncommon traps 1940 // Iterate over all methods in class 1941 int comp_level = CompilationPolicy::policy()->initial_compile_level(); 1942 InstanceKlass* ik = InstanceKlass::cast(k); 1943 for (int n = 0; n < ik->methods()->length(); n++) { 1944 methodHandle m (THREAD, ik->methods()->at(n)); 1945 if (can_be_compiled(m, comp_level)) { 1946 if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) { 1947 // Give sweeper a chance to keep up with CTW 1948 VM_CTWThreshold op; 1949 VMThread::execute(&op); 1950 _codecache_sweep_counter = 0; 1951 } 1952 // Force compilation 1953 CompileBroker::compile_method(m, InvocationEntryBci, comp_level, 1954 methodHandle(), 0, CompileTask::Reason_CTW, THREAD); 1955 if (HAS_PENDING_EXCEPTION) { 1956 clear_pending_exception_if_not_oom(CHECK); 1957 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string()); 1958 } else { 1959 _compile_the_world_method_counter++; 1960 } 1961 if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) { 1962 // Clobber the first compile and force second tier compilation 1963 CompiledMethod* nm = m->code(); 1964 if (nm != NULL && !m->is_method_handle_intrinsic()) { 1965 // Throw out the code so that the code cache doesn't fill up 1966 nm->make_not_entrant(); 1967 } 1968 CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization, 1969 methodHandle(), 0, CompileTask::Reason_CTW, THREAD); 1970 if (HAS_PENDING_EXCEPTION) { 1971 clear_pending_exception_if_not_oom(CHECK); 1972 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string()); 1973 } else { 1974 _compile_the_world_method_counter++; 1975 } 1976 } 1977 } else { 1978 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string()); 1979 } 1980 1981 CompiledMethod* nm = m->code(); 1982 if (nm != NULL && !m->is_method_handle_intrinsic()) { 1983 // Throw out the code so that the code cache doesn't fill up 1984 nm->make_not_entrant(); 1985 } 1986 } 1987 } 1988 } 1989 } 1990 } 1991 } 1992 1993 #endif //PRODUCT 1994 1995 // Please keep following two functions at end of this file. With them placed at top or in middle of the file, 1996 // they could get inlined by agressive compiler, an unknown trick, see bug 6966589. 1997 void PerfClassTraceTime::initialize() { 1998 if (!UsePerfData) return; 1999 2000 if (_eventp != NULL) { 2001 // increment the event counter 2002 _eventp->inc(); 2003 } 2004 2005 // stop the current active thread-local timer to measure inclusive time 2006 _prev_active_event = -1; 2007 for (int i=0; i < EVENT_TYPE_COUNT; i++) { 2008 if (_timers[i].is_active()) { 2009 assert(_prev_active_event == -1, "should have only one active timer"); 2010 _prev_active_event = i; 2011 _timers[i].stop(); 2012 } 2013 } 2014 2015 if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) { 2016 // start the inclusive timer if not recursively called 2017 _t.start(); 2018 } 2019 2020 // start thread-local timer of the given event type 2021 if (!_timers[_event_type].is_active()) { 2022 _timers[_event_type].start(); 2023 } 2024 } 2025 2026 PerfClassTraceTime::~PerfClassTraceTime() { 2027 if (!UsePerfData) return; 2028 2029 // stop the thread-local timer as the event completes 2030 // and resume the thread-local timer of the event next on the stack 2031 _timers[_event_type].stop(); 2032 jlong selftime = _timers[_event_type].ticks(); 2033 2034 if (_prev_active_event >= 0) { 2035 _timers[_prev_active_event].start(); 2036 } 2037 2038 if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return; 2039 2040 // increment the counters only on the leaf call 2041 _t.stop(); 2042 _timep->inc(_t.ticks()); 2043 if (_selftimep != NULL) { 2044 _selftimep->inc(selftime); 2045 } 2046 // add all class loading related event selftime to the accumulated time counter 2047 ClassLoader::perf_accumulated_time()->inc(selftime); 2048 2049 // reset the timer 2050 _timers[_event_type].reset(); 2051 }