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