src/share/vm/classfile/classLoader.cpp

Sat, 01 Sep 2012 13:25:18 -0400

author
coleenp
date
Sat, 01 Sep 2012 13:25:18 -0400
changeset 4037
da91efe96a93
parent 3900
d2a62e0f25eb
child 4261
6cb0d32b828b
permissions
-rw-r--r--

6964458: Reimplement class meta-data storage to use native memory
Summary: Remove PermGen, allocate meta-data in metaspace linked to class loaders, rewrite GC walking, rewrite and rename metadata to be C++ classes
Reviewed-by: jmasa, stefank, never, coleenp, kvn, brutisso, mgerdin, dholmes, jrose, twisti, roland
Contributed-by: jmasa <jon.masamitsu@oracle.com>, stefank <stefan.karlsson@oracle.com>, mgerdin <mikael.gerdin@oracle.com>, never <tom.rodriguez@oracle.com>

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

mercurial