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