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