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