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