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