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