src/share/vm/classfile/systemDictionary.cpp
Index Unified diffs Context diffs Sdiffs Wdiffs Patch New Old Previous File Next File

## src/share/vm/classfile/systemDictionary.cpp

Print this page

      61 #include "runtime/orderAccess.inline.hpp"
      62 #include "runtime/signature.hpp"
      63 #include "services/classLoadingService.hpp"
      64 #include "services/threadService.hpp"
      65 #include "utilities/macros.hpp"
      66 #include "utilities/ticks.hpp"
      67 #if INCLUDE_TRACE
      68 #include "trace/tracing.hpp"
      69 #endif
      70
      71 Dictionary*            SystemDictionary::_dictionary          = NULL;
      72 PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
      73 Dictionary*            SystemDictionary::_shared_dictionary   = NULL;
      74 LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
      75 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
      76 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
      77
      78
      79 int         SystemDictionary::_number_of_modifications = 0;
      80 int         SystemDictionary::_sdgeneration               = 0;
      81 const int   SystemDictionary::_primelist[_prime_array_size] = {1009,2017,4049,5051,10103,
      82               20201,40423,99991};
      83
      84 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
      85
      86 Klass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
      87                                                           =  { NULL /*, NULL...*/ };
      88
      89 Klass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
      90
      91 oop         SystemDictionary::_java_system_loader         =  NULL;
      92
      93 bool        SystemDictionary::_has_loadClassInternal      =  false;
      94 bool        SystemDictionary::_has_checkPackageAccess     =  false;
      95
      96 // lazily initialized klass variables
      97 Klass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
      98
      99
     100 // ----------------------------------------------------------------------------
     101 // Java-level SystemLoader
     316                                                  bool is_superclass,
     317                                                  TRAPS) {
     318   // Double-check, if child class is already loaded, just return super-class,interface
     319   // Don't add a placedholder if already loaded, i.e. already in system dictionary
     320   // Make sure there's a placeholder for the *child* before resolving.
     321   // Used as a claim that this thread is currently loading superclass/classloader
     322   // Used here for ClassCircularity checks and also for heap verification
     323   // (every InstanceKlass in the heap needs to be in the system dictionary
     324   // or have a placeholder).
     325   // Must check ClassCircularity before checking if super class is already loaded
     326   //
     327   // We might not already have a placeholder if this child_name was
     328   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
     329   // the name of the class might not be known until the stream is actually
     330   // parsed.
     331   // Bugs 4643874, 4715493
     332   // compute_hash can have a safepoint
     333
     334   ClassLoaderData* loader_data = class_loader_data(class_loader);
     335   unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);
     336   int d_index = dictionary()->hash_to_index(d_hash);
     337   unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);
     338   int p_index = placeholders()->hash_to_index(p_hash);
     339   // can't throw error holding a lock
     340   bool child_already_loaded = false;
     341   bool throw_circularity_error = false;
     342   {
     343     MutexLocker mu(SystemDictionary_lock, THREAD);
     344     Klass* childk = find_class(d_index, d_hash, child_name, loader_data);

     345     Klass* quicksuperk;
     346     // to support // loading: if child done loading, just return superclass
     347     // if class_name, & class_loader don't match:
     348     // if initial define, SD update will give LinkageError
     349     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
     350     // so we don't throw an exception here.
     351     // see: nsk redefclass014 & java.lang.instrument Instrument032
     352     if ((childk != NULL ) && (is_superclass) &&
     353        ((quicksuperk = InstanceKlass::cast(childk)->super()) != NULL) &&
     354
     355          ((quicksuperk->name() == class_name) &&
     356             (quicksuperk->class_loader()  == class_loader()))) {
     357            return quicksuperk;
     358     } else {
     359       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
     360       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
     361           throw_circularity_error = true;
     362       }
     363     }
     364     if (!throw_circularity_error) {
     371   }
     372
     373 // java.lang.Object should have been found above
     374   assert(class_name != NULL, "null super class for resolving");
     375   // Resolve the super class or interface, check results on return
     376   Klass* superk = SystemDictionary::resolve_or_null(class_name,
     377                                                  class_loader,
     378                                                  protection_domain,
     379                                                  THREAD);
     380
     381   KlassHandle superk_h(THREAD, superk);
     382
     383   // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
     384   // It is no longer necessary to keep the placeholder table alive until update_dictionary
     385   // or error. GC used to walk the placeholder table as strong roots.
     386   // The instanceKlass is kept alive because the class loader is on the stack,
     387   // which keeps the loader_data alive, as well as all instanceKlasses in
     388   // the loader_data. parseClassFile adds the instanceKlass to loader_data.
     389   {
     390     MutexLocker mu(SystemDictionary_lock, THREAD);

     391     placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
     392     SystemDictionary_lock->notify_all();
     393   }
     394   if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
     395     // can null superk
     396     superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
     397   }
     398
     399   return superk_h();
     400 }
     401
     402 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
     403                                                   Handle class_loader,
     404                                                   Handle protection_domain,
     405                                                   TRAPS) {
     406   if(!has_checkPackageAccess()) return;
     407
     408   // Now we have to call back to java to check if the initating class has access
     409   JavaValue result(T_VOID);
     410   if (TraceProtectionDomainVerification) {
     428   if (TraceProtectionDomainVerification) {
     429     if (HAS_PENDING_EXCEPTION) {
     430       tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
     431     } else {
     432      tty->print_cr(" -> granted");
     433     }
     434     tty->cr();
     435   }
     436
     437   if (HAS_PENDING_EXCEPTION) return;
     438
     439   // If no exception has been thrown, we have validated the protection domain
     440   // Insert the protection domain of the initiating class into the set.
     441   {
     442     // We recalculate the entry here -- we've called out to java since
     443     // the last time it was calculated.
     444     ClassLoaderData* loader_data = class_loader_data(class_loader);
     445
     446     Symbol*  kn = klass->name();
     447     unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);
     448     int d_index = dictionary()->hash_to_index(d_hash);
     449
     450     MutexLocker mu(SystemDictionary_lock, THREAD);
     451     {
     452       // Note that we have an entry, and entries can be deleted only during GC,
     453       // so we cannot allow GC to occur while we're holding this entry.
     454
     455       // We're using a No_Safepoint_Verifier to catch any place where we
     456       // might potentially do a GC at all.
     457       // Dictionary::do_unloading() asserts that classes in SD are only
     458       // unloaded at a safepoint. Anonymous classes are not in SD.
     459       No_Safepoint_Verifier nosafepoint;
     460       dictionary()->add_protection_domain(d_index, d_hash, klass, loader_data,
     461                                           protection_domain, THREAD);
     462     }
     463   }
     464 }
     465
     466 // We only get here if this thread finds that another thread
     467 // has already claimed the placeholder token for the current operation,
     468 // but that other thread either never owned or gave up the
     469 // object lock
     470 // Waits on SystemDictionary_lock to indicate placeholder table updated
     471 // On return, caller must recheck placeholder table state
     472 //
     473 // We only get here if
     474 //  1) custom classLoader, i.e. not bootstrap classloader
     475 //  2) UnsyncloadClass not set
     476 //  3) custom classLoader has broken the class loader objectLock
     477 //     so another thread got here in parallel
     478 //
     479 // lockObject must be held.
     480 // Complicated dance due to lock ordering:
     506 // If the class in is in the placeholder table, class loading is in progress
     507 // For cases where the application changes threads to load classes, it
     508 // is critical to ClassCircularity detection that we try loading
     509 // the superclass on the same thread internally, so we do parallel
     510 // super class loading here.
     511 // This also is critical in cases where the original thread gets stalled
     512 // even in non-circularity situations.
     513 // Note: must call resolve_super_or_fail even if null super -
     514 // to force placeholder entry creation for this class for circularity detection
     515 // Caller must check for pending exception
     516 // Returns non-null Klass* if other thread has completed load
     517 // and we are done,
     518 // If return null Klass* and no pending exception, the caller must load the class
     519 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
     520     Symbol* name, Symbol* superclassname, Handle class_loader,
     521     Handle protection_domain, Handle lockObject, TRAPS) {
     522
     523   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
     524   ClassLoaderData* loader_data = class_loader_data(class_loader);
     525   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
     526   int d_index = dictionary()->hash_to_index(d_hash);
     527   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
     528   int p_index = placeholders()->hash_to_index(p_hash);
     529
     530   // superk is not used, resolve_super called for circularity check only
     531   // This code is reached in two situations. One if this thread
     532   // is loading the same class twice (e.g. ClassCircularity, or
     533   // java.lang.instrument).
     534   // The second is if another thread started the resolve_super first
     535   // and has not yet finished.
     536   // In both cases the original caller will clean up the placeholder
     537   // entry on error.
     538   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
     539                                                           superclassname,
     540                                                           class_loader,
     541                                                           protection_domain,
     542                                                           true,
     543                                                           CHECK_(nh));
     544
     545   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
     546   // Serial class loaders and bootstrap classloader do wait for superclass loads
     547  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
     548     MutexLocker mu(SystemDictionary_lock, THREAD);
     549     // Check if classloading completed while we were loading superclass or waiting
     550     Klass* check = find_class(d_index, d_hash, name, loader_data);
     551     if (check != NULL) {
     552       // Klass is already loaded, so just return it
     553       return(instanceKlassHandle(THREAD, check));
     554     } else {
     555       return nh;
     556     }
     557   }
     558
     559   // must loop to both handle other placeholder updates
     560   // and spurious notifications
     561   bool super_load_in_progress = true;
     562   PlaceholderEntry* placeholder;
     563   while (super_load_in_progress) {
     564     MutexLocker mu(SystemDictionary_lock, THREAD);

     565     // Check if classloading completed while we were loading superclass or waiting
     566     Klass* check = find_class(d_index, d_hash, name, loader_data);
     567     if (check != NULL) {
     568       // Klass is already loaded, so just return it
     569       return(instanceKlassHandle(THREAD, check));
     570     } else {
     571       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
     572       if (placeholder && placeholder->super_load_in_progress() ){
     573         // Before UnsyncloadClass:
     574         // We only get here if the application has released the
     575         // classloader lock when another thread was in the middle of loading a
     576         // superclass/superinterface for this class, and now
     577         // this thread is also trying to load this class.
     578         // To minimize surprises, the first thread that started to
     579         // load a class should be the one to complete the loading
     580         // with the classfile it initially expected.
     581         // This logic has the current thread wait once it has done
     582         // all the superclass/superinterface loading it can, until
     583         // the original thread completes the class loading or fails
     584         // If it completes we will use the resulting InstanceKlass
     585         // which we will find below in the systemDictionary.
     586         // We also get here for parallel bootstrap classloader
     603                                                         Handle class_loader,
     604                                                         Handle protection_domain,
     605                                                         TRAPS) {
     606   assert(name != NULL && !FieldType::is_array(name) &&
     607          !FieldType::is_obj(name), "invalid class name");
     608
     609   Ticks class_load_start_time = Ticks::now();
     610
     611   // UseNewReflection
     612   // Fix for 4474172; see evaluation for more details
     613   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
     614   ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);
     615
     616   // Do lookup to see if class already exist and the protection domain
     617   // has the right access
     618   // This call uses find which checks protection domain already matches
     619   // All subsequent calls use find_class, and set has_loaded_class so that
     620   // before we return a result we call out to java to check for valid protection domain
     621   // to allow returning the Klass* and add it to the pd_set if it is valid
     622   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
     623   int d_index = dictionary()->hash_to_index(d_hash);
     624   Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data,
     625                                       protection_domain, THREAD);
     626   if (probe != NULL) return probe;
     627
     628
     629   // Non-bootstrap class loaders will call out to class loader and
     630   // define via jvm/jni_DefineClass which will acquire the
     631   // class loader object lock to protect against multiple threads
     632   // defining the class in parallel by accident.
     633   // This lock must be acquired here so the waiter will find
     634   // any successful result in the SystemDictionary and not attempt
     635   // the define
     636   // ParallelCapable Classloaders and the bootstrap classloader,
     637   // or all classloaders with UnsyncloadClass do not acquire lock here
     638   bool DoObjectLock = true;
     639   if (is_parallelCapable(class_loader)) {
     640     DoObjectLock = false;
     641   }
     642
     643   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
     644   int p_index = placeholders()->hash_to_index(p_hash);
     645
     646   // Class is not in SystemDictionary so we have to do loading.
     647   // Make sure we are synchronized on the class loader before we proceed
     648   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
     649   check_loader_lock_contention(lockObject, THREAD);
     650   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
     651
     652   // Check again (after locking) if class already exist in SystemDictionary
     653   bool class_has_been_loaded   = false;
     654   bool super_load_in_progress  = false;
     655   bool havesupername = false;
     656   instanceKlassHandle k;
     657   PlaceholderEntry* placeholder;
     658   Symbol* superclassname = NULL;
     659
     660   {
     661     MutexLocker mu(SystemDictionary_lock, THREAD);
     662     Klass* check = find_class(d_index, d_hash, name, loader_data);

     663     if (check != NULL) {
     664       // Klass is already loaded, so just return it
     665       class_has_been_loaded = true;
     666       k = instanceKlassHandle(THREAD, check);
     667     } else {
     668       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
     669       if (placeholder && placeholder->super_load_in_progress()) {
     670          super_load_in_progress = true;
     671          if (placeholder->havesupername() == true) {
     672            superclassname = placeholder->supername();
     673            havesupername = true;
     674          }
     675       }
     676     }
     677   }
     678
     679   // If the class is in the placeholder table, class loading is in progress
     680   if (super_load_in_progress && havesupername==true) {
     681     k = SystemDictionary::handle_parallel_super_load(name, superclassname,
     682         class_loader, protection_domain, lockObject, THREAD);
     702     // case 1. traditional classloaders that rely on the classloader object lock
     703     //   - no other need for LOAD_INSTANCE
     704     // case 2. traditional classloaders that break the classloader object lock
     705     //    as a deadlock workaround. Detection of this case requires that
     706     //    this check is done while holding the classloader object lock,
     707     //    and that lock is still held when calling classloader's loadClass.
     708     //    For these classloaders, we ensure that the first requestor
     709     //    completes the load and other requestors wait for completion.
     710     // case 3. UnsyncloadClass - don't use objectLocker
     711     //    With this flag, we allow parallel classloading of a
     712     //    class/classloader pair
     713     // case4. Bootstrap classloader - don't own objectLocker
     714     //    This classloader supports parallelism at the classloader level,
     715     //    but only allows a single load of a class/classloader pair.
     716     //    No performance benefit and no deadlock issues.
     717     // case 5. parallelCapable user level classloaders - without objectLocker
     718     //    Allow parallel classloading of a class/classloader pair
     719
     720     {
     721       MutexLocker mu(SystemDictionary_lock, THREAD);

     722       if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
     723         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
     724         if (oldprobe) {
     725           // only need check_seen_thread once, not on each loop
     726           // 6341374 java/lang/Instrument with -Xcomp
     727           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
     728             throw_circularity_error = true;
     729           } else {
     730             // case 1: traditional: should never see load_in_progress.
     731             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
     732
     733               // case 4: bootstrap classloader: prevent futile classloading,
     734               // wait on first requestor
     735               if (class_loader.is_null()) {
     736                 SystemDictionary_lock->wait();
     737               } else {
     738               // case 2: traditional with broken classloader lock. wait on first
     739               // requestor.
     740                 double_lock_wait(lockObject, THREAD);
     741               }
     742               // Check if classloading completed while we were waiting
     743               Klass* check = find_class(d_index, d_hash, name, loader_data);
     744               if (check != NULL) {
     745                 // Klass is already loaded, so just return it
     746                 k = instanceKlassHandle(THREAD, check);
     747                 class_has_been_loaded = true;
     748               }
     749               // check if other thread failed to load and cleaned up
     750               oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
     751             }
     752           }
     753         }
     754       }
     755       // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
     756       // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
     757       // LOAD_INSTANCE in parallel
     758
     759       if (!throw_circularity_error && !class_has_been_loaded) {
     760         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
     761         load_instance_added = true;
     762         // For class loaders that do not acquire the classloader object lock,
     763         // if they did not catch another thread holding LOAD_INSTANCE,
     764         // need a check analogous to the acquire ObjectLocker/find_class
     765         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
     766         // one final check if the load has already completed
     767         // class loaders holding the ObjectLock shouldn't find the class here
     768         Klass* check = find_class(d_index, d_hash, name, loader_data);
     769         if (check != NULL) {
     770         // Klass is already loaded, so return it after checking/adding protection domain
     771           k = instanceKlassHandle(THREAD, check);
     772           class_has_been_loaded = true;
     773         }
     774       }
     775     }
     776
     777     // must throw error outside of owning lock
     778     if (throw_circularity_error) {
     779       assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
     780       ResourceMark rm(THREAD);
     781       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
     782     }
     783
     784     if (!class_has_been_loaded) {
     785
     786       // Do actual loading
     787       k = load_instance_class(name, class_loader, THREAD);
     788
     789       // For UnsyncloadClass only
     790       // If they got a linkageError, check if a parallel class load succeeded.
     791       // If it did, then for bytecode resolution the specification requires
     792       // that we return the same result we did for the other thread, i.e. the
     793       // successfully loaded InstanceKlass
     794       // Should not get here for classloaders that support parallelism
     795       // with the new cleaner mechanism, even with AllowParallelDefineClass
     796       // Bootstrap goes through here to allow for an extra guarantee check
     797       if (UnsyncloadClass || (class_loader.is_null())) {
     798         if (k.is_null() && HAS_PENDING_EXCEPTION
     799           && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
     800           MutexLocker mu(SystemDictionary_lock, THREAD);
     801           Klass* check = find_class(d_index, d_hash, name, loader_data);
     802           if (check != NULL) {
     803             // Klass is already loaded, so just use it
     804             k = instanceKlassHandle(THREAD, check);
     805             CLEAR_PENDING_EXCEPTION;
     806             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
     807           }
     808         }
     809       }
     810
     811       // If everything was OK (no exceptions, no null return value), and
     812       // class_loader is NOT the defining loader, do a little more bookkeeping.
     813       if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
     814         k->class_loader() != class_loader()) {
     815
     816         check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
     817
     818         // Need to check for a PENDING_EXCEPTION again; check_constraints
     819         // can throw and doesn't use the CHECK macro.
     820         if (!HAS_PENDING_EXCEPTION) {
     821           { // Grabbing the Compile_lock prevents systemDictionary updates
     822             // during compilations.
     823             MutexLocker mu(Compile_lock, THREAD);
     824             update_dictionary(d_index, d_hash, p_index, p_hash,
     825                               k, class_loader, THREAD);
     826           }
     827
     828           if (JvmtiExport::should_post_class_load()) {
     829             Thread *thread = THREAD;
     830             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
     831             JvmtiExport::post_class_load((JavaThread *) thread, k());
     832           }
     833         }
     834       }
     835     } // load_instance_class loop
     836
     837     if (load_instance_added == true) {
     838       // clean up placeholder entries for LOAD_INSTANCE success or error
     839       // This brackets the SystemDictionary updates for both defining
     840       // and initiating loaders
     841       MutexLocker mu(SystemDictionary_lock, THREAD);

     842       placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
     843       SystemDictionary_lock->notify_all();
     844     }
     845   }
     846
     847   if (HAS_PENDING_EXCEPTION || k.is_null()) {
     848     return NULL;
     849   }
     850
     851   post_class_load_event(class_load_start_time, k, class_loader);
     852
     853 #ifdef ASSERT
     854   {
     855     ClassLoaderData* loader_data = k->class_loader_data();
     856     MutexLocker mu(SystemDictionary_lock, THREAD);
     857     Klass* kk = find_class(name, loader_data);
     858     assert(kk == k(), "should be present in dictionary");
     859   }
     860 #endif
     861
     862   // return if the protection domain in NULL
     863   if (protection_domain() == NULL) return k();
     864
     865   // Check the protection domain has the right access
     866   {
     867     MutexLocker mu(SystemDictionary_lock, THREAD);
     868     // Note that we have an entry, and entries can be deleted only during GC,
     869     // so we cannot allow GC to occur while we're holding this entry.
     870     // We're using a No_Safepoint_Verifier to catch any place where we
     871     // might potentially do a GC at all.
     872     // Dictionary::do_unloading() asserts that classes in SD are only
     873     // unloaded at a safepoint. Anonymous classes are not in SD.
     874     No_Safepoint_Verifier nosafepoint;
     875     if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
     876                                                  loader_data,
     877                                                  protection_domain)) {
     878       return k();
     879     }
     880   }
     881
     882   // Verify protection domain. If it fails an exception is thrown
     883   validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
     884
     885   return k();
     886 }
     887
     888
     889 // This routine does not lock the system dictionary.
     890 //
     891 // Since readers don't hold a lock, we must make sure that system
     892 // dictionary entries are only removed at a safepoint (when only one
     893 // thread is running), and are added to in a safe way (all links must
     894 // be updated in an MT-safe manner).
     895 //
     899
     900 Klass* SystemDictionary::find(Symbol* class_name,
     901                               Handle class_loader,
     902                               Handle protection_domain,
     903                               TRAPS) {
     904
     905   // UseNewReflection
     906   // The result of this call should be consistent with the result
     907   // of the call to resolve_instance_class_or_null().
     908   // See evaluation 6790209 and 4474172 for more details.
     909   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
     910   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
     911
     912   if (loader_data == NULL) {
     913     // If the ClassLoaderData has not been setup,
     914     // then the class loader has no entries in the dictionary.
     915     return NULL;
     916   }
     917
     918   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
     919   int d_index = dictionary()->hash_to_index(d_hash);
     920
     921   {
     922     // Note that we have an entry, and entries can be deleted only during GC,
     923     // so we cannot allow GC to occur while we're holding this entry.
     924     // We're using a No_Safepoint_Verifier to catch any place where we
     925     // might potentially do a GC at all.
     926     // Dictionary::do_unloading() asserts that classes in SD are only
     927     // unloaded at a safepoint. Anonymous classes are not in SD.
     928     No_Safepoint_Verifier nosafepoint;
     929     return dictionary()->find(d_index, d_hash, class_name, loader_data,
     930                               protection_domain, THREAD);
     931   }
     932 }
     933
     934
     935 // Look for a loaded instance or array klass by name.  Do not do any loading.
     936 // return NULL in case of error.
     937 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
     938                                                       Handle class_loader,
     939                                                       Handle protection_domain,
     940                                                       TRAPS) {
     941   Klass* k = NULL;
     942   assert(class_name != NULL, "class name must be non NULL");
     943
     944   if (FieldType::is_array(class_name)) {
     945     // The name refers to an array.  Parse the name.
     946     // dimension and object_key in FieldArrayInfo are assigned as a
     947     // side-effect of this call
     948     FieldArrayInfo fd;
     949     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
    1141   } );
    1142
    1143   return k();
    1144 }
    1145
    1146 #if INCLUDE_CDS
    1147 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
    1148                                              int number_of_entries) {
    1149   assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
    1150          "bad shared dictionary size.");
    1151   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
    1152 }
    1153
    1154
    1155 // If there is a shared dictionary, then find the entry for the
    1156 // given shared system class, if any.
    1157
    1158 Klass* SystemDictionary::find_shared_class(Symbol* class_name) {
    1159   if (shared_dictionary() != NULL) {
    1160     unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);
    1161     int d_index = shared_dictionary()->hash_to_index(d_hash);
    1162
    1163     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
    1164   } else {
    1165     return NULL;
    1166   }
    1167 }
    1168
    1169
    1170 // Load a class from the shared spaces (found through the shared system
    1171 // dictionary).  Force the superclass and all interfaces to be loaded.
    1172 // Update the class definition to include sibling classes and no
    1173 // subclasses (yet).  [Classes in the shared space are not part of the
    1174 // object hierarchy until loaded.]
    1175
    1176 instanceKlassHandle SystemDictionary::load_shared_class(
    1177                  Symbol* class_name, Handle class_loader, TRAPS) {
    1178   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
    1179   // Make sure we only return the boot class for the NULL classloader.
    1180   if (ik.not_null() &&
    1181       SharedClassUtil::is_shared_boot_class(ik()) && class_loader.is_null()) {
    1182     Handle protection_domain;
    1183     return load_shared_class(ik, class_loader, protection_domain, THREAD);
    1375  // If a parallelCapable class loader calls define_instance_class instead of
    1376  // find_or_define_instance_class to get here, we have a timing
    1377  // hole with systemDictionary updates and check_constraints
    1378  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
    1379     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
    1380          compute_loader_lock_object(class_loader_h, THREAD)),
    1381          "define called without lock");
    1382   }
    1383
    1384   // Check class-loading constraints. Throw exception if violation is detected.
    1385   // Grabs and releases SystemDictionary_lock
    1386   // The check_constraints/find_class call and update_dictionary sequence
    1387   // must be "atomic" for a specific class/classloader pair so we never
    1388   // define two different instanceKlasses for that class/classloader pair.
    1389   // Existing classloaders will call define_instance_class with the
    1390   // classloader lock held
    1391   // Parallel classloaders will call find_or_define_instance_class
    1392   // which will require a token to perform the define class
    1393   Symbol*  name_h = k->name();
    1394   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
    1395   int d_index = dictionary()->hash_to_index(d_hash);
    1396   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
    1397
    1398   // Register class just loaded with class loader (placed in Vector)
    1399   // Note we do this before updating the dictionary, as this can
    1400   // fail with an OutOfMemoryError (if it does, we will *not* put this
    1401   // class in the dictionary and will not update the class hierarchy).
    1402   // JVMTI FollowReferences needs to find the classes this way.
    1403   if (k->class_loader() != NULL) {
    1404     methodHandle m(THREAD, Universe::loader_addClass_method());
    1405     JavaValue result(T_VOID);
    1406     JavaCallArguments args(class_loader_h);
    1407     args.push_oop(Handle(THREAD, k->java_mirror()));
    1408     JavaCalls::call(&result, m, &args, CHECK);
    1409   }
    1410
    1411   // Add the new class. We need recompile lock during update of CHA.
    1412   {
    1413     unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
    1414     int p_index = placeholders()->hash_to_index(p_hash);
    1415
    1416     MutexLocker mu_r(Compile_lock, THREAD);
    1417
    1418     // Add to class hierarchy, initialize vtables, and do possible
    1419     // deoptimizations.
    1420     add_to_hierarchy(k, CHECK); // No exception, but can block
    1421
    1422     // Add to systemDictionary - so other classes can see it.
    1423     // Grabs and releases SystemDictionary_lock
    1424     update_dictionary(d_index, d_hash, p_index, p_hash,
    1425                       k, class_loader_h, THREAD);
    1426   }
    1427   k->eager_initialize(THREAD);
    1428
    1429   // notify jvmti
    1430   if (JvmtiExport::should_post_class_load()) {
    1431       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
    1432       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
    1433
    1434   }
    1435
    1436 }
    1437
    1438 // Support parallel classloading
    1439 // All parallel class loaders, including bootstrap classloader
    1440 // lock a placeholder entry for this class/class_loader pair
    1441 // to allow parallel defines of different classes for this class loader
    1442 // With AllowParallelDefine flag==true, in case they do not synchronize around
    1443 // FindLoadedClass/DefineClass, calls, we check for parallel
    1444 // loading for them, wait if a defineClass is in progress
    1445 // and return the initial requestor's results
    1446 // This flag does not apply to the bootstrap classloader.
    1447 // With AllowParallelDefine flag==false, call through to define_instance_class
    1448 // which will throw LinkageError: duplicate class definition.
    1449 // False is the requested default.
    1450 // For better performance, the class loaders should synchronize
    1451 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
    1452 // potentially waste time reading and parsing the bytestream.
    1453 // Note: VM callers should ensure consistency of k/class_name,class_loader
    1454 instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
    1455
    1456   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
    1457   Symbol*  name_h = k->name(); // passed in class_name may be null
    1458   ClassLoaderData* loader_data = class_loader_data(class_loader);
    1459
    1460   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
    1461   int d_index = dictionary()->hash_to_index(d_hash);
    1462
    1463 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
    1464   unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
    1465   int p_index = placeholders()->hash_to_index(p_hash);
    1466   PlaceholderEntry* probe;
    1467
    1468   {
    1469     MutexLocker mu(SystemDictionary_lock, THREAD);

    1470     // First check if class already defined
    1471     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
    1472       Klass* check = find_class(d_index, d_hash, name_h, loader_data);
    1473       if (check != NULL) {
    1474         return(instanceKlassHandle(THREAD, check));
    1475       }
    1476     }
    1477
    1478     // Acquire define token for this class/classloader
    1479     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
    1480     // Wait if another thread defining in parallel
    1481     // All threads wait - even those that will throw duplicate class: otherwise
    1482     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
    1483     // if other thread has not finished updating dictionary
    1484     while (probe->definer() != NULL) {
    1485       SystemDictionary_lock->wait();
    1486     }
    1487     // Only special cases allow parallel defines and can use other thread's results
    1488     // Other cases fall through, and may run into duplicate defines
    1489     // caught by finding an entry in the SystemDictionary
    1490     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
    1491         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
    1492         SystemDictionary_lock->notify_all();
    1493 #ifdef ASSERT
    1494         Klass* check = find_class(d_index, d_hash, name_h, loader_data);
    1495         assert(check != NULL, "definer missed recording success");
    1496 #endif
    1497         return(instanceKlassHandle(THREAD, probe->instance_klass()));
    1498     } else {
    1499       // This thread will define the class (even if earlier thread tried and had an error)
    1500       probe->set_definer(THREAD);
    1501     }
    1502   }
    1503
    1504   define_instance_class(k, THREAD);
    1505
    1506   Handle linkage_exception = Handle(); // null handle
    1507
    1508   // definer must notify any waiting threads
    1509   {
    1510     MutexLocker mu(SystemDictionary_lock, THREAD);

    1511     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
    1512     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
    1513     if (probe != NULL) {
    1514       if (HAS_PENDING_EXCEPTION) {
    1515         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
    1516         CLEAR_PENDING_EXCEPTION;
    1517       } else {
    1518         probe->set_instance_klass(k());
    1519       }
    1520       probe->set_definer(NULL);
    1521       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
    1522       SystemDictionary_lock->notify_all();
    1523     }
    1524   }
    1525
    1526   // Can't throw exception while holding lock due to rank ordering
    1527   if (linkage_exception() != NULL) {
    1528     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
    1529   }
    1530
    1548     return;
    1549   }
    1550
    1551   assert(!loader_lock.is_null(), "NULL lock object");
    1552
    1553   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
    1554       == ObjectSynchronizer::owner_other) {
    1555     // contention will likely happen, so increment the corresponding
    1556     // contention counter.
    1557     if (loader_lock() == _system_loader_lock_obj) {
    1558       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
    1559     } else {
    1560       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
    1561     }
    1562   }
    1563 }
    1564
    1565 // ----------------------------------------------------------------------------
    1566 // Lookup
    1567
    1568 Klass* SystemDictionary::find_class(int index, unsigned int hash,
    1569                                       Symbol* class_name,
    1570                                       ClassLoaderData* loader_data) {
    1571   assert_locked_or_safepoint(SystemDictionary_lock);
    1572   assert (index == dictionary()->index_for(class_name, loader_data),
    1573           "incorrect index?");
    1574
    1575   Klass* k = dictionary()->find_class(index, hash, class_name, loader_data);
    1576   return k;
    1577 }
    1578
    1579
    1580 // Basic find on classes in the midst of being loaded
    1581 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
    1582                                            ClassLoaderData* loader_data) {
    1583   assert_locked_or_safepoint(SystemDictionary_lock);
    1584   unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
    1585   int p_index = placeholders()->hash_to_index(p_hash);
    1586   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
    1587 }
    1588
    1589
    1590 // Used for assertions and verification only
    1591 Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
    1592   #ifndef ASSERT
    1593   guarantee(VerifyBeforeGC      ||
    1594             VerifyDuringGC      ||
    1595             VerifyBeforeExit    ||
    1596             VerifyDuringStartup ||
    1597             VerifyAfterGC, "too expensive");
    1598   #endif
    1599   assert_locked_or_safepoint(SystemDictionary_lock);
    1600
    1601   // First look in the loaded class array
    1602   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
    1603   int d_index = dictionary()->hash_to_index(d_hash);
    1604   return find_class(d_index, d_hash, class_name, loader_data);
    1605 }
    1606
    1607
    1608 // Get the next class in the diictionary.
    1609 Klass* SystemDictionary::try_get_next_class() {
    1610   return dictionary()->try_get_next_class();
    1611 }
    1612
    1613
    1614 // ----------------------------------------------------------------------------
    1615 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
    1616 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
    1617 // before a new class is used.
    1618
    1619 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
    1620   assert(k.not_null(), "just checking");
    1621   assert_locked_or_safepoint(Compile_lock);
    1622
    1623   // Link into hierachy. Make sure the vtables are initialized before linking into
    1624   k->append_to_sibling_list();                    // add to superklass/sibling list
    1798
    1799   // if multiple threads calling this function, only one thread will load
    1800   // the class.  The other threads will find the loaded version once the
    1801   // class is loaded.
    1802   Klass* aos = _abstract_ownable_synchronizer_klass;
    1803   if (aos == NULL) {
    1804     Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
    1805     // Force a fence to prevent any read before the write completes
    1806     OrderAccess::fence();
    1807     _abstract_ownable_synchronizer_klass = k;
    1808   }
    1809 }
    1810
    1811 // ----------------------------------------------------------------------------
    1812 // Initialization
    1813
    1814 void SystemDictionary::initialize(TRAPS) {
    1815   // Allocate arrays
    1816   assert(dictionary() == NULL,
    1817          "SystemDictionary should only be initialized once");

    1818   _sdgeneration        = 0;
    1819   _dictionary          = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));

    1820   _placeholders        = new PlaceholderTable(_nof_buckets);
    1821   _number_of_modifications = 0;

    1822   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);

    1823   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);

    1824   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
    1825
    1826   // Allocate private object used as system class loader lock
    1827   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
    1828   // Initialize basic classes
    1829   initialize_preloaded_classes(CHECK);
    1830 }
    1831
    1832 // Compact table of directions on the initialization of klasses:
    1833 static const short wk_init_info[] = {
    1834   #define WK_KLASS_INIT_INFO(name, symbol, option) \
    1835     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
    1836           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
    1837       | (int)SystemDictionary::option ),
    1838   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
    1839   #undef WK_KLASS_INIT_INFO
    1840   0
    1841 };
    1842
    1843 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
    1949
    1950 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
    1951 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
    1952 BasicType SystemDictionary::box_klass_type(Klass* k) {
    1953   assert(k != NULL, "");
    1954   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
    1955     if (_box_klasses[i] == k)
    1956       return (BasicType)i;
    1957   }
    1958   return T_OBJECT;
    1959 }
    1960
    1961 // Constraints on class loaders. The details of the algorithm can be
    1962 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
    1963 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
    1964 // that the system dictionary needs to maintain a set of contraints that
    1965 // must be satisfied by all classes in the dictionary.
    1966 // if defining is true, then LinkageError if already in systemDictionary
    1967 // if initiating loader, then ok if InstanceKlass matches existing entry
    1968
    1969 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
    1970                                          instanceKlassHandle k,
    1971                                          Handle class_loader, bool defining,
    1972                                          TRAPS) {
    1973   const char *linkage_error = NULL;
    1974   {
    1975     Symbol*  name  = k->name();
    1976     ClassLoaderData *loader_data = class_loader_data(class_loader);
    1977
    1978     MutexLocker mu(SystemDictionary_lock, THREAD);
    1979
    1980     Klass* check = find_class(d_index, d_hash, name, loader_data);
    1981     if (check != (Klass*)NULL) {
    1982       // if different InstanceKlass - duplicate class definition,
    1983       // else - ok, class loaded by a different thread in parallel,
    1984       // we should only have found it if it was done loading and ok to use
    1985       // system dictionary only holds instance classes, placeholders
    1986       // also holds array classes
    1987
    1988       assert(check->oop_is_instance(), "noninstance in systemdictionary");
    1989       if ((defining == true) || (k() != check)) {
    1990         linkage_error = "loader (instance of  %s): attempted  duplicate class "
    1991           "definition for name: \"%s\"";
    1992       } else {
    1993         return;
    1994       }
    1995     }
    1996
    1997 #ifdef ASSERT
    1998     Symbol* ph_check = find_placeholder(name, loader_data);
    1999     assert(ph_check == NULL || ph_check == name, "invalid symbol");
    2000 #endif
    2008   }
    2009
    2010   // Throw error now if needed (cannot throw while holding
    2011   // SystemDictionary_lock because of rank ordering)
    2012
    2013   if (linkage_error) {
    2014     ResourceMark rm(THREAD);
    2015     const char* class_loader_name = loader_name(class_loader());
    2016     char* type_name = k->name()->as_C_string();
    2017     size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
    2018       strlen(type_name);
    2019     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
    2020     jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
    2021     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
    2022   }
    2023 }
    2024
    2025
    2026 // Update system dictionary - done after check_constraint and add_to_hierachy
    2027 // have been called.
    2028 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
    2029                                          int p_index, unsigned int p_hash,
    2030                                          instanceKlassHandle k,
    2031                                          Handle class_loader,
    2032                                          TRAPS) {
    2033   // Compile_lock prevents systemDictionary updates during compilations
    2034   assert_locked_or_safepoint(Compile_lock);
    2035   Symbol*  name  = k->name();
    2036   ClassLoaderData *loader_data = class_loader_data(class_loader);
    2037
    2038   {
    2039   MutexLocker mu1(SystemDictionary_lock, THREAD);
    2040
    2041   // See whether biased locking is enabled and if so set it for this
    2042   // klass.
    2043   // Note that this must be done past the last potential blocking
    2044   // point / safepoint. We enable biased locking lazily using a
    2045   // VM_Operation to iterate the SystemDictionary and installing the
    2046   // biasable mark word into each InstanceKlass's prototype header.
    2047   // To avoid race conditions where we accidentally miss enabling the
    2048   // optimization for one class in the process of being added to the
    2049   // dictionary, we must not safepoint after the test of
    2050   // BiasedLocking::enabled().
    2051   if (UseBiasedLocking && BiasedLocking::enabled()) {
    2052     // Set biased locking bit for all loaded classes; it will be
    2053     // cleared if revocation occurs too often for this type
    2054     // NOTE that we must only do this when the class is initally
    2055     // defined, not each time it is referenced from a new class loader
    2056     if (k->class_loader() == class_loader()) {
    2057       k->set_prototype_header(markOopDesc::biased_locking_prototype());
    2058     }
    2059   }
    2060
    2061   // Make a new system dictionary entry.
    2062   Klass* sd_check = find_class(d_index, d_hash, name, loader_data);
    2063   if (sd_check == NULL) {
    2064     dictionary()->add_klass(name, loader_data, k);
    2065     notice_modification();
    2066   }
    2067 #ifdef ASSERT
    2068   sd_check = find_class(d_index, d_hash, name, loader_data);
    2069   assert (sd_check != NULL, "should have entry in system dictionary");
    2070   // Note: there may be a placeholder entry: for circularity testing
    2071   // or for parallel defines
    2072 #endif
    2073     SystemDictionary_lock->notify_all();
    2074   }
    2075 }
    2076
    2077
    2078 // Try to find a class name using the loader constraints.  The
    2079 // loader constraints might know about a class that isn't fully loaded
    2080 // yet and these will be ignored.
    2081 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
    2082                     Symbol* class_name, Handle class_loader, TRAPS) {
    2083
    2084   // First see if it has been loaded directly.
    2085   // Force the protection domain to be null.  (This removes protection checks.)
    2086   Handle no_protection_domain;
    2087   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
    2088                                               no_protection_domain, CHECK_NULL);
    2123                                              Thread* THREAD) {
    2124   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
    2125   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
    2126
    2127   Symbol* constraint_name = NULL;
    2128   if (!FieldType::is_array(class_name)) {
    2129     constraint_name = class_name;
    2130   } else {
    2131     // For array classes, their Klass*s are not kept in the
    2132     // constraint table. The element classes are.
    2133     FieldArrayInfo fd;
    2134     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
    2135     // primitive types always pass
    2136     if (t != T_OBJECT) {
    2137       return true;
    2138     } else {
    2139       constraint_name = fd.object_key();
    2140     }
    2141   }
    2142   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
    2143   int d_index1 = dictionary()->hash_to_index(d_hash1);
    2144
    2145   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
    2146   int d_index2 = dictionary()->hash_to_index(d_hash2);
    2147   {
    2148   MutexLocker mu_s(SystemDictionary_lock, THREAD);
    2149
    2150   // Better never do a GC while we're holding these oops
    2151   No_Safepoint_Verifier nosafepoint;
    2152
    2153   Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
    2154   Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
    2155   return constraints()->add_entry(constraint_name, klass1, class_loader1,
    2156                                   klass2, class_loader2);
    2157   }
    2158 }
    2159
    2160 // Add entry to resolution error table to record the error when the first
    2161 // attempt to resolve a reference to a class has failed.
    2162 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, Symbol* error) {
    2163   unsigned int hash = resolution_errors()->compute_hash(pool, which);
    2164   int index = resolution_errors()->hash_to_index(hash);
    2165   {
    2166     MutexLocker ml(SystemDictionary_lock, Thread::current());

    2167     resolution_errors()->add_entry(index, hash, pool, which, error);
    2168   }
    2169 }
    2170
    2171 // Delete a resolution error for RedefineClasses for a constant pool is going away
    2172 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
    2173   resolution_errors()->delete_entry(pool);
    2174 }
    2175
    2176 // Lookup resolution error table. Returns error if found, otherwise NULL.
    2177 Symbol* SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
    2178   unsigned int hash = resolution_errors()->compute_hash(pool, which);
    2179   int index = resolution_errors()->hash_to_index(hash);
    2180   {
    2181     MutexLocker ml(SystemDictionary_lock, Thread::current());

    2182     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
    2183     return (entry != NULL) ? entry->error() : (Symbol*)NULL;
    2184   }
    2185 }
    2186
    2187
    2188 // Signature constraints ensure that callers and callees agree about
    2189 // the meaning of type names in their signatures.  This routine is the
    2190 // intake for constraints.  It collects them from several places:
    2191 //
    2192 //  * LinkResolver::resolve_method (if check_access is true) requires
    2193 //    that the resolving class (the caller) and the defining class of
    2194 //    the resolved method (the callee) agree on each type in the
    2195 //    method's signature.
    2196 //
    2197 //  * LinkResolver::resolve_interface_method performs exactly the same
    2198 //    checks.
    2199 //
    2200 //  * LinkResolver::resolve_field requires that the constant pool
    2201 //    attempting to link to a field agree with the field's defining
    2271   int          index = invoke_method_table()->hash_to_index(hash);
    2272   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
    2273   methodHandle m;
    2274   if (spe == NULL || spe->method() == NULL) {
    2275     spe = NULL;
    2276     // Must create lots of stuff here, but outside of the SystemDictionary lock.
    2277     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));
    2278     if (!Arguments::is_interpreter_only()) {
    2279       // Generate a compiled form of the MH intrinsic.
    2280       AdapterHandlerLibrary::create_native_wrapper(m);
    2281       // Check if have the compiled code.
    2282       if (!m->has_compiled_code()) {
    2283         THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),
    2284                    "out of space in CodeCache for method handle intrinsic", empty);
    2285       }
    2286     }
    2287     // Now grab the lock.  We might have to throw away the new method,
    2288     // if a racing thread has managed to install one at the same time.
    2289     {
    2290       MutexLocker ml(SystemDictionary_lock, THREAD);

    2291       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
    2292       if (spe == NULL)
    2293         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
    2294       if (spe->method() == NULL)
    2295         spe->set_method(m());
    2296     }
    2297   }
    2298
    2299   assert(spe != NULL && spe->method() != NULL, "");
    2300   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
    2301          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
    2302          "MH intrinsic invariant");
    2303   return spe->method();
    2304 }
    2305
    2306 // Helper for unpacking the return value from linkMethod and linkCallSite.
    2307 static methodHandle unpack_method_and_appendix(Handle mname,
    2308                                                KlassHandle accessing_klass,
    2309                                                objArrayHandle appendix_box,
    2310                                                Handle* appendix_result,
    2447         LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
    2448       }
    2449     }
    2450   }
    2451   assert(arg == npts, "");
    2452
    2453   // call java.lang.invoke.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
    2454   JavaCallArguments args(Handle(THREAD, rt()));
    2455   args.push_oop(pts());
    2456   JavaValue result(T_OBJECT);
    2457   JavaCalls::call_static(&result,
    2458                          SystemDictionary::MethodHandleNatives_klass(),
    2459                          vmSymbols::findMethodHandleType_name(),
    2460                          vmSymbols::findMethodHandleType_signature(),
    2461                          &args, CHECK_(empty));
    2462   Handle method_type(THREAD, (oop) result.get_jobject());
    2463
    2464   if (is_on_bcp) {
    2465     // We can cache this MethodType inside the JVM.
    2466     MutexLocker ml(SystemDictionary_lock, THREAD);

    2467     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
    2468     if (spe == NULL)
    2469       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
    2470     if (spe->method_type() == NULL) {
    2471       spe->set_method_type(method_type());
    2472     }
    2473   }
    2474
    2475   // report back to the caller with the MethodType
    2476   return method_type;
    2477 }
    2478
    2479 // Ask Java code to find or construct a method handle constant.
    2480 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
    2481                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
    2482                                                      KlassHandle callee,
    2483                                                      Symbol* name_sym,
    2484                                                      Symbol* signature,
    2485                                                      TRAPS) {
    2486   Handle empty;
    2602
    2603
    2604 void SystemDictionary::reverse() {
    2605   dictionary()->reverse();
    2606 }
    2607
    2608 int SystemDictionary::number_of_classes() {
    2609   return dictionary()->number_of_entries();
    2610 }
    2611
    2612
    2613 // ----------------------------------------------------------------------------
    2614 void SystemDictionary::print_shared(bool details) {
    2615   shared_dictionary()->print(details);
    2616 }
    2617
    2618 void SystemDictionary::print(bool details) {
    2619   dictionary()->print(details);
    2620
    2621   // Placeholders
    2622   GCMutexLocker mu(SystemDictionary_lock);
    2623   placeholders()->print();
    2624
    2625   // loader constraints - print under SD_lock
    2626   constraints()->print();
    2627 }
    2628
    2629
    2630 void SystemDictionary::verify() {
    2631   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
    2632   guarantee(constraints() != NULL,
    2633             "Verify of loader constraints failed");
    2634   guarantee(dictionary()->number_of_entries() >= 0 &&
    2635             placeholders()->number_of_entries() >= 0,
    2636             "Verify of system dictionary failed");
    2637
    2638   // Verify dictionary
    2639   dictionary()->verify();
    2640
    2641   GCMutexLocker mu(SystemDictionary_lock);
    2642   placeholders()->verify();
    2643
    2644   // Verify constraint table
    2645   guarantee(constraints() != NULL, "Verify of loader constraints failed");
    2646   constraints()->verify(dictionary(), placeholders());
      61 #include "runtime/orderAccess.inline.hpp"
      62 #include "runtime/signature.hpp"
      63 #include "services/classLoadingService.hpp"
      64 #include "services/threadService.hpp"
      65 #include "utilities/macros.hpp"
      66 #include "utilities/ticks.hpp"
      67 #if INCLUDE_TRACE
      68 #include "trace/tracing.hpp"
      69 #endif
      70
      71 Dictionary*            SystemDictionary::_dictionary          = NULL;
      72 PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
      73 Dictionary*            SystemDictionary::_shared_dictionary   = NULL;
      74 LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
      75 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
      76 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
      77
      78
      79 int         SystemDictionary::_number_of_modifications    = 0;
      80 int         SystemDictionary::_sdgeneration               = 0;
      81 const int   SystemDictionary::_primelist[_prime_array_size] = {defaultSystemDictionarySize,2017,4049,5051,10103,
      82   20201,40423,99991};
      83
      84 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
      85
      86 Klass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
      87                                                           =  { NULL /*, NULL...*/ };
      88
      89 Klass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
      90
      91 oop         SystemDictionary::_java_system_loader         =  NULL;
      92
      93 bool        SystemDictionary::_has_loadClassInternal      =  false;
      94 bool        SystemDictionary::_has_checkPackageAccess     =  false;
      95
      96 // lazily initialized klass variables
      97 Klass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
      98
      99
     100 // ----------------------------------------------------------------------------
     101 // Java-level SystemLoader
     316                                                  bool is_superclass,
     317                                                  TRAPS) {
     318   // Double-check, if child class is already loaded, just return super-class,interface
     319   // Don't add a placedholder if already loaded, i.e. already in system dictionary
     320   // Make sure there's a placeholder for the *child* before resolving.
     321   // Used as a claim that this thread is currently loading superclass/classloader
     322   // Used here for ClassCircularity checks and also for heap verification
     323   // (every InstanceKlass in the heap needs to be in the system dictionary
     324   // or have a placeholder).
     325   // Must check ClassCircularity before checking if super class is already loaded
     326   //
     327   // We might not already have a placeholder if this child_name was
     328   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
     329   // the name of the class might not be known until the stream is actually
     330   // parsed.
     331   // Bugs 4643874, 4715493
     332   // compute_hash can have a safepoint
     333
     334   ClassLoaderData* loader_data = class_loader_data(class_loader);
     335   unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);

     336   unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);

     337   // can't throw error holding a lock
     338   bool child_already_loaded = false;
     339   bool throw_circularity_error = false;
     340   {
     341     MutexLocker mu(SystemDictionary_lock, THREAD);
     342     int p_index = placeholders()->hash_to_index(p_hash);
     343     Klass* childk = find_class(d_hash, child_name, loader_data);
     344     Klass* quicksuperk;
     345     // to support // loading: if child done loading, just return superclass
     346     // if class_name, & class_loader don't match:
     347     // if initial define, SD update will give LinkageError
     348     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
     349     // so we don't throw an exception here.
     350     // see: nsk redefclass014 & java.lang.instrument Instrument032
     351     if ((childk != NULL ) && (is_superclass) &&
     352        ((quicksuperk = InstanceKlass::cast(childk)->super()) != NULL) &&
     353
     354          ((quicksuperk->name() == class_name) &&
     355             (quicksuperk->class_loader()  == class_loader()))) {
     356            return quicksuperk;
     357     } else {
     358       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
     359       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
     360           throw_circularity_error = true;
     361       }
     362     }
     363     if (!throw_circularity_error) {
     370   }
     371
     372 // java.lang.Object should have been found above
     373   assert(class_name != NULL, "null super class for resolving");
     374   // Resolve the super class or interface, check results on return
     375   Klass* superk = SystemDictionary::resolve_or_null(class_name,
     376                                                  class_loader,
     377                                                  protection_domain,
     378                                                  THREAD);
     379
     380   KlassHandle superk_h(THREAD, superk);
     381
     382   // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
     383   // It is no longer necessary to keep the placeholder table alive until update_dictionary
     384   // or error. GC used to walk the placeholder table as strong roots.
     385   // The instanceKlass is kept alive because the class loader is on the stack,
     386   // which keeps the loader_data alive, as well as all instanceKlasses in
     387   // the loader_data. parseClassFile adds the instanceKlass to loader_data.
     388   {
     389     MutexLocker mu(SystemDictionary_lock, THREAD);
     390     int p_index = placeholders()->hash_to_index(p_hash);
     391     placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
     392     SystemDictionary_lock->notify_all();
     393   }
     394   if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
     395     // can null superk
     396     superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, class_loader, protection_domain, true, superk_h, THREAD));
     397   }
     398
     399   return superk_h();
     400 }
     401
     402 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
     403                                                   Handle class_loader,
     404                                                   Handle protection_domain,
     405                                                   TRAPS) {
     406   if(!has_checkPackageAccess()) return;
     407
     408   // Now we have to call back to java to check if the initating class has access
     409   JavaValue result(T_VOID);
     410   if (TraceProtectionDomainVerification) {
     428   if (TraceProtectionDomainVerification) {
     429     if (HAS_PENDING_EXCEPTION) {
     430       tty->print_cr(" -> DENIED !!!!!!!!!!!!!!!!!!!!!");
     431     } else {
     432      tty->print_cr(" -> granted");
     433     }
     434     tty->cr();
     435   }
     436
     437   if (HAS_PENDING_EXCEPTION) return;
     438
     439   // If no exception has been thrown, we have validated the protection domain
     440   // Insert the protection domain of the initiating class into the set.
     441   {
     442     // We recalculate the entry here -- we've called out to java since
     443     // the last time it was calculated.
     444     ClassLoaderData* loader_data = class_loader_data(class_loader);
     445
     446     Symbol*  kn = klass->name();
     447     unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);

     448
     449     MutexLocker mu(SystemDictionary_lock, THREAD);
     450     {
     451       // Note that we have an entry, and entries can be deleted only during GC,
     452       // so we cannot allow GC to occur while we're holding this entry.
     453
     454       // We're using a No_Safepoint_Verifier to catch any place where we
     455       // might potentially do a GC at all.
     456       // Dictionary::do_unloading() asserts that classes in SD are only
     457       // unloaded at a safepoint. Anonymous classes are not in SD.
     458       No_Safepoint_Verifier nosafepoint;
     459       dictionary()->add_protection_domain(d_hash, klass, loader_data,
     460                                           protection_domain, THREAD);
     461     }
     462   }
     463 }
     464
     465 // We only get here if this thread finds that another thread
     466 // has already claimed the placeholder token for the current operation,
     467 // but that other thread either never owned or gave up the
     468 // object lock
     469 // Waits on SystemDictionary_lock to indicate placeholder table updated
     470 // On return, caller must recheck placeholder table state
     471 //
     472 // We only get here if
     473 //  1) custom classLoader, i.e. not bootstrap classloader
     474 //  2) UnsyncloadClass not set
     475 //  3) custom classLoader has broken the class loader objectLock
     476 //     so another thread got here in parallel
     477 //
     478 // lockObject must be held.
     479 // Complicated dance due to lock ordering:
     505 // If the class in is in the placeholder table, class loading is in progress
     506 // For cases where the application changes threads to load classes, it
     507 // is critical to ClassCircularity detection that we try loading
     508 // the superclass on the same thread internally, so we do parallel
     509 // super class loading here.
     510 // This also is critical in cases where the original thread gets stalled
     511 // even in non-circularity situations.
     512 // Note: must call resolve_super_or_fail even if null super -
     513 // to force placeholder entry creation for this class for circularity detection
     514 // Caller must check for pending exception
     515 // Returns non-null Klass* if other thread has completed load
     516 // and we are done,
     517 // If return null Klass* and no pending exception, the caller must load the class
     518 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
     519     Symbol* name, Symbol* superclassname, Handle class_loader,
     520     Handle protection_domain, Handle lockObject, TRAPS) {
     521
     522   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
     523   ClassLoaderData* loader_data = class_loader_data(class_loader);
     524   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);

     525   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);

     526
     527   // superk is not used, resolve_super called for circularity check only
     528   // This code is reached in two situations. One if this thread
     529   // is loading the same class twice (e.g. ClassCircularity, or
     530   // java.lang.instrument).
     531   // The second is if another thread started the resolve_super first
     532   // and has not yet finished.
     533   // In both cases the original caller will clean up the placeholder
     534   // entry on error.
     535   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
     536                                                           superclassname,
     537                                                           class_loader,
     538                                                           protection_domain,
     539                                                           true,
     540                                                           CHECK_(nh));
     541
     542   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
     543   // Serial class loaders and bootstrap classloader do wait for superclass loads
     544  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
     545     MutexLocker mu(SystemDictionary_lock, THREAD);
     546     // Check if classloading completed while we were loading superclass or waiting
     547     Klass* check = find_class(d_hash, name, loader_data);
     548     if (check != NULL) {
     549       // Klass is already loaded, so just return it
     550       return(instanceKlassHandle(THREAD, check));
     551     } else {
     552       return nh;
     553     }
     554   }
     555
     556   // must loop to both handle other placeholder updates
     557   // and spurious notifications
     558   bool super_load_in_progress = true;
     559   PlaceholderEntry* placeholder;
     560   while (super_load_in_progress) {
     561     MutexLocker mu(SystemDictionary_lock, THREAD);
     562     int p_index = placeholders()->hash_to_index(p_hash);
     563     // Check if classloading completed while we were loading superclass or waiting
     564     Klass* check = find_class(d_hash, name, loader_data);
     565     if (check != NULL) {
     566       // Klass is already loaded, so just return it
     567       return(instanceKlassHandle(THREAD, check));
     568     } else {
     569       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
     570       if (placeholder && placeholder->super_load_in_progress() ){
     571         // Before UnsyncloadClass:
     572         // We only get here if the application has released the
     573         // classloader lock when another thread was in the middle of loading a
     574         // superclass/superinterface for this class, and now
     575         // this thread is also trying to load this class.
     576         // To minimize surprises, the first thread that started to
     577         // load a class should be the one to complete the loading
     578         // with the classfile it initially expected.
     579         // This logic has the current thread wait once it has done
     580         // all the superclass/superinterface loading it can, until
     581         // the original thread completes the class loading or fails
     582         // If it completes we will use the resulting InstanceKlass
     583         // which we will find below in the systemDictionary.
     584         // We also get here for parallel bootstrap classloader
     601                                                         Handle class_loader,
     602                                                         Handle protection_domain,
     603                                                         TRAPS) {
     604   assert(name != NULL && !FieldType::is_array(name) &&
     605          !FieldType::is_obj(name), "invalid class name");
     606
     607   Ticks class_load_start_time = Ticks::now();
     608
     609   // UseNewReflection
     610   // Fix for 4474172; see evaluation for more details
     611   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
     612   ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);
     613
     614   // Do lookup to see if class already exist and the protection domain
     615   // has the right access
     616   // This call uses find which checks protection domain already matches
     617   // All subsequent calls use find_class, and set has_loaded_class so that
     618   // before we return a result we call out to java to check for valid protection domain
     619   // to allow returning the Klass* and add it to the pd_set if it is valid
     620   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
     621   Klass* probe = dictionary()->find(d_hash, name, loader_data,

     622                                       protection_domain, THREAD);
     623   if (probe != NULL) return probe;
     624
     625
     626   // Non-bootstrap class loaders will call out to class loader and
     627   // define via jvm/jni_DefineClass which will acquire the
     628   // class loader object lock to protect against multiple threads
     629   // defining the class in parallel by accident.
     630   // This lock must be acquired here so the waiter will find
     631   // any successful result in the SystemDictionary and not attempt
     632   // the define
     633   // ParallelCapable Classloaders and the bootstrap classloader,
     634   // or all classloaders with UnsyncloadClass do not acquire lock here
     635   bool DoObjectLock = true;
     636   if (is_parallelCapable(class_loader)) {
     637     DoObjectLock = false;
     638   }
     639
     640   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);

     641
     642   // Class is not in SystemDictionary so we have to do loading.
     643   // Make sure we are synchronized on the class loader before we proceed
     644   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
     645   check_loader_lock_contention(lockObject, THREAD);
     646   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
     647
     648   // Check again (after locking) if class already exist in SystemDictionary
     649   bool class_has_been_loaded   = false;
     650   bool super_load_in_progress  = false;
     651   bool havesupername = false;
     652   instanceKlassHandle k;
     653   PlaceholderEntry* placeholder;
     654   Symbol* superclassname = NULL;
     655
     656   {
     657     MutexLocker mu(SystemDictionary_lock, THREAD);
     658     int p_index = placeholders()->hash_to_index(p_hash);
     659     Klass* check = find_class(d_hash, name, loader_data);
     660     if (check != NULL) {
     661       // Klass is already loaded, so just return it
     662       class_has_been_loaded = true;
     663       k = instanceKlassHandle(THREAD, check);
     664     } else {
     665       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
     666       if (placeholder && placeholder->super_load_in_progress()) {
     667          super_load_in_progress = true;
     668          if (placeholder->havesupername() == true) {
     669            superclassname = placeholder->supername();
     670            havesupername = true;
     671          }
     672       }
     673     }
     674   }
     675
     676   // If the class is in the placeholder table, class loading is in progress
     677   if (super_load_in_progress && havesupername==true) {
     678     k = SystemDictionary::handle_parallel_super_load(name, superclassname,
     679         class_loader, protection_domain, lockObject, THREAD);
     699     // case 1. traditional classloaders that rely on the classloader object lock
     700     //   - no other need for LOAD_INSTANCE
     701     // case 2. traditional classloaders that break the classloader object lock
     702     //    as a deadlock workaround. Detection of this case requires that
     703     //    this check is done while holding the classloader object lock,
     704     //    and that lock is still held when calling classloader's loadClass.
     705     //    For these classloaders, we ensure that the first requestor
     706     //    completes the load and other requestors wait for completion.
     707     // case 3. UnsyncloadClass - don't use objectLocker
     708     //    With this flag, we allow parallel classloading of a
     709     //    class/classloader pair
     710     // case4. Bootstrap classloader - don't own objectLocker
     711     //    This classloader supports parallelism at the classloader level,
     712     //    but only allows a single load of a class/classloader pair.
     713     //    No performance benefit and no deadlock issues.
     714     // case 5. parallelCapable user level classloaders - without objectLocker
     715     //    Allow parallel classloading of a class/classloader pair
     716
     717     {
     718       MutexLocker mu(SystemDictionary_lock, THREAD);
     719       int p_index = placeholders()->hash_to_index(p_hash);
     720       if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
     721         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
     722         if (oldprobe) {
     723           // only need check_seen_thread once, not on each loop
     724           // 6341374 java/lang/Instrument with -Xcomp
     725           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
     726             throw_circularity_error = true;
     727           } else {
     728             // case 1: traditional: should never see load_in_progress.
     729             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
     730
     731               // case 4: bootstrap classloader: prevent futile classloading,
     732               // wait on first requestor
     733               if (class_loader.is_null()) {
     734                 SystemDictionary_lock->wait();
     735               } else {
     736               // case 2: traditional with broken classloader lock. wait on first
     737               // requestor.
     738                 double_lock_wait(lockObject, THREAD);
     739               }
     740               // Check if classloading completed while we were waiting
     741               Klass* check = find_class(d_hash, name, loader_data);
     742               if (check != NULL) {
     743                 // Klass is already loaded, so just return it
     744                 k = instanceKlassHandle(THREAD, check);
     745                 class_has_been_loaded = true;
     746               }
     747               // check if other thread failed to load and cleaned up
     748               oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
     749             }
     750           }
     751         }
     752       }
     753       // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
     754       // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
     755       // LOAD_INSTANCE in parallel
     756
     757       if (!throw_circularity_error && !class_has_been_loaded) {
     758         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
     759         load_instance_added = true;
     760         // For class loaders that do not acquire the classloader object lock,
     761         // if they did not catch another thread holding LOAD_INSTANCE,
     762         // need a check analogous to the acquire ObjectLocker/find_class
     763         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
     764         // one final check if the load has already completed
     765         // class loaders holding the ObjectLock shouldn't find the class here
     766         Klass* check = find_class(d_hash, name, loader_data);
     767         if (check != NULL) {
     768         // Klass is already loaded, so return it after checking/adding protection domain
     769           k = instanceKlassHandle(THREAD, check);
     770           class_has_been_loaded = true;
     771         }
     772       }
     773     }
     774
     775     // must throw error outside of owning lock
     776     if (throw_circularity_error) {
     777       assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
     778       ResourceMark rm(THREAD);
     779       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
     780     }
     781
     782     if (!class_has_been_loaded) {
     783
     784       // Do actual loading
     785       k = load_instance_class(name, class_loader, THREAD);
     786
     787       // For UnsyncloadClass only
     788       // If they got a linkageError, check if a parallel class load succeeded.
     789       // If it did, then for bytecode resolution the specification requires
     790       // that we return the same result we did for the other thread, i.e. the
     791       // successfully loaded InstanceKlass
     792       // Should not get here for classloaders that support parallelism
     793       // with the new cleaner mechanism, even with AllowParallelDefineClass
     794       // Bootstrap goes through here to allow for an extra guarantee check
     795       if (UnsyncloadClass || (class_loader.is_null())) {
     796         if (k.is_null() && HAS_PENDING_EXCEPTION
     797           && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
     798           MutexLocker mu(SystemDictionary_lock, THREAD);
     799           Klass* check = find_class(d_hash, name, loader_data);
     800           if (check != NULL) {
     801             // Klass is already loaded, so just use it
     802             k = instanceKlassHandle(THREAD, check);
     803             CLEAR_PENDING_EXCEPTION;
     804             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
     805           }
     806         }
     807       }
     808
     809       // If everything was OK (no exceptions, no null return value), and
     810       // class_loader is NOT the defining loader, do a little more bookkeeping.
     811       if (!HAS_PENDING_EXCEPTION && !k.is_null() &&
     812         k->class_loader() != class_loader()) {
     813
     814         check_constraints(d_hash, k, class_loader, false, THREAD);
     815
     816         // Need to check for a PENDING_EXCEPTION again; check_constraints
     817         // can throw and doesn't use the CHECK macro.
     818         if (!HAS_PENDING_EXCEPTION) {
     819           { // Grabbing the Compile_lock prevents systemDictionary updates
     820             // during compilations.
     821             MutexLocker mu(Compile_lock, THREAD);
     822             update_dictionary(d_hash, p_hash,
     823                               k, class_loader, THREAD);
     824           }
     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     } // load_instance_class loop
     834
     835     if (load_instance_added == true) {
     836       // clean up placeholder entries for LOAD_INSTANCE success or error
     837       // This brackets the SystemDictionary updates for both defining
     838       // and initiating loaders
     839       MutexLocker mu(SystemDictionary_lock, THREAD);
     840       int p_index = placeholders()->hash_to_index(p_hash);
     841       placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
     842       SystemDictionary_lock->notify_all();
     843     }
     844   }
     845
     846   if (HAS_PENDING_EXCEPTION || k.is_null()) {
     847     return NULL;
     848   }
     849
     850   post_class_load_event(class_load_start_time, k, class_loader);
     851
     852 #ifdef ASSERT
     853   {
     854     ClassLoaderData* loader_data = k->class_loader_data();
     855     MutexLocker mu(SystemDictionary_lock, THREAD);
     856     Klass* kk = find_class(name, loader_data);
     857     assert(kk == k(), "should be present in dictionary");
     858   }
     859 #endif
     860
     861   // return if the protection domain in NULL
     862   if (protection_domain() == NULL) return k();
     863
     864   // Check the protection domain has the right access
     865   {
     866     MutexLocker mu(SystemDictionary_lock, THREAD);
     867     // Note that we have an entry, and entries can be deleted only during GC,
     868     // so we cannot allow GC to occur while we're holding this entry.
     869     // We're using a No_Safepoint_Verifier to catch any place where we
     870     // might potentially do a GC at all.
     871     // Dictionary::do_unloading() asserts that classes in SD are only
     872     // unloaded at a safepoint. Anonymous classes are not in SD.
     873     No_Safepoint_Verifier nosafepoint;
     874     if (dictionary()->is_valid_protection_domain(d_hash, name,
     875                                                  loader_data,
     876                                                  protection_domain)) {
     877       return k();
     878     }
     879   }
     880
     881   // Verify protection domain. If it fails an exception is thrown
     882   validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
     883
     884   return k();
     885 }
     886
     887
     888 // This routine does not lock the system dictionary.
     889 //
     890 // Since readers don't hold a lock, we must make sure that system
     891 // dictionary entries are only removed at a safepoint (when only one
     892 // thread is running), and are added to in a safe way (all links must
     893 // be updated in an MT-safe manner).
     894 //
     898
     899 Klass* SystemDictionary::find(Symbol* class_name,
     900                               Handle class_loader,
     901                               Handle protection_domain,
     902                               TRAPS) {
     903
     904   // UseNewReflection
     905   // The result of this call should be consistent with the result
     906   // of the call to resolve_instance_class_or_null().
     907   // See evaluation 6790209 and 4474172 for more details.
     908   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
     909   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
     910
     911   if (loader_data == NULL) {
     912     // If the ClassLoaderData has not been setup,
     913     // then the class loader has no entries in the dictionary.
     914     return NULL;
     915   }
     916
     917   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);

     918
     919   {
     920     // Note that we have an entry, and entries can be deleted only during GC,
     921     // so we cannot allow GC to occur while we're holding this entry.
     922     // We're using a No_Safepoint_Verifier to catch any place where we
     923     // might potentially do a GC at all.
     924     // Dictionary::do_unloading() asserts that classes in SD are only
     925     // unloaded at a safepoint. Anonymous classes are not in SD.
     926     No_Safepoint_Verifier nosafepoint;
     927     return dictionary()->find(d_hash, class_name, loader_data,
     928                               protection_domain, THREAD);
     929   }
     930 }
     931
     932
     933 // Look for a loaded instance or array klass by name.  Do not do any loading.
     934 // return NULL in case of error.
     935 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
     936                                                       Handle class_loader,
     937                                                       Handle protection_domain,
     938                                                       TRAPS) {
     939   Klass* k = NULL;
     940   assert(class_name != NULL, "class name must be non NULL");
     941
     942   if (FieldType::is_array(class_name)) {
     943     // The name refers to an array.  Parse the name.
     944     // dimension and object_key in FieldArrayInfo are assigned as a
     945     // side-effect of this call
     946     FieldArrayInfo fd;
     947     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
    1139   } );
    1140
    1141   return k();
    1142 }
    1143
    1144 #if INCLUDE_CDS
    1145 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
    1146                                              int number_of_entries) {
    1147   assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
    1148          "bad shared dictionary size.");
    1149   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
    1150 }
    1151
    1152
    1153 // If there is a shared dictionary, then find the entry for the
    1154 // given shared system class, if any.
    1155
    1156 Klass* SystemDictionary::find_shared_class(Symbol* class_name) {
    1157   if (shared_dictionary() != NULL) {
    1158     unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);

    1159
    1160     return shared_dictionary()->find_shared_class(d_hash, class_name);
    1161   } else {
    1162     return NULL;
    1163   }
    1164 }
    1165
    1166
    1167 // Load a class from the shared spaces (found through the shared system
    1168 // dictionary).  Force the superclass and all interfaces to be loaded.
    1169 // Update the class definition to include sibling classes and no
    1170 // subclasses (yet).  [Classes in the shared space are not part of the
    1171 // object hierarchy until loaded.]
    1172
    1173 instanceKlassHandle SystemDictionary::load_shared_class(
    1174                  Symbol* class_name, Handle class_loader, TRAPS) {
    1175   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
    1176   // Make sure we only return the boot class for the NULL classloader.
    1177   if (ik.not_null() &&
    1178       SharedClassUtil::is_shared_boot_class(ik()) && class_loader.is_null()) {
    1179     Handle protection_domain;
    1180     return load_shared_class(ik, class_loader, protection_domain, THREAD);
    1372  // If a parallelCapable class loader calls define_instance_class instead of
    1373  // find_or_define_instance_class to get here, we have a timing
    1374  // hole with systemDictionary updates and check_constraints
    1375  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
    1376     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
    1377          compute_loader_lock_object(class_loader_h, THREAD)),
    1378          "define called without lock");
    1379   }
    1380
    1381   // Check class-loading constraints. Throw exception if violation is detected.
    1382   // Grabs and releases SystemDictionary_lock
    1383   // The check_constraints/find_class call and update_dictionary sequence
    1384   // must be "atomic" for a specific class/classloader pair so we never
    1385   // define two different instanceKlasses for that class/classloader pair.
    1386   // Existing classloaders will call define_instance_class with the
    1387   // classloader lock held
    1388   // Parallel classloaders will call find_or_define_instance_class
    1389   // which will require a token to perform the define class
    1390   Symbol*  name_h = k->name();
    1391   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
    1392   check_constraints(d_hash, k, class_loader_h, true, CHECK);

    1393
    1394   // Register class just loaded with class loader (placed in Vector)
    1395   // Note we do this before updating the dictionary, as this can
    1396   // fail with an OutOfMemoryError (if it does, we will *not* put this
    1397   // class in the dictionary and will not update the class hierarchy).
    1398   // JVMTI FollowReferences needs to find the classes this way.
    1399   if (k->class_loader() != NULL) {
    1400     methodHandle m(THREAD, Universe::loader_addClass_method());
    1401     JavaValue result(T_VOID);
    1402     JavaCallArguments args(class_loader_h);
    1403     args.push_oop(Handle(THREAD, k->java_mirror()));
    1404     JavaCalls::call(&result, m, &args, CHECK);
    1405   }
    1406
    1407   // Add the new class. We need recompile lock during update of CHA.
    1408   {
    1409     unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);

    1410
    1411     MutexLocker mu_r(Compile_lock, THREAD);
    1412
    1413     // Add to class hierarchy, initialize vtables, and do possible
    1414     // deoptimizations.
    1415     add_to_hierarchy(k, CHECK); // No exception, but can block
    1416
    1417     // Add to systemDictionary - so other classes can see it.
    1418     // Grabs and releases SystemDictionary_lock
    1419     update_dictionary(d_hash, p_hash,
    1420                       k, class_loader_h, THREAD);
    1421   }
    1422   k->eager_initialize(THREAD);
    1423
    1424   // notify jvmti
    1425   if (JvmtiExport::should_post_class_load()) {
    1426       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
    1427       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
    1428
    1429   }
    1430
    1431 }
    1432
    1433 // Support parallel classloading
    1434 // All parallel class loaders, including bootstrap classloader
    1435 // lock a placeholder entry for this class/class_loader pair
    1436 // to allow parallel defines of different classes for this class loader
    1437 // With AllowParallelDefine flag==true, in case they do not synchronize around
    1438 // FindLoadedClass/DefineClass, calls, we check for parallel
    1439 // loading for them, wait if a defineClass is in progress
    1440 // and return the initial requestor's results
    1441 // This flag does not apply to the bootstrap classloader.
    1442 // With AllowParallelDefine flag==false, call through to define_instance_class
    1443 // which will throw LinkageError: duplicate class definition.
    1444 // False is the requested default.
    1445 // For better performance, the class loaders should synchronize
    1446 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
    1447 // potentially waste time reading and parsing the bytestream.
    1448 // Note: VM callers should ensure consistency of k/class_name,class_loader
    1449 instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {
    1450
    1451   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
    1452   Symbol*  name_h = k->name(); // passed in class_name may be null
    1453   ClassLoaderData* loader_data = class_loader_data(class_loader);
    1454
    1455   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);

    1456
    1457 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
    1458   unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);

    1459   PlaceholderEntry* probe;
    1460
    1461   {
    1462     MutexLocker mu(SystemDictionary_lock, THREAD);
    1463     int p_index = placeholders()->hash_to_index(p_hash);
    1464     // First check if class already defined
    1465     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
    1466       Klass* check = find_class(d_hash, name_h, loader_data);
    1467       if (check != NULL) {
    1468         return(instanceKlassHandle(THREAD, check));
    1469       }
    1470     }
    1471
    1472     // Acquire define token for this class/classloader
    1473     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
    1474     // Wait if another thread defining in parallel
    1475     // All threads wait - even those that will throw duplicate class: otherwise
    1476     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
    1477     // if other thread has not finished updating dictionary
    1478     while (probe->definer() != NULL) { // gznote: we're already holding SystemDictionary_lock, so why spin?
    1479       SystemDictionary_lock->wait();
    1480     }
    1481     // Only special cases allow parallel defines and can use other thread's results
    1482     // Other cases fall through, and may run into duplicate defines
    1483     // caught by finding an entry in the SystemDictionary
    1484     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
    1485         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
    1486         SystemDictionary_lock->notify_all();
    1487 #ifdef ASSERT
    1488         Klass* check = find_class(d_hash, name_h, loader_data);
    1489         assert(check != NULL, "definer missed recording success");
    1490 #endif
    1491         return(instanceKlassHandle(THREAD, probe->instance_klass()));
    1492     } else {
    1493       // This thread will define the class (even if earlier thread tried and had an error)
    1494       probe->set_definer(THREAD);
    1495     }
    1496   }
    1497
    1498   define_instance_class(k, THREAD);
    1499
    1500   Handle linkage_exception = Handle(); // null handle
    1501
    1502   // definer must notify any waiting threads
    1503   {
    1504     MutexLocker mu(SystemDictionary_lock, THREAD);
    1505     int p_index = placeholders()->hash_to_index(p_hash);
    1506     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
    1507     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
    1508     if (probe != NULL) {
    1509       if (HAS_PENDING_EXCEPTION) {
    1510         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
    1511         CLEAR_PENDING_EXCEPTION;
    1512       } else {
    1513         probe->set_instance_klass(k());
    1514       }
    1515       probe->set_definer(NULL);
    1516       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
    1517       SystemDictionary_lock->notify_all();
    1518     }
    1519   }
    1520
    1521   // Can't throw exception while holding lock due to rank ordering
    1522   if (linkage_exception() != NULL) {
    1523     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
    1524   }
    1525
    1543     return;
    1544   }
    1545
    1546   assert(!loader_lock.is_null(), "NULL lock object");
    1547
    1548   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
    1549       == ObjectSynchronizer::owner_other) {
    1550     // contention will likely happen, so increment the corresponding
    1551     // contention counter.
    1552     if (loader_lock() == _system_loader_lock_obj) {
    1553       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
    1554     } else {
    1555       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
    1556     }
    1557   }
    1558 }
    1559
    1560 // ----------------------------------------------------------------------------
    1561 // Lookup
    1562
    1563 Klass* SystemDictionary::find_class(unsigned int hash,
    1564                                       Symbol* class_name,
    1565                                       ClassLoaderData* loader_data) {
    1566   assert_locked_or_safepoint(SystemDictionary_lock);
    1567   Klass* k = dictionary()->find_class(hash, class_name, loader_data);

    1568   return k;
    1569 }
    1570
    1571
    1572 // Basic find on classes in the midst of being loaded
    1573 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
    1574                                            ClassLoaderData* loader_data) {
    1575   assert_locked_or_safepoint(SystemDictionary_lock);
    1576   unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
    1577   int p_index = placeholders()->hash_to_index(p_hash);
    1578   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
    1579 }
    1580
    1581
    1582 // Used for assertions and verification only
    1583 Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
    1584   #ifndef ASSERT
    1585   guarantee(VerifyBeforeGC      ||
    1586             VerifyDuringGC      ||
    1587             VerifyBeforeExit    ||
    1588             VerifyDuringStartup ||
    1589             VerifyAfterGC, "too expensive");
    1590   #endif
    1591   assert_locked_or_safepoint(SystemDictionary_lock);
    1592
    1593   // First look in the loaded class array
    1594   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
    1595   return find_class(d_hash, class_name, loader_data);

    1596 }
    1597
    1598
    1599 // Get the next class in the diictionary.
    1600 Klass* SystemDictionary::try_get_next_class() {
    1601   return dictionary()->try_get_next_class();
    1602 }
    1603
    1604
    1605 // ----------------------------------------------------------------------------
    1606 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
    1607 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
    1608 // before a new class is used.
    1609
    1610 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
    1611   assert(k.not_null(), "just checking");
    1612   assert_locked_or_safepoint(Compile_lock);
    1613
    1614   // Link into hierachy. Make sure the vtables are initialized before linking into
    1615   k->append_to_sibling_list();                    // add to superklass/sibling list
    1789
    1790   // if multiple threads calling this function, only one thread will load
    1791   // the class.  The other threads will find the loaded version once the
    1792   // class is loaded.
    1793   Klass* aos = _abstract_ownable_synchronizer_klass;
    1794   if (aos == NULL) {
    1795     Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
    1796     // Force a fence to prevent any read before the write completes
    1797     OrderAccess::fence();
    1798     _abstract_ownable_synchronizer_klass = k;
    1799   }
    1800 }
    1801
    1802 // ----------------------------------------------------------------------------
    1803 // Initialization
    1804
    1805 void SystemDictionary::initialize(TRAPS) {
    1806   // Allocate arrays
    1807   assert(dictionary() == NULL,
    1808          "SystemDictionary should only be initialized once");
    1809 #ifdef PRINT_HASHTABLES_CREATION
    1810   fprintf(stderr, ">>>>> Creating SystemDictionary Dictionary\n");
    1811 #endif
    1812   _sdgeneration        = 0;
    1813   _dictionary          = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));
    1814 #ifdef PRINT_HASHTABLES_CREATION
    1815   fprintf(stderr, ">>>>> Creating SystemDictionary PlaceholderTable\n");
    1816 #endif
    1817   _placeholders        = new PlaceholderTable(_nof_buckets);
    1818   _number_of_modifications = 0;
    1819 #ifdef PRINT_HASHTABLES_CREATION
    1820   fprintf(stderr, ">>>>> Creating SystemDictionary LoaderConstraintTable\n");
    1821 #endif
    1822   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
    1823 #ifdef PRINT_HASHTABLES_CREATION
    1824   fprintf(stderr, ">>>>> Creating SystemDictionary ResolutionErrorTable\n");
    1825 #endif
    1826   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
    1827 #ifdef PRINT_HASHTABLES_CREATION
    1828   fprintf(stderr, ">>>>> Creating SystemDictionary SymbolPropertyTable\n");
    1829 #endif
    1830   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
    1831
    1832   // Allocate private object used as system class loader lock
    1833   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
    1834   // Initialize basic classes
    1835   initialize_preloaded_classes(CHECK);
    1836 }
    1837
    1838 // Compact table of directions on the initialization of klasses:
    1839 static const short wk_init_info[] = {
    1840   #define WK_KLASS_INIT_INFO(name, symbol, option) \
    1841     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
    1842           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
    1843       | (int)SystemDictionary::option ),
    1844   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
    1845   #undef WK_KLASS_INIT_INFO
    1846   0
    1847 };
    1848
    1849 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
    1955
    1956 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
    1957 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
    1958 BasicType SystemDictionary::box_klass_type(Klass* k) {
    1959   assert(k != NULL, "");
    1960   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
    1961     if (_box_klasses[i] == k)
    1962       return (BasicType)i;
    1963   }
    1964   return T_OBJECT;
    1965 }
    1966
    1967 // Constraints on class loaders. The details of the algorithm can be
    1968 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
    1969 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
    1970 // that the system dictionary needs to maintain a set of contraints that
    1971 // must be satisfied by all classes in the dictionary.
    1972 // if defining is true, then LinkageError if already in systemDictionary
    1973 // if initiating loader, then ok if InstanceKlass matches existing entry
    1974
    1975 void SystemDictionary::check_constraints(unsigned int d_hash,
    1976                                          instanceKlassHandle k,
    1977                                          Handle class_loader, bool defining,
    1978                                          TRAPS) {
    1979   const char *linkage_error = NULL;
    1980   {
    1981     Symbol*  name  = k->name();
    1982     ClassLoaderData *loader_data = class_loader_data(class_loader);
    1983
    1984     MutexLocker mu(SystemDictionary_lock, THREAD);
    1985
    1986     Klass* check = find_class(d_hash, name, loader_data);
    1987     if (check != (Klass*)NULL) {
    1988       // if different InstanceKlass - duplicate class definition,
    1989       // else - ok, class loaded by a different thread in parallel,
    1990       // we should only have found it if it was done loading and ok to use
    1991       // system dictionary only holds instance classes, placeholders
    1992       // also holds array classes
    1993
    1994       assert(check->oop_is_instance(), "noninstance in systemdictionary");
    1995       if ((defining == true) || (k() != check)) {
    1996         linkage_error = "loader (instance of  %s): attempted  duplicate class "
    1997           "definition for name: \"%s\"";
    1998       } else {
    1999         return;
    2000       }
    2001     }
    2002
    2003 #ifdef ASSERT
    2004     Symbol* ph_check = find_placeholder(name, loader_data);
    2005     assert(ph_check == NULL || ph_check == name, "invalid symbol");
    2006 #endif
    2014   }
    2015
    2016   // Throw error now if needed (cannot throw while holding
    2017   // SystemDictionary_lock because of rank ordering)
    2018
    2019   if (linkage_error) {
    2020     ResourceMark rm(THREAD);
    2021     const char* class_loader_name = loader_name(class_loader());
    2022     char* type_name = k->name()->as_C_string();
    2023     size_t buflen = strlen(linkage_error) + strlen(class_loader_name) +
    2024       strlen(type_name);
    2025     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
    2026     jio_snprintf(buf, buflen, linkage_error, class_loader_name, type_name);
    2027     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
    2028   }
    2029 }
    2030
    2031
    2032 // Update system dictionary - done after check_constraint and add_to_hierachy
    2033 // have been called.
    2034 void SystemDictionary::update_dictionary(unsigned int d_hash,
    2035                                          unsigned int p_hash,
    2036                                          instanceKlassHandle k,
    2037                                          Handle class_loader,
    2038                                          TRAPS) {
    2039   // Compile_lock prevents systemDictionary updates during compilations
    2040   assert_locked_or_safepoint(Compile_lock);
    2041   Symbol*  name  = k->name();
    2042   ClassLoaderData *loader_data = class_loader_data(class_loader);
    2043
    2044   {
    2045   MutexLocker mu1(SystemDictionary_lock, THREAD);
    2046
    2047   // See whether biased locking is enabled and if so set it for this
    2048   // klass.
    2049   // Note that this must be done past the last potential blocking
    2050   // point / safepoint. We enable biased locking lazily using a
    2051   // VM_Operation to iterate the SystemDictionary and installing the
    2052   // biasable mark word into each InstanceKlass's prototype header.
    2053   // To avoid race conditions where we accidentally miss enabling the
    2054   // optimization for one class in the process of being added to the
    2055   // dictionary, we must not safepoint after the test of
    2056   // BiasedLocking::enabled().
    2057   if (UseBiasedLocking && BiasedLocking::enabled()) {
    2058     // Set biased locking bit for all loaded classes; it will be
    2059     // cleared if revocation occurs too often for this type
    2060     // NOTE that we must only do this when the class is initally
    2061     // defined, not each time it is referenced from a new class loader
    2062     if (k->class_loader() == class_loader()) {
    2063       k->set_prototype_header(markOopDesc::biased_locking_prototype());
    2064     }
    2065   }
    2066
    2067   // Make a new system dictionary entry.
    2068   Klass* sd_check = find_class(d_hash, name, loader_data);
    2069   if (sd_check == NULL) {
    2070     dictionary()->add_klass(name, loader_data, k);
    2071     notice_modification();
    2072   }
    2073 #ifdef ASSERT
    2074   sd_check = find_class(d_hash, name, loader_data);
    2075   assert (sd_check != NULL, "should have entry in system dictionary");
    2076   // Note: there may be a placeholder entry: for circularity testing
    2077   // or for parallel defines
    2078 #endif
    2079     SystemDictionary_lock->notify_all();
    2080   }
    2081 }
    2082
    2083
    2084 // Try to find a class name using the loader constraints.  The
    2085 // loader constraints might know about a class that isn't fully loaded
    2086 // yet and these will be ignored.
    2087 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
    2088                     Symbol* class_name, Handle class_loader, TRAPS) {
    2089
    2090   // First see if it has been loaded directly.
    2091   // Force the protection domain to be null.  (This removes protection checks.)
    2092   Handle no_protection_domain;
    2093   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
    2094                                               no_protection_domain, CHECK_NULL);
    2129                                              Thread* THREAD) {
    2130   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
    2131   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
    2132
    2133   Symbol* constraint_name = NULL;
    2134   if (!FieldType::is_array(class_name)) {
    2135     constraint_name = class_name;
    2136   } else {
    2137     // For array classes, their Klass*s are not kept in the
    2138     // constraint table. The element classes are.
    2139     FieldArrayInfo fd;
    2140     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
    2141     // primitive types always pass
    2142     if (t != T_OBJECT) {
    2143       return true;
    2144     } else {
    2145       constraint_name = fd.object_key();
    2146     }
    2147   }
    2148   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);

    2149   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);

    2150   {
    2151     MutexLocker mu_s(SystemDictionary_lock, THREAD);
    2152
    2153     // Better never do a GC while we're holding these oops
    2154     No_Safepoint_Verifier nosafepoint;
    2155
    2156     Klass* klass1 = find_class(d_hash1, constraint_name, loader_data1);
    2157     Klass* klass2 = find_class(d_hash2, constraint_name, loader_data2);
    2158     return constraints()->add_entry(constraint_name, klass1, class_loader1,
    2159                                     klass2, class_loader2);
    2160   }
    2161 }
    2162
    2163 // Add entry to resolution error table to record the error when the first
    2164 // attempt to resolve a reference to a class has failed.
    2165 void SystemDictionary::add_resolution_error(constantPoolHandle pool, int which, Symbol* error) {
    2166   unsigned int hash = resolution_errors()->compute_hash(pool, which);

    2167   {
    2168     MutexLocker ml(SystemDictionary_lock, Thread::current());
    2169     int index = resolution_errors()->hash_to_index(hash);
    2170     resolution_errors()->add_entry(index, hash, pool, which, error);
    2171   }
    2172 }
    2173
    2174 // Delete a resolution error for RedefineClasses for a constant pool is going away
    2175 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
    2176   resolution_errors()->delete_entry(pool);
    2177 }
    2178
    2179 // Lookup resolution error table. Returns error if found, otherwise NULL.
    2180 Symbol* SystemDictionary::find_resolution_error(constantPoolHandle pool, int which) {
    2181   unsigned int hash = resolution_errors()->compute_hash(pool, which);

    2182   {
    2183     MutexLocker ml(SystemDictionary_lock, Thread::current());
    2184     int index = resolution_errors()->hash_to_index(hash);
    2185     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
    2186     return (entry != NULL) ? entry->error() : (Symbol*)NULL;
    2187   }
    2188 }
    2189
    2190
    2191 // Signature constraints ensure that callers and callees agree about
    2192 // the meaning of type names in their signatures.  This routine is the
    2193 // intake for constraints.  It collects them from several places:
    2194 //
    2195 //  * LinkResolver::resolve_method (if check_access is true) requires
    2196 //    that the resolving class (the caller) and the defining class of
    2197 //    the resolved method (the callee) agree on each type in the
    2198 //    method's signature.
    2199 //
    2200 //  * LinkResolver::resolve_interface_method performs exactly the same
    2201 //    checks.
    2202 //
    2203 //  * LinkResolver::resolve_field requires that the constant pool
    2204 //    attempting to link to a field agree with the field's defining
    2274   int          index = invoke_method_table()->hash_to_index(hash);
    2275   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
    2276   methodHandle m;
    2277   if (spe == NULL || spe->method() == NULL) {
    2278     spe = NULL;
    2279     // Must create lots of stuff here, but outside of the SystemDictionary lock.
    2280     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_(empty));
    2281     if (!Arguments::is_interpreter_only()) {
    2282       // Generate a compiled form of the MH intrinsic.
    2283       AdapterHandlerLibrary::create_native_wrapper(m);
    2284       // Check if have the compiled code.
    2285       if (!m->has_compiled_code()) {
    2286         THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),
    2287                    "out of space in CodeCache for method handle intrinsic", empty);
    2288       }
    2289     }
    2290     // Now grab the lock.  We might have to throw away the new method,
    2291     // if a racing thread has managed to install one at the same time.
    2292     {
    2293       MutexLocker ml(SystemDictionary_lock, THREAD);
    2294       index = invoke_method_table()->hash_to_index(hash);
    2295       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
    2296       if (spe == NULL)
    2297         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
    2298       if (spe->method() == NULL)
    2299         spe->set_method(m());
    2300     }
    2301   }
    2302
    2303   assert(spe != NULL && spe->method() != NULL, "");
    2304   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
    2305          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
    2306          "MH intrinsic invariant");
    2307   return spe->method();
    2308 }
    2309
    2310 // Helper for unpacking the return value from linkMethod and linkCallSite.
    2311 static methodHandle unpack_method_and_appendix(Handle mname,
    2312                                                KlassHandle accessing_klass,
    2313                                                objArrayHandle appendix_box,
    2314                                                Handle* appendix_result,
    2451         LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
    2452       }
    2453     }
    2454   }
    2455   assert(arg == npts, "");
    2456
    2457   // call java.lang.invoke.MethodHandleNatives::findMethodType(Class rt, Class[] pts) -> MethodType
    2458   JavaCallArguments args(Handle(THREAD, rt()));
    2459   args.push_oop(pts());
    2460   JavaValue result(T_OBJECT);
    2461   JavaCalls::call_static(&result,
    2462                          SystemDictionary::MethodHandleNatives_klass(),
    2463                          vmSymbols::findMethodHandleType_name(),
    2464                          vmSymbols::findMethodHandleType_signature(),
    2465                          &args, CHECK_(empty));
    2466   Handle method_type(THREAD, (oop) result.get_jobject());
    2467
    2468   if (is_on_bcp) {
    2469     // We can cache this MethodType inside the JVM.
    2470     MutexLocker ml(SystemDictionary_lock, THREAD);
    2471     index = invoke_method_table()->hash_to_index(hash);
    2472     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
    2473     if (spe == NULL)
    2474       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
    2475     if (spe->method_type() == NULL) {
    2476       spe->set_method_type(method_type());
    2477     }
    2478   }
    2479
    2480   // report back to the caller with the MethodType
    2481   return method_type;
    2482 }
    2483
    2484 // Ask Java code to find or construct a method handle constant.
    2485 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
    2486                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
    2487                                                      KlassHandle callee,
    2488                                                      Symbol* name_sym,
    2489                                                      Symbol* signature,
    2490                                                      TRAPS) {
    2491   Handle empty;
    2607
    2608
    2609 void SystemDictionary::reverse() {
    2610   dictionary()->reverse();
    2611 }
    2612
    2613 int SystemDictionary::number_of_classes() {
    2614   return dictionary()->number_of_entries();
    2615 }
    2616
    2617
    2618 // ----------------------------------------------------------------------------
    2619 void SystemDictionary::print_shared(bool details) {
    2620   shared_dictionary()->print(details);
    2621 }
    2622
    2623 void SystemDictionary::print(bool details) {
    2624   dictionary()->print(details);
    2625
    2626   // Placeholders
    2627 //  GCMutexLocker mu(SystemDictionary_lock);
    2628 //  placeholders()->print();
    2629
    2630   // loader constraints - print under SD_lock
    2631 //  constraints()->print();
    2632 }
    2633
    2634
    2635 void SystemDictionary::verify() {
    2636   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
    2637   guarantee(constraints() != NULL,
    2638             "Verify of loader constraints failed");
    2639   guarantee(dictionary()->number_of_entries() >= 0 &&
    2640             placeholders()->number_of_entries() >= 0,
    2641             "Verify of system dictionary failed");
    2642
    2643   // Verify dictionary
    2644   dictionary()->verify();
    2645
    2646   GCMutexLocker mu(SystemDictionary_lock);
    2647   placeholders()->verify();
    2648
    2649   // Verify constraint table
    2650   guarantee(constraints() != NULL, "Verify of loader constraints failed");
    2651   constraints()->verify(dictionary(), placeholders());

src/share/vm/classfile/systemDictionary.cpp
Index Unified diffs Context diffs Sdiffs Wdiffs Patch New Old Previous File Next File