Mon, 15 Jun 2020 14:08:11 +0300
8245167: Top package in method profiling shows null in JMC
Reviewed-by: neugens
Contributed-by: asemenov@azul.com
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/classLoaderExt.hpp"
30 #include "classfile/classLoaderData.inline.hpp"
31 #include "classfile/javaClasses.hpp"
32 #if INCLUDE_CDS
33 #include "classfile/sharedPathsMiscInfo.hpp"
34 #include "classfile/sharedClassUtil.hpp"
35 #endif
36 #include "classfile/systemDictionary.hpp"
37 #include "classfile/vmSymbols.hpp"
38 #include "compiler/compileBroker.hpp"
39 #include "gc_interface/collectedHeap.inline.hpp"
40 #include "interpreter/bytecodeStream.hpp"
41 #include "interpreter/oopMapCache.hpp"
42 #include "memory/allocation.inline.hpp"
43 #include "memory/filemap.hpp"
44 #include "memory/generation.hpp"
45 #include "memory/oopFactory.hpp"
46 #include "memory/universe.inline.hpp"
47 #include "oops/instanceKlass.hpp"
48 #include "oops/instanceRefKlass.hpp"
49 #include "oops/oop.inline.hpp"
50 #include "oops/symbol.hpp"
51 #include "prims/jvm_misc.hpp"
52 #include "runtime/arguments.hpp"
53 #include "runtime/compilationPolicy.hpp"
54 #include "runtime/fprofiler.hpp"
55 #include "runtime/handles.hpp"
56 #include "runtime/handles.inline.hpp"
57 #include "runtime/init.hpp"
58 #include "runtime/interfaceSupport.hpp"
59 #include "runtime/java.hpp"
60 #include "runtime/javaCalls.hpp"
61 #include "runtime/threadCritical.hpp"
62 #include "runtime/timer.hpp"
63 #include "services/management.hpp"
64 #include "services/threadService.hpp"
65 #include "utilities/events.hpp"
66 #include "utilities/hashtable.hpp"
67 #include "utilities/hashtable.inline.hpp"
68 #ifdef TARGET_OS_FAMILY_linux
69 # include "os_linux.inline.hpp"
70 #endif
71 #ifdef TARGET_OS_FAMILY_solaris
72 # include "os_solaris.inline.hpp"
73 #endif
74 #ifdef TARGET_OS_FAMILY_windows
75 # include "os_windows.inline.hpp"
76 #endif
77 #ifdef TARGET_OS_FAMILY_aix
78 # include "os_aix.inline.hpp"
79 #endif
80 #ifdef TARGET_OS_FAMILY_bsd
81 # include "os_bsd.inline.hpp"
82 #endif
85 // Entry points in zip.dll for loading zip/jar file entries
87 typedef void * * (JNICALL *ZipOpen_t)(const char *name, char **pmsg);
88 typedef void (JNICALL *ZipClose_t)(jzfile *zip);
89 typedef jzentry* (JNICALL *FindEntry_t)(jzfile *zip, const char *name, jint *sizeP, jint *nameLen);
90 typedef jboolean (JNICALL *ReadEntry_t)(jzfile *zip, jzentry *entry, unsigned char *buf, char *namebuf);
91 typedef jboolean (JNICALL *ReadMappedEntry_t)(jzfile *zip, jzentry *entry, unsigned char **buf, char *namebuf);
92 typedef jzentry* (JNICALL *GetNextEntry_t)(jzfile *zip, jint n);
93 typedef jint (JNICALL *Crc32_t)(jint crc, const jbyte *buf, jint len);
95 static ZipOpen_t ZipOpen = NULL;
96 static ZipClose_t ZipClose = NULL;
97 static FindEntry_t FindEntry = NULL;
98 static ReadEntry_t ReadEntry = NULL;
99 static ReadMappedEntry_t ReadMappedEntry = NULL;
100 static GetNextEntry_t GetNextEntry = NULL;
101 static canonicalize_fn_t CanonicalizeEntry = NULL;
102 static Crc32_t Crc32 = NULL;
104 // Globals
106 PerfCounter* ClassLoader::_perf_accumulated_time = NULL;
107 PerfCounter* ClassLoader::_perf_classes_inited = NULL;
108 PerfCounter* ClassLoader::_perf_class_init_time = NULL;
109 PerfCounter* ClassLoader::_perf_class_init_selftime = NULL;
110 PerfCounter* ClassLoader::_perf_classes_verified = NULL;
111 PerfCounter* ClassLoader::_perf_class_verify_time = NULL;
112 PerfCounter* ClassLoader::_perf_class_verify_selftime = NULL;
113 PerfCounter* ClassLoader::_perf_classes_linked = NULL;
114 PerfCounter* ClassLoader::_perf_class_link_time = NULL;
115 PerfCounter* ClassLoader::_perf_class_link_selftime = NULL;
116 PerfCounter* ClassLoader::_perf_class_parse_time = NULL;
117 PerfCounter* ClassLoader::_perf_class_parse_selftime = NULL;
118 PerfCounter* ClassLoader::_perf_sys_class_lookup_time = NULL;
119 PerfCounter* ClassLoader::_perf_shared_classload_time = NULL;
120 PerfCounter* ClassLoader::_perf_sys_classload_time = NULL;
121 PerfCounter* ClassLoader::_perf_app_classload_time = NULL;
122 PerfCounter* ClassLoader::_perf_app_classload_selftime = NULL;
123 PerfCounter* ClassLoader::_perf_app_classload_count = NULL;
124 PerfCounter* ClassLoader::_perf_define_appclasses = NULL;
125 PerfCounter* ClassLoader::_perf_define_appclass_time = NULL;
126 PerfCounter* ClassLoader::_perf_define_appclass_selftime = NULL;
127 PerfCounter* ClassLoader::_perf_app_classfile_bytes_read = NULL;
128 PerfCounter* ClassLoader::_perf_sys_classfile_bytes_read = NULL;
129 PerfCounter* ClassLoader::_sync_systemLoaderLockContentionRate = NULL;
130 PerfCounter* ClassLoader::_sync_nonSystemLoaderLockContentionRate = NULL;
131 PerfCounter* ClassLoader::_sync_JVMFindLoadedClassLockFreeCounter = NULL;
132 PerfCounter* ClassLoader::_sync_JVMDefineClassLockFreeCounter = NULL;
133 PerfCounter* ClassLoader::_sync_JNIDefineClassLockFreeCounter = NULL;
134 PerfCounter* ClassLoader::_unsafe_defineClassCallCounter = NULL;
135 PerfCounter* ClassLoader::_isUnsyncloadClass = NULL;
136 PerfCounter* ClassLoader::_load_instance_class_failCounter = NULL;
138 ClassPathEntry* ClassLoader::_first_entry = NULL;
139 ClassPathEntry* ClassLoader::_last_entry = NULL;
140 int ClassLoader::_num_entries = 0;
141 PackageHashtable* ClassLoader::_package_hash_table = NULL;
143 #if INCLUDE_CDS
144 SharedPathsMiscInfo* ClassLoader::_shared_paths_misc_info = NULL;
145 #endif
146 // helper routines
147 bool string_starts_with(const char* str, const char* str_to_find) {
148 size_t str_len = strlen(str);
149 size_t str_to_find_len = strlen(str_to_find);
150 if (str_to_find_len > str_len) {
151 return false;
152 }
153 return (strncmp(str, str_to_find, str_to_find_len) == 0);
154 }
156 bool string_ends_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_len - str_to_find_len), str_to_find, str_to_find_len) == 0);
163 }
165 // Used to obtain the package name from a fully qualified class name.
166 // It is the responsibility of the caller to establish a ResourceMark.
167 const char* ClassLoader::package_from_name(const char* const class_name, bool* bad_class_name) {
168 if (class_name == NULL) {
169 if (bad_class_name != NULL) {
170 *bad_class_name = true;
171 }
172 return NULL;
173 }
175 if (bad_class_name != NULL) {
176 *bad_class_name = false;
177 }
179 const char* const last_slash = strrchr(class_name, '/');
180 if (last_slash == NULL) {
181 // No package name
182 return NULL;
183 }
185 char* class_name_ptr = (char*) class_name;
186 // Skip over '['s
187 if (*class_name_ptr == '[') {
188 do {
189 class_name_ptr++;
190 } while (*class_name_ptr == '[');
192 // Fully qualified class names should not contain a 'L'.
193 // Set bad_class_name to true to indicate that the package name
194 // could not be obtained due to an error condition.
195 // In this situation, is_same_class_package returns false.
196 if (*class_name_ptr == 'L') {
197 if (bad_class_name != NULL) {
198 *bad_class_name = true;
199 }
200 return NULL;
201 }
202 }
204 int length = last_slash - class_name_ptr;
206 // A class name could have just the slash character in the name.
207 if (length <= 0) {
208 // No package name
209 if (bad_class_name != NULL) {
210 *bad_class_name = true;
211 }
212 return NULL;
213 }
215 // drop name after last slash (including slash)
216 // Ex., "java/lang/String.class" => "java/lang"
217 char* pkg_name = NEW_RESOURCE_ARRAY(char, length + 1);
218 strncpy(pkg_name, class_name_ptr, length);
219 *(pkg_name+length) = '\0';
221 return (const char *)pkg_name;
222 }
224 MetaIndex::MetaIndex(char** meta_package_names, int num_meta_package_names) {
225 if (num_meta_package_names == 0) {
226 _meta_package_names = NULL;
227 _num_meta_package_names = 0;
228 } else {
229 _meta_package_names = NEW_C_HEAP_ARRAY(char*, num_meta_package_names, mtClass);
230 _num_meta_package_names = num_meta_package_names;
231 memcpy(_meta_package_names, meta_package_names, num_meta_package_names * sizeof(char*));
232 }
233 }
236 MetaIndex::~MetaIndex() {
237 FREE_C_HEAP_ARRAY(char*, _meta_package_names, mtClass);
238 }
241 bool MetaIndex::may_contain(const char* class_name) {
242 if ( _num_meta_package_names == 0) {
243 return false;
244 }
245 size_t class_name_len = strlen(class_name);
246 for (int i = 0; i < _num_meta_package_names; i++) {
247 char* pkg = _meta_package_names[i];
248 size_t pkg_len = strlen(pkg);
249 size_t min_len = MIN2(class_name_len, pkg_len);
250 if (!strncmp(class_name, pkg, min_len)) {
251 return true;
252 }
253 }
254 return false;
255 }
258 ClassPathEntry::ClassPathEntry() {
259 set_next(NULL);
260 }
263 bool ClassPathEntry::is_lazy() {
264 return false;
265 }
267 ClassPathDirEntry::ClassPathDirEntry(const char* dir) : ClassPathEntry() {
268 char* copy = NEW_C_HEAP_ARRAY(char, strlen(dir)+1, mtClass);
269 strcpy(copy, dir);
270 _dir = copy;
271 }
274 ClassFileStream* ClassPathDirEntry::open_stream(const char* name, TRAPS) {
275 // construct full path name
276 char path[JVM_MAXPATHLEN];
277 if (jio_snprintf(path, sizeof(path), "%s%s%s", _dir, os::file_separator(), name) == -1) {
278 return NULL;
279 }
280 // check if file exists
281 struct stat st;
282 if (os::stat(path, &st) == 0) {
283 #if INCLUDE_CDS
284 if (DumpSharedSpaces) {
285 // We have already check in ClassLoader::check_shared_classpath() that the directory is empty, so
286 // we should never find a file underneath it -- unless user has added a new file while we are running
287 // the dump, in which case let's quit!
288 ShouldNotReachHere();
289 }
290 #endif
291 // found file, open it
292 int file_handle = os::open(path, 0, 0);
293 if (file_handle != -1) {
294 // read contents into resource array
295 u1* buffer = NEW_RESOURCE_ARRAY(u1, st.st_size);
296 size_t num_read = os::read(file_handle, (char*) buffer, st.st_size);
297 // close file
298 os::close(file_handle);
299 // construct ClassFileStream
300 if (num_read == (size_t)st.st_size) {
301 if (UsePerfData) {
302 ClassLoader::perf_sys_classfile_bytes_read()->inc(num_read);
303 }
304 return new ClassFileStream(buffer, st.st_size, _dir); // Resource allocated
305 }
306 }
307 }
308 return NULL;
309 }
312 ClassPathZipEntry::ClassPathZipEntry(jzfile* zip, const char* zip_name) : ClassPathEntry() {
313 _zip = zip;
314 char *copy = NEW_C_HEAP_ARRAY(char, strlen(zip_name)+1, mtClass);
315 strcpy(copy, zip_name);
316 _zip_name = copy;
317 }
319 ClassPathZipEntry::~ClassPathZipEntry() {
320 if (ZipClose != NULL) {
321 (*ZipClose)(_zip);
322 }
323 FREE_C_HEAP_ARRAY(char, _zip_name, mtClass);
324 }
326 u1* ClassPathZipEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {
327 // enable call to C land
328 JavaThread* thread = JavaThread::current();
329 ThreadToNativeFromVM ttn(thread);
330 // check whether zip archive contains name
331 jint name_len;
332 jzentry* entry = (*FindEntry)(_zip, name, filesize, &name_len);
333 if (entry == NULL) return NULL;
334 u1* buffer;
335 char name_buf[128];
336 char* filename;
337 if (name_len < 128) {
338 filename = name_buf;
339 } else {
340 filename = NEW_RESOURCE_ARRAY(char, name_len + 1);
341 }
343 // file found, get pointer to the entry in mmapped jar file.
344 if (ReadMappedEntry == NULL ||
345 !(*ReadMappedEntry)(_zip, entry, &buffer, filename)) {
346 // mmapped access not available, perhaps due to compression,
347 // read contents into resource array
348 int size = (*filesize) + ((nul_terminate) ? 1 : 0);
349 buffer = NEW_RESOURCE_ARRAY(u1, size);
350 if (!(*ReadEntry)(_zip, entry, buffer, filename)) return NULL;
351 }
353 // return result
354 if (nul_terminate) {
355 buffer[*filesize] = 0;
356 }
357 return buffer;
358 }
360 ClassFileStream* ClassPathZipEntry::open_stream(const char* name, TRAPS) {
361 jint filesize;
362 u1* buffer = open_entry(name, &filesize, false, CHECK_NULL);
363 if (buffer == NULL) {
364 return NULL;
365 }
366 if (UsePerfData) {
367 ClassLoader::perf_sys_classfile_bytes_read()->inc(filesize);
368 }
369 return new ClassFileStream(buffer, filesize, _zip_name); // Resource allocated
370 }
372 // invoke function for each entry in the zip file
373 void ClassPathZipEntry::contents_do(void f(const char* name, void* context), void* context) {
374 JavaThread* thread = JavaThread::current();
375 HandleMark handle_mark(thread);
376 ThreadToNativeFromVM ttn(thread);
377 for (int n = 0; ; n++) {
378 jzentry * ze = ((*GetNextEntry)(_zip, n));
379 if (ze == NULL) break;
380 (*f)(ze->name, context);
381 }
382 }
384 LazyClassPathEntry::LazyClassPathEntry(const char* path, const struct stat* st, bool throw_exception) : ClassPathEntry() {
385 _path = strdup(path);
386 _st = *st;
387 _meta_index = NULL;
388 _resolved_entry = NULL;
389 _has_error = false;
390 _throw_exception = throw_exception;
391 }
393 bool LazyClassPathEntry::is_jar_file() {
394 return ((_st.st_mode & S_IFREG) == S_IFREG);
395 }
397 ClassPathEntry* LazyClassPathEntry::resolve_entry(TRAPS) {
398 if (_resolved_entry != NULL) {
399 return (ClassPathEntry*) _resolved_entry;
400 }
401 ClassPathEntry* new_entry = NULL;
402 new_entry = ClassLoader::create_class_path_entry(_path, &_st, false, _throw_exception, CHECK_NULL);
403 if (!_throw_exception && new_entry == NULL) {
404 assert(!HAS_PENDING_EXCEPTION, "must be");
405 return NULL;
406 }
407 {
408 ThreadCritical tc;
409 if (_resolved_entry == NULL) {
410 _resolved_entry = new_entry;
411 return new_entry;
412 }
413 }
414 assert(_resolved_entry != NULL, "bug in MT-safe resolution logic");
415 delete new_entry;
416 return (ClassPathEntry*) _resolved_entry;
417 }
419 ClassFileStream* LazyClassPathEntry::open_stream(const char* name, TRAPS) {
420 if (_meta_index != NULL &&
421 !_meta_index->may_contain(name)) {
422 return NULL;
423 }
424 if (_has_error) {
425 return NULL;
426 }
427 ClassPathEntry* cpe = resolve_entry(THREAD);
428 if (cpe == NULL) {
429 _has_error = true;
430 return NULL;
431 } else {
432 return cpe->open_stream(name, THREAD);
433 }
434 }
436 bool LazyClassPathEntry::is_lazy() {
437 return true;
438 }
440 u1* LazyClassPathEntry::open_entry(const char* name, jint* filesize, bool nul_terminate, TRAPS) {
441 if (_has_error) {
442 return NULL;
443 }
444 ClassPathEntry* cpe = resolve_entry(THREAD);
445 if (cpe == NULL) {
446 _has_error = true;
447 return NULL;
448 } else if (cpe->is_jar_file()) {
449 return ((ClassPathZipEntry*)cpe)->open_entry(name, filesize, nul_terminate,THREAD);
450 } else {
451 ShouldNotReachHere();
452 *filesize = 0;
453 return NULL;
454 }
455 }
457 static void print_meta_index(LazyClassPathEntry* entry,
458 GrowableArray<char*>& meta_packages) {
459 tty->print("[Meta index for %s=", entry->name());
460 for (int i = 0; i < meta_packages.length(); i++) {
461 if (i > 0) tty->print(" ");
462 tty->print("%s", meta_packages.at(i));
463 }
464 tty->print_cr("]");
465 }
467 #if INCLUDE_CDS
468 void ClassLoader::exit_with_path_failure(const char* error, const char* message) {
469 assert(DumpSharedSpaces, "only called at dump time");
470 tty->print_cr("Hint: enable -XX:+TraceClassPaths to diagnose the failure");
471 vm_exit_during_initialization(error, message);
472 }
473 #endif
475 void ClassLoader::trace_class_path(outputStream* out, const char* msg, const char* name) {
476 if (!TraceClassPaths) {
477 return;
478 }
480 if (msg) {
481 out->print("%s", msg);
482 }
483 if (name) {
484 if (strlen(name) < 256) {
485 out->print("%s", name);
486 } else {
487 // For very long paths, we need to print each character separately,
488 // as print_cr() has a length limit
489 while (name[0] != '\0') {
490 out->print("%c", name[0]);
491 name++;
492 }
493 }
494 }
495 if (msg && msg[0] == '[') {
496 out->print_cr("]");
497 } else {
498 out->cr();
499 }
500 }
502 void ClassLoader::setup_bootstrap_meta_index() {
503 // Set up meta index which allows us to open boot jars lazily if
504 // class data sharing is enabled
505 const char* meta_index_path = Arguments::get_meta_index_path();
506 const char* meta_index_dir = Arguments::get_meta_index_dir();
507 setup_meta_index(meta_index_path, meta_index_dir, 0);
508 }
510 void ClassLoader::setup_meta_index(const char* meta_index_path, const char* meta_index_dir, int start_index) {
511 const char* known_version = "% VERSION 2";
512 FILE* file = fopen(meta_index_path, "r");
513 int line_no = 0;
514 #if INCLUDE_CDS
515 if (DumpSharedSpaces) {
516 if (file != NULL) {
517 _shared_paths_misc_info->add_required_file(meta_index_path);
518 } else {
519 _shared_paths_misc_info->add_nonexist_path(meta_index_path);
520 }
521 }
522 #endif
523 if (file != NULL) {
524 ResourceMark rm;
525 LazyClassPathEntry* cur_entry = NULL;
526 GrowableArray<char*> boot_class_path_packages(10);
527 char package_name[256];
528 bool skipCurrentJar = false;
529 while (fgets(package_name, sizeof(package_name), file) != NULL) {
530 ++line_no;
531 // Remove trailing newline
532 package_name[strlen(package_name) - 1] = '\0';
533 switch(package_name[0]) {
534 case '%':
535 {
536 if ((line_no == 1) && (strcmp(package_name, known_version) != 0)) {
537 if (TraceClassLoading && Verbose) {
538 tty->print("[Unsupported meta index version]");
539 }
540 fclose(file);
541 return;
542 }
543 }
545 // These directives indicate jar files which contain only
546 // classes, only non-classfile resources, or a combination of
547 // the two. See src/share/classes/sun/misc/MetaIndex.java and
548 // make/tools/MetaIndex/BuildMetaIndex.java in the J2SE
549 // workspace.
550 case '#':
551 case '!':
552 case '@':
553 {
554 // Hand off current packages to current lazy entry (if any)
555 if ((cur_entry != NULL) &&
556 (boot_class_path_packages.length() > 0)) {
557 if ((TraceClassLoading || TraceClassPaths) && Verbose) {
558 print_meta_index(cur_entry, boot_class_path_packages);
559 }
560 MetaIndex* index = new MetaIndex(boot_class_path_packages.adr_at(0),
561 boot_class_path_packages.length());
562 cur_entry->set_meta_index(index);
563 }
564 cur_entry = NULL;
565 boot_class_path_packages.clear();
567 // Find lazy entry corresponding to this jar file
568 int count = 0;
569 for (ClassPathEntry* entry = _first_entry; entry != NULL; entry = entry->next(), count++) {
570 if (count >= start_index &&
571 entry->is_lazy() &&
572 string_starts_with(entry->name(), meta_index_dir) &&
573 string_ends_with(entry->name(), &package_name[2])) {
574 cur_entry = (LazyClassPathEntry*) entry;
575 break;
576 }
577 }
579 // If the first character is '@', it indicates the following jar
580 // file is a resource only jar file in which case, we should skip
581 // reading the subsequent entries since the resource loading is
582 // totally handled by J2SE side.
583 if (package_name[0] == '@') {
584 if (cur_entry != NULL) {
585 cur_entry->set_meta_index(new MetaIndex(NULL, 0));
586 }
587 cur_entry = NULL;
588 skipCurrentJar = true;
589 } else {
590 skipCurrentJar = false;
591 }
593 break;
594 }
596 default:
597 {
598 if (!skipCurrentJar && cur_entry != NULL) {
599 char* new_name = strdup(package_name);
600 boot_class_path_packages.append(new_name);
601 }
602 }
603 }
604 }
605 // Hand off current packages to current lazy entry (if any)
606 if ((cur_entry != NULL) &&
607 (boot_class_path_packages.length() > 0)) {
608 if ((TraceClassLoading || TraceClassPaths) && Verbose) {
609 print_meta_index(cur_entry, boot_class_path_packages);
610 }
611 MetaIndex* index = new MetaIndex(boot_class_path_packages.adr_at(0),
612 boot_class_path_packages.length());
613 cur_entry->set_meta_index(index);
614 }
615 fclose(file);
616 }
617 }
619 #if INCLUDE_CDS
620 void ClassLoader::check_shared_classpath(const char *path) {
621 if (strcmp(path, "") == 0) {
622 exit_with_path_failure("Cannot have empty path in archived classpaths", NULL);
623 }
625 struct stat st;
626 if (os::stat(path, &st) == 0) {
627 if ((st.st_mode & S_IFREG) != S_IFREG) { // is directory
628 if (!os::dir_is_empty(path)) {
629 tty->print_cr("Error: non-empty directory '%s'", path);
630 exit_with_path_failure("CDS allows only empty directories in archived classpaths", NULL);
631 }
632 }
633 }
634 }
635 #endif
637 void ClassLoader::setup_bootstrap_search_path() {
638 assert(_first_entry == NULL, "should not setup bootstrap class search path twice");
639 const char* sys_class_path = Arguments::get_sysclasspath();
640 if (PrintSharedArchiveAndExit) {
641 // Don't print sys_class_path - this is the bootcp of this current VM process, not necessarily
642 // the same as the bootcp of the shared archive.
643 } else {
644 trace_class_path(tty, "[Bootstrap loader class path=", sys_class_path);
645 }
646 #if INCLUDE_CDS
647 if (DumpSharedSpaces) {
648 _shared_paths_misc_info->add_boot_classpath(sys_class_path);
649 }
650 #endif
651 setup_search_path(sys_class_path);
652 }
654 #if INCLUDE_CDS
655 int ClassLoader::get_shared_paths_misc_info_size() {
656 return _shared_paths_misc_info->get_used_bytes();
657 }
659 void* ClassLoader::get_shared_paths_misc_info() {
660 return _shared_paths_misc_info->buffer();
661 }
663 bool ClassLoader::check_shared_paths_misc_info(void *buf, int size) {
664 SharedPathsMiscInfo* checker = SharedClassUtil::allocate_shared_paths_misc_info((char*)buf, size);
665 bool result = checker->check();
666 delete checker;
667 return result;
668 }
669 #endif
671 void ClassLoader::setup_search_path(const char *class_path, bool canonicalize) {
672 int offset = 0;
673 int len = (int)strlen(class_path);
674 int end = 0;
676 // Iterate over class path entries
677 for (int start = 0; start < len; start = end) {
678 while (class_path[end] && class_path[end] != os::path_separator()[0]) {
679 end++;
680 }
681 EXCEPTION_MARK;
682 ResourceMark rm(THREAD);
683 char* path = NEW_RESOURCE_ARRAY(char, end - start + 1);
684 strncpy(path, &class_path[start], end - start);
685 path[end - start] = '\0';
686 if (canonicalize) {
687 char* canonical_path = NEW_RESOURCE_ARRAY(char, JVM_MAXPATHLEN + 1);
688 if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
689 path = canonical_path;
690 }
691 }
692 update_class_path_entry_list(path, /*check_for_duplicates=*/canonicalize);
693 #if INCLUDE_CDS
694 if (DumpSharedSpaces) {
695 check_shared_classpath(path);
696 }
697 #endif
698 while (class_path[end] == os::path_separator()[0]) {
699 end++;
700 }
701 }
702 }
704 ClassPathEntry* ClassLoader::create_class_path_entry(const char *path, const struct stat* st,
705 bool lazy, bool throw_exception, TRAPS) {
706 JavaThread* thread = JavaThread::current();
707 if (lazy) {
708 return new LazyClassPathEntry(path, st, throw_exception);
709 }
710 ClassPathEntry* new_entry = NULL;
711 if ((st->st_mode & S_IFREG) == S_IFREG) {
712 // Regular file, should be a zip file
713 // Canonicalized filename
714 char canonical_path[JVM_MAXPATHLEN];
715 if (!get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
716 // This matches the classic VM
717 if (throw_exception) {
718 THROW_MSG_(vmSymbols::java_io_IOException(), "Bad pathname", NULL);
719 } else {
720 return NULL;
721 }
722 }
723 char* error_msg = NULL;
724 jzfile* zip;
725 {
726 // enable call to C land
727 ThreadToNativeFromVM ttn(thread);
728 HandleMark hm(thread);
729 zip = (*ZipOpen)(canonical_path, &error_msg);
730 }
731 if (zip != NULL && error_msg == NULL) {
732 new_entry = new ClassPathZipEntry(zip, path);
733 if (TraceClassLoading || TraceClassPaths) {
734 tty->print_cr("[Opened %s]", path);
735 }
736 } else {
737 ResourceMark rm(thread);
738 char *msg;
739 if (error_msg == NULL) {
740 msg = NEW_RESOURCE_ARRAY(char, strlen(path) + 128); ;
741 jio_snprintf(msg, strlen(path) + 127, "error in opening JAR file %s", path);
742 } else {
743 int len = (int)(strlen(path) + strlen(error_msg) + 128);
744 msg = NEW_RESOURCE_ARRAY(char, len); ;
745 jio_snprintf(msg, len - 1, "error in opening JAR file <%s> %s", error_msg, path);
746 }
747 if (throw_exception) {
748 THROW_MSG_(vmSymbols::java_lang_ClassNotFoundException(), msg, NULL);
749 } else {
750 return NULL;
751 }
752 }
753 } else {
754 // Directory
755 new_entry = new ClassPathDirEntry(path);
756 if (TraceClassLoading || TraceClassPaths) {
757 tty->print_cr("[Path %s]", path);
758 }
759 }
760 return new_entry;
761 }
764 // Create a class path zip entry for a given path (return NULL if not found
765 // or zip/JAR file cannot be opened)
766 ClassPathZipEntry* ClassLoader::create_class_path_zip_entry(const char *path) {
767 // check for a regular file
768 struct stat st;
769 if (os::stat(path, &st) == 0) {
770 if ((st.st_mode & S_IFREG) == S_IFREG) {
771 char canonical_path[JVM_MAXPATHLEN];
772 if (get_canonical_path(path, canonical_path, JVM_MAXPATHLEN)) {
773 char* error_msg = NULL;
774 jzfile* zip;
775 {
776 // enable call to C land
777 JavaThread* thread = JavaThread::current();
778 ThreadToNativeFromVM ttn(thread);
779 HandleMark hm(thread);
780 zip = (*ZipOpen)(canonical_path, &error_msg);
781 }
782 if (zip != NULL && error_msg == NULL) {
783 // create using canonical path
784 return new ClassPathZipEntry(zip, canonical_path);
785 }
786 }
787 }
788 }
789 return NULL;
790 }
792 // returns true if entry already on class path
793 bool ClassLoader::contains_entry(ClassPathEntry *entry) {
794 ClassPathEntry* e = _first_entry;
795 while (e != NULL) {
796 // assume zip entries have been canonicalized
797 if (strcmp(entry->name(), e->name()) == 0) {
798 return true;
799 }
800 e = e->next();
801 }
802 return false;
803 }
805 void ClassLoader::add_to_list(ClassPathEntry *new_entry) {
806 if (new_entry != NULL) {
807 if (_last_entry == NULL) {
808 _first_entry = _last_entry = new_entry;
809 } else {
810 _last_entry->set_next(new_entry);
811 _last_entry = new_entry;
812 }
813 }
814 _num_entries ++;
815 }
817 // Returns true IFF the file/dir exists and the entry was successfully created.
818 bool ClassLoader::update_class_path_entry_list(const char *path,
819 bool check_for_duplicates,
820 bool throw_exception) {
821 struct stat st;
822 if (os::stat(path, &st) == 0) {
823 // File or directory found
824 ClassPathEntry* new_entry = NULL;
825 Thread* THREAD = Thread::current();
826 new_entry = create_class_path_entry(path, &st, LazyBootClassLoader, throw_exception, CHECK_(false));
827 if (new_entry == NULL) {
828 return false;
829 }
830 // The kernel VM adds dynamically to the end of the classloader path and
831 // doesn't reorder the bootclasspath which would break java.lang.Package
832 // (see PackageInfo).
833 // Add new entry to linked list
834 if (!check_for_duplicates || !contains_entry(new_entry)) {
835 ClassLoaderExt::add_class_path_entry(path, check_for_duplicates, new_entry);
836 }
837 return true;
838 } else {
839 #if INCLUDE_CDS
840 if (DumpSharedSpaces) {
841 _shared_paths_misc_info->add_nonexist_path(path);
842 }
843 #endif
844 return false;
845 }
846 }
848 void ClassLoader::print_bootclasspath() {
849 ClassPathEntry* e = _first_entry;
850 tty->print("[bootclasspath= ");
851 while (e != NULL) {
852 tty->print("%s ;", e->name());
853 e = e->next();
854 }
855 tty->print_cr("]");
856 }
858 void ClassLoader::load_zip_library() {
859 assert(ZipOpen == NULL, "should not load zip library twice");
860 // First make sure native library is loaded
861 os::native_java_library();
862 // Load zip library
863 char path[JVM_MAXPATHLEN];
864 char ebuf[1024];
865 void* handle = NULL;
866 if (os::dll_build_name(path, sizeof(path), Arguments::get_dll_dir(), "zip")) {
867 handle = os::dll_load(path, ebuf, sizeof ebuf);
868 }
869 if (handle == NULL) {
870 vm_exit_during_initialization("Unable to load ZIP library", path);
871 }
872 // Lookup zip entry points
873 ZipOpen = CAST_TO_FN_PTR(ZipOpen_t, os::dll_lookup(handle, "ZIP_Open"));
874 ZipClose = CAST_TO_FN_PTR(ZipClose_t, os::dll_lookup(handle, "ZIP_Close"));
875 FindEntry = CAST_TO_FN_PTR(FindEntry_t, os::dll_lookup(handle, "ZIP_FindEntry"));
876 ReadEntry = CAST_TO_FN_PTR(ReadEntry_t, os::dll_lookup(handle, "ZIP_ReadEntry"));
877 ReadMappedEntry = CAST_TO_FN_PTR(ReadMappedEntry_t, os::dll_lookup(handle, "ZIP_ReadMappedEntry"));
878 GetNextEntry = CAST_TO_FN_PTR(GetNextEntry_t, os::dll_lookup(handle, "ZIP_GetNextEntry"));
879 Crc32 = CAST_TO_FN_PTR(Crc32_t, os::dll_lookup(handle, "ZIP_CRC32"));
881 // ZIP_Close is not exported on Windows in JDK5.0 so don't abort if ZIP_Close is NULL
882 if (ZipOpen == NULL || FindEntry == NULL || ReadEntry == NULL ||
883 GetNextEntry == NULL || Crc32 == NULL) {
884 vm_exit_during_initialization("Corrupted ZIP library", path);
885 }
887 // Lookup canonicalize entry in libjava.dll
888 void *javalib_handle = os::native_java_library();
889 CanonicalizeEntry = CAST_TO_FN_PTR(canonicalize_fn_t, os::dll_lookup(javalib_handle, "Canonicalize"));
890 // This lookup only works on 1.3. Do not check for non-null here
891 }
893 int ClassLoader::crc32(int crc, const char* buf, int len) {
894 assert(Crc32 != NULL, "ZIP_CRC32 is not found");
895 return (*Crc32)(crc, (const jbyte*)buf, len);
896 }
898 // PackageInfo data exists in order to support the java.lang.Package
899 // class. A Package object provides information about a java package
900 // (version, vendor, etc.) which originates in the manifest of the jar
901 // file supplying the package. For application classes, the ClassLoader
902 // object takes care of this.
904 // For system (boot) classes, the Java code in the Package class needs
905 // to be able to identify which source jar file contained the boot
906 // class, so that it can extract the manifest from it. This table
907 // identifies java packages with jar files in the boot classpath.
909 // Because the boot classpath cannot change, the classpath index is
910 // sufficient to identify the source jar file or directory. (Since
911 // directories have no manifests, the directory name is not required,
912 // but is available.)
914 // When using sharing -- the pathnames of entries in the boot classpath
915 // may not be the same at runtime as they were when the archive was
916 // created (NFS, Samba, etc.). The actual files and directories named
917 // in the classpath must be the same files, in the same order, even
918 // though the exact name is not the same.
920 class PackageInfo: public BasicHashtableEntry<mtClass> {
921 public:
922 const char* _pkgname; // Package name
923 int _classpath_index; // Index of directory or JAR file loaded from
925 PackageInfo* next() {
926 return (PackageInfo*)BasicHashtableEntry<mtClass>::next();
927 }
929 const char* pkgname() { return _pkgname; }
930 void set_pkgname(char* pkgname) { _pkgname = pkgname; }
932 const char* filename() {
933 return ClassLoader::classpath_entry(_classpath_index)->name();
934 }
936 void set_index(int index) {
937 _classpath_index = index;
938 }
939 };
942 class PackageHashtable : public BasicHashtable<mtClass> {
943 private:
944 inline unsigned int compute_hash(const char *s, int n) {
945 unsigned int val = 0;
946 while (--n >= 0) {
947 val = *s++ + 31 * val;
948 }
949 return val;
950 }
952 PackageInfo* bucket(int index) {
953 return (PackageInfo*)BasicHashtable<mtClass>::bucket(index);
954 }
956 PackageInfo* get_entry(int index, unsigned int hash,
957 const char* pkgname, size_t n) {
958 for (PackageInfo* pp = bucket(index); pp != NULL; pp = pp->next()) {
959 if (pp->hash() == hash &&
960 strncmp(pkgname, pp->pkgname(), n) == 0 &&
961 pp->pkgname()[n] == '\0') {
962 return pp;
963 }
964 }
965 return NULL;
966 }
968 public:
969 PackageHashtable(int table_size)
970 : BasicHashtable<mtClass>(table_size, sizeof(PackageInfo)) {}
972 PackageHashtable(int table_size, HashtableBucket<mtClass>* t, int number_of_entries)
973 : BasicHashtable<mtClass>(table_size, sizeof(PackageInfo), t, number_of_entries) {}
975 PackageInfo* get_entry(const char* pkgname, int n) {
976 unsigned int hash = compute_hash(pkgname, n);
977 return get_entry(hash_to_index(hash), hash, pkgname, n);
978 }
980 PackageInfo* new_entry(char* pkgname, int n) {
981 unsigned int hash = compute_hash(pkgname, n);
982 PackageInfo* pp;
983 pp = (PackageInfo*)BasicHashtable<mtClass>::new_entry(hash);
984 pp->set_pkgname(pkgname);
985 return pp;
986 }
988 void add_entry(PackageInfo* pp) {
989 int index = hash_to_index(pp->hash());
990 BasicHashtable<mtClass>::add_entry(index, pp);
991 }
993 void copy_pkgnames(const char** packages) {
994 int n = 0;
995 for (int i = 0; i < table_size(); ++i) {
996 for (PackageInfo* pp = bucket(i); pp != NULL; pp = pp->next()) {
997 packages[n++] = pp->pkgname();
998 }
999 }
1000 assert(n == number_of_entries(), "just checking");
1001 }
1003 CDS_ONLY(void copy_table(char** top, char* end, PackageHashtable* table);)
1004 };
1006 #if INCLUDE_CDS
1007 void PackageHashtable::copy_table(char** top, char* end,
1008 PackageHashtable* table) {
1009 // Copy (relocate) the table to the shared space.
1010 BasicHashtable<mtClass>::copy_table(top, end);
1012 // Calculate the space needed for the package name strings.
1013 int i;
1014 intptr_t* tableSize = (intptr_t*)(*top);
1015 *top += sizeof(intptr_t); // For table size
1016 char* tableStart = *top;
1018 for (i = 0; i < table_size(); ++i) {
1019 for (PackageInfo* pp = table->bucket(i);
1020 pp != NULL;
1021 pp = pp->next()) {
1022 int n1 = (int)(strlen(pp->pkgname()) + 1);
1023 if (*top + n1 >= end) {
1024 report_out_of_shared_space(SharedMiscData);
1025 }
1026 pp->set_pkgname((char*)memcpy(*top, pp->pkgname(), n1));
1027 *top += n1;
1028 }
1029 }
1030 *top = (char*)align_size_up((intptr_t)*top, sizeof(HeapWord));
1031 if (*top >= end) {
1032 report_out_of_shared_space(SharedMiscData);
1033 }
1035 // Write table size
1036 intptr_t len = *top - (char*)tableStart;
1037 *tableSize = len;
1038 }
1041 void ClassLoader::copy_package_info_buckets(char** top, char* end) {
1042 _package_hash_table->copy_buckets(top, end);
1043 }
1045 void ClassLoader::copy_package_info_table(char** top, char* end) {
1046 _package_hash_table->copy_table(top, end, _package_hash_table);
1047 }
1048 #endif
1050 PackageInfo* ClassLoader::lookup_package(const char *pkgname) {
1051 const char *cp = strrchr(pkgname, '/');
1052 if (cp != NULL) {
1053 // Package prefix found
1054 int n = cp - pkgname + 1;
1055 return _package_hash_table->get_entry(pkgname, n);
1056 }
1057 return NULL;
1058 }
1061 bool ClassLoader::add_package(const char *pkgname, int classpath_index, TRAPS) {
1062 assert(pkgname != NULL, "just checking");
1063 // Bootstrap loader no longer holds system loader lock obj serializing
1064 // load_instance_class and thereby add_package
1065 {
1066 MutexLocker ml(PackageTable_lock, THREAD);
1067 // First check for previously loaded entry
1068 PackageInfo* pp = lookup_package(pkgname);
1069 if (pp != NULL) {
1070 // Existing entry found, check source of package
1071 pp->set_index(classpath_index);
1072 return true;
1073 }
1075 const char *cp = strrchr(pkgname, '/');
1076 if (cp != NULL) {
1077 // Package prefix found
1078 int n = cp - pkgname + 1;
1080 char* new_pkgname = NEW_C_HEAP_ARRAY(char, n + 1, mtClass);
1081 if (new_pkgname == NULL) {
1082 return false;
1083 }
1085 memcpy(new_pkgname, pkgname, n);
1086 new_pkgname[n] = '\0';
1087 pp = _package_hash_table->new_entry(new_pkgname, n);
1088 pp->set_index(classpath_index);
1090 // Insert into hash table
1091 _package_hash_table->add_entry(pp);
1092 }
1093 return true;
1094 }
1095 }
1098 oop ClassLoader::get_system_package(const char* name, TRAPS) {
1099 PackageInfo* pp;
1100 {
1101 MutexLocker ml(PackageTable_lock, THREAD);
1102 pp = lookup_package(name);
1103 }
1104 if (pp == NULL) {
1105 return NULL;
1106 } else {
1107 Handle p = java_lang_String::create_from_str(pp->filename(), THREAD);
1108 return p();
1109 }
1110 }
1113 objArrayOop ClassLoader::get_system_packages(TRAPS) {
1114 ResourceMark rm(THREAD);
1115 int nof_entries;
1116 const char** packages;
1117 {
1118 MutexLocker ml(PackageTable_lock, THREAD);
1119 // Allocate resource char* array containing package names
1120 nof_entries = _package_hash_table->number_of_entries();
1121 if ((packages = NEW_RESOURCE_ARRAY(const char*, nof_entries)) == NULL) {
1122 return NULL;
1123 }
1124 _package_hash_table->copy_pkgnames(packages);
1125 }
1126 // Allocate objArray and fill with java.lang.String
1127 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
1128 nof_entries, CHECK_0);
1129 objArrayHandle result(THREAD, r);
1130 for (int i = 0; i < nof_entries; i++) {
1131 Handle str = java_lang_String::create_from_str(packages[i], CHECK_0);
1132 result->obj_at_put(i, str());
1133 }
1135 return result();
1136 }
1139 instanceKlassHandle ClassLoader::load_classfile(Symbol* h_name, TRAPS) {
1140 ResourceMark rm(THREAD);
1141 const char* class_name = h_name->as_C_string();
1142 EventMark m("loading class %s", class_name);
1143 ThreadProfilerMark tpm(ThreadProfilerMark::classLoaderRegion);
1145 stringStream st;
1146 // st.print() uses too much stack space while handling a StackOverflowError
1147 // st.print("%s.class", h_name->as_utf8());
1148 st.print_raw(h_name->as_utf8());
1149 st.print_raw(".class");
1150 const char* file_name = st.as_string();
1151 ClassLoaderExt::Context context(class_name, file_name, THREAD);
1153 // Lookup stream for parsing .class file
1154 ClassFileStream* stream = NULL;
1155 int classpath_index = 0;
1156 ClassPathEntry* e = NULL;
1157 instanceKlassHandle h;
1158 {
1159 PerfClassTraceTime vmtimer(perf_sys_class_lookup_time(),
1160 ((JavaThread*) THREAD)->get_thread_stat()->perf_timers_addr(),
1161 PerfClassTraceTime::CLASS_LOAD);
1162 e = _first_entry;
1163 while (e != NULL) {
1164 stream = e->open_stream(file_name, CHECK_NULL);
1165 if (!context.check(stream, classpath_index)) {
1166 return h; // NULL
1167 }
1168 if (stream != NULL) {
1169 break;
1170 }
1171 e = e->next();
1172 ++classpath_index;
1173 }
1174 }
1176 if (stream != NULL) {
1177 // class file found, parse it
1178 ClassFileParser parser(stream);
1179 ClassLoaderData* loader_data = ClassLoaderData::the_null_class_loader_data();
1180 Handle protection_domain;
1181 TempNewSymbol parsed_name = NULL;
1182 instanceKlassHandle result = parser.parseClassFile(h_name,
1183 loader_data,
1184 protection_domain,
1185 parsed_name,
1186 context.should_verify(classpath_index),
1187 THREAD);
1188 if (HAS_PENDING_EXCEPTION) {
1189 ResourceMark rm;
1190 if (DumpSharedSpaces) {
1191 tty->print_cr("Preload Error: Failed to load %s", class_name);
1192 }
1193 return h;
1194 }
1196 #if INCLUDE_JFR
1197 {
1198 InstanceKlass* ik = result();
1199 ON_KLASS_CREATION(ik, parser, THREAD);
1200 result = instanceKlassHandle(ik);
1201 }
1202 #endif
1204 h = context.record_result(classpath_index, e, result, THREAD);
1205 } else {
1206 if (DumpSharedSpaces) {
1207 tty->print_cr("Preload Warning: Cannot find %s", class_name);
1208 }
1209 }
1211 return h;
1212 }
1215 void ClassLoader::create_package_info_table(HashtableBucket<mtClass> *t, int length,
1216 int number_of_entries) {
1217 assert(_package_hash_table == NULL, "One package info table allowed.");
1218 assert(length == package_hash_table_size * sizeof(HashtableBucket<mtClass>),
1219 "bad shared package info size.");
1220 _package_hash_table = new PackageHashtable(package_hash_table_size, t,
1221 number_of_entries);
1222 }
1225 void ClassLoader::create_package_info_table() {
1226 assert(_package_hash_table == NULL, "shouldn't have one yet");
1227 _package_hash_table = new PackageHashtable(package_hash_table_size);
1228 }
1231 // Initialize the class loader's access to methods in libzip. Parse and
1232 // process the boot classpath into a list ClassPathEntry objects. Once
1233 // this list has been created, it must not change order (see class PackageInfo)
1234 // it can be appended to and is by jvmti and the kernel vm.
1236 void ClassLoader::initialize() {
1237 assert(_package_hash_table == NULL, "should have been initialized by now.");
1238 EXCEPTION_MARK;
1240 if (UsePerfData) {
1241 // jvmstat performance counters
1242 NEWPERFTICKCOUNTER(_perf_accumulated_time, SUN_CLS, "time");
1243 NEWPERFTICKCOUNTER(_perf_class_init_time, SUN_CLS, "classInitTime");
1244 NEWPERFTICKCOUNTER(_perf_class_init_selftime, SUN_CLS, "classInitTime.self");
1245 NEWPERFTICKCOUNTER(_perf_class_verify_time, SUN_CLS, "classVerifyTime");
1246 NEWPERFTICKCOUNTER(_perf_class_verify_selftime, SUN_CLS, "classVerifyTime.self");
1247 NEWPERFTICKCOUNTER(_perf_class_link_time, SUN_CLS, "classLinkedTime");
1248 NEWPERFTICKCOUNTER(_perf_class_link_selftime, SUN_CLS, "classLinkedTime.self");
1249 NEWPERFEVENTCOUNTER(_perf_classes_inited, SUN_CLS, "initializedClasses");
1250 NEWPERFEVENTCOUNTER(_perf_classes_linked, SUN_CLS, "linkedClasses");
1251 NEWPERFEVENTCOUNTER(_perf_classes_verified, SUN_CLS, "verifiedClasses");
1253 NEWPERFTICKCOUNTER(_perf_class_parse_time, SUN_CLS, "parseClassTime");
1254 NEWPERFTICKCOUNTER(_perf_class_parse_selftime, SUN_CLS, "parseClassTime.self");
1255 NEWPERFTICKCOUNTER(_perf_sys_class_lookup_time, SUN_CLS, "lookupSysClassTime");
1256 NEWPERFTICKCOUNTER(_perf_shared_classload_time, SUN_CLS, "sharedClassLoadTime");
1257 NEWPERFTICKCOUNTER(_perf_sys_classload_time, SUN_CLS, "sysClassLoadTime");
1258 NEWPERFTICKCOUNTER(_perf_app_classload_time, SUN_CLS, "appClassLoadTime");
1259 NEWPERFTICKCOUNTER(_perf_app_classload_selftime, SUN_CLS, "appClassLoadTime.self");
1260 NEWPERFEVENTCOUNTER(_perf_app_classload_count, SUN_CLS, "appClassLoadCount");
1261 NEWPERFTICKCOUNTER(_perf_define_appclasses, SUN_CLS, "defineAppClasses");
1262 NEWPERFTICKCOUNTER(_perf_define_appclass_time, SUN_CLS, "defineAppClassTime");
1263 NEWPERFTICKCOUNTER(_perf_define_appclass_selftime, SUN_CLS, "defineAppClassTime.self");
1264 NEWPERFBYTECOUNTER(_perf_app_classfile_bytes_read, SUN_CLS, "appClassBytes");
1265 NEWPERFBYTECOUNTER(_perf_sys_classfile_bytes_read, SUN_CLS, "sysClassBytes");
1268 // The following performance counters are added for measuring the impact
1269 // of the bug fix of 6365597. They are mainly focused on finding out
1270 // the behavior of system & user-defined classloader lock, whether
1271 // ClassLoader.loadClass/findClass is being called synchronized or not.
1272 // Also two additional counters are created to see whether 'UnsyncloadClass'
1273 // flag is being set or not and how many times load_instance_class call
1274 // fails with linkageError etc.
1275 NEWPERFEVENTCOUNTER(_sync_systemLoaderLockContentionRate, SUN_CLS,
1276 "systemLoaderLockContentionRate");
1277 NEWPERFEVENTCOUNTER(_sync_nonSystemLoaderLockContentionRate, SUN_CLS,
1278 "nonSystemLoaderLockContentionRate");
1279 NEWPERFEVENTCOUNTER(_sync_JVMFindLoadedClassLockFreeCounter, SUN_CLS,
1280 "jvmFindLoadedClassNoLockCalls");
1281 NEWPERFEVENTCOUNTER(_sync_JVMDefineClassLockFreeCounter, SUN_CLS,
1282 "jvmDefineClassNoLockCalls");
1284 NEWPERFEVENTCOUNTER(_sync_JNIDefineClassLockFreeCounter, SUN_CLS,
1285 "jniDefineClassNoLockCalls");
1287 NEWPERFEVENTCOUNTER(_unsafe_defineClassCallCounter, SUN_CLS,
1288 "unsafeDefineClassCalls");
1290 NEWPERFEVENTCOUNTER(_isUnsyncloadClass, SUN_CLS, "isUnsyncloadClassSet");
1291 NEWPERFEVENTCOUNTER(_load_instance_class_failCounter, SUN_CLS,
1292 "loadInstanceClassFailRate");
1294 // increment the isUnsyncloadClass counter if UnsyncloadClass is set.
1295 if (UnsyncloadClass) {
1296 _isUnsyncloadClass->inc();
1297 }
1298 }
1300 // lookup zip library entry points
1301 load_zip_library();
1302 #if INCLUDE_CDS
1303 // initialize search path
1304 if (DumpSharedSpaces) {
1305 _shared_paths_misc_info = SharedClassUtil::allocate_shared_paths_misc_info();
1306 }
1307 #endif
1308 setup_bootstrap_search_path();
1309 if (LazyBootClassLoader) {
1310 // set up meta index which makes boot classpath initialization lazier
1311 setup_bootstrap_meta_index();
1312 }
1313 }
1315 #if INCLUDE_CDS
1316 void ClassLoader::initialize_shared_path() {
1317 if (DumpSharedSpaces) {
1318 ClassLoaderExt::setup_search_paths();
1319 _shared_paths_misc_info->write_jint(0); // see comments in SharedPathsMiscInfo::check()
1320 }
1321 }
1322 #endif
1324 jlong ClassLoader::classloader_time_ms() {
1325 return UsePerfData ?
1326 Management::ticks_to_ms(_perf_accumulated_time->get_value()) : -1;
1327 }
1329 jlong ClassLoader::class_init_count() {
1330 return UsePerfData ? _perf_classes_inited->get_value() : -1;
1331 }
1333 jlong ClassLoader::class_init_time_ms() {
1334 return UsePerfData ?
1335 Management::ticks_to_ms(_perf_class_init_time->get_value()) : -1;
1336 }
1338 jlong ClassLoader::class_verify_time_ms() {
1339 return UsePerfData ?
1340 Management::ticks_to_ms(_perf_class_verify_time->get_value()) : -1;
1341 }
1343 jlong ClassLoader::class_link_count() {
1344 return UsePerfData ? _perf_classes_linked->get_value() : -1;
1345 }
1347 jlong ClassLoader::class_link_time_ms() {
1348 return UsePerfData ?
1349 Management::ticks_to_ms(_perf_class_link_time->get_value()) : -1;
1350 }
1352 int ClassLoader::compute_Object_vtable() {
1353 // hardwired for JDK1.2 -- would need to duplicate class file parsing
1354 // code to determine actual value from file
1355 // Would be value '11' if finals were in vtable
1356 int JDK_1_2_Object_vtable_size = 5;
1357 return JDK_1_2_Object_vtable_size * vtableEntry::size();
1358 }
1361 void classLoader_init() {
1362 ClassLoader::initialize();
1363 }
1366 bool ClassLoader::get_canonical_path(const char* orig, char* out, int len) {
1367 assert(orig != NULL && out != NULL && len > 0, "bad arguments");
1368 if (CanonicalizeEntry != NULL) {
1369 JavaThread* THREAD = JavaThread::current();
1370 JNIEnv* env = THREAD->jni_environment();
1371 ResourceMark rm(THREAD);
1373 // os::native_path writes into orig_copy
1374 char* orig_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, strlen(orig)+1);
1375 strcpy(orig_copy, orig);
1376 if ((CanonicalizeEntry)(env, os::native_path(orig_copy), out, len) < 0) {
1377 return false;
1378 }
1379 } else {
1380 // On JDK 1.2.2 the Canonicalize does not exist, so just do nothing
1381 strncpy(out, orig, len);
1382 out[len - 1] = '\0';
1383 }
1384 return true;
1385 }
1387 #ifndef PRODUCT
1389 void ClassLoader::verify() {
1390 _package_hash_table->verify();
1391 }
1394 // CompileTheWorld
1395 //
1396 // Iterates over all class path entries and forces compilation of all methods
1397 // in all classes found. Currently, only zip/jar archives are searched.
1398 //
1399 // The classes are loaded by the Java level bootstrap class loader, and the
1400 // initializer is called. If DelayCompilationDuringStartup is true (default),
1401 // the interpreter will run the initialization code. Note that forcing
1402 // initialization in this way could potentially lead to initialization order
1403 // problems, in which case we could just force the initialization bit to be set.
1406 // We need to iterate over the contents of a zip/jar file, so we replicate the
1407 // jzcell and jzfile definitions from zip_util.h but rename jzfile to real_jzfile,
1408 // since jzfile already has a void* definition.
1409 //
1410 // Note that this is only used in debug mode.
1411 //
1412 // HotSpot integration note:
1413 // Matches zip_util.h 1.14 99/06/01 from jdk1.3 beta H build
1416 // JDK 1.3 version
1417 typedef struct real_jzentry13 { /* Zip file entry */
1418 char *name; /* entry name */
1419 jint time; /* modification time */
1420 jint size; /* size of uncompressed data */
1421 jint csize; /* size of compressed data (zero if uncompressed) */
1422 jint crc; /* crc of uncompressed data */
1423 char *comment; /* optional zip file comment */
1424 jbyte *extra; /* optional extra data */
1425 jint pos; /* position of LOC header (if negative) or data */
1426 } real_jzentry13;
1428 typedef struct real_jzfile13 { /* Zip file */
1429 char *name; /* zip file name */
1430 jint refs; /* number of active references */
1431 jint fd; /* open file descriptor */
1432 void *lock; /* read lock */
1433 char *comment; /* zip file comment */
1434 char *msg; /* zip error message */
1435 void *entries; /* array of hash cells */
1436 jint total; /* total number of entries */
1437 unsigned short *table; /* Hash chain heads: indexes into entries */
1438 jint tablelen; /* number of hash eads */
1439 real_jzfile13 *next; /* next zip file in search list */
1440 jzentry *cache; /* we cache the most recently freed jzentry */
1441 /* Information on metadata names in META-INF directory */
1442 char **metanames; /* array of meta names (may have null names) */
1443 jint metacount; /* number of slots in metanames array */
1444 /* If there are any per-entry comments, they are in the comments array */
1445 char **comments;
1446 } real_jzfile13;
1448 // JDK 1.2 version
1449 typedef struct real_jzentry12 { /* Zip file entry */
1450 char *name; /* entry name */
1451 jint time; /* modification time */
1452 jint size; /* size of uncompressed data */
1453 jint csize; /* size of compressed data (zero if uncompressed) */
1454 jint crc; /* crc of uncompressed data */
1455 char *comment; /* optional zip file comment */
1456 jbyte *extra; /* optional extra data */
1457 jint pos; /* position of LOC header (if negative) or data */
1458 struct real_jzentry12 *next; /* next entry in hash table */
1459 } real_jzentry12;
1461 typedef struct real_jzfile12 { /* Zip file */
1462 char *name; /* zip file name */
1463 jint refs; /* number of active references */
1464 jint fd; /* open file descriptor */
1465 void *lock; /* read lock */
1466 char *comment; /* zip file comment */
1467 char *msg; /* zip error message */
1468 real_jzentry12 *entries; /* array of zip entries */
1469 jint total; /* total number of entries */
1470 real_jzentry12 **table; /* hash table of entries */
1471 jint tablelen; /* number of buckets */
1472 jzfile *next; /* next zip file in search list */
1473 } real_jzfile12;
1476 void ClassPathDirEntry::compile_the_world(Handle loader, TRAPS) {
1477 // For now we only compile all methods in all classes in zip/jar files
1478 tty->print_cr("CompileTheWorld : Skipped classes in %s", _dir);
1479 tty->cr();
1480 }
1483 bool ClassPathDirEntry::is_rt_jar() {
1484 return false;
1485 }
1487 void ClassPathZipEntry::compile_the_world(Handle loader, TRAPS) {
1488 if (JDK_Version::is_jdk12x_version()) {
1489 compile_the_world12(loader, THREAD);
1490 } else {
1491 compile_the_world13(loader, THREAD);
1492 }
1493 if (HAS_PENDING_EXCEPTION) {
1494 if (PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1495 CLEAR_PENDING_EXCEPTION;
1496 tty->print_cr("\nCompileTheWorld : Ran out of memory\n");
1497 tty->print_cr("Increase class metadata storage if a limit was set");
1498 } else {
1499 tty->print_cr("\nCompileTheWorld : Unexpected exception occurred\n");
1500 }
1501 }
1502 }
1504 // Version that works for JDK 1.3.x
1505 void ClassPathZipEntry::compile_the_world13(Handle loader, TRAPS) {
1506 real_jzfile13* zip = (real_jzfile13*) _zip;
1507 tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
1508 tty->cr();
1509 // Iterate over all entries in zip file
1510 for (int n = 0; ; n++) {
1511 real_jzentry13 * ze = (real_jzentry13 *)((*GetNextEntry)(_zip, n));
1512 if (ze == NULL) break;
1513 ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
1514 }
1515 }
1518 // Version that works for JDK 1.2.x
1519 void ClassPathZipEntry::compile_the_world12(Handle loader, TRAPS) {
1520 real_jzfile12* zip = (real_jzfile12*) _zip;
1521 tty->print_cr("CompileTheWorld : Compiling all classes in %s", zip->name);
1522 tty->cr();
1523 // Iterate over all entries in zip file
1524 for (int n = 0; ; n++) {
1525 real_jzentry12 * ze = (real_jzentry12 *)((*GetNextEntry)(_zip, n));
1526 if (ze == NULL) break;
1527 ClassLoader::compile_the_world_in(ze->name, loader, CHECK);
1528 }
1529 }
1531 bool ClassPathZipEntry::is_rt_jar() {
1532 if (JDK_Version::is_jdk12x_version()) {
1533 return is_rt_jar12();
1534 } else {
1535 return is_rt_jar13();
1536 }
1537 }
1539 // JDK 1.3 version
1540 bool ClassPathZipEntry::is_rt_jar13() {
1541 real_jzfile13* zip = (real_jzfile13*) _zip;
1542 int len = (int)strlen(zip->name);
1543 // Check whether zip name ends in "rt.jar"
1544 // This will match other archives named rt.jar as well, but this is
1545 // only used for debugging.
1546 return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0);
1547 }
1549 // JDK 1.2 version
1550 bool ClassPathZipEntry::is_rt_jar12() {
1551 real_jzfile12* zip = (real_jzfile12*) _zip;
1552 int len = (int)strlen(zip->name);
1553 // Check whether zip name ends in "rt.jar"
1554 // This will match other archives named rt.jar as well, but this is
1555 // only used for debugging.
1556 return (len >= 6) && (strcasecmp(zip->name + len - 6, "rt.jar") == 0);
1557 }
1559 void LazyClassPathEntry::compile_the_world(Handle loader, TRAPS) {
1560 ClassPathEntry* cpe = resolve_entry(THREAD);
1561 if (cpe != NULL) {
1562 cpe->compile_the_world(loader, CHECK);
1563 }
1564 }
1566 bool LazyClassPathEntry::is_rt_jar() {
1567 Thread* THREAD = Thread::current();
1568 ClassPathEntry* cpe = resolve_entry(THREAD);
1569 return (cpe != NULL) ? cpe->is_jar_file() : false;
1570 }
1572 void ClassLoader::compile_the_world() {
1573 EXCEPTION_MARK;
1574 HandleMark hm(THREAD);
1575 ResourceMark rm(THREAD);
1576 // Make sure we don't run with background compilation
1577 BackgroundCompilation = false;
1578 // Find bootstrap loader
1579 Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
1580 // Iterate over all bootstrap class path entries
1581 ClassPathEntry* e = _first_entry;
1582 jlong start = os::javaTimeMillis();
1583 while (e != NULL) {
1584 // We stop at rt.jar, unless it is the first bootstrap path entry
1585 if (e->is_rt_jar() && e != _first_entry) break;
1586 e->compile_the_world(system_class_loader, CATCH);
1587 e = e->next();
1588 }
1589 jlong end = os::javaTimeMillis();
1590 tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, " JLONG_FORMAT " ms)",
1591 _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));
1592 {
1593 // Print statistics as if before normal exit:
1594 extern void print_statistics();
1595 print_statistics();
1596 }
1597 vm_exit(0);
1598 }
1600 int ClassLoader::_compile_the_world_class_counter = 0;
1601 int ClassLoader::_compile_the_world_method_counter = 0;
1602 static int _codecache_sweep_counter = 0;
1604 // Filter out all exceptions except OOMs
1605 static void clear_pending_exception_if_not_oom(TRAPS) {
1606 if (HAS_PENDING_EXCEPTION &&
1607 !PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())) {
1608 CLEAR_PENDING_EXCEPTION;
1609 }
1610 // The CHECK at the caller will propagate the exception out
1611 }
1613 /**
1614 * Returns if the given method should be compiled when doing compile-the-world.
1615 *
1616 * TODO: This should be a private method in a CompileTheWorld class.
1617 */
1618 static bool can_be_compiled(methodHandle m, int comp_level) {
1619 assert(CompileTheWorld, "must be");
1621 // It's not valid to compile a native wrapper for MethodHandle methods
1622 // that take a MemberName appendix since the bytecode signature is not
1623 // correct.
1624 vmIntrinsics::ID iid = m->intrinsic_id();
1625 if (MethodHandles::is_signature_polymorphic(iid) && MethodHandles::has_member_arg(iid)) {
1626 return false;
1627 }
1629 return CompilationPolicy::can_be_compiled(m, comp_level);
1630 }
1632 void ClassLoader::compile_the_world_in(char* name, Handle loader, TRAPS) {
1633 int len = (int)strlen(name);
1634 if (len > 6 && strcmp(".class", name + len - 6) == 0) {
1635 // We have a .class file
1636 char buffer[2048];
1637 strncpy(buffer, name, len - 6);
1638 buffer[len-6] = 0;
1639 // If the file has a period after removing .class, it's not really a
1640 // valid class file. The class loader will check everything else.
1641 if (strchr(buffer, '.') == NULL) {
1642 _compile_the_world_class_counter++;
1643 if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;
1645 // Construct name without extension
1646 TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
1647 // Use loader to load and initialize class
1648 Klass* ik = SystemDictionary::resolve_or_null(sym, loader, Handle(), THREAD);
1649 instanceKlassHandle k (THREAD, ik);
1650 if (k.not_null() && !HAS_PENDING_EXCEPTION) {
1651 k->initialize(THREAD);
1652 }
1653 bool exception_occurred = HAS_PENDING_EXCEPTION;
1654 clear_pending_exception_if_not_oom(CHECK);
1655 if (CompileTheWorldPreloadClasses && k.not_null()) {
1656 ConstantPool::preload_and_initialize_all_classes(k->constants(), THREAD);
1657 if (HAS_PENDING_EXCEPTION) {
1658 // If something went wrong in preloading we just ignore it
1659 clear_pending_exception_if_not_oom(CHECK);
1660 tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer);
1661 }
1662 }
1664 if (_compile_the_world_class_counter >= CompileTheWorldStartAt) {
1665 if (k.is_null() || exception_occurred) {
1666 // If something went wrong (e.g. ExceptionInInitializerError) we skip this class
1667 tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer);
1668 } else {
1669 tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer);
1670 // Preload all classes to get around uncommon traps
1671 // Iterate over all methods in class
1672 int comp_level = CompilationPolicy::policy()->initial_compile_level();
1673 for (int n = 0; n < k->methods()->length(); n++) {
1674 methodHandle m (THREAD, k->methods()->at(n));
1675 if (can_be_compiled(m, comp_level)) {
1676 if (++_codecache_sweep_counter == CompileTheWorldSafepointInterval) {
1677 // Give sweeper a chance to keep up with CTW
1678 VM_ForceSafepoint op;
1679 VMThread::execute(&op);
1680 _codecache_sweep_counter = 0;
1681 }
1682 // Force compilation
1683 CompileBroker::compile_method(m, InvocationEntryBci, comp_level,
1684 methodHandle(), 0, "CTW", THREAD);
1685 if (HAS_PENDING_EXCEPTION) {
1686 clear_pending_exception_if_not_oom(CHECK);
1687 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1688 } else {
1689 _compile_the_world_method_counter++;
1690 }
1691 if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) {
1692 // Clobber the first compile and force second tier compilation
1693 nmethod* nm = m->code();
1694 if (nm != NULL && !m->is_method_handle_intrinsic()) {
1695 // Throw out the code so that the code cache doesn't fill up
1696 nm->make_not_entrant();
1697 }
1698 CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_full_optimization,
1699 methodHandle(), 0, "CTW", THREAD);
1700 if (HAS_PENDING_EXCEPTION) {
1701 clear_pending_exception_if_not_oom(CHECK);
1702 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1703 } else {
1704 _compile_the_world_method_counter++;
1705 }
1706 }
1707 } else {
1708 tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name_and_sig_as_C_string());
1709 }
1711 nmethod* nm = m->code();
1712 if (nm != NULL && !m->is_method_handle_intrinsic()) {
1713 // Throw out the code so that the code cache doesn't fill up
1714 nm->make_not_entrant();
1715 }
1716 }
1717 }
1718 }
1719 }
1720 }
1721 }
1723 #endif //PRODUCT
1725 // Please keep following two functions at end of this file. With them placed at top or in middle of the file,
1726 // they could get inlined by agressive compiler, an unknown trick, see bug 6966589.
1727 void PerfClassTraceTime::initialize() {
1728 if (!UsePerfData) return;
1730 if (_eventp != NULL) {
1731 // increment the event counter
1732 _eventp->inc();
1733 }
1735 // stop the current active thread-local timer to measure inclusive time
1736 _prev_active_event = -1;
1737 for (int i=0; i < EVENT_TYPE_COUNT; i++) {
1738 if (_timers[i].is_active()) {
1739 assert(_prev_active_event == -1, "should have only one active timer");
1740 _prev_active_event = i;
1741 _timers[i].stop();
1742 }
1743 }
1745 if (_recursion_counters == NULL || (_recursion_counters[_event_type])++ == 0) {
1746 // start the inclusive timer if not recursively called
1747 _t.start();
1748 }
1750 // start thread-local timer of the given event type
1751 if (!_timers[_event_type].is_active()) {
1752 _timers[_event_type].start();
1753 }
1754 }
1756 PerfClassTraceTime::~PerfClassTraceTime() {
1757 if (!UsePerfData) return;
1759 // stop the thread-local timer as the event completes
1760 // and resume the thread-local timer of the event next on the stack
1761 _timers[_event_type].stop();
1762 jlong selftime = _timers[_event_type].ticks();
1764 if (_prev_active_event >= 0) {
1765 _timers[_prev_active_event].start();
1766 }
1768 if (_recursion_counters != NULL && --(_recursion_counters[_event_type]) > 0) return;
1770 // increment the counters only on the leaf call
1771 _t.stop();
1772 _timep->inc(_t.ticks());
1773 if (_selftimep != NULL) {
1774 _selftimep->inc(selftime);
1775 }
1776 // add all class loading related event selftime to the accumulated time counter
1777 ClassLoader::perf_accumulated_time()->inc(selftime);
1779 // reset the timer
1780 _timers[_event_type].reset();
1781 }