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