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