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