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