classLoader.cpp revision 11330:778d1fc95e05
1/*
2 * Copyright (c) 1997, 2016, 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/classFileStream.hpp"
27#include "classfile/classLoader.hpp"
28#include "classfile/classLoaderData.inline.hpp"
29#include "classfile/classLoaderExt.hpp"
30#include "classfile/javaClasses.hpp"
31#include "classfile/jimage.hpp"
32#include "classfile/moduleEntry.hpp"
33#include "classfile/modules.hpp"
34#include "classfile/packageEntry.hpp"
35#include "classfile/klassFactory.hpp"
36#include "classfile/systemDictionary.hpp"
37#include "classfile/vmSymbols.hpp"
38#include "compiler/compileBroker.hpp"
39#include "gc/shared/collectedHeap.inline.hpp"
40#include "gc/shared/generation.hpp"
41#include "interpreter/bytecodeStream.hpp"
42#include "interpreter/oopMapCache.hpp"
43#include "logging/logTag.hpp"
44#include "memory/allocation.inline.hpp"
45#include "memory/filemap.hpp"
46#include "memory/oopFactory.hpp"
47#include "memory/resourceArea.hpp"
48#include "memory/universe.inline.hpp"
49#include "oops/instanceKlass.hpp"
50#include "oops/instanceRefKlass.hpp"
51#include "oops/objArrayOop.inline.hpp"
52#include "oops/oop.inline.hpp"
53#include "oops/symbol.hpp"
54#include "prims/jvm_misc.hpp"
55#include "runtime/arguments.hpp"
56#include "runtime/compilationPolicy.hpp"
57#include "runtime/fprofiler.hpp"
58#include "runtime/handles.hpp"
59#include "runtime/handles.inline.hpp"
60#include "runtime/init.hpp"
61#include "runtime/interfaceSupport.hpp"
62#include "runtime/java.hpp"
63#include "runtime/javaCalls.hpp"
64#include "runtime/os.hpp"
65#include "runtime/threadCritical.hpp"
66#include "runtime/timer.hpp"
67#include "runtime/vm_version.hpp"
68#include "services/management.hpp"
69#include "services/threadService.hpp"
70#include "utilities/events.hpp"
71#include "utilities/hashtable.inline.hpp"
72#include "utilities/macros.hpp"
73#if INCLUDE_CDS
74#include "classfile/sharedClassUtil.hpp"
75#include "classfile/sharedPathsMiscInfo.hpp"
76#endif
77
78// Entry points in zip.dll for loading zip/jar file entries
79
80typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg);
81typedef void (JNICALL *ZipClose_t)(jzfile *zip);
82typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen);
83typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);
84typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf);
85typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);
86typedef jboolean (JNICALL *ZipInflateFully_t)(void *inBuf, jlong inLen, void *outBuf, jlong outLen, char **pmsg);
87typedef jint     (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);
88
89static ZipOpen_t         ZipOpen            = NULL;
90static ZipClose_t        ZipClose           = NULL;
91static FindEntry_t       FindEntry          = NULL;
92static ReadEntry_t       ReadEntry          = NULL;
93static ReadMappedEntry_t ReadMappedEntry    = NULL;
94static GetNextEntry_t    GetNextEntry       = NULL;
95static canonicalize_fn_t CanonicalizeEntry  = NULL;
96static ZipInflateFully_t ZipInflateFully    = NULL;
97static Crc32_t           Crc32              = NULL;
98
99// Entry points for jimage.dll for loading jimage file entries
100
101static JImageOpen_t                    JImageOpen             = NULL;
102static JImageClose_t                   JImageClose            = NULL;
103static JImagePackageToModule_t         JImagePackageToModule  = NULL;
104static JImageFindResource_t            JImageFindResource     = NULL;
105static JImageGetResource_t             JImageGetResource      = NULL;
106static JImageResourceIterator_t        JImageResourceIterator = NULL;
107static JImage_ResourcePath_t           JImageResourcePath     = NULL;
108
109// Globals
110
111PerfCounter*    ClassLoader::_perf_accumulated_time = NULL;
112PerfCounter*    ClassLoader::_perf_classes_inited = NULL;
113PerfCounter*    ClassLoader::_perf_class_init_time = NULL;
114PerfCounter*    ClassLoader::_perf_class_init_selftime = NULL;
115PerfCounter*    ClassLoader::_perf_classes_verified = NULL;
116PerfCounter*    ClassLoader::_perf_class_verify_time = NULL;
117PerfCounter*    ClassLoader::_perf_class_verify_selftime = NULL;
118PerfCounter*    ClassLoader::_perf_classes_linked = NULL;
119PerfCounter*    ClassLoader::_perf_class_link_time = NULL;
120PerfCounter*    ClassLoader::_perf_class_link_selftime = NULL;
121PerfCounter*    ClassLoader::_perf_class_parse_time = NULL;
122PerfCounter*    ClassLoader::_perf_class_parse_selftime = NULL;
123PerfCounter*    ClassLoader::_perf_sys_class_lookup_time = NULL;
124PerfCounter*    ClassLoader::_perf_shared_classload_time = NULL;
125PerfCounter*    ClassLoader::_perf_sys_classload_time = NULL;
126PerfCounter*    ClassLoader::_perf_app_classload_time = NULL;
127PerfCounter*    ClassLoader::_perf_app_classload_selftime = NULL;
128PerfCounter*    ClassLoader::_perf_app_classload_count = NULL;
129PerfCounter*    ClassLoader::_perf_define_appclasses = NULL;
130PerfCounter*    ClassLoader::_perf_define_appclass_time = NULL;
131PerfCounter*    ClassLoader::_perf_define_appclass_selftime = NULL;
132PerfCounter*    ClassLoader::_perf_app_classfile_bytes_read = NULL;
133PerfCounter*    ClassLoader::_perf_sys_classfile_bytes_read = NULL;
134PerfCounter*    ClassLoader::_sync_systemLoaderLockContentionRate = NULL;
135PerfCounter*    ClassLoader::_sync_nonSystemLoaderLockContentionRate = NULL;
136PerfCounter*    ClassLoader::_sync_JVMFindLoadedClassLockFreeCounter = NULL;
137PerfCounter*    ClassLoader::_sync_JVMDefineClassLockFreeCounter = NULL;
138PerfCounter*    ClassLoader::_sync_JNIDefineClassLockFreeCounter = NULL;
139PerfCounter*    ClassLoader::_unsafe_defineClassCallCounter = NULL;
140PerfCounter*    ClassLoader::_isUnsyncloadClass = NULL;
141PerfCounter*    ClassLoader::_load_instance_class_failCounter = NULL;
142
143GrowableArray<ModuleClassPathList*>* ClassLoader::_xpatch_entries = NULL;
144ClassPathEntry* ClassLoader::_first_entry        = NULL;
145ClassPathEntry* ClassLoader::_last_entry         = NULL;
146int             ClassLoader::_num_entries        = 0;
147ClassPathEntry* ClassLoader::_first_append_entry = NULL;
148bool            ClassLoader::_has_jimage = false;
149#if INCLUDE_CDS
150GrowableArray<char*>* ClassLoader::_boot_modules_array = NULL;
151GrowableArray<char*>* ClassLoader::_platform_modules_array = NULL;
152SharedPathsMiscInfo* ClassLoader::_shared_paths_misc_info = NULL;
153#endif
154
155// helper routines
156bool string_starts_with(const char* str, const char* str_to_find) {
157  size_t str_len = strlen(str);
158  size_t str_to_find_len = strlen(str_to_find);
159  if (str_to_find_len > str_len) {
160    return false;
161  }
162  return (strncmp(str, str_to_find, str_to_find_len) == 0);
163}
164
165static const char* get_jimage_version_string() {
166  static char version_string[10] = "";
167  if (version_string[0] == '\0') {
168    jio_snprintf(version_string, sizeof(version_string), "%d.%d",
169                 Abstract_VM_Version::vm_major_version(), Abstract_VM_Version::vm_minor_version());
170  }
171  return (const char*)version_string;
172}
173
174bool ClassLoader::string_ends_with(const char* str, const char* str_to_find) {
175  size_t str_len = strlen(str);
176  size_t str_to_find_len = strlen(str_to_find);
177  if (str_to_find_len > str_len) {
178    return false;
179  }
180  return (strncmp(str + (str_len - str_to_find_len), str_to_find, str_to_find_len) == 0);
181}
182
183// Used to obtain the package name from a fully qualified class name.
184// It is the responsibility of the caller to establish ResourceMark.
185const char* ClassLoader::package_from_name(const char* class_name) {
186  const char* last_slash = strrchr(class_name, '/');
187  if (last_slash == NULL) {
188    // No package name
189    return NULL;
190  }
191  int length = last_slash - class_name;
192
193  // A class name could have just the slash character in the name,
194  // resulting in a negative length.
195  if (length <= 0) {
196    // No package name
197    return NULL;
198  }
199
200  // drop name after last slash (including slash)
201  // Ex., "java/lang/String.class" => "java/lang"
202  char* pkg_name = NEW_RESOURCE_ARRAY(char, length + 1);
203  strncpy(pkg_name, class_name, length);
204  *(pkg_name+length) = '\0';
205
206  return (const char *)pkg_name;
207}
208
209// Given a fully qualified class name, find its defining package in the class loader's
210// package entry table.
211static PackageEntry* get_package_entry(const char* class_name, ClassLoaderData* loader_data, TRAPS) {
212  ResourceMark rm(THREAD);
213  const char *pkg_name = ClassLoader::package_from_name(class_name);
214  if (pkg_name == NULL) {
215    return NULL;
216  }
217  PackageEntryTable* pkgEntryTable = loader_data->packages();
218  TempNewSymbol pkg_symbol = SymbolTable::new_symbol(pkg_name, CHECK_NULL);
219  return pkgEntryTable->lookup_only(pkg_symbol);
220}
221
222ClassPathDirEntry::ClassPathDirEntry(const char* dir) : ClassPathEntry() {
223  char* copy = NEW_C_HEAP_ARRAY(char, strlen(dir)+1, mtClass);
224  strcpy(copy, dir);
225  _dir = copy;
226}
227
228
229ClassFileStream* ClassPathDirEntry::open_stream(const char* name, TRAPS) {
230  // construct full path name
231  char path[JVM_MAXPATHLEN];
232  if (jio_snprintf(path, sizeof(path), "%s%s%s", _dir, os::file_separator(), name) == -1) {
233    return NULL;
234  }
235  // check if file exists
236  struct stat st;
237  if (os::stat(path, &st) == 0) {
238#if INCLUDE_CDS
239    if (DumpSharedSpaces) {
240      // We have already check in ClassLoader::check_shared_classpath() that the directory is empty, so
241      // we should never find a file underneath it -- unless user has added a new file while we are running
242      // the dump, in which case let's quit!
243      ShouldNotReachHere();
244    }
245#endif
246    // found file, open it
247    int file_handle = os::open(path, 0, 0);
248    if (file_handle != -1) {
249      // read contents into resource array
250      u1* buffer = NEW_RESOURCE_ARRAY(u1, st.st_size);
251      size_t num_read = os::read(file_handle, (char*) buffer, st.st_size);
252      // close file
253      os::close(file_handle);
254      // construct ClassFileStream
255      if (num_read == (size_t)st.st_size) {
256        if (UsePerfData) {
257          ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read);
258        }
259        // Resource allocated
260        return new ClassFileStream(buffer,
261                                   st.st_size,
262                                   _dir,
263                                   ClassFileStream::verify);
264      }
265    }
266  }
267  return NULL;
268}
269
270ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name, bool is_boot_append) : ClassPathEntry() {
271  _zip = zip;
272  char *copy = NEW_C_HEAP_ARRAY(char, strlen(zip_name)+1, mtClass);
273  strcpy(copy, zip_name);
274  _zip_name = copy;
275  _is_boot_append = is_boot_append;
276  _multi_versioned = _unknown;
277}
278
279ClassPathZipEntry::~ClassPathZipEntry() {
280  if (ZipClose != NULL) {
281    (*ZipClose)(_zip);
282  }
283  FREE_C_HEAP_ARRAY(char, _zip_name);
284}
285
286u1* ClassPathZipEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {
287    // enable call to C land
288  JavaThread* thread = JavaThread::current();
289  ThreadToNativeFromVM ttn(thread);
290  // check whether zip archive contains name
291  jint name_len;
292  jzentry* entry = (*FindEntry)(_zip, name, filesize, &name_len);
293  if (entry == NULL) return NULL;
294  u1* buffer;
295  char name_buf[128];
296  char* filename;
297  if (name_len < 128) {
298    filename = name_buf;
299  } else {
300    filename = NEW_RESOURCE_ARRAY(char, name_len + 1);
301  }
302
303  // file found, get pointer to the entry in mmapped jar file.
304  if (ReadMappedEntry == NULL ||
305      !(*ReadMappedEntry)(_zip, entry, &buffer, filename)) {
306      // mmapped access not available, perhaps due to compression,
307      // read contents into resource array
308      int size = (*filesize) + ((nul_terminate) ? 1 : 0);
309      buffer = NEW_RESOURCE_ARRAY(u1, size);
310      if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL;
311  }
312
313  // return result
314  if (nul_terminate) {
315    buffer[*filesize] = 0;
316  }
317  return buffer;
318}
319
320#if INCLUDE_CDS
321u1* ClassPathZipEntry::open_versioned_entry(const char* name, jint* filesize, TRAPS) {
322  u1* buffer = NULL;
323  if (DumpSharedSpaces && !_is_boot_append) {
324    // We presume default is multi-release enabled
325    const char* multi_ver = Arguments::get_property("jdk.util.jar.enableMultiRelease");
326    const char* verstr = Arguments::get_property("jdk.util.jar.version");
327    bool is_multi_ver = (multi_ver == NULL ||
328                         strcmp(multi_ver, "true") == 0 ||
329                         strcmp(multi_ver, "force")  == 0) &&
330                         is_multiple_versioned(THREAD);
331    // command line version setting
332    int version = 0;
333    const int base_version = 8; // JDK8
334    int cur_ver = JDK_Version::current().major_version();
335    if (verstr != NULL) {
336      version = atoi(verstr);
337      if (version < base_version || version > cur_ver) {
338        is_multi_ver = false;
339        // print out warning, do not use assertion here since it will continue to look
340        // for proper version.
341        warning("JDK%d is not supported in multiple version jars", version);
342      }
343    }
344
345    if (is_multi_ver) {
346      int n;
347      char entry_name[JVM_MAXPATHLEN];
348      if (version > 0) {
349        n = jio_snprintf(entry_name, sizeof(entry_name), "META-INF/versions/%d/%s", version, name);
350        entry_name[n] = '\0';
351        buffer = open_entry((const char*)entry_name, filesize, false, CHECK_NULL);
352        if (buffer == NULL) {
353          warning("Could not find %s in %s, try to find highest version instead", entry_name, _zip_name);
354        }
355      }
356      if (buffer == NULL) {
357        for (int i = cur_ver; i >= base_version; i--) {
358          n = jio_snprintf(entry_name, sizeof(entry_name), "META-INF/versions/%d/%s", i, name);
359          entry_name[n] = '\0';
360          buffer = open_entry((const char*)entry_name, filesize, false, CHECK_NULL);
361          if (buffer != NULL) {
362            break;
363          }
364        }
365      }
366    }
367  }
368  return buffer;
369}
370
371bool ClassPathZipEntry::is_multiple_versioned(TRAPS) {
372  assert(DumpSharedSpaces, "called only at dump time");
373  if (_multi_versioned != _unknown) {
374    return (_multi_versioned == _yes) ? true : false;
375  }
376  jint size;
377  char* buffer = (char*)open_entry("META-INF/MANIFEST.MF", &size, true, CHECK_false);
378  if (buffer != NULL) {
379    char* p = buffer;
380    for ( ; *p; ++p) *p = tolower(*p);
381    if (strstr(buffer, "multi-release: true") != NULL) {
382      _multi_versioned = _yes;
383      return true;
384    }
385  }
386  _multi_versioned = _no;
387  return false;
388}
389#endif // INCLUDE_CDS
390
391ClassFileStream* ClassPathZipEntry::open_stream(const char* name, TRAPS) {
392  jint filesize;
393  u1* buffer = open_versioned_entry(name, &filesize, CHECK_NULL);
394  if (buffer == NULL) {
395    buffer = open_entry(name, &filesize, false, CHECK_NULL);
396    if (buffer == NULL) {
397      return NULL;
398    }
399  }
400  if (UsePerfData) {
401    ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize);
402  }
403  // Resource allocated
404  return new ClassFileStream(buffer,
405                             filesize,
406                             _zip_name,
407                             ClassFileStream::verify);
408}
409
410// invoke function for each entry in the zip file
411void ClassPathZipEntry::contents_do(void f(const char* name, void* context), void* context) {
412  JavaThread* thread = JavaThread::current();
413  HandleMark  handle_mark(thread);
414  ThreadToNativeFromVM ttn(thread);
415  for (int n = 0; ; n++) {
416    jzentry * ze = ((*GetNextEntry)(_zip, n));
417    if (ze == NULL) break;
418    (*f)(ze->name, context);
419  }
420}
421
422ClassPathImageEntry::ClassPathImageEntry(JImageFile* jimage, const char* name) :
423  ClassPathEntry(),
424  _jimage(jimage) {
425  guarantee(jimage != NULL, "jimage file is null");
426  guarantee(name != NULL, "jimage file name is null");
427  size_t len = strlen(name) + 1;
428  _name = NEW_C_HEAP_ARRAY(const char, len, mtClass);
429  strncpy((char *)_name, name, len);
430}
431
432ClassPathImageEntry::~ClassPathImageEntry() {
433  if (_name != NULL) {
434    FREE_C_HEAP_ARRAY(const char, _name);
435    _name = NULL;
436  }
437  if (_jimage != NULL) {
438    (*JImageClose)(_jimage);
439    _jimage = NULL;
440  }
441}
442
443// For a class in a named module, look it up in the jimage file using this syntax:
444//    /<module-name>/<package-name>/<base-class>
445//
446// Assumptions:
447//     1. There are no unnamed modules in the jimage file.
448//     2. A package is in at most one module in the jimage file.
449//
450ClassFileStream* ClassPathImageEntry::open_stream(const char* name, TRAPS) {
451  jlong size;
452  JImageLocationRef location = (*JImageFindResource)(_jimage, "", get_jimage_version_string(), name, &size);
453
454  if (location == 0) {
455    ResourceMark rm;
456    const char* pkg_name = ClassLoader::package_from_name(name);
457
458    if (pkg_name != NULL) {
459      if (!Universe::is_module_initialized()) {
460        location = (*JImageFindResource)(_jimage, "java.base", get_jimage_version_string(), name, &size);
461#if INCLUDE_CDS
462        // CDS uses the boot class loader to load classes whose packages are in
463        // modules defined for other class loaders.  So, for now, get their module
464        // names from the "modules" jimage file.
465        if (DumpSharedSpaces && location == 0) {
466          const char* module_name = (*JImagePackageToModule)(_jimage, pkg_name);
467          if (module_name != NULL) {
468            location = (*JImageFindResource)(_jimage, module_name, get_jimage_version_string(), name, &size);
469          }
470        }
471#endif
472
473      } else {
474        PackageEntry* package_entry = get_package_entry(name, ClassLoaderData::the_null_class_loader_data(), THREAD);
475        if (package_entry != NULL) {
476          ResourceMark rm;
477          // Get the module name
478          ModuleEntry* module = package_entry->module();
479          assert(module != NULL, "Boot classLoader package missing module");
480          assert(module->is_named(), "Boot classLoader package is in unnamed module");
481          const char* module_name = module->name()->as_C_string();
482          if (module_name != NULL) {
483            location = (*JImageFindResource)(_jimage, module_name, get_jimage_version_string(), name, &size);
484          }
485        }
486      }
487    }
488  }
489  if (location != 0) {
490    if (UsePerfData) {
491      ClassLoader::perf_sys_classfile_bytes_read()->inc(size);
492    }
493    char* data = NEW_RESOURCE_ARRAY(char, size);
494    (*JImageGetResource)(_jimage, location, data, size);
495    // Resource allocated
496    return new ClassFileStream((u1*)data,
497                               (int)size,
498                               _name,
499                               ClassFileStream::verify);
500  }
501
502  return NULL;
503}
504
505#ifndef PRODUCT
506bool ctw_visitor(JImageFile* jimage,
507        const char* module_name, const char* version, const char* package,
508        const char* name, const char* extension, void* arg) {
509  if (strcmp(extension, "class") == 0) {
510    Thread* THREAD = Thread::current();
511    char path[JIMAGE_MAX_PATH];
512    jio_snprintf(path, JIMAGE_MAX_PATH - 1, "%s/%s.class", package, name);
513    ClassLoader::compile_the_world_in(path, *(Handle*)arg, THREAD);
514    return !HAS_PENDING_EXCEPTION;
515  }
516  return true;
517}
518
519void ClassPathImageEntry::compile_the_world(Handle loader, TRAPS) {
520  tty->print_cr("CompileTheWorld : Compiling all classes in %s", name());
521  tty->cr();
522  (*JImageResourceIterator)(_jimage, (JImageResourceVisitor_t)ctw_visitor, (void *)&loader);
523  if (HAS_PENDING_EXCEPTION) {
524    if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
525      CLEAR_PENDING_EXCEPTION;
526      tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
527      tty->print_cr("Increase class metadata storage if a limit was set");
528    } else {
529      tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
530    }
531  }
532}
533#endif
534
535bool ClassPathImageEntry::is_jrt() {
536  return ClassLoader::is_jrt(name());
537}
538
539#if INCLUDE_CDS
540void ClassLoader::exit_with_path_failure(const char* error, const char* message) {
541  assert(DumpSharedSpaces, "only called at dump time");
542  tty->print_cr("Hint: enable -Xlog:class+path=info to diagnose the failure");
543  vm_exit_during_initialization(error, message);
544}
545#endif
546
547ModuleClassPathList::ModuleClassPathList(Symbol* module_name) {
548  _module_name = module_name;
549  _module_first_entry = NULL;
550  _module_last_entry = NULL;
551}
552
553ModuleClassPathList::~ModuleClassPathList() {
554  // Clean out each ClassPathEntry on list
555  ClassPathEntry* e = _module_first_entry;
556  while (e != NULL) {
557    ClassPathEntry* next_entry = e->next();
558    delete e;
559    e = next_entry;
560  }
561}
562
563void ModuleClassPathList::add_to_list(ClassPathEntry* new_entry) {
564  if (new_entry != NULL) {
565    if (_module_last_entry == NULL) {
566      _module_first_entry = _module_last_entry = new_entry;
567    } else {
568      _module_last_entry->set_next(new_entry);
569      _module_last_entry = new_entry;
570    }
571  }
572}
573
574void ClassLoader::trace_class_path(const char* msg, const char* name) {
575  if (log_is_enabled(Info, class, path)) {
576    ResourceMark rm;
577    outputStream* out = Log(class, path)::info_stream();
578    if (msg) {
579      out->print("%s", msg);
580    }
581    if (name) {
582      if (strlen(name) < 256) {
583        out->print("%s", name);
584      } else {
585        // For very long paths, we need to print each character separately,
586        // as print_cr() has a length limit
587        while (name[0] != '\0') {
588          out->print("%c", name[0]);
589          name++;
590        }
591      }
592    }
593    out->cr();
594  }
595}
596
597#if INCLUDE_CDS
598void ClassLoader::check_shared_classpath(const char *path) {
599  if (strcmp(path, "") == 0) {
600    exit_with_path_failure("Cannot have empty path in archived classpaths", NULL);
601  }
602
603  struct stat st;
604  if (os::stat(path, &st) == 0) {
605    if ((st.st_mode & S_IFREG) != S_IFREG) { // is directory
606      if (!os::dir_is_empty(path)) {
607        tty->print_cr("Error: non-empty directory '%s'", path);
608        exit_with_path_failure("CDS allows only empty directories in archived classpaths", NULL);
609      }
610    }
611  }
612}
613#endif
614
615void ClassLoader::setup_bootstrap_search_path() {
616  assert(_first_entry == NULL, "should not setup bootstrap class search path twice");
617  const char* sys_class_path = Arguments::get_sysclasspath();
618  const char* java_class_path = Arguments::get_appclasspath();
619  if (PrintSharedArchiveAndExit) {
620    // Don't print sys_class_path - this is the bootcp of this current VM process, not necessarily
621    // the same as the bootcp of the shared archive.
622  } else {
623    trace_class_path("bootstrap loader class path=", sys_class_path);
624    trace_class_path("classpath: ", java_class_path);
625  }
626#if INCLUDE_CDS
627  if (DumpSharedSpaces) {
628    _shared_paths_misc_info->add_boot_classpath(sys_class_path);
629  }
630#endif
631  setup_search_path(sys_class_path, true);
632}
633
634#if INCLUDE_CDS
635int ClassLoader::get_shared_paths_misc_info_size() {
636  return _shared_paths_misc_info->get_used_bytes();
637}
638
639void* ClassLoader::get_shared_paths_misc_info() {
640  return _shared_paths_misc_info->buffer();
641}
642
643bool ClassLoader::check_shared_paths_misc_info(void *buf, int size) {
644  SharedPathsMiscInfo* checker = SharedClassUtil::allocate_shared_paths_misc_info((char*)buf, size);
645  bool result = checker->check();
646  delete checker;
647  return result;
648}
649#endif
650
651// Construct the array of module/path pairs as specified to -Xpatch
652// for the boot loader to search ahead of the jimage, if the class being
653// loaded is defined to a module that has been specified to -Xpatch.
654void ClassLoader::setup_xpatch_entries() {
655  Thread* THREAD = Thread::current();
656  GrowableArray<ModuleXPatchPath*>* xpatch_args = Arguments::get_xpatchprefix();
657  int num_of_entries = xpatch_args->length();
658
659  // Set up the boot loader's xpatch_entries list
660  _xpatch_entries = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<ModuleClassPathList*>(num_of_entries, true);
661
662  for (int i = 0; i < num_of_entries; i++) {
663    const char* module_name = (xpatch_args->at(i))->module_name();
664    Symbol* const module_sym = SymbolTable::lookup(module_name, (int)strlen(module_name), CHECK);
665    assert(module_sym != NULL, "Failed to obtain Symbol for module name");
666    ModuleClassPathList* module_cpl = new ModuleClassPathList(module_sym);
667
668    char* class_path = (xpatch_args->at(i))->path_string();
669    int len = (int)strlen(class_path);
670    int end = 0;
671    // Iterate over the module's class path entries
672    for (int start = 0; start < len; start = end) {
673      while (class_path[end] && class_path[end] != os::path_separator()[0]) {
674        end++;
675      }
676      EXCEPTION_MARK;
677      ResourceMark rm(THREAD);
678      char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);
679      strncpy(path, &class_path[start], end - start);
680      path[end - start] = '\0';
681
682      struct stat st;
683      if (os::stat(path, &st) == 0) {
684        // File or directory found
685        Thread* THREAD = Thread::current();
686        ClassPathEntry* new_entry = create_class_path_entry(path, &st, false, false, CHECK);
687        // If the path specification is valid, enter it into this module's list
688        if (new_entry != NULL) {
689          module_cpl->add_to_list(new_entry);
690        }
691      }
692
693      while (class_path[end] == os::path_separator()[0]) {
694        end++;
695      }
696    }
697
698    // Record the module into the list of -Xpatch entries only if
699    // valid ClassPathEntrys have been created
700    if (module_cpl->module_first_entry() != NULL) {
701      _xpatch_entries->push(module_cpl);
702    }
703  }
704}
705
706void ClassLoader::setup_search_path(const char *class_path, bool bootstrap_search) {
707  int offset = 0;
708  int len = (int)strlen(class_path);
709  int end = 0;
710  bool mark_append_entry = false;
711
712  // Iterate over class path entries
713  for (int start = 0; start < len; start = end) {
714    while (class_path[end] && class_path[end] != os::path_separator()[0]) {
715      end++;
716    }
717    EXCEPTION_MARK;
718    ResourceMark rm(THREAD);
719    mark_append_entry = (mark_append_entry ||
720      (bootstrap_search && (start == Arguments::bootclassloader_append_index())));
721    char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);
722    strncpy(path, &class_path[start], end - start);
723    path[end - start] = '\0';
724    update_class_path_entry_list(path, false, mark_append_entry, false, bootstrap_search);
725
726    // Check on the state of the boot loader's append path
727    if (mark_append_entry && (_first_append_entry == NULL)) {
728      // Failure to mark the first append entry, most likely
729      // due to a non-existent path. Record the next entry
730      // as the first boot loader append entry.
731      mark_append_entry = true;
732    } else {
733      mark_append_entry = false;
734    }
735
736#if INCLUDE_CDS
737    if (DumpSharedSpaces) {
738      check_shared_classpath(path);
739    }
740#endif
741    while (class_path[end] == os::path_separator()[0]) {
742      end++;
743    }
744  }
745}
746
747ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st,
748                                                     bool throw_exception,
749                                                     bool is_boot_append, TRAPS) {
750  JavaThread* thread = JavaThread::current();
751  ClassPathEntry* new_entry = NULL;
752  if ((st->st_mode & S_IFREG) == S_IFREG) {
753    // Regular file, should be a zip or jimage file
754    // Canonicalized filename
755    char canonical_path[JVM_MAXPATHLEN];
756    if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
757      // This matches the classic VM
758      if (throw_exception) {
759        THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL);
760      } else {
761        return NULL;
762      }
763    }
764    jint error;
765    JImageFile* jimage =(*JImageOpen)(canonical_path, &error);
766    if (jimage != NULL) {
767      new_entry = new ClassPathImageEntry(jimage, canonical_path);
768    } else {
769      char* error_msg = NULL;
770      jzfile* zip;
771      {
772        // enable call to C land
773        ThreadToNativeFromVM ttn(thread);
774        HandleMark hm(thread);
775        zip = (*ZipOpen)(canonical_path, &error_msg);
776      }
777      if (zip != NULL && error_msg == NULL) {
778        new_entry = new ClassPathZipEntry(zip, path, is_boot_append);
779      } else {
780        ResourceMark rm(thread);
781        char *msg;
782        if (error_msg == NULL) {
783          msg = NEW_RESOURCE_ARRAY(char, strlen(path) + 128); ;
784          jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
785        } else {
786          int len = (int)(strlen(path) + strlen(error_msg) + 128);
787          msg = NEW_RESOURCE_ARRAY(char, len); ;
788          jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path);
789        }
790        // Don't complain about bad jar files added via -Xbootclasspath/a:.
791        if (throw_exception && is_init_completed()) {
792          THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL);
793        } else {
794          return NULL;
795        }
796      }
797    }
798    log_info(class, path)("opened: %s", path);
799    log_info(class, load)("opened: %s", path);
800  } else {
801    // Directory
802    new_entry = new ClassPathDirEntry(path);
803    log_info(class, load)("path: %s", path);
804  }
805  return new_entry;
806}
807
808
809// Create a class path zip entry for a given path (return NULL if not found
810// or zip/JAR file cannot be opened)
811ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path, bool is_boot_append) {
812  // check for a regular file
813  struct stat st;
814  if (os::stat(path, &st) == 0) {
815    if ((st.st_mode & S_IFREG) == S_IFREG) {
816      char canonical_path[JVM_MAXPATHLEN];
817      if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
818        char* error_msg = NULL;
819        jzfile* zip;
820        {
821          // enable call to C land
822          JavaThread* thread = JavaThread::current();
823          ThreadToNativeFromVM ttn(thread);
824          HandleMark hm(thread);
825          zip = (*ZipOpen)(canonical_path, &error_msg);
826        }
827        if (zip != NULL && error_msg == NULL) {
828          // create using canonical path
829          return new ClassPathZipEntry(zip, canonical_path, is_boot_append);
830        }
831      }
832    }
833  }
834  return NULL;
835}
836
837// The boot class loader must adhere to specfic visibility rules.
838// Prior to loading a class in a named package, the package is checked
839// to see if it is in a module defined to the boot loader. If the
840// package is not in a module defined to the boot loader, the class
841// must be loaded only in the boot loader's append path, which
842// consists of [-Xbootclasspath/a]; [jvmti appended entries]
843void ClassLoader::set_first_append_entry(ClassPathEntry *new_entry) {
844  if (_first_append_entry == NULL) {
845    _first_append_entry = new_entry;
846  }
847}
848
849// returns true if entry already on class path
850bool ClassLoader::contains_entry(ClassPathEntry *entry) {
851  ClassPathEntry* e = _first_entry;
852  while (e != NULL) {
853    // assume zip entries have been canonicalized
854    if (strcmp(entry->name(), e->name()) == 0) {
855      return true;
856    }
857    e = e->next();
858  }
859  return false;
860}
861
862void ClassLoader::add_to_list(ClassPathEntry *new_entry) {
863  if (new_entry != NULL) {
864    if (_last_entry == NULL) {
865      _first_entry = _last_entry = new_entry;
866    } else {
867      _last_entry->set_next(new_entry);
868      _last_entry = new_entry;
869    }
870  }
871  _num_entries ++;
872}
873
874void ClassLoader::prepend_to_list(ClassPathEntry *new_entry) {
875  if (new_entry != NULL) {
876    if (_last_entry == NULL) {
877      _first_entry = _last_entry = new_entry;
878    } else {
879      new_entry->set_next(_first_entry);
880      _first_entry = new_entry;
881    }
882  }
883  _num_entries ++;
884}
885
886void ClassLoader::add_to_list(const char *apath) {
887  update_class_path_entry_list((char*)apath, false, false, false, false);
888}
889
890void ClassLoader::prepend_to_list(const char *apath) {
891  update_class_path_entry_list((char*)apath, false, false, true, false);
892}
893
894// Returns true IFF the file/dir exists and the entry was successfully created.
895bool ClassLoader::update_class_path_entry_list(const char *path,
896                                               bool check_for_duplicates,
897                                               bool mark_append_entry,
898                                               bool prepend_entry,
899                                               bool is_boot_append,
900                                               bool throw_exception) {
901  struct stat st;
902  if (os::stat(path, &st) == 0) {
903    // File or directory found
904    ClassPathEntry* new_entry = NULL;
905    Thread* THREAD = Thread::current();
906    new_entry = create_class_path_entry(path, &st, throw_exception, is_boot_append, CHECK_(false));
907    if (new_entry == NULL) {
908      return false;
909    }
910
911    // Ensure that the first boot loader append entry will always be set correctly.
912    assert((!mark_append_entry ||
913            (mark_append_entry && (!check_for_duplicates || !contains_entry(new_entry)))),
914           "failed to mark boot loader's first append boundary");
915
916    // Do not reorder the bootclasspath which would break get_system_package().
917    // Add new entry to linked list
918
919    if (!check_for_duplicates || !contains_entry(new_entry)) {
920      ClassLoaderExt::add_class_path_entry(path, check_for_duplicates, new_entry, prepend_entry);
921      if (mark_append_entry) {
922        set_first_append_entry(new_entry);
923      }
924    }
925    return true;
926  } else {
927#if INCLUDE_CDS
928    if (DumpSharedSpaces) {
929      _shared_paths_misc_info->add_nonexist_path(path);
930    }
931#endif
932    return false;
933  }
934}
935
936void ClassLoader::print_bootclasspath() {
937  ClassPathEntry* e;
938  tty->print("[bootclasspath= ");
939
940  // Print -Xpatch module/path specifications first
941  if (_xpatch_entries != NULL) {
942    ResourceMark rm;
943    int num_of_entries = _xpatch_entries->length();
944    for (int i = 0; i < num_of_entries; i++) {
945      ModuleClassPathList* mpl = _xpatch_entries->at(i);
946      tty->print("%s=", mpl->module_name()->as_C_string());
947      e = mpl->module_first_entry();
948      while (e != NULL) {
949        tty->print("%s", e->name());
950        e = e->next();
951        if (e != NULL) {
952          tty->print("%s", os::path_separator());
953        }
954      }
955      tty->print(" ;");
956    }
957  }
958
959  e = _first_entry;
960  while (e != NULL) {
961    tty->print("%s ;", e->name());
962    e = e->next();
963  }
964  tty->print_cr("]");
965}
966
967void ClassLoader::load_zip_library() {
968  assert(ZipOpen == NULL, "should not load zip library twice");
969  // First make sure native library is loaded
970  os::native_java_library();
971  // Load zip library
972  char path[JVM_MAXPATHLEN];
973  char ebuf[1024];
974  void* handle = NULL;
975  if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {
976    handle = os::dll_load(path, ebuf, sizeof ebuf);
977  }
978  if (handle == NULL) {
979    vm_exit_during_initialization("Unable to load ZIP library", path);
980  }
981  // Lookup zip entry points
982  ZipOpen      = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));
983  ZipClose     = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));
984  FindEntry    = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));
985  ReadEntry    = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
986  ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));
987  GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));
988  ZipInflateFully = CAST_TO_FN_PTR(ZipInflateFully_t, os::dll_lookup(handle, "ZIP_InflateFully"));
989  Crc32        = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));
990
991  // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
992  if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||
993      GetNextEntry == NULL || Crc32 == NULL) {
994    vm_exit_during_initialization("Corrupted ZIP library", path);
995  }
996
997  if (ZipInflateFully == NULL) {
998    vm_exit_during_initialization("Corrupted ZIP library ZIP_InflateFully missing", path);
999  }
1000
1001  // Lookup canonicalize entry in libjava.dll
1002  void *javalib_handle = os::native_java_library();
1003  CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));
1004  // This lookup only works on 1.3. Do not check for non-null here
1005}
1006
1007void ClassLoader::load_jimage_library() {
1008  // First make sure native library is loaded
1009  os::native_java_library();
1010  // Load jimage library
1011  char path[JVM_MAXPATHLEN];
1012  char ebuf[1024];
1013  void* handle = NULL;
1014  if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "jimage")) {
1015    handle = os::dll_load(path, ebuf, sizeof ebuf);
1016  }
1017  if (handle == NULL) {
1018    vm_exit_during_initialization("Unable to load jimage library", path);
1019  }
1020
1021  // Lookup jimage entry points
1022  JImageOpen = CAST_TO_FN_PTR(JImageOpen_t, os::dll_lookup(handle, "JIMAGE_Open"));
1023  guarantee(JImageOpen != NULL, "function JIMAGE_Open not found");
1024  JImageClose = CAST_TO_FN_PTR(JImageClose_t, os::dll_lookup(handle, "JIMAGE_Close"));
1025  guarantee(JImageClose != NULL, "function JIMAGE_Close not found");
1026  JImagePackageToModule = CAST_TO_FN_PTR(JImagePackageToModule_t, os::dll_lookup(handle, "JIMAGE_PackageToModule"));
1027  guarantee(JImagePackageToModule != NULL, "function JIMAGE_PackageToModule not found");
1028  JImageFindResource = CAST_TO_FN_PTR(JImageFindResource_t, os::dll_lookup(handle, "JIMAGE_FindResource"));
1029  guarantee(JImageFindResource != NULL, "function JIMAGE_FindResource not found");
1030  JImageGetResource = CAST_TO_FN_PTR(JImageGetResource_t, os::dll_lookup(handle, "JIMAGE_GetResource"));
1031  guarantee(JImageGetResource != NULL, "function JIMAGE_GetResource not found");
1032  JImageResourceIterator = CAST_TO_FN_PTR(JImageResourceIterator_t, os::dll_lookup(handle, "JIMAGE_ResourceIterator"));
1033  guarantee(JImageResourceIterator != NULL, "function JIMAGE_ResourceIterator not found");
1034  JImageResourcePath = CAST_TO_FN_PTR(JImage_ResourcePath_t, os::dll_lookup(handle, "JIMAGE_ResourcePath"));
1035  guarantee(JImageResourcePath != NULL, "function JIMAGE_ResourcePath not found");
1036}
1037
1038jboolean ClassLoader::decompress(void *in, u8 inSize, void *out, u8 outSize, char **pmsg) {
1039  return (*ZipInflateFully)(in, inSize, out, outSize, pmsg);
1040}
1041
1042int ClassLoader::crc32(int crc, const char* buf, int len) {
1043  assert(Crc32 != NULL, "ZIP_CRC32 is not found");
1044  return (*Crc32)(crc, (const jbyte*)buf, len);
1045}
1046
1047#if INCLUDE_CDS
1048void ClassLoader::initialize_module_loader_map(JImageFile* jimage) {
1049  if (!DumpSharedSpaces) {
1050    return; // only needed for CDS dump time
1051  }
1052
1053  ResourceMark rm;
1054  jlong size;
1055  JImageLocationRef location = (*JImageFindResource)(jimage, "java.base", get_jimage_version_string(), MODULE_LOADER_MAP, &size);
1056  if (location == 0) {
1057    vm_exit_during_initialization(
1058      "Cannot find ModuleLoaderMap location from modules jimage.", NULL);
1059  }
1060  char* buffer = NEW_RESOURCE_ARRAY(char, size + 1);
1061  buffer[size] = '\0';
1062  jlong read = (*JImageGetResource)(jimage, location, buffer, size);
1063  if (read != size) {
1064    vm_exit_during_initialization(
1065      "Cannot find ModuleLoaderMap resource from modules jimage.", NULL);
1066  }
1067  char* char_buf = (char*)buffer;
1068  int buflen = (int)strlen(char_buf);
1069  char* begin_ptr = char_buf;
1070  char* end_ptr = strchr(begin_ptr, '\n');
1071  bool process_boot_modules = false;
1072  _boot_modules_array = new (ResourceObj::C_HEAP, mtInternal)
1073    GrowableArray<char*>(INITIAL_BOOT_MODULES_ARRAY_SIZE, true);
1074  _platform_modules_array = new (ResourceObj::C_HEAP, mtInternal)
1075    GrowableArray<char*>(INITIAL_PLATFORM_MODULES_ARRAY_SIZE, true);
1076  while (end_ptr != NULL && (end_ptr - char_buf) < buflen) {
1077    // Allocate a buffer from the C heap to be appended to the _boot_modules_array
1078    // or the _platform_modules_array.
1079    char* temp_name = NEW_C_HEAP_ARRAY(char, (size_t)(end_ptr - begin_ptr + 1), mtInternal);
1080    strncpy(temp_name, begin_ptr, end_ptr - begin_ptr);
1081    temp_name[end_ptr - begin_ptr] = '\0';
1082    if (strncmp(temp_name, "BOOT", 4) == 0) {
1083      process_boot_modules = true;
1084      FREE_C_HEAP_ARRAY(char, temp_name);
1085    } else if (strncmp(temp_name, "PLATFORM", 8) == 0) {
1086      process_boot_modules = false;
1087      FREE_C_HEAP_ARRAY(char, temp_name);
1088    } else {
1089      // module name
1090      if (process_boot_modules) {
1091        _boot_modules_array->append(temp_name);
1092      } else {
1093        _platform_modules_array->append(temp_name);
1094      }
1095    }
1096    begin_ptr = ++end_ptr;
1097    end_ptr = strchr(begin_ptr, '\n');
1098  }
1099}
1100#endif
1101
1102// Function add_package extracts the package from the fully qualified class name
1103// and checks if the package is in the boot loader's package entry table.  If so,
1104// then it sets the classpath_index in the package entry record.
1105//
1106// The classpath_index field is used to find the entry on the boot loader class
1107// path for packages with classes loaded by the boot loader from -Xbootclasspath/a
1108// in an unnamed module.  It is also used to indicate (for all packages whose
1109// classes are loaded by the boot loader) that at least one of the package's
1110// classes has been loaded.
1111bool ClassLoader::add_package(const char *fullq_class_name, s2 classpath_index, TRAPS) {
1112  assert(fullq_class_name != NULL, "just checking");
1113
1114  // Get package name from fully qualified class name.
1115  const char *cp = strrchr(fullq_class_name, '/');
1116  if (cp != NULL) {
1117    int len = cp - fullq_class_name;
1118    PackageEntryTable* pkg_entry_tbl =
1119      ClassLoaderData::the_null_class_loader_data()->packages();
1120    TempNewSymbol pkg_symbol =
1121      SymbolTable::new_symbol(fullq_class_name, len, CHECK_false);
1122    PackageEntry* pkg_entry = pkg_entry_tbl->lookup_only(pkg_symbol);
1123    if (pkg_entry != NULL) {
1124      assert(classpath_index != -1, "Unexpected classpath_index");
1125      pkg_entry->set_classpath_index(classpath_index);
1126    } else {
1127      return false;
1128    }
1129  }
1130  return true;
1131}
1132
1133oop ClassLoader::get_system_package(const char* name, TRAPS) {
1134  // Look up the name in the boot loader's package entry table.
1135  if (name != NULL) {
1136    TempNewSymbol package_sym = SymbolTable::new_symbol(name, (int)strlen(name), CHECK_NULL);
1137    // Look for the package entry in the boot loader's package entry table.
1138    PackageEntry* package =
1139      ClassLoaderData::the_null_class_loader_data()->packages()->lookup_only(package_sym);
1140
1141    // Return NULL if package does not exist or if no classes in that package
1142    // have been loaded.
1143    if (package != NULL && package->has_loaded_class()) {
1144      ModuleEntry* module = package->module();
1145      if (module->location() != NULL) {
1146        ResourceMark rm(THREAD);
1147        Handle ml = java_lang_String::create_from_str(
1148          module->location()->as_C_string(), THREAD);
1149        return ml();
1150      }
1151      // Return entry on boot loader class path.
1152      Handle cph = java_lang_String::create_from_str(
1153        ClassLoader::classpath_entry(package->classpath_index())->name(), THREAD);
1154      return cph();
1155    }
1156  }
1157  return NULL;
1158}
1159
1160objArrayOop ClassLoader::get_system_packages(TRAPS) {
1161  ResourceMark rm(THREAD);
1162  // List of pointers to PackageEntrys that have loaded classes.
1163  GrowableArray<PackageEntry*>* loaded_class_pkgs = new GrowableArray<PackageEntry*>(50);
1164  {
1165    MutexLocker ml(Module_lock, THREAD);
1166
1167    PackageEntryTable* pe_table =
1168      ClassLoaderData::the_null_class_loader_data()->packages();
1169
1170    // Collect the packages that have at least one loaded class.
1171    for (int x = 0; x < pe_table->table_size(); x++) {
1172      for (PackageEntry* package_entry = pe_table->bucket(x);
1173           package_entry != NULL;
1174           package_entry = package_entry->next()) {
1175        if (package_entry->has_loaded_class()) {
1176          loaded_class_pkgs->append(package_entry);
1177        }
1178      }
1179    }
1180  }
1181
1182
1183  // Allocate objArray and fill with java.lang.String
1184  objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
1185                                           loaded_class_pkgs->length(), CHECK_NULL);
1186  objArrayHandle result(THREAD, r);
1187  for (int x = 0; x < loaded_class_pkgs->length(); x++) {
1188    PackageEntry* package_entry = loaded_class_pkgs->at(x);
1189    Handle str = java_lang_String::create_from_symbol(package_entry->name(), CHECK_NULL);
1190    result->obj_at_put(x, str());
1191  }
1192  return result();
1193}
1194
1195#if INCLUDE_CDS
1196s2 ClassLoader::module_to_classloader(const char* module_name) {
1197
1198  assert(DumpSharedSpaces, "dump time only");
1199  assert(_boot_modules_array != NULL, "_boot_modules_array is NULL");
1200  assert(_platform_modules_array != NULL, "_platform_modules_array is NULL");
1201
1202  int array_size = _boot_modules_array->length();
1203  for (int i = 0; i < array_size; i++) {
1204    if (strcmp(module_name, _boot_modules_array->at(i)) == 0) {
1205      return BOOT_LOADER;
1206    }
1207  }
1208
1209  array_size = _platform_modules_array->length();
1210  for (int i = 0; i < array_size; i++) {
1211    if (strcmp(module_name, _platform_modules_array->at(i)) == 0) {
1212      return PLATFORM_LOADER;
1213    }
1214  }
1215
1216  return APP_LOADER;
1217}
1218
1219s2 ClassLoader::classloader_type(Symbol* class_name, ClassPathEntry* e, int classpath_index, TRAPS) {
1220  assert(DumpSharedSpaces, "Only used for CDS dump time");
1221
1222  // obtain the classloader type based on the class name.
1223  // First obtain the package name based on the class name. Then obtain
1224  // the classloader type based on the package name from the jimage using
1225  // a jimage API. If the classloader type cannot be found from the
1226  // jimage, it is determined by the class path entry.
1227  jshort loader_type = ClassLoader::APP_LOADER;
1228  if (e->is_jrt()) {
1229    int length = 0;
1230    const jbyte* pkg_string = InstanceKlass::package_from_name(class_name, length);
1231    if (pkg_string != NULL) {
1232      ResourceMark rm;
1233      TempNewSymbol pkg_name = SymbolTable::new_symbol((const char*)pkg_string, length, THREAD);
1234      const char* pkg_name_C_string = (const char*)(pkg_name->as_C_string());
1235      ClassPathImageEntry* cpie = (ClassPathImageEntry*)e;
1236      JImageFile* jimage = cpie->jimage();
1237      char* module_name = (char*)(*JImagePackageToModule)(jimage, pkg_name_C_string);
1238      if (module_name != NULL) {
1239        loader_type = ClassLoader::module_to_classloader(module_name);
1240      }
1241    }
1242  } else if (ClassLoaderExt::is_boot_classpath(classpath_index)) {
1243    loader_type = ClassLoader::BOOT_LOADER;
1244  }
1245  return loader_type;
1246}
1247#endif
1248
1249// caller needs ResourceMark
1250const char* ClassLoader::file_name_for_class_name(const char* class_name,
1251                                                  int class_name_len) {
1252  assert(class_name != NULL, "invariant");
1253  assert((int)strlen(class_name) == class_name_len, "invariant");
1254
1255  static const char class_suffix[] = ".class";
1256
1257  char* const file_name = NEW_RESOURCE_ARRAY(char,
1258                                             class_name_len +
1259                                             sizeof(class_suffix)); // includes term NULL
1260
1261  strncpy(file_name, class_name, class_name_len);
1262  strncpy(&file_name[class_name_len], class_suffix, sizeof(class_suffix));
1263
1264  return file_name;
1265}
1266
1267instanceKlassHandle ClassLoader::load_class(Symbol* name, bool search_append_only, TRAPS) {
1268  assert(name != NULL, "invariant");
1269  assert(THREAD->is_Java_thread(), "must be a JavaThread");
1270
1271  ResourceMark rm(THREAD);
1272  HandleMark hm(THREAD);
1273
1274  const char* const class_name = name->as_C_string();
1275
1276  EventMark m("loading class %s", class_name);
1277  ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion);
1278
1279  const char* const file_name = file_name_for_class_name(class_name,
1280                                                         name->utf8_length());
1281  assert(file_name != NULL, "invariant");
1282
1283  ClassLoaderExt::Context context(class_name, file_name, THREAD);
1284
1285  // Lookup stream for parsing .class file
1286  ClassFileStream* stream = NULL;
1287  s2 classpath_index = 0;
1288  ClassPathEntry* e = NULL;
1289
1290  // If DumpSharedSpaces is true, boot loader visibility boundaries are set
1291  // to be _first_entry to the end (all path entries). No -Xpatch entries are
1292  // included since CDS and AppCDS are not supported if -Xpatch is specified.
1293  //
1294  // If search_append_only is true, boot loader visibility boundaries are
1295  // set to be _first_append_entry to the end. This includes:
1296  //   [-Xbootclasspath/a]; [jvmti appended entries]
1297  //
1298  // If both DumpSharedSpaces and search_append_only are false, boot loader
1299  // visibility boundaries are set to be _first_entry to the entry before
1300  // the _first_append_entry.  This would include:
1301  //   [-Xpatch:<module>=<file>(<pathsep><file>)*];  [exploded build | jimage]
1302  //
1303  // DumpSharedSpaces and search_append_only are mutually exclusive and cannot
1304  // be true at the same time.
1305  assert(!(DumpSharedSpaces && search_append_only), "DumpSharedSpaces and search_append_only are both true");
1306
1307  // Load Attempt #1: -Xpatch
1308  // Determine the class' defining module.  If it appears in the _xpatch_entries,
1309  // attempt to load the class from those locations specific to the module.
1310  // Note: The -Xpatch entries are never searched if the boot loader's
1311  //       visibility boundary is limited to only searching the append entries.
1312  if (_xpatch_entries != NULL && !search_append_only && !DumpSharedSpaces) {
1313    // Find the module in the boot loader's module entry table
1314    PackageEntry* pkg_entry = get_package_entry(class_name, ClassLoaderData::the_null_class_loader_data(), THREAD);
1315    ModuleEntry* mod_entry = (pkg_entry != NULL) ? pkg_entry->module() : NULL;
1316
1317    // If the module system has not defined java.base yet, then
1318    // classes loaded are assumed to be defined to java.base.
1319    // When java.base is eventually defined by the module system,
1320    // all packages of classes that have been previously loaded
1321    // are verified in ModuleEntryTable::verify_javabase_packages().
1322    if (!Universe::is_module_initialized() &&
1323        !ModuleEntryTable::javabase_defined() &&
1324        mod_entry == NULL) {
1325      mod_entry = ModuleEntryTable::javabase_module();
1326    }
1327
1328    // The module must be a named module
1329    if (mod_entry != NULL && mod_entry->is_named()) {
1330      int num_of_entries = _xpatch_entries->length();
1331      const Symbol* class_module_name = mod_entry->name();
1332
1333      // Loop through all the xpatch entries looking for module
1334      for (int i = 0; i < num_of_entries; i++) {
1335        ModuleClassPathList* module_cpl = _xpatch_entries->at(i);
1336        Symbol* module_cpl_name = module_cpl->module_name();
1337
1338        if (module_cpl_name->fast_compare(class_module_name) == 0) {
1339          // Class' module has been located, attempt to load
1340          // the class from the module's ClassPathEntry list.
1341          e = module_cpl->module_first_entry();
1342          while (e != NULL) {
1343            stream = e->open_stream(file_name, CHECK_NULL);
1344            // No context.check is required since both CDS
1345            // and AppCDS are turned off if -Xpatch is specified.
1346            if (NULL != stream) {
1347              break;
1348            }
1349            e = e->next();
1350          }
1351          // If the module was located in the xpatch entries, break out
1352          // even if the class was not located successfully from that module's
1353          // ClassPathEntry list. There will not be another valid entry for
1354          // that module in the _xpatch_entries array.
1355          break;
1356        }
1357      }
1358    }
1359  }
1360
1361  // Load Attempt #2: [exploded build | jimage]
1362  if (!search_append_only && (NULL == stream)) {
1363    e = _first_entry;
1364    while ((e != NULL) && (e != _first_append_entry)) {
1365      stream = e->open_stream(file_name, CHECK_NULL);
1366      if (!context.check(stream, classpath_index)) {
1367        return NULL;
1368      }
1369      if (NULL != stream) {
1370        break;
1371      }
1372      e = e->next();
1373      ++classpath_index;
1374    }
1375  }
1376
1377  // Load Attempt #3: [-Xbootclasspath/a]; [jvmti appended entries]
1378  if ((search_append_only || DumpSharedSpaces) && (NULL == stream)) {
1379    // For the boot loader append path search, must calculate
1380    // the starting classpath_index prior to attempting to
1381    // load the classfile.
1382    if (search_append_only) {
1383      ClassPathEntry *tmp_e = _first_entry;
1384      while ((tmp_e != NULL) && (tmp_e != _first_append_entry)) {
1385        tmp_e = tmp_e->next();
1386        ++classpath_index;
1387      }
1388    }
1389
1390    e = _first_append_entry;
1391    while (e != NULL) {
1392      stream = e->open_stream(file_name, CHECK_NULL);
1393      if (!context.check(stream, classpath_index)) {
1394        return NULL;
1395      }
1396      if (NULL != stream) {
1397        break;
1398      }
1399      e = e->next();
1400      ++classpath_index;
1401    }
1402  }
1403
1404  if (NULL == stream) {
1405    if (DumpSharedSpaces) {
1406      tty->print_cr("Preload Warning: Cannot find %s", class_name);
1407    }
1408    return NULL;
1409  }
1410
1411  stream->set_verify(context.should_verify(classpath_index));
1412
1413  ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
1414  Handle protection_domain;
1415
1416  instanceKlassHandle result = KlassFactory::create_from_stream(stream,
1417                                                                name,
1418                                                                loader_data,
1419                                                                protection_domain,
1420                                                                NULL, // host_klass
1421                                                                NULL, // cp_patches
1422                                                                NULL, // parsed_name
1423                                                                THREAD);
1424  if (HAS_PENDING_EXCEPTION) {
1425    if (DumpSharedSpaces) {
1426      tty->print_cr("Preload Error: Failed to load %s", class_name);
1427    }
1428    return NULL;
1429  }
1430
1431  return context.record_result(name, e, classpath_index, result, THREAD);
1432}
1433
1434// Initialize the class loader's access to methods in libzip.  Parse and
1435// process the boot classpath into a list ClassPathEntry objects.  Once
1436// this list has been created, it must not change order (see class PackageInfo)
1437// it can be appended to and is by jvmti and the kernel vm.
1438
1439void ClassLoader::initialize() {
1440  EXCEPTION_MARK;
1441
1442  if (UsePerfData) {
1443    // jvmstat performance counters
1444    NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");
1445    NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");
1446    NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");
1447    NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");
1448    NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");
1449    NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");
1450    NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");
1451    NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");
1452    NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");
1453    NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");
1454
1455    NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime");
1456    NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self");
1457    NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime");
1458    NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");
1459    NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");
1460    NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");
1461    NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");
1462    NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");
1463    NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");
1464    NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");
1465    NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");
1466    NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");
1467    NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");
1468
1469
1470    // The following performance counters are added for measuring the impact
1471    // of the bug fix of 6365597. They are mainly focused on finding out
1472    // the behavior of system & user-defined classloader lock, whether
1473    // ClassLoader.loadClass/findClass is being called synchronized or not.
1474    // Also two additional counters are created to see whether 'UnsyncloadClass'
1475    // flag is being set or not and how many times load_instance_class call
1476    // fails with linkageError etc.
1477    NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS,
1478                        "systemLoaderLockContentionRate");
1479    NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS,
1480                        "nonSystemLoaderLockContentionRate");
1481    NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS,
1482                        "jvmFindLoadedClassNoLockCalls");
1483    NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS,
1484                        "jvmDefineClassNoLockCalls");
1485
1486    NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS,
1487                        "jniDefineClassNoLockCalls");
1488
1489    NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS,
1490                        "unsafeDefineClassCalls");
1491
1492    NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet");
1493    NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS,
1494                        "loadInstanceClassFailRate");
1495
1496    // increment the isUnsyncloadClass counter if UnsyncloadClass is set.
1497    if (UnsyncloadClass) {
1498      _isUnsyncloadClass->inc();
1499    }
1500  }
1501
1502  // lookup zip library entry points
1503  load_zip_library();
1504  // lookup jimage library entry points
1505  load_jimage_library();
1506#if INCLUDE_CDS
1507  // initialize search path
1508  if (DumpSharedSpaces) {
1509    _shared_paths_misc_info = SharedClassUtil::allocate_shared_paths_misc_info();
1510  }
1511#endif
1512  setup_bootstrap_search_path();
1513}
1514
1515#if INCLUDE_CDS
1516void ClassLoader::initialize_shared_path() {
1517  if (DumpSharedSpaces) {
1518    ClassLoaderExt::setup_search_paths();
1519    _shared_paths_misc_info->write_jint(0); // see comments in SharedPathsMiscInfo::check()
1520  }
1521}
1522#endif
1523
1524jlong ClassLoader::classloader_time_ms() {
1525  return UsePerfData ?
1526    Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;
1527}
1528
1529jlong ClassLoader::class_init_count() {
1530  return UsePerfData ? _perf_classes_inited->get_value() : -1;
1531}
1532
1533jlong ClassLoader::class_init_time_ms() {
1534  return UsePerfData ?
1535    Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;
1536}
1537
1538jlong ClassLoader::class_verify_time_ms() {
1539  return UsePerfData ?
1540    Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;
1541}
1542
1543jlong ClassLoader::class_link_count() {
1544  return UsePerfData ? _perf_classes_linked->get_value() : -1;
1545}
1546
1547jlong ClassLoader::class_link_time_ms() {
1548  return UsePerfData ?
1549    Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;
1550}
1551
1552int ClassLoader::compute_Object_vtable() {
1553  // hardwired for JDK1.2 -- would need to duplicate class file parsing
1554  // code to determine actual value from file
1555  // Would be value '11' if finals were in vtable
1556  int JDK_1_2_Object_vtable_size = 5;
1557  return JDK_1_2_Object_vtable_size * vtableEntry::size();
1558}
1559
1560
1561void classLoader_init1() {
1562  ClassLoader::initialize();
1563}
1564
1565// Complete the ClassPathEntry setup for the boot loader
1566void classLoader_init2() {
1567  // Setup the list of module/path pairs for -Xpatch processing
1568  // This must be done after the SymbolTable is created in order
1569  // to use fast_compare on module names instead of a string compare.
1570  if (Arguments::get_xpatchprefix() != NULL) {
1571    ClassLoader::setup_xpatch_entries();
1572  }
1573
1574  // Determine if this is an exploded build
1575  ClassLoader::set_has_jimage();
1576}
1577
1578
1579bool ClassLoader::get_canonical_path(const char* orig, char* out, int len) {
1580  assert(orig != NULL && out != NULL && len > 0, "bad arguments");
1581  if (CanonicalizeEntry != NULL) {
1582    JavaThread* THREAD = JavaThread::current();
1583    JNIEnv* env = THREAD->jni_environment();
1584    ResourceMark rm(THREAD);
1585
1586    // os::native_path writes into orig_copy
1587    char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(orig)+1);
1588    strcpy(orig_copy, orig);
1589    if ((CanonicalizeEntry)(env, os::native_path(orig_copy), out, len) < 0) {
1590      return false;
1591    }
1592  } else {
1593    // On JDK 1.2.2 the Canonicalize does not exist, so just do nothing
1594    strncpy(out, orig, len);
1595    out[len - 1] = '\0';
1596  }
1597  return true;
1598}
1599
1600void ClassLoader::create_javabase() {
1601  Thread* THREAD = Thread::current();
1602
1603  // Create java.base's module entry for the boot
1604  // class loader prior to loading j.l.Ojbect.
1605  ClassLoaderData* null_cld = ClassLoaderData::the_null_class_loader_data();
1606
1607  // Get module entry table
1608  ModuleEntryTable* null_cld_modules = null_cld->modules();
1609  if (null_cld_modules == NULL) {
1610    vm_exit_during_initialization("No ModuleEntryTable for the boot class loader");
1611  }
1612
1613  {
1614    MutexLocker ml(Module_lock, THREAD);
1615    ModuleEntry* jb_module = null_cld_modules->locked_create_entry_or_null(Handle(NULL), vmSymbols::java_base(), NULL, NULL, null_cld);
1616    if (jb_module == NULL) {
1617      vm_exit_during_initialization("Unable to create ModuleEntry for java.base");
1618    }
1619    ModuleEntryTable::set_javabase_module(jb_module);
1620  }
1621}
1622
1623void ClassLoader::set_has_jimage() {
1624  // Determine if this is an exploded build. When looking for
1625  // the jimage file, only search the piece of the boot
1626  // loader's boot class path which contains [exploded build | jimage].
1627  // Do not search the boot loader's xpatch entries or append path.
1628  ClassPathEntry* e = _first_entry;
1629  ClassPathEntry* last_e = _first_append_entry;
1630  while ((e != NULL) && (e != last_e)) {
1631    JImageFile *jimage = e->jimage();
1632    if (jimage != NULL && e->is_jrt()) {
1633      _has_jimage = true;
1634#if INCLUDE_CDS
1635      ClassLoader::initialize_module_loader_map(jimage);
1636#endif
1637      return;
1638    }
1639    e = e->next();
1640  }
1641}
1642
1643#ifndef PRODUCT
1644
1645// CompileTheWorld
1646//
1647// Iterates over all class path entries and forces compilation of all methods
1648// in all classes found. Currently, only zip/jar archives are searched.
1649//
1650// The classes are loaded by the Java level bootstrap class loader, and the
1651// initializer is called. If DelayCompilationDuringStartup is true (default),
1652// the interpreter will run the initialization code. Note that forcing
1653// initialization in this way could potentially lead to initialization order
1654// problems, in which case we could just force the initialization bit to be set.
1655
1656
1657// We need to iterate over the contents of a zip/jar file, so we replicate the
1658// jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile,
1659// since jzfile already has a void* definition.
1660//
1661// Note that this is only used in debug mode.
1662//
1663// HotSpot integration note:
1664// Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build
1665
1666
1667// JDK 1.3 version
1668typedef struct real_jzentry {         /* Zip file entry */
1669    char *name;                 /* entry name */
1670    jint time;                  /* modification time */
1671    jint size;                  /* size of uncompressed data */
1672    jint csize;                 /* size of compressed data (zero if uncompressed) */
1673    jint crc;                   /* crc of uncompressed data */
1674    char *comment;              /* optional zip file comment */
1675    jbyte *extra;               /* optional extra data */
1676    jint pos;                   /* position of LOC header (if negative) or data */
1677} real_jzentry;
1678
1679typedef struct real_jzfile {  /* Zip file */
1680    char *name;                 /* zip file name */
1681    jint refs;                  /* number of active references */
1682    jint fd;                    /* open file descriptor */
1683    void *lock;                 /* read lock */
1684    char *comment;              /* zip file comment */
1685    char *msg;                  /* zip error message */
1686    void *entries;              /* array of hash cells */
1687    jint total;                 /* total number of entries */
1688    unsigned short *table;      /* Hash chain heads: indexes into entries */
1689    jint tablelen;              /* number of hash eads */
1690    real_jzfile *next;        /* next zip file in search list */
1691    jzentry *cache;             /* we cache the most recently freed jzentry */
1692    /* Information on metadata names in META-INF directory */
1693    char **metanames;           /* array of meta names (may have null names) */
1694    jint metacount;             /* number of slots in metanames array */
1695    /* If there are any per-entry comments, they are in the comments array */
1696    char **comments;
1697} real_jzfile;
1698
1699void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {
1700  // For now we only compile all methods in all classes in zip/jar files
1701  tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);
1702  tty->cr();
1703}
1704
1705void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {
1706  real_jzfile* zip = (real_jzfile*) _zip;
1707  tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
1708  tty->cr();
1709  // Iterate over all entries in zip file
1710  for (int n = 0; ; n++) {
1711    real_jzentry * ze = (real_jzentry *)((*GetNextEntry)(_zip, n));
1712    if (ze == NULL) break;
1713    ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
1714  }
1715  if (HAS_PENDING_EXCEPTION) {
1716    if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1717      CLEAR_PENDING_EXCEPTION;
1718      tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
1719      tty->print_cr("Increase class metadata storage if a limit was set");
1720    } else {
1721      tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
1722    }
1723  }
1724}
1725
1726void ClassLoader::compile_the_world() {
1727  EXCEPTION_MARK;
1728  HandleMark hm(THREAD);
1729  ResourceMark rm(THREAD);
1730
1731  // Find bootstrap loader
1732  Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
1733  // Iterate over all bootstrap class path entries
1734  ClassPathEntry* e = _first_entry;
1735  jlong start = os::javaTimeMillis();
1736  while (e != NULL) {
1737    // We stop at "modules" jimage, unless it is the first bootstrap path entry
1738    if (e->is_jrt() && e != _first_entry) break;
1739    e->compile_the_world(system_class_loader, CATCH);
1740    e = e->next();
1741  }
1742  jlong end = os::javaTimeMillis();
1743  tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)",
1744                _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));
1745  {
1746    // Print statistics as if before normal exit:
1747    extern void print_statistics();
1748    print_statistics();
1749  }
1750  vm_exit(0);
1751}
1752
1753int ClassLoader::_compile_the_world_class_counter = 0;
1754int ClassLoader::_compile_the_world_method_counter = 0;
1755static int _codecache_sweep_counter = 0;
1756
1757// Filter out all exceptions except OOMs
1758static void clear_pending_exception_if_not_oom(TRAPS) {
1759  if (HAS_PENDING_EXCEPTION &&
1760      !PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1761    CLEAR_PENDING_EXCEPTION;
1762  }
1763  // The CHECK at the caller will propagate the exception out
1764}
1765
1766/**
1767 * Returns if the given method should be compiled when doing compile-the-world.
1768 *
1769 * TODO:  This should be a private method in a CompileTheWorld class.
1770 */
1771static bool can_be_compiled(methodHandle m, int comp_level) {
1772  assert(CompileTheWorld, "must be");
1773
1774  // It's not valid to compile a native wrapper for MethodHandle methods
1775  // that take a MemberName appendix since the bytecode signature is not
1776  // correct.
1777  vmIntrinsics::ID iid = m->intrinsic_id();
1778  if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) {
1779    return false;
1780  }
1781
1782  return CompilationPolicy::can_be_compiled(m, comp_level);
1783}
1784
1785void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {
1786  if (string_ends_with(name, ".class")) {
1787    // We have a .class file
1788    int len = (int)strlen(name);
1789    char buffer[2048];
1790    strncpy(buffer, name, len - 6);
1791    buffer[len-6] = 0;
1792    // If the file has a period after removing .class, it's not really a
1793    // valid class file.  The class loader will check everything else.
1794    if (strchr(buffer, '.') == NULL) {
1795      _compile_the_world_class_counter++;
1796      if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;
1797
1798      // Construct name without extension
1799      TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
1800      // Use loader to load and initialize class
1801      Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);
1802      instanceKlassHandle k (THREAD, ik);
1803      if (k.not_null() && !HAS_PENDING_EXCEPTION) {
1804        k->initialize(THREAD);
1805      }
1806      bool exception_occurred = HAS_PENDING_EXCEPTION;
1807      clear_pending_exception_if_not_oom(CHECK);
1808      if (CompileTheWorldPreloadClasses && k.not_null()) {
1809        ConstantPool::preload_and_initialize_all_classes(k->constants(), THREAD);
1810        if (HAS_PENDING_EXCEPTION) {
1811          // If something went wrong in preloading we just ignore it
1812          clear_pending_exception_if_not_oom(CHECK);
1813          tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer);
1814        }
1815      }
1816
1817      if (_compile_the_world_class_counter >= CompileTheWorldStartAt) {
1818        if (k.is_null() || exception_occurred) {
1819          // If something went wrong (e.g. ExceptionInInitializerError) we skip this class
1820          tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer);
1821        } else {
1822          tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer);
1823          // Preload all classes to get around uncommon traps
1824          // Iterate over all methods in class
1825          int comp_level = CompilationPolicy::policy()->initial_compile_level();
1826          for (int n = 0; n < k->methods()->length(); n++) {
1827            methodHandle m (THREAD, k->methods()->at(n));
1828            if (can_be_compiled(m, comp_level)) {
1829              if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) {
1830                // Give sweeper a chance to keep up with CTW
1831                VM_ForceSafepoint op;
1832                VMThread::execute(&op);
1833                _codecache_sweep_counter = 0;
1834              }
1835              // Force compilation
1836              CompileBroker::compile_method(m, InvocationEntryBci, comp_level,
1837                                            methodHandle(), 0, CompileTask::Reason_CTW, THREAD);
1838              if (HAS_PENDING_EXCEPTION) {
1839                clear_pending_exception_if_not_oom(CHECK);
1840                tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1841              } else {
1842                _compile_the_world_method_counter++;
1843              }
1844              if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) {
1845                // Clobber the first compile and force second tier compilation
1846                CompiledMethod* nm = m->code();
1847                if (nm != NULL && !m->is_method_handle_intrinsic()) {
1848                  // Throw out the code so that the code cache doesn't fill up
1849                  nm->make_not_entrant();
1850                  m->clear_code();
1851                }
1852                CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization,
1853                                              methodHandle(), 0, CompileTask::Reason_CTW, THREAD);
1854                if (HAS_PENDING_EXCEPTION) {
1855                  clear_pending_exception_if_not_oom(CHECK);
1856                  tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1857                } else {
1858                  _compile_the_world_method_counter++;
1859                }
1860              }
1861            } else {
1862              tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1863            }
1864
1865            CompiledMethod* nm = m->code();
1866            if (nm != NULL && !m->is_method_handle_intrinsic()) {
1867              // Throw out the code so that the code cache doesn't fill up
1868              nm->make_not_entrant();
1869              m->clear_code();
1870            }
1871          }
1872        }
1873      }
1874    }
1875  }
1876}
1877
1878#endif //PRODUCT
1879
1880// Please keep following two functions at end of this file. With them placed at top or in middle of the file,
1881// they could get inlined by agressive compiler, an unknown trick, see bug 6966589.
1882void PerfClassTraceTime::initialize() {
1883  if (!UsePerfData) return;
1884
1885  if (_eventp != NULL) {
1886    // increment the event counter
1887    _eventp->inc();
1888  }
1889
1890  // stop the current active thread-local timer to measure inclusive time
1891  _prev_active_event = -1;
1892  for (int i=0; i < EVENT_TYPE_COUNT; i++) {
1893     if (_timers[i].is_active()) {
1894       assert(_prev_active_event == -1, "should have only one active timer");
1895       _prev_active_event = i;
1896       _timers[i].stop();
1897     }
1898  }
1899
1900  if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) {
1901    // start the inclusive timer if not recursively called
1902    _t.start();
1903  }
1904
1905  // start thread-local timer of the given event type
1906   if (!_timers[_event_type].is_active()) {
1907    _timers[_event_type].start();
1908  }
1909}
1910
1911PerfClassTraceTime::~PerfClassTraceTime() {
1912  if (!UsePerfData) return;
1913
1914  // stop the thread-local timer as the event completes
1915  // and resume the thread-local timer of the event next on the stack
1916  _timers[_event_type].stop();
1917  jlong selftime = _timers[_event_type].ticks();
1918
1919  if (_prev_active_event >= 0) {
1920    _timers[_prev_active_event].start();
1921  }
1922
1923  if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return;
1924
1925  // increment the counters only on the leaf call
1926  _t.stop();
1927  _timep->inc(_t.ticks());
1928  if (_selftimep != NULL) {
1929    _selftimep->inc(selftime);
1930  }
1931  // add all class loading related event selftime to the accumulated time counter
1932  ClassLoader::perf_accumulated_time()->inc(selftime);
1933
1934  // reset the timer
1935  _timers[_event_type].reset();
1936}
1937