Tue, 21 Dec 2010 04:37:30 -0800
7008165: Garbage in ClassFormatError message
Summary: When bootstrap_method_ref in BootstrapMethods attribute points to a wrong CP entry (non-MethodHandle), JVM throws ClassFormatError with a message, where method index and class file name is garbage.
Reviewed-by: iveresov
1 /*
2 * Copyright (c) 1997, 2010, 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/dictionary.hpp"
27 #include "classfile/javaClasses.hpp"
28 #include "classfile/loaderConstraints.hpp"
29 #include "classfile/placeholders.hpp"
30 #include "classfile/resolutionErrors.hpp"
31 #include "classfile/systemDictionary.hpp"
32 #include "classfile/vmSymbols.hpp"
33 #include "interpreter/bytecodeStream.hpp"
34 #include "interpreter/interpreter.hpp"
35 #include "memory/gcLocker.hpp"
36 #include "memory/oopFactory.hpp"
37 #include "oops/instanceKlass.hpp"
38 #include "oops/instanceRefKlass.hpp"
39 #include "oops/klass.inline.hpp"
40 #include "oops/methodDataOop.hpp"
41 #include "oops/objArrayKlass.hpp"
42 #include "oops/oop.inline.hpp"
43 #include "oops/oop.inline2.hpp"
44 #include "oops/typeArrayKlass.hpp"
45 #include "prims/jvmtiEnvBase.hpp"
46 #include "prims/methodHandles.hpp"
47 #include "runtime/biasedLocking.hpp"
48 #include "runtime/fieldType.hpp"
49 #include "runtime/handles.inline.hpp"
50 #include "runtime/java.hpp"
51 #include "runtime/javaCalls.hpp"
52 #include "runtime/mutexLocker.hpp"
53 #include "runtime/signature.hpp"
54 #include "services/classLoadingService.hpp"
55 #include "services/threadService.hpp"
58 Dictionary* SystemDictionary::_dictionary = NULL;
59 PlaceholderTable* SystemDictionary::_placeholders = NULL;
60 Dictionary* SystemDictionary::_shared_dictionary = NULL;
61 LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL;
62 ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL;
63 SymbolPropertyTable* SystemDictionary::_invoke_method_table = NULL;
66 int SystemDictionary::_number_of_modifications = 0;
68 oop SystemDictionary::_system_loader_lock_obj = NULL;
70 klassOop SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
71 = { NULL /*, NULL...*/ };
73 klassOop SystemDictionary::_box_klasses[T_VOID+1] = { NULL /*, NULL...*/ };
75 oop SystemDictionary::_java_system_loader = NULL;
77 bool SystemDictionary::_has_loadClassInternal = false;
78 bool SystemDictionary::_has_checkPackageAccess = false;
80 // lazily initialized klass variables
81 volatile klassOop SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
84 // ----------------------------------------------------------------------------
85 // Java-level SystemLoader
87 oop SystemDictionary::java_system_loader() {
88 return _java_system_loader;
89 }
91 void SystemDictionary::compute_java_system_loader(TRAPS) {
92 KlassHandle system_klass(THREAD, WK_KLASS(ClassLoader_klass));
93 JavaValue result(T_OBJECT);
94 JavaCalls::call_static(&result,
95 KlassHandle(THREAD, WK_KLASS(ClassLoader_klass)),
96 vmSymbolHandles::getSystemClassLoader_name(),
97 vmSymbolHandles::void_classloader_signature(),
98 CHECK);
100 _java_system_loader = (oop)result.get_jobject();
101 }
104 // ----------------------------------------------------------------------------
105 // debugging
107 #ifdef ASSERT
109 // return true if class_name contains no '.' (internal format is '/')
110 bool SystemDictionary::is_internal_format(symbolHandle class_name) {
111 if (class_name.not_null()) {
112 ResourceMark rm;
113 char* name = class_name->as_C_string();
114 return strchr(name, '.') == NULL;
115 } else {
116 return true;
117 }
118 }
120 #endif
122 // ----------------------------------------------------------------------------
123 // Parallel class loading check
125 bool SystemDictionary::is_parallelCapable(Handle class_loader) {
126 if (UnsyncloadClass || class_loader.is_null()) return true;
127 if (AlwaysLockClassLoader) return false;
128 return java_lang_Class::parallelCapable(class_loader());
129 }
130 // ----------------------------------------------------------------------------
131 // ParallelDefineClass flag does not apply to bootclass loader
132 bool SystemDictionary::is_parallelDefine(Handle class_loader) {
133 if (class_loader.is_null()) return false;
134 if (AllowParallelDefineClass && java_lang_Class::parallelCapable(class_loader())) {
135 return true;
136 }
137 return false;
138 }
139 // ----------------------------------------------------------------------------
140 // Resolving of classes
142 // Forwards to resolve_or_null
144 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
145 klassOop klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
146 if (HAS_PENDING_EXCEPTION || klass == NULL) {
147 KlassHandle k_h(THREAD, klass);
148 // can return a null klass
149 klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
150 }
151 return klass;
152 }
154 klassOop SystemDictionary::handle_resolution_exception(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
155 if (HAS_PENDING_EXCEPTION) {
156 // If we have a pending exception we forward it to the caller, unless throw_error is true,
157 // in which case we have to check whether the pending exception is a ClassNotFoundException,
158 // and if so convert it to a NoClassDefFoundError
159 // And chain the original ClassNotFoundException
160 if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
161 ResourceMark rm(THREAD);
162 assert(klass_h() == NULL, "Should not have result with exception pending");
163 Handle e(THREAD, PENDING_EXCEPTION);
164 CLEAR_PENDING_EXCEPTION;
165 THROW_MSG_CAUSE_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
166 } else {
167 return NULL;
168 }
169 }
170 // Class not found, throw appropriate error or exception depending on value of throw_error
171 if (klass_h() == NULL) {
172 ResourceMark rm(THREAD);
173 if (throw_error) {
174 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
175 } else {
176 THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
177 }
178 }
179 return (klassOop)klass_h();
180 }
183 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name,
184 bool throw_error, TRAPS)
185 {
186 return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
187 }
190 // Forwards to resolve_instance_class_or_null
192 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
193 assert(!THREAD->is_Compiler_thread(), "Can not load classes with the Compiler thread");
194 if (FieldType::is_array(class_name())) {
195 return resolve_array_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
196 } else {
197 return resolve_instance_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
198 }
199 }
201 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, TRAPS) {
202 return resolve_or_null(class_name, Handle(), Handle(), THREAD);
203 }
205 // Forwards to resolve_instance_class_or_null
207 klassOop SystemDictionary::resolve_array_class_or_null(symbolHandle class_name,
208 Handle class_loader,
209 Handle protection_domain,
210 TRAPS) {
211 assert(FieldType::is_array(class_name()), "must be array");
212 jint dimension;
213 symbolOop object_key;
214 klassOop k = NULL;
215 // dimension and object_key are assigned as a side-effect of this call
216 BasicType t = FieldType::get_array_info(class_name(),
217 &dimension,
218 &object_key,
219 CHECK_NULL);
221 if (t == T_OBJECT) {
222 symbolHandle h_key(THREAD, object_key);
223 // naked oop "k" is OK here -- we assign back into it
224 k = SystemDictionary::resolve_instance_class_or_null(h_key,
225 class_loader,
226 protection_domain,
227 CHECK_NULL);
228 if (k != NULL) {
229 k = Klass::cast(k)->array_klass(dimension, CHECK_NULL);
230 }
231 } else {
232 k = Universe::typeArrayKlassObj(t);
233 k = typeArrayKlass::cast(k)->array_klass(dimension, CHECK_NULL);
234 }
235 return k;
236 }
239 // Must be called for any super-class or super-interface resolution
240 // during class definition to allow class circularity checking
241 // super-interface callers:
242 // parse_interfaces - for defineClass & jvmtiRedefineClasses
243 // super-class callers:
244 // ClassFileParser - for defineClass & jvmtiRedefineClasses
245 // load_shared_class - while loading a class from shared archive
246 // resolve_instance_class_or_null:
247 // via: handle_parallel_super_load
248 // when resolving a class that has an existing placeholder with
249 // a saved superclass [i.e. a defineClass is currently in progress]
250 // if another thread is trying to resolve the class, it must do
251 // super-class checks on its own thread to catch class circularity
252 // This last call is critical in class circularity checking for cases
253 // where classloading is delegated to different threads and the
254 // classloader lock is released.
255 // Take the case: Base->Super->Base
256 // 1. If thread T1 tries to do a defineClass of class Base
257 // resolve_super_or_fail creates placeholder: T1, Base (super Super)
258 // 2. resolve_instance_class_or_null does not find SD or placeholder for Super
259 // so it tries to load Super
260 // 3. If we load the class internally, or user classloader uses same thread
261 // loadClassFromxxx or defineClass via parseClassFile Super ...
262 // 3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
263 // 3.3 resolve_instance_class_or_null Base, finds placeholder for Base
264 // 3.4 calls resolve_super_or_fail Base
265 // 3.5 finds T1,Base -> throws class circularity
266 //OR 4. If T2 tries to resolve Super via defineClass Super ...
267 // 4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
268 // 4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
269 // 4.3 calls resolve_super_or_fail Super in parallel on own thread T2
270 // 4.4 finds T2, Super -> throws class circularity
271 // Must be called, even if superclass is null, since this is
272 // where the placeholder entry is created which claims this
273 // thread is loading this class/classloader.
274 klassOop SystemDictionary::resolve_super_or_fail(symbolHandle child_name,
275 symbolHandle class_name,
276 Handle class_loader,
277 Handle protection_domain,
278 bool is_superclass,
279 TRAPS) {
281 // Try to get one of the well-known klasses.
282 // They are trusted, and do not participate in circularities.
283 if (LinkWellKnownClasses) {
284 klassOop k = find_well_known_klass(class_name());
285 if (k != NULL) {
286 return k;
287 }
288 }
290 // Double-check, if child class is already loaded, just return super-class,interface
291 // Don't add a placedholder if already loaded, i.e. already in system dictionary
292 // Make sure there's a placeholder for the *child* before resolving.
293 // Used as a claim that this thread is currently loading superclass/classloader
294 // Used here for ClassCircularity checks and also for heap verification
295 // (every instanceKlass in the heap needs to be in the system dictionary
296 // or have a placeholder).
297 // Must check ClassCircularity before checking if super class is already loaded
298 //
299 // We might not already have a placeholder if this child_name was
300 // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
301 // the name of the class might not be known until the stream is actually
302 // parsed.
303 // Bugs 4643874, 4715493
304 // compute_hash can have a safepoint
306 unsigned int d_hash = dictionary()->compute_hash(child_name, class_loader);
307 int d_index = dictionary()->hash_to_index(d_hash);
308 unsigned int p_hash = placeholders()->compute_hash(child_name, class_loader);
309 int p_index = placeholders()->hash_to_index(p_hash);
310 // can't throw error holding a lock
311 bool child_already_loaded = false;
312 bool throw_circularity_error = false;
313 {
314 MutexLocker mu(SystemDictionary_lock, THREAD);
315 klassOop childk = find_class(d_index, d_hash, child_name, class_loader);
316 klassOop quicksuperk;
317 // to support // loading: if child done loading, just return superclass
318 // if class_name, & class_loader don't match:
319 // if initial define, SD update will give LinkageError
320 // if redefine: compare_class_versions will give HIERARCHY_CHANGED
321 // so we don't throw an exception here.
322 // see: nsk redefclass014 & java.lang.instrument Instrument032
323 if ((childk != NULL ) && (is_superclass) &&
324 ((quicksuperk = instanceKlass::cast(childk)->super()) != NULL) &&
326 ((Klass::cast(quicksuperk)->name() == class_name()) &&
327 (Klass::cast(quicksuperk)->class_loader() == class_loader()))) {
328 return quicksuperk;
329 } else {
330 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
331 if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
332 throw_circularity_error = true;
333 }
334 }
335 if (!throw_circularity_error) {
336 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, class_loader, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
337 }
338 }
339 if (throw_circularity_error) {
340 ResourceMark rm(THREAD);
341 THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
342 }
344 // java.lang.Object should have been found above
345 assert(class_name() != NULL, "null super class for resolving");
346 // Resolve the super class or interface, check results on return
347 klassOop superk = NULL;
348 superk = SystemDictionary::resolve_or_null(class_name,
349 class_loader,
350 protection_domain,
351 THREAD);
353 KlassHandle superk_h(THREAD, superk);
355 // Note: clean up of placeholders currently in callers of
356 // resolve_super_or_fail - either at update_dictionary time
357 // or on error
358 {
359 MutexLocker mu(SystemDictionary_lock, THREAD);
360 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
361 if (probe != NULL) {
362 probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER);
363 }
364 }
365 if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
366 // can null superk
367 superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
368 }
370 return superk_h();
371 }
373 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
374 Handle class_loader,
375 Handle protection_domain,
376 TRAPS) {
377 if(!has_checkPackageAccess()) return;
379 // Now we have to call back to java to check if the initating class has access
380 JavaValue result(T_VOID);
381 if (TraceProtectionDomainVerification) {
382 // Print out trace information
383 tty->print_cr("Checking package access");
384 tty->print(" - class loader: "); class_loader()->print_value_on(tty); tty->cr();
385 tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();
386 tty->print(" - loading: "); klass()->print_value_on(tty); tty->cr();
387 }
389 assert(class_loader() != NULL, "should not have non-null protection domain for null classloader");
391 KlassHandle system_loader(THREAD, SystemDictionary::ClassLoader_klass());
392 JavaCalls::call_special(&result,
393 class_loader,
394 system_loader,
395 vmSymbolHandles::checkPackageAccess_name(),
396 vmSymbolHandles::class_protectiondomain_signature(),
397 Handle(THREAD, klass->java_mirror()),
398 protection_domain,
399 THREAD);
401 if (TraceProtectionDomainVerification) {
402 if (HAS_PENDING_EXCEPTION) {
403 tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
404 } else {
405 tty->print_cr(" -> granted");
406 }
407 tty->cr();
408 }
410 if (HAS_PENDING_EXCEPTION) return;
412 // If no exception has been thrown, we have validated the protection domain
413 // Insert the protection domain of the initiating class into the set.
414 {
415 // We recalculate the entry here -- we've called out to java since
416 // the last time it was calculated.
417 symbolHandle kn(THREAD, klass->name());
418 unsigned int d_hash = dictionary()->compute_hash(kn, class_loader);
419 int d_index = dictionary()->hash_to_index(d_hash);
421 MutexLocker mu(SystemDictionary_lock, THREAD);
422 {
423 // Note that we have an entry, and entries can be deleted only during GC,
424 // so we cannot allow GC to occur while we're holding this entry.
426 // We're using a No_Safepoint_Verifier to catch any place where we
427 // might potentially do a GC at all.
428 // SystemDictionary::do_unloading() asserts that classes are only
429 // unloaded at a safepoint.
430 No_Safepoint_Verifier nosafepoint;
431 dictionary()->add_protection_domain(d_index, d_hash, klass, class_loader,
432 protection_domain, THREAD);
433 }
434 }
435 }
437 // We only get here if this thread finds that another thread
438 // has already claimed the placeholder token for the current operation,
439 // but that other thread either never owned or gave up the
440 // object lock
441 // Waits on SystemDictionary_lock to indicate placeholder table updated
442 // On return, caller must recheck placeholder table state
443 //
444 // We only get here if
445 // 1) custom classLoader, i.e. not bootstrap classloader
446 // 2) UnsyncloadClass not set
447 // 3) custom classLoader has broken the class loader objectLock
448 // so another thread got here in parallel
449 //
450 // lockObject must be held.
451 // Complicated dance due to lock ordering:
452 // Must first release the classloader object lock to
453 // allow initial definer to complete the class definition
454 // and to avoid deadlock
455 // Reclaim classloader lock object with same original recursion count
456 // Must release SystemDictionary_lock after notify, since
457 // class loader lock must be claimed before SystemDictionary_lock
458 // to prevent deadlocks
459 //
460 // The notify allows applications that did an untimed wait() on
461 // the classloader object lock to not hang.
462 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
463 assert_lock_strong(SystemDictionary_lock);
465 bool calledholdinglock
466 = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
467 assert(calledholdinglock,"must hold lock for notify");
468 assert((!(lockObject() == _system_loader_lock_obj) && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
469 ObjectSynchronizer::notifyall(lockObject, THREAD);
470 intptr_t recursions = ObjectSynchronizer::complete_exit(lockObject, THREAD);
471 SystemDictionary_lock->wait();
472 SystemDictionary_lock->unlock();
473 ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
474 SystemDictionary_lock->lock();
475 }
477 // If the class in is in the placeholder table, class loading is in progress
478 // For cases where the application changes threads to load classes, it
479 // is critical to ClassCircularity detection that we try loading
480 // the superclass on the same thread internally, so we do parallel
481 // super class loading here.
482 // This also is critical in cases where the original thread gets stalled
483 // even in non-circularity situations.
484 // Note: only one thread can define the class, but multiple can resolve
485 // Note: must call resolve_super_or_fail even if null super -
486 // to force placeholder entry creation for this class for circularity detection
487 // Caller must check for pending exception
488 // Returns non-null klassOop if other thread has completed load
489 // and we are done,
490 // If return null klassOop and no pending exception, the caller must load the class
491 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
492 symbolHandle name, symbolHandle superclassname, Handle class_loader,
493 Handle protection_domain, Handle lockObject, TRAPS) {
495 instanceKlassHandle nh = instanceKlassHandle(); // null Handle
496 unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
497 int d_index = dictionary()->hash_to_index(d_hash);
498 unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
499 int p_index = placeholders()->hash_to_index(p_hash);
501 // superk is not used, resolve_super called for circularity check only
502 // This code is reached in two situations. One if this thread
503 // is loading the same class twice (e.g. ClassCircularity, or
504 // java.lang.instrument).
505 // The second is if another thread started the resolve_super first
506 // and has not yet finished.
507 // In both cases the original caller will clean up the placeholder
508 // entry on error.
509 klassOop superk = SystemDictionary::resolve_super_or_fail(name,
510 superclassname,
511 class_loader,
512 protection_domain,
513 true,
514 CHECK_(nh));
515 // We don't redefine the class, so we just need to clean up if there
516 // was not an error (don't want to modify any system dictionary
517 // data structures).
518 {
519 MutexLocker mu(SystemDictionary_lock, THREAD);
520 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
521 SystemDictionary_lock->notify_all();
522 }
524 // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
525 // Serial class loaders and bootstrap classloader do wait for superclass loads
526 if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
527 MutexLocker mu(SystemDictionary_lock, THREAD);
528 // Check if classloading completed while we were loading superclass or waiting
529 klassOop check = find_class(d_index, d_hash, name, class_loader);
530 if (check != NULL) {
531 // Klass is already loaded, so just return it
532 return(instanceKlassHandle(THREAD, check));
533 } else {
534 return nh;
535 }
536 }
538 // must loop to both handle other placeholder updates
539 // and spurious notifications
540 bool super_load_in_progress = true;
541 PlaceholderEntry* placeholder;
542 while (super_load_in_progress) {
543 MutexLocker mu(SystemDictionary_lock, THREAD);
544 // Check if classloading completed while we were loading superclass or waiting
545 klassOop check = find_class(d_index, d_hash, name, class_loader);
546 if (check != NULL) {
547 // Klass is already loaded, so just return it
548 return(instanceKlassHandle(THREAD, check));
549 } else {
550 placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
551 if (placeholder && placeholder->super_load_in_progress() ){
552 // Before UnsyncloadClass:
553 // We only get here if the application has released the
554 // classloader lock when another thread was in the middle of loading a
555 // superclass/superinterface for this class, and now
556 // this thread is also trying to load this class.
557 // To minimize surprises, the first thread that started to
558 // load a class should be the one to complete the loading
559 // with the classfile it initially expected.
560 // This logic has the current thread wait once it has done
561 // all the superclass/superinterface loading it can, until
562 // the original thread completes the class loading or fails
563 // If it completes we will use the resulting instanceKlass
564 // which we will find below in the systemDictionary.
565 // We also get here for parallel bootstrap classloader
566 if (class_loader.is_null()) {
567 SystemDictionary_lock->wait();
568 } else {
569 double_lock_wait(lockObject, THREAD);
570 }
571 } else {
572 // If not in SD and not in PH, other thread's load must have failed
573 super_load_in_progress = false;
574 }
575 }
576 }
577 return (nh);
578 }
581 klassOop SystemDictionary::resolve_instance_class_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
582 assert(class_name.not_null() && !FieldType::is_array(class_name()), "invalid class name");
583 // First check to see if we should remove wrapping L and ;
584 symbolHandle name;
585 if (FieldType::is_obj(class_name())) {
586 ResourceMark rm(THREAD);
587 // Ignore wrapping L and ;.
588 name = oopFactory::new_symbol_handle(class_name()->as_C_string() + 1, class_name()->utf8_length() - 2, CHECK_NULL);
589 } else {
590 name = class_name;
591 }
593 // UseNewReflection
594 // Fix for 4474172; see evaluation for more details
595 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
597 // Do lookup to see if class already exist and the protection domain
598 // has the right access
599 unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
600 int d_index = dictionary()->hash_to_index(d_hash);
601 klassOop probe = dictionary()->find(d_index, d_hash, name, class_loader,
602 protection_domain, THREAD);
603 if (probe != NULL) return probe;
606 // Non-bootstrap class loaders will call out to class loader and
607 // define via jvm/jni_DefineClass which will acquire the
608 // class loader object lock to protect against multiple threads
609 // defining the class in parallel by accident.
610 // This lock must be acquired here so the waiter will find
611 // any successful result in the SystemDictionary and not attempt
612 // the define
613 // ParallelCapable Classloaders and the bootstrap classloader,
614 // or all classloaders with UnsyncloadClass do not acquire lock here
615 bool DoObjectLock = true;
616 if (is_parallelCapable(class_loader)) {
617 DoObjectLock = false;
618 }
620 unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
621 int p_index = placeholders()->hash_to_index(p_hash);
623 // Class is not in SystemDictionary so we have to do loading.
624 // Make sure we are synchronized on the class loader before we proceed
625 Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
626 check_loader_lock_contention(lockObject, THREAD);
627 ObjectLocker ol(lockObject, THREAD, DoObjectLock);
629 // Check again (after locking) if class already exist in SystemDictionary
630 bool class_has_been_loaded = false;
631 bool super_load_in_progress = false;
632 bool havesupername = false;
633 instanceKlassHandle k;
634 PlaceholderEntry* placeholder;
635 symbolHandle superclassname;
637 {
638 MutexLocker mu(SystemDictionary_lock, THREAD);
639 klassOop check = find_class(d_index, d_hash, name, class_loader);
640 if (check != NULL) {
641 // Klass is already loaded, so just return it
642 class_has_been_loaded = true;
643 k = instanceKlassHandle(THREAD, check);
644 } else {
645 placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
646 if (placeholder && placeholder->super_load_in_progress()) {
647 super_load_in_progress = true;
648 if (placeholder->havesupername() == true) {
649 superclassname = symbolHandle(THREAD, placeholder->supername());
650 havesupername = true;
651 }
652 }
653 }
654 }
656 // If the class in is in the placeholder table, class loading is in progress
657 if (super_load_in_progress && havesupername==true) {
658 k = SystemDictionary::handle_parallel_super_load(name, superclassname,
659 class_loader, protection_domain, lockObject, THREAD);
660 if (HAS_PENDING_EXCEPTION) {
661 return NULL;
662 }
663 if (!k.is_null()) {
664 class_has_been_loaded = true;
665 }
666 }
668 if (!class_has_been_loaded) {
670 // add placeholder entry to record loading instance class
671 // Five cases:
672 // All cases need to prevent modifying bootclasssearchpath
673 // in parallel with a classload of same classname
674 // Redefineclasses uses existence of the placeholder for the duration
675 // of the class load to prevent concurrent redefinition of not completely
676 // defined classes.
677 // case 1. traditional classloaders that rely on the classloader object lock
678 // - no other need for LOAD_INSTANCE
679 // case 2. traditional classloaders that break the classloader object lock
680 // as a deadlock workaround. Detection of this case requires that
681 // this check is done while holding the classloader object lock,
682 // and that lock is still held when calling classloader's loadClass.
683 // For these classloaders, we ensure that the first requestor
684 // completes the load and other requestors wait for completion.
685 // case 3. UnsyncloadClass - don't use objectLocker
686 // With this flag, we allow parallel classloading of a
687 // class/classloader pair
688 // case4. Bootstrap classloader - don't own objectLocker
689 // This classloader supports parallelism at the classloader level,
690 // but only allows a single load of a class/classloader pair.
691 // No performance benefit and no deadlock issues.
692 // case 5. parallelCapable user level classloaders - without objectLocker
693 // Allow parallel classloading of a class/classloader pair
694 symbolHandle nullsymbolHandle;
695 bool throw_circularity_error = false;
696 {
697 MutexLocker mu(SystemDictionary_lock, THREAD);
698 if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
699 PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
700 if (oldprobe) {
701 // only need check_seen_thread once, not on each loop
702 // 6341374 java/lang/Instrument with -Xcomp
703 if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
704 throw_circularity_error = true;
705 } else {
706 // case 1: traditional: should never see load_in_progress.
707 while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
709 // case 4: bootstrap classloader: prevent futile classloading,
710 // wait on first requestor
711 if (class_loader.is_null()) {
712 SystemDictionary_lock->wait();
713 } else {
714 // case 2: traditional with broken classloader lock. wait on first
715 // requestor.
716 double_lock_wait(lockObject, THREAD);
717 }
718 // Check if classloading completed while we were waiting
719 klassOop check = find_class(d_index, d_hash, name, class_loader);
720 if (check != NULL) {
721 // Klass is already loaded, so just return it
722 k = instanceKlassHandle(THREAD, check);
723 class_has_been_loaded = true;
724 }
725 // check if other thread failed to load and cleaned up
726 oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
727 }
728 }
729 }
730 }
731 // All cases: add LOAD_INSTANCE
732 // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
733 // LOAD_INSTANCE in parallel
734 // add placeholder entry even if error - callers will remove on error
735 if (!throw_circularity_error && !class_has_been_loaded) {
736 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, class_loader, PlaceholderTable::LOAD_INSTANCE, nullsymbolHandle, THREAD);
737 // For class loaders that do not acquire the classloader object lock,
738 // if they did not catch another thread holding LOAD_INSTANCE,
739 // need a check analogous to the acquire ObjectLocker/find_class
740 // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
741 // one final check if the load has already completed
742 // class loaders holding the ObjectLock shouldn't find the class here
743 klassOop check = find_class(d_index, d_hash, name, class_loader);
744 if (check != NULL) {
745 // Klass is already loaded, so just return it
746 k = instanceKlassHandle(THREAD, check);
747 class_has_been_loaded = true;
748 newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
749 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
750 SystemDictionary_lock->notify_all();
751 }
752 }
753 }
754 // must throw error outside of owning lock
755 if (throw_circularity_error) {
756 ResourceMark rm(THREAD);
757 THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
758 }
760 if (!class_has_been_loaded) {
762 // Do actual loading
763 k = load_instance_class(name, class_loader, THREAD);
765 // For UnsyncloadClass only
766 // If they got a linkageError, check if a parallel class load succeeded.
767 // If it did, then for bytecode resolution the specification requires
768 // that we return the same result we did for the other thread, i.e. the
769 // successfully loaded instanceKlass
770 // Should not get here for classloaders that support parallelism
771 // with the new cleaner mechanism, even with AllowParallelDefineClass
772 // Bootstrap goes through here to allow for an extra guarantee check
773 if (UnsyncloadClass || (class_loader.is_null())) {
774 if (k.is_null() && HAS_PENDING_EXCEPTION
775 && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
776 MutexLocker mu(SystemDictionary_lock, THREAD);
777 klassOop check = find_class(d_index, d_hash, name, class_loader);
778 if (check != NULL) {
779 // Klass is already loaded, so just use it
780 k = instanceKlassHandle(THREAD, check);
781 CLEAR_PENDING_EXCEPTION;
782 guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
783 }
784 }
785 }
787 // clean up placeholder entries for success or error
788 // This cleans up LOAD_INSTANCE entries
789 // It also cleans up LOAD_SUPER entries on errors from
790 // calling load_instance_class
791 {
792 MutexLocker mu(SystemDictionary_lock, THREAD);
793 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
794 if (probe != NULL) {
795 probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
796 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
797 SystemDictionary_lock->notify_all();
798 }
799 }
801 // If everything was OK (no exceptions, no null return value), and
802 // class_loader is NOT the defining loader, do a little more bookkeeping.
803 if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
804 k->class_loader() != class_loader()) {
806 check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
808 // Need to check for a PENDING_EXCEPTION again; check_constraints
809 // can throw and doesn't use the CHECK macro.
810 if (!HAS_PENDING_EXCEPTION) {
811 { // Grabbing the Compile_lock prevents systemDictionary updates
812 // during compilations.
813 MutexLocker mu(Compile_lock, THREAD);
814 update_dictionary(d_index, d_hash, p_index, p_hash,
815 k, class_loader, THREAD);
816 }
817 if (JvmtiExport::should_post_class_load()) {
818 Thread *thread = THREAD;
819 assert(thread->is_Java_thread(), "thread->is_Java_thread()");
820 JvmtiExport::post_class_load((JavaThread *) thread, k());
821 }
822 }
823 }
824 if (HAS_PENDING_EXCEPTION || k.is_null()) {
825 // On error, clean up placeholders
826 {
827 MutexLocker mu(SystemDictionary_lock, THREAD);
828 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
829 SystemDictionary_lock->notify_all();
830 }
831 return NULL;
832 }
833 }
834 }
836 #ifdef ASSERT
837 {
838 Handle loader (THREAD, k->class_loader());
839 MutexLocker mu(SystemDictionary_lock, THREAD);
840 oop kk = find_class_or_placeholder(name, loader);
841 assert(kk == k(), "should be present in dictionary");
842 }
843 #endif
845 // return if the protection domain in NULL
846 if (protection_domain() == NULL) return k();
848 // Check the protection domain has the right access
849 {
850 MutexLocker mu(SystemDictionary_lock, THREAD);
851 // Note that we have an entry, and entries can be deleted only during GC,
852 // so we cannot allow GC to occur while we're holding this entry.
853 // We're using a No_Safepoint_Verifier to catch any place where we
854 // might potentially do a GC at all.
855 // SystemDictionary::do_unloading() asserts that classes are only
856 // unloaded at a safepoint.
857 No_Safepoint_Verifier nosafepoint;
858 if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
859 class_loader,
860 protection_domain)) {
861 return k();
862 }
863 }
865 // Verify protection domain. If it fails an exception is thrown
866 validate_protection_domain(k, class_loader, protection_domain, CHECK_(klassOop(NULL)));
868 return k();
869 }
872 // This routine does not lock the system dictionary.
873 //
874 // Since readers don't hold a lock, we must make sure that system
875 // dictionary entries are only removed at a safepoint (when only one
876 // thread is running), and are added to in a safe way (all links must
877 // be updated in an MT-safe manner).
878 //
879 // Callers should be aware that an entry could be added just after
880 // _dictionary->bucket(index) is read here, so the caller will not see
881 // the new entry.
883 klassOop SystemDictionary::find(symbolHandle class_name,
884 Handle class_loader,
885 Handle protection_domain,
886 TRAPS) {
888 // UseNewReflection
889 // The result of this call should be consistent with the result
890 // of the call to resolve_instance_class_or_null().
891 // See evaluation 6790209 and 4474172 for more details.
892 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
894 unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
895 int d_index = dictionary()->hash_to_index(d_hash);
897 {
898 // Note that we have an entry, and entries can be deleted only during GC,
899 // so we cannot allow GC to occur while we're holding this entry.
900 // We're using a No_Safepoint_Verifier to catch any place where we
901 // might potentially do a GC at all.
902 // SystemDictionary::do_unloading() asserts that classes are only
903 // unloaded at a safepoint.
904 No_Safepoint_Verifier nosafepoint;
905 return dictionary()->find(d_index, d_hash, class_name, class_loader,
906 protection_domain, THREAD);
907 }
908 }
911 // Look for a loaded instance or array klass by name. Do not do any loading.
912 // return NULL in case of error.
913 klassOop SystemDictionary::find_instance_or_array_klass(symbolHandle class_name,
914 Handle class_loader,
915 Handle protection_domain,
916 TRAPS) {
917 klassOop k = NULL;
918 assert(class_name() != NULL, "class name must be non NULL");
920 // Try to get one of the well-known klasses.
921 if (LinkWellKnownClasses) {
922 k = find_well_known_klass(class_name());
923 if (k != NULL) {
924 return k;
925 }
926 }
928 if (FieldType::is_array(class_name())) {
929 // The name refers to an array. Parse the name.
930 jint dimension;
931 symbolOop object_key;
933 // dimension and object_key are assigned as a side-effect of this call
934 BasicType t = FieldType::get_array_info(class_name(), &dimension,
935 &object_key, CHECK_(NULL));
936 if (t != T_OBJECT) {
937 k = Universe::typeArrayKlassObj(t);
938 } else {
939 symbolHandle h_key(THREAD, object_key);
940 k = SystemDictionary::find(h_key, class_loader, protection_domain, THREAD);
941 }
942 if (k != NULL) {
943 k = Klass::cast(k)->array_klass_or_null(dimension);
944 }
945 } else {
946 k = find(class_name, class_loader, protection_domain, THREAD);
947 }
948 return k;
949 }
951 // Quick range check for names of well-known classes:
952 static symbolOop wk_klass_name_limits[2] = {NULL, NULL};
954 #ifndef PRODUCT
955 static int find_wkk_calls, find_wkk_probes, find_wkk_wins;
956 // counts for "hello world": 3983, 1616, 1075
957 // => 60% hit after limit guard, 25% total win rate
958 #endif
960 klassOop SystemDictionary::find_well_known_klass(symbolOop class_name) {
961 // A bounds-check on class_name will quickly get a negative result.
962 NOT_PRODUCT(find_wkk_calls++);
963 if (class_name >= wk_klass_name_limits[0] &&
964 class_name <= wk_klass_name_limits[1]) {
965 NOT_PRODUCT(find_wkk_probes++);
966 vmSymbols::SID sid = vmSymbols::find_sid(class_name);
967 if (sid != vmSymbols::NO_SID) {
968 klassOop k = NULL;
969 switch (sid) {
970 #define WK_KLASS_CASE(name, symbol, ignore_option) \
971 case vmSymbols::VM_SYMBOL_ENUM_NAME(symbol): \
972 k = WK_KLASS(name); break;
973 WK_KLASSES_DO(WK_KLASS_CASE)
974 #undef WK_KLASS_CASE
975 }
976 NOT_PRODUCT(if (k != NULL) find_wkk_wins++);
977 return k;
978 }
979 }
980 return NULL;
981 }
983 // Note: this method is much like resolve_from_stream, but
984 // updates no supplemental data structures.
985 // TODO consolidate the two methods with a helper routine?
986 klassOop SystemDictionary::parse_stream(symbolHandle class_name,
987 Handle class_loader,
988 Handle protection_domain,
989 ClassFileStream* st,
990 KlassHandle host_klass,
991 GrowableArray<Handle>* cp_patches,
992 TRAPS) {
993 symbolHandle parsed_name;
995 // Parse the stream. Note that we do this even though this klass might
996 // already be present in the SystemDictionary, otherwise we would not
997 // throw potential ClassFormatErrors.
998 //
999 // Note: "name" is updated.
1000 // Further note: a placeholder will be added for this class when
1001 // super classes are loaded (resolve_super_or_fail). We expect this
1002 // to be called for all classes but java.lang.Object; and we preload
1003 // java.lang.Object through resolve_or_fail, not this path.
1005 instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
1006 class_loader,
1007 protection_domain,
1008 host_klass,
1009 cp_patches,
1010 parsed_name,
1011 true,
1012 THREAD);
1015 // We don't redefine the class, so we just need to clean up whether there
1016 // was an error or not (don't want to modify any system dictionary
1017 // data structures).
1018 // Parsed name could be null if we threw an error before we got far
1019 // enough along to parse it -- in that case, there is nothing to clean up.
1020 if (!parsed_name.is_null()) {
1021 unsigned int p_hash = placeholders()->compute_hash(parsed_name,
1022 class_loader);
1023 int p_index = placeholders()->hash_to_index(p_hash);
1024 {
1025 MutexLocker mu(SystemDictionary_lock, THREAD);
1026 placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
1027 SystemDictionary_lock->notify_all();
1028 }
1029 }
1031 if (host_klass.not_null() && k.not_null()) {
1032 assert(AnonymousClasses, "");
1033 // If it's anonymous, initialize it now, since nobody else will.
1034 k->set_host_klass(host_klass());
1036 {
1037 MutexLocker mu_r(Compile_lock, THREAD);
1039 // Add to class hierarchy, initialize vtables, and do possible
1040 // deoptimizations.
1041 add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
1043 // But, do not add to system dictionary.
1044 }
1046 k->eager_initialize(THREAD);
1048 // notify jvmti
1049 if (JvmtiExport::should_post_class_load()) {
1050 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1051 JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1052 }
1053 }
1055 return k();
1056 }
1058 // Add a klass to the system from a stream (called by jni_DefineClass and
1059 // JVM_DefineClass).
1060 // Note: class_name can be NULL. In that case we do not know the name of
1061 // the class until we have parsed the stream.
1063 klassOop SystemDictionary::resolve_from_stream(symbolHandle class_name,
1064 Handle class_loader,
1065 Handle protection_domain,
1066 ClassFileStream* st,
1067 bool verify,
1068 TRAPS) {
1070 // Classloaders that support parallelism, e.g. bootstrap classloader,
1071 // or all classloaders with UnsyncloadClass do not acquire lock here
1072 bool DoObjectLock = true;
1073 if (is_parallelCapable(class_loader)) {
1074 DoObjectLock = false;
1075 }
1077 // Make sure we are synchronized on the class loader before we proceed
1078 Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1079 check_loader_lock_contention(lockObject, THREAD);
1080 ObjectLocker ol(lockObject, THREAD, DoObjectLock);
1082 symbolHandle parsed_name;
1084 // Parse the stream. Note that we do this even though this klass might
1085 // already be present in the SystemDictionary, otherwise we would not
1086 // throw potential ClassFormatErrors.
1087 //
1088 // Note: "name" is updated.
1089 // Further note: a placeholder will be added for this class when
1090 // super classes are loaded (resolve_super_or_fail). We expect this
1091 // to be called for all classes but java.lang.Object; and we preload
1092 // java.lang.Object through resolve_or_fail, not this path.
1094 instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
1095 class_loader,
1096 protection_domain,
1097 parsed_name,
1098 verify,
1099 THREAD);
1101 const char* pkg = "java/";
1102 if (!HAS_PENDING_EXCEPTION &&
1103 !class_loader.is_null() &&
1104 !parsed_name.is_null() &&
1105 !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
1106 // It is illegal to define classes in the "java." package from
1107 // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
1108 ResourceMark rm(THREAD);
1109 char* name = parsed_name->as_C_string();
1110 char* index = strrchr(name, '/');
1111 *index = '\0'; // chop to just the package name
1112 while ((index = strchr(name, '/')) != NULL) {
1113 *index = '.'; // replace '/' with '.' in package name
1114 }
1115 const char* fmt = "Prohibited package name: %s";
1116 size_t len = strlen(fmt) + strlen(name);
1117 char* message = NEW_RESOURCE_ARRAY(char, len);
1118 jio_snprintf(message, len, fmt, name);
1119 Exceptions::_throw_msg(THREAD_AND_LOCATION,
1120 vmSymbols::java_lang_SecurityException(), message);
1121 }
1123 if (!HAS_PENDING_EXCEPTION) {
1124 assert(!parsed_name.is_null(), "Sanity");
1125 assert(class_name.is_null() || class_name() == parsed_name(),
1126 "name mismatch");
1127 // Verification prevents us from creating names with dots in them, this
1128 // asserts that that's the case.
1129 assert(is_internal_format(parsed_name),
1130 "external class name format used internally");
1132 // Add class just loaded
1133 // If a class loader supports parallel classloading handle parallel define requests
1134 // find_or_define_instance_class may return a different instanceKlass
1135 if (is_parallelCapable(class_loader)) {
1136 k = find_or_define_instance_class(class_name, class_loader, k, THREAD);
1137 } else {
1138 define_instance_class(k, THREAD);
1139 }
1140 }
1142 // If parsing the class file or define_instance_class failed, we
1143 // need to remove the placeholder added on our behalf. But we
1144 // must make sure parsed_name is valid first (it won't be if we had
1145 // a format error before the class was parsed far enough to
1146 // find the name).
1147 if (HAS_PENDING_EXCEPTION && !parsed_name.is_null()) {
1148 unsigned int p_hash = placeholders()->compute_hash(parsed_name,
1149 class_loader);
1150 int p_index = placeholders()->hash_to_index(p_hash);
1151 {
1152 MutexLocker mu(SystemDictionary_lock, THREAD);
1153 placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
1154 SystemDictionary_lock->notify_all();
1155 }
1156 return NULL;
1157 }
1159 // Make sure that we didn't leave a place holder in the
1160 // SystemDictionary; this is only done on success
1161 debug_only( {
1162 if (!HAS_PENDING_EXCEPTION) {
1163 assert(!parsed_name.is_null(), "parsed_name is still null?");
1164 symbolHandle h_name (THREAD, k->name());
1165 Handle h_loader (THREAD, k->class_loader());
1167 MutexLocker mu(SystemDictionary_lock, THREAD);
1169 oop check = find_class_or_placeholder(parsed_name, class_loader);
1170 assert(check == k(), "should be present in the dictionary");
1172 oop check2 = find_class_or_placeholder(h_name, h_loader);
1173 assert(check == check2, "name inconsistancy in SystemDictionary");
1174 }
1175 } );
1177 return k();
1178 }
1181 void SystemDictionary::set_shared_dictionary(HashtableBucket* t, int length,
1182 int number_of_entries) {
1183 assert(length == _nof_buckets * sizeof(HashtableBucket),
1184 "bad shared dictionary size.");
1185 _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
1186 }
1189 // If there is a shared dictionary, then find the entry for the
1190 // given shared system class, if any.
1192 klassOop SystemDictionary::find_shared_class(symbolHandle class_name) {
1193 if (shared_dictionary() != NULL) {
1194 unsigned int d_hash = dictionary()->compute_hash(class_name, Handle());
1195 int d_index = dictionary()->hash_to_index(d_hash);
1196 return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1197 } else {
1198 return NULL;
1199 }
1200 }
1203 // Load a class from the shared spaces (found through the shared system
1204 // dictionary). Force the superclass and all interfaces to be loaded.
1205 // Update the class definition to include sibling classes and no
1206 // subclasses (yet). [Classes in the shared space are not part of the
1207 // object hierarchy until loaded.]
1209 instanceKlassHandle SystemDictionary::load_shared_class(
1210 symbolHandle class_name, Handle class_loader, TRAPS) {
1211 instanceKlassHandle ik (THREAD, find_shared_class(class_name));
1212 return load_shared_class(ik, class_loader, THREAD);
1213 }
1215 // Note well! Changes to this method may affect oop access order
1216 // in the shared archive. Please take care to not make changes that
1217 // adversely affect cold start time by changing the oop access order
1218 // that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
1219 // MarkAndMoveOrderedReadWrite closures.
1220 instanceKlassHandle SystemDictionary::load_shared_class(
1221 instanceKlassHandle ik, Handle class_loader, TRAPS) {
1222 assert(class_loader.is_null(), "non-null classloader for shared class?");
1223 if (ik.not_null()) {
1224 instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1225 symbolHandle class_name(THREAD, ik->name());
1227 // Found the class, now load the superclass and interfaces. If they
1228 // are shared, add them to the main system dictionary and reset
1229 // their hierarchy references (supers, subs, and interfaces).
1231 if (ik->super() != NULL) {
1232 symbolHandle cn(THREAD, ik->super()->klass_part()->name());
1233 resolve_super_or_fail(class_name, cn,
1234 class_loader, Handle(), true, CHECK_(nh));
1235 }
1237 objArrayHandle interfaces (THREAD, ik->local_interfaces());
1238 int num_interfaces = interfaces->length();
1239 for (int index = 0; index < num_interfaces; index++) {
1240 klassOop k = klassOop(interfaces->obj_at(index));
1242 // Note: can not use instanceKlass::cast here because
1243 // interfaces' instanceKlass's C++ vtbls haven't been
1244 // reinitialized yet (they will be once the interface classes
1245 // are loaded)
1246 symbolHandle name (THREAD, k->klass_part()->name());
1247 resolve_super_or_fail(class_name, name, class_loader, Handle(), false, CHECK_(nh));
1248 }
1250 // Adjust methods to recover missing data. They need addresses for
1251 // interpreter entry points and their default native method address
1252 // must be reset.
1254 // Updating methods must be done under a lock so multiple
1255 // threads don't update these in parallel
1256 // Shared classes are all currently loaded by the bootstrap
1257 // classloader, so this will never cause a deadlock on
1258 // a custom class loader lock.
1260 {
1261 Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1262 check_loader_lock_contention(lockObject, THREAD);
1263 ObjectLocker ol(lockObject, THREAD, true);
1265 objArrayHandle methods (THREAD, ik->methods());
1266 int num_methods = methods->length();
1267 for (int index2 = 0; index2 < num_methods; ++index2) {
1268 methodHandle m(THREAD, methodOop(methods->obj_at(index2)));
1269 m()->link_method(m, CHECK_(nh));
1270 }
1271 }
1273 if (TraceClassLoading) {
1274 ResourceMark rm;
1275 tty->print("[Loaded %s", ik->external_name());
1276 tty->print(" from shared objects file");
1277 tty->print_cr("]");
1278 }
1279 // notify a class loaded from shared object
1280 ClassLoadingService::notify_class_loaded(instanceKlass::cast(ik()),
1281 true /* shared class */);
1282 }
1283 return ik;
1284 }
1286 #ifdef KERNEL
1287 // Some classes on the bootstrap class path haven't been installed on the
1288 // system yet. Call the DownloadManager method to make them appear in the
1289 // bootstrap class path and try again to load the named class.
1290 // Note that with delegation class loaders all classes in another loader will
1291 // first try to call this so it'd better be fast!!
1292 static instanceKlassHandle download_and_retry_class_load(
1293 symbolHandle class_name,
1294 TRAPS) {
1296 klassOop dlm = SystemDictionary::sun_jkernel_DownloadManager_klass();
1297 instanceKlassHandle nk;
1299 // If download manager class isn't loaded just return.
1300 if (dlm == NULL) return nk;
1302 { HandleMark hm(THREAD);
1303 ResourceMark rm(THREAD);
1304 Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nk));
1305 Handle class_string = java_lang_String::externalize_classname(s, CHECK_(nk));
1307 // return value
1308 JavaValue result(T_OBJECT);
1310 // Call the DownloadManager. We assume that it has a lock because
1311 // multiple classes could be not found and downloaded at the same time.
1312 // class sun.misc.DownloadManager;
1313 // public static String getBootClassPathEntryForClass(String className);
1314 JavaCalls::call_static(&result,
1315 KlassHandle(THREAD, dlm),
1316 vmSymbolHandles::getBootClassPathEntryForClass_name(),
1317 vmSymbolHandles::string_string_signature(),
1318 class_string,
1319 CHECK_(nk));
1321 // Get result.string and add to bootclasspath
1322 assert(result.get_type() == T_OBJECT, "just checking");
1323 oop obj = (oop) result.get_jobject();
1324 if (obj == NULL) { return nk; }
1326 Handle h_obj(THREAD, obj);
1327 char* new_class_name = java_lang_String::as_platform_dependent_str(h_obj,
1328 CHECK_(nk));
1330 // lock the loader
1331 // we use this lock because JVMTI does.
1332 Handle loader_lock(THREAD, SystemDictionary::system_loader_lock());
1334 ObjectLocker ol(loader_lock, THREAD);
1335 // add the file to the bootclasspath
1336 ClassLoader::update_class_path_entry_list(new_class_name, true);
1337 } // end HandleMark
1339 if (TraceClassLoading) {
1340 ClassLoader::print_bootclasspath();
1341 }
1342 return ClassLoader::load_classfile(class_name, CHECK_(nk));
1343 }
1344 #endif // KERNEL
1347 instanceKlassHandle SystemDictionary::load_instance_class(symbolHandle class_name, Handle class_loader, TRAPS) {
1348 instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1349 if (class_loader.is_null()) {
1351 // Search the shared system dictionary for classes preloaded into the
1352 // shared spaces.
1353 instanceKlassHandle k;
1354 {
1355 PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1356 k = load_shared_class(class_name, class_loader, THREAD);
1357 }
1359 if (k.is_null()) {
1360 // Use VM class loader
1361 PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1362 k = ClassLoader::load_classfile(class_name, CHECK_(nh));
1363 }
1365 #ifdef KERNEL
1366 // If the VM class loader has failed to load the class, call the
1367 // DownloadManager class to make it magically appear on the classpath
1368 // and try again. This is only configured with the Kernel VM.
1369 if (k.is_null()) {
1370 k = download_and_retry_class_load(class_name, CHECK_(nh));
1371 }
1372 #endif // KERNEL
1374 // find_or_define_instance_class may return a different instanceKlass
1375 if (!k.is_null()) {
1376 k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
1377 }
1378 return k;
1379 } else {
1380 // Use user specified class loader to load class. Call loadClass operation on class_loader.
1381 ResourceMark rm(THREAD);
1383 assert(THREAD->is_Java_thread(), "must be a JavaThread");
1384 JavaThread* jt = (JavaThread*) THREAD;
1386 PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1387 ClassLoader::perf_app_classload_selftime(),
1388 ClassLoader::perf_app_classload_count(),
1389 jt->get_thread_stat()->perf_recursion_counts_addr(),
1390 jt->get_thread_stat()->perf_timers_addr(),
1391 PerfClassTraceTime::CLASS_LOAD);
1393 Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
1394 // Translate to external class name format, i.e., convert '/' chars to '.'
1395 Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
1397 JavaValue result(T_OBJECT);
1399 KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());
1401 // Call public unsynchronized loadClass(String) directly for all class loaders
1402 // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
1403 // acquire a class-name based lock rather than the class loader object lock.
1404 // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
1405 // so the call to loadClassInternal() was not required.
1406 //
1407 // UnsyncloadClass flag means both call loadClass(String) and do
1408 // not acquire the class loader lock even for class loaders that are
1409 // not parallelCapable. This was a risky transitional
1410 // flag for diagnostic purposes only. It is risky to call
1411 // custom class loaders without synchronization.
1412 // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1413 // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
1414 // Do NOT assume this will be supported in future releases.
1415 //
1416 // Added MustCallLoadClassInternal in case we discover in the field
1417 // a customer that counts on this call
1418 if (MustCallLoadClassInternal && has_loadClassInternal()) {
1419 JavaCalls::call_special(&result,
1420 class_loader,
1421 spec_klass,
1422 vmSymbolHandles::loadClassInternal_name(),
1423 vmSymbolHandles::string_class_signature(),
1424 string,
1425 CHECK_(nh));
1426 } else {
1427 JavaCalls::call_virtual(&result,
1428 class_loader,
1429 spec_klass,
1430 vmSymbolHandles::loadClass_name(),
1431 vmSymbolHandles::string_class_signature(),
1432 string,
1433 CHECK_(nh));
1434 }
1436 assert(result.get_type() == T_OBJECT, "just checking");
1437 oop obj = (oop) result.get_jobject();
1439 // Primitive classes return null since forName() can not be
1440 // used to obtain any of the Class objects representing primitives or void
1441 if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1442 instanceKlassHandle k =
1443 instanceKlassHandle(THREAD, java_lang_Class::as_klassOop(obj));
1444 // For user defined Java class loaders, check that the name returned is
1445 // the same as that requested. This check is done for the bootstrap
1446 // loader when parsing the class file.
1447 if (class_name() == k->name()) {
1448 return k;
1449 }
1450 }
1451 // Class is not found or has the wrong name, return NULL
1452 return nh;
1453 }
1454 }
1456 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
1458 Handle class_loader_h(THREAD, k->class_loader());
1460 // for bootstrap and other parallel classloaders don't acquire lock,
1461 // use placeholder token
1462 // If a parallelCapable class loader calls define_instance_class instead of
1463 // find_or_define_instance_class to get here, we have a timing
1464 // hole with systemDictionary updates and check_constraints
1465 if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1466 assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1467 compute_loader_lock_object(class_loader_h, THREAD)),
1468 "define called without lock");
1469 }
1471 // Check class-loading constraints. Throw exception if violation is detected.
1472 // Grabs and releases SystemDictionary_lock
1473 // The check_constraints/find_class call and update_dictionary sequence
1474 // must be "atomic" for a specific class/classloader pair so we never
1475 // define two different instanceKlasses for that class/classloader pair.
1476 // Existing classloaders will call define_instance_class with the
1477 // classloader lock held
1478 // Parallel classloaders will call find_or_define_instance_class
1479 // which will require a token to perform the define class
1480 symbolHandle name_h(THREAD, k->name());
1481 unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader_h);
1482 int d_index = dictionary()->hash_to_index(d_hash);
1483 check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1485 // Register class just loaded with class loader (placed in Vector)
1486 // Note we do this before updating the dictionary, as this can
1487 // fail with an OutOfMemoryError (if it does, we will *not* put this
1488 // class in the dictionary and will not update the class hierarchy).
1489 if (k->class_loader() != NULL) {
1490 methodHandle m(THREAD, Universe::loader_addClass_method());
1491 JavaValue result(T_VOID);
1492 JavaCallArguments args(class_loader_h);
1493 args.push_oop(Handle(THREAD, k->java_mirror()));
1494 JavaCalls::call(&result, m, &args, CHECK);
1495 }
1497 // Add the new class. We need recompile lock during update of CHA.
1498 {
1499 unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader_h);
1500 int p_index = placeholders()->hash_to_index(p_hash);
1502 MutexLocker mu_r(Compile_lock, THREAD);
1504 // Add to class hierarchy, initialize vtables, and do possible
1505 // deoptimizations.
1506 add_to_hierarchy(k, CHECK); // No exception, but can block
1508 // Add to systemDictionary - so other classes can see it.
1509 // Grabs and releases SystemDictionary_lock
1510 update_dictionary(d_index, d_hash, p_index, p_hash,
1511 k, class_loader_h, THREAD);
1512 }
1513 k->eager_initialize(THREAD);
1515 // notify jvmti
1516 if (JvmtiExport::should_post_class_load()) {
1517 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1518 JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1520 }
1521 }
1523 // Support parallel classloading
1524 // All parallel class loaders, including bootstrap classloader
1525 // lock a placeholder entry for this class/class_loader pair
1526 // to allow parallel defines of different classes for this class loader
1527 // With AllowParallelDefine flag==true, in case they do not synchronize around
1528 // FindLoadedClass/DefineClass, calls, we check for parallel
1529 // loading for them, wait if a defineClass is in progress
1530 // and return the initial requestor's results
1531 // This flag does not apply to the bootstrap classloader.
1532 // With AllowParallelDefine flag==false, call through to define_instance_class
1533 // which will throw LinkageError: duplicate class definition.
1534 // False is the requested default.
1535 // For better performance, the class loaders should synchronize
1536 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1537 // potentially waste time reading and parsing the bytestream.
1538 // Note: VM callers should ensure consistency of k/class_name,class_loader
1539 instanceKlassHandle SystemDictionary::find_or_define_instance_class(symbolHandle class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
1541 instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1542 symbolHandle name_h(THREAD, k->name()); // passed in class_name may be null
1544 unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader);
1545 int d_index = dictionary()->hash_to_index(d_hash);
1547 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1548 unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader);
1549 int p_index = placeholders()->hash_to_index(p_hash);
1550 PlaceholderEntry* probe;
1552 {
1553 MutexLocker mu(SystemDictionary_lock, THREAD);
1554 // First check if class already defined
1555 if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1556 klassOop check = find_class(d_index, d_hash, name_h, class_loader);
1557 if (check != NULL) {
1558 return(instanceKlassHandle(THREAD, check));
1559 }
1560 }
1562 // Acquire define token for this class/classloader
1563 symbolHandle nullsymbolHandle;
1564 probe = placeholders()->find_and_add(p_index, p_hash, name_h, class_loader, PlaceholderTable::DEFINE_CLASS, nullsymbolHandle, THREAD);
1565 // Wait if another thread defining in parallel
1566 // All threads wait - even those that will throw duplicate class: otherwise
1567 // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1568 // if other thread has not finished updating dictionary
1569 while (probe->definer() != NULL) {
1570 SystemDictionary_lock->wait();
1571 }
1572 // Only special cases allow parallel defines and can use other thread's results
1573 // Other cases fall through, and may run into duplicate defines
1574 // caught by finding an entry in the SystemDictionary
1575 if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instanceKlass() != NULL)) {
1576 probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
1577 placeholders()->find_and_remove(p_index, p_hash, name_h, class_loader, THREAD);
1578 SystemDictionary_lock->notify_all();
1579 #ifdef ASSERT
1580 klassOop check = find_class(d_index, d_hash, name_h, class_loader);
1581 assert(check != NULL, "definer missed recording success");
1582 #endif
1583 return(instanceKlassHandle(THREAD, probe->instanceKlass()));
1584 } else {
1585 // This thread will define the class (even if earlier thread tried and had an error)
1586 probe->set_definer(THREAD);
1587 }
1588 }
1590 define_instance_class(k, THREAD);
1592 Handle linkage_exception = Handle(); // null handle
1594 // definer must notify any waiting threads
1595 {
1596 MutexLocker mu(SystemDictionary_lock, THREAD);
1597 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, class_loader);
1598 assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1599 if (probe != NULL) {
1600 if (HAS_PENDING_EXCEPTION) {
1601 linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1602 CLEAR_PENDING_EXCEPTION;
1603 } else {
1604 probe->set_instanceKlass(k());
1605 }
1606 probe->set_definer(NULL);
1607 probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
1608 placeholders()->find_and_remove(p_index, p_hash, name_h, class_loader, THREAD);
1609 SystemDictionary_lock->notify_all();
1610 }
1611 }
1613 // Can't throw exception while holding lock due to rank ordering
1614 if (linkage_exception() != NULL) {
1615 THROW_OOP_(linkage_exception(), nh); // throws exception and returns
1616 }
1618 return k;
1619 }
1620 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1621 // If class_loader is NULL we synchronize on _system_loader_lock_obj
1622 if (class_loader.is_null()) {
1623 return Handle(THREAD, _system_loader_lock_obj);
1624 } else {
1625 return class_loader;
1626 }
1627 }
1629 // This method is added to check how often we have to wait to grab loader
1630 // lock. The results are being recorded in the performance counters defined in
1631 // ClassLoader::_sync_systemLoaderLockContentionRate and
1632 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1633 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1634 if (!UsePerfData) {
1635 return;
1636 }
1638 assert(!loader_lock.is_null(), "NULL lock object");
1640 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1641 == ObjectSynchronizer::owner_other) {
1642 // contention will likely happen, so increment the corresponding
1643 // contention counter.
1644 if (loader_lock() == _system_loader_lock_obj) {
1645 ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1646 } else {
1647 ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1648 }
1649 }
1650 }
1652 // ----------------------------------------------------------------------------
1653 // Lookup
1655 klassOop SystemDictionary::find_class(int index, unsigned int hash,
1656 symbolHandle class_name,
1657 Handle class_loader) {
1658 assert_locked_or_safepoint(SystemDictionary_lock);
1659 assert (index == dictionary()->index_for(class_name, class_loader),
1660 "incorrect index?");
1662 klassOop k = dictionary()->find_class(index, hash, class_name, class_loader);
1663 return k;
1664 }
1667 // Basic find on classes in the midst of being loaded
1668 symbolOop SystemDictionary::find_placeholder(int index, unsigned int hash,
1669 symbolHandle class_name,
1670 Handle class_loader) {
1671 assert_locked_or_safepoint(SystemDictionary_lock);
1673 return placeholders()->find_entry(index, hash, class_name, class_loader);
1674 }
1677 // Used for assertions and verification only
1678 oop SystemDictionary::find_class_or_placeholder(symbolHandle class_name,
1679 Handle class_loader) {
1680 #ifndef ASSERT
1681 guarantee(VerifyBeforeGC ||
1682 VerifyDuringGC ||
1683 VerifyBeforeExit ||
1684 VerifyAfterGC, "too expensive");
1685 #endif
1686 assert_locked_or_safepoint(SystemDictionary_lock);
1687 symbolOop class_name_ = class_name();
1688 oop class_loader_ = class_loader();
1690 // First look in the loaded class array
1691 unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
1692 int d_index = dictionary()->hash_to_index(d_hash);
1693 oop lookup = find_class(d_index, d_hash, class_name, class_loader);
1695 if (lookup == NULL) {
1696 // Next try the placeholders
1697 unsigned int p_hash = placeholders()->compute_hash(class_name,class_loader);
1698 int p_index = placeholders()->hash_to_index(p_hash);
1699 lookup = find_placeholder(p_index, p_hash, class_name, class_loader);
1700 }
1702 return lookup;
1703 }
1706 // Get the next class in the diictionary.
1707 klassOop SystemDictionary::try_get_next_class() {
1708 return dictionary()->try_get_next_class();
1709 }
1712 // ----------------------------------------------------------------------------
1713 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1714 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1715 // before a new class is used.
1717 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
1718 assert(k.not_null(), "just checking");
1719 // Link into hierachy. Make sure the vtables are initialized before linking into
1720 k->append_to_sibling_list(); // add to superklass/sibling list
1721 k->process_interfaces(THREAD); // handle all "implements" declarations
1722 k->set_init_state(instanceKlass::loaded);
1723 // Now flush all code that depended on old class hierarchy.
1724 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1725 // Also, first reinitialize vtable because it may have gotten out of synch
1726 // while the new class wasn't connected to the class hierarchy.
1727 Universe::flush_dependents_on(k);
1728 }
1731 // ----------------------------------------------------------------------------
1732 // GC support
1734 // Following roots during mark-sweep is separated in two phases.
1735 //
1736 // The first phase follows preloaded classes and all other system
1737 // classes, since these will never get unloaded anyway.
1738 //
1739 // The second phase removes (unloads) unreachable classes from the
1740 // system dictionary and follows the remaining classes' contents.
1742 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1743 // Follow preloaded classes/mirrors and system loader object
1744 blk->do_oop(&_java_system_loader);
1745 preloaded_oops_do(blk);
1746 always_strong_classes_do(blk);
1747 }
1750 void SystemDictionary::always_strong_classes_do(OopClosure* blk) {
1751 // Follow all system classes and temporary placeholders in dictionary
1752 dictionary()->always_strong_classes_do(blk);
1754 // Placeholders. These are *always* strong roots, as they
1755 // represent classes we're actively loading.
1756 placeholders_do(blk);
1758 // Visit extra methods
1759 invoke_method_table()->oops_do(blk);
1761 // Loader constraints. We must keep the symbolOop used in the name alive.
1762 constraints()->always_strong_classes_do(blk);
1764 // Resolution errors keep the symbolOop for the error alive
1765 resolution_errors()->always_strong_classes_do(blk);
1766 }
1769 void SystemDictionary::placeholders_do(OopClosure* blk) {
1770 placeholders()->oops_do(blk);
1771 }
1774 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive) {
1775 bool result = dictionary()->do_unloading(is_alive);
1776 constraints()->purge_loader_constraints(is_alive);
1777 resolution_errors()->purge_resolution_errors(is_alive);
1778 return result;
1779 }
1782 // The mirrors are scanned by shared_oops_do() which is
1783 // not called by oops_do(). In order to process oops in
1784 // a necessary order, shared_oops_do() is call by
1785 // Universe::oops_do().
1786 void SystemDictionary::oops_do(OopClosure* f) {
1787 // Adjust preloaded classes and system loader object
1788 f->do_oop(&_java_system_loader);
1789 preloaded_oops_do(f);
1791 lazily_loaded_oops_do(f);
1793 // Adjust dictionary
1794 dictionary()->oops_do(f);
1796 // Visit extra methods
1797 invoke_method_table()->oops_do(f);
1799 // Partially loaded classes
1800 placeholders()->oops_do(f);
1802 // Adjust constraint table
1803 constraints()->oops_do(f);
1805 // Adjust resolution error table
1806 resolution_errors()->oops_do(f);
1807 }
1810 void SystemDictionary::preloaded_oops_do(OopClosure* f) {
1811 f->do_oop((oop*) &wk_klass_name_limits[0]);
1812 f->do_oop((oop*) &wk_klass_name_limits[1]);
1814 for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
1815 f->do_oop((oop*) &_well_known_klasses[k]);
1816 }
1818 {
1819 for (int i = 0; i < T_VOID+1; i++) {
1820 if (_box_klasses[i] != NULL) {
1821 assert(i >= T_BOOLEAN, "checking");
1822 f->do_oop((oop*) &_box_klasses[i]);
1823 }
1824 }
1825 }
1827 // The basic type mirrors would have already been processed in
1828 // Universe::oops_do(), via a call to shared_oops_do(), so should
1829 // not be processed again.
1831 f->do_oop((oop*) &_system_loader_lock_obj);
1832 FilteredFieldsMap::klasses_oops_do(f);
1833 }
1835 void SystemDictionary::lazily_loaded_oops_do(OopClosure* f) {
1836 f->do_oop((oop*) &_abstract_ownable_synchronizer_klass);
1837 }
1839 // Just the classes from defining class loaders
1840 // Don't iterate over placeholders
1841 void SystemDictionary::classes_do(void f(klassOop)) {
1842 dictionary()->classes_do(f);
1843 }
1845 // Added for initialize_itable_for_klass
1846 // Just the classes from defining class loaders
1847 // Don't iterate over placeholders
1848 void SystemDictionary::classes_do(void f(klassOop, TRAPS), TRAPS) {
1849 dictionary()->classes_do(f, CHECK);
1850 }
1852 // All classes, and their class loaders
1853 // Don't iterate over placeholders
1854 void SystemDictionary::classes_do(void f(klassOop, oop)) {
1855 dictionary()->classes_do(f);
1856 }
1858 // All classes, and their class loaders
1859 // (added for helpers that use HandleMarks and ResourceMarks)
1860 // Don't iterate over placeholders
1861 void SystemDictionary::classes_do(void f(klassOop, oop, TRAPS), TRAPS) {
1862 dictionary()->classes_do(f, CHECK);
1863 }
1865 void SystemDictionary::placeholders_do(void f(symbolOop, oop)) {
1866 placeholders()->entries_do(f);
1867 }
1869 void SystemDictionary::methods_do(void f(methodOop)) {
1870 dictionary()->methods_do(f);
1871 invoke_method_table()->methods_do(f);
1872 }
1874 // ----------------------------------------------------------------------------
1875 // Lazily load klasses
1877 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
1878 assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
1880 // if multiple threads calling this function, only one thread will load
1881 // the class. The other threads will find the loaded version once the
1882 // class is loaded.
1883 klassOop aos = _abstract_ownable_synchronizer_klass;
1884 if (aos == NULL) {
1885 klassOop k = resolve_or_fail(vmSymbolHandles::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
1886 // Force a fence to prevent any read before the write completes
1887 OrderAccess::fence();
1888 _abstract_ownable_synchronizer_klass = k;
1889 }
1890 }
1892 // ----------------------------------------------------------------------------
1893 // Initialization
1895 void SystemDictionary::initialize(TRAPS) {
1896 // Allocate arrays
1897 assert(dictionary() == NULL,
1898 "SystemDictionary should only be initialized once");
1899 _dictionary = new Dictionary(_nof_buckets);
1900 _placeholders = new PlaceholderTable(_nof_buckets);
1901 _number_of_modifications = 0;
1902 _loader_constraints = new LoaderConstraintTable(_loader_constraint_size);
1903 _resolution_errors = new ResolutionErrorTable(_resolution_error_size);
1904 _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
1906 // Allocate private object used as system class loader lock
1907 _system_loader_lock_obj = oopFactory::new_system_objArray(0, CHECK);
1908 // Initialize basic classes
1909 initialize_preloaded_classes(CHECK);
1910 }
1912 // Compact table of directions on the initialization of klasses:
1913 static const short wk_init_info[] = {
1914 #define WK_KLASS_INIT_INFO(name, symbol, option) \
1915 ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
1916 << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
1917 | (int)SystemDictionary::option ),
1918 WK_KLASSES_DO(WK_KLASS_INIT_INFO)
1919 #undef WK_KLASS_INIT_INFO
1920 0
1921 };
1923 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
1924 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1925 int info = wk_init_info[id - FIRST_WKID];
1926 int sid = (info >> CEIL_LG_OPTION_LIMIT);
1927 symbolHandle symbol = vmSymbolHandles::symbol_handle_at((vmSymbols::SID)sid);
1928 klassOop* klassp = &_well_known_klasses[id];
1929 bool must_load = (init_opt < SystemDictionary::Opt);
1930 bool try_load = true;
1931 if (init_opt == SystemDictionary::Opt_Kernel) {
1932 #ifndef KERNEL
1933 try_load = false;
1934 #endif //KERNEL
1935 }
1936 if ((*klassp) == NULL && try_load) {
1937 if (must_load) {
1938 (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
1939 } else {
1940 (*klassp) = resolve_or_null(symbol, CHECK_0); // load optional klass
1941 }
1942 }
1943 return ((*klassp) != NULL);
1944 }
1946 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
1947 assert((int)start_id <= (int)limit_id, "IDs are out of order!");
1948 for (int id = (int)start_id; id < (int)limit_id; id++) {
1949 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1950 int info = wk_init_info[id - FIRST_WKID];
1951 int sid = (info >> CEIL_LG_OPTION_LIMIT);
1952 int opt = (info & right_n_bits(CEIL_LG_OPTION_LIMIT));
1954 initialize_wk_klass((WKID)id, opt, CHECK);
1956 // Update limits, so find_well_known_klass can be very fast:
1957 symbolOop s = vmSymbols::symbol_at((vmSymbols::SID)sid);
1958 if (wk_klass_name_limits[1] == NULL) {
1959 wk_klass_name_limits[0] = wk_klass_name_limits[1] = s;
1960 } else if (wk_klass_name_limits[1] < s) {
1961 wk_klass_name_limits[1] = s;
1962 } else if (wk_klass_name_limits[0] > s) {
1963 wk_klass_name_limits[0] = s;
1964 }
1965 }
1967 // move the starting value forward to the limit:
1968 start_id = limit_id;
1969 }
1972 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
1973 assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
1974 // Preload commonly used klasses
1975 WKID scan = FIRST_WKID;
1976 // first do Object, String, Class
1977 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
1979 debug_only(instanceKlass::verify_class_klass_nonstatic_oop_maps(WK_KLASS(Class_klass)));
1981 // Fixup mirrors for classes loaded before java.lang.Class.
1982 // These calls iterate over the objects currently in the perm gen
1983 // so calling them at this point is matters (not before when there
1984 // are fewer objects and not later after there are more objects
1985 // in the perm gen.
1986 Universe::initialize_basic_type_mirrors(CHECK);
1987 Universe::fixup_mirrors(CHECK);
1989 // do a bunch more:
1990 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
1992 // Preload ref klasses and set reference types
1993 instanceKlass::cast(WK_KLASS(Reference_klass))->set_reference_type(REF_OTHER);
1994 instanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
1996 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK);
1997 instanceKlass::cast(WK_KLASS(SoftReference_klass))->set_reference_type(REF_SOFT);
1998 instanceKlass::cast(WK_KLASS(WeakReference_klass))->set_reference_type(REF_WEAK);
1999 instanceKlass::cast(WK_KLASS(FinalReference_klass))->set_reference_type(REF_FINAL);
2000 instanceKlass::cast(WK_KLASS(PhantomReference_klass))->set_reference_type(REF_PHANTOM);
2002 WKID meth_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
2003 WKID meth_group_end = WK_KLASS_ENUM_NAME(WrongMethodTypeException_klass);
2004 initialize_wk_klasses_until(meth_group_start, scan, CHECK);
2005 if (EnableMethodHandles) {
2006 initialize_wk_klasses_through(meth_group_end, scan, CHECK);
2007 }
2008 if (_well_known_klasses[meth_group_start] == NULL) {
2009 // Skip the rest of the method handle classes, if MethodHandle is not loaded.
2010 scan = WKID(meth_group_end+1);
2011 }
2012 WKID indy_group_start = WK_KLASS_ENUM_NAME(Linkage_klass);
2013 WKID indy_group_end = WK_KLASS_ENUM_NAME(CallSite_klass);
2014 initialize_wk_klasses_until(indy_group_start, scan, CHECK);
2015 if (EnableInvokeDynamic) {
2016 initialize_wk_klasses_through(indy_group_end, scan, CHECK);
2017 }
2018 if (_well_known_klasses[indy_group_start] == NULL) {
2019 // Skip the rest of the dynamic typing classes, if Linkage is not loaded.
2020 scan = WKID(indy_group_end+1);
2021 }
2023 initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);
2025 _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
2026 _box_klasses[T_CHAR] = WK_KLASS(Character_klass);
2027 _box_klasses[T_FLOAT] = WK_KLASS(Float_klass);
2028 _box_klasses[T_DOUBLE] = WK_KLASS(Double_klass);
2029 _box_klasses[T_BYTE] = WK_KLASS(Byte_klass);
2030 _box_klasses[T_SHORT] = WK_KLASS(Short_klass);
2031 _box_klasses[T_INT] = WK_KLASS(Integer_klass);
2032 _box_klasses[T_LONG] = WK_KLASS(Long_klass);
2033 //_box_klasses[T_OBJECT] = WK_KLASS(object_klass);
2034 //_box_klasses[T_ARRAY] = WK_KLASS(object_klass);
2036 #ifdef KERNEL
2037 if (sun_jkernel_DownloadManager_klass() == NULL) {
2038 warning("Cannot find sun/jkernel/DownloadManager");
2039 }
2040 #endif // KERNEL
2042 { // Compute whether we should use loadClass or loadClassInternal when loading classes.
2043 methodOop method = instanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
2044 _has_loadClassInternal = (method != NULL);
2045 }
2046 { // Compute whether we should use checkPackageAccess or NOT
2047 methodOop method = instanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
2048 _has_checkPackageAccess = (method != NULL);
2049 }
2050 }
2052 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
2053 // If so, returns the basic type it holds. If not, returns T_OBJECT.
2054 BasicType SystemDictionary::box_klass_type(klassOop k) {
2055 assert(k != NULL, "");
2056 for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
2057 if (_box_klasses[i] == k)
2058 return (BasicType)i;
2059 }
2060 return T_OBJECT;
2061 }
2063 KlassHandle SystemDictionaryHandles::box_klass(BasicType t) {
2064 if (t >= T_BOOLEAN && t <= T_VOID)
2065 return KlassHandle(&SystemDictionary::_box_klasses[t], true);
2066 else
2067 return KlassHandle();
2068 }
2070 // Constraints on class loaders. The details of the algorithm can be
2071 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2072 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is
2073 // that the system dictionary needs to maintain a set of contraints that
2074 // must be satisfied by all classes in the dictionary.
2075 // if defining is true, then LinkageError if already in systemDictionary
2076 // if initiating loader, then ok if instanceKlass matches existing entry
2078 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
2079 instanceKlassHandle k,
2080 Handle class_loader, bool defining,
2081 TRAPS) {
2082 const char *linkage_error = NULL;
2083 {
2084 symbolHandle name (THREAD, k->name());
2085 MutexLocker mu(SystemDictionary_lock, THREAD);
2087 klassOop check = find_class(d_index, d_hash, name, class_loader);
2088 if (check != (klassOop)NULL) {
2089 // if different instanceKlass - duplicate class definition,
2090 // else - ok, class loaded by a different thread in parallel,
2091 // we should only have found it if it was done loading and ok to use
2092 // system dictionary only holds instance classes, placeholders
2093 // also holds array classes
2095 assert(check->klass_part()->oop_is_instance(), "noninstance in systemdictionary");
2096 if ((defining == true) || (k() != check)) {
2097 linkage_error = "loader (instance of %s): attempted duplicate class "
2098 "definition for name: \"%s\"";
2099 } else {
2100 return;
2101 }
2102 }
2104 #ifdef ASSERT
2105 unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
2106 int p_index = placeholders()->hash_to_index(p_hash);
2107 symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
2108 assert(ph_check == NULL || ph_check == name(), "invalid symbol");
2109 #endif
2111 if (linkage_error == NULL) {
2112 if (constraints()->check_or_update(k, class_loader, name) == false) {
2113 linkage_error = "loader constraint violation: loader (instance of %s)"
2114 " previously initiated loading for a different type with name \"%s\"";
2115 }
2116 }
2117 }
2119 // Throw error now if needed (cannot throw while holding
2120 // SystemDictionary_lock because of rank ordering)
2122 if (linkage_error) {
2123 ResourceMark rm(THREAD);
2124 const char* class_loader_name = loader_name(class_loader());
2125 char* type_name = k->name()->as_C_string();
2126 size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
2127 strlen(type_name);
2128 char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
2129 jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
2130 THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
2131 }
2132 }
2135 // Update system dictionary - done after check_constraint and add_to_hierachy
2136 // have been called.
2137 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
2138 int p_index, unsigned int p_hash,
2139 instanceKlassHandle k,
2140 Handle class_loader,
2141 TRAPS) {
2142 // Compile_lock prevents systemDictionary updates during compilations
2143 assert_locked_or_safepoint(Compile_lock);
2144 symbolHandle name (THREAD, k->name());
2146 {
2147 MutexLocker mu1(SystemDictionary_lock, THREAD);
2149 // See whether biased locking is enabled and if so set it for this
2150 // klass.
2151 // Note that this must be done past the last potential blocking
2152 // point / safepoint. We enable biased locking lazily using a
2153 // VM_Operation to iterate the SystemDictionary and installing the
2154 // biasable mark word into each instanceKlass's prototype header.
2155 // To avoid race conditions where we accidentally miss enabling the
2156 // optimization for one class in the process of being added to the
2157 // dictionary, we must not safepoint after the test of
2158 // BiasedLocking::enabled().
2159 if (UseBiasedLocking && BiasedLocking::enabled()) {
2160 // Set biased locking bit for all loaded classes; it will be
2161 // cleared if revocation occurs too often for this type
2162 // NOTE that we must only do this when the class is initally
2163 // defined, not each time it is referenced from a new class loader
2164 if (k->class_loader() == class_loader()) {
2165 k->set_prototype_header(markOopDesc::biased_locking_prototype());
2166 }
2167 }
2169 // Check for a placeholder. If there, remove it and make a
2170 // new system dictionary entry.
2171 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
2172 klassOop sd_check = find_class(d_index, d_hash, name, class_loader);
2173 if (sd_check == NULL) {
2174 dictionary()->add_klass(name, class_loader, k);
2175 notice_modification();
2176 }
2177 #ifdef ASSERT
2178 sd_check = find_class(d_index, d_hash, name, class_loader);
2179 assert (sd_check != NULL, "should have entry in system dictionary");
2180 // Changed to allow PH to remain to complete class circularity checking
2181 // while only one thread can define a class at one time, multiple
2182 // classes can resolve the superclass for a class at one time,
2183 // and the placeholder is used to track that
2184 // symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
2185 // assert (ph_check == NULL, "should not have a placeholder entry");
2186 #endif
2187 SystemDictionary_lock->notify_all();
2188 }
2189 }
2192 klassOop SystemDictionary::find_constrained_instance_or_array_klass(
2193 symbolHandle class_name, Handle class_loader, TRAPS) {
2195 // First see if it has been loaded directly.
2196 // Force the protection domain to be null. (This removes protection checks.)
2197 Handle no_protection_domain;
2198 klassOop klass = find_instance_or_array_klass(class_name, class_loader,
2199 no_protection_domain, CHECK_NULL);
2200 if (klass != NULL)
2201 return klass;
2203 // Now look to see if it has been loaded elsewhere, and is subject to
2204 // a loader constraint that would require this loader to return the
2205 // klass that is already loaded.
2206 if (FieldType::is_array(class_name())) {
2207 // For array classes, their klassOops are not kept in the
2208 // constraint table. The element klassOops are.
2209 jint dimension;
2210 symbolOop object_key;
2211 BasicType t = FieldType::get_array_info(class_name(), &dimension,
2212 &object_key, CHECK_(NULL));
2213 if (t != T_OBJECT) {
2214 klass = Universe::typeArrayKlassObj(t);
2215 } else {
2216 symbolHandle elem_name(THREAD, object_key);
2217 MutexLocker mu(SystemDictionary_lock, THREAD);
2218 klass = constraints()->find_constrained_klass(elem_name, class_loader);
2219 }
2220 // If element class already loaded, allocate array klass
2221 if (klass != NULL) {
2222 klass = Klass::cast(klass)->array_klass_or_null(dimension);
2223 }
2224 } else {
2225 MutexLocker mu(SystemDictionary_lock, THREAD);
2226 // Non-array classes are easy: simply check the constraint table.
2227 klass = constraints()->find_constrained_klass(class_name, class_loader);
2228 }
2230 return klass;
2231 }
2234 bool SystemDictionary::add_loader_constraint(symbolHandle class_name,
2235 Handle class_loader1,
2236 Handle class_loader2,
2237 Thread* THREAD) {
2238 symbolHandle constraint_name;
2239 if (!FieldType::is_array(class_name())) {
2240 constraint_name = class_name;
2241 } else {
2242 // For array classes, their klassOops are not kept in the
2243 // constraint table. The element classes are.
2244 jint dimension;
2245 symbolOop object_key;
2246 BasicType t = FieldType::get_array_info(class_name(), &dimension,
2247 &object_key, CHECK_(false));
2248 // primitive types always pass
2249 if (t != T_OBJECT) {
2250 return true;
2251 } else {
2252 constraint_name = symbolHandle(THREAD, object_key);
2253 }
2254 }
2255 unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, class_loader1);
2256 int d_index1 = dictionary()->hash_to_index(d_hash1);
2258 unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, class_loader2);
2259 int d_index2 = dictionary()->hash_to_index(d_hash2);
2260 {
2261 MutexLocker mu_s(SystemDictionary_lock, THREAD);
2263 // Better never do a GC while we're holding these oops
2264 No_Safepoint_Verifier nosafepoint;
2266 klassOop klass1 = find_class(d_index1, d_hash1, constraint_name, class_loader1);
2267 klassOop klass2 = find_class(d_index2, d_hash2, constraint_name, class_loader2);
2268 return constraints()->add_entry(constraint_name, klass1, class_loader1,
2269 klass2, class_loader2);
2270 }
2271 }
2273 // Add entry to resolution error table to record the error when the first
2274 // attempt to resolve a reference to a class has failed.
2275 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, symbolHandle error) {
2276 unsigned int hash = resolution_errors()->compute_hash(pool, which);
2277 int index = resolution_errors()->hash_to_index(hash);
2278 {
2279 MutexLocker ml(SystemDictionary_lock, Thread::current());
2280 resolution_errors()->add_entry(index, hash, pool, which, error);
2281 }
2282 }
2284 // Lookup resolution error table. Returns error if found, otherwise NULL.
2285 symbolOop SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
2286 unsigned int hash = resolution_errors()->compute_hash(pool, which);
2287 int index = resolution_errors()->hash_to_index(hash);
2288 {
2289 MutexLocker ml(SystemDictionary_lock, Thread::current());
2290 ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2291 return (entry != NULL) ? entry->error() : (symbolOop)NULL;
2292 }
2293 }
2296 // Signature constraints ensure that callers and callees agree about
2297 // the meaning of type names in their signatures. This routine is the
2298 // intake for constraints. It collects them from several places:
2299 //
2300 // * LinkResolver::resolve_method (if check_access is true) requires
2301 // that the resolving class (the caller) and the defining class of
2302 // the resolved method (the callee) agree on each type in the
2303 // method's signature.
2304 //
2305 // * LinkResolver::resolve_interface_method performs exactly the same
2306 // checks.
2307 //
2308 // * LinkResolver::resolve_field requires that the constant pool
2309 // attempting to link to a field agree with the field's defining
2310 // class about the type of the field signature.
2311 //
2312 // * klassVtable::initialize_vtable requires that, when a class
2313 // overrides a vtable entry allocated by a superclass, that the
2314 // overriding method (i.e., the callee) agree with the superclass
2315 // on each type in the method's signature.
2316 //
2317 // * klassItable::initialize_itable requires that, when a class fills
2318 // in its itables, for each non-abstract method installed in an
2319 // itable, the method (i.e., the callee) agree with the interface
2320 // on each type in the method's signature.
2321 //
2322 // All those methods have a boolean (check_access, checkconstraints)
2323 // which turns off the checks. This is used from specialized contexts
2324 // such as bootstrapping, dumping, and debugging.
2325 //
2326 // No direct constraint is placed between the class and its
2327 // supertypes. Constraints are only placed along linked relations
2328 // between callers and callees. When a method overrides or implements
2329 // an abstract method in a supertype (superclass or interface), the
2330 // constraints are placed as if the supertype were the caller to the
2331 // overriding method. (This works well, since callers to the
2332 // supertype have already established agreement between themselves and
2333 // the supertype.) As a result of all this, a class can disagree with
2334 // its supertype about the meaning of a type name, as long as that
2335 // class neither calls a relevant method of the supertype, nor is
2336 // called (perhaps via an override) from the supertype.
2337 //
2338 //
2339 // SystemDictionary::check_signature_loaders(sig, l1, l2)
2340 //
2341 // Make sure all class components (including arrays) in the given
2342 // signature will be resolved to the same class in both loaders.
2343 // Returns the name of the type that failed a loader constraint check, or
2344 // NULL if no constraint failed. The returned C string needs cleaning up
2345 // with a ResourceMark in the caller. No exception except OOME is thrown.
2346 // Arrays are not added to the loader constraint table, their elements are.
2347 char* SystemDictionary::check_signature_loaders(symbolHandle signature,
2348 Handle loader1, Handle loader2,
2349 bool is_method, TRAPS) {
2350 // Nothing to do if loaders are the same.
2351 if (loader1() == loader2()) {
2352 return NULL;
2353 }
2355 SignatureStream sig_strm(signature, is_method);
2356 while (!sig_strm.is_done()) {
2357 if (sig_strm.is_object()) {
2358 symbolOop s = sig_strm.as_symbol(CHECK_NULL);
2359 symbolHandle sig (THREAD, s);
2360 if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2361 return sig()->as_C_string();
2362 }
2363 }
2364 sig_strm.next();
2365 }
2366 return NULL;
2367 }
2370 methodOop SystemDictionary::find_method_handle_invoke(symbolHandle name,
2371 symbolHandle signature,
2372 KlassHandle accessing_klass,
2373 TRAPS) {
2374 if (!EnableMethodHandles) return NULL;
2375 vmSymbols::SID name_id = vmSymbols::find_sid(name());
2376 assert(name_id != vmSymbols::NO_SID, "must be a known name");
2377 unsigned int hash = invoke_method_table()->compute_hash(signature, name_id);
2378 int index = invoke_method_table()->hash_to_index(hash);
2379 SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, name_id);
2380 methodHandle non_cached_result;
2381 if (spe == NULL || spe->property_oop() == NULL) {
2382 spe = NULL;
2383 // Must create lots of stuff here, but outside of the SystemDictionary lock.
2384 if (THREAD->is_Compiler_thread())
2385 return NULL; // do not attempt from within compiler
2386 bool for_invokeGeneric = (name_id == vmSymbols::VM_SYMBOL_ENUM_NAME(invokeGeneric_name));
2387 bool found_on_bcp = false;
2388 Handle mt = find_method_handle_type(signature(), accessing_klass,
2389 for_invokeGeneric,
2390 found_on_bcp, CHECK_NULL);
2391 KlassHandle mh_klass = SystemDictionaryHandles::MethodHandle_klass();
2392 methodHandle m = methodOopDesc::make_invoke_method(mh_klass, name, signature,
2393 mt, CHECK_NULL);
2394 // Now grab the lock. We might have to throw away the new method,
2395 // if a racing thread has managed to install one at the same time.
2396 if (found_on_bcp) {
2397 MutexLocker ml(SystemDictionary_lock, Thread::current());
2398 spe = invoke_method_table()->find_entry(index, hash, signature, name_id);
2399 if (spe == NULL)
2400 spe = invoke_method_table()->add_entry(index, hash, signature, name_id);
2401 if (spe->property_oop() == NULL)
2402 spe->set_property_oop(m());
2403 } else {
2404 non_cached_result = m;
2405 }
2406 }
2407 if (spe != NULL && spe->property_oop() != NULL) {
2408 assert(spe->property_oop()->is_method(), "");
2409 return (methodOop) spe->property_oop();
2410 } else {
2411 return non_cached_result();
2412 }
2413 }
2415 // Ask Java code to find or construct a java.dyn.MethodType for the given
2416 // signature, as interpreted relative to the given class loader.
2417 // Because of class loader constraints, all method handle usage must be
2418 // consistent with this loader.
2419 Handle SystemDictionary::find_method_handle_type(symbolHandle signature,
2420 KlassHandle accessing_klass,
2421 bool for_invokeGeneric,
2422 bool& return_bcp_flag,
2423 TRAPS) {
2424 Handle class_loader, protection_domain;
2425 bool is_on_bcp = true; // keep this true as long as we can materialize from the boot classloader
2426 Handle empty;
2427 int npts = ArgumentCount(signature()).size();
2428 objArrayHandle pts = oopFactory::new_objArray(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2429 int arg = 0;
2430 Handle rt; // the return type from the signature
2431 for (SignatureStream ss(signature()); !ss.is_done(); ss.next()) {
2432 oop mirror = NULL;
2433 if (is_on_bcp) {
2434 mirror = ss.as_java_mirror(class_loader, protection_domain,
2435 SignatureStream::ReturnNull, CHECK_(empty));
2436 if (mirror == NULL) {
2437 // fall back from BCP to accessing_klass
2438 if (accessing_klass.not_null()) {
2439 class_loader = Handle(THREAD, instanceKlass::cast(accessing_klass())->class_loader());
2440 protection_domain = Handle(THREAD, instanceKlass::cast(accessing_klass())->protection_domain());
2441 }
2442 is_on_bcp = false;
2443 }
2444 }
2445 if (!is_on_bcp) {
2446 // Resolve, throwing a real error if it doesn't work.
2447 mirror = ss.as_java_mirror(class_loader, protection_domain,
2448 SignatureStream::NCDFError, CHECK_(empty));
2449 }
2450 if (ss.at_return_type())
2451 rt = Handle(THREAD, mirror);
2452 else
2453 pts->obj_at_put(arg++, mirror);
2454 // Check accessibility.
2455 if (ss.is_object() && accessing_klass.not_null()) {
2456 klassOop sel_klass = java_lang_Class::as_klassOop(mirror);
2457 // Emulate constantPoolOopDesc::verify_constant_pool_resolve.
2458 if (Klass::cast(sel_klass)->oop_is_objArray())
2459 sel_klass = objArrayKlass::cast(sel_klass)->bottom_klass();
2460 if (Klass::cast(sel_klass)->oop_is_instance()) {
2461 KlassHandle sel_kh(THREAD, sel_klass);
2462 LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
2463 }
2464 }
2465 }
2466 assert(arg == npts, "");
2468 // call sun.dyn.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
2469 JavaCallArguments args(Handle(THREAD, rt()));
2470 args.push_oop(pts());
2471 JavaValue result(T_OBJECT);
2472 JavaCalls::call_static(&result,
2473 SystemDictionary::MethodHandleNatives_klass(),
2474 vmSymbols::findMethodHandleType_name(),
2475 vmSymbols::findMethodHandleType_signature(),
2476 &args, CHECK_(empty));
2477 Handle method_type(THREAD, (oop) result.get_jobject());
2479 if (for_invokeGeneric) {
2480 // call sun.dyn.MethodHandleNatives::notifyGenericMethodType(MethodType) -> void
2481 JavaCallArguments args(Handle(THREAD, method_type()));
2482 JavaValue no_result(T_VOID);
2483 JavaCalls::call_static(&no_result,
2484 SystemDictionary::MethodHandleNatives_klass(),
2485 vmSymbols::notifyGenericMethodType_name(),
2486 vmSymbols::notifyGenericMethodType_signature(),
2487 &args, THREAD);
2488 if (HAS_PENDING_EXCEPTION) {
2489 // If the notification fails, just kill it.
2490 CLEAR_PENDING_EXCEPTION;
2491 }
2492 }
2494 // report back to the caller with the MethodType and the "on_bcp" flag
2495 return_bcp_flag = is_on_bcp;
2496 return method_type;
2497 }
2499 // Ask Java code to find or construct a method handle constant.
2500 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
2501 int ref_kind, //e.g., JVM_REF_invokeVirtual
2502 KlassHandle callee,
2503 symbolHandle name_sym,
2504 symbolHandle signature,
2505 TRAPS) {
2506 Handle empty;
2507 Handle name = java_lang_String::create_from_symbol(name_sym(), CHECK_(empty));
2508 Handle type;
2509 if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
2510 bool ignore_is_on_bcp = false;
2511 type = find_method_handle_type(signature, caller, false, ignore_is_on_bcp, CHECK_(empty));
2512 } else {
2513 SignatureStream ss(signature(), false);
2514 if (!ss.is_done()) {
2515 oop mirror = ss.as_java_mirror(caller->class_loader(), caller->protection_domain(),
2516 SignatureStream::NCDFError, CHECK_(empty));
2517 type = Handle(THREAD, mirror);
2518 ss.next();
2519 if (!ss.is_done()) type = Handle(); // error!
2520 }
2521 }
2522 if (type.is_null()) {
2523 THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
2524 }
2526 // call sun.dyn.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2527 JavaCallArguments args;
2528 args.push_oop(caller->java_mirror()); // the referring class
2529 args.push_int(ref_kind);
2530 args.push_oop(callee->java_mirror()); // the target class
2531 args.push_oop(name());
2532 args.push_oop(type());
2533 JavaValue result(T_OBJECT);
2534 JavaCalls::call_static(&result,
2535 SystemDictionary::MethodHandleNatives_klass(),
2536 vmSymbols::linkMethodHandleConstant_name(),
2537 vmSymbols::linkMethodHandleConstant_signature(),
2538 &args, CHECK_(empty));
2539 return Handle(THREAD, (oop) result.get_jobject());
2540 }
2542 // Ask Java code to find or construct a java.dyn.CallSite for the given
2543 // name and signature, as interpreted relative to the given class loader.
2544 Handle SystemDictionary::make_dynamic_call_site(Handle bootstrap_method,
2545 symbolHandle name,
2546 methodHandle signature_invoker,
2547 Handle info,
2548 methodHandle caller_method,
2549 int caller_bci,
2550 TRAPS) {
2551 Handle empty;
2552 guarantee(bootstrap_method.not_null() &&
2553 java_dyn_MethodHandle::is_instance(bootstrap_method()),
2554 "caller must supply a valid BSM");
2556 Handle caller_mname = MethodHandles::new_MemberName(CHECK_(empty));
2557 MethodHandles::init_MemberName(caller_mname(), caller_method());
2559 // call sun.dyn.MethodHandleNatives::makeDynamicCallSite(bootm, name, mtype, info, caller_mname, caller_pos)
2560 oop name_str_oop = StringTable::intern(name(), CHECK_(empty)); // not a handle!
2561 JavaCallArguments args(Handle(THREAD, bootstrap_method()));
2562 args.push_oop(name_str_oop);
2563 args.push_oop(signature_invoker->method_handle_type());
2564 args.push_oop(info());
2565 args.push_oop(caller_mname());
2566 args.push_int(caller_bci);
2567 JavaValue result(T_OBJECT);
2568 JavaCalls::call_static(&result,
2569 SystemDictionary::MethodHandleNatives_klass(),
2570 vmSymbols::makeDynamicCallSite_name(),
2571 vmSymbols::makeDynamicCallSite_signature(),
2572 &args, CHECK_(empty));
2573 oop call_site_oop = (oop) result.get_jobject();
2574 assert(call_site_oop->is_oop()
2575 /*&& java_dyn_CallSite::is_instance(call_site_oop)*/, "must be sane");
2576 if (TraceMethodHandles) {
2577 #ifndef PRODUCT
2578 tty->print_cr("Linked invokedynamic bci=%d site="INTPTR_FORMAT":", caller_bci, call_site_oop);
2579 call_site_oop->print();
2580 tty->cr();
2581 #endif //PRODUCT
2582 }
2583 return call_site_oop;
2584 }
2586 Handle SystemDictionary::find_bootstrap_method(methodHandle caller_method, int caller_bci,
2587 int cache_index,
2588 Handle& argument_info_result,
2589 TRAPS) {
2590 Handle empty;
2592 constantPoolHandle pool;
2593 {
2594 klassOop caller = caller_method->method_holder();
2595 if (!Klass::cast(caller)->oop_is_instance()) return empty;
2596 pool = constantPoolHandle(THREAD, instanceKlass::cast(caller)->constants());
2597 }
2599 int constant_pool_index = pool->cache()->entry_at(cache_index)->constant_pool_index();
2600 constantTag tag = pool->tag_at(constant_pool_index);
2602 if (tag.is_invoke_dynamic()) {
2603 // JVM_CONSTANT_InvokeDynamic is an ordered pair of [bootm, name&type], plus optional arguments
2604 // The bootm, being a JVM_CONSTANT_MethodHandle, has its own cache entry.
2605 int bsm_index = pool->invoke_dynamic_bootstrap_method_ref_index_at(constant_pool_index);
2606 if (bsm_index != 0) {
2607 int bsm_index_in_cache = pool->cache()->entry_at(cache_index)->bootstrap_method_index_in_cache();
2608 DEBUG_ONLY(int bsm_index_2 = pool->cache()->entry_at(bsm_index_in_cache)->constant_pool_index());
2609 assert(bsm_index == bsm_index_2, "BSM constant lifted to cache");
2610 if (TraceMethodHandles) {
2611 tty->print_cr("resolving bootstrap method for "PTR_FORMAT" at %d at cache[%d]CP[%d]...",
2612 (intptr_t) caller_method(), caller_bci, cache_index, constant_pool_index);
2613 }
2614 oop bsm_oop = pool->resolve_cached_constant_at(bsm_index_in_cache, CHECK_(empty));
2615 if (TraceMethodHandles) {
2616 tty->print_cr("bootstrap method for "PTR_FORMAT" at %d retrieved as "PTR_FORMAT":",
2617 (intptr_t) caller_method(), caller_bci, (intptr_t) bsm_oop);
2618 }
2619 assert(bsm_oop->is_oop(), "must be sane");
2620 // caller must verify that it is of type MethodHandle
2621 Handle bsm(THREAD, bsm_oop);
2622 bsm_oop = NULL; // safety
2624 // Extract the optional static arguments.
2625 Handle argument_info; // either null, or one arg, or Object[]{arg...}
2626 int argc = pool->invoke_dynamic_argument_count_at(constant_pool_index);
2627 if (TraceInvokeDynamic) {
2628 tty->print_cr("find_bootstrap_method: [%d/%d] CONSTANT_InvokeDynamic: %d[%d]",
2629 constant_pool_index, cache_index, bsm_index, argc);
2630 }
2631 if (argc > 0) {
2632 objArrayHandle arg_array;
2633 if (argc > 1) {
2634 objArrayOop arg_array_oop = oopFactory::new_objArray(SystemDictionary::Object_klass(), argc, CHECK_(empty));
2635 arg_array = objArrayHandle(THREAD, arg_array_oop);
2636 argument_info = arg_array;
2637 }
2638 for (int arg_i = 0; arg_i < argc; arg_i++) {
2639 int arg_index = pool->invoke_dynamic_argument_index_at(constant_pool_index, arg_i);
2640 oop arg_oop = pool->resolve_possibly_cached_constant_at(arg_index, CHECK_(empty));
2641 if (arg_array.is_null()) {
2642 argument_info = Handle(THREAD, arg_oop);
2643 } else {
2644 arg_array->obj_at_put(arg_i, arg_oop);
2645 }
2646 }
2647 }
2649 argument_info_result = argument_info; // return argument_info to caller
2650 return bsm;
2651 }
2652 // else null BSM; fall through
2653 } else if (tag.is_name_and_type()) {
2654 // JSR 292 EDR does not have JVM_CONSTANT_InvokeDynamic
2655 // a bare name&type defaults its BSM to null, so fall through...
2656 } else {
2657 ShouldNotReachHere(); // verifier does not allow this
2658 }
2660 // Fall through to pick up the per-class bootstrap method.
2661 // This mechanism may go away in the PFD.
2662 assert(AllowTransitionalJSR292, "else the verifier should have stopped us already");
2663 argument_info_result = empty; // return no argument_info to caller
2664 oop bsm_oop = instanceKlass::cast(caller_method->method_holder())->bootstrap_method();
2665 if (bsm_oop != NULL) {
2666 if (TraceMethodHandles) {
2667 tty->print_cr("bootstrap method for "PTR_FORMAT" registered as "PTR_FORMAT":",
2668 (intptr_t) caller_method(), (intptr_t) bsm_oop);
2669 }
2670 assert(bsm_oop->is_oop(), "must be sane");
2671 return Handle(THREAD, bsm_oop);
2672 }
2674 return empty;
2675 }
2677 // Since the identity hash code for symbols changes when the symbols are
2678 // moved from the regular perm gen (hash in the mark word) to the shared
2679 // spaces (hash is the address), the classes loaded into the dictionary
2680 // may be in the wrong buckets.
2682 void SystemDictionary::reorder_dictionary() {
2683 dictionary()->reorder_dictionary();
2684 }
2687 void SystemDictionary::copy_buckets(char** top, char* end) {
2688 dictionary()->copy_buckets(top, end);
2689 }
2692 void SystemDictionary::copy_table(char** top, char* end) {
2693 dictionary()->copy_table(top, end);
2694 }
2697 void SystemDictionary::reverse() {
2698 dictionary()->reverse();
2699 }
2701 int SystemDictionary::number_of_classes() {
2702 return dictionary()->number_of_entries();
2703 }
2706 // ----------------------------------------------------------------------------
2707 #ifndef PRODUCT
2709 void SystemDictionary::print() {
2710 dictionary()->print();
2712 // Placeholders
2713 GCMutexLocker mu(SystemDictionary_lock);
2714 placeholders()->print();
2716 // loader constraints - print under SD_lock
2717 constraints()->print();
2718 }
2720 #endif
2722 void SystemDictionary::verify() {
2723 guarantee(dictionary() != NULL, "Verify of system dictionary failed");
2724 guarantee(constraints() != NULL,
2725 "Verify of loader constraints failed");
2726 guarantee(dictionary()->number_of_entries() >= 0 &&
2727 placeholders()->number_of_entries() >= 0,
2728 "Verify of system dictionary failed");
2730 // Verify dictionary
2731 dictionary()->verify();
2733 GCMutexLocker mu(SystemDictionary_lock);
2734 placeholders()->verify();
2736 // Verify constraint table
2737 guarantee(constraints() != NULL, "Verify of loader constraints failed");
2738 constraints()->verify(dictionary(), placeholders());
2739 }
2742 void SystemDictionary::verify_obj_klass_present(Handle obj,
2743 symbolHandle class_name,
2744 Handle class_loader) {
2745 GCMutexLocker mu(SystemDictionary_lock);
2746 oop probe = find_class_or_placeholder(class_name, class_loader);
2747 if (probe == NULL) {
2748 probe = SystemDictionary::find_shared_class(class_name);
2749 }
2750 guarantee(probe != NULL &&
2751 (!probe->is_klass() || probe == obj()),
2752 "Loaded klasses should be in SystemDictionary");
2753 }
2755 #ifndef PRODUCT
2757 // statistics code
2758 class ClassStatistics: AllStatic {
2759 private:
2760 static int nclasses; // number of classes
2761 static int nmethods; // number of methods
2762 static int nmethoddata; // number of methodData
2763 static int class_size; // size of class objects in words
2764 static int method_size; // size of method objects in words
2765 static int debug_size; // size of debug info in methods
2766 static int methoddata_size; // size of methodData objects in words
2768 static void do_class(klassOop k) {
2769 nclasses++;
2770 class_size += k->size();
2771 if (k->klass_part()->oop_is_instance()) {
2772 instanceKlass* ik = (instanceKlass*)k->klass_part();
2773 class_size += ik->methods()->size();
2774 class_size += ik->constants()->size();
2775 class_size += ik->local_interfaces()->size();
2776 class_size += ik->transitive_interfaces()->size();
2777 // We do not have to count implementors, since we only store one!
2778 class_size += ik->fields()->size();
2779 }
2780 }
2782 static void do_method(methodOop m) {
2783 nmethods++;
2784 method_size += m->size();
2785 // class loader uses same objArray for empty vectors, so don't count these
2786 if (m->exception_table()->length() != 0) method_size += m->exception_table()->size();
2787 if (m->has_stackmap_table()) {
2788 method_size += m->stackmap_data()->size();
2789 }
2791 methodDataOop mdo = m->method_data();
2792 if (mdo != NULL) {
2793 nmethoddata++;
2794 methoddata_size += mdo->size();
2795 }
2796 }
2798 public:
2799 static void print() {
2800 SystemDictionary::classes_do(do_class);
2801 SystemDictionary::methods_do(do_method);
2802 tty->print_cr("Class statistics:");
2803 tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
2804 tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,
2805 (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
2806 tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
2807 }
2808 };
2811 int ClassStatistics::nclasses = 0;
2812 int ClassStatistics::nmethods = 0;
2813 int ClassStatistics::nmethoddata = 0;
2814 int ClassStatistics::class_size = 0;
2815 int ClassStatistics::method_size = 0;
2816 int ClassStatistics::debug_size = 0;
2817 int ClassStatistics::methoddata_size = 0;
2819 void SystemDictionary::print_class_statistics() {
2820 ResourceMark rm;
2821 ClassStatistics::print();
2822 }
2825 class MethodStatistics: AllStatic {
2826 public:
2827 enum {
2828 max_parameter_size = 10
2829 };
2830 private:
2832 static int _number_of_methods;
2833 static int _number_of_final_methods;
2834 static int _number_of_static_methods;
2835 static int _number_of_native_methods;
2836 static int _number_of_synchronized_methods;
2837 static int _number_of_profiled_methods;
2838 static int _number_of_bytecodes;
2839 static int _parameter_size_profile[max_parameter_size];
2840 static int _bytecodes_profile[Bytecodes::number_of_java_codes];
2842 static void initialize() {
2843 _number_of_methods = 0;
2844 _number_of_final_methods = 0;
2845 _number_of_static_methods = 0;
2846 _number_of_native_methods = 0;
2847 _number_of_synchronized_methods = 0;
2848 _number_of_profiled_methods = 0;
2849 _number_of_bytecodes = 0;
2850 for (int i = 0; i < max_parameter_size ; i++) _parameter_size_profile[i] = 0;
2851 for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile [j] = 0;
2852 };
2854 static void do_method(methodOop m) {
2855 _number_of_methods++;
2856 // collect flag info
2857 if (m->is_final() ) _number_of_final_methods++;
2858 if (m->is_static() ) _number_of_static_methods++;
2859 if (m->is_native() ) _number_of_native_methods++;
2860 if (m->is_synchronized()) _number_of_synchronized_methods++;
2861 if (m->method_data() != NULL) _number_of_profiled_methods++;
2862 // collect parameter size info (add one for receiver, if any)
2863 _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
2864 // collect bytecodes info
2865 {
2866 Thread *thread = Thread::current();
2867 HandleMark hm(thread);
2868 BytecodeStream s(methodHandle(thread, m));
2869 Bytecodes::Code c;
2870 while ((c = s.next()) >= 0) {
2871 _number_of_bytecodes++;
2872 _bytecodes_profile[c]++;
2873 }
2874 }
2875 }
2877 public:
2878 static void print() {
2879 initialize();
2880 SystemDictionary::methods_do(do_method);
2881 // generate output
2882 tty->cr();
2883 tty->print_cr("Method statistics (static):");
2884 // flag distribution
2885 tty->cr();
2886 tty->print_cr("%6d final methods %6.1f%%", _number_of_final_methods , _number_of_final_methods * 100.0F / _number_of_methods);
2887 tty->print_cr("%6d static methods %6.1f%%", _number_of_static_methods , _number_of_static_methods * 100.0F / _number_of_methods);
2888 tty->print_cr("%6d native methods %6.1f%%", _number_of_native_methods , _number_of_native_methods * 100.0F / _number_of_methods);
2889 tty->print_cr("%6d synchronized methods %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
2890 tty->print_cr("%6d profiled methods %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
2891 // parameter size profile
2892 tty->cr();
2893 { int tot = 0;
2894 int avg = 0;
2895 for (int i = 0; i < max_parameter_size; i++) {
2896 int n = _parameter_size_profile[i];
2897 tot += n;
2898 avg += n*i;
2899 tty->print_cr("parameter size = %1d: %6d methods %5.1f%%", i, n, n * 100.0F / _number_of_methods);
2900 }
2901 assert(tot == _number_of_methods, "should be the same");
2902 tty->print_cr(" %6d methods 100.0%%", _number_of_methods);
2903 tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
2904 }
2905 // bytecodes profile
2906 tty->cr();
2907 { int tot = 0;
2908 for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
2909 if (Bytecodes::is_defined(i)) {
2910 Bytecodes::Code c = Bytecodes::cast(i);
2911 int n = _bytecodes_profile[c];
2912 tot += n;
2913 tty->print_cr("%9d %7.3f%% %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
2914 }
2915 }
2916 assert(tot == _number_of_bytecodes, "should be the same");
2917 tty->print_cr("%9d 100.000%%", _number_of_bytecodes);
2918 }
2919 tty->cr();
2920 }
2921 };
2923 int MethodStatistics::_number_of_methods;
2924 int MethodStatistics::_number_of_final_methods;
2925 int MethodStatistics::_number_of_static_methods;
2926 int MethodStatistics::_number_of_native_methods;
2927 int MethodStatistics::_number_of_synchronized_methods;
2928 int MethodStatistics::_number_of_profiled_methods;
2929 int MethodStatistics::_number_of_bytecodes;
2930 int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
2931 int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];
2934 void SystemDictionary::print_method_statistics() {
2935 MethodStatistics::print();
2936 }
2938 #endif // PRODUCT