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