1 /* 2 * Copyright (c) 1997, 2014, 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/classFileParser.hpp" 27 #include "classfile/classFileStream.hpp" 28 #include "classfile/classLoader.hpp" 29 #include "classfile/classLoaderData.inline.hpp" 30 #include "classfile/javaClasses.hpp" 31 #include "classfile/systemDictionary.hpp" 32 #include "classfile/vmSymbols.hpp" 33 #include "compiler/compileBroker.hpp" 34 #include "gc_interface/collectedHeap.inline.hpp" 35 #include "interpreter/bytecodeStream.hpp" 36 #include "interpreter/oopMapCache.hpp" 37 #include "memory/allocation.inline.hpp" 38 #include "memory/generation.hpp" 39 #include "memory/oopFactory.hpp" 40 #include "memory/universe.inline.hpp" 41 #include "oops/instanceKlass.hpp" 42 #include "oops/instanceRefKlass.hpp" 43 #include "oops/oop.inline.hpp" 44 #include "oops/symbol.hpp" 45 #include "prims/jvm_misc.hpp" 46 #include "runtime/arguments.hpp" 47 #include "runtime/compilationPolicy.hpp" 48 #include "runtime/fprofiler.hpp" 49 #include "runtime/handles.hpp" 50 #include "runtime/handles.inline.hpp" 51 #include "runtime/init.hpp" 52 #include "runtime/interfaceSupport.hpp" 53 #include "runtime/java.hpp" 54 #include "runtime/javaCalls.hpp" 55 #include "runtime/os.hpp" 56 #include "runtime/threadCritical.hpp" 57 #include "runtime/timer.hpp" 58 #include "services/management.hpp" 59 #include "services/threadService.hpp" 60 #include "utilities/events.hpp" 61 #include "utilities/hashtable.hpp" 62 #include "utilities/hashtable.inline.hpp" 63 64 // Entry points in zip.dll for loading zip/jar file entries 65 66 typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg); 67 typedef void (JNICALL *ZipClose_t)(jzfile *zip); 68 typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen); 69 typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf); 70 typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf); 71 typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n); 72 73 static ZipOpen_t ZipOpen = NULL; 74 static ZipClose_t ZipClose = NULL; 75 static FindEntry_t FindEntry = NULL; 76 static ReadEntry_t ReadEntry = NULL; 77 static ReadMappedEntry_t ReadMappedEntry = NULL; 78 static GetNextEntry_t GetNextEntry = NULL; 79 static canonicalize_fn_t CanonicalizeEntry = NULL; 80 81 // Globals 82 83 PerfCounter* ClassLoader::_perf_accumulated_time = NULL; 84 PerfCounter* ClassLoader::_perf_classes_inited = NULL; 85 PerfCounter* ClassLoader::_perf_class_init_time = NULL; 86 PerfCounter* ClassLoader::_perf_class_init_selftime = NULL; 87 PerfCounter* ClassLoader::_perf_classes_verified = NULL; 88 PerfCounter* ClassLoader::_perf_class_verify_time = NULL; 89 PerfCounter* ClassLoader::_perf_class_verify_selftime = NULL; 90 PerfCounter* ClassLoader::_perf_classes_linked = NULL; 91 PerfCounter* ClassLoader::_perf_class_link_time = NULL; 92 PerfCounter* ClassLoader::_perf_class_link_selftime = NULL; 93 PerfCounter* ClassLoader::_perf_class_parse_time = NULL; 94 PerfCounter* ClassLoader::_perf_class_parse_selftime = NULL; 95 PerfCounter* ClassLoader::_perf_sys_class_lookup_time = NULL; 96 PerfCounter* ClassLoader::_perf_shared_classload_time = NULL; 97 PerfCounter* ClassLoader::_perf_sys_classload_time = NULL; 98 PerfCounter* ClassLoader::_perf_app_classload_time = NULL; 99 PerfCounter* ClassLoader::_perf_app_classload_selftime = NULL; 100 PerfCounter* ClassLoader::_perf_app_classload_count = NULL; 101 PerfCounter* ClassLoader::_perf_define_appclasses = NULL; 102 PerfCounter* ClassLoader::_perf_define_appclass_time = NULL; 103 PerfCounter* ClassLoader::_perf_define_appclass_selftime = NULL; 104 PerfCounter* ClassLoader::_perf_app_classfile_bytes_read = NULL; 105 PerfCounter* ClassLoader::_perf_sys_classfile_bytes_read = NULL; 106 PerfCounter* ClassLoader::_sync_systemLoaderLockContentionRate = NULL; 107 PerfCounter* ClassLoader::_sync_nonSystemLoaderLockContentionRate = NULL; 108 PerfCounter* ClassLoader::_sync_JVMFindLoadedClassLockFreeCounter = NULL; 109 PerfCounter* ClassLoader::_sync_JVMDefineClassLockFreeCounter = NULL; 110 PerfCounter* ClassLoader::_sync_JNIDefineClassLockFreeCounter = NULL; 111 PerfCounter* ClassLoader::_unsafe_defineClassCallCounter = NULL; 112 PerfCounter* ClassLoader::_isUnsyncloadClass = NULL; 113 PerfCounter* ClassLoader::_load_instance_class_failCounter = NULL; 114 115 ClassPathEntry* ClassLoader::_first_entry = NULL; 116 ClassPathEntry* ClassLoader::_last_entry = NULL; 117 PackageHashtable* ClassLoader::_package_hash_table = NULL; 118 119 // helper routines 120 bool string_starts_with(const char* str, const char* str_to_find) { 121 size_t str_len = strlen(str); 122 size_t str_to_find_len = strlen(str_to_find); 123 if (str_to_find_len > str_len) { 124 return false; 125 } 126 return (strncmp(str, str_to_find, str_to_find_len) == 0); 127 } 128 129 bool string_ends_with(const char* str, const char* str_to_find) { 130 size_t str_len = strlen(str); 131 size_t str_to_find_len = strlen(str_to_find); 132 if (str_to_find_len > str_len) { 133 return false; 134 } 135 return (strncmp(str + (str_len - str_to_find_len), str_to_find, str_to_find_len) == 0); 136 } 137 138 139 MetaIndex::MetaIndex(char** meta_package_names, int num_meta_package_names) { 140 if (num_meta_package_names == 0) { 141 _meta_package_names = NULL; 142 _num_meta_package_names = 0; 143 } else { 144 _meta_package_names = NEW_C_HEAP_ARRAY(char*, num_meta_package_names, mtClass); 145 _num_meta_package_names = num_meta_package_names; 146 memcpy(_meta_package_names, meta_package_names, num_meta_package_names * sizeof(char*)); 147 } 148 } 149 150 151 MetaIndex::~MetaIndex() { 152 FREE_C_HEAP_ARRAY(char*, _meta_package_names, mtClass); 153 } 154 155 156 bool MetaIndex::may_contain(const char* class_name) { 157 if ( _num_meta_package_names == 0) { 158 return false; 159 } 160 size_t class_name_len = strlen(class_name); 161 for (int i = 0; i < _num_meta_package_names; i++) { 162 char* pkg = _meta_package_names[i]; 163 size_t pkg_len = strlen(pkg); 164 size_t min_len = MIN2(class_name_len, pkg_len); 165 if (!strncmp(class_name, pkg, min_len)) { 166 return true; 167 } 168 } 169 return false; 170 } 171 172 173 ClassPathEntry::ClassPathEntry() { 174 set_next(NULL); 175 } 176 177 178 bool ClassPathEntry::is_lazy() { 179 return false; 180 } 181 182 ClassPathDirEntry::ClassPathDirEntry(char* dir) : ClassPathEntry() { 183 _dir = NEW_C_HEAP_ARRAY(char, strlen(dir)+1, mtClass); 184 strcpy(_dir, dir); 185 } 186 187 188 ClassFileStream* ClassPathDirEntry::open_stream(const char* name, TRAPS) { 189 // construct full path name 190 char path[JVM_MAXPATHLEN]; 191 if (jio_snprintf(path, sizeof(path), "%s%s%s", _dir, os::file_separator(), name) == -1) { 192 return NULL; 193 } 194 // check if file exists 195 struct stat st; 196 if (os::stat(path, &st) == 0) { 197 // found file, open it 198 int file_handle = os::open(path, 0, 0); 199 if (file_handle != -1) { 200 // read contents into resource array 201 u1* buffer = NEW_RESOURCE_ARRAY(u1, st.st_size); 202 size_t num_read = os::read(file_handle, (char*) buffer, st.st_size); 203 // close file 204 os::close(file_handle); 205 // construct ClassFileStream 206 if (num_read == (size_t)st.st_size) { 207 if (UsePerfData) { 208 ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read); 209 } 210 return new ClassFileStream(buffer, st.st_size, _dir); // Resource allocated 211 } 212 } 213 } 214 return NULL; 215 } 216 217 218 ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name) : ClassPathEntry() { 219 _zip = zip; 220 _zip_name = NEW_C_HEAP_ARRAY(char, strlen(zip_name)+1, mtClass); 221 strcpy(_zip_name, zip_name); 222 } 223 224 ClassPathZipEntry::~ClassPathZipEntry() { 225 if (ZipClose != NULL) { 226 (*ZipClose)(_zip); 227 } 228 FREE_C_HEAP_ARRAY(char, _zip_name, mtClass); 229 } 230 231 ClassFileStream* ClassPathZipEntry::open_stream(const char* name, TRAPS) { 232 // enable call to C land 233 JavaThread* thread = JavaThread::current(); 234 ThreadToNativeFromVM ttn(thread); 235 // check whether zip archive contains name 236 jint filesize, name_len; 237 jzentry* entry = (*FindEntry)(_zip, name, &filesize, &name_len); 238 if (entry == NULL) return NULL; 239 u1* buffer; 240 char name_buf[128]; 241 char* filename; 242 if (name_len < 128) { 243 filename = name_buf; 244 } else { 245 filename = NEW_RESOURCE_ARRAY(char, name_len + 1); 246 } 247 248 // file found, get pointer to class in mmaped jar file. 249 if (ReadMappedEntry == NULL || 250 !(*ReadMappedEntry)(_zip, entry, &buffer, filename)) { 251 // mmaped access not available, perhaps due to compression, 252 // read contents into resource array 253 buffer = NEW_RESOURCE_ARRAY(u1, filesize); 254 if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL; 255 } 256 if (UsePerfData) { 257 ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize); 258 } 259 // return result 260 return new ClassFileStream(buffer, filesize, _zip_name); // Resource allocated 261 } 262 263 // invoke function for each entry in the zip file 264 void ClassPathZipEntry::contents_do(void f(const char* name, void* context), void* context) { 265 JavaThread* thread = JavaThread::current(); 266 HandleMark handle_mark(thread); 267 ThreadToNativeFromVM ttn(thread); 268 for (int n = 0; ; n++) { 269 jzentry * ze = ((*GetNextEntry)(_zip, n)); 270 if (ze == NULL) break; 271 (*f)(ze->name, context); 272 } 273 } 274 275 LazyClassPathEntry::LazyClassPathEntry(char* path, const struct stat* st) : ClassPathEntry() { 276 _path = os::strdup_check_oom(path); 277 _st = *st; 278 _meta_index = NULL; 279 _resolved_entry = NULL; 280 _has_error = false; 281 } 282 283 LazyClassPathEntry::~LazyClassPathEntry() { 284 os::free(_path); 285 } 286 287 bool LazyClassPathEntry::is_jar_file() { 288 return ((_st.st_mode & S_IFREG) == S_IFREG); 289 } 290 291 ClassPathEntry* LazyClassPathEntry::resolve_entry(TRAPS) { 292 if (_resolved_entry != NULL) { 293 return (ClassPathEntry*) _resolved_entry; 294 } 295 ClassPathEntry* new_entry = NULL; 296 new_entry = ClassLoader::create_class_path_entry(_path, &_st, false, CHECK_NULL); 297 { 298 ThreadCritical tc; 299 if (_resolved_entry == NULL) { 300 _resolved_entry = new_entry; 301 return new_entry; 302 } 303 } 304 assert(_resolved_entry != NULL, "bug in MT-safe resolution logic"); 305 delete new_entry; 306 return (ClassPathEntry*) _resolved_entry; 307 } 308 309 ClassFileStream* LazyClassPathEntry::open_stream(const char* name, TRAPS) { 310 if (_meta_index != NULL && 311 !_meta_index->may_contain(name)) { 312 return NULL; 313 } 314 if (_has_error) { 315 return NULL; 316 } 317 ClassPathEntry* cpe = resolve_entry(THREAD); 318 if (cpe == NULL) { 319 _has_error = true; 320 return NULL; 321 } else { 322 return cpe->open_stream(name, THREAD); 323 } 324 } 325 326 bool LazyClassPathEntry::is_lazy() { 327 return true; 328 } 329 330 static void print_meta_index(LazyClassPathEntry* entry, 331 GrowableArray<char*>& meta_packages) { 332 tty->print("[Meta index for %s=", entry->name()); 333 for (int i = 0; i < meta_packages.length(); i++) { 334 if (i > 0) tty->print(" "); 335 tty->print("%s", meta_packages.at(i)); 336 } 337 tty->print_cr("]"); 338 } 339 340 341 void ClassLoader::setup_meta_index() { 342 // Set up meta index which allows us to open boot jars lazily if 343 // class data sharing is enabled 344 const char* known_version = "% VERSION 2"; 345 char* meta_index_path = Arguments::get_meta_index_path(); 346 char* meta_index_dir = Arguments::get_meta_index_dir(); 347 FILE* file = fopen(meta_index_path, "r"); 348 int line_no = 0; 349 if (file != NULL) { 350 ResourceMark rm; 351 LazyClassPathEntry* cur_entry = NULL; 352 GrowableArray<char*> boot_class_path_packages(10); 353 char package_name[256]; 354 bool skipCurrentJar = false; 355 while (fgets(package_name, sizeof(package_name), file) != NULL) { 356 ++line_no; 357 // Remove trailing newline 358 package_name[strlen(package_name) - 1] = '\0'; 359 switch(package_name[0]) { 360 case '%': 361 { 362 if ((line_no == 1) && (strcmp(package_name, known_version) != 0)) { 363 if (TraceClassLoading && Verbose) { 364 tty->print("[Unsupported meta index version]"); 365 } 366 fclose(file); 367 return; 368 } 369 } 370 371 // These directives indicate jar files which contain only 372 // classes, only non-classfile resources, or a combination of 373 // the two. See src/share/classes/sun/misc/MetaIndex.java and 374 // make/tools/MetaIndex/BuildMetaIndex.java in the J2SE 375 // workspace. 376 case '#': 377 case '!': 378 case '@': 379 { 380 // Hand off current packages to current lazy entry (if any) 381 if ((cur_entry != NULL) && 382 (boot_class_path_packages.length() > 0)) { 383 if (TraceClassLoading && Verbose) { 384 print_meta_index(cur_entry, boot_class_path_packages); 385 } 386 MetaIndex* index = new MetaIndex(boot_class_path_packages.adr_at(0), 387 boot_class_path_packages.length()); 388 cur_entry->set_meta_index(index); 389 } 390 cur_entry = NULL; 391 boot_class_path_packages.clear(); 392 393 // Find lazy entry corresponding to this jar file 394 for (ClassPathEntry* entry = _first_entry; entry != NULL; entry = entry->next()) { 395 if (entry->is_lazy() && 396 string_starts_with(entry->name(), meta_index_dir) && 397 string_ends_with(entry->name(), &package_name[2])) { 398 cur_entry = (LazyClassPathEntry*) entry; 399 break; 400 } 401 } 402 403 // If the first character is '@', it indicates the following jar 404 // file is a resource only jar file in which case, we should skip 405 // reading the subsequent entries since the resource loading is 406 // totally handled by J2SE side. 407 if (package_name[0] == '@') { 408 if (cur_entry != NULL) { 409 cur_entry->set_meta_index(new MetaIndex(NULL, 0)); 410 } 411 cur_entry = NULL; 412 skipCurrentJar = true; 413 } else { 414 skipCurrentJar = false; 415 } 416 417 break; 418 } 419 420 default: 421 { 422 if (!skipCurrentJar && cur_entry != NULL) { 423 char* new_name = os::strdup_check_oom(package_name); 424 boot_class_path_packages.append(new_name); 425 } 426 } 427 } 428 } 429 // Hand off current packages to current lazy entry (if any) 430 if ((cur_entry != NULL) && 431 (boot_class_path_packages.length() > 0)) { 432 if (TraceClassLoading && Verbose) { 433 print_meta_index(cur_entry, boot_class_path_packages); 434 } 435 MetaIndex* index = new MetaIndex(boot_class_path_packages.adr_at(0), 436 boot_class_path_packages.length()); 437 cur_entry->set_meta_index(index); 438 } 439 fclose(file); 440 } 441 } 442 443 void ClassLoader::setup_bootstrap_search_path() { 444 assert(_first_entry == NULL, "should not setup bootstrap class search path twice"); 445 char* sys_class_path = os::strdup_check_oom(Arguments::get_sysclasspath()); 446 if (TraceClassLoading && Verbose) { 447 tty->print_cr("[Bootstrap loader class path=%s]", sys_class_path); 448 } 449 450 int len = (int)strlen(sys_class_path); 451 int end = 0; 452 453 // Iterate over class path entries 454 for (int start = 0; start < len; start = end) { 455 while (sys_class_path[end] && sys_class_path[end] != os::path_separator()[0]) { 456 end++; 457 } 458 char* path = NEW_C_HEAP_ARRAY(char, end-start+1, mtClass); 459 strncpy(path, &sys_class_path[start], end-start); 460 path[end-start] = '\0'; 461 update_class_path_entry_list(path, false); 462 FREE_C_HEAP_ARRAY(char, path, mtClass); 463 while (sys_class_path[end] == os::path_separator()[0]) { 464 end++; 465 } 466 } 467 os::free(sys_class_path); 468 } 469 470 ClassPathEntry* ClassLoader::create_class_path_entry(char *path, const struct stat* st, bool lazy, TRAPS) { 471 JavaThread* thread = JavaThread::current(); 472 if (lazy) { 473 return new LazyClassPathEntry(path, st); 474 } 475 ClassPathEntry* new_entry = NULL; 476 if ((st->st_mode & S_IFREG) == S_IFREG) { 477 // Regular file, should be a zip file 478 // Canonicalized filename 479 char canonical_path[JVM_MAXPATHLEN]; 480 if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) { 481 // This matches the classic VM 482 THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL); 483 } 484 char* error_msg = NULL; 485 jzfile* zip; 486 { 487 // enable call to C land 488 ThreadToNativeFromVM ttn(thread); 489 HandleMark hm(thread); 490 zip = (*ZipOpen)(canonical_path, &error_msg); 491 } 492 if (zip != NULL && error_msg == NULL) { 493 new_entry = new ClassPathZipEntry(zip, path); 494 if (TraceClassLoading) { 495 tty->print_cr("[Opened %s]", path); 496 } 497 } else { 498 ResourceMark rm(thread); 499 char *msg; 500 if (error_msg == NULL) { 501 msg = NEW_RESOURCE_ARRAY(char, strlen(path) + 128); ; 502 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path); 503 } else { 504 int len = (int)(strlen(path) + strlen(error_msg) + 128); 505 msg = NEW_RESOURCE_ARRAY(char, len); ; 506 jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path); 507 } 508 THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL); 509 } 510 } else { 511 // Directory 512 new_entry = new ClassPathDirEntry(path); 513 if (TraceClassLoading) { 514 tty->print_cr("[Path %s]", path); 515 } 516 } 517 return new_entry; 518 } 519 520 521 // Create a class path zip entry for a given path (return NULL if not found 522 // or zip/JAR file cannot be opened) 523 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path) { 524 // check for a regular file 525 struct stat st; 526 if (os::stat(path, &st) == 0) { 527 if ((st.st_mode & S_IFREG) == S_IFREG) { 528 char orig_path[JVM_MAXPATHLEN]; 529 char canonical_path[JVM_MAXPATHLEN]; 530 531 strcpy(orig_path, path); 532 if (get_canonical_path(orig_path, canonical_path, JVM_MAXPATHLEN)) { 533 char* error_msg = NULL; 534 jzfile* zip; 535 { 536 // enable call to C land 537 JavaThread* thread = JavaThread::current(); 538 ThreadToNativeFromVM ttn(thread); 539 HandleMark hm(thread); 540 zip = (*ZipOpen)(canonical_path, &error_msg); 541 } 542 if (zip != NULL && error_msg == NULL) { 543 // create using canonical path 544 return new ClassPathZipEntry(zip, canonical_path); 545 } 546 } 547 } 548 } 549 return NULL; 550 } 551 552 // returns true if entry already on class path 553 bool ClassLoader::contains_entry(ClassPathEntry *entry) { 554 ClassPathEntry* e = _first_entry; 555 while (e != NULL) { 556 // assume zip entries have been canonicalized 557 if (strcmp(entry->name(), e->name()) == 0) { 558 return true; 559 } 560 e = e->next(); 561 } 562 return false; 563 } 564 565 void ClassLoader::add_to_list(ClassPathEntry *new_entry) { 566 if (new_entry != NULL) { 567 if (_last_entry == NULL) { 568 _first_entry = _last_entry = new_entry; 569 } else { 570 _last_entry->set_next(new_entry); 571 _last_entry = new_entry; 572 } 573 } 574 } 575 576 void ClassLoader::update_class_path_entry_list(char *path, 577 bool check_for_duplicates) { 578 struct stat st; 579 if (os::stat(path, &st) == 0) { 580 // File or directory found 581 ClassPathEntry* new_entry = NULL; 582 Thread* THREAD = Thread::current(); 583 new_entry = create_class_path_entry(path, &st, LazyBootClassLoader, CHECK); 584 // The kernel VM adds dynamically to the end of the classloader path and 585 // doesn't reorder the bootclasspath which would break java.lang.Package 586 // (see PackageInfo). 587 // Add new entry to linked list 588 if (!check_for_duplicates || !contains_entry(new_entry)) { 589 add_to_list(new_entry); 590 } 591 } 592 } 593 594 void ClassLoader::print_bootclasspath() { 595 ClassPathEntry* e = _first_entry; 596 tty->print("[bootclasspath= "); 597 while (e != NULL) { 598 tty->print("%s ;", e->name()); 599 e = e->next(); 600 } 601 tty->print_cr("]"); 602 } 603 604 void ClassLoader::load_zip_library() { 605 assert(ZipOpen == NULL, "should not load zip library twice"); 606 // First make sure native library is loaded 607 os::native_java_library(); 608 // Load zip library 609 char path[JVM_MAXPATHLEN]; 610 char ebuf[1024]; 611 void* handle = NULL; 612 if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) { 613 handle = os::dll_load(path, ebuf, sizeof ebuf); 614 } 615 if (handle == NULL) { 616 vm_exit_during_initialization("Unable to load ZIP library", path); 617 } 618 // Lookup zip entry points 619 ZipOpen = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open")); 620 ZipClose = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close")); 621 FindEntry = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry")); 622 ReadEntry = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry")); 623 ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry")); 624 GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry")); 625 626 // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL 627 if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL || GetNextEntry == NULL) { 628 vm_exit_during_initialization("Corrupted ZIP library", path); 629 } 630 631 // Lookup canonicalize entry in libjava.dll 632 void *javalib_handle = os::native_java_library(); 633 CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize")); 634 // This lookup only works on 1.3. Do not check for non-null here 635 } 636 637 // PackageInfo data exists in order to support the java.lang.Package 638 // class. A Package object provides information about a java package 639 // (version, vendor, etc.) which originates in the manifest of the jar 640 // file supplying the package. For application classes, the ClassLoader 641 // object takes care of this. 642 643 // For system (boot) classes, the Java code in the Package class needs 644 // to be able to identify which source jar file contained the boot 645 // class, so that it can extract the manifest from it. This table 646 // identifies java packages with jar files in the boot classpath. 647 648 // Because the boot classpath cannot change, the classpath index is 649 // sufficient to identify the source jar file or directory. (Since 650 // directories have no manifests, the directory name is not required, 651 // but is available.) 652 653 // When using sharing -- the pathnames of entries in the boot classpath 654 // may not be the same at runtime as they were when the archive was 655 // created (NFS, Samba, etc.). The actual files and directories named 656 // in the classpath must be the same files, in the same order, even 657 // though the exact name is not the same. 658 659 class PackageInfo: public BasicHashtableEntry<mtClass> { 660 public: 661 const char* _pkgname; // Package name 662 int _classpath_index; // Index of directory or JAR file loaded from 663 664 PackageInfo* next() { 665 return (PackageInfo*)BasicHashtableEntry<mtClass>::next(); 666 } 667 668 const char* pkgname() { return _pkgname; } 669 void set_pkgname(char* pkgname) { _pkgname = pkgname; } 670 671 const char* filename() { 672 return ClassLoader::classpath_entry(_classpath_index)->name(); 673 } 674 675 void set_index(int index) { 676 _classpath_index = index; 677 } 678 }; 679 680 681 class PackageHashtable : public BasicHashtable<mtClass> { 682 private: 683 inline unsigned int compute_hash(const char *s, int n) { 684 unsigned int val = 0; 685 while (--n >= 0) { 686 val = *s++ + 31 * val; 687 } 688 return val; 689 } 690 691 PackageInfo* bucket(int index) { 692 return (PackageInfo*)BasicHashtable<mtClass>::bucket(index); 693 } 694 695 PackageInfo* get_entry(int index, unsigned int hash, 696 const char* pkgname, size_t n) { 697 for (PackageInfo* pp = bucket(index); pp != NULL; pp = pp->next()) { 698 if (pp->hash() == hash && 699 strncmp(pkgname, pp->pkgname(), n) == 0 && 700 pp->pkgname()[n] == '\0') { 701 return pp; 702 } 703 } 704 return NULL; 705 } 706 707 public: 708 PackageHashtable(int table_size) 709 : BasicHashtable<mtClass>(table_size, sizeof(PackageInfo)) {} 710 711 PackageHashtable(int table_size, HashtableBucket<mtClass>* t, int number_of_entries) 712 : BasicHashtable<mtClass>(table_size, sizeof(PackageInfo), t, number_of_entries) {} 713 714 PackageInfo* get_entry(const char* pkgname, int n) { 715 unsigned int hash = compute_hash(pkgname, n); 716 return get_entry(hash_to_index(hash), hash, pkgname, n); 717 } 718 719 PackageInfo* new_entry(char* pkgname, int n) { 720 unsigned int hash = compute_hash(pkgname, n); 721 PackageInfo* pp; 722 pp = (PackageInfo*)BasicHashtable<mtClass>::new_entry(hash); 723 pp->set_pkgname(pkgname); 724 return pp; 725 } 726 727 void add_entry(PackageInfo* pp) { 728 int index = hash_to_index(pp->hash()); 729 BasicHashtable<mtClass>::add_entry(index, pp); 730 } 731 732 void copy_pkgnames(const char** packages) { 733 int n = 0; 734 for (int i = 0; i < table_size(); ++i) { 735 for (PackageInfo* pp = bucket(i); pp != NULL; pp = pp->next()) { 736 packages[n++] = pp->pkgname(); 737 } 738 } 739 assert(n == number_of_entries(), "just checking"); 740 } 741 742 void copy_table(char** top, char* end, PackageHashtable* table); 743 }; 744 745 746 void PackageHashtable::copy_table(char** top, char* end, 747 PackageHashtable* table) { 748 // Copy (relocate) the table to the shared space. 749 BasicHashtable<mtClass>::copy_table(top, end); 750 751 // Calculate the space needed for the package name strings. 752 int i; 753 int n = 0; 754 for (i = 0; i < table_size(); ++i) { 755 for (PackageInfo* pp = table->bucket(i); 756 pp != NULL; 757 pp = pp->next()) { 758 n += (int)(strlen(pp->pkgname()) + 1); 759 } 760 } 761 if (*top + n + sizeof(intptr_t) >= end) { 762 report_out_of_shared_space(SharedMiscData); 763 } 764 765 // Copy the table data (the strings) to the shared space. 766 n = align_size_up(n, sizeof(HeapWord)); 767 *(intptr_t*)(*top) = n; 768 *top += sizeof(intptr_t); 769 770 for (i = 0; i < table_size(); ++i) { 771 for (PackageInfo* pp = table->bucket(i); 772 pp != NULL; 773 pp = pp->next()) { 774 int n1 = (int)(strlen(pp->pkgname()) + 1); 775 pp->set_pkgname((char*)memcpy(*top, pp->pkgname(), n1)); 776 *top += n1; 777 } 778 } 779 *top = (char*)align_size_up((intptr_t)*top, sizeof(HeapWord)); 780 } 781 782 783 void ClassLoader::copy_package_info_buckets(char** top, char* end) { 784 _package_hash_table->copy_buckets(top, end); 785 } 786 787 void ClassLoader::copy_package_info_table(char** top, char* end) { 788 _package_hash_table->copy_table(top, end, _package_hash_table); 789 } 790 791 792 PackageInfo* ClassLoader::lookup_package(const char *pkgname) { 793 const char *cp = strrchr(pkgname, '/'); 794 if (cp != NULL) { 795 // Package prefix found 796 int n = cp - pkgname + 1; 797 return _package_hash_table->get_entry(pkgname, n); 798 } 799 return NULL; 800 } 801 802 803 bool ClassLoader::add_package(const char *pkgname, int classpath_index, TRAPS) { 804 assert(pkgname != NULL, "just checking"); 805 // Bootstrap loader no longer holds system loader lock obj serializing 806 // load_instance_class and thereby add_package 807 { 808 MutexLocker ml(PackageTable_lock, THREAD); 809 // First check for previously loaded entry 810 PackageInfo* pp = lookup_package(pkgname); 811 if (pp != NULL) { 812 // Existing entry found, check source of package 813 pp->set_index(classpath_index); 814 return true; 815 } 816 817 const char *cp = strrchr(pkgname, '/'); 818 if (cp != NULL) { 819 // Package prefix found 820 int n = cp - pkgname + 1; 821 822 char* new_pkgname = NEW_C_HEAP_ARRAY(char, n + 1, mtClass); 823 if (new_pkgname == NULL) { 824 return false; 825 } 826 827 memcpy(new_pkgname, pkgname, n); 828 new_pkgname[n] = '\0'; 829 pp = _package_hash_table->new_entry(new_pkgname, n); 830 pp->set_index(classpath_index); 831 832 // Insert into hash table 833 _package_hash_table->add_entry(pp); 834 } 835 return true; 836 } 837 } 838 839 840 oop ClassLoader::get_system_package(const char* name, TRAPS) { 841 PackageInfo* pp; 842 { 843 MutexLocker ml(PackageTable_lock, THREAD); 844 pp = lookup_package(name); 845 } 846 if (pp == NULL) { 847 return NULL; 848 } else { 849 Handle p = java_lang_String::create_from_str(pp->filename(), THREAD); 850 return p(); 851 } 852 } 853 854 855 objArrayOop ClassLoader::get_system_packages(TRAPS) { 856 ResourceMark rm(THREAD); 857 int nof_entries; 858 const char** packages; 859 { 860 MutexLocker ml(PackageTable_lock, THREAD); 861 // Allocate resource char* array containing package names 862 nof_entries = _package_hash_table->number_of_entries(); 863 if ((packages = NEW_RESOURCE_ARRAY(const char*, nof_entries)) == NULL) { 864 return NULL; 865 } 866 _package_hash_table->copy_pkgnames(packages); 867 } 868 // Allocate objArray and fill with java.lang.String 869 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(), 870 nof_entries, CHECK_0); 871 objArrayHandle result(THREAD, r); 872 for (int i = 0; i < nof_entries; i++) { 873 Handle str = java_lang_String::create_from_str(packages[i], CHECK_0); 874 result->obj_at_put(i, str()); 875 } 876 877 return result(); 878 } 879 880 881 instanceKlassHandle ClassLoader::load_classfile(Symbol* h_name, TRAPS) { 882 ResourceMark rm(THREAD); 883 EventMark m("loading class %s", h_name->as_C_string()); 884 ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion); 885 886 stringStream st; 887 // st.print() uses too much stack space while handling a StackOverflowError 888 // st.print("%s.class", h_name->as_utf8()); 889 st.print_raw(h_name->as_utf8()); 890 st.print_raw(".class"); 891 char* name = st.as_string(); 892 893 // Lookup stream for parsing .class file 894 ClassFileStream* stream = NULL; 895 int classpath_index = 0; 896 { 897 PerfClassTraceTime vmtimer(perf_sys_class_lookup_time(), 898 ((JavaThread*) THREAD)->get_thread_stat()->perf_timers_addr(), 899 PerfClassTraceTime::CLASS_LOAD); 900 ClassPathEntry* e = _first_entry; 901 while (e != NULL) { 902 stream = e->open_stream(name, CHECK_NULL); 903 if (stream != NULL) { 904 break; 905 } 906 e = e->next(); 907 ++classpath_index; 908 } 909 } 910 911 instanceKlassHandle h; 912 if (stream != NULL) { 913 914 // class file found, parse it 915 ClassFileParser parser(stream); 916 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data(); 917 Handle protection_domain; 918 TempNewSymbol parsed_name = NULL; 919 instanceKlassHandle result = parser.parseClassFile(h_name, 920 loader_data, 921 protection_domain, 922 parsed_name, 923 false, 924 CHECK_(h)); 925 926 // add to package table 927 if (add_package(name, classpath_index, THREAD)) { 928 h = result; 929 } 930 } 931 932 return h; 933 } 934 935 936 void ClassLoader::create_package_info_table(HashtableBucket<mtClass> *t, int length, 937 int number_of_entries) { 938 assert(_package_hash_table == NULL, "One package info table allowed."); 939 assert(length == package_hash_table_size * sizeof(HashtableBucket<mtClass>), 940 "bad shared package info size."); 941 _package_hash_table = new PackageHashtable(package_hash_table_size, t, 942 number_of_entries); 943 } 944 945 946 void ClassLoader::create_package_info_table() { 947 assert(_package_hash_table == NULL, "shouldn't have one yet"); 948 _package_hash_table = new PackageHashtable(package_hash_table_size); 949 } 950 951 952 // Initialize the class loader's access to methods in libzip. Parse and 953 // process the boot classpath into a list ClassPathEntry objects. Once 954 // this list has been created, it must not change order (see class PackageInfo) 955 // it can be appended to and is by jvmti and the kernel vm. 956 957 void ClassLoader::initialize() { 958 assert(_package_hash_table == NULL, "should have been initialized by now."); 959 EXCEPTION_MARK; 960 961 if (UsePerfData) { 962 // jvmstat performance counters 963 NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time"); 964 NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime"); 965 NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self"); 966 NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime"); 967 NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self"); 968 NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime"); 969 NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self"); 970 NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses"); 971 NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses"); 972 NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses"); 973 974 NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime"); 975 NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self"); 976 NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime"); 977 NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime"); 978 NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime"); 979 NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime"); 980 NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self"); 981 NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount"); 982 NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses"); 983 NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime"); 984 NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self"); 985 NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes"); 986 NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes"); 987 988 989 // The following performance counters are added for measuring the impact 990 // of the bug fix of 6365597. They are mainly focused on finding out 991 // the behavior of system & user-defined classloader lock, whether 992 // ClassLoader.loadClass/findClass is being called synchronized or not. 993 // Also two additional counters are created to see whether 'UnsyncloadClass' 994 // flag is being set or not and how many times load_instance_class call 995 // fails with linkageError etc. 996 NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS, 997 "systemLoaderLockContentionRate"); 998 NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS, 999 "nonSystemLoaderLockContentionRate"); 1000 NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS, 1001 "jvmFindLoadedClassNoLockCalls"); 1002 NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS, 1003 "jvmDefineClassNoLockCalls"); 1004 1005 NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS, 1006 "jniDefineClassNoLockCalls"); 1007 1008 NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS, 1009 "unsafeDefineClassCalls"); 1010 1011 NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet"); 1012 NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS, 1013 "loadInstanceClassFailRate"); 1014 1015 // increment the isUnsyncloadClass counter if UnsyncloadClass is set. 1016 if (UnsyncloadClass) { 1017 _isUnsyncloadClass->inc(); 1018 } 1019 } 1020 1021 // lookup zip library entry points 1022 load_zip_library(); 1023 // initialize search path 1024 setup_bootstrap_search_path(); 1025 if (LazyBootClassLoader) { 1026 // set up meta index which makes boot classpath initialization lazier 1027 setup_meta_index(); 1028 } 1029 } 1030 1031 1032 jlong ClassLoader::classloader_time_ms() { 1033 return UsePerfData ? 1034 Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1; 1035 } 1036 1037 jlong ClassLoader::class_init_count() { 1038 return UsePerfData ? _perf_classes_inited->get_value() : -1; 1039 } 1040 1041 jlong ClassLoader::class_init_time_ms() { 1042 return UsePerfData ? 1043 Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1; 1044 } 1045 1046 jlong ClassLoader::class_verify_time_ms() { 1047 return UsePerfData ? 1048 Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1; 1049 } 1050 1051 jlong ClassLoader::class_link_count() { 1052 return UsePerfData ? _perf_classes_linked->get_value() : -1; 1053 } 1054 1055 jlong ClassLoader::class_link_time_ms() { 1056 return UsePerfData ? 1057 Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1; 1058 } 1059 1060 int ClassLoader::compute_Object_vtable() { 1061 // hardwired for JDK1.2 -- would need to duplicate class file parsing 1062 // code to determine actual value from file 1063 // Would be value '11' if finals were in vtable 1064 int JDK_1_2_Object_vtable_size = 5; 1065 return JDK_1_2_Object_vtable_size * vtableEntry::size(); 1066 } 1067 1068 1069 void classLoader_init() { 1070 ClassLoader::initialize(); 1071 } 1072 1073 1074 bool ClassLoader::get_canonical_path(char* orig, char* out, int len) { 1075 assert(orig != NULL && out != NULL && len > 0, "bad arguments"); 1076 if (CanonicalizeEntry != NULL) { 1077 JNIEnv* env = JavaThread::current()->jni_environment(); 1078 if ((CanonicalizeEntry)(env, os::native_path(orig), out, len) < 0) { 1079 return false; 1080 } 1081 } else { 1082 // On JDK 1.2.2 the Canonicalize does not exist, so just do nothing 1083 strncpy(out, orig, len); 1084 out[len - 1] = '\0'; 1085 } 1086 return true; 1087 } 1088 1089 #ifndef PRODUCT 1090 1091 void ClassLoader::verify() { 1092 _package_hash_table->verify(); 1093 } 1094 1095 1096 // CompileTheWorld 1097 // 1098 // Iterates over all class path entries and forces compilation of all methods 1099 // in all classes found. Currently, only zip/jar archives are searched. 1100 // 1101 // The classes are loaded by the Java level bootstrap class loader, and the 1102 // initializer is called. If DelayCompilationDuringStartup is true (default), 1103 // the interpreter will run the initialization code. Note that forcing 1104 // initialization in this way could potentially lead to initialization order 1105 // problems, in which case we could just force the initialization bit to be set. 1106 1107 1108 // We need to iterate over the contents of a zip/jar file, so we replicate the 1109 // jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile, 1110 // since jzfile already has a void* definition. 1111 // 1112 // Note that this is only used in debug mode. 1113 // 1114 // HotSpot integration note: 1115 // Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build 1116 1117 1118 // JDK 1.3 version 1119 typedef struct real_jzentry { /* Zip file entry */ 1120 char *name; /* entry name */ 1121 jint time; /* modification time */ 1122 jint size; /* size of uncompressed data */ 1123 jint csize; /* size of compressed data (zero if uncompressed) */ 1124 jint crc; /* crc of uncompressed data */ 1125 char *comment; /* optional zip file comment */ 1126 jbyte *extra; /* optional extra data */ 1127 jint pos; /* position of LOC header (if negative) or data */ 1128 } real_jzentry; 1129 1130 typedef struct real_jzfile { /* Zip file */ 1131 char *name; /* zip file name */ 1132 jint refs; /* number of active references */ 1133 jint fd; /* open file descriptor */ 1134 void *lock; /* read lock */ 1135 char *comment; /* zip file comment */ 1136 char *msg; /* zip error message */ 1137 void *entries; /* array of hash cells */ 1138 jint total; /* total number of entries */ 1139 unsigned short *table; /* Hash chain heads: indexes into entries */ 1140 jint tablelen; /* number of hash eads */ 1141 real_jzfile *next; /* next zip file in search list */ 1142 jzentry *cache; /* we cache the most recently freed jzentry */ 1143 /* Information on metadata names in META-INF directory */ 1144 char **metanames; /* array of meta names (may have null names) */ 1145 jint metacount; /* number of slots in metanames array */ 1146 /* If there are any per-entry comments, they are in the comments array */ 1147 char **comments; 1148 } real_jzfile; 1149 1150 void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) { 1151 // For now we only compile all methods in all classes in zip/jar files 1152 tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir); 1153 tty->cr(); 1154 } 1155 1156 1157 bool ClassPathDirEntry::is_rt_jar() { 1158 return false; 1159 } 1160 1161 void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) { 1162 real_jzfile* zip = (real_jzfile*) _zip; 1163 tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name); 1164 tty->cr(); 1165 // Iterate over all entries in zip file 1166 for (int n = 0; ; n++) { 1167 real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n)); 1168 if (ze == NULL) break; 1169 ClassLoader::compile_the_world_in(ze->name, loader, CHECK); 1170 } 1171 if (HAS_PENDING_EXCEPTION) { 1172 if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) { 1173 CLEAR_PENDING_EXCEPTION; 1174 tty->print_cr("\nCompileTheWorld : Ran out of memory\n"); 1175 tty->print_cr("Increase class metadata storage if a limit was set"); 1176 } else { 1177 tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n"); 1178 } 1179 } 1180 } 1181 1182 bool ClassPathZipEntry::is_rt_jar() { 1183 real_jzfile* zip = (real_jzfile*) _zip; 1184 int len = (int)strlen(zip->name); 1185 // Check whether zip name ends in "rt.jar" 1186 // This will match other archives named rt.jar as well, but this is 1187 // only used for debugging. 1188 return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0); 1189 } 1190 1191 void LazyClassPathEntry::compile_the_world(Handle loader, TRAPS) { 1192 ClassPathEntry* cpe = resolve_entry(THREAD); 1193 if (cpe != NULL) { 1194 cpe->compile_the_world(loader, CHECK); 1195 } 1196 } 1197 1198 bool LazyClassPathEntry::is_rt_jar() { 1199 Thread* THREAD = Thread::current(); 1200 ClassPathEntry* cpe = resolve_entry(THREAD); 1201 return (cpe != NULL) ? cpe->is_jar_file() : false; 1202 } 1203 1204 void ClassLoader::compile_the_world() { 1205 EXCEPTION_MARK; 1206 HandleMark hm(THREAD); 1207 ResourceMark rm(THREAD); 1208 // Make sure we don't run with background compilation 1209 BackgroundCompilation = false; 1210 // Find bootstrap loader 1211 Handle system_class_loader (THREAD, SystemDictionary::java_system_loader()); 1212 // Iterate over all bootstrap class path entries 1213 ClassPathEntry* e = _first_entry; 1214 jlong start = os::javaTimeMillis(); 1215 while (e != NULL) { 1216 // We stop at rt.jar, unless it is the first bootstrap path entry 1217 if (e->is_rt_jar() && e != _first_entry) break; 1218 e->compile_the_world(system_class_loader, CATCH); 1219 e = e->next(); 1220 } 1221 jlong end = os::javaTimeMillis(); 1222 tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)", 1223 _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start)); 1224 { 1225 // Print statistics as if before normal exit: 1226 extern void print_statistics(); 1227 print_statistics(); 1228 } 1229 vm_exit(0); 1230 } 1231 1232 int ClassLoader::_compile_the_world_class_counter = 0; 1233 int ClassLoader::_compile_the_world_method_counter = 0; 1234 static int _codecache_sweep_counter = 0; 1235 1236 // Filter out all exceptions except OOMs 1237 static void clear_pending_exception_if_not_oom(TRAPS) { 1238 if (HAS_PENDING_EXCEPTION && 1239 !PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) { 1240 CLEAR_PENDING_EXCEPTION; 1241 } 1242 // The CHECK at the caller will propagate the exception out 1243 } 1244 1245 /** 1246 * Returns if the given method should be compiled when doing compile-the-world. 1247 * 1248 * TODO: This should be a private method in a CompileTheWorld class. 1249 */ 1250 static bool can_be_compiled(methodHandle m, int comp_level) { 1251 assert(CompileTheWorld, "must be"); 1252 1253 // It's not valid to compile a native wrapper for MethodHandle methods 1254 // that take a MemberName appendix since the bytecode signature is not 1255 // correct. 1256 vmIntrinsics::ID iid = m->intrinsic_id(); 1257 if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) { 1258 return false; 1259 } 1260 1261 return CompilationPolicy::can_be_compiled(m, comp_level); 1262 } 1263 1264 void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) { 1265 int len = (int)strlen(name); 1266 if (len > 6 && strcmp(".class", name + len - 6) == 0) { 1267 // We have a .class file 1268 char buffer[2048]; 1269 strncpy(buffer, name, len - 6); 1270 buffer[len-6] = 0; 1271 // If the file has a period after removing .class, it's not really a 1272 // valid class file. The class loader will check everything else. 1273 if (strchr(buffer, '.') == NULL) { 1274 _compile_the_world_class_counter++; 1275 if (_compile_the_world_class_counter > CompileTheWorldStopAt) return; 1276 1277 // Construct name without extension 1278 TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK); 1279 // Use loader to load and initialize class 1280 Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD); 1281 instanceKlassHandle k (THREAD, ik); 1282 if (k.not_null() && !HAS_PENDING_EXCEPTION) { 1283 k->initialize(THREAD); 1284 } 1285 bool exception_occurred = HAS_PENDING_EXCEPTION; 1286 clear_pending_exception_if_not_oom(CHECK); 1287 if (CompileTheWorldPreloadClasses && k.not_null()) { 1288 ConstantPool::preload_and_initialize_all_classes(k->constants(), THREAD); 1289 if (HAS_PENDING_EXCEPTION) { 1290 // If something went wrong in preloading we just ignore it 1291 clear_pending_exception_if_not_oom(CHECK); 1292 tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer); 1293 } 1294 } 1295 1296 if (_compile_the_world_class_counter >= CompileTheWorldStartAt) { 1297 if (k.is_null() || exception_occurred) { 1298 // If something went wrong (e.g. ExceptionInInitializerError) we skip this class 1299 tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer); 1300 } else { 1301 tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer); 1302 // Preload all classes to get around uncommon traps 1303 // Iterate over all methods in class 1304 int comp_level = CompilationPolicy::policy()->initial_compile_level(); 1305 for (int n = 0; n < k->methods()->length(); n++) { 1306 methodHandle m (THREAD, k->methods()->at(n)); 1307 if (can_be_compiled(m, comp_level)) { 1308 if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) { 1309 // Give sweeper a chance to keep up with CTW 1310 VM_ForceSafepoint op; 1311 VMThread::execute(&op); 1312 _codecache_sweep_counter = 0; 1313 } 1314 // Force compilation 1315 CompileBroker::compile_method(m, InvocationEntryBci, comp_level, 1316 methodHandle(), 0, "CTW", THREAD); 1317 if (HAS_PENDING_EXCEPTION) { 1318 clear_pending_exception_if_not_oom(CHECK); 1319 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string()); 1320 } else { 1321 _compile_the_world_method_counter++; 1322 } 1323 if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) { 1324 // Clobber the first compile and force second tier compilation 1325 nmethod* nm = m->code(); 1326 if (nm != NULL) { 1327 // Throw out the code so that the code cache doesn't fill up 1328 nm->make_not_entrant(); 1329 m->clear_code(); 1330 } 1331 CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization, 1332 methodHandle(), 0, "CTW", THREAD); 1333 if (HAS_PENDING_EXCEPTION) { 1334 clear_pending_exception_if_not_oom(CHECK); 1335 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string()); 1336 } else { 1337 _compile_the_world_method_counter++; 1338 } 1339 } 1340 } else { 1341 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string()); 1342 } 1343 1344 nmethod* nm = m->code(); 1345 if (nm != NULL) { 1346 // Throw out the code so that the code cache doesn't fill up 1347 nm->make_not_entrant(); 1348 m->clear_code(); 1349 } 1350 } 1351 } 1352 } 1353 } 1354 } 1355 } 1356 1357 #endif //PRODUCT 1358 1359 // Please keep following two functions at end of this file. With them placed at top or in middle of the file, 1360 // they could get inlined by agressive compiler, an unknown trick, see bug 6966589. 1361 void PerfClassTraceTime::initialize() { 1362 if (!UsePerfData) return; 1363 1364 if (_eventp != NULL) { 1365 // increment the event counter 1366 _eventp->inc(); 1367 } 1368 1369 // stop the current active thread-local timer to measure inclusive time 1370 _prev_active_event = -1; 1371 for (int i=0; i < EVENT_TYPE_COUNT; i++) { 1372 if (_timers[i].is_active()) { 1373 assert(_prev_active_event == -1, "should have only one active timer"); 1374 _prev_active_event = i; 1375 _timers[i].stop(); 1376 } 1377 } 1378 1379 if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) { 1380 // start the inclusive timer if not recursively called 1381 _t.start(); 1382 } 1383 1384 // start thread-local timer of the given event type 1385 if (!_timers[_event_type].is_active()) { 1386 _timers[_event_type].start(); 1387 } 1388 } 1389 1390 PerfClassTraceTime::~PerfClassTraceTime() { 1391 if (!UsePerfData) return; 1392 1393 // stop the thread-local timer as the event completes 1394 // and resume the thread-local timer of the event next on the stack 1395 _timers[_event_type].stop(); 1396 jlong selftime = _timers[_event_type].ticks(); 1397 1398 if (_prev_active_event >= 0) { 1399 _timers[_prev_active_event].start(); 1400 } 1401 1402 if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return; 1403 1404 // increment the counters only on the leaf call 1405 _t.stop(); 1406 _timep->inc(_t.ticks()); 1407 if (_selftimep != NULL) { 1408 _selftimep->inc(selftime); 1409 } 1410 // add all class loading related event selftime to the accumulated time counter 1411 ClassLoader::perf_accumulated_time()->inc(selftime); 1412 1413 // reset the timer 1414 _timers[_event_type].reset(); 1415 }