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