Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/classfile/classLoader.cpp
32285 views
/*1* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/classFileParser.hpp"26#include "classfile/classFileStream.hpp"27#include "classfile/classLoader.hpp"28#include "classfile/classLoaderExt.hpp"29#include "classfile/classLoaderData.inline.hpp"30#include "classfile/javaClasses.hpp"31#if INCLUDE_CDS32#include "classfile/sharedPathsMiscInfo.hpp"33#include "classfile/sharedClassUtil.hpp"34#endif35#include "classfile/systemDictionary.hpp"36#include "classfile/vmSymbols.hpp"37#include "compiler/compileBroker.hpp"38#include "gc_interface/collectedHeap.inline.hpp"39#include "interpreter/bytecodeStream.hpp"40#include "interpreter/oopMapCache.hpp"41#include "memory/allocation.inline.hpp"42#include "memory/filemap.hpp"43#include "memory/generation.hpp"44#include "memory/oopFactory.hpp"45#include "memory/universe.inline.hpp"46#include "oops/instanceKlass.hpp"47#include "oops/instanceRefKlass.hpp"48#include "oops/oop.inline.hpp"49#include "oops/symbol.hpp"50#include "prims/jvm_misc.hpp"51#include "runtime/arguments.hpp"52#include "runtime/compilationPolicy.hpp"53#include "runtime/fprofiler.hpp"54#include "runtime/handles.hpp"55#include "runtime/handles.inline.hpp"56#include "runtime/init.hpp"57#include "runtime/interfaceSupport.hpp"58#include "runtime/java.hpp"59#include "runtime/javaCalls.hpp"60#include "runtime/threadCritical.hpp"61#include "runtime/timer.hpp"62#include "services/management.hpp"63#include "services/threadService.hpp"64#include "utilities/events.hpp"65#include "utilities/hashtable.hpp"66#include "utilities/hashtable.inline.hpp"67#ifdef TARGET_OS_FAMILY_linux68# include "os_linux.inline.hpp"69#endif70#ifdef TARGET_OS_FAMILY_solaris71# include "os_solaris.inline.hpp"72#endif73#ifdef TARGET_OS_FAMILY_windows74# include "os_windows.inline.hpp"75#endif76#ifdef TARGET_OS_FAMILY_aix77# include "os_aix.inline.hpp"78#endif79#ifdef TARGET_OS_FAMILY_bsd80# include "os_bsd.inline.hpp"81#endif828384// Entry points in zip.dll for loading zip/jar file entries8586typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg);87typedef void (JNICALL *ZipClose_t)(jzfile *zip);88typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen);89typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);90typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf);91typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);92typedef jint (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);9394static ZipOpen_t ZipOpen = NULL;95static ZipClose_t ZipClose = NULL;96static FindEntry_t FindEntry = NULL;97static ReadEntry_t ReadEntry = NULL;98static ReadMappedEntry_t ReadMappedEntry = NULL;99static GetNextEntry_t GetNextEntry = NULL;100static canonicalize_fn_t CanonicalizeEntry = NULL;101static Crc32_t Crc32 = NULL;102103// Globals104105PerfCounter* ClassLoader::_perf_accumulated_time = NULL;106PerfCounter* ClassLoader::_perf_classes_inited = NULL;107PerfCounter* ClassLoader::_perf_class_init_time = NULL;108PerfCounter* ClassLoader::_perf_class_init_selftime = NULL;109PerfCounter* ClassLoader::_perf_classes_verified = NULL;110PerfCounter* ClassLoader::_perf_class_verify_time = NULL;111PerfCounter* ClassLoader::_perf_class_verify_selftime = NULL;112PerfCounter* ClassLoader::_perf_classes_linked = NULL;113PerfCounter* ClassLoader::_perf_class_link_time = NULL;114PerfCounter* ClassLoader::_perf_class_link_selftime = NULL;115PerfCounter* ClassLoader::_perf_class_parse_time = NULL;116PerfCounter* ClassLoader::_perf_class_parse_selftime = NULL;117PerfCounter* ClassLoader::_perf_sys_class_lookup_time = NULL;118PerfCounter* ClassLoader::_perf_shared_classload_time = NULL;119PerfCounter* ClassLoader::_perf_sys_classload_time = NULL;120PerfCounter* ClassLoader::_perf_app_classload_time = NULL;121PerfCounter* ClassLoader::_perf_app_classload_selftime = NULL;122PerfCounter* ClassLoader::_perf_app_classload_count = NULL;123PerfCounter* ClassLoader::_perf_define_appclasses = NULL;124PerfCounter* ClassLoader::_perf_define_appclass_time = NULL;125PerfCounter* ClassLoader::_perf_define_appclass_selftime = NULL;126PerfCounter* ClassLoader::_perf_app_classfile_bytes_read = NULL;127PerfCounter* ClassLoader::_perf_sys_classfile_bytes_read = NULL;128PerfCounter* ClassLoader::_sync_systemLoaderLockContentionRate = NULL;129PerfCounter* ClassLoader::_sync_nonSystemLoaderLockContentionRate = NULL;130PerfCounter* ClassLoader::_sync_JVMFindLoadedClassLockFreeCounter = NULL;131PerfCounter* ClassLoader::_sync_JVMDefineClassLockFreeCounter = NULL;132PerfCounter* ClassLoader::_sync_JNIDefineClassLockFreeCounter = NULL;133PerfCounter* ClassLoader::_unsafe_defineClassCallCounter = NULL;134PerfCounter* ClassLoader::_isUnsyncloadClass = NULL;135PerfCounter* ClassLoader::_load_instance_class_failCounter = NULL;136137ClassPathEntry* ClassLoader::_first_entry = NULL;138ClassPathEntry* ClassLoader::_last_entry = NULL;139int ClassLoader::_num_entries = 0;140PackageHashtable* ClassLoader::_package_hash_table = NULL;141142#if INCLUDE_CDS143SharedPathsMiscInfo* ClassLoader::_shared_paths_misc_info = NULL;144#endif145// helper routines146bool string_starts_with(const char* str, const char* str_to_find) {147size_t str_len = strlen(str);148size_t str_to_find_len = strlen(str_to_find);149if (str_to_find_len > str_len) {150return false;151}152return (strncmp(str, str_to_find, str_to_find_len) == 0);153}154155bool string_ends_with(const char* str, const char* str_to_find) {156size_t str_len = strlen(str);157size_t str_to_find_len = strlen(str_to_find);158if (str_to_find_len > str_len) {159return false;160}161return (strncmp(str + (str_len - str_to_find_len), str_to_find, str_to_find_len) == 0);162}163164// Used to obtain the package name from a fully qualified class name.165// It is the responsibility of the caller to establish a ResourceMark.166const char* ClassLoader::package_from_name(const char* const class_name, bool* bad_class_name) {167if (class_name == NULL) {168if (bad_class_name != NULL) {169*bad_class_name = true;170}171return NULL;172}173174if (bad_class_name != NULL) {175*bad_class_name = false;176}177178const char* const last_slash = strrchr(class_name, '/');179if (last_slash == NULL) {180// No package name181return NULL;182}183184char* class_name_ptr = (char*) class_name;185// Skip over '['s186if (*class_name_ptr == '[') {187do {188class_name_ptr++;189} while (*class_name_ptr == '[');190191// Fully qualified class names should not contain a 'L'.192// Set bad_class_name to true to indicate that the package name193// could not be obtained due to an error condition.194// In this situation, is_same_class_package returns false.195if (*class_name_ptr == 'L') {196if (bad_class_name != NULL) {197*bad_class_name = true;198}199return NULL;200}201}202203int length = last_slash - class_name_ptr;204205// A class name could have just the slash character in the name.206if (length <= 0) {207// No package name208if (bad_class_name != NULL) {209*bad_class_name = true;210}211return NULL;212}213214// drop name after last slash (including slash)215// Ex., "java/lang/String.class" => "java/lang"216char* pkg_name = NEW_RESOURCE_ARRAY(char, length + 1);217strncpy(pkg_name, class_name_ptr, length);218*(pkg_name+length) = '\0';219220return (const char *)pkg_name;221}222223MetaIndex::MetaIndex(char** meta_package_names, int num_meta_package_names) {224if (num_meta_package_names == 0) {225_meta_package_names = NULL;226_num_meta_package_names = 0;227} else {228_meta_package_names = NEW_C_HEAP_ARRAY(char*, num_meta_package_names, mtClass);229_num_meta_package_names = num_meta_package_names;230memcpy(_meta_package_names, meta_package_names, num_meta_package_names * sizeof(char*));231}232}233234235MetaIndex::~MetaIndex() {236FREE_C_HEAP_ARRAY(char*, _meta_package_names, mtClass);237}238239240bool MetaIndex::may_contain(const char* class_name) {241if ( _num_meta_package_names == 0) {242return false;243}244size_t class_name_len = strlen(class_name);245for (int i = 0; i < _num_meta_package_names; i++) {246char* pkg = _meta_package_names[i];247size_t pkg_len = strlen(pkg);248size_t min_len = MIN2(class_name_len, pkg_len);249if (!strncmp(class_name, pkg, min_len)) {250return true;251}252}253return false;254}255256257ClassPathEntry::ClassPathEntry() {258set_next(NULL);259}260261262bool ClassPathEntry::is_lazy() {263return false;264}265266ClassPathDirEntry::ClassPathDirEntry(const char* dir) : ClassPathEntry() {267char* copy = NEW_C_HEAP_ARRAY(char, strlen(dir)+1, mtClass);268strcpy(copy, dir);269_dir = copy;270}271272273ClassFileStream* ClassPathDirEntry::open_stream(const char* name, TRAPS) {274// construct full path name275char path[JVM_MAXPATHLEN];276if (jio_snprintf(path, sizeof(path), "%s%s%s", _dir, os::file_separator(), name) == -1) {277return NULL;278}279// check if file exists280struct stat st;281if (os::stat(path, &st) == 0) {282#if INCLUDE_CDS283if (DumpSharedSpaces) {284// We have already check in ClassLoader::check_shared_classpath() that the directory is empty, so285// we should never find a file underneath it -- unless user has added a new file while we are running286// the dump, in which case let's quit!287ShouldNotReachHere();288}289#endif290// found file, open it291int file_handle = os::open(path, 0, 0);292if (file_handle != -1) {293// read contents into resource array294u1* buffer = NEW_RESOURCE_ARRAY(u1, st.st_size);295size_t num_read = os::read(file_handle, (char*) buffer, st.st_size);296// close file297os::close(file_handle);298// construct ClassFileStream299if (num_read == (size_t)st.st_size) {300if (UsePerfData) {301ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read);302}303return new ClassFileStream(buffer, st.st_size, _dir); // Resource allocated304}305}306}307return NULL;308}309310311ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name) : ClassPathEntry() {312_zip = zip;313char *copy = NEW_C_HEAP_ARRAY(char, strlen(zip_name)+1, mtClass);314strcpy(copy, zip_name);315_zip_name = copy;316}317318ClassPathZipEntry::~ClassPathZipEntry() {319if (ZipClose != NULL) {320(*ZipClose)(_zip);321}322FREE_C_HEAP_ARRAY(char, _zip_name, mtClass);323}324325u1* ClassPathZipEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {326// enable call to C land327JavaThread* thread = JavaThread::current();328ThreadToNativeFromVM ttn(thread);329// check whether zip archive contains name330jint name_len;331jzentry* entry = (*FindEntry)(_zip, name, filesize, &name_len);332if (entry == NULL) return NULL;333u1* buffer;334char name_buf[128];335char* filename;336if (name_len < 128) {337filename = name_buf;338} else {339filename = NEW_RESOURCE_ARRAY(char, name_len + 1);340}341342// file found, get pointer to the entry in mmapped jar file.343if (ReadMappedEntry == NULL ||344!(*ReadMappedEntry)(_zip, entry, &buffer, filename)) {345// mmapped access not available, perhaps due to compression,346// read contents into resource array347int size = (*filesize) + ((nul_terminate) ? 1 : 0);348buffer = NEW_RESOURCE_ARRAY(u1, size);349if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL;350}351352// return result353if (nul_terminate) {354buffer[*filesize] = 0;355}356return buffer;357}358359ClassFileStream* ClassPathZipEntry::open_stream(const char* name, TRAPS) {360jint filesize;361u1* buffer = open_entry(name, &filesize, false, CHECK_NULL);362if (buffer == NULL) {363return NULL;364}365if (UsePerfData) {366ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize);367}368return new ClassFileStream(buffer, filesize, _zip_name); // Resource allocated369}370371// invoke function for each entry in the zip file372void ClassPathZipEntry::contents_do(void f(const char* name, void* context), void* context) {373JavaThread* thread = JavaThread::current();374HandleMark handle_mark(thread);375ThreadToNativeFromVM ttn(thread);376for (int n = 0; ; n++) {377jzentry * ze = ((*GetNextEntry)(_zip, n));378if (ze == NULL) break;379(*f)(ze->name, context);380}381}382383LazyClassPathEntry::LazyClassPathEntry(const char* path, const struct stat* st, bool throw_exception) : ClassPathEntry() {384_path = strdup(path);385_st = *st;386_meta_index = NULL;387_resolved_entry = NULL;388_has_error = false;389_throw_exception = throw_exception;390}391392bool LazyClassPathEntry::is_jar_file() {393return ((_st.st_mode & S_IFREG) == S_IFREG);394}395396ClassPathEntry* LazyClassPathEntry::resolve_entry(TRAPS) {397if (_resolved_entry != NULL) {398return (ClassPathEntry*) _resolved_entry;399}400ClassPathEntry* new_entry = NULL;401new_entry = ClassLoader::create_class_path_entry(_path, &_st, false, _throw_exception, CHECK_NULL);402if (!_throw_exception && new_entry == NULL) {403assert(!HAS_PENDING_EXCEPTION, "must be");404return NULL;405}406{407ThreadCritical tc;408if (_resolved_entry == NULL) {409_resolved_entry = new_entry;410return new_entry;411}412}413assert(_resolved_entry != NULL, "bug in MT-safe resolution logic");414delete new_entry;415return (ClassPathEntry*) _resolved_entry;416}417418ClassFileStream* LazyClassPathEntry::open_stream(const char* name, TRAPS) {419if (_meta_index != NULL &&420!_meta_index->may_contain(name)) {421return NULL;422}423if (_has_error) {424return NULL;425}426ClassPathEntry* cpe = resolve_entry(THREAD);427if (cpe == NULL) {428_has_error = true;429return NULL;430} else {431return cpe->open_stream(name, THREAD);432}433}434435bool LazyClassPathEntry::is_lazy() {436return true;437}438439u1* LazyClassPathEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {440if (_has_error) {441return NULL;442}443ClassPathEntry* cpe = resolve_entry(THREAD);444if (cpe == NULL) {445_has_error = true;446return NULL;447} else if (cpe->is_jar_file()) {448return ((ClassPathZipEntry*)cpe)->open_entry(name, filesize, nul_terminate,THREAD);449} else {450ShouldNotReachHere();451*filesize = 0;452return NULL;453}454}455456static void print_meta_index(LazyClassPathEntry* entry,457GrowableArray<char*>& meta_packages) {458tty->print("[Meta index for %s=", entry->name());459for (int i = 0; i < meta_packages.length(); i++) {460if (i > 0) tty->print(" ");461tty->print("%s", meta_packages.at(i));462}463tty->print_cr("]");464}465466#if INCLUDE_CDS467void ClassLoader::exit_with_path_failure(const char* error, const char* message) {468assert(DumpSharedSpaces, "only called at dump time");469tty->print_cr("Hint: enable -XX:+TraceClassPaths to diagnose the failure");470vm_exit_during_initialization(error, message);471}472#endif473474void ClassLoader::trace_class_path(outputStream* out, const char* msg, const char* name) {475if (!TraceClassPaths) {476return;477}478479if (msg) {480out->print("%s", msg);481}482if (name) {483if (strlen(name) < 256) {484out->print("%s", name);485} else {486// For very long paths, we need to print each character separately,487// as print_cr() has a length limit488while (name[0] != '\0') {489out->print("%c", name[0]);490name++;491}492}493}494if (msg && msg[0] == '[') {495out->print_cr("]");496} else {497out->cr();498}499}500501void ClassLoader::setup_bootstrap_meta_index() {502// Set up meta index which allows us to open boot jars lazily if503// class data sharing is enabled504const char* meta_index_path = Arguments::get_meta_index_path();505const char* meta_index_dir = Arguments::get_meta_index_dir();506setup_meta_index(meta_index_path, meta_index_dir, 0);507}508509void ClassLoader::setup_meta_index(const char* meta_index_path, const char* meta_index_dir, int start_index) {510const char* known_version = "% VERSION 2";511FILE* file = fopen(meta_index_path, "r");512int line_no = 0;513#if INCLUDE_CDS514if (DumpSharedSpaces) {515if (file != NULL) {516_shared_paths_misc_info->add_required_file(meta_index_path);517} else {518_shared_paths_misc_info->add_nonexist_path(meta_index_path);519}520}521#endif522if (file != NULL) {523ResourceMark rm;524LazyClassPathEntry* cur_entry = NULL;525GrowableArray<char*> boot_class_path_packages(10);526char package_name[256];527bool skipCurrentJar = false;528while (fgets(package_name, sizeof(package_name), file) != NULL) {529++line_no;530// Remove trailing newline531package_name[strlen(package_name) - 1] = '\0';532switch(package_name[0]) {533case '%':534{535if ((line_no == 1) && (strcmp(package_name, known_version) != 0)) {536if (TraceClassLoading && Verbose) {537tty->print("[Unsupported meta index version]");538}539fclose(file);540return;541}542}543544// These directives indicate jar files which contain only545// classes, only non-classfile resources, or a combination of546// the two. See src/share/classes/sun/misc/MetaIndex.java and547// make/tools/MetaIndex/BuildMetaIndex.java in the J2SE548// workspace.549case '#':550case '!':551case '@':552{553// Hand off current packages to current lazy entry (if any)554if ((cur_entry != NULL) &&555(boot_class_path_packages.length() > 0)) {556if ((TraceClassLoading || TraceClassPaths) && Verbose) {557print_meta_index(cur_entry, boot_class_path_packages);558}559MetaIndex* index = new MetaIndex(boot_class_path_packages.adr_at(0),560boot_class_path_packages.length());561cur_entry->set_meta_index(index);562}563cur_entry = NULL;564boot_class_path_packages.clear();565566// Find lazy entry corresponding to this jar file567int count = 0;568for (ClassPathEntry* entry = _first_entry; entry != NULL; entry = entry->next(), count++) {569if (count >= start_index &&570entry->is_lazy() &&571string_starts_with(entry->name(), meta_index_dir) &&572string_ends_with(entry->name(), &package_name[2])) {573cur_entry = (LazyClassPathEntry*) entry;574break;575}576}577578// If the first character is '@', it indicates the following jar579// file is a resource only jar file in which case, we should skip580// reading the subsequent entries since the resource loading is581// totally handled by J2SE side.582if (package_name[0] == '@') {583if (cur_entry != NULL) {584cur_entry->set_meta_index(new MetaIndex(NULL, 0));585}586cur_entry = NULL;587skipCurrentJar = true;588} else {589skipCurrentJar = false;590}591592break;593}594595default:596{597if (!skipCurrentJar && cur_entry != NULL) {598char* new_name = strdup(package_name);599boot_class_path_packages.append(new_name);600}601}602}603}604// Hand off current packages to current lazy entry (if any)605if ((cur_entry != NULL) &&606(boot_class_path_packages.length() > 0)) {607if ((TraceClassLoading || TraceClassPaths) && Verbose) {608print_meta_index(cur_entry, boot_class_path_packages);609}610MetaIndex* index = new MetaIndex(boot_class_path_packages.adr_at(0),611boot_class_path_packages.length());612cur_entry->set_meta_index(index);613}614fclose(file);615}616}617618#if INCLUDE_CDS619void ClassLoader::check_shared_classpath(const char *path) {620if (strcmp(path, "") == 0) {621exit_with_path_failure("Cannot have empty path in archived classpaths", NULL);622}623624struct stat st;625if (os::stat(path, &st) == 0) {626if ((st.st_mode & S_IFREG) != S_IFREG) { // is directory627if (!os::dir_is_empty(path)) {628tty->print_cr("Error: non-empty directory '%s'", path);629exit_with_path_failure("CDS allows only empty directories in archived classpaths", NULL);630}631}632}633}634#endif635636void ClassLoader::setup_bootstrap_search_path() {637assert(_first_entry == NULL, "should not setup bootstrap class search path twice");638const char* sys_class_path = Arguments::get_sysclasspath();639if (PrintSharedArchiveAndExit) {640// Don't print sys_class_path - this is the bootcp of this current VM process, not necessarily641// the same as the bootcp of the shared archive.642} else {643trace_class_path(tty, "[Bootstrap loader class path=", sys_class_path);644}645#if INCLUDE_CDS646if (DumpSharedSpaces) {647_shared_paths_misc_info->add_boot_classpath(sys_class_path);648}649#endif650setup_search_path(sys_class_path);651}652653#if INCLUDE_CDS654int ClassLoader::get_shared_paths_misc_info_size() {655return _shared_paths_misc_info->get_used_bytes();656}657658void* ClassLoader::get_shared_paths_misc_info() {659return _shared_paths_misc_info->buffer();660}661662bool ClassLoader::check_shared_paths_misc_info(void *buf, int size) {663SharedPathsMiscInfo* checker = SharedClassUtil::allocate_shared_paths_misc_info((char*)buf, size);664bool result = checker->check();665delete checker;666return result;667}668#endif669670void ClassLoader::setup_search_path(const char *class_path, bool canonicalize) {671int offset = 0;672int len = (int)strlen(class_path);673int end = 0;674675// Iterate over class path entries676for (int start = 0; start < len; start = end) {677while (class_path[end] && class_path[end] != os::path_separator()[0]) {678end++;679}680EXCEPTION_MARK;681ResourceMark rm(THREAD);682char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);683strncpy(path, &class_path[start], end - start);684path[end - start] = '\0';685if (canonicalize) {686char* canonical_path = NEW_RESOURCE_ARRAY(char, JVM_MAXPATHLEN + 1);687if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {688path = canonical_path;689}690}691update_class_path_entry_list(path, /*check_for_duplicates=*/canonicalize);692#if INCLUDE_CDS693if (DumpSharedSpaces) {694check_shared_classpath(path);695}696#endif697while (class_path[end] == os::path_separator()[0]) {698end++;699}700}701}702703ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st,704bool lazy, bool throw_exception, TRAPS) {705JavaThread* thread = JavaThread::current();706if (lazy) {707return new LazyClassPathEntry(path, st, throw_exception);708}709ClassPathEntry* new_entry = NULL;710if ((st->st_mode & S_IFREG) == S_IFREG) {711// Regular file, should be a zip file712// Canonicalized filename713char canonical_path[JVM_MAXPATHLEN];714if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {715// This matches the classic VM716if (throw_exception) {717THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL);718} else {719return NULL;720}721}722char* error_msg = NULL;723jzfile* zip;724{725// enable call to C land726ThreadToNativeFromVM ttn(thread);727HandleMark hm(thread);728zip = (*ZipOpen)(canonical_path, &error_msg);729}730if (zip != NULL && error_msg == NULL) {731new_entry = new ClassPathZipEntry(zip, path);732if (TraceClassLoading || TraceClassPaths) {733tty->print_cr("[Opened %s]", path);734}735} else {736ResourceMark rm(thread);737char *msg;738if (error_msg == NULL) {739msg = NEW_RESOURCE_ARRAY(char, strlen(path) + 128); ;740jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);741} else {742int len = (int)(strlen(path) + strlen(error_msg) + 128);743msg = NEW_RESOURCE_ARRAY(char, len); ;744jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path);745}746if (throw_exception) {747THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL);748} else {749return NULL;750}751}752} else {753// Directory754new_entry = new ClassPathDirEntry(path);755if (TraceClassLoading || TraceClassPaths) {756tty->print_cr("[Path %s]", path);757}758}759return new_entry;760}761762763// Create a class path zip entry for a given path (return NULL if not found764// or zip/JAR file cannot be opened)765ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path) {766// check for a regular file767struct stat st;768if (os::stat(path, &st) == 0) {769if ((st.st_mode & S_IFREG) == S_IFREG) {770char canonical_path[JVM_MAXPATHLEN];771if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {772char* error_msg = NULL;773jzfile* zip;774{775// enable call to C land776JavaThread* thread = JavaThread::current();777ThreadToNativeFromVM ttn(thread);778HandleMark hm(thread);779zip = (*ZipOpen)(canonical_path, &error_msg);780}781if (zip != NULL && error_msg == NULL) {782// create using canonical path783return new ClassPathZipEntry(zip, canonical_path);784}785}786}787}788return NULL;789}790791// returns true if entry already on class path792bool ClassLoader::contains_entry(ClassPathEntry *entry) {793ClassPathEntry* e = _first_entry;794while (e != NULL) {795// assume zip entries have been canonicalized796if (strcmp(entry->name(), e->name()) == 0) {797return true;798}799e = e->next();800}801return false;802}803804void ClassLoader::add_to_list(ClassPathEntry *new_entry) {805if (new_entry != NULL) {806if (_last_entry == NULL) {807_first_entry = _last_entry = new_entry;808} else {809_last_entry->set_next(new_entry);810_last_entry = new_entry;811}812}813_num_entries ++;814}815816// Returns true IFF the file/dir exists and the entry was successfully created.817bool ClassLoader::update_class_path_entry_list(const char *path,818bool check_for_duplicates,819bool throw_exception) {820struct stat st;821if (os::stat(path, &st) == 0) {822// File or directory found823ClassPathEntry* new_entry = NULL;824Thread* THREAD = Thread::current();825new_entry = create_class_path_entry(path, &st, LazyBootClassLoader, throw_exception, CHECK_(false));826if (new_entry == NULL) {827return false;828}829// The kernel VM adds dynamically to the end of the classloader path and830// doesn't reorder the bootclasspath which would break java.lang.Package831// (see PackageInfo).832// Add new entry to linked list833if (!check_for_duplicates || !contains_entry(new_entry)) {834ClassLoaderExt::add_class_path_entry(path, check_for_duplicates, new_entry);835}836return true;837} else {838#if INCLUDE_CDS839if (DumpSharedSpaces) {840_shared_paths_misc_info->add_nonexist_path(path);841}842#endif843return false;844}845}846847void ClassLoader::print_bootclasspath() {848ClassPathEntry* e = _first_entry;849tty->print("[bootclasspath= ");850while (e != NULL) {851tty->print("%s ;", e->name());852e = e->next();853}854tty->print_cr("]");855}856857void ClassLoader::load_zip_library() {858assert(ZipOpen == NULL, "should not load zip library twice");859// First make sure native library is loaded860os::native_java_library();861// Load zip library862char path[JVM_MAXPATHLEN];863char ebuf[1024];864void* handle = NULL;865if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {866handle = os::dll_load(path, ebuf, sizeof ebuf);867}868if (handle == NULL) {869vm_exit_during_initialization("Unable to load ZIP library", path);870}871// Lookup zip entry points872ZipOpen = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));873ZipClose = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));874FindEntry = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));875ReadEntry = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));876ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));877GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));878Crc32 = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));879880// ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL881if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||882GetNextEntry == NULL || Crc32 == NULL) {883vm_exit_during_initialization("Corrupted ZIP library", path);884}885886// Lookup canonicalize entry in libjava.dll887void *javalib_handle = os::native_java_library();888CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));889// This lookup only works on 1.3. Do not check for non-null here890}891892int ClassLoader::crc32(int crc, const char* buf, int len) {893assert(Crc32 != NULL, "ZIP_CRC32 is not found");894return (*Crc32)(crc, (const jbyte*)buf, len);895}896897// PackageInfo data exists in order to support the java.lang.Package898// class. A Package object provides information about a java package899// (version, vendor, etc.) which originates in the manifest of the jar900// file supplying the package. For application classes, the ClassLoader901// object takes care of this.902903// For system (boot) classes, the Java code in the Package class needs904// to be able to identify which source jar file contained the boot905// class, so that it can extract the manifest from it. This table906// identifies java packages with jar files in the boot classpath.907908// Because the boot classpath cannot change, the classpath index is909// sufficient to identify the source jar file or directory. (Since910// directories have no manifests, the directory name is not required,911// but is available.)912913// When using sharing -- the pathnames of entries in the boot classpath914// may not be the same at runtime as they were when the archive was915// created (NFS, Samba, etc.). The actual files and directories named916// in the classpath must be the same files, in the same order, even917// though the exact name is not the same.918919class PackageInfo: public BasicHashtableEntry<mtClass> {920public:921const char* _pkgname; // Package name922int _classpath_index; // Index of directory or JAR file loaded from923924PackageInfo* next() {925return (PackageInfo*)BasicHashtableEntry<mtClass>::next();926}927928const char* pkgname() { return _pkgname; }929void set_pkgname(char* pkgname) { _pkgname = pkgname; }930931const char* filename() {932return ClassLoader::classpath_entry(_classpath_index)->name();933}934935void set_index(int index) {936_classpath_index = index;937}938};939940941class PackageHashtable : public BasicHashtable<mtClass> {942private:943inline unsigned int compute_hash(const char *s, int n) {944unsigned int val = 0;945while (--n >= 0) {946val = *s++ + 31 * val;947}948return val;949}950951PackageInfo* bucket(int index) {952return (PackageInfo*)BasicHashtable<mtClass>::bucket(index);953}954955PackageInfo* get_entry(int index, unsigned int hash,956const char* pkgname, size_t n) {957for (PackageInfo* pp = bucket(index); pp != NULL; pp = pp->next()) {958if (pp->hash() == hash &&959strncmp(pkgname, pp->pkgname(), n) == 0 &&960pp->pkgname()[n] == '\0') {961return pp;962}963}964return NULL;965}966967public:968PackageHashtable(int table_size)969: BasicHashtable<mtClass>(table_size, sizeof(PackageInfo)) {}970971PackageHashtable(int table_size, HashtableBucket<mtClass>* t, int number_of_entries)972: BasicHashtable<mtClass>(table_size, sizeof(PackageInfo), t, number_of_entries) {}973974PackageInfo* get_entry(const char* pkgname, int n) {975unsigned int hash = compute_hash(pkgname, n);976return get_entry(hash_to_index(hash), hash, pkgname, n);977}978979PackageInfo* new_entry(char* pkgname, int n) {980unsigned int hash = compute_hash(pkgname, n);981PackageInfo* pp;982pp = (PackageInfo*)BasicHashtable<mtClass>::new_entry(hash);983pp->set_pkgname(pkgname);984return pp;985}986987void add_entry(PackageInfo* pp) {988int index = hash_to_index(pp->hash());989BasicHashtable<mtClass>::add_entry(index, pp);990}991992void copy_pkgnames(const char** packages) {993int n = 0;994for (int i = 0; i < table_size(); ++i) {995for (PackageInfo* pp = bucket(i); pp != NULL; pp = pp->next()) {996packages[n++] = pp->pkgname();997}998}999assert(n == number_of_entries(), "just checking");1000}10011002CDS_ONLY(void copy_table(char** top, char* end, PackageHashtable* table);)1003};10041005#if INCLUDE_CDS1006void PackageHashtable::copy_table(char** top, char* end,1007PackageHashtable* table) {1008// Copy (relocate) the table to the shared space.1009BasicHashtable<mtClass>::copy_table(top, end);10101011// Calculate the space needed for the package name strings.1012int i;1013intptr_t* tableSize = (intptr_t*)(*top);1014*top += sizeof(intptr_t); // For table size1015char* tableStart = *top;10161017for (i = 0; i < table_size(); ++i) {1018for (PackageInfo* pp = table->bucket(i);1019pp != NULL;1020pp = pp->next()) {1021int n1 = (int)(strlen(pp->pkgname()) + 1);1022if (*top + n1 >= end) {1023report_out_of_shared_space(SharedMiscData);1024}1025pp->set_pkgname((char*)memcpy(*top, pp->pkgname(), n1));1026*top += n1;1027}1028}1029*top = (char*)align_size_up((intptr_t)*top, sizeof(HeapWord));1030if (*top >= end) {1031report_out_of_shared_space(SharedMiscData);1032}10331034// Write table size1035intptr_t len = *top - (char*)tableStart;1036*tableSize = len;1037}103810391040void ClassLoader::copy_package_info_buckets(char** top, char* end) {1041_package_hash_table->copy_buckets(top, end);1042}10431044void ClassLoader::copy_package_info_table(char** top, char* end) {1045_package_hash_table->copy_table(top, end, _package_hash_table);1046}1047#endif10481049PackageInfo* ClassLoader::lookup_package(const char *pkgname) {1050const char *cp = strrchr(pkgname, '/');1051if (cp != NULL) {1052// Package prefix found1053int n = cp - pkgname + 1;1054return _package_hash_table->get_entry(pkgname, n);1055}1056return NULL;1057}105810591060bool ClassLoader::add_package(const char *pkgname, int classpath_index, TRAPS) {1061assert(pkgname != NULL, "just checking");1062// Bootstrap loader no longer holds system loader lock obj serializing1063// load_instance_class and thereby add_package1064{1065MutexLocker ml(PackageTable_lock, THREAD);1066// First check for previously loaded entry1067PackageInfo* pp = lookup_package(pkgname);1068if (pp != NULL) {1069// Existing entry found, check source of package1070pp->set_index(classpath_index);1071return true;1072}10731074const char *cp = strrchr(pkgname, '/');1075if (cp != NULL) {1076// Package prefix found1077int n = cp - pkgname + 1;10781079char* new_pkgname = NEW_C_HEAP_ARRAY(char, n + 1, mtClass);1080if (new_pkgname == NULL) {1081return false;1082}10831084memcpy(new_pkgname, pkgname, n);1085new_pkgname[n] = '\0';1086pp = _package_hash_table->new_entry(new_pkgname, n);1087pp->set_index(classpath_index);10881089// Insert into hash table1090_package_hash_table->add_entry(pp);1091}1092return true;1093}1094}109510961097oop ClassLoader::get_system_package(const char* name, TRAPS) {1098PackageInfo* pp;1099{1100MutexLocker ml(PackageTable_lock, THREAD);1101pp = lookup_package(name);1102}1103if (pp == NULL) {1104return NULL;1105} else {1106Handle p = java_lang_String::create_from_str(pp->filename(), THREAD);1107return p();1108}1109}111011111112objArrayOop ClassLoader::get_system_packages(TRAPS) {1113ResourceMark rm(THREAD);1114int nof_entries;1115const char** packages;1116{1117MutexLocker ml(PackageTable_lock, THREAD);1118// Allocate resource char* array containing package names1119nof_entries = _package_hash_table->number_of_entries();1120if ((packages = NEW_RESOURCE_ARRAY(const char*, nof_entries)) == NULL) {1121return NULL;1122}1123_package_hash_table->copy_pkgnames(packages);1124}1125// Allocate objArray and fill with java.lang.String1126objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),1127nof_entries, CHECK_0);1128objArrayHandle result(THREAD, r);1129for (int i = 0; i < nof_entries; i++) {1130Handle str = java_lang_String::create_from_str(packages[i], CHECK_0);1131result->obj_at_put(i, str());1132}11331134return result();1135}113611371138instanceKlassHandle ClassLoader::load_classfile(Symbol* h_name, TRAPS) {1139ResourceMark rm(THREAD);1140const char* class_name = h_name->as_C_string();1141EventMark m("loading class %s", class_name);1142ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion);11431144stringStream st;1145// st.print() uses too much stack space while handling a StackOverflowError1146// st.print("%s.class", h_name->as_utf8());1147st.print_raw(h_name->as_utf8());1148st.print_raw(".class");1149const char* file_name = st.as_string();1150ClassLoaderExt::Context context(class_name, file_name, THREAD);11511152// Lookup stream for parsing .class file1153ClassFileStream* stream = NULL;1154int classpath_index = 0;1155ClassPathEntry* e = NULL;1156instanceKlassHandle h;1157{1158PerfClassTraceTime vmtimer(perf_sys_class_lookup_time(),1159((JavaThread*) THREAD)->get_thread_stat()->perf_timers_addr(),1160PerfClassTraceTime::CLASS_LOAD);1161e = _first_entry;1162while (e != NULL) {1163stream = e->open_stream(file_name, CHECK_NULL);1164if (!context.check(stream, classpath_index)) {1165return h; // NULL1166}1167if (stream != NULL) {1168break;1169}1170e = e->next();1171++classpath_index;1172}1173}11741175if (stream != NULL) {1176// class file found, parse it1177ClassFileParser parser(stream);1178ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();1179Handle protection_domain;1180TempNewSymbol parsed_name = NULL;1181// Callers are expected to declare a ResourceMark to determine1182// the lifetime of any updated (resource) allocated under1183// this call to parseClassFile1184// We do not declare another ResourceMark here, reusing the one declared1185// at the start of the method1186instanceKlassHandle result = parser.parseClassFile(h_name,1187loader_data,1188protection_domain,1189parsed_name,1190context.should_verify(classpath_index),1191THREAD);1192if (HAS_PENDING_EXCEPTION) {1193ResourceMark rm;1194if (DumpSharedSpaces) {1195tty->print_cr("Preload Error: Failed to load %s", class_name);1196}1197return h;1198}11991200#if INCLUDE_JFR1201{1202InstanceKlass* ik = result();1203ON_KLASS_CREATION(ik, parser, THREAD);1204result = instanceKlassHandle(ik);1205}1206#endif12071208h = context.record_result(classpath_index, e, result, THREAD);1209} else {1210if (DumpSharedSpaces) {1211tty->print_cr("Preload Warning: Cannot find %s", class_name);1212}1213}12141215return h;1216}121712181219void ClassLoader::create_package_info_table(HashtableBucket<mtClass> *t, int length,1220int number_of_entries) {1221assert(_package_hash_table == NULL, "One package info table allowed.");1222assert(length == package_hash_table_size * sizeof(HashtableBucket<mtClass>),1223"bad shared package info size.");1224_package_hash_table = new PackageHashtable(package_hash_table_size, t,1225number_of_entries);1226}122712281229void ClassLoader::create_package_info_table() {1230assert(_package_hash_table == NULL, "shouldn't have one yet");1231_package_hash_table = new PackageHashtable(package_hash_table_size);1232}123312341235// Initialize the class loader's access to methods in libzip. Parse and1236// process the boot classpath into a list ClassPathEntry objects. Once1237// this list has been created, it must not change order (see class PackageInfo)1238// it can be appended to and is by jvmti and the kernel vm.12391240void ClassLoader::initialize() {1241assert(_package_hash_table == NULL, "should have been initialized by now.");1242EXCEPTION_MARK;12431244if (UsePerfData) {1245// jvmstat performance counters1246NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");1247NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");1248NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");1249NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");1250NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");1251NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");1252NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");1253NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");1254NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");1255NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");12561257NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime");1258NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self");1259NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime");1260NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");1261NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");1262NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");1263NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");1264NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");1265NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");1266NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");1267NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");1268NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");1269NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");127012711272// The following performance counters are added for measuring the impact1273// of the bug fix of 6365597. They are mainly focused on finding out1274// the behavior of system & user-defined classloader lock, whether1275// ClassLoader.loadClass/findClass is being called synchronized or not.1276// Also two additional counters are created to see whether 'UnsyncloadClass'1277// flag is being set or not and how many times load_instance_class call1278// fails with linkageError etc.1279NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS,1280"systemLoaderLockContentionRate");1281NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS,1282"nonSystemLoaderLockContentionRate");1283NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS,1284"jvmFindLoadedClassNoLockCalls");1285NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS,1286"jvmDefineClassNoLockCalls");12871288NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS,1289"jniDefineClassNoLockCalls");12901291NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS,1292"unsafeDefineClassCalls");12931294NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet");1295NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS,1296"loadInstanceClassFailRate");12971298// increment the isUnsyncloadClass counter if UnsyncloadClass is set.1299if (UnsyncloadClass) {1300_isUnsyncloadClass->inc();1301}1302}13031304// lookup zip library entry points1305load_zip_library();1306#if INCLUDE_CDS1307// initialize search path1308if (DumpSharedSpaces) {1309_shared_paths_misc_info = SharedClassUtil::allocate_shared_paths_misc_info();1310}1311#endif1312setup_bootstrap_search_path();1313if (LazyBootClassLoader) {1314// set up meta index which makes boot classpath initialization lazier1315setup_bootstrap_meta_index();1316}1317}13181319#if INCLUDE_CDS1320void ClassLoader::initialize_shared_path() {1321if (DumpSharedSpaces) {1322ClassLoaderExt::setup_search_paths();1323_shared_paths_misc_info->write_jint(0); // see comments in SharedPathsMiscInfo::check()1324}1325}1326#endif13271328jlong ClassLoader::classloader_time_ms() {1329return UsePerfData ?1330Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;1331}13321333jlong ClassLoader::class_init_count() {1334return UsePerfData ? _perf_classes_inited->get_value() : -1;1335}13361337jlong ClassLoader::class_init_time_ms() {1338return UsePerfData ?1339Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;1340}13411342jlong ClassLoader::class_verify_time_ms() {1343return UsePerfData ?1344Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;1345}13461347jlong ClassLoader::class_link_count() {1348return UsePerfData ? _perf_classes_linked->get_value() : -1;1349}13501351jlong ClassLoader::class_link_time_ms() {1352return UsePerfData ?1353Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;1354}13551356int ClassLoader::compute_Object_vtable() {1357// hardwired for JDK1.2 -- would need to duplicate class file parsing1358// code to determine actual value from file1359// Would be value '11' if finals were in vtable1360int JDK_1_2_Object_vtable_size = 5;1361return JDK_1_2_Object_vtable_size * vtableEntry::size();1362}136313641365void classLoader_init() {1366ClassLoader::initialize();1367}136813691370bool ClassLoader::get_canonical_path(const char* orig, char* out, int len) {1371assert(orig != NULL && out != NULL && len > 0, "bad arguments");1372if (CanonicalizeEntry != NULL) {1373JavaThread* THREAD = JavaThread::current();1374JNIEnv* env = THREAD->jni_environment();1375ResourceMark rm(THREAD);13761377// os::native_path writes into orig_copy1378char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(orig)+1);1379strcpy(orig_copy, orig);1380if ((CanonicalizeEntry)(env, os::native_path(orig_copy), out, len) < 0) {1381return false;1382}1383} else {1384// On JDK 1.2.2 the Canonicalize does not exist, so just do nothing1385strncpy(out, orig, len);1386out[len - 1] = '\0';1387}1388return true;1389}13901391#ifndef PRODUCT13921393void ClassLoader::verify() {1394_package_hash_table->verify();1395}139613971398// CompileTheWorld1399//1400// Iterates over all class path entries and forces compilation of all methods1401// in all classes found. Currently, only zip/jar archives are searched.1402//1403// The classes are loaded by the Java level bootstrap class loader, and the1404// initializer is called. If DelayCompilationDuringStartup is true (default),1405// the interpreter will run the initialization code. Note that forcing1406// initialization in this way could potentially lead to initialization order1407// problems, in which case we could just force the initialization bit to be set.140814091410// We need to iterate over the contents of a zip/jar file, so we replicate the1411// jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile,1412// since jzfile already has a void* definition.1413//1414// Note that this is only used in debug mode.1415//1416// HotSpot integration note:1417// Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build141814191420// JDK 1.3 version1421typedef struct real_jzentry13 { /* Zip file entry */1422char *name; /* entry name */1423jint time; /* modification time */1424jint size; /* size of uncompressed data */1425jint csize; /* size of compressed data (zero if uncompressed) */1426jint crc; /* crc of uncompressed data */1427char *comment; /* optional zip file comment */1428jbyte *extra; /* optional extra data */1429jint pos; /* position of LOC header (if negative) or data */1430} real_jzentry13;14311432typedef struct real_jzfile13 { /* Zip file */1433char *name; /* zip file name */1434jint refs; /* number of active references */1435jint fd; /* open file descriptor */1436void *lock; /* read lock */1437char *comment; /* zip file comment */1438char *msg; /* zip error message */1439void *entries; /* array of hash cells */1440jint total; /* total number of entries */1441unsigned short *table; /* Hash chain heads: indexes into entries */1442jint tablelen; /* number of hash eads */1443real_jzfile13 *next; /* next zip file in search list */1444jzentry *cache; /* we cache the most recently freed jzentry */1445/* Information on metadata names in META-INF directory */1446char **metanames; /* array of meta names (may have null names) */1447jint metacount; /* number of slots in metanames array */1448/* If there are any per-entry comments, they are in the comments array */1449char **comments;1450} real_jzfile13;14511452// JDK 1.2 version1453typedef struct real_jzentry12 { /* Zip file entry */1454char *name; /* entry name */1455jint time; /* modification time */1456jint size; /* size of uncompressed data */1457jint csize; /* size of compressed data (zero if uncompressed) */1458jint crc; /* crc of uncompressed data */1459char *comment; /* optional zip file comment */1460jbyte *extra; /* optional extra data */1461jint pos; /* position of LOC header (if negative) or data */1462struct real_jzentry12 *next; /* next entry in hash table */1463} real_jzentry12;14641465typedef struct real_jzfile12 { /* Zip file */1466char *name; /* zip file name */1467jint refs; /* number of active references */1468jint fd; /* open file descriptor */1469void *lock; /* read lock */1470char *comment; /* zip file comment */1471char *msg; /* zip error message */1472real_jzentry12 *entries; /* array of zip entries */1473jint total; /* total number of entries */1474real_jzentry12 **table; /* hash table of entries */1475jint tablelen; /* number of buckets */1476jzfile *next; /* next zip file in search list */1477} real_jzfile12;147814791480void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {1481// For now we only compile all methods in all classes in zip/jar files1482tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);1483tty->cr();1484}148514861487bool ClassPathDirEntry::is_rt_jar() {1488return false;1489}14901491void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {1492if (JDK_Version::is_jdk12x_version()) {1493compile_the_world12(loader, THREAD);1494} else {1495compile_the_world13(loader, THREAD);1496}1497if (HAS_PENDING_EXCEPTION) {1498if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {1499CLEAR_PENDING_EXCEPTION;1500tty->print_cr("\nCompileTheWorld : Ran out of memory\n");1501tty->print_cr("Increase class metadata storage if a limit was set");1502} else {1503tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");1504}1505}1506}15071508// Version that works for JDK 1.3.x1509void ClassPathZipEntry::compile_the_world13(Handle loader, TRAPS) {1510real_jzfile13* zip = (real_jzfile13*) _zip;1511tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);1512tty->cr();1513// Iterate over all entries in zip file1514for (int n = 0; ; n++) {1515real_jzentry13 * ze = (real_jzentry13 *)((*GetNextEntry)(_zip, n));1516if (ze == NULL) break;1517ClassLoader::compile_the_world_in(ze->name, loader, CHECK);1518}1519}152015211522// Version that works for JDK 1.2.x1523void ClassPathZipEntry::compile_the_world12(Handle loader, TRAPS) {1524real_jzfile12* zip = (real_jzfile12*) _zip;1525tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);1526tty->cr();1527// Iterate over all entries in zip file1528for (int n = 0; ; n++) {1529real_jzentry12 * ze = (real_jzentry12 *)((*GetNextEntry)(_zip, n));1530if (ze == NULL) break;1531ClassLoader::compile_the_world_in(ze->name, loader, CHECK);1532}1533}15341535bool ClassPathZipEntry::is_rt_jar() {1536if (JDK_Version::is_jdk12x_version()) {1537return is_rt_jar12();1538} else {1539return is_rt_jar13();1540}1541}15421543// JDK 1.3 version1544bool ClassPathZipEntry::is_rt_jar13() {1545real_jzfile13* zip = (real_jzfile13*) _zip;1546int len = (int)strlen(zip->name);1547// Check whether zip name ends in "rt.jar"1548// This will match other archives named rt.jar as well, but this is1549// only used for debugging.1550return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0);1551}15521553// JDK 1.2 version1554bool ClassPathZipEntry::is_rt_jar12() {1555real_jzfile12* zip = (real_jzfile12*) _zip;1556int len = (int)strlen(zip->name);1557// Check whether zip name ends in "rt.jar"1558// This will match other archives named rt.jar as well, but this is1559// only used for debugging.1560return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0);1561}15621563void LazyClassPathEntry::compile_the_world(Handle loader, TRAPS) {1564ClassPathEntry* cpe = resolve_entry(THREAD);1565if (cpe != NULL) {1566cpe->compile_the_world(loader, CHECK);1567}1568}15691570bool LazyClassPathEntry::is_rt_jar() {1571Thread* THREAD = Thread::current();1572ClassPathEntry* cpe = resolve_entry(THREAD);1573return (cpe != NULL) ? cpe->is_jar_file() : false;1574}15751576void ClassLoader::compile_the_world() {1577EXCEPTION_MARK;1578HandleMark hm(THREAD);1579ResourceMark rm(THREAD);1580// Make sure we don't run with background compilation1581BackgroundCompilation = false;1582// Find bootstrap loader1583Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());1584// Iterate over all bootstrap class path entries1585ClassPathEntry* e = _first_entry;1586jlong start = os::javaTimeMillis();1587while (e != NULL) {1588// We stop at rt.jar, unless it is the first bootstrap path entry1589if (e->is_rt_jar() && e != _first_entry) break;1590e->compile_the_world(system_class_loader, CATCH);1591e = e->next();1592}1593jlong end = os::javaTimeMillis();1594tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)",1595_compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));1596{1597// Print statistics as if before normal exit:1598extern void print_statistics();1599print_statistics();1600}1601vm_exit(0);1602}16031604int ClassLoader::_compile_the_world_class_counter = 0;1605int ClassLoader::_compile_the_world_method_counter = 0;1606static int _codecache_sweep_counter = 0;16071608// Filter out all exceptions except OOMs1609static void clear_pending_exception_if_not_oom(TRAPS) {1610if (HAS_PENDING_EXCEPTION &&1611!PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {1612CLEAR_PENDING_EXCEPTION;1613}1614// The CHECK at the caller will propagate the exception out1615}16161617/**1618* Returns if the given method should be compiled when doing compile-the-world.1619*1620* TODO: This should be a private method in a CompileTheWorld class.1621*/1622static bool can_be_compiled(methodHandle m, int comp_level) {1623assert(CompileTheWorld, "must be");16241625// It's not valid to compile a native wrapper for MethodHandle methods1626// that take a MemberName appendix since the bytecode signature is not1627// correct.1628vmIntrinsics::ID iid = m->intrinsic_id();1629if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) {1630return false;1631}16321633return CompilationPolicy::can_be_compiled(m, comp_level);1634}16351636void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {1637size_t len = strlen(name);1638if (len > 6 && strcmp(".class", name + len - 6) == 0) {1639// We have a .class file1640char buffer[2048];1641if (len-6 >= sizeof(buffer)) return;1642strncpy(buffer, name, sizeof(buffer));1643buffer[len-6] = 0; // Truncate ".class" suffix.1644// If the file has a period after removing .class, it's not really a1645// valid class file. The class loader will check everything else.1646if (strchr(buffer, '.') == NULL) {1647_compile_the_world_class_counter++;1648if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;16491650// Construct name without extension1651TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);1652// Use loader to load and initialize class1653Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);1654instanceKlassHandle k (THREAD, ik);1655if (k.not_null() && !HAS_PENDING_EXCEPTION) {1656k->initialize(THREAD);1657}1658bool exception_occurred = HAS_PENDING_EXCEPTION;1659clear_pending_exception_if_not_oom(CHECK);1660if (CompileTheWorldPreloadClasses && k.not_null()) {1661ConstantPool::preload_and_initialize_all_classes(k->constants(), THREAD);1662if (HAS_PENDING_EXCEPTION) {1663// If something went wrong in preloading we just ignore it1664clear_pending_exception_if_not_oom(CHECK);1665tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer);1666}1667}16681669if (_compile_the_world_class_counter >= CompileTheWorldStartAt) {1670if (k.is_null() || exception_occurred) {1671// If something went wrong (e.g. ExceptionInInitializerError) we skip this class1672tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer);1673} else {1674tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer);1675// Preload all classes to get around uncommon traps1676// Iterate over all methods in class1677int comp_level = CompilationPolicy::policy()->initial_compile_level();1678for (int n = 0; n < k->methods()->length(); n++) {1679methodHandle m (THREAD, k->methods()->at(n));1680if (can_be_compiled(m, comp_level)) {1681if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) {1682// Give sweeper a chance to keep up with CTW1683VM_ForceSafepoint op;1684VMThread::execute(&op);1685_codecache_sweep_counter = 0;1686}1687// Force compilation1688CompileBroker::compile_method(m, InvocationEntryBci, comp_level,1689methodHandle(), 0, "CTW", THREAD);1690if (HAS_PENDING_EXCEPTION) {1691clear_pending_exception_if_not_oom(CHECK);1692tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());1693} else {1694_compile_the_world_method_counter++;1695}1696if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) {1697// Clobber the first compile and force second tier compilation1698nmethod* nm = m->code();1699if (nm != NULL && !m->is_method_handle_intrinsic()) {1700// Throw out the code so that the code cache doesn't fill up1701nm->make_not_entrant();1702}1703CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization,1704methodHandle(), 0, "CTW", THREAD);1705if (HAS_PENDING_EXCEPTION) {1706clear_pending_exception_if_not_oom(CHECK);1707tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());1708} else {1709_compile_the_world_method_counter++;1710}1711}1712} else {1713tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());1714}17151716nmethod* nm = m->code();1717if (nm != NULL && !m->is_method_handle_intrinsic()) {1718// Throw out the code so that the code cache doesn't fill up1719nm->make_not_entrant();1720}1721}1722}1723}1724}1725}1726}17271728#endif //PRODUCT17291730// Please keep following two functions at end of this file. With them placed at top or in middle of the file,1731// they could get inlined by agressive compiler, an unknown trick, see bug 6966589.1732void PerfClassTraceTime::initialize() {1733if (!UsePerfData) return;17341735if (_eventp != NULL) {1736// increment the event counter1737_eventp->inc();1738}17391740// stop the current active thread-local timer to measure inclusive time1741_prev_active_event = -1;1742for (int i=0; i < EVENT_TYPE_COUNT; i++) {1743if (_timers[i].is_active()) {1744assert(_prev_active_event == -1, "should have only one active timer");1745_prev_active_event = i;1746_timers[i].stop();1747}1748}17491750if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) {1751// start the inclusive timer if not recursively called1752_t.start();1753}17541755// start thread-local timer of the given event type1756if (!_timers[_event_type].is_active()) {1757_timers[_event_type].start();1758}1759}17601761PerfClassTraceTime::~PerfClassTraceTime() {1762if (!UsePerfData) return;17631764// stop the thread-local timer as the event completes1765// and resume the thread-local timer of the event next on the stack1766_timers[_event_type].stop();1767jlong selftime = _timers[_event_type].ticks();17681769if (_prev_active_event >= 0) {1770_timers[_prev_active_event].start();1771}17721773if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return;17741775// increment the counters only on the leaf call1776_t.stop();1777_timep->inc(_t.ticks());1778if (_selftimep != NULL) {1779_selftimep->inc(selftime);1780}1781// add all class loading related event selftime to the accumulated time counter1782ClassLoader::perf_accumulated_time()->inc(selftime);17831784// reset the timer1785_timers[_event_type].reset();1786}178717881789