src/share/vm/classfile/classLoader.cpp

Wed, 07 Nov 2012 17:53:02 -0500

author
bpittore
date
Wed, 07 Nov 2012 17:53:02 -0500
changeset 4261
6cb0d32b828b
parent 4037
da91efe96a93
child 4304
90273fc0a981
permissions
-rw-r--r--

8001185: parsing of sun.boot.library.path in os::dll_build_name somewhat broken
Summary: dll_dir can contain multiple paths, need to parse them correctly when loading agents
Reviewed-by: dholmes, dlong
Contributed-by: bill.pittore@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   void* handle = NULL;
   609   if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {
   610     handle = os::dll_load(path, ebuf, sizeof ebuf);
   611   }
   612   if (handle == NULL) {
   613     vm_exit_during_initialization("Unable to load ZIP library", path);
   614   }
   615   // Lookup zip entry points
   616   ZipOpen      = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));
   617   ZipClose     = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));
   618   FindEntry    = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));
   619   ReadEntry    = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
   620   ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));
   621   GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));
   623   // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
   624   if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL || GetNextEntry == NULL) {
   625     vm_exit_during_initialization("Corrupted ZIP library", path);
   626   }
   628   // Lookup canonicalize entry in libjava.dll
   629   void *javalib_handle = os::native_java_library();
   630   CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));
   631   // This lookup only works on 1.3. Do not check for non-null here
   632 }
   634 // PackageInfo data exists in order to support the java.lang.Package
   635 // class.  A Package object provides information about a java package
   636 // (version, vendor, etc.) which originates in the manifest of the jar
   637 // file supplying the package.  For application classes, the ClassLoader
   638 // object takes care of this.
   640 // For system (boot) classes, the Java code in the Package class needs
   641 // to be able to identify which source jar file contained the boot
   642 // class, so that it can extract the manifest from it.  This table
   643 // identifies java packages with jar files in the boot classpath.
   645 // Because the boot classpath cannot change, the classpath index is
   646 // sufficient to identify the source jar file or directory.  (Since
   647 // directories have no manifests, the directory name is not required,
   648 // but is available.)
   650 // When using sharing -- the pathnames of entries in the boot classpath
   651 // may not be the same at runtime as they were when the archive was
   652 // created (NFS, Samba, etc.).  The actual files and directories named
   653 // in the classpath must be the same files, in the same order, even
   654 // though the exact name is not the same.
   656 class PackageInfo: public BasicHashtableEntry<mtClass> {
   657 public:
   658   const char* _pkgname;       // Package name
   659   int _classpath_index;       // Index of directory or JAR file loaded from
   661   PackageInfo* next() {
   662     return (PackageInfo*)BasicHashtableEntry<mtClass>::next();
   663   }
   665   const char* pkgname()           { return _pkgname; }
   666   void set_pkgname(char* pkgname) { _pkgname = pkgname; }
   668   const char* filename() {
   669     return ClassLoader::classpath_entry(_classpath_index)->name();
   670   }
   672   void set_index(int index) {
   673     _classpath_index = index;
   674   }
   675 };
   678 class PackageHashtable : public BasicHashtable<mtClass> {
   679 private:
   680   inline unsigned int compute_hash(const char *s, int n) {
   681     unsigned int val = 0;
   682     while (--n >= 0) {
   683       val = *s++ + 31 * val;
   684     }
   685     return val;
   686   }
   688   PackageInfo* bucket(int index) {
   689     return (PackageInfo*)BasicHashtable<mtClass>::bucket(index);
   690   }
   692   PackageInfo* get_entry(int index, unsigned int hash,
   693                          const char* pkgname, size_t n) {
   694     for (PackageInfo* pp = bucket(index); pp != NULL; pp = pp->next()) {
   695       if (pp->hash() == hash &&
   696           strncmp(pkgname, pp->pkgname(), n) == 0 &&
   697           pp->pkgname()[n] == '\0') {
   698         return pp;
   699       }
   700     }
   701     return NULL;
   702   }
   704 public:
   705   PackageHashtable(int table_size)
   706     : BasicHashtable<mtClass>(table_size, sizeof(PackageInfo)) {}
   708   PackageHashtable(int table_size, HashtableBucket<mtClass>* t, int number_of_entries)
   709     : BasicHashtable<mtClass>(table_size, sizeof(PackageInfo), t, number_of_entries) {}
   711   PackageInfo* get_entry(const char* pkgname, int n) {
   712     unsigned int hash = compute_hash(pkgname, n);
   713     return get_entry(hash_to_index(hash), hash, pkgname, n);
   714   }
   716   PackageInfo* new_entry(char* pkgname, int n) {
   717     unsigned int hash = compute_hash(pkgname, n);
   718     PackageInfo* pp;
   719     pp = (PackageInfo*)BasicHashtable<mtClass>::new_entry(hash);
   720     pp->set_pkgname(pkgname);
   721     return pp;
   722   }
   724   void add_entry(PackageInfo* pp) {
   725     int index = hash_to_index(pp->hash());
   726     BasicHashtable<mtClass>::add_entry(index, pp);
   727   }
   729   void copy_pkgnames(const char** packages) {
   730     int n = 0;
   731     for (int i = 0; i < table_size(); ++i) {
   732       for (PackageInfo* pp = bucket(i); pp != NULL; pp = pp->next()) {
   733         packages[n++] = pp->pkgname();
   734       }
   735     }
   736     assert(n == number_of_entries(), "just checking");
   737   }
   739   void copy_table(char** top, char* end, PackageHashtable* table);
   740 };
   743 void PackageHashtable::copy_table(char** top, char* end,
   744                                   PackageHashtable* table) {
   745   // Copy (relocate) the table to the shared space.
   746   BasicHashtable<mtClass>::copy_table(top, end);
   748   // Calculate the space needed for the package name strings.
   749   int i;
   750   int n = 0;
   751   for (i = 0; i < table_size(); ++i) {
   752     for (PackageInfo* pp = table->bucket(i);
   753                       pp != NULL;
   754                       pp = pp->next()) {
   755       n += (int)(strlen(pp->pkgname()) + 1);
   756     }
   757   }
   758   if (*top + n + sizeof(intptr_t) >= end) {
   759     report_out_of_shared_space(SharedMiscData);
   760   }
   762   // Copy the table data (the strings) to the shared space.
   763   n = align_size_up(n, sizeof(HeapWord));
   764   *(intptr_t*)(*top) = n;
   765   *top += sizeof(intptr_t);
   767   for (i = 0; i < table_size(); ++i) {
   768     for (PackageInfo* pp = table->bucket(i);
   769                       pp != NULL;
   770                       pp = pp->next()) {
   771       int n1 = (int)(strlen(pp->pkgname()) + 1);
   772       pp->set_pkgname((char*)memcpy(*top, pp->pkgname(), n1));
   773       *top += n1;
   774     }
   775   }
   776   *top = (char*)align_size_up((intptr_t)*top, sizeof(HeapWord));
   777 }
   780 void ClassLoader::copy_package_info_buckets(char** top, char* end) {
   781   _package_hash_table->copy_buckets(top, end);
   782 }
   784 void ClassLoader::copy_package_info_table(char** top, char* end) {
   785   _package_hash_table->copy_table(top, end, _package_hash_table);
   786 }
   789 PackageInfo* ClassLoader::lookup_package(const char *pkgname) {
   790   const char *cp = strrchr(pkgname, '/');
   791   if (cp != NULL) {
   792     // Package prefix found
   793     int n = cp - pkgname + 1;
   794     return _package_hash_table->get_entry(pkgname, n);
   795   }
   796   return NULL;
   797 }
   800 bool ClassLoader::add_package(const char *pkgname, int classpath_index, TRAPS) {
   801   assert(pkgname != NULL, "just checking");
   802   // Bootstrap loader no longer holds system loader lock obj serializing
   803   // load_instance_class and thereby add_package
   804   {
   805     MutexLocker ml(PackageTable_lock, THREAD);
   806     // First check for previously loaded entry
   807     PackageInfo* pp = lookup_package(pkgname);
   808     if (pp != NULL) {
   809       // Existing entry found, check source of package
   810       pp->set_index(classpath_index);
   811       return true;
   812     }
   814     const char *cp = strrchr(pkgname, '/');
   815     if (cp != NULL) {
   816       // Package prefix found
   817       int n = cp - pkgname + 1;
   819       char* new_pkgname = NEW_C_HEAP_ARRAY(char, n + 1, mtClass);
   820       if (new_pkgname == NULL) {
   821         return false;
   822       }
   824       memcpy(new_pkgname, pkgname, n);
   825       new_pkgname[n] = '\0';
   826       pp = _package_hash_table->new_entry(new_pkgname, n);
   827       pp->set_index(classpath_index);
   829       // Insert into hash table
   830       _package_hash_table->add_entry(pp);
   831     }
   832     return true;
   833   }
   834 }
   837 oop ClassLoader::get_system_package(const char* name, TRAPS) {
   838   PackageInfo* pp;
   839   {
   840     MutexLocker ml(PackageTable_lock, THREAD);
   841     pp = lookup_package(name);
   842   }
   843   if (pp == NULL) {
   844     return NULL;
   845   } else {
   846     Handle p = java_lang_String::create_from_str(pp->filename(), THREAD);
   847     return p();
   848   }
   849 }
   852 objArrayOop ClassLoader::get_system_packages(TRAPS) {
   853   ResourceMark rm(THREAD);
   854   int nof_entries;
   855   const char** packages;
   856   {
   857     MutexLocker ml(PackageTable_lock, THREAD);
   858     // Allocate resource char* array containing package names
   859     nof_entries = _package_hash_table->number_of_entries();
   860     if ((packages = NEW_RESOURCE_ARRAY(const char*, nof_entries)) == NULL) {
   861       return NULL;
   862     }
   863     _package_hash_table->copy_pkgnames(packages);
   864   }
   865   // Allocate objArray and fill with java.lang.String
   866   objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
   867                                            nof_entries, CHECK_0);
   868   objArrayHandle result(THREAD, r);
   869   for (int i = 0; i < nof_entries; i++) {
   870     Handle str = java_lang_String::create_from_str(packages[i], CHECK_0);
   871     result->obj_at_put(i, str());
   872   }
   874   return result();
   875 }
   878 instanceKlassHandle ClassLoader::load_classfile(Symbol* h_name, TRAPS) {
   879   ResourceMark rm(THREAD);
   880   EventMark m("loading class " INTPTR_FORMAT, (address)h_name);
   881   ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion);
   883   stringStream st;
   884   // st.print() uses too much stack space while handling a StackOverflowError
   885   // st.print("%s.class", h_name->as_utf8());
   886   st.print_raw(h_name->as_utf8());
   887   st.print_raw(".class");
   888   char* name = st.as_string();
   890   // Lookup stream for parsing .class file
   891   ClassFileStream* stream = NULL;
   892   int classpath_index = 0;
   893   {
   894     PerfClassTraceTime vmtimer(perf_sys_class_lookup_time(),
   895                                ((JavaThread*) THREAD)->get_thread_stat()->perf_timers_addr(),
   896                                PerfClassTraceTime::CLASS_LOAD);
   897     ClassPathEntry* e = _first_entry;
   898     while (e != NULL) {
   899       stream = e->open_stream(name);
   900       if (stream != NULL) {
   901         break;
   902       }
   903       e = e->next();
   904       ++classpath_index;
   905     }
   906   }
   908   instanceKlassHandle h;
   909   if (stream != NULL) {
   911     // class file found, parse it
   912     ClassFileParser parser(stream);
   913     Handle class_loader;
   914     Handle protection_domain;
   915     TempNewSymbol parsed_name = NULL;
   916     instanceKlassHandle result = parser.parseClassFile(h_name,
   917                                                        class_loader,
   918                                                        protection_domain,
   919                                                        parsed_name,
   920                                                        false,
   921                                                        CHECK_(h));
   923     // add to package table
   924     if (add_package(name, classpath_index, THREAD)) {
   925       h = result;
   926     }
   927   }
   929   return h;
   930 }
   933 void ClassLoader::create_package_info_table(HashtableBucket<mtClass> *t, int length,
   934                                             int number_of_entries) {
   935   assert(_package_hash_table == NULL, "One package info table allowed.");
   936   assert(length == package_hash_table_size * sizeof(HashtableBucket<mtClass>),
   937          "bad shared package info size.");
   938   _package_hash_table = new PackageHashtable(package_hash_table_size, t,
   939                                              number_of_entries);
   940 }
   943 void ClassLoader::create_package_info_table() {
   944     assert(_package_hash_table == NULL, "shouldn't have one yet");
   945     _package_hash_table = new PackageHashtable(package_hash_table_size);
   946 }
   949 // Initialize the class loader's access to methods in libzip.  Parse and
   950 // process the boot classpath into a list ClassPathEntry objects.  Once
   951 // this list has been created, it must not change order (see class PackageInfo)
   952 // it can be appended to and is by jvmti and the kernel vm.
   954 void ClassLoader::initialize() {
   955   assert(_package_hash_table == NULL, "should have been initialized by now.");
   956   EXCEPTION_MARK;
   958   if (UsePerfData) {
   959     // jvmstat performance counters
   960     NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");
   961     NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");
   962     NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");
   963     NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");
   964     NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");
   965     NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");
   966     NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");
   967     NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");
   968     NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");
   969     NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");
   971     NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime");
   972     NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self");
   973     NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime");
   974     NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");
   975     NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");
   976     NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");
   977     NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");
   978     NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");
   979     NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");
   980     NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");
   981     NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");
   982     NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");
   983     NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");
   986     // The following performance counters are added for measuring the impact
   987     // of the bug fix of 6365597. They are mainly focused on finding out
   988     // the behavior of system & user-defined classloader lock, whether
   989     // ClassLoader.loadClass/findClass is being called synchronized or not.
   990     // Also two additional counters are created to see whether 'UnsyncloadClass'
   991     // flag is being set or not and how many times load_instance_class call
   992     // fails with linkageError etc.
   993     NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS,
   994                         "systemLoaderLockContentionRate");
   995     NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS,
   996                         "nonSystemLoaderLockContentionRate");
   997     NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS,
   998                         "jvmFindLoadedClassNoLockCalls");
   999     NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS,
  1000                         "jvmDefineClassNoLockCalls");
  1002     NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS,
  1003                         "jniDefineClassNoLockCalls");
  1005     NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS,
  1006                         "unsafeDefineClassCalls");
  1008     NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet");
  1009     NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS,
  1010                         "loadInstanceClassFailRate");
  1012     // increment the isUnsyncloadClass counter if UnsyncloadClass is set.
  1013     if (UnsyncloadClass) {
  1014       _isUnsyncloadClass->inc();
  1018   // lookup zip library entry points
  1019   load_zip_library();
  1020   // initialize search path
  1021   setup_bootstrap_search_path();
  1022   if (LazyBootClassLoader) {
  1023     // set up meta index which makes boot classpath initialization lazier
  1024     setup_meta_index();
  1029 jlong ClassLoader::classloader_time_ms() {
  1030   return UsePerfData ?
  1031     Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;
  1034 jlong ClassLoader::class_init_count() {
  1035   return UsePerfData ? _perf_classes_inited->get_value() : -1;
  1038 jlong ClassLoader::class_init_time_ms() {
  1039   return UsePerfData ?
  1040     Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;
  1043 jlong ClassLoader::class_verify_time_ms() {
  1044   return UsePerfData ?
  1045     Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;
  1048 jlong ClassLoader::class_link_count() {
  1049   return UsePerfData ? _perf_classes_linked->get_value() : -1;
  1052 jlong ClassLoader::class_link_time_ms() {
  1053   return UsePerfData ?
  1054     Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;
  1057 int ClassLoader::compute_Object_vtable() {
  1058   // hardwired for JDK1.2 -- would need to duplicate class file parsing
  1059   // code to determine actual value from file
  1060   // Would be value '11' if finals were in vtable
  1061   int JDK_1_2_Object_vtable_size = 5;
  1062   return JDK_1_2_Object_vtable_size * vtableEntry::size();
  1066 void classLoader_init() {
  1067   ClassLoader::initialize();
  1071 bool ClassLoader::get_canonical_path(char* orig, char* out, int len) {
  1072   assert(orig != NULL && out != NULL && len > 0, "bad arguments");
  1073   if (CanonicalizeEntry != NULL) {
  1074     JNIEnv* env = JavaThread::current()->jni_environment();
  1075     if ((CanonicalizeEntry)(env, os::native_path(orig), out, len) < 0) {
  1076       return false;
  1078   } else {
  1079     // On JDK 1.2.2 the Canonicalize does not exist, so just do nothing
  1080     strncpy(out, orig, len);
  1081     out[len - 1] = '\0';
  1083   return true;
  1086 #ifndef PRODUCT
  1088 void ClassLoader::verify() {
  1089   _package_hash_table->verify();
  1093 // CompileTheWorld
  1094 //
  1095 // Iterates over all class path entries and forces compilation of all methods
  1096 // in all classes found. Currently, only zip/jar archives are searched.
  1097 //
  1098 // The classes are loaded by the Java level bootstrap class loader, and the
  1099 // initializer is called. If DelayCompilationDuringStartup is true (default),
  1100 // the interpreter will run the initialization code. Note that forcing
  1101 // initialization in this way could potentially lead to initialization order
  1102 // problems, in which case we could just force the initialization bit to be set.
  1105 // We need to iterate over the contents of a zip/jar file, so we replicate the
  1106 // jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile,
  1107 // since jzfile already has a void* definition.
  1108 //
  1109 // Note that this is only used in debug mode.
  1110 //
  1111 // HotSpot integration note:
  1112 // Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build
  1115 // JDK 1.3 version
  1116 typedef struct real_jzentry13 {         /* Zip file entry */
  1117     char *name;                 /* entry name */
  1118     jint time;                  /* modification time */
  1119     jint size;                  /* size of uncompressed data */
  1120     jint csize;                 /* size of compressed data (zero if uncompressed) */
  1121     jint crc;                   /* crc of uncompressed data */
  1122     char *comment;              /* optional zip file comment */
  1123     jbyte *extra;               /* optional extra data */
  1124     jint pos;                   /* position of LOC header (if negative) or data */
  1125 } real_jzentry13;
  1127 typedef struct real_jzfile13 {  /* Zip file */
  1128     char *name;                 /* zip file name */
  1129     jint refs;                  /* number of active references */
  1130     jint fd;                    /* open file descriptor */
  1131     void *lock;                 /* read lock */
  1132     char *comment;              /* zip file comment */
  1133     char *msg;                  /* zip error message */
  1134     void *entries;              /* array of hash cells */
  1135     jint total;                 /* total number of entries */
  1136     unsigned short *table;      /* Hash chain heads: indexes into entries */
  1137     jint tablelen;              /* number of hash eads */
  1138     real_jzfile13 *next;        /* next zip file in search list */
  1139     jzentry *cache;             /* we cache the most recently freed jzentry */
  1140     /* Information on metadata names in META-INF directory */
  1141     char **metanames;           /* array of meta names (may have null names) */
  1142     jint metacount;             /* number of slots in metanames array */
  1143     /* If there are any per-entry comments, they are in the comments array */
  1144     char **comments;
  1145 } real_jzfile13;
  1147 // JDK 1.2 version
  1148 typedef struct real_jzentry12 {  /* Zip file entry */
  1149     char *name;                  /* entry name */
  1150     jint time;                   /* modification time */
  1151     jint size;                   /* size of uncompressed data */
  1152     jint csize;                  /* size of compressed data (zero if uncompressed) */
  1153     jint crc;                    /* crc of uncompressed data */
  1154     char *comment;               /* optional zip file comment */
  1155     jbyte *extra;                /* optional extra data */
  1156     jint pos;                    /* position of LOC header (if negative) or data */
  1157     struct real_jzentry12 *next; /* next entry in hash table */
  1158 } real_jzentry12;
  1160 typedef struct real_jzfile12 {  /* Zip file */
  1161     char *name;                 /* zip file name */
  1162     jint refs;                  /* number of active references */
  1163     jint fd;                    /* open file descriptor */
  1164     void *lock;                 /* read lock */
  1165     char *comment;              /* zip file comment */
  1166     char *msg;                  /* zip error message */
  1167     real_jzentry12 *entries;    /* array of zip entries */
  1168     jint total;                 /* total number of entries */
  1169     real_jzentry12 **table;     /* hash table of entries */
  1170     jint tablelen;              /* number of buckets */
  1171     jzfile *next;               /* next zip file in search list */
  1172 } real_jzfile12;
  1175 void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {
  1176   // For now we only compile all methods in all classes in zip/jar files
  1177   tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);
  1178   tty->cr();
  1182 bool ClassPathDirEntry::is_rt_jar() {
  1183   return false;
  1186 void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {
  1187   if (JDK_Version::is_jdk12x_version()) {
  1188     compile_the_world12(loader, THREAD);
  1189   } else {
  1190     compile_the_world13(loader, THREAD);
  1192   if (HAS_PENDING_EXCEPTION) {
  1193     if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
  1194       CLEAR_PENDING_EXCEPTION;
  1195       tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
  1196       tty->print_cr("Increase class metadata storage if a limit was set");
  1197     } else {
  1198       tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
  1203 // Version that works for JDK 1.3.x
  1204 void ClassPathZipEntry::compile_the_world13(Handle loader, TRAPS) {
  1205   real_jzfile13* zip = (real_jzfile13*) _zip;
  1206   tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
  1207   tty->cr();
  1208   // Iterate over all entries in zip file
  1209   for (int n = 0; ; n++) {
  1210     real_jzentry13 * ze = (real_jzentry13 *)((*GetNextEntry)(_zip, n));
  1211     if (ze == NULL) break;
  1212     ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
  1217 // Version that works for JDK 1.2.x
  1218 void ClassPathZipEntry::compile_the_world12(Handle loader, TRAPS) {
  1219   real_jzfile12* zip = (real_jzfile12*) _zip;
  1220   tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
  1221   tty->cr();
  1222   // Iterate over all entries in zip file
  1223   for (int n = 0; ; n++) {
  1224     real_jzentry12 * ze = (real_jzentry12 *)((*GetNextEntry)(_zip, n));
  1225     if (ze == NULL) break;
  1226     ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
  1230 bool ClassPathZipEntry::is_rt_jar() {
  1231   if (JDK_Version::is_jdk12x_version()) {
  1232     return is_rt_jar12();
  1233   } else {
  1234     return is_rt_jar13();
  1238 // JDK 1.3 version
  1239 bool ClassPathZipEntry::is_rt_jar13() {
  1240   real_jzfile13* zip = (real_jzfile13*) _zip;
  1241   int len = (int)strlen(zip->name);
  1242   // Check whether zip name ends in "rt.jar"
  1243   // This will match other archives named rt.jar as well, but this is
  1244   // only used for debugging.
  1245   return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0);
  1248 // JDK 1.2 version
  1249 bool ClassPathZipEntry::is_rt_jar12() {
  1250   real_jzfile12* zip = (real_jzfile12*) _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 void LazyClassPathEntry::compile_the_world(Handle loader, TRAPS) {
  1259   resolve_entry()->compile_the_world(loader, CHECK);
  1262 bool LazyClassPathEntry::is_rt_jar() {
  1263   return resolve_entry()->is_rt_jar();
  1266 void ClassLoader::compile_the_world() {
  1267   EXCEPTION_MARK;
  1268   HandleMark hm(THREAD);
  1269   ResourceMark rm(THREAD);
  1270   // Make sure we don't run with background compilation
  1271   BackgroundCompilation = false;
  1272   // Find bootstrap loader
  1273   Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
  1274   // Iterate over all bootstrap class path entries
  1275   ClassPathEntry* e = _first_entry;
  1276   while (e != NULL) {
  1277     // We stop at rt.jar, unless it is the first bootstrap path entry
  1278     if (e->is_rt_jar() && e != _first_entry) break;
  1279     e->compile_the_world(system_class_loader, CATCH);
  1280     e = e->next();
  1282   tty->print_cr("CompileTheWorld : Done");
  1284     // Print statistics as if before normal exit:
  1285     extern void print_statistics();
  1286     print_statistics();
  1288   vm_exit(0);
  1291 int ClassLoader::_compile_the_world_counter = 0;
  1292 static int _codecache_sweep_counter = 0;
  1294 // Filter out all exceptions except OOMs
  1295 static void clear_pending_exception_if_not_oom(TRAPS) {
  1296   if (HAS_PENDING_EXCEPTION &&
  1297       !PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
  1298     CLEAR_PENDING_EXCEPTION;
  1300   // The CHECK at the caller will propagate the exception out
  1303 void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {
  1304   int len = (int)strlen(name);
  1305   if (len > 6 && strcmp(".class", name + len - 6) == 0) {
  1306     // We have a .class file
  1307     char buffer[2048];
  1308     strncpy(buffer, name, len - 6);
  1309     buffer[len-6] = 0;
  1310     // If the file has a period after removing .class, it's not really a
  1311     // valid class file.  The class loader will check everything else.
  1312     if (strchr(buffer, '.') == NULL) {
  1313       _compile_the_world_counter++;
  1314       if (_compile_the_world_counter > CompileTheWorldStopAt) return;
  1316       // Construct name without extension
  1317       TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
  1318       // Use loader to load and initialize class
  1319       Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);
  1320       instanceKlassHandle k (THREAD, ik);
  1321       if (k.not_null() && !HAS_PENDING_EXCEPTION) {
  1322         k->initialize(THREAD);
  1324       bool exception_occurred = HAS_PENDING_EXCEPTION;
  1325       clear_pending_exception_if_not_oom(CHECK);
  1326       if (CompileTheWorldPreloadClasses && k.not_null()) {
  1327         ConstantPool::preload_and_initialize_all_classes(k->constants(), THREAD);
  1328         if (HAS_PENDING_EXCEPTION) {
  1329           // If something went wrong in preloading we just ignore it
  1330           clear_pending_exception_if_not_oom(CHECK);
  1331           tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_counter, buffer);
  1335       if (_compile_the_world_counter >= CompileTheWorldStartAt) {
  1336         if (k.is_null() || exception_occurred) {
  1337           // If something went wrong (e.g. ExceptionInInitializerError) we skip this class
  1338           tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_counter, buffer);
  1339         } else {
  1340           tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_counter, buffer);
  1341           // Preload all classes to get around uncommon traps
  1342           // Iterate over all methods in class
  1343           for (int n = 0; n < k->methods()->length(); n++) {
  1344             methodHandle m (THREAD, k->methods()->at(n));
  1345             if (CompilationPolicy::can_be_compiled(m)) {
  1347               if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) {
  1348                 // Give sweeper a chance to keep up with CTW
  1349                 VM_ForceSafepoint op;
  1350                 VMThread::execute(&op);
  1351                 _codecache_sweep_counter = 0;
  1353               // Force compilation
  1354               CompileBroker::compile_method(m, InvocationEntryBci, CompilationPolicy::policy()->initial_compile_level(),
  1355                                             methodHandle(), 0, "CTW", THREAD);
  1356               if (HAS_PENDING_EXCEPTION) {
  1357                 clear_pending_exception_if_not_oom(CHECK);
  1358                 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_counter, m->name()->as_C_string());
  1360               if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) {
  1361                 // Clobber the first compile and force second tier compilation
  1362                 nmethod* nm = m->code();
  1363                 if (nm != NULL) {
  1364                   // Throw out the code so that the code cache doesn't fill up
  1365                   nm->make_not_entrant();
  1366                   m->clear_code();
  1368                 CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization,
  1369                                               methodHandle(), 0, "CTW", THREAD);
  1370                 if (HAS_PENDING_EXCEPTION) {
  1371                   clear_pending_exception_if_not_oom(CHECK);
  1372                   tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_counter, m->name()->as_C_string());
  1377             nmethod* nm = m->code();
  1378             if (nm != NULL) {
  1379               // Throw out the code so that the code cache doesn't fill up
  1380               nm->make_not_entrant();
  1381               m->clear_code();
  1390 #endif //PRODUCT
  1392 // Please keep following two functions at end of this file. With them placed at top or in middle of the file,
  1393 // they could get inlined by agressive compiler, an unknown trick, see bug 6966589.
  1394 void PerfClassTraceTime::initialize() {
  1395   if (!UsePerfData) return;
  1397   if (_eventp != NULL) {
  1398     // increment the event counter
  1399     _eventp->inc();
  1402   // stop the current active thread-local timer to measure inclusive time
  1403   _prev_active_event = -1;
  1404   for (int i=0; i < EVENT_TYPE_COUNT; i++) {
  1405      if (_timers[i].is_active()) {
  1406        assert(_prev_active_event == -1, "should have only one active timer");
  1407        _prev_active_event = i;
  1408        _timers[i].stop();
  1412   if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) {
  1413     // start the inclusive timer if not recursively called
  1414     _t.start();
  1417   // start thread-local timer of the given event type
  1418    if (!_timers[_event_type].is_active()) {
  1419     _timers[_event_type].start();
  1423 PerfClassTraceTime::~PerfClassTraceTime() {
  1424   if (!UsePerfData) return;
  1426   // stop the thread-local timer as the event completes
  1427   // and resume the thread-local timer of the event next on the stack
  1428   _timers[_event_type].stop();
  1429   jlong selftime = _timers[_event_type].ticks();
  1431   if (_prev_active_event >= 0) {
  1432     _timers[_prev_active_event].start();
  1435   if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return;
  1437   // increment the counters only on the leaf call
  1438   _t.stop();
  1439   _timep->inc(_t.ticks());
  1440   if (_selftimep != NULL) {
  1441     _selftimep->inc(selftime);
  1443   // add all class loading related event selftime to the accumulated time counter
  1444   ClassLoader::perf_accumulated_time()->inc(selftime);
  1446   // reset the timer
  1447   _timers[_event_type].reset();

mercurial