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