1 /*
2 * Copyright 1997-2007 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
20 * CA 95054 USA or visit www.sun.com if you need additional information or
21 * have any questions.
22 *
23 */
24
25 # include "incls/_precompiled.incl"
26 # include "incls/_systemDictionary.cpp.incl"
27
28
29 Dictionary* SystemDictionary::_dictionary = NULL;
30 PlaceholderTable* SystemDictionary::_placeholders = NULL;
31 Dictionary* SystemDictionary::_shared_dictionary = NULL;
32 LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL;
33 ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL;
34
35
36 int SystemDictionary::_number_of_modifications = 0;
37
38 oop SystemDictionary::_system_loader_lock_obj = NULL;
39
40 klassOop SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
41 = { NULL /*, NULL...*/ };
42
43 klassOop SystemDictionary::_box_klasses[T_VOID+1] = { NULL /*, NULL...*/ };
44
45 oop SystemDictionary::_java_system_loader = NULL;
46
47 bool SystemDictionary::_has_loadClassInternal = false;
48 bool SystemDictionary::_has_checkPackageAccess = false;
49
50 // lazily initialized klass variables
51 volatile klassOop SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
52
53
54 // ----------------------------------------------------------------------------
55 // Java-level SystemLoader
56
57 oop SystemDictionary::java_system_loader() {
58 return _java_system_loader;
59 }
60
61 void SystemDictionary::compute_java_system_loader(TRAPS) {
62 KlassHandle system_klass(THREAD, WK_KLASS(classloader_klass));
63 JavaValue result(T_OBJECT);
64 JavaCalls::call_static(&result,
65 KlassHandle(THREAD, WK_KLASS(classloader_klass)),
66 vmSymbolHandles::getSystemClassLoader_name(),
67 vmSymbolHandles::void_classloader_signature(),
68 CHECK);
69
70 _java_system_loader = (oop)result.get_jobject();
71 }
72
73
74 // ----------------------------------------------------------------------------
75 // debugging
76
77 #ifdef ASSERT
78
79 // return true if class_name contains no '.' (internal format is '/')
80 bool SystemDictionary::is_internal_format(symbolHandle class_name) {
81 if (class_name.not_null()) {
82 ResourceMark rm;
83 char* name = class_name->as_C_string();
84 return strchr(name, '.') == NULL;
85 } else {
86 return true;
87 }
88 }
89
90 #endif
91
92 // ----------------------------------------------------------------------------
93 // Resolving of classes
94
95 // Forwards to resolve_or_null
96
97 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
98 klassOop klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
99 if (HAS_PENDING_EXCEPTION || klass == NULL) {
100 KlassHandle k_h(THREAD, klass);
101 // can return a null klass
102 klass = handle_resolution_exception(class_name, class_loader, protection_domain, throw_error, k_h, THREAD);
103 }
104 return klass;
105 }
106
107 klassOop SystemDictionary::handle_resolution_exception(symbolHandle class_name, Handle class_loader, Handle protection_domain, bool throw_error, KlassHandle klass_h, TRAPS) {
108 if (HAS_PENDING_EXCEPTION) {
109 // If we have a pending exception we forward it to the caller, unless throw_error is true,
110 // in which case we have to check whether the pending exception is a ClassNotFoundException,
111 // and if so convert it to a NoClassDefFoundError
112 // And chain the original ClassNotFoundException
113 if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::classNotFoundException_klass())) {
114 ResourceMark rm(THREAD);
115 assert(klass_h() == NULL, "Should not have result with exception pending");
116 Handle e(THREAD, PENDING_EXCEPTION);
117 CLEAR_PENDING_EXCEPTION;
118 THROW_MSG_CAUSE_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
119 } else {
120 return NULL;
121 }
122 }
123 // Class not found, throw appropriate error or exception depending on value of throw_error
124 if (klass_h() == NULL) {
125 ResourceMark rm(THREAD);
126 if (throw_error) {
127 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
128 } else {
129 THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
130 }
131 }
132 return (klassOop)klass_h();
133 }
134
135
136 klassOop SystemDictionary::resolve_or_fail(symbolHandle class_name,
137 bool throw_error, TRAPS)
138 {
139 return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
140 }
141
142
143 // Forwards to resolve_instance_class_or_null
144
145 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
146 assert(!THREAD->is_Compiler_thread(), "Can not load classes with the Compiler thread");
147 if (FieldType::is_array(class_name())) {
148 return resolve_array_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
149 } else {
150 return resolve_instance_class_or_null(class_name, class_loader, protection_domain, CHECK_NULL);
151 }
152 }
153
154 klassOop SystemDictionary::resolve_or_null(symbolHandle class_name, TRAPS) {
155 return resolve_or_null(class_name, Handle(), Handle(), THREAD);
156 }
157
158 // Forwards to resolve_instance_class_or_null
159
160 klassOop SystemDictionary::resolve_array_class_or_null(symbolHandle class_name,
161 Handle class_loader,
162 Handle protection_domain,
163 TRAPS) {
164 assert(FieldType::is_array(class_name()), "must be array");
165 jint dimension;
166 symbolOop object_key;
167 klassOop k = NULL;
168 // dimension and object_key are assigned as a side-effect of this call
169 BasicType t = FieldType::get_array_info(class_name(),
170 &dimension,
171 &object_key,
172 CHECK_NULL);
173
174 if (t == T_OBJECT) {
175 symbolHandle h_key(THREAD, object_key);
176 // naked oop "k" is OK here -- we assign back into it
177 k = SystemDictionary::resolve_instance_class_or_null(h_key,
178 class_loader,
179 protection_domain,
180 CHECK_NULL);
181 if (k != NULL) {
182 k = Klass::cast(k)->array_klass(dimension, CHECK_NULL);
183 }
184 } else {
185 k = Universe::typeArrayKlassObj(t);
186 k = typeArrayKlass::cast(k)->array_klass(dimension, CHECK_NULL);
187 }
188 return k;
189 }
190
191
192 // Must be called for any super-class or super-interface resolution
193 // during class definition to allow class circularity checking
194 // super-interface callers:
195 // parse_interfaces - for defineClass & jvmtiRedefineClasses
196 // super-class callers:
197 // ClassFileParser - for defineClass & jvmtiRedefineClasses
198 // load_shared_class - while loading a class from shared archive
199 // resolve_instance_class_or_fail:
200 // when resolving a class that has an existing placeholder with
201 // a saved superclass [i.e. a defineClass is currently in progress]
202 // if another thread is trying to resolve the class, it must do
203 // super-class checks on its own thread to catch class circularity
204 // This last call is critical in class circularity checking for cases
205 // where classloading is delegated to different threads and the
206 // classloader lock is released.
207 // Take the case: Base->Super->Base
208 // 1. If thread T1 tries to do a defineClass of class Base
209 // resolve_super_or_fail creates placeholder: T1, Base (super Super)
210 // 2. resolve_instance_class_or_null does not find SD or placeholder for Super
211 // so it tries to load Super
212 // 3. If we load the class internally, or user classloader uses same thread
213 // loadClassFromxxx or defineClass via parseClassFile Super ...
214 // 3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
215 // 3.3 resolve_instance_class_or_null Base, finds placeholder for Base
216 // 3.4 calls resolve_super_or_fail Base
217 // 3.5 finds T1,Base -> throws class circularity
218 //OR 4. If T2 tries to resolve Super via defineClass Super ...
219 // 4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
220 // 4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
221 // 4.3 calls resolve_super_or_fail Super in parallel on own thread T2
222 // 4.4 finds T2, Super -> throws class circularity
223 // Must be called, even if superclass is null, since this is
224 // where the placeholder entry is created which claims this
225 // thread is loading this class/classloader.
226 klassOop SystemDictionary::resolve_super_or_fail(symbolHandle child_name,
227 symbolHandle class_name,
228 Handle class_loader,
229 Handle protection_domain,
230 bool is_superclass,
231 TRAPS) {
232
233 // Try to get one of the well-known klasses.
234 // They are trusted, and do not participate in circularities.
235 { klassOop k = find_well_known_klass(class_name());
236 if (k != NULL) {
237 return k;
238 }
239 }
240
241 // Double-check, if child class is already loaded, just return super-class,interface
242 // Don't add a placedholder if already loaded, i.e. already in system dictionary
243 // Make sure there's a placeholder for the *child* before resolving.
244 // Used as a claim that this thread is currently loading superclass/classloader
245 // Used here for ClassCircularity checks and also for heap verification
246 // (every instanceKlass in the heap needs to be in the system dictionary
247 // or have a placeholder).
248 // Must check ClassCircularity before checking if super class is already loaded
249 //
250 // We might not already have a placeholder if this child_name was
251 // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
252 // the name of the class might not be known until the stream is actually
253 // parsed.
254 // Bugs 4643874, 4715493
255 // compute_hash can have a safepoint
256
257 unsigned int d_hash = dictionary()->compute_hash(child_name, class_loader);
258 int d_index = dictionary()->hash_to_index(d_hash);
259 unsigned int p_hash = placeholders()->compute_hash(child_name, class_loader);
260 int p_index = placeholders()->hash_to_index(p_hash);
261 // can't throw error holding a lock
262 bool child_already_loaded = false;
263 bool throw_circularity_error = false;
264 {
265 MutexLocker mu(SystemDictionary_lock, THREAD);
266 klassOop childk = find_class(d_index, d_hash, child_name, class_loader);
267 klassOop quicksuperk;
268 // to support // loading: if child done loading, just return superclass
269 // if class_name, & class_loader don't match:
270 // if initial define, SD update will give LinkageError
271 // if redefine: compare_class_versions will give HIERARCHY_CHANGED
272 // so we don't throw an exception here.
273 // see: nsk redefclass014 & java.lang.instrument Instrument032
274 if ((childk != NULL ) && (is_superclass) &&
275 ((quicksuperk = instanceKlass::cast(childk)->super()) != NULL) &&
276
277 ((Klass::cast(quicksuperk)->name() == class_name()) &&
278 (Klass::cast(quicksuperk)->class_loader() == class_loader()))) {
279 return quicksuperk;
280 } else {
281 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
282 if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
283 throw_circularity_error = true;
284 }
285
286 // add placeholder entry even if error - callers will remove on error
287 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, class_loader, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
288 if (throw_circularity_error) {
289 newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER);
290 }
291 }
292 }
293 if (throw_circularity_error) {
294 ResourceMark rm(THREAD);
295 THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
296 }
297
298 // java.lang.Object should have been found above
299 assert(class_name() != NULL, "null super class for resolving");
300 // Resolve the super class or interface, check results on return
301 klassOop superk = NULL;
302 superk = SystemDictionary::resolve_or_null(class_name,
303 class_loader,
304 protection_domain,
305 THREAD);
306
307 KlassHandle superk_h(THREAD, superk);
308
309 // Note: clean up of placeholders currently in callers of
310 // resolve_super_or_fail - either at update_dictionary time
311 // or on error
312 {
313 MutexLocker mu(SystemDictionary_lock, THREAD);
314 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, class_loader);
315 if (probe != NULL) {
316 probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER);
317 }
318 }
319 if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
320 // can null superk
321 superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
322 }
323
324 return superk_h();
325 }
326
327
328 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
329 Handle class_loader,
330 Handle protection_domain,
331 TRAPS) {
332 if(!has_checkPackageAccess()) return;
333
334 // Now we have to call back to java to check if the initating class has access
335 JavaValue result(T_VOID);
336 if (TraceProtectionDomainVerification) {
337 // Print out trace information
338 tty->print_cr("Checking package access");
339 tty->print(" - class loader: "); class_loader()->print_value_on(tty); tty->cr();
340 tty->print(" - protection domain: "); protection_domain()->print_value_on(tty); tty->cr();
341 tty->print(" - loading: "); klass()->print_value_on(tty); tty->cr();
342 }
343
344 assert(class_loader() != NULL, "should not have non-null protection domain for null classloader");
345
346 KlassHandle system_loader(THREAD, SystemDictionary::classloader_klass());
347 JavaCalls::call_special(&result,
348 class_loader,
349 system_loader,
350 vmSymbolHandles::checkPackageAccess_name(),
351 vmSymbolHandles::class_protectiondomain_signature(),
352 Handle(THREAD, klass->java_mirror()),
353 protection_domain,
354 THREAD);
355
356 if (TraceProtectionDomainVerification) {
357 if (HAS_PENDING_EXCEPTION) {
358 tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
359 } else {
360 tty->print_cr(" -> granted");
361 }
362 tty->cr();
363 }
364
365 if (HAS_PENDING_EXCEPTION) return;
366
367 // If no exception has been thrown, we have validated the protection domain
368 // Insert the protection domain of the initiating class into the set.
369 {
370 // We recalculate the entry here -- we've called out to java since
371 // the last time it was calculated.
372 symbolHandle kn(THREAD, klass->name());
373 unsigned int d_hash = dictionary()->compute_hash(kn, class_loader);
374 int d_index = dictionary()->hash_to_index(d_hash);
375
376 MutexLocker mu(SystemDictionary_lock, THREAD);
377 {
378 // Note that we have an entry, and entries can be deleted only during GC,
379 // so we cannot allow GC to occur while we're holding this entry.
380
381 // We're using a No_Safepoint_Verifier to catch any place where we
382 // might potentially do a GC at all.
383 // SystemDictionary::do_unloading() asserts that classes are only
384 // unloaded at a safepoint.
385 No_Safepoint_Verifier nosafepoint;
386 dictionary()->add_protection_domain(d_index, d_hash, klass, class_loader,
387 protection_domain, THREAD);
388 }
389 }
390 }
391
392 // We only get here if this thread finds that another thread
393 // has already claimed the placeholder token for the current operation,
394 // but that other thread either never owned or gave up the
395 // object lock
396 // Waits on SystemDictionary_lock to indicate placeholder table updated
397 // On return, caller must recheck placeholder table state
398 //
399 // We only get here if
400 // 1) custom classLoader, i.e. not bootstrap classloader
401 // 2) UnsyncloadClass not set
402 // 3) custom classLoader has broken the class loader objectLock
403 // so another thread got here in parallel
404 //
405 // lockObject must be held.
406 // Complicated dance due to lock ordering:
407 // Must first release the classloader object lock to
408 // allow initial definer to complete the class definition
409 // and to avoid deadlock
410 // Reclaim classloader lock object with same original recursion count
411 // Must release SystemDictionary_lock after notify, since
412 // class loader lock must be claimed before SystemDictionary_lock
413 // to prevent deadlocks
414 //
415 // The notify allows applications that did an untimed wait() on
416 // the classloader object lock to not hang.
417 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
418 assert_lock_strong(SystemDictionary_lock);
419
420 bool calledholdinglock
421 = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
422 assert(calledholdinglock,"must hold lock for notify");
423 assert(!UnsyncloadClass, "unexpected double_lock_wait");
424 ObjectSynchronizer::notifyall(lockObject, THREAD);
425 intptr_t recursions = ObjectSynchronizer::complete_exit(lockObject, THREAD);
426 SystemDictionary_lock->wait();
427 SystemDictionary_lock->unlock();
428 ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
429 SystemDictionary_lock->lock();
430 }
431
432 // If the class in is in the placeholder table, class loading is in progress
433 // For cases where the application changes threads to load classes, it
434 // is critical to ClassCircularity detection that we try loading
435 // the superclass on the same thread internally, so we do parallel
436 // super class loading here.
437 // This also is critical in cases where the original thread gets stalled
438 // even in non-circularity situations.
439 // Note: only one thread can define the class, but multiple can resolve
440 // Note: must call resolve_super_or_fail even if null super -
441 // to force placeholder entry creation for this class
442 // Caller must check for pending exception
443 // Returns non-null klassOop if other thread has completed load
444 // and we are done,
445 // If return null klassOop and no pending exception, the caller must load the class
446 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
447 symbolHandle name, symbolHandle superclassname, Handle class_loader,
448 Handle protection_domain, Handle lockObject, TRAPS) {
449
450 instanceKlassHandle nh = instanceKlassHandle(); // null Handle
451 unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
452 int d_index = dictionary()->hash_to_index(d_hash);
453 unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
454 int p_index = placeholders()->hash_to_index(p_hash);
455
456 // superk is not used, resolve_super called for circularity check only
457 // This code is reached in two situations. One if this thread
458 // is loading the same class twice (e.g. ClassCircularity, or
459 // java.lang.instrument).
460 // The second is if another thread started the resolve_super first
461 // and has not yet finished.
462 // In both cases the original caller will clean up the placeholder
463 // entry on error.
464 klassOop superk = SystemDictionary::resolve_super_or_fail(name,
465 superclassname,
466 class_loader,
467 protection_domain,
468 true,
469 CHECK_(nh));
470 // We don't redefine the class, so we just need to clean up if there
471 // was not an error (don't want to modify any system dictionary
472 // data structures).
473 {
474 MutexLocker mu(SystemDictionary_lock, THREAD);
475 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
476 SystemDictionary_lock->notify_all();
477 }
478
479 // UnsyncloadClass does NOT wait for parallel superclass loads to complete
480 // Bootstrap classloader does wait for parallel superclass loads
481 if (UnsyncloadClass) {
482 MutexLocker mu(SystemDictionary_lock, THREAD);
483 // Check if classloading completed while we were loading superclass or waiting
484 klassOop check = find_class(d_index, d_hash, name, class_loader);
485 if (check != NULL) {
486 // Klass is already loaded, so just return it
487 return(instanceKlassHandle(THREAD, check));
488 } else {
489 return nh;
490 }
491 }
492
493 // must loop to both handle other placeholder updates
494 // and spurious notifications
495 bool super_load_in_progress = true;
496 PlaceholderEntry* placeholder;
497 while (super_load_in_progress) {
498 MutexLocker mu(SystemDictionary_lock, THREAD);
499 // Check if classloading completed while we were loading superclass or waiting
500 klassOop check = find_class(d_index, d_hash, name, class_loader);
501 if (check != NULL) {
502 // Klass is already loaded, so just return it
503 return(instanceKlassHandle(THREAD, check));
504 } else {
505 placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
506 if (placeholder && placeholder->super_load_in_progress() ){
507 // Before UnsyncloadClass:
508 // We only get here if the application has released the
509 // classloader lock when another thread was in the middle of loading a
510 // superclass/superinterface for this class, and now
511 // this thread is also trying to load this class.
512 // To minimize surprises, the first thread that started to
513 // load a class should be the one to complete the loading
514 // with the classfile it initially expected.
515 // This logic has the current thread wait once it has done
516 // all the superclass/superinterface loading it can, until
517 // the original thread completes the class loading or fails
518 // If it completes we will use the resulting instanceKlass
519 // which we will find below in the systemDictionary.
520 // We also get here for parallel bootstrap classloader
521 if (class_loader.is_null()) {
522 SystemDictionary_lock->wait();
523 } else {
524 double_lock_wait(lockObject, THREAD);
525 }
526 } else {
527 // If not in SD and not in PH, other thread's load must have failed
528 super_load_in_progress = false;
529 }
530 }
531 }
532 return (nh);
533 }
534
535
536 klassOop SystemDictionary::resolve_instance_class_or_null(symbolHandle class_name, Handle class_loader, Handle protection_domain, TRAPS) {
537 assert(class_name.not_null() && !FieldType::is_array(class_name()), "invalid class name");
538 // First check to see if we should remove wrapping L and ;
539 symbolHandle name;
540 if (FieldType::is_obj(class_name())) {
541 ResourceMark rm(THREAD);
542 // Ignore wrapping L and ;.
543 name = oopFactory::new_symbol_handle(class_name()->as_C_string() + 1, class_name()->utf8_length() - 2, CHECK_NULL);
544 } else {
545 name = class_name;
546 }
547
548 // UseNewReflection
549 // Fix for 4474172; see evaluation for more details
550 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
551
552 // Do lookup to see if class already exist and the protection domain
553 // has the right access
554 unsigned int d_hash = dictionary()->compute_hash(name, class_loader);
555 int d_index = dictionary()->hash_to_index(d_hash);
556 klassOop probe = dictionary()->find(d_index, d_hash, name, class_loader,
557 protection_domain, THREAD);
558 if (probe != NULL) return probe;
559
560
561 // Non-bootstrap class loaders will call out to class loader and
562 // define via jvm/jni_DefineClass which will acquire the
563 // class loader object lock to protect against multiple threads
564 // defining the class in parallel by accident.
565 // This lock must be acquired here so the waiter will find
566 // any successful result in the SystemDictionary and not attempt
567 // the define
568 // Classloaders that support parallelism, e.g. bootstrap classloader,
569 // or all classloaders with UnsyncloadClass do not acquire lock here
570 bool DoObjectLock = true;
571 if (UnsyncloadClass || (class_loader.is_null())) {
572 DoObjectLock = false;
573 }
574
575 unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
576 int p_index = placeholders()->hash_to_index(p_hash);
577
578 // Class is not in SystemDictionary so we have to do loading.
579 // Make sure we are synchronized on the class loader before we proceed
580 Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
581 check_loader_lock_contention(lockObject, THREAD);
582 ObjectLocker ol(lockObject, THREAD, DoObjectLock);
583
584 // Check again (after locking) if class already exist in SystemDictionary
585 bool class_has_been_loaded = false;
586 bool super_load_in_progress = false;
587 bool havesupername = false;
588 instanceKlassHandle k;
589 PlaceholderEntry* placeholder;
590 symbolHandle superclassname;
591
592 {
593 MutexLocker mu(SystemDictionary_lock, THREAD);
594 klassOop check = find_class(d_index, d_hash, name, class_loader);
595 if (check != NULL) {
596 // Klass is already loaded, so just return it
597 class_has_been_loaded = true;
598 k = instanceKlassHandle(THREAD, check);
599 } else {
600 placeholder = placeholders()->get_entry(p_index, p_hash, name, class_loader);
601 if (placeholder && placeholder->super_load_in_progress()) {
602 super_load_in_progress = true;
603 if (placeholder->havesupername() == true) {
604 superclassname = symbolHandle(THREAD, placeholder->supername());
605 havesupername = true;
606 }
607 }
608 }
609 }
610
611 // If the class in is in the placeholder table, class loading is in progress
612 if (super_load_in_progress && havesupername==true) {
613 k = SystemDictionary::handle_parallel_super_load(name, superclassname,
614 class_loader, protection_domain, lockObject, THREAD);
615 if (HAS_PENDING_EXCEPTION) {
616 return NULL;
617 }
618 if (!k.is_null()) {
619 class_has_been_loaded = true;
620 }
621 }
622
623 if (!class_has_been_loaded) {
624
625 // add placeholder entry to record loading instance class
626 // Five cases:
627 // All cases need to prevent modifying bootclasssearchpath
628 // in parallel with a classload of same classname
629 // case 1. traditional classloaders that rely on the classloader object lock
630 // - no other need for LOAD_INSTANCE
631 // case 2. traditional classloaders that break the classloader object lock
632 // as a deadlock workaround. Detection of this case requires that
633 // this check is done while holding the classloader object lock,
634 // and that lock is still held when calling classloader's loadClass.
635 // For these classloaders, we ensure that the first requestor
636 // completes the load and other requestors wait for completion.
637 // case 3. UnsyncloadClass - don't use objectLocker
638 // With this flag, we allow parallel classloading of a
639 // class/classloader pair
640 // case4. Bootstrap classloader - don't own objectLocker
641 // This classloader supports parallelism at the classloader level,
642 // but only allows a single load of a class/classloader pair.
643 // No performance benefit and no deadlock issues.
644 // case 5. Future: parallel user level classloaders - without objectLocker
645 symbolHandle nullsymbolHandle;
646 bool throw_circularity_error = false;
647 {
648 MutexLocker mu(SystemDictionary_lock, THREAD);
649 if (!UnsyncloadClass) {
650 PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
651 if (oldprobe) {
652 // only need check_seen_thread once, not on each loop
653 // 6341374 java/lang/Instrument with -Xcomp
654 if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
655 throw_circularity_error = true;
656 } else {
657 // case 1: traditional: should never see load_in_progress.
658 while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
659
660 // case 4: bootstrap classloader: prevent futile classloading,
661 // wait on first requestor
662 if (class_loader.is_null()) {
663 SystemDictionary_lock->wait();
664 } else {
665 // case 2: traditional with broken classloader lock. wait on first
666 // requestor.
667 double_lock_wait(lockObject, THREAD);
668 }
669 // Check if classloading completed while we were waiting
670 klassOop check = find_class(d_index, d_hash, name, class_loader);
671 if (check != NULL) {
672 // Klass is already loaded, so just return it
673 k = instanceKlassHandle(THREAD, check);
674 class_has_been_loaded = true;
675 }
676 // check if other thread failed to load and cleaned up
677 oldprobe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
678 }
679 }
680 }
681 }
682 // All cases: add LOAD_INSTANCE
683 // case 3: UnsyncloadClass: allow competing threads to try
684 // LOAD_INSTANCE in parallel
685 // add placeholder entry even if error - callers will remove on error
686 if (!class_has_been_loaded) {
687 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, class_loader, PlaceholderTable::LOAD_INSTANCE, nullsymbolHandle, THREAD);
688 if (throw_circularity_error) {
689 newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
690 }
691 // For class loaders that do not acquire the classloader object lock,
692 // if they did not catch another thread holding LOAD_INSTANCE,
693 // need a check analogous to the acquire ObjectLocker/find_class
694 // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
695 // one final check if the load has already completed
696 klassOop check = find_class(d_index, d_hash, name, class_loader);
697 if (check != NULL) {
698 // Klass is already loaded, so just return it
699 k = instanceKlassHandle(THREAD, check);
700 class_has_been_loaded = true;
701 newprobe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
702 }
703 }
704 }
705 // must throw error outside of owning lock
706 if (throw_circularity_error) {
707 ResourceMark rm(THREAD);
708 THROW_MSG_0(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
709 }
710
711 if (!class_has_been_loaded) {
712
713 // Do actual loading
714 k = load_instance_class(name, class_loader, THREAD);
715
716 // In custom class loaders, the usual findClass calls
717 // findLoadedClass, which directly searches the SystemDictionary, then
718 // defineClass. If these are not atomic with respect to other threads,
719 // the findLoadedClass can fail, but the defineClass can get a
720 // LinkageError:: duplicate class definition.
721 // If they got a linkageError, check if a parallel class load succeeded.
722 // If it did, then for bytecode resolution the specification requires
723 // that we return the same result we did for the other thread, i.e. the
724 // successfully loaded instanceKlass
725 // Note: Class can not be unloaded as long as any classloader refs exist
726 // Should not get here for classloaders that support parallelism
727 // with the new cleaner mechanism, e.g. bootstrap classloader
728 if (UnsyncloadClass || (class_loader.is_null())) {
729 if (k.is_null() && HAS_PENDING_EXCEPTION
730 && PENDING_EXCEPTION->is_a(SystemDictionary::linkageError_klass())) {
731 MutexLocker mu(SystemDictionary_lock, THREAD);
732 klassOop check = find_class(d_index, d_hash, name, class_loader);
733 if (check != NULL) {
734 // Klass is already loaded, so just use it
735 k = instanceKlassHandle(THREAD, check);
736 CLEAR_PENDING_EXCEPTION;
737 guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
738 }
739 }
740 }
741
742 // clean up placeholder entries for success or error
743 // This cleans up LOAD_INSTANCE entries
744 // It also cleans up LOAD_SUPER entries on errors from
745 // calling load_instance_class
746 {
747 MutexLocker mu(SystemDictionary_lock, THREAD);
748 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name, class_loader);
749 if (probe != NULL) {
750 probe->remove_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE);
751 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
752 SystemDictionary_lock->notify_all();
753 }
754 }
755
756 // If everything was OK (no exceptions, no null return value), and
757 // class_loader is NOT the defining loader, do a little more bookkeeping.
758 if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
759 k->class_loader() != class_loader()) {
760
761 check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
762
763 // Need to check for a PENDING_EXCEPTION again; check_constraints
764 // can throw and doesn't use the CHECK macro.
765 if (!HAS_PENDING_EXCEPTION) {
766 { // Grabbing the Compile_lock prevents systemDictionary updates
767 // during compilations.
768 MutexLocker mu(Compile_lock, THREAD);
769 update_dictionary(d_index, d_hash, p_index, p_hash,
770 k, class_loader, THREAD);
771 }
772 if (JvmtiExport::should_post_class_load()) {
773 Thread *thread = THREAD;
774 assert(thread->is_Java_thread(), "thread->is_Java_thread()");
775 JvmtiExport::post_class_load((JavaThread *) thread, k());
776 }
777 }
778 }
779 if (HAS_PENDING_EXCEPTION || k.is_null()) {
780 // On error, clean up placeholders
781 {
782 MutexLocker mu(SystemDictionary_lock, THREAD);
783 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
784 SystemDictionary_lock->notify_all();
785 }
786 return NULL;
787 }
788 }
789 }
790
791 #ifdef ASSERT
792 {
793 Handle loader (THREAD, k->class_loader());
794 MutexLocker mu(SystemDictionary_lock, THREAD);
795 oop kk = find_class_or_placeholder(name, loader);
796 assert(kk == k(), "should be present in dictionary");
797 }
798 #endif
799
800 // return if the protection domain in NULL
801 if (protection_domain() == NULL) return k();
802
803 // Check the protection domain has the right access
804 {
805 MutexLocker mu(SystemDictionary_lock, THREAD);
806 // Note that we have an entry, and entries can be deleted only during GC,
807 // so we cannot allow GC to occur while we're holding this entry.
808 // We're using a No_Safepoint_Verifier to catch any place where we
809 // might potentially do a GC at all.
810 // SystemDictionary::do_unloading() asserts that classes are only
811 // unloaded at a safepoint.
812 No_Safepoint_Verifier nosafepoint;
813 if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
814 class_loader,
815 protection_domain)) {
816 return k();
817 }
818 }
819
820 // Verify protection domain. If it fails an exception is thrown
821 validate_protection_domain(k, class_loader, protection_domain, CHECK_(klassOop(NULL)));
822
823 return k();
824 }
825
826
827 // This routine does not lock the system dictionary.
828 //
829 // Since readers don't hold a lock, we must make sure that system
830 // dictionary entries are only removed at a safepoint (when only one
831 // thread is running), and are added to in a safe way (all links must
832 // be updated in an MT-safe manner).
833 //
834 // Callers should be aware that an entry could be added just after
835 // _dictionary->bucket(index) is read here, so the caller will not see
836 // the new entry.
837
838 klassOop SystemDictionary::find(symbolHandle class_name,
839 Handle class_loader,
840 Handle protection_domain,
841 TRAPS) {
842
843 unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
844 int d_index = dictionary()->hash_to_index(d_hash);
845
846 {
847 // Note that we have an entry, and entries can be deleted only during GC,
848 // so we cannot allow GC to occur while we're holding this entry.
849 // We're using a No_Safepoint_Verifier to catch any place where we
850 // might potentially do a GC at all.
851 // SystemDictionary::do_unloading() asserts that classes are only
852 // unloaded at a safepoint.
853 No_Safepoint_Verifier nosafepoint;
854 return dictionary()->find(d_index, d_hash, class_name, class_loader,
855 protection_domain, THREAD);
856 }
857 }
858
859
860 // Look for a loaded instance or array klass by name. Do not do any loading.
861 // return NULL in case of error.
862 klassOop SystemDictionary::find_instance_or_array_klass(symbolHandle class_name,
863 Handle class_loader,
864 Handle protection_domain,
865 TRAPS) {
866 klassOop k = NULL;
867 assert(class_name() != NULL, "class name must be non NULL");
868
869 // Try to get one of the well-known klasses.
870 k = find_well_known_klass(class_name());
871 if (k != NULL) {
872 return k;
873 }
874
875 if (FieldType::is_array(class_name())) {
876 // The name refers to an array. Parse the name.
877 jint dimension;
878 symbolOop object_key;
879
880 // dimension and object_key are assigned as a side-effect of this call
881 BasicType t = FieldType::get_array_info(class_name(), &dimension,
882 &object_key, CHECK_(NULL));
883 if (t != T_OBJECT) {
884 k = Universe::typeArrayKlassObj(t);
885 } else {
886 symbolHandle h_key(THREAD, object_key);
887 k = SystemDictionary::find(h_key, class_loader, protection_domain, THREAD);
888 }
889 if (k != NULL) {
890 k = Klass::cast(k)->array_klass_or_null(dimension);
891 }
892 } else {
893 k = find(class_name, class_loader, protection_domain, THREAD);
894 }
895 return k;
896 }
897
898 // Quick range check for names of well-known classes:
899 static symbolOop wk_klass_name_limits[2] = {NULL, NULL};
900
901 #ifndef PRODUCT
902 static int find_wkk_calls, find_wkk_probes, find_wkk_wins;
903 // counts for "hello world": 3983, 1616, 1075
904 // => 60% hit after limit guard, 25% total win rate
905 #endif
906
907 klassOop SystemDictionary::find_well_known_klass(symbolOop class_name) {
908 // A bounds-check on class_name will quickly get a negative result.
909 NOT_PRODUCT(find_wkk_calls++);
910 if (class_name >= wk_klass_name_limits[0] &&
911 class_name <= wk_klass_name_limits[1]) {
912 NOT_PRODUCT(find_wkk_probes++);
913 vmSymbols::SID sid = vmSymbols::find_sid(class_name);
914 if (sid != vmSymbols::NO_SID) {
915 klassOop k = NULL;
916 switch (sid) {
917 #define WK_KLASS_CASE(name, symbol, ignore_option) \
918 case vmSymbols::VM_SYMBOL_ENUM_NAME(symbol): \
919 k = WK_KLASS(name); break;
920 WK_KLASSES_DO(WK_KLASS_CASE)
921 #undef WK_KLASS_CASE
922 }
923 NOT_PRODUCT(if (k != NULL) find_wkk_wins++);
924 return k;
925 }
926 }
927 return NULL;
928 }
929
930 // Note: this method is much like resolve_from_stream, but
931 // updates no supplemental data structures.
932 // TODO consolidate the two methods with a helper routine?
933 klassOop SystemDictionary::parse_stream(symbolHandle class_name,
934 Handle class_loader,
935 Handle protection_domain,
936 ClassFileStream* st,
937 KlassHandle host_klass,
938 GrowableArray<Handle>* cp_patches,
939 TRAPS) {
940 symbolHandle parsed_name;
941
942 // Parse the stream. Note that we do this even though this klass might
943 // already be present in the SystemDictionary, otherwise we would not
944 // throw potential ClassFormatErrors.
945 //
946 // Note: "name" is updated.
947 // Further note: a placeholder will be added for this class when
948 // super classes are loaded (resolve_super_or_fail). We expect this
949 // to be called for all classes but java.lang.Object; and we preload
950 // java.lang.Object through resolve_or_fail, not this path.
951
952 instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
953 class_loader,
954 protection_domain,
955 cp_patches,
956 parsed_name,
957 THREAD);
958
959 // We don't redefine the class, so we just need to clean up whether there
960 // was an error or not (don't want to modify any system dictionary
961 // data structures).
962 // Parsed name could be null if we threw an error before we got far
963 // enough along to parse it -- in that case, there is nothing to clean up.
964 if (!parsed_name.is_null()) {
965 unsigned int p_hash = placeholders()->compute_hash(parsed_name,
966 class_loader);
967 int p_index = placeholders()->hash_to_index(p_hash);
968 {
969 MutexLocker mu(SystemDictionary_lock, THREAD);
970 placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
971 SystemDictionary_lock->notify_all();
972 }
973 }
974
975 if (host_klass.not_null() && k.not_null()) {
976 // If it's anonymous, initialize it now, since nobody else will.
977 k->set_host_klass(host_klass());
978
979 {
980 MutexLocker mu_r(Compile_lock, THREAD);
981
982 // Add to class hierarchy, initialize vtables, and do possible
983 // deoptimizations.
984 add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
985
986 // But, do not add to system dictionary.
987 }
988
989 k->eager_initialize(THREAD);
990
991 // notify jvmti
992 if (JvmtiExport::should_post_class_load()) {
993 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
994 JvmtiExport::post_class_load((JavaThread *) THREAD, k());
995 }
996 }
997
998 return k();
999 }
1000
1001 // Add a klass to the system from a stream (called by jni_DefineClass and
1002 // JVM_DefineClass).
1003 // Note: class_name can be NULL. In that case we do not know the name of
1004 // the class until we have parsed the stream.
1005
1006 klassOop SystemDictionary::resolve_from_stream(symbolHandle class_name,
1007 Handle class_loader,
1008 Handle protection_domain,
1009 ClassFileStream* st,
1010 TRAPS) {
1011
1012 // Make sure we are synchronized on the class loader before we initiate
1013 // loading.
1014 Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1015 check_loader_lock_contention(lockObject, THREAD);
1016 ObjectLocker ol(lockObject, THREAD);
1017
1018 symbolHandle parsed_name;
1019
1020 // Parse the stream. Note that we do this even though this klass might
1021 // already be present in the SystemDictionary, otherwise we would not
1022 // throw potential ClassFormatErrors.
1023 //
1024 // Note: "name" is updated.
1025 // Further note: a placeholder will be added for this class when
1026 // super classes are loaded (resolve_super_or_fail). We expect this
1027 // to be called for all classes but java.lang.Object; and we preload
1028 // java.lang.Object through resolve_or_fail, not this path.
1029
1030 instanceKlassHandle k = ClassFileParser(st).parseClassFile(class_name,
1031 class_loader,
1032 protection_domain,
1033 parsed_name,
1034 THREAD);
1035
1036 const char* pkg = "java/";
1037 if (!HAS_PENDING_EXCEPTION &&
1038 !class_loader.is_null() &&
1039 !parsed_name.is_null() &&
1040 !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
1041 // It is illegal to define classes in the "java." package from
1042 // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
1043 ResourceMark rm(THREAD);
1044 char* name = parsed_name->as_C_string();
1045 char* index = strrchr(name, '/');
1046 *index = '\0'; // chop to just the package name
1047 while ((index = strchr(name, '/')) != NULL) {
1048 *index = '.'; // replace '/' with '.' in package name
1049 }
1050 const char* fmt = "Prohibited package name: %s";
1051 size_t len = strlen(fmt) + strlen(name);
1052 char* message = NEW_RESOURCE_ARRAY(char, len);
1053 jio_snprintf(message, len, fmt, name);
1054 Exceptions::_throw_msg(THREAD_AND_LOCATION,
1055 vmSymbols::java_lang_SecurityException(), message);
1056 }
1057
1058 if (!HAS_PENDING_EXCEPTION) {
1059 assert(!parsed_name.is_null(), "Sanity");
1060 assert(class_name.is_null() || class_name() == parsed_name(),
1061 "name mismatch");
1062 // Verification prevents us from creating names with dots in them, this
1063 // asserts that that's the case.
1064 assert(is_internal_format(parsed_name),
1065 "external class name format used internally");
1066
1067 // Add class just loaded
1068 define_instance_class(k, THREAD);
1069 }
1070
1071 // If parsing the class file or define_instance_class failed, we
1072 // need to remove the placeholder added on our behalf. But we
1073 // must make sure parsed_name is valid first (it won't be if we had
1074 // a format error before the class was parsed far enough to
1075 // find the name).
1076 if (HAS_PENDING_EXCEPTION && !parsed_name.is_null()) {
1077 unsigned int p_hash = placeholders()->compute_hash(parsed_name,
1078 class_loader);
1079 int p_index = placeholders()->hash_to_index(p_hash);
1080 {
1081 MutexLocker mu(SystemDictionary_lock, THREAD);
1082 placeholders()->find_and_remove(p_index, p_hash, parsed_name, class_loader, THREAD);
1083 SystemDictionary_lock->notify_all();
1084 }
1085 return NULL;
1086 }
1087
1088 // Make sure that we didn't leave a place holder in the
1089 // SystemDictionary; this is only done on success
1090 debug_only( {
1091 if (!HAS_PENDING_EXCEPTION) {
1092 assert(!parsed_name.is_null(), "parsed_name is still null?");
1093 symbolHandle h_name (THREAD, k->name());
1094 Handle h_loader (THREAD, k->class_loader());
1095
1096 MutexLocker mu(SystemDictionary_lock, THREAD);
1097
1098 oop check = find_class_or_placeholder(parsed_name, class_loader);
1099 assert(check == k(), "should be present in the dictionary");
1100
1101 oop check2 = find_class_or_placeholder(h_name, h_loader);
1102 assert(check == check2, "name inconsistancy in SystemDictionary");
1103 }
1104 } );
1105
1106 return k();
1107 }
1108
1109
1110 void SystemDictionary::set_shared_dictionary(HashtableBucket* t, int length,
1111 int number_of_entries) {
1112 assert(length == _nof_buckets * sizeof(HashtableBucket),
1113 "bad shared dictionary size.");
1114 _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
1115 }
1116
1117
1118 // If there is a shared dictionary, then find the entry for the
1119 // given shared system class, if any.
1120
1121 klassOop SystemDictionary::find_shared_class(symbolHandle class_name) {
1122 if (shared_dictionary() != NULL) {
1123 unsigned int d_hash = dictionary()->compute_hash(class_name, Handle());
1124 int d_index = dictionary()->hash_to_index(d_hash);
1125 return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1126 } else {
1127 return NULL;
1128 }
1129 }
1130
1131
1132 // Load a class from the shared spaces (found through the shared system
1133 // dictionary). Force the superclass and all interfaces to be loaded.
1134 // Update the class definition to include sibling classes and no
1135 // subclasses (yet). [Classes in the shared space are not part of the
1136 // object hierarchy until loaded.]
1137
1138 instanceKlassHandle SystemDictionary::load_shared_class(
1139 symbolHandle class_name, Handle class_loader, TRAPS) {
1140 instanceKlassHandle ik (THREAD, find_shared_class(class_name));
1141 return load_shared_class(ik, class_loader, THREAD);
1142 }
1143
1144 // Note well! Changes to this method may affect oop access order
1145 // in the shared archive. Please take care to not make changes that
1146 // adversely affect cold start time by changing the oop access order
1147 // that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
1148 // MarkAndMoveOrderedReadWrite closures.
1149 instanceKlassHandle SystemDictionary::load_shared_class(
1150 instanceKlassHandle ik, Handle class_loader, TRAPS) {
1151 assert(class_loader.is_null(), "non-null classloader for shared class?");
1152 if (ik.not_null()) {
1153 instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1154 symbolHandle class_name(THREAD, ik->name());
1155
1156 // Found the class, now load the superclass and interfaces. If they
1157 // are shared, add them to the main system dictionary and reset
1158 // their hierarchy references (supers, subs, and interfaces).
1159
1160 if (ik->super() != NULL) {
1161 symbolHandle cn(THREAD, ik->super()->klass_part()->name());
1162 resolve_super_or_fail(class_name, cn,
1163 class_loader, Handle(), true, CHECK_(nh));
1164 }
1165
1166 objArrayHandle interfaces (THREAD, ik->local_interfaces());
1167 int num_interfaces = interfaces->length();
1168 for (int index = 0; index < num_interfaces; index++) {
1169 klassOop k = klassOop(interfaces->obj_at(index));
1170
1171 // Note: can not use instanceKlass::cast here because
1172 // interfaces' instanceKlass's C++ vtbls haven't been
1173 // reinitialized yet (they will be once the interface classes
1174 // are loaded)
1175 symbolHandle name (THREAD, k->klass_part()->name());
1176 resolve_super_or_fail(class_name, name, class_loader, Handle(), false, CHECK_(nh));
1177 }
1178
1179 // Adjust methods to recover missing data. They need addresses for
1180 // interpreter entry points and their default native method address
1181 // must be reset.
1182
1183 // Updating methods must be done under a lock so multiple
1184 // threads don't update these in parallel
1185 // Shared classes are all currently loaded by the bootstrap
1186 // classloader, so this will never cause a deadlock on
1187 // a custom class loader lock.
1188
1189 {
1190 Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1191 check_loader_lock_contention(lockObject, THREAD);
1192 ObjectLocker ol(lockObject, THREAD, true);
1193
1194 objArrayHandle methods (THREAD, ik->methods());
1195 int num_methods = methods->length();
1196 for (int index2 = 0; index2 < num_methods; ++index2) {
1197 methodHandle m(THREAD, methodOop(methods->obj_at(index2)));
1198 m()->link_method(m, CHECK_(nh));
1199 }
1200 }
1201
1202 if (TraceClassLoading) {
1203 ResourceMark rm;
1204 tty->print("[Loaded %s", ik->external_name());
1205 tty->print(" from shared objects file");
1206 tty->print_cr("]");
1207 }
1208 // notify a class loaded from shared object
1209 ClassLoadingService::notify_class_loaded(instanceKlass::cast(ik()),
1210 true /* shared class */);
1211 }
1212 return ik;
1213 }
1214
1215 #ifdef KERNEL
1216 // Some classes on the bootstrap class path haven't been installed on the
1217 // system yet. Call the DownloadManager method to make them appear in the
1218 // bootstrap class path and try again to load the named class.
1219 // Note that with delegation class loaders all classes in another loader will
1220 // first try to call this so it'd better be fast!!
1221 static instanceKlassHandle download_and_retry_class_load(
1222 symbolHandle class_name,
1223 TRAPS) {
1224
1225 klassOop dlm = SystemDictionary::sun_jkernel_DownloadManager_klass();
1226 instanceKlassHandle nk;
1227
1228 // If download manager class isn't loaded just return.
1229 if (dlm == NULL) return nk;
1230
1231 { HandleMark hm(THREAD);
1232 ResourceMark rm(THREAD);
1233 Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nk));
1234 Handle class_string = java_lang_String::externalize_classname(s, CHECK_(nk));
1235
1236 // return value
1237 JavaValue result(T_OBJECT);
1238
1239 // Call the DownloadManager. We assume that it has a lock because
1240 // multiple classes could be not found and downloaded at the same time.
1241 // class sun.misc.DownloadManager;
1242 // public static String getBootClassPathEntryForClass(String className);
1243 JavaCalls::call_static(&result,
1244 KlassHandle(THREAD, dlm),
1245 vmSymbolHandles::getBootClassPathEntryForClass_name(),
1246 vmSymbolHandles::string_string_signature(),
1247 class_string,
1248 CHECK_(nk));
1249
1250 // Get result.string and add to bootclasspath
1251 assert(result.get_type() == T_OBJECT, "just checking");
1252 oop obj = (oop) result.get_jobject();
1253 if (obj == NULL) { return nk; }
1254
1255 char* new_class_name = java_lang_String::as_utf8_string(obj);
1256
1257 // lock the loader
1258 // we use this lock because JVMTI does.
1259 Handle loader_lock(THREAD, SystemDictionary::system_loader_lock());
1260
1261 ObjectLocker ol(loader_lock, THREAD);
1262 // add the file to the bootclasspath
1263 ClassLoader::update_class_path_entry_list(new_class_name, true);
1264 } // end HandleMark
1265
1266 if (TraceClassLoading) {
1267 ClassLoader::print_bootclasspath();
1268 }
1269 return ClassLoader::load_classfile(class_name, CHECK_(nk));
1270 }
1271 #endif // KERNEL
1272
1273
1274 instanceKlassHandle SystemDictionary::load_instance_class(symbolHandle class_name, Handle class_loader, TRAPS) {
1275 instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1276 if (class_loader.is_null()) {
1277 // Search the shared system dictionary for classes preloaded into the
1278 // shared spaces.
1279 instanceKlassHandle k;
1280 k = load_shared_class(class_name, class_loader, THREAD);
1281
1282 if (k.is_null()) {
1283 // Use VM class loader
1284 k = ClassLoader::load_classfile(class_name, CHECK_(nh));
1285 }
1286
1287 #ifdef KERNEL
1288 // If the VM class loader has failed to load the class, call the
1289 // DownloadManager class to make it magically appear on the classpath
1290 // and try again. This is only configured with the Kernel VM.
1291 if (k.is_null()) {
1292 k = download_and_retry_class_load(class_name, CHECK_(nh));
1293 }
1294 #endif // KERNEL
1295
1296 // find_or_define_instance_class may return a different k
1297 if (!k.is_null()) {
1298 k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
1299 }
1300 return k;
1301 } else {
1302 // Use user specified class loader to load class. Call loadClass operation on class_loader.
1303 ResourceMark rm(THREAD);
1304
1305 Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
1306 // Translate to external class name format, i.e., convert '/' chars to '.'
1307 Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
1308
1309 JavaValue result(T_OBJECT);
1310
1311 KlassHandle spec_klass (THREAD, SystemDictionary::classloader_klass());
1312
1313 // UnsyncloadClass option means don't synchronize loadClass() calls.
1314 // loadClassInternal() is synchronized and public loadClass(String) is not.
1315 // This flag is for diagnostic purposes only. It is risky to call
1316 // custom class loaders without synchronization.
1317 // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1318 // findClass, this flag risks unexpected timing bugs in the field.
1319 // Do NOT assume this will be supported in future releases.
1320 if (!UnsyncloadClass && has_loadClassInternal()) {
1321 JavaCalls::call_special(&result,
1322 class_loader,
1323 spec_klass,
1324 vmSymbolHandles::loadClassInternal_name(),
1325 vmSymbolHandles::string_class_signature(),
1326 string,
1327 CHECK_(nh));
1328 } else {
1329 JavaCalls::call_virtual(&result,
1330 class_loader,
1331 spec_klass,
1332 vmSymbolHandles::loadClass_name(),
1333 vmSymbolHandles::string_class_signature(),
1334 string,
1335 CHECK_(nh));
1336 }
1337
1338 assert(result.get_type() == T_OBJECT, "just checking");
1339 oop obj = (oop) result.get_jobject();
1340
1341 // Primitive classes return null since forName() can not be
1342 // used to obtain any of the Class objects representing primitives or void
1343 if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1344 instanceKlassHandle k =
1345 instanceKlassHandle(THREAD, java_lang_Class::as_klassOop(obj));
1346 // For user defined Java class loaders, check that the name returned is
1347 // the same as that requested. This check is done for the bootstrap
1348 // loader when parsing the class file.
1349 if (class_name() == k->name()) {
1350 return k;
1351 }
1352 }
1353 // Class is not found or has the wrong name, return NULL
1354 return nh;
1355 }
1356 }
1357
1358 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
1359
1360 Handle class_loader_h(THREAD, k->class_loader());
1361
1362 // for bootstrap classloader don't acquire lock
1363 if (!class_loader_h.is_null()) {
1364 assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1365 compute_loader_lock_object(class_loader_h, THREAD)),
1366 "define called without lock");
1367 }
1368
1369
1370 // Check class-loading constraints. Throw exception if violation is detected.
1371 // Grabs and releases SystemDictionary_lock
1372 // The check_constraints/find_class call and update_dictionary sequence
1373 // must be "atomic" for a specific class/classloader pair so we never
1374 // define two different instanceKlasses for that class/classloader pair.
1375 // Existing classloaders will call define_instance_class with the
1376 // classloader lock held
1377 // Parallel classloaders will call find_or_define_instance_class
1378 // which will require a token to perform the define class
1379 symbolHandle name_h(THREAD, k->name());
1380 unsigned int d_hash = dictionary()->compute_hash(name_h, class_loader_h);
1381 int d_index = dictionary()->hash_to_index(d_hash);
1382 check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1383
1384 // Register class just loaded with class loader (placed in Vector)
1385 // Note we do this before updating the dictionary, as this can
1386 // fail with an OutOfMemoryError (if it does, we will *not* put this
1387 // class in the dictionary and will not update the class hierarchy).
1388 if (k->class_loader() != NULL) {
1389 methodHandle m(THREAD, Universe::loader_addClass_method());
1390 JavaValue result(T_VOID);
1391 JavaCallArguments args(class_loader_h);
1392 args.push_oop(Handle(THREAD, k->java_mirror()));
1393 JavaCalls::call(&result, m, &args, CHECK);
1394 }
1395
1396 // Add the new class. We need recompile lock during update of CHA.
1397 {
1398 unsigned int p_hash = placeholders()->compute_hash(name_h, class_loader_h);
1399 int p_index = placeholders()->hash_to_index(p_hash);
1400
1401 MutexLocker mu_r(Compile_lock, THREAD);
1402
1403 // Add to class hierarchy, initialize vtables, and do possible
1404 // deoptimizations.
1405 add_to_hierarchy(k, CHECK); // No exception, but can block
1406
1407 // Add to systemDictionary - so other classes can see it.
1408 // Grabs and releases SystemDictionary_lock
1409 update_dictionary(d_index, d_hash, p_index, p_hash,
1410 k, class_loader_h, THREAD);
1411 }
1412 k->eager_initialize(THREAD);
1413
1414 // notify jvmti
1415 if (JvmtiExport::should_post_class_load()) {
1416 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1417 JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1418
1419 }
1420 }
1421
1422 // Support parallel classloading
1423 // Initial implementation for bootstrap classloader
1424 // For future:
1425 // For custom class loaders that support parallel classloading,
1426 // in case they do not synchronize around
1427 // FindLoadedClass/DefineClass calls, we check for parallel
1428 // loading for them, wait if a defineClass is in progress
1429 // and return the initial requestor's results
1430 // For better performance, the class loaders should synchronize
1431 // findClass(), i.e. FindLoadedClass/DefineClass or they
1432 // potentially waste time reading and parsing the bytestream.
1433 // Note: VM callers should ensure consistency of k/class_name,class_loader
1434 instanceKlassHandle SystemDictionary::find_or_define_instance_class(symbolHandle class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
1435
1436 instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1437
1438 unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
1439 int d_index = dictionary()->hash_to_index(d_hash);
1440
1441 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1442 unsigned int p_hash = placeholders()->compute_hash(class_name, class_loader);
1443 int p_index = placeholders()->hash_to_index(p_hash);
1444 PlaceholderEntry* probe;
1445
1446 {
1447 MutexLocker mu(SystemDictionary_lock, THREAD);
1448 // First check if class already defined
1449 klassOop check = find_class(d_index, d_hash, class_name, class_loader);
1450 if (check != NULL) {
1451 return(instanceKlassHandle(THREAD, check));
1452 }
1453
1454 // Acquire define token for this class/classloader
1455 symbolHandle nullsymbolHandle;
1456 probe = placeholders()->find_and_add(p_index, p_hash, class_name, class_loader, PlaceholderTable::DEFINE_CLASS, nullsymbolHandle, THREAD);
1457 // Check if another thread defining in parallel
1458 if (probe->definer() == NULL) {
1459 // Thread will define the class
1460 probe->set_definer(THREAD);
1461 } else {
1462 // Wait for defining thread to finish and return results
1463 while (probe->definer() != NULL) {
1464 SystemDictionary_lock->wait();
1465 }
1466 if (probe->instanceKlass() != NULL) {
1467 probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
1468 return(instanceKlassHandle(THREAD, probe->instanceKlass()));
1469 } else {
1470 // If definer had an error, try again as any new thread would
1471 probe->set_definer(THREAD);
1472 #ifdef ASSERT
1473 klassOop check = find_class(d_index, d_hash, class_name, class_loader);
1474 assert(check == NULL, "definer missed recording success");
1475 #endif
1476 }
1477 }
1478 }
1479
1480 define_instance_class(k, THREAD);
1481
1482 Handle linkage_exception = Handle(); // null handle
1483
1484 // definer must notify any waiting threads
1485 {
1486 MutexLocker mu(SystemDictionary_lock, THREAD);
1487 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, class_name, class_loader);
1488 assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1489 if (probe != NULL) {
1490 if (HAS_PENDING_EXCEPTION) {
1491 linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1492 CLEAR_PENDING_EXCEPTION;
1493 } else {
1494 probe->set_instanceKlass(k());
1495 }
1496 probe->set_definer(NULL);
1497 probe->remove_seen_thread(THREAD, PlaceholderTable::DEFINE_CLASS);
1498 SystemDictionary_lock->notify_all();
1499 }
1500 }
1501
1502 // Can't throw exception while holding lock due to rank ordering
1503 if (linkage_exception() != NULL) {
1504 THROW_OOP_(linkage_exception(), nh); // throws exception and returns
1505 }
1506
1507 return k;
1508 }
1509
1510 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1511 // If class_loader is NULL we synchronize on _system_loader_lock_obj
1512 if (class_loader.is_null()) {
1513 return Handle(THREAD, _system_loader_lock_obj);
1514 } else {
1515 return class_loader;
1516 }
1517 }
1518
1519 // This method is added to check how often we have to wait to grab loader
1520 // lock. The results are being recorded in the performance counters defined in
1521 // ClassLoader::_sync_systemLoaderLockContentionRate and
1522 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1523 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1524 if (!UsePerfData) {
1525 return;
1526 }
1527
1528 assert(!loader_lock.is_null(), "NULL lock object");
1529
1530 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1531 == ObjectSynchronizer::owner_other) {
1532 // contention will likely happen, so increment the corresponding
1533 // contention counter.
1534 if (loader_lock() == _system_loader_lock_obj) {
1535 ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1536 } else {
1537 ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1538 }
1539 }
1540 }
1541
1542 // ----------------------------------------------------------------------------
1543 // Lookup
1544
1545 klassOop SystemDictionary::find_class(int index, unsigned int hash,
1546 symbolHandle class_name,
1547 Handle class_loader) {
1548 assert_locked_or_safepoint(SystemDictionary_lock);
1549 assert (index == dictionary()->index_for(class_name, class_loader),
1550 "incorrect index?");
1551
1552 klassOop k = dictionary()->find_class(index, hash, class_name, class_loader);
1553 return k;
1554 }
1555
1556
1557 // Basic find on classes in the midst of being loaded
1558 symbolOop SystemDictionary::find_placeholder(int index, unsigned int hash,
1559 symbolHandle class_name,
1560 Handle class_loader) {
1561 assert_locked_or_safepoint(SystemDictionary_lock);
1562
1563 return placeholders()->find_entry(index, hash, class_name, class_loader);
1564 }
1565
1566
1567 // Used for assertions and verification only
1568 oop SystemDictionary::find_class_or_placeholder(symbolHandle class_name,
1569 Handle class_loader) {
1570 #ifndef ASSERT
1571 guarantee(VerifyBeforeGC ||
1572 VerifyDuringGC ||
1573 VerifyBeforeExit ||
1574 VerifyAfterGC, "too expensive");
1575 #endif
1576 assert_locked_or_safepoint(SystemDictionary_lock);
1577 symbolOop class_name_ = class_name();
1578 oop class_loader_ = class_loader();
1579
1580 // First look in the loaded class array
1581 unsigned int d_hash = dictionary()->compute_hash(class_name, class_loader);
1582 int d_index = dictionary()->hash_to_index(d_hash);
1583 oop lookup = find_class(d_index, d_hash, class_name, class_loader);
1584
1585 if (lookup == NULL) {
1586 // Next try the placeholders
1587 unsigned int p_hash = placeholders()->compute_hash(class_name,class_loader);
1588 int p_index = placeholders()->hash_to_index(p_hash);
1589 lookup = find_placeholder(p_index, p_hash, class_name, class_loader);
1590 }
1591
1592 return lookup;
1593 }
1594
1595
1596 // Get the next class in the diictionary.
1597 klassOop SystemDictionary::try_get_next_class() {
1598 return dictionary()->try_get_next_class();
1599 }
1600
1601
1602 // ----------------------------------------------------------------------------
1603 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1604 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1605 // before a new class is used.
1606
1607 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
1608 assert(k.not_null(), "just checking");
1609 // Link into hierachy. Make sure the vtables are initialized before linking into
1610 k->append_to_sibling_list(); // add to superklass/sibling list
1611 k->process_interfaces(THREAD); // handle all "implements" declarations
1612 k->set_init_state(instanceKlass::loaded);
1613 // Now flush all code that depended on old class hierarchy.
1614 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1615 // Also, first reinitialize vtable because it may have gotten out of synch
1616 // while the new class wasn't connected to the class hierarchy.
1617 Universe::flush_dependents_on(k);
1618 }
1619
1620
1621 // ----------------------------------------------------------------------------
1622 // GC support
1623
1624 // Following roots during mark-sweep is separated in two phases.
1625 //
1626 // The first phase follows preloaded classes and all other system
1627 // classes, since these will never get unloaded anyway.
1628 //
1629 // The second phase removes (unloads) unreachable classes from the
1630 // system dictionary and follows the remaining classes' contents.
1631
1632 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1633 // Follow preloaded classes/mirrors and system loader object
1634 blk->do_oop(&_java_system_loader);
1635 preloaded_oops_do(blk);
1636 always_strong_classes_do(blk);
1637 }
1638
1639
1640 void SystemDictionary::always_strong_classes_do(OopClosure* blk) {
1641 // Follow all system classes and temporary placeholders in dictionary
1642 dictionary()->always_strong_classes_do(blk);
1643
1644 // Placeholders. These are *always* strong roots, as they
1645 // represent classes we're actively loading.
1646 placeholders_do(blk);
1647
1648 // Loader constraints. We must keep the symbolOop used in the name alive.
1649 constraints()->always_strong_classes_do(blk);
1650
1651 // Resolution errors keep the symbolOop for the error alive
1652 resolution_errors()->always_strong_classes_do(blk);
1653 }
1654
1655
1656 void SystemDictionary::placeholders_do(OopClosure* blk) {
1657 placeholders()->oops_do(blk);
1658 }
1659
1660
1661 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive) {
1662 bool result = dictionary()->do_unloading(is_alive);
1663 constraints()->purge_loader_constraints(is_alive);
1664 resolution_errors()->purge_resolution_errors(is_alive);
1665 return result;
1666 }
1667
1668
1669 // The mirrors are scanned by shared_oops_do() which is
1670 // not called by oops_do(). In order to process oops in
1671 // a necessary order, shared_oops_do() is call by
1672 // Universe::oops_do().
1673 void SystemDictionary::oops_do(OopClosure* f) {
1674 // Adjust preloaded classes and system loader object
1675 f->do_oop(&_java_system_loader);
1676 preloaded_oops_do(f);
1677
1678 lazily_loaded_oops_do(f);
1679
1680 // Adjust dictionary
1681 dictionary()->oops_do(f);
1682
1683 // Partially loaded classes
1684 placeholders()->oops_do(f);
1685
1686 // Adjust constraint table
1687 constraints()->oops_do(f);
1688
1689 // Adjust resolution error table
1690 resolution_errors()->oops_do(f);
1691 }
1692
1693
1694 void SystemDictionary::preloaded_oops_do(OopClosure* f) {
1695 f->do_oop((oop*) &wk_klass_name_limits[0]);
1696 f->do_oop((oop*) &wk_klass_name_limits[1]);
1697
1698 for (int k = (int)FIRST_WKID; k < (int)WKID_LIMIT; k++) {
1699 f->do_oop((oop*) &_well_known_klasses[k]);
1700 }
1701
1702 {
1703 for (int i = 0; i < T_VOID+1; i++) {
1704 if (_box_klasses[i] != NULL) {
1705 assert(i >= T_BOOLEAN, "checking");
1706 f->do_oop((oop*) &_box_klasses[i]);
1707 }
1708 }
1709 }
1710
1711 // The basic type mirrors would have already been processed in
1712 // Universe::oops_do(), via a call to shared_oops_do(), so should
1713 // not be processed again.
1714
1715 f->do_oop((oop*) &_system_loader_lock_obj);
1716 FilteredFieldsMap::klasses_oops_do(f);
1717 }
1718
1719 void SystemDictionary::lazily_loaded_oops_do(OopClosure* f) {
1720 f->do_oop((oop*) &_abstract_ownable_synchronizer_klass);
1721 }
1722
1723 // Just the classes from defining class loaders
1724 // Don't iterate over placeholders
1725 void SystemDictionary::classes_do(void f(klassOop)) {
1726 dictionary()->classes_do(f);
1727 }
1728
1729 // Added for initialize_itable_for_klass
1730 // Just the classes from defining class loaders
1731 // Don't iterate over placeholders
1732 void SystemDictionary::classes_do(void f(klassOop, TRAPS), TRAPS) {
1733 dictionary()->classes_do(f, CHECK);
1734 }
1735
1736 // All classes, and their class loaders
1737 // Don't iterate over placeholders
1738 void SystemDictionary::classes_do(void f(klassOop, oop)) {
1739 dictionary()->classes_do(f);
1740 }
1741
1742 // All classes, and their class loaders
1743 // (added for helpers that use HandleMarks and ResourceMarks)
1744 // Don't iterate over placeholders
1745 void SystemDictionary::classes_do(void f(klassOop, oop, TRAPS), TRAPS) {
1746 dictionary()->classes_do(f, CHECK);
1747 }
1748
1749 void SystemDictionary::placeholders_do(void f(symbolOop, oop)) {
1750 placeholders()->entries_do(f);
1751 }
1752
1753 void SystemDictionary::methods_do(void f(methodOop)) {
1754 dictionary()->methods_do(f);
1755 }
1756
1757 // ----------------------------------------------------------------------------
1758 // Lazily load klasses
1759
1760 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
1761 assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
1762
1763 // if multiple threads calling this function, only one thread will load
1764 // the class. The other threads will find the loaded version once the
1765 // class is loaded.
1766 klassOop aos = _abstract_ownable_synchronizer_klass;
1767 if (aos == NULL) {
1768 klassOop k = resolve_or_fail(vmSymbolHandles::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
1769 // Force a fence to prevent any read before the write completes
1770 OrderAccess::fence();
1771 _abstract_ownable_synchronizer_klass = k;
1772 }
1773 }
1774
1775 // ----------------------------------------------------------------------------
1776 // Initialization
1777
1778 void SystemDictionary::initialize(TRAPS) {
1779 // Allocate arrays
1780 assert(dictionary() == NULL,
1781 "SystemDictionary should only be initialized once");
1782 _dictionary = new Dictionary(_nof_buckets);
1783 _placeholders = new PlaceholderTable(_nof_buckets);
1784 _number_of_modifications = 0;
1785 _loader_constraints = new LoaderConstraintTable(_loader_constraint_size);
1786 _resolution_errors = new ResolutionErrorTable(_resolution_error_size);
1787
1788 // Allocate private object used as system class loader lock
1789 _system_loader_lock_obj = oopFactory::new_system_objArray(0, CHECK);
1790 // Initialize basic classes
1791 initialize_preloaded_classes(CHECK);
1792 }
1793
1794 // Compact table of directions on the initialization of klasses:
1795 static const short wk_init_info[] = {
1796 #define WK_KLASS_INIT_INFO(name, symbol, option) \
1797 ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) << 1) \
1798 | (SystemDictionary::option < SystemDictionary::Opt ? 0 : 1) ),
1799 WK_KLASSES_DO(WK_KLASS_INIT_INFO)
1800 #undef WK_KLASS_INIT_INFO
1801 0
1802 };
1803
1804 bool SystemDictionary::initialize_wk_klass(WKID id, bool must_load, TRAPS) {
1805 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1806 int info = wk_init_info[id - FIRST_WKID];
1807 int sid = (info >> 1);
1808 symbolHandle symbol = vmSymbolHandles::symbol_handle_at((vmSymbols::SID)sid);
1809 klassOop* klassp = &_well_known_klasses[id];
1810 if ((*klassp) == NULL) {
1811 if (must_load) {
1812 (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
1813 } else {
1814 (*klassp) = resolve_or_null(symbol, CHECK_0); // load optional klass
1815 }
1816 }
1817 return ((*klassp) != NULL);
1818 }
1819
1820 void SystemDictionary::initialize_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
1821 assert((int)start_id <= (int)limit_id, "IDs are out of order!");
1822 for (int id = (int)start_id; id < (int)limit_id; id++) {
1823 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1824 int info = wk_init_info[id - FIRST_WKID];
1825 int sid = (info >> 1);
1826 bool opt = (info & 1);
1827
1828 initialize_wk_klass((WKID)id, !opt, CHECK);
1829
1830 // Update limits, so find_well_known_klass can be very fast:
1831 symbolOop s = vmSymbols::symbol_at((vmSymbols::SID)sid);
1832 if (wk_klass_name_limits[1] == NULL) {
1833 wk_klass_name_limits[0] = wk_klass_name_limits[1] = s;
1834 } else if (wk_klass_name_limits[1] < s) {
1835 wk_klass_name_limits[1] = s;
1836 } else if (wk_klass_name_limits[0] > s) {
1837 wk_klass_name_limits[0] = s;
1838 }
1839 }
1840 }
1841
1842
1843 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
1844 assert(WK_KLASS(object_klass) == NULL, "preloaded classes should only be initialized once");
1845 // Preload commonly used klasses
1846 WKID scan = FIRST_WKID;
1847 // first do Object, String, Class
1848 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(class_klass), scan, CHECK);
1849
1850 debug_only(instanceKlass::verify_class_klass_nonstatic_oop_maps(WK_KLASS(class_klass)));
1851
1852 // Fixup mirrors for classes loaded before java.lang.Class.
1853 // These calls iterate over the objects currently in the perm gen
1854 // so calling them at this point is matters (not before when there
1855 // are fewer objects and not later after there are more objects
1856 // in the perm gen.
1857 Universe::initialize_basic_type_mirrors(CHECK);
1858 Universe::fixup_mirrors(CHECK);
1859
1860 // do a bunch more:
1861 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(reference_klass), scan, CHECK);
1862
1863 // Preload ref klasses and set reference types
1864 instanceKlass::cast(WK_KLASS(reference_klass))->set_reference_type(REF_OTHER);
1865 instanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(reference_klass));
1866
1867 initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(phantom_reference_klass), scan, CHECK);
1868 instanceKlass::cast(WK_KLASS(soft_reference_klass))->set_reference_type(REF_SOFT);
1869 instanceKlass::cast(WK_KLASS(weak_reference_klass))->set_reference_type(REF_WEAK);
1870 instanceKlass::cast(WK_KLASS(final_reference_klass))->set_reference_type(REF_FINAL);
1871 instanceKlass::cast(WK_KLASS(phantom_reference_klass))->set_reference_type(REF_PHANTOM);
1872
1873 initialize_wk_klasses_until(WKID_LIMIT, scan, CHECK);
1874
1875 _box_klasses[T_BOOLEAN] = WK_KLASS(boolean_klass);
1876 _box_klasses[T_CHAR] = WK_KLASS(char_klass);
1877 _box_klasses[T_FLOAT] = WK_KLASS(float_klass);
1878 _box_klasses[T_DOUBLE] = WK_KLASS(double_klass);
1879 _box_klasses[T_BYTE] = WK_KLASS(byte_klass);
1880 _box_klasses[T_SHORT] = WK_KLASS(short_klass);
1881 _box_klasses[T_INT] = WK_KLASS(int_klass);
1882 _box_klasses[T_LONG] = WK_KLASS(long_klass);
1883 //_box_klasses[T_OBJECT] = WK_KLASS(object_klass);
1884 //_box_klasses[T_ARRAY] = WK_KLASS(object_klass);
1885
1886 #ifdef KERNEL
1887 _sun_jkernel_DownloadManager_klass = resolve_or_null(vmSymbolHandles::sun_jkernel_DownloadManager(), CHECK);
1888 if (_sun_jkernel_DownloadManager_klass == NULL) {
1889 warning("Cannot find sun/jkernel/DownloadManager");
1890 }
1891 #endif // KERNEL
1892 { // Compute whether we should use loadClass or loadClassInternal when loading classes.
1893 methodOop method = instanceKlass::cast(classloader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
1894 _has_loadClassInternal = (method != NULL);
1895 }
1896
1897 { // Compute whether we should use checkPackageAccess or NOT
1898 methodOop method = instanceKlass::cast(classloader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
1899 _has_checkPackageAccess = (method != NULL);
1900 }
1901 }
1902
1903 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
1904 // If so, returns the basic type it holds. If not, returns T_OBJECT.
1905 BasicType SystemDictionary::box_klass_type(klassOop k) {
1906 assert(k != NULL, "");
1907 for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
1908 if (_box_klasses[i] == k)
1909 return (BasicType)i;
1910 }
1911 return T_OBJECT;
1912 }
1913
1914 // Constraints on class loaders. The details of the algorithm can be
1915 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
1916 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is
1917 // that the system dictionary needs to maintain a set of contraints that
1918 // must be satisfied by all classes in the dictionary.
1919 // if defining is true, then LinkageError if already in systemDictionary
1920 // if initiating loader, then ok if instanceKlass matches existing entry
1921
1922 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
1923 instanceKlassHandle k,
1924 Handle class_loader, bool defining,
1925 TRAPS) {
1926 const char *linkage_error = NULL;
1927 {
1928 symbolHandle name (THREAD, k->name());
1929 MutexLocker mu(SystemDictionary_lock, THREAD);
1930
1931 klassOop check = find_class(d_index, d_hash, name, class_loader);
1932 if (check != (klassOop)NULL) {
1933 // if different instanceKlass - duplicate class definition,
1934 // else - ok, class loaded by a different thread in parallel,
1935 // we should only have found it if it was done loading and ok to use
1936 // system dictionary only holds instance classes, placeholders
1937 // also holds array classes
1938
1939 assert(check->klass_part()->oop_is_instance(), "noninstance in systemdictionary");
1940 if ((defining == true) || (k() != check)) {
1941 linkage_error = "loader (instance of %s): attempted duplicate class "
1942 "definition for name: \"%s\"";
1943 } else {
1944 return;
1945 }
1946 }
1947
1948 #ifdef ASSERT
1949 unsigned int p_hash = placeholders()->compute_hash(name, class_loader);
1950 int p_index = placeholders()->hash_to_index(p_hash);
1951 symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
1952 assert(ph_check == NULL || ph_check == name(), "invalid symbol");
1953 #endif
1954
1955 if (linkage_error == NULL) {
1956 if (constraints()->check_or_update(k, class_loader, name) == false) {
1957 linkage_error = "loader constraint violation: loader (instance of %s)"
1958 " previously initiated loading for a different type with name \"%s\"";
1959 }
1960 }
1961 }
1962
1963 // Throw error now if needed (cannot throw while holding
1964 // SystemDictionary_lock because of rank ordering)
1965
1966 if (linkage_error) {
1967 ResourceMark rm(THREAD);
1968 const char* class_loader_name = loader_name(class_loader());
1969 char* type_name = k->name()->as_C_string();
1970 size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
1971 strlen(type_name);
1972 char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
1973 jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
1974 THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
1975 }
1976 }
1977
1978
1979 // Update system dictionary - done after check_constraint and add_to_hierachy
1980 // have been called.
1981 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
1982 int p_index, unsigned int p_hash,
1983 instanceKlassHandle k,
1984 Handle class_loader,
1985 TRAPS) {
1986 // Compile_lock prevents systemDictionary updates during compilations
1987 assert_locked_or_safepoint(Compile_lock);
1988 symbolHandle name (THREAD, k->name());
1989
1990 {
1991 MutexLocker mu1(SystemDictionary_lock, THREAD);
1992
1993 // See whether biased locking is enabled and if so set it for this
1994 // klass.
1995 // Note that this must be done past the last potential blocking
1996 // point / safepoint. We enable biased locking lazily using a
1997 // VM_Operation to iterate the SystemDictionary and installing the
1998 // biasable mark word into each instanceKlass's prototype header.
1999 // To avoid race conditions where we accidentally miss enabling the
2000 // optimization for one class in the process of being added to the
2001 // dictionary, we must not safepoint after the test of
2002 // BiasedLocking::enabled().
2003 if (UseBiasedLocking && BiasedLocking::enabled()) {
2004 // Set biased locking bit for all loaded classes; it will be
2005 // cleared if revocation occurs too often for this type
2006 // NOTE that we must only do this when the class is initally
2007 // defined, not each time it is referenced from a new class loader
2008 if (k->class_loader() == class_loader()) {
2009 k->set_prototype_header(markOopDesc::biased_locking_prototype());
2010 }
2011 }
2012
2013 // Check for a placeholder. If there, remove it and make a
2014 // new system dictionary entry.
2015 placeholders()->find_and_remove(p_index, p_hash, name, class_loader, THREAD);
2016 klassOop sd_check = find_class(d_index, d_hash, name, class_loader);
2017 if (sd_check == NULL) {
2018 dictionary()->add_klass(name, class_loader, k);
2019 notice_modification();
2020 }
2021 #ifdef ASSERT
2022 sd_check = find_class(d_index, d_hash, name, class_loader);
2023 assert (sd_check != NULL, "should have entry in system dictionary");
2024 // Changed to allow PH to remain to complete class circularity checking
2025 // while only one thread can define a class at one time, multiple
2026 // classes can resolve the superclass for a class at one time,
2027 // and the placeholder is used to track that
2028 // symbolOop ph_check = find_placeholder(p_index, p_hash, name, class_loader);
2029 // assert (ph_check == NULL, "should not have a placeholder entry");
2030 #endif
2031 SystemDictionary_lock->notify_all();
2032 }
2033 }
2034
2035
2036 klassOop SystemDictionary::find_constrained_instance_or_array_klass(
2037 symbolHandle class_name, Handle class_loader, TRAPS) {
2038
2039 // First see if it has been loaded directly.
2040 // Force the protection domain to be null. (This removes protection checks.)
2041 Handle no_protection_domain;
2042 klassOop klass = find_instance_or_array_klass(class_name, class_loader,
2043 no_protection_domain, CHECK_NULL);
2044 if (klass != NULL)
2045 return klass;
2046
2047 // Now look to see if it has been loaded elsewhere, and is subject to
2048 // a loader constraint that would require this loader to return the
2049 // klass that is already loaded.
2050 if (FieldType::is_array(class_name())) {
2051 // Array classes are hard because their klassOops are not kept in the
2052 // constraint table. The array klass may be constrained, but the elem class
2053 // may not be.
2054 jint dimension;
2055 symbolOop object_key;
2056 BasicType t = FieldType::get_array_info(class_name(), &dimension,
2057 &object_key, CHECK_(NULL));
2058 if (t != T_OBJECT) {
2059 klass = Universe::typeArrayKlassObj(t);
2060 } else {
2061 symbolHandle elem_name(THREAD, object_key);
2062 MutexLocker mu(SystemDictionary_lock, THREAD);
2063 klass = constraints()->find_constrained_elem_klass(class_name, elem_name, class_loader, THREAD);
2064 }
2065 if (klass != NULL) {
2066 klass = Klass::cast(klass)->array_klass_or_null(dimension);
2067 }
2068 } else {
2069 MutexLocker mu(SystemDictionary_lock, THREAD);
2070 // Non-array classes are easy: simply check the constraint table.
2071 klass = constraints()->find_constrained_klass(class_name, class_loader);
2072 }
2073
2074 return klass;
2075 }
2076
2077
2078 bool SystemDictionary::add_loader_constraint(symbolHandle class_name,
2079 Handle class_loader1,
2080 Handle class_loader2,
2081 Thread* THREAD) {
2082 unsigned int d_hash1 = dictionary()->compute_hash(class_name, class_loader1);
2083 int d_index1 = dictionary()->hash_to_index(d_hash1);
2084
2085 unsigned int d_hash2 = dictionary()->compute_hash(class_name, class_loader2);
2086 int d_index2 = dictionary()->hash_to_index(d_hash2);
2087
2088 {
2089 MutexLocker mu_s(SystemDictionary_lock, THREAD);
2090
2091 // Better never do a GC while we're holding these oops
2092 No_Safepoint_Verifier nosafepoint;
2093
2094 klassOop klass1 = find_class(d_index1, d_hash1, class_name, class_loader1);
2095 klassOop klass2 = find_class(d_index2, d_hash2, class_name, class_loader2);
2096 return constraints()->add_entry(class_name, klass1, class_loader1,
2097 klass2, class_loader2);
2098 }
2099 }
2100
2101 // Add entry to resolution error table to record the error when the first
2102 // attempt to resolve a reference to a class has failed.
2103 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, symbolHandle error) {
2104 unsigned int hash = resolution_errors()->compute_hash(pool, which);
2105 int index = resolution_errors()->hash_to_index(hash);
2106 {
2107 MutexLocker ml(SystemDictionary_lock, Thread::current());
2108 resolution_errors()->add_entry(index, hash, pool, which, error);
2109 }
2110 }
2111
2112 // Lookup resolution error table. Returns error if found, otherwise NULL.
2113 symbolOop SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
2114 unsigned int hash = resolution_errors()->compute_hash(pool, which);
2115 int index = resolution_errors()->hash_to_index(hash);
2116 {
2117 MutexLocker ml(SystemDictionary_lock, Thread::current());
2118 ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2119 return (entry != NULL) ? entry->error() : (symbolOop)NULL;
2120 }
2121 }
2122
2123
2124 // Make sure all class components (including arrays) in the given
2125 // signature will be resolved to the same class in both loaders.
2126 // Returns the name of the type that failed a loader constraint check, or
2127 // NULL if no constraint failed. The returned C string needs cleaning up
2128 // with a ResourceMark in the caller
2129 char* SystemDictionary::check_signature_loaders(symbolHandle signature,
2130 Handle loader1, Handle loader2,
2131 bool is_method, TRAPS) {
2132 // Nothing to do if loaders are the same.
2133 if (loader1() == loader2()) {
2134 return NULL;
2135 }
2136
2137 SignatureStream sig_strm(signature, is_method);
2138 while (!sig_strm.is_done()) {
2139 if (sig_strm.is_object()) {
2140 symbolOop s = sig_strm.as_symbol(CHECK_NULL);
2141 symbolHandle sig (THREAD, s);
2142 if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2143 return sig()->as_C_string();
2144 }
2145 }
2146 sig_strm.next();
2147 }
2148 return NULL;
2149 }
2150
2151
2152 // Since the identity hash code for symbols changes when the symbols are
2153 // moved from the regular perm gen (hash in the mark word) to the shared
2154 // spaces (hash is the address), the classes loaded into the dictionary
2155 // may be in the wrong buckets.
2156
2157 void SystemDictionary::reorder_dictionary() {
2158 dictionary()->reorder_dictionary();
2159 }
2160
2161
2162 void SystemDictionary::copy_buckets(char** top, char* end) {
2163 dictionary()->copy_buckets(top, end);
2164 }
2165
2166
2167 void SystemDictionary::copy_table(char** top, char* end) {
2168 dictionary()->copy_table(top, end);
2169 }
2170
2171
2172 void SystemDictionary::reverse() {
2173 dictionary()->reverse();
2174 }
2175
2176 int SystemDictionary::number_of_classes() {
2177 return dictionary()->number_of_entries();
2178 }
2179
2180
2181 // ----------------------------------------------------------------------------
2182 #ifndef PRODUCT
2183
2184 void SystemDictionary::print() {
2185 dictionary()->print();
2186
2187 // Placeholders
2188 GCMutexLocker mu(SystemDictionary_lock);
2189 placeholders()->print();
2190
2191 // loader constraints - print under SD_lock
2192 constraints()->print();
2193 }
2194
2195 #endif
2196
2197 void SystemDictionary::verify() {
2198 guarantee(dictionary() != NULL, "Verify of system dictionary failed");
2199 guarantee(constraints() != NULL,
2200 "Verify of loader constraints failed");
2201 guarantee(dictionary()->number_of_entries() >= 0 &&
2202 placeholders()->number_of_entries() >= 0,
2203 "Verify of system dictionary failed");
2204
2205 // Verify dictionary
2206 dictionary()->verify();
2207
2208 GCMutexLocker mu(SystemDictionary_lock);
2209 placeholders()->verify();
2210
2211 // Verify constraint table
2212 guarantee(constraints() != NULL, "Verify of loader constraints failed");
2213 constraints()->verify(dictionary());
2214 }
2215
2216
2217 void SystemDictionary::verify_obj_klass_present(Handle obj,
2218 symbolHandle class_name,
2219 Handle class_loader) {
2220 GCMutexLocker mu(SystemDictionary_lock);
2221 oop probe = find_class_or_placeholder(class_name, class_loader);
2222 if (probe == NULL) {
2223 probe = SystemDictionary::find_shared_class(class_name);
2224 }
2225 guarantee(probe != NULL &&
2226 (!probe->is_klass() || probe == obj()),
2227 "Loaded klasses should be in SystemDictionary");
2228 }
2229
2230 #ifndef PRODUCT
2231
2232 // statistics code
2233 class ClassStatistics: AllStatic {
2234 private:
2235 static int nclasses; // number of classes
2236 static int nmethods; // number of methods
2237 static int nmethoddata; // number of methodData
2238 static int class_size; // size of class objects in words
2239 static int method_size; // size of method objects in words
2240 static int debug_size; // size of debug info in methods
2241 static int methoddata_size; // size of methodData objects in words
2242
2243 static void do_class(klassOop k) {
2244 nclasses++;
2245 class_size += k->size();
2246 if (k->klass_part()->oop_is_instance()) {
2247 instanceKlass* ik = (instanceKlass*)k->klass_part();
2248 class_size += ik->methods()->size();
2249 class_size += ik->constants()->size();
2250 class_size += ik->local_interfaces()->size();
2251 class_size += ik->transitive_interfaces()->size();
2252 // We do not have to count implementors, since we only store one!
2253 class_size += ik->fields()->size();
2254 }
2255 }
2256
2257 static void do_method(methodOop m) {
2258 nmethods++;
2259 method_size += m->size();
2260 // class loader uses same objArray for empty vectors, so don't count these
2261 if (m->exception_table()->length() != 0) method_size += m->exception_table()->size();
2262 if (m->has_stackmap_table()) {
2263 method_size += m->stackmap_data()->size();
2264 }
2265
2266 methodDataOop mdo = m->method_data();
2267 if (mdo != NULL) {
2268 nmethoddata++;
2269 methoddata_size += mdo->size();
2270 }
2271 }
2272
2273 public:
2274 static void print() {
2275 SystemDictionary::classes_do(do_class);
2276 SystemDictionary::methods_do(do_method);
2277 tty->print_cr("Class statistics:");
2278 tty->print_cr("%d classes (%d bytes)", nclasses, class_size * oopSize);
2279 tty->print_cr("%d methods (%d bytes = %d base + %d debug info)", nmethods,
2280 (method_size + debug_size) * oopSize, method_size * oopSize, debug_size * oopSize);
2281 tty->print_cr("%d methoddata (%d bytes)", nmethoddata, methoddata_size * oopSize);
2282 }
2283 };
2284
2285
2286 int ClassStatistics::nclasses = 0;
2287 int ClassStatistics::nmethods = 0;
2288 int ClassStatistics::nmethoddata = 0;
2289 int ClassStatistics::class_size = 0;
2290 int ClassStatistics::method_size = 0;
2291 int ClassStatistics::debug_size = 0;
2292 int ClassStatistics::methoddata_size = 0;
2293
2294 void SystemDictionary::print_class_statistics() {
2295 ResourceMark rm;
2296 ClassStatistics::print();
2297 }
2298
2299
2300 class MethodStatistics: AllStatic {
2301 public:
2302 enum {
2303 max_parameter_size = 10
2304 };
2305 private:
2306
2307 static int _number_of_methods;
2308 static int _number_of_final_methods;
2309 static int _number_of_static_methods;
2310 static int _number_of_native_methods;
2311 static int _number_of_synchronized_methods;
2312 static int _number_of_profiled_methods;
2313 static int _number_of_bytecodes;
2314 static int _parameter_size_profile[max_parameter_size];
2315 static int _bytecodes_profile[Bytecodes::number_of_java_codes];
2316
2317 static void initialize() {
2318 _number_of_methods = 0;
2319 _number_of_final_methods = 0;
2320 _number_of_static_methods = 0;
2321 _number_of_native_methods = 0;
2322 _number_of_synchronized_methods = 0;
2323 _number_of_profiled_methods = 0;
2324 _number_of_bytecodes = 0;
2325 for (int i = 0; i < max_parameter_size ; i++) _parameter_size_profile[i] = 0;
2326 for (int j = 0; j < Bytecodes::number_of_java_codes; j++) _bytecodes_profile [j] = 0;
2327 };
2328
2329 static void do_method(methodOop m) {
2330 _number_of_methods++;
2331 // collect flag info
2332 if (m->is_final() ) _number_of_final_methods++;
2333 if (m->is_static() ) _number_of_static_methods++;
2334 if (m->is_native() ) _number_of_native_methods++;
2335 if (m->is_synchronized()) _number_of_synchronized_methods++;
2336 if (m->method_data() != NULL) _number_of_profiled_methods++;
2337 // collect parameter size info (add one for receiver, if any)
2338 _parameter_size_profile[MIN2(m->size_of_parameters() + (m->is_static() ? 0 : 1), max_parameter_size - 1)]++;
2339 // collect bytecodes info
2340 {
2341 Thread *thread = Thread::current();
2342 HandleMark hm(thread);
2343 BytecodeStream s(methodHandle(thread, m));
2344 Bytecodes::Code c;
2345 while ((c = s.next()) >= 0) {
2346 _number_of_bytecodes++;
2347 _bytecodes_profile[c]++;
2348 }
2349 }
2350 }
2351
2352 public:
2353 static void print() {
2354 initialize();
2355 SystemDictionary::methods_do(do_method);
2356 // generate output
2357 tty->cr();
2358 tty->print_cr("Method statistics (static):");
2359 // flag distribution
2360 tty->cr();
2361 tty->print_cr("%6d final methods %6.1f%%", _number_of_final_methods , _number_of_final_methods * 100.0F / _number_of_methods);
2362 tty->print_cr("%6d static methods %6.1f%%", _number_of_static_methods , _number_of_static_methods * 100.0F / _number_of_methods);
2363 tty->print_cr("%6d native methods %6.1f%%", _number_of_native_methods , _number_of_native_methods * 100.0F / _number_of_methods);
2364 tty->print_cr("%6d synchronized methods %6.1f%%", _number_of_synchronized_methods, _number_of_synchronized_methods * 100.0F / _number_of_methods);
2365 tty->print_cr("%6d profiled methods %6.1f%%", _number_of_profiled_methods, _number_of_profiled_methods * 100.0F / _number_of_methods);
2366 // parameter size profile
2367 tty->cr();
2368 { int tot = 0;
2369 int avg = 0;
2370 for (int i = 0; i < max_parameter_size; i++) {
2371 int n = _parameter_size_profile[i];
2372 tot += n;
2373 avg += n*i;
2374 tty->print_cr("parameter size = %1d: %6d methods %5.1f%%", i, n, n * 100.0F / _number_of_methods);
2375 }
2376 assert(tot == _number_of_methods, "should be the same");
2377 tty->print_cr(" %6d methods 100.0%%", _number_of_methods);
2378 tty->print_cr("(average parameter size = %3.1f including receiver, if any)", (float)avg / _number_of_methods);
2379 }
2380 // bytecodes profile
2381 tty->cr();
2382 { int tot = 0;
2383 for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
2384 if (Bytecodes::is_defined(i)) {
2385 Bytecodes::Code c = Bytecodes::cast(i);
2386 int n = _bytecodes_profile[c];
2387 tot += n;
2388 tty->print_cr("%9d %7.3f%% %s", n, n * 100.0F / _number_of_bytecodes, Bytecodes::name(c));
2389 }
2390 }
2391 assert(tot == _number_of_bytecodes, "should be the same");
2392 tty->print_cr("%9d 100.000%%", _number_of_bytecodes);
2393 }
2394 tty->cr();
2395 }
2396 };
2397
2398 int MethodStatistics::_number_of_methods;
2399 int MethodStatistics::_number_of_final_methods;
2400 int MethodStatistics::_number_of_static_methods;
2401 int MethodStatistics::_number_of_native_methods;
2402 int MethodStatistics::_number_of_synchronized_methods;
2403 int MethodStatistics::_number_of_profiled_methods;
2404 int MethodStatistics::_number_of_bytecodes;
2405 int MethodStatistics::_parameter_size_profile[MethodStatistics::max_parameter_size];
2406 int MethodStatistics::_bytecodes_profile[Bytecodes::number_of_java_codes];
2407
2408
2409 void SystemDictionary::print_method_statistics() {
2410 MethodStatistics::print();
2411 }
2412
2413 #endif // PRODUCT