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