src/share/vm/classfile/classLoader.cpp

Print this page




  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classFileParser.hpp"
  27 #include "classfile/classFileStream.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/classLoaderExt.hpp"
  30 #include "classfile/classLoaderData.inline.hpp"

  31 #include "classfile/javaClasses.hpp"
  32 #if INCLUDE_CDS
  33 #include "classfile/sharedPathsMiscInfo.hpp"
  34 #include "classfile/sharedClassUtil.hpp"
  35 #endif
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/vmSymbols.hpp"
  38 #include "compiler/compileBroker.hpp"
  39 #include "gc_interface/collectedHeap.inline.hpp"
  40 #include "interpreter/bytecodeStream.hpp"
  41 #include "interpreter/oopMapCache.hpp"
  42 #include "memory/allocation.inline.hpp"
  43 #include "memory/filemap.hpp"
  44 #include "memory/generation.hpp"
  45 #include "memory/oopFactory.hpp"
  46 #include "memory/universe.inline.hpp"
  47 #include "oops/instanceKlass.hpp"
  48 #include "oops/instanceRefKlass.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "oops/symbol.hpp"
  51 #include "prims/jvm_misc.hpp"
  52 #include "runtime/arguments.hpp"
  53 #include "runtime/compilationPolicy.hpp"
  54 #include "runtime/fprofiler.hpp"
  55 #include "runtime/handles.hpp"
  56 #include "runtime/handles.inline.hpp"
  57 #include "runtime/init.hpp"
  58 #include "runtime/interfaceSupport.hpp"
  59 #include "runtime/java.hpp"
  60 #include "runtime/javaCalls.hpp"
  61 #include "runtime/os.hpp"
  62 #include "runtime/threadCritical.hpp"
  63 #include "runtime/timer.hpp"
  64 #include "services/management.hpp"
  65 #include "services/threadService.hpp"
  66 #include "utilities/events.hpp"
  67 #include "utilities/hashtable.hpp"
  68 #include "utilities/hashtable.inline.hpp"
  69 
  70 // Entry points in zip.dll for loading zip/jar file entries
  71 
  72 typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg);
  73 typedef void (JNICALL *ZipClose_t)(jzfile *zip);
  74 typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen);
  75 typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);
  76 typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf);
  77 typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);

  78 typedef jint     (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);
  79 
  80 static ZipOpen_t         ZipOpen            = NULL;
  81 static ZipClose_t        ZipClose           = NULL;
  82 static FindEntry_t       FindEntry          = NULL;
  83 static ReadEntry_t       ReadEntry          = NULL;
  84 static ReadMappedEntry_t ReadMappedEntry    = NULL;
  85 static GetNextEntry_t    GetNextEntry       = NULL;
  86 static canonicalize_fn_t CanonicalizeEntry  = NULL;

  87 static Crc32_t           Crc32              = NULL;
  88 
  89 // Globals
  90 
  91 PerfCounter*    ClassLoader::_perf_accumulated_time = NULL;
  92 PerfCounter*    ClassLoader::_perf_classes_inited = NULL;
  93 PerfCounter*    ClassLoader::_perf_class_init_time = NULL;
  94 PerfCounter*    ClassLoader::_perf_class_init_selftime = NULL;
  95 PerfCounter*    ClassLoader::_perf_classes_verified = NULL;
  96 PerfCounter*    ClassLoader::_perf_class_verify_time = NULL;
  97 PerfCounter*    ClassLoader::_perf_class_verify_selftime = NULL;
  98 PerfCounter*    ClassLoader::_perf_classes_linked = NULL;
  99 PerfCounter*    ClassLoader::_perf_class_link_time = NULL;
 100 PerfCounter*    ClassLoader::_perf_class_link_selftime = NULL;
 101 PerfCounter*    ClassLoader::_perf_class_parse_time = NULL;
 102 PerfCounter*    ClassLoader::_perf_class_parse_selftime = NULL;
 103 PerfCounter*    ClassLoader::_perf_sys_class_lookup_time = NULL;
 104 PerfCounter*    ClassLoader::_perf_shared_classload_time = NULL;
 105 PerfCounter*    ClassLoader::_perf_sys_classload_time = NULL;
 106 PerfCounter*    ClassLoader::_perf_app_classload_time = NULL;


 305     jzentry * ze = ((*GetNextEntry)(_zip, n));
 306     if (ze == NULL) break;
 307     (*f)(ze->name, context);
 308   }
 309 }
 310 
 311 LazyClassPathEntry::LazyClassPathEntry(const char* path, const struct stat* st, bool throw_exception) : ClassPathEntry() {
 312   _path = os::strdup_check_oom(path);
 313   _st = *st;
 314   _meta_index = NULL;
 315   _resolved_entry = NULL;
 316   _has_error = false;
 317   _throw_exception = throw_exception;
 318 }
 319 
 320 LazyClassPathEntry::~LazyClassPathEntry() {
 321   os::free((void*)_path);
 322 }
 323 
 324 bool LazyClassPathEntry::is_jar_file() {


 325   return ((_st.st_mode & S_IFREG) == S_IFREG);
 326 }
 327 
 328 ClassPathEntry* LazyClassPathEntry::resolve_entry(TRAPS) {
 329   if (_resolved_entry != NULL) {
 330     return (ClassPathEntry*) _resolved_entry;
 331   }
 332   ClassPathEntry* new_entry = NULL;
 333   new_entry = ClassLoader::create_class_path_entry(_path, &_st, false, _throw_exception, CHECK_NULL);
 334   if (!_throw_exception && new_entry == NULL) {
 335     assert(!HAS_PENDING_EXCEPTION, "must be");
 336     return NULL;
 337   }
 338   {
 339     ThreadCritical tc;
 340     if (_resolved_entry == NULL) {
 341       _resolved_entry = new_entry;
 342       return new_entry;
 343     }
 344   }


 368   return true;
 369 }
 370 
 371 u1* LazyClassPathEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {
 372   if (_has_error) {
 373     return NULL;
 374   }
 375   ClassPathEntry* cpe = resolve_entry(THREAD);
 376   if (cpe == NULL) {
 377     _has_error = true;
 378     return NULL;
 379   } else if (cpe->is_jar_file()) {
 380     return ((ClassPathZipEntry*)cpe)->open_entry(name, filesize, nul_terminate,THREAD);
 381   } else {
 382     ShouldNotReachHere();
 383     *filesize = 0;
 384     return NULL;
 385   }
 386 }
 387 








































































 388 static void print_meta_index(LazyClassPathEntry* entry,
 389                              GrowableArray<char*>& meta_packages) {
 390   tty->print("[Meta index for %s=", entry->name());
 391   for (int i = 0; i < meta_packages.length(); i++) {
 392     if (i > 0) tty->print(" ");
 393     tty->print("%s", meta_packages.at(i));
 394   }
 395   tty->print_cr("]");
 396 }
 397 
 398 #if INCLUDE_CDS
 399 void ClassLoader::exit_with_path_failure(const char* error, const char* message) {
 400   assert(DumpSharedSpaces, "only called at dump time");
 401   tty->print_cr("Hint: enable -XX:+TraceClassPaths to diagnose the failure");
 402   vm_exit_during_initialization(error, message);
 403 }
 404 #endif
 405 
 406 void ClassLoader::trace_class_path(const char* msg, const char* name) {
 407   if (!TraceClassPaths) {


 617     update_class_path_entry_list(path, false);
 618 #if INCLUDE_CDS
 619     if (DumpSharedSpaces) {
 620       check_shared_classpath(path);
 621     }
 622 #endif
 623     while (class_path[end] == os::path_separator()[0]) {
 624       end++;
 625     }
 626   }
 627 }
 628 
 629 ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st,
 630                                                      bool lazy, bool throw_exception, TRAPS) {
 631   JavaThread* thread = JavaThread::current();
 632   if (lazy) {
 633     return new LazyClassPathEntry(path, st, throw_exception);
 634   }
 635   ClassPathEntry* new_entry = NULL;
 636   if ((st->st_mode & S_IFREG) == S_IFREG) {
 637     // Regular file, should be a zip file
 638     // Canonicalized filename
 639     char canonical_path[JVM_MAXPATHLEN];
 640     if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
 641       // This matches the classic VM
 642       if (throw_exception) {
 643         THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL);
 644       } else {
 645         return NULL;
 646       }
 647     }





 648     char* error_msg = NULL;
 649     jzfile* zip;
 650     {
 651       // enable call to C land
 652       ThreadToNativeFromVM ttn(thread);
 653       HandleMark hm(thread);
 654       zip = (*ZipOpen)(canonical_path, &error_msg);
 655     }
 656     if (zip != NULL && error_msg == NULL) {
 657       new_entry = new ClassPathZipEntry(zip, path);
 658       if (TraceClassLoading || TraceClassPaths) {
 659         tty->print_cr("[Opened %s]", path);
 660       }
 661     } else {
 662       ResourceMark rm(thread);
 663       char *msg;
 664       if (error_msg == NULL) {
 665         msg = NEW_RESOURCE_ARRAY(char, strlen(path) + 128); ;
 666         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
 667       } else {
 668         int len = (int)(strlen(path) + strlen(error_msg) + 128);
 669         msg = NEW_RESOURCE_ARRAY(char, len); ;
 670         jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path);
 671       }
 672       if (throw_exception) {
 673         THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL);
 674       } else {
 675         return NULL;
 676       }
 677     }




 678   } else {
 679     // Directory
 680     new_entry = new ClassPathDirEntry(path);
 681     if (TraceClassLoading || TraceClassPaths) {
 682       tty->print_cr("[Path %s]", path);
 683     }
 684   }
 685   return new_entry;
 686 }
 687 
 688 
 689 // Create a class path zip entry for a given path (return NULL if not found
 690 // or zip/JAR file cannot be opened)
 691 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path) {
 692   // check for a regular file
 693   struct stat st;
 694   if (os::stat(path, &st) == 0) {
 695     if ((st.st_mode & S_IFREG) == S_IFREG) {
 696       char canonical_path[JVM_MAXPATHLEN];
 697       if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
 698         char* error_msg = NULL;
 699         jzfile* zip;
 700         {
 701           // enable call to C land


 784   assert(ZipOpen == NULL, "should not load zip library twice");
 785   // First make sure native library is loaded
 786   os::native_java_library();
 787   // Load zip library
 788   char path[JVM_MAXPATHLEN];
 789   char ebuf[1024];
 790   void* handle = NULL;
 791   if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {
 792     handle = os::dll_load(path, ebuf, sizeof ebuf);
 793   }
 794   if (handle == NULL) {
 795     vm_exit_during_initialization("Unable to load ZIP library", path);
 796   }
 797   // Lookup zip entry points
 798   ZipOpen      = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));
 799   ZipClose     = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));
 800   FindEntry    = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));
 801   ReadEntry    = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
 802   ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));
 803   GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));

 804   Crc32        = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));
 805 

 806   // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
 807   if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||
 808       GetNextEntry == NULL || Crc32 == NULL) {
 809     vm_exit_during_initialization("Corrupted ZIP library", path);
 810   }
 811 




 812   // Lookup canonicalize entry in libjava.dll
 813   void *javalib_handle = os::native_java_library();
 814   CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));
 815   // This lookup only works on 1.3. Do not check for non-null here
 816 }
 817 




 818 int ClassLoader::crc32(int crc, const char* buf, int len) {
 819   assert(Crc32 != NULL, "ZIP_CRC32 is not found");
 820   return (*Crc32)(crc, (const jbyte*)buf, len);
 821 }
 822 
 823 // PackageInfo data exists in order to support the java.lang.Package
 824 // class.  A Package object provides information about a java package
 825 // (version, vendor, etc.) which originates in the manifest of the jar
 826 // file supplying the package.  For application classes, the ClassLoader
 827 // object takes care of this.
 828 
 829 // For system (boot) classes, the Java code in the Package class needs
 830 // to be able to identify which source jar file contained the boot
 831 // class, so that it can extract the manifest from it.  This table
 832 // identifies java packages with jar files in the boot classpath.
 833 
 834 // Because the boot classpath cannot change, the classpath index is
 835 // sufficient to identify the source jar file or directory.  (Since
 836 // directories have no manifests, the directory name is not required,
 837 // but is available.)


1351     void *entries;              /* array of hash cells */
1352     jint total;                 /* total number of entries */
1353     unsigned short *table;      /* Hash chain heads: indexes into entries */
1354     jint tablelen;              /* number of hash eads */
1355     real_jzfile *next;        /* next zip file in search list */
1356     jzentry *cache;             /* we cache the most recently freed jzentry */
1357     /* Information on metadata names in META-INF directory */
1358     char **metanames;           /* array of meta names (may have null names) */
1359     jint metacount;             /* number of slots in metanames array */
1360     /* If there are any per-entry comments, they are in the comments array */
1361     char **comments;
1362 } real_jzfile;
1363 
1364 void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {
1365   // For now we only compile all methods in all classes in zip/jar files
1366   tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);
1367   tty->cr();
1368 }
1369 
1370 
1371 bool ClassPathDirEntry::is_rt_jar() {
1372   return false;
1373 }
1374 
1375 void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {
1376   real_jzfile* zip = (real_jzfile*) _zip;
1377   tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
1378   tty->cr();
1379   // Iterate over all entries in zip file
1380   for (int n = 0; ; n++) {
1381     real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n));
1382     if (ze == NULL) break;
1383     ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
1384   }
1385   if (HAS_PENDING_EXCEPTION) {
1386     if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1387       CLEAR_PENDING_EXCEPTION;
1388       tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
1389       tty->print_cr("Increase class metadata storage if a limit was set");
1390     } else {
1391       tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
1392     }
1393   }
1394 }
1395 
1396 bool ClassPathZipEntry::is_rt_jar() {
1397   real_jzfile* zip = (real_jzfile*) _zip;
1398   int len = (int)strlen(zip->name);
1399   // Check whether zip name ends in "rt.jar"
1400   // This will match other archives named rt.jar as well, but this is
1401   // only used for debugging.
1402   return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0);
1403 }
1404 
1405 void LazyClassPathEntry::compile_the_world(Handle loader, TRAPS) {
1406   ClassPathEntry* cpe = resolve_entry(THREAD);
1407   if (cpe != NULL) {
1408     cpe->compile_the_world(loader, CHECK);
1409   }
1410 }
1411 
1412 bool LazyClassPathEntry::is_rt_jar() {
1413   Thread* THREAD = Thread::current();
1414   ClassPathEntry* cpe = resolve_entry(THREAD);
1415   return (cpe != NULL) ? cpe->is_jar_file() : false;
1416 }
1417 
1418 void ClassLoader::compile_the_world() {
1419   EXCEPTION_MARK;
1420   HandleMark hm(THREAD);
1421   ResourceMark rm(THREAD);
1422   // Make sure we don't run with background compilation
1423   BackgroundCompilation = false;
1424   // Find bootstrap loader
1425   Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
1426   // Iterate over all bootstrap class path entries
1427   ClassPathEntry* e = _first_entry;
1428   jlong start = os::javaTimeMillis();
1429   while (e != NULL) {
1430     // We stop at rt.jar, unless it is the first bootstrap path entry
1431     if (e->is_rt_jar() && e != _first_entry) break;
1432     e->compile_the_world(system_class_loader, CATCH);
1433     e = e->next();
1434   }
1435   jlong end = os::javaTimeMillis();
1436   tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)",
1437                 _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));
1438   {
1439     // Print statistics as if before normal exit:
1440     extern void print_statistics();
1441     print_statistics();
1442   }
1443   vm_exit(0);
1444 }
1445 
1446 int ClassLoader::_compile_the_world_class_counter = 0;
1447 int ClassLoader::_compile_the_world_method_counter = 0;
1448 static int _codecache_sweep_counter = 0;
1449 
1450 // Filter out all exceptions except OOMs
1451 static void clear_pending_exception_if_not_oom(TRAPS) {


1459 /**
1460  * Returns if the given method should be compiled when doing compile-the-world.
1461  *
1462  * TODO:  This should be a private method in a CompileTheWorld class.
1463  */
1464 static bool can_be_compiled(methodHandle m, int comp_level) {
1465   assert(CompileTheWorld, "must be");
1466 
1467   // It's not valid to compile a native wrapper for MethodHandle methods
1468   // that take a MemberName appendix since the bytecode signature is not
1469   // correct.
1470   vmIntrinsics::ID iid = m->intrinsic_id();
1471   if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) {
1472     return false;
1473   }
1474 
1475   return CompilationPolicy::can_be_compiled(m, comp_level);
1476 }
1477 
1478 void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {
1479   int len = (int)strlen(name);
1480   if (len > 6 && strcmp(".class", name + len - 6) == 0) {
1481     // We have a .class file

1482     char buffer[2048];
1483     strncpy(buffer, name, len - 6);
1484     buffer[len-6] = 0;
1485     // If the file has a period after removing .class, it's not really a
1486     // valid class file.  The class loader will check everything else.
1487     if (strchr(buffer, '.') == NULL) {
1488       _compile_the_world_class_counter++;
1489       if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;
1490 
1491       // Construct name without extension
1492       TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
1493       // Use loader to load and initialize class
1494       Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);
1495       instanceKlassHandle k (THREAD, ik);
1496       if (k.not_null() && !HAS_PENDING_EXCEPTION) {
1497         k->initialize(THREAD);
1498       }
1499       bool exception_occurred = HAS_PENDING_EXCEPTION;
1500       clear_pending_exception_if_not_oom(CHECK);
1501       if (CompileTheWorldPreloadClasses && k.not_null()) {




  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classFileParser.hpp"
  27 #include "classfile/classFileStream.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/classLoaderExt.hpp"
  30 #include "classfile/classLoaderData.inline.hpp"
  31 #include "classfile/imageFile.hpp"
  32 #include "classfile/javaClasses.hpp"
  33 #if INCLUDE_CDS
  34 #include "classfile/sharedPathsMiscInfo.hpp"
  35 #include "classfile/sharedClassUtil.hpp"
  36 #endif
  37 #include "classfile/systemDictionary.hpp"
  38 #include "classfile/vmSymbols.hpp"
  39 #include "compiler/compileBroker.hpp"
  40 #include "gc_interface/collectedHeap.inline.hpp"
  41 #include "interpreter/bytecodeStream.hpp"
  42 #include "interpreter/oopMapCache.hpp"
  43 #include "memory/allocation.inline.hpp"
  44 #include "memory/filemap.hpp"
  45 #include "memory/generation.hpp"
  46 #include "memory/oopFactory.hpp"
  47 #include "memory/universe.inline.hpp"
  48 #include "oops/instanceKlass.hpp"
  49 #include "oops/instanceRefKlass.hpp"
  50 #include "oops/oop.inline.hpp"
  51 #include "oops/symbol.hpp"
  52 #include "prims/jvm_misc.hpp"
  53 #include "runtime/arguments.hpp"
  54 #include "runtime/compilationPolicy.hpp"
  55 #include "runtime/fprofiler.hpp"
  56 #include "runtime/handles.hpp"
  57 #include "runtime/handles.inline.hpp"
  58 #include "runtime/init.hpp"
  59 #include "runtime/interfaceSupport.hpp"
  60 #include "runtime/java.hpp"
  61 #include "runtime/javaCalls.hpp"
  62 #include "runtime/os.hpp"
  63 #include "runtime/threadCritical.hpp"
  64 #include "runtime/timer.hpp"
  65 #include "services/management.hpp"
  66 #include "services/threadService.hpp"
  67 #include "utilities/events.hpp"
  68 #include "utilities/hashtable.hpp"
  69 #include "utilities/hashtable.inline.hpp"
  70 
  71 // Entry points in zip.dll for loading zip/jar file entries and image file entries
  72 
  73 typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg);
  74 typedef void (JNICALL *ZipClose_t)(jzfile *zip);
  75 typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen);
  76 typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);
  77 typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf);
  78 typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);
  79 typedef jboolean (JNICALL *ZipInflateFully_t)(void *inBuf, jlong inLen, void *outBuf, jlong outLen, char **pmsg);
  80 typedef jint     (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);
  81 
  82 static ZipOpen_t         ZipOpen            = NULL;
  83 static ZipClose_t        ZipClose           = NULL;
  84 static FindEntry_t       FindEntry          = NULL;
  85 static ReadEntry_t       ReadEntry          = NULL;
  86 static ReadMappedEntry_t ReadMappedEntry    = NULL;
  87 static GetNextEntry_t    GetNextEntry       = NULL;
  88 static canonicalize_fn_t CanonicalizeEntry  = NULL;
  89 static ZipInflateFully_t ZipInflateFully   = NULL;
  90 static Crc32_t           Crc32              = NULL;
  91 
  92 // Globals
  93 
  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;


 308     jzentry * ze = ((*GetNextEntry)(_zip, n));
 309     if (ze == NULL) break;
 310     (*f)(ze->name, context);
 311   }
 312 }
 313 
 314 LazyClassPathEntry::LazyClassPathEntry(const char* path, const struct stat* st, bool throw_exception) : ClassPathEntry() {
 315   _path = os::strdup_check_oom(path);
 316   _st = *st;
 317   _meta_index = NULL;
 318   _resolved_entry = NULL;
 319   _has_error = false;
 320   _throw_exception = throw_exception;
 321 }
 322 
 323 LazyClassPathEntry::~LazyClassPathEntry() {
 324   os::free((void*)_path);
 325 }
 326 
 327 bool LazyClassPathEntry::is_jar_file() {
 328   size_t len = strlen(_path);
 329   if (len < 4 || strcmp(_path + len - 4, ".jar") != 0) return false;
 330   return ((_st.st_mode & S_IFREG) == S_IFREG);
 331 }
 332 
 333 ClassPathEntry* LazyClassPathEntry::resolve_entry(TRAPS) {
 334   if (_resolved_entry != NULL) {
 335     return (ClassPathEntry*) _resolved_entry;
 336   }
 337   ClassPathEntry* new_entry = NULL;
 338   new_entry = ClassLoader::create_class_path_entry(_path, &_st, false, _throw_exception, CHECK_NULL);
 339   if (!_throw_exception && new_entry == NULL) {
 340     assert(!HAS_PENDING_EXCEPTION, "must be");
 341     return NULL;
 342   }
 343   {
 344     ThreadCritical tc;
 345     if (_resolved_entry == NULL) {
 346       _resolved_entry = new_entry;
 347       return new_entry;
 348     }
 349   }


 373   return true;
 374 }
 375 
 376 u1* LazyClassPathEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {
 377   if (_has_error) {
 378     return NULL;
 379   }
 380   ClassPathEntry* cpe = resolve_entry(THREAD);
 381   if (cpe == NULL) {
 382     _has_error = true;
 383     return NULL;
 384   } else if (cpe->is_jar_file()) {
 385     return ((ClassPathZipEntry*)cpe)->open_entry(name, filesize, nul_terminate,THREAD);
 386   } else {
 387     ShouldNotReachHere();
 388     *filesize = 0;
 389     return NULL;
 390   }
 391 }
 392 
 393 ClassPathImageEntry::ClassPathImageEntry(char* name) : ClassPathEntry(), _image(new ImageFile(name)) {
 394   bool opened = _image->open();
 395   if (!opened) {
 396     _image = NULL;
 397   }
 398 }
 399 
 400 ClassPathImageEntry::~ClassPathImageEntry() {
 401   if (_image) {
 402     _image->close();
 403     _image = NULL;
 404   }
 405 }
 406 
 407 const char* ClassPathImageEntry::name() {
 408   return _image ? _image->name() : "";
 409 }
 410 
 411 ClassFileStream* ClassPathImageEntry::open_stream(const char* name, TRAPS) {
 412   u1* buffer;
 413   u8 size;
 414   _image->get_resource(name, buffer, size);
 415 
 416   if (buffer) {
 417     if (UsePerfData) {
 418       ClassLoader::perf_sys_classfile_bytes_read()->inc(size);
 419     }
 420     return new ClassFileStream(buffer, (int)size, (char*)name);  // Resource allocated
 421   }
 422 
 423   return NULL;
 424 }
 425 
 426 #ifndef PRODUCT
 427 void ClassPathImageEntry::compile_the_world(Handle loader, TRAPS) {
 428   tty->print_cr("CompileTheWorld : Compiling all classes in %s", name());
 429   tty->cr();
 430   const ImageStrings strings = _image->get_strings();
 431   // Retrieve each path component string.
 432   u4 count = _image->get_location_count();
 433   for (u4 i = 0; i < count; i++) {
 434     u1* location_data = _image->get_location_data(i);
 435 
 436     if (location_data) {
 437        ImageLocation location(location_data);
 438        const char* parent = location.get_attribute(ImageLocation::ATTRIBUTE_PARENT, strings);
 439        const char* base = location.get_attribute(ImageLocation::ATTRIBUTE_BASE, strings);
 440        const char* extension = location.get_attribute(ImageLocation::ATTRIBUTE_EXTENSION, strings);
 441        assert((strlen(parent) + strlen(base) + strlen(extension)) < JVM_MAXPATHLEN, "path exceeds buffer");
 442        char path[JVM_MAXPATHLEN];
 443        strcpy(path, parent);
 444        strcat(path, base);
 445        strcat(path, extension);
 446        ClassLoader::compile_the_world_in(path, loader, CHECK);
 447     }
 448   }
 449   if (HAS_PENDING_EXCEPTION) {
 450   if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
 451     CLEAR_PENDING_EXCEPTION;
 452     tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
 453     tty->print_cr("Increase class metadata storage if a limit was set");
 454   } else {
 455     tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
 456   }
 457   }
 458 }
 459 
 460 bool ClassPathImageEntry::is_jrt() {
 461   return string_ends_with(name(), "bootmodules.jimage");
 462 }
 463 #endif
 464 
 465 static void print_meta_index(LazyClassPathEntry* entry,
 466                              GrowableArray<char*>& meta_packages) {
 467   tty->print("[Meta index for %s=", entry->name());
 468   for (int i = 0; i < meta_packages.length(); i++) {
 469     if (i > 0) tty->print(" ");
 470     tty->print("%s", meta_packages.at(i));
 471   }
 472   tty->print_cr("]");
 473 }
 474 
 475 #if INCLUDE_CDS
 476 void ClassLoader::exit_with_path_failure(const char* error, const char* message) {
 477   assert(DumpSharedSpaces, "only called at dump time");
 478   tty->print_cr("Hint: enable -XX:+TraceClassPaths to diagnose the failure");
 479   vm_exit_during_initialization(error, message);
 480 }
 481 #endif
 482 
 483 void ClassLoader::trace_class_path(const char* msg, const char* name) {
 484   if (!TraceClassPaths) {


 694     update_class_path_entry_list(path, false);
 695 #if INCLUDE_CDS
 696     if (DumpSharedSpaces) {
 697       check_shared_classpath(path);
 698     }
 699 #endif
 700     while (class_path[end] == os::path_separator()[0]) {
 701       end++;
 702     }
 703   }
 704 }
 705 
 706 ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st,
 707                                                      bool lazy, bool throw_exception, TRAPS) {
 708   JavaThread* thread = JavaThread::current();
 709   if (lazy) {
 710     return new LazyClassPathEntry(path, st, throw_exception);
 711   }
 712   ClassPathEntry* new_entry = NULL;
 713   if ((st->st_mode & S_IFREG) == S_IFREG) {
 714     // Regular file, should be a zip or image file
 715     // Canonicalized filename
 716     char canonical_path[JVM_MAXPATHLEN];
 717     if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
 718       // This matches the classic VM
 719       if (throw_exception) {
 720         THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL);
 721       } else {
 722         return NULL;
 723       }
 724     }
 725     // TODO - add proper criteria for selecting image file
 726     ClassPathImageEntry* entry = new ClassPathImageEntry(canonical_path);
 727     if (entry->is_open()) {
 728       new_entry = entry;
 729     } else {
 730     char* error_msg = NULL;
 731     jzfile* zip;
 732     {
 733       // enable call to C land
 734       ThreadToNativeFromVM ttn(thread);
 735       HandleMark hm(thread);
 736       zip = (*ZipOpen)(canonical_path, &error_msg);
 737     }
 738     if (zip != NULL && error_msg == NULL) {
 739       new_entry = new ClassPathZipEntry(zip, path);



 740     } else {
 741       ResourceMark rm(thread);
 742       char *msg;
 743       if (error_msg == NULL) {
 744         msg = NEW_RESOURCE_ARRAY(char, strlen(path) + 128); ;
 745         jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
 746       } else {
 747         int len = (int)(strlen(path) + strlen(error_msg) + 128);
 748         msg = NEW_RESOURCE_ARRAY(char, len); ;
 749         jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path);
 750       }
 751       if (throw_exception) {
 752         THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL);
 753       } else {
 754         return NULL;
 755       }
 756     }
 757     }
 758     if (TraceClassLoading || TraceClassPaths) {
 759       tty->print_cr("[Opened %s]", path);
 760     }
 761   } else  {
 762     // Directory
 763     new_entry = new ClassPathDirEntry(path);
 764     if (TraceClassLoading) {
 765       tty->print_cr("[Path %s]", path);
 766     }
 767   }
 768   return new_entry;
 769 }
 770 
 771 
 772 // Create a class path zip entry for a given path (return NULL if not found
 773 // or zip/JAR file cannot be opened)
 774 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path) {
 775   // check for a regular file
 776   struct stat st;
 777   if (os::stat(path, &st) == 0) {
 778     if ((st.st_mode & S_IFREG) == S_IFREG) {
 779       char canonical_path[JVM_MAXPATHLEN];
 780       if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
 781         char* error_msg = NULL;
 782         jzfile* zip;
 783         {
 784           // enable call to C land


 867   assert(ZipOpen == NULL, "should not load zip library twice");
 868   // First make sure native library is loaded
 869   os::native_java_library();
 870   // Load zip library
 871   char path[JVM_MAXPATHLEN];
 872   char ebuf[1024];
 873   void* handle = NULL;
 874   if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {
 875     handle = os::dll_load(path, ebuf, sizeof ebuf);
 876   }
 877   if (handle == NULL) {
 878     vm_exit_during_initialization("Unable to load ZIP library", path);
 879   }
 880   // Lookup zip entry points
 881   ZipOpen      = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));
 882   ZipClose     = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));
 883   FindEntry    = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));
 884   ReadEntry    = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
 885   ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));
 886   GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));
 887   ZipInflateFully = CAST_TO_FN_PTR(ZipInflateFully_t, os::dll_lookup(handle, "ZIP_InflateFully"));
 888   Crc32        = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));
 889 
 890 
 891   // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
 892   if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||
 893       GetNextEntry == NULL || Crc32 == NULL) {
 894     vm_exit_during_initialization("Corrupted ZIP library", path);
 895   }
 896 
 897   if (ZipInflateFully == NULL) {
 898     vm_exit_during_initialization("Corrupted ZIP library ZIP_InflateFully missing", path);
 899   }
 900 
 901   // Lookup canonicalize entry in libjava.dll
 902   void *javalib_handle = os::native_java_library();
 903   CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));
 904   // This lookup only works on 1.3. Do not check for non-null here
 905 }
 906 
 907 jboolean ClassLoader::decompress(void *in, u8 inSize, void *out, u8 outSize, char **pmsg) {
 908   return (*ZipInflateFully)(in, inSize, out, outSize, pmsg);
 909 }
 910 
 911 int ClassLoader::crc32(int crc, const char* buf, int len) {
 912   assert(Crc32 != NULL, "ZIP_CRC32 is not found");
 913   return (*Crc32)(crc, (const jbyte*)buf, len);
 914 }
 915 
 916 // PackageInfo data exists in order to support the java.lang.Package
 917 // class.  A Package object provides information about a java package
 918 // (version, vendor, etc.) which originates in the manifest of the jar
 919 // file supplying the package.  For application classes, the ClassLoader
 920 // object takes care of this.
 921 
 922 // For system (boot) classes, the Java code in the Package class needs
 923 // to be able to identify which source jar file contained the boot
 924 // class, so that it can extract the manifest from it.  This table
 925 // identifies java packages with jar files in the boot classpath.
 926 
 927 // Because the boot classpath cannot change, the classpath index is
 928 // sufficient to identify the source jar file or directory.  (Since
 929 // directories have no manifests, the directory name is not required,
 930 // but is available.)


1444     void *entries;              /* array of hash cells */
1445     jint total;                 /* total number of entries */
1446     unsigned short *table;      /* Hash chain heads: indexes into entries */
1447     jint tablelen;              /* number of hash eads */
1448     real_jzfile *next;        /* next zip file in search list */
1449     jzentry *cache;             /* we cache the most recently freed jzentry */
1450     /* Information on metadata names in META-INF directory */
1451     char **metanames;           /* array of meta names (may have null names) */
1452     jint metacount;             /* number of slots in metanames array */
1453     /* If there are any per-entry comments, they are in the comments array */
1454     char **comments;
1455 } real_jzfile;
1456 
1457 void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {
1458   // For now we only compile all methods in all classes in zip/jar files
1459   tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);
1460   tty->cr();
1461 }
1462 
1463 
1464 bool ClassPathDirEntry::is_jrt() {
1465   return false;
1466 }
1467 
1468 void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {
1469   real_jzfile* zip = (real_jzfile*) _zip;
1470   tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
1471   tty->cr();
1472   // Iterate over all entries in zip file
1473   for (int n = 0; ; n++) {
1474     real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n));
1475     if (ze == NULL) break;
1476     ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
1477   }
1478   if (HAS_PENDING_EXCEPTION) {
1479     if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1480       CLEAR_PENDING_EXCEPTION;
1481       tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
1482       tty->print_cr("Increase class metadata storage if a limit was set");
1483     } else {
1484       tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
1485     }
1486   }
1487 }
1488 
1489 bool ClassPathZipEntry::is_jrt() {
1490   real_jzfile* zip = (real_jzfile*) _zip;
1491   int len = (int)strlen(zip->name);
1492   // Check whether zip name ends in "rt.jar"
1493   // This will match other archives named rt.jar as well, but this is
1494   // only used for debugging.
1495   return string_ends_with(zip->name, "rt.jar");
1496 }
1497 
1498 void LazyClassPathEntry::compile_the_world(Handle loader, TRAPS) {
1499   ClassPathEntry* cpe = resolve_entry(THREAD);
1500   if (cpe != NULL) {
1501     cpe->compile_the_world(loader, CHECK);
1502   }
1503 }
1504 
1505 bool LazyClassPathEntry::is_jrt() {
1506   Thread* THREAD = Thread::current();
1507   ClassPathEntry* cpe = resolve_entry(THREAD);
1508   return (cpe != NULL) ? cpe->is_jar_file() : false;
1509 }
1510 
1511 void ClassLoader::compile_the_world() {
1512   EXCEPTION_MARK;
1513   HandleMark hm(THREAD);
1514   ResourceMark rm(THREAD);
1515   // Make sure we don't run with background compilation
1516   BackgroundCompilation = false;
1517   // Find bootstrap loader
1518   Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
1519   // Iterate over all bootstrap class path entries
1520   ClassPathEntry* e = _first_entry;
1521   jlong start = os::javaTimeMillis();
1522   while (e != NULL) {
1523     // We stop at rt.jar, unless it is the first bootstrap path entry
1524     if (e->is_jrt() && e != _first_entry) break;
1525     e->compile_the_world(system_class_loader, CATCH);
1526     e = e->next();
1527   }
1528   jlong end = os::javaTimeMillis();
1529   tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)",
1530                 _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));
1531   {
1532     // Print statistics as if before normal exit:
1533     extern void print_statistics();
1534     print_statistics();
1535   }
1536   vm_exit(0);
1537 }
1538 
1539 int ClassLoader::_compile_the_world_class_counter = 0;
1540 int ClassLoader::_compile_the_world_method_counter = 0;
1541 static int _codecache_sweep_counter = 0;
1542 
1543 // Filter out all exceptions except OOMs
1544 static void clear_pending_exception_if_not_oom(TRAPS) {


1552 /**
1553  * Returns if the given method should be compiled when doing compile-the-world.
1554  *
1555  * TODO:  This should be a private method in a CompileTheWorld class.
1556  */
1557 static bool can_be_compiled(methodHandle m, int comp_level) {
1558   assert(CompileTheWorld, "must be");
1559 
1560   // It's not valid to compile a native wrapper for MethodHandle methods
1561   // that take a MemberName appendix since the bytecode signature is not
1562   // correct.
1563   vmIntrinsics::ID iid = m->intrinsic_id();
1564   if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) {
1565     return false;
1566   }
1567 
1568   return CompilationPolicy::can_be_compiled(m, comp_level);
1569 }
1570 
1571 void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {
1572   if (string_ends_with(name, ".class")) {

1573     // We have a .class file
1574     int len = (int)strlen(name);
1575     char buffer[2048];
1576     strncpy(buffer, name, len - 6);
1577     buffer[len-6] = 0;
1578     // If the file has a period after removing .class, it's not really a
1579     // valid class file.  The class loader will check everything else.
1580     if (strchr(buffer, '.') == NULL) {
1581       _compile_the_world_class_counter++;
1582       if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;
1583 
1584       // Construct name without extension
1585       TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
1586       // Use loader to load and initialize class
1587       Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);
1588       instanceKlassHandle k (THREAD, ik);
1589       if (k.not_null() && !HAS_PENDING_EXCEPTION) {
1590         k->initialize(THREAD);
1591       }
1592       bool exception_occurred = HAS_PENDING_EXCEPTION;
1593       clear_pending_exception_if_not_oom(CHECK);
1594       if (CompileTheWorldPreloadClasses && k.not_null()) {