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