src/share/vm/classfile/classLoader.cpp

Mon, 20 Jan 2014 11:47:07 +0100

author
tschatzl
date
Mon, 20 Jan 2014 11:47:07 +0100
changeset 6229
5a32d2a3cc1e
parent 5723
3a4e6c929bf3
child 6472
2b8e28fdf503
permissions
-rw-r--r--

8027476: Improve performance of Stringtable unlink
8027455: Improve symbol table scan times during gc pauses
Summary: Parallelize string table and symbol table scan during remark and full GC. Some additional statistics output if the experimental flag G1TraceStringSymbolTableScrubbing is set.
Reviewed-by: mgerdin, coleenp, brutisso

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

mercurial