< prev index next >

src/share/vm/classfile/systemDictionary.cpp

Print this page




  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "aot/aotLoader.hpp"
  27 #include "classfile/classFileParser.hpp"
  28 #include "classfile/classFileStream.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/classLoaderData.inline.hpp"
  31 #include "classfile/classLoaderExt.hpp"
  32 #include "classfile/dictionary.hpp"
  33 #include "classfile/javaClasses.inline.hpp"
  34 #include "classfile/klassFactory.hpp"
  35 #include "classfile/loaderConstraints.hpp"
  36 #include "classfile/packageEntry.hpp"
  37 #include "classfile/placeholders.hpp"

  38 #include "classfile/resolutionErrors.hpp"
  39 #include "classfile/stringTable.hpp"
  40 #include "classfile/systemDictionary.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "code/codeCache.hpp"
  43 #include "compiler/compileBroker.hpp"
  44 #include "gc/shared/gcLocker.hpp"
  45 #include "gc/shared/gcTraceTime.inline.hpp"
  46 #include "interpreter/bytecodeStream.hpp"
  47 #include "interpreter/interpreter.hpp"
  48 #include "logging/log.hpp"
  49 #include "memory/filemap.hpp"
  50 #include "memory/oopFactory.hpp"
  51 #include "memory/resourceArea.hpp"
  52 #include "oops/instanceKlass.hpp"
  53 #include "oops/instanceRefKlass.hpp"
  54 #include "oops/klass.inline.hpp"
  55 #include "oops/methodData.hpp"
  56 #include "oops/objArrayKlass.hpp"
  57 #include "oops/objArrayOop.inline.hpp"


  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/mutexLocker.hpp"
  72 #include "runtime/orderAccess.inline.hpp"
  73 #include "runtime/signature.hpp"
  74 #include "services/classLoadingService.hpp"
  75 #include "services/threadService.hpp"
  76 #include "trace/traceMacros.hpp"
  77 #include "utilities/macros.hpp"
  78 #include "utilities/ticks.hpp"
  79 #if INCLUDE_CDS
  80 #include "classfile/sharedClassUtil.hpp"
  81 #include "classfile/systemDictionaryShared.hpp"
  82 #endif
  83 #if INCLUDE_JVMCI
  84 #include "jvmci/jvmciRuntime.hpp"
  85 #endif
  86 #if INCLUDE_TRACE
  87 #include "trace/tracing.hpp"
  88 #endif
  89 
  90 Dictionary*            SystemDictionary::_dictionary          = NULL;
  91 PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
  92 Dictionary*            SystemDictionary::_shared_dictionary   = NULL;
  93 LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
  94 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
  95 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
  96 
  97 
  98 int         SystemDictionary::_number_of_modifications = 0;
  99 int         SystemDictionary::_sdgeneration               = 0;
 100 const int   SystemDictionary::_primelist[_prime_array_size] = {1009,2017,4049,5051,10103,
 101               20201,40423,99991};
 102 
 103 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
 104 
 105 InstanceKlass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
 106                                                           =  { NULL /*, NULL...*/ };
 107 
 108 InstanceKlass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
 109 
 110 oop         SystemDictionary::_java_system_loader         =  NULL;
 111 
 112 bool        SystemDictionary::_has_loadClassInternal      =  false;
 113 bool        SystemDictionary::_has_checkPackageAccess     =  false;
 114 
 115 // lazily initialized klass variables
 116 InstanceKlass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
 117 




 118 
 119 // ----------------------------------------------------------------------------
 120 // Java-level SystemLoader
 121 
 122 oop SystemDictionary::java_system_loader() {
 123   return _java_system_loader;
 124 }
 125 
 126 void SystemDictionary::compute_java_system_loader(TRAPS) {
 127   Klass* system_klass = WK_KLASS(ClassLoader_klass);
 128   JavaValue result(T_OBJECT);
 129   JavaCalls::call_static(&result,
 130                          WK_KLASS(ClassLoader_klass),
 131                          vmSymbols::getSystemClassLoader_name(),
 132                          vmSymbols::void_classloader_signature(),
 133                          CHECK);
 134 
 135   _java_system_loader = (oop)result.get_jobject();
 136 
 137   CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)


 325 // you need to find_and_remove it before returning.
 326 // So be careful to not exit with a CHECK_ macro betweeen these calls.
 327 Klass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,
 328                                                  Symbol* class_name,
 329                                                  Handle class_loader,
 330                                                  Handle protection_domain,
 331                                                  bool is_superclass,
 332                                                  TRAPS) {
 333 #if INCLUDE_CDS
 334   if (DumpSharedSpaces) {
 335     // Special processing for CDS dump time.
 336     Klass* k = SystemDictionaryShared::dump_time_resolve_super_or_fail(child_name,
 337         class_name, class_loader, protection_domain, is_superclass, CHECK_NULL);
 338     if (k) {
 339       return k;
 340     }
 341   }
 342 #endif // INCLUDE_CDS
 343 
 344   // Double-check, if child class is already loaded, just return super-class,interface
 345   // Don't add a placedholder if already loaded, i.e. already in system dictionary

 346   // Make sure there's a placeholder for the *child* before resolving.
 347   // Used as a claim that this thread is currently loading superclass/classloader
 348   // Used here for ClassCircularity checks and also for heap verification
 349   // (every InstanceKlass in the heap needs to be in the system dictionary
 350   // or have a placeholder).
 351   // Must check ClassCircularity before checking if super class is already loaded
 352   //
 353   // We might not already have a placeholder if this child_name was
 354   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
 355   // the name of the class might not be known until the stream is actually
 356   // parsed.
 357   // Bugs 4643874, 4715493
 358   // compute_hash can have a safepoint
 359 
 360   ClassLoaderData* loader_data = class_loader_data(class_loader);
 361   unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);
 362   int d_index = dictionary()->hash_to_index(d_hash);
 363   unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);

 364   int p_index = placeholders()->hash_to_index(p_hash);
 365   // can't throw error holding a lock
 366   bool child_already_loaded = false;
 367   bool throw_circularity_error = false;
 368   {
 369     MutexLocker mu(SystemDictionary_lock, THREAD);
 370     Klass* childk = find_class(d_index, d_hash, child_name, loader_data);
 371     Klass* quicksuperk;
 372     // to support // loading: if child done loading, just return superclass
 373     // if class_name, & class_loader don't match:
 374     // if initial define, SD update will give LinkageError
 375     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
 376     // so we don't throw an exception here.
 377     // see: nsk redefclass014 & java.lang.instrument Instrument032
 378     if ((childk != NULL ) && (is_superclass) &&
 379        ((quicksuperk = childk->super()) != NULL) &&
 380 
 381          ((quicksuperk->name() == class_name) &&
 382             (quicksuperk->class_loader()  == class_loader()))) {
 383            return quicksuperk;
 384     } else {
 385       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
 386       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
 387           throw_circularity_error = true;
 388       }
 389     }
 390     if (!throw_circularity_error) {


 426 
 427 void SystemDictionary::validate_protection_domain(InstanceKlass* klass,
 428                                                   Handle class_loader,
 429                                                   Handle protection_domain,
 430                                                   TRAPS) {
 431   if(!has_checkPackageAccess()) return;
 432 
 433   // Now we have to call back to java to check if the initating class has access
 434   JavaValue result(T_VOID);
 435   if (log_is_enabled(Debug, protectiondomain)) {
 436     ResourceMark rm;
 437     // Print out trace information
 438     outputStream* log = Log(protectiondomain)::debug_stream();
 439     log->print_cr("Checking package access");
 440     log->print("class loader: "); class_loader()->print_value_on(log);
 441     log->print(" protection domain: "); protection_domain()->print_value_on(log);
 442     log->print(" loading: "); klass->print_value_on(log);
 443     log->cr();
 444   }
 445 





 446   InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass();
 447   JavaCalls::call_special(&result,
 448                          class_loader,
 449                          system_loader,
 450                          vmSymbols::checkPackageAccess_name(),
 451                          vmSymbols::class_protectiondomain_signature(),
 452                          Handle(THREAD, klass->java_mirror()),
 453                          protection_domain,
 454                          THREAD);
 455 
 456   if (HAS_PENDING_EXCEPTION) {
 457     log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
 458   } else {
 459    log_debug(protectiondomain)("granted");
 460   }
 461 
 462   if (HAS_PENDING_EXCEPTION) return;
 463 
 464   // If no exception has been thrown, we have validated the protection domain
 465   // Insert the protection domain of the initiating class into the set.
 466   {
 467     // We recalculate the entry here -- we've called out to java since
 468     // the last time it was calculated.
 469     ClassLoaderData* loader_data = class_loader_data(class_loader);

 470 
 471     Symbol*  kn = klass->name();
 472     unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);
 473     int d_index = dictionary()->hash_to_index(d_hash);
 474 
 475     MutexLocker mu(SystemDictionary_lock, THREAD);
 476     {
 477       // Note that we have an entry, and entries can be deleted only during GC,
 478       // so we cannot allow GC to occur while we're holding this entry.
 479 
 480       // We're using a NoSafepointVerifier to catch any place where we
 481       // might potentially do a GC at all.
 482       // Dictionary::do_unloading() asserts that classes in SD are only
 483       // unloaded at a safepoint. Anonymous classes are not in SD.
 484       NoSafepointVerifier nosafepoint;
 485       dictionary()->add_protection_domain(d_index, d_hash, klass, loader_data,
 486                                           protection_domain, THREAD);
 487     }
 488   }
 489 }
 490 
 491 // We only get here if this thread finds that another thread
 492 // has already claimed the placeholder token for the current operation,
 493 // but that other thread either never owned or gave up the
 494 // object lock
 495 // Waits on SystemDictionary_lock to indicate placeholder table updated
 496 // On return, caller must recheck placeholder table state
 497 //
 498 // We only get here if
 499 //  1) custom classLoader, i.e. not bootstrap classloader
 500 //  2) UnsyncloadClass not set
 501 //  3) custom classLoader has broken the class loader objectLock
 502 //     so another thread got here in parallel
 503 //
 504 // lockObject must be held.
 505 // Complicated dance due to lock ordering:
 506 // Must first release the classloader object lock to
 507 // allow initial definer to complete the class definition
 508 // and to avoid deadlock


 529 }
 530 
 531 // If the class in is in the placeholder table, class loading is in progress
 532 // For cases where the application changes threads to load classes, it
 533 // is critical to ClassCircularity detection that we try loading
 534 // the superclass on the same thread internally, so we do parallel
 535 // super class loading here.
 536 // This also is critical in cases where the original thread gets stalled
 537 // even in non-circularity situations.
 538 // Note: must call resolve_super_or_fail even if null super -
 539 // to force placeholder entry creation for this class for circularity detection
 540 // Caller must check for pending exception
 541 // Returns non-null Klass* if other thread has completed load
 542 // and we are done,
 543 // If return null Klass* and no pending exception, the caller must load the class
 544 InstanceKlass* SystemDictionary::handle_parallel_super_load(
 545     Symbol* name, Symbol* superclassname, Handle class_loader,
 546     Handle protection_domain, Handle lockObject, TRAPS) {
 547 
 548   ClassLoaderData* loader_data = class_loader_data(class_loader);
 549   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
 550   int d_index = dictionary()->hash_to_index(d_hash);
 551   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);

 552   int p_index = placeholders()->hash_to_index(p_hash);
 553 
 554   // superk is not used, resolve_super called for circularity check only
 555   // This code is reached in two situations. One if this thread
 556   // is loading the same class twice (e.g. ClassCircularity, or
 557   // java.lang.instrument).
 558   // The second is if another thread started the resolve_super first
 559   // and has not yet finished.
 560   // In both cases the original caller will clean up the placeholder
 561   // entry on error.
 562   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
 563                                                           superclassname,
 564                                                           class_loader,
 565                                                           protection_domain,
 566                                                           true,
 567                                                           CHECK_NULL);
 568 
 569   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
 570   // Serial class loaders and bootstrap classloader do wait for superclass loads
 571  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
 572     MutexLocker mu(SystemDictionary_lock, THREAD);
 573     // Check if classloading completed while we were loading superclass or waiting
 574     return find_class(d_index, d_hash, name, loader_data);
 575   }
 576 
 577   // must loop to both handle other placeholder updates
 578   // and spurious notifications
 579   bool super_load_in_progress = true;
 580   PlaceholderEntry* placeholder;
 581   while (super_load_in_progress) {
 582     MutexLocker mu(SystemDictionary_lock, THREAD);
 583     // Check if classloading completed while we were loading superclass or waiting
 584     InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
 585     if (check != NULL) {
 586       // Klass is already loaded, so just return it
 587       return check;
 588     } else {
 589       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 590       if (placeholder && placeholder->super_load_in_progress() ){
 591         // Before UnsyncloadClass:
 592         // We only get here if the application has released the
 593         // classloader lock when another thread was in the middle of loading a
 594         // superclass/superinterface for this class, and now
 595         // this thread is also trying to load this class.
 596         // To minimize surprises, the first thread that started to
 597         // load a class should be the one to complete the loading
 598         // with the classfile it initially expected.
 599         // This logic has the current thread wait once it has done
 600         // all the superclass/superinterface loading it can, until
 601         // the original thread completes the class loading or fails
 602         // If it completes we will use the resulting InstanceKlass
 603         // which we will find below in the systemDictionary.
 604         // We also get here for parallel bootstrap classloader


 644 }
 645 
 646 // Be careful when modifying this code: once you have run
 647 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
 648 // you need to find_and_remove it before returning.
 649 // So be careful to not exit with a CHECK_ macro betweeen these calls.
 650 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
 651                                                         Handle class_loader,
 652                                                         Handle protection_domain,
 653                                                         TRAPS) {
 654   assert(name != NULL && !FieldType::is_array(name) &&
 655          !FieldType::is_obj(name), "invalid class name");
 656 
 657   Ticks class_load_start_time = Ticks::now();
 658 
 659   HandleMark hm(THREAD);
 660 
 661   // Fix for 4474172; see evaluation for more details
 662   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 663   ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);

 664 
 665   // Do lookup to see if class already exist and the protection domain
 666   // has the right access
 667   // This call uses find which checks protection domain already matches
 668   // All subsequent calls use find_class, and set has_loaded_class so that
 669   // before we return a result we call out to java to check for valid protection domain
 670   // to allow returning the Klass* and add it to the pd_set if it is valid
 671   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
 672   int d_index = dictionary()->hash_to_index(d_hash);
 673   Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data,
 674                                       protection_domain, THREAD);
 675   if (probe != NULL) return probe;
 676 
 677 
 678   // Non-bootstrap class loaders will call out to class loader and
 679   // define via jvm/jni_DefineClass which will acquire the
 680   // class loader object lock to protect against multiple threads
 681   // defining the class in parallel by accident.
 682   // This lock must be acquired here so the waiter will find
 683   // any successful result in the SystemDictionary and not attempt
 684   // the define
 685   // ParallelCapable Classloaders and the bootstrap classloader,
 686   // or all classloaders with UnsyncloadClass do not acquire lock here
 687   bool DoObjectLock = true;
 688   if (is_parallelCapable(class_loader)) {
 689     DoObjectLock = false;
 690   }
 691 
 692   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
 693   int p_index = placeholders()->hash_to_index(p_hash);
 694 
 695   // Class is not in SystemDictionary so we have to do loading.
 696   // Make sure we are synchronized on the class loader before we proceed
 697   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 698   check_loader_lock_contention(lockObject, THREAD);
 699   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 700 
 701   // Check again (after locking) if class already exist in SystemDictionary
 702   bool class_has_been_loaded   = false;
 703   bool super_load_in_progress  = false;
 704   bool havesupername = false;
 705   InstanceKlass* k = NULL;
 706   PlaceholderEntry* placeholder;
 707   Symbol* superclassname = NULL;
 708 
 709   {
 710     MutexLocker mu(SystemDictionary_lock, THREAD);
 711     InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
 712     if (check != NULL) {
 713       // Klass is already loaded, so just return it
 714       class_has_been_loaded = true;
 715       k = check;
 716     } else {
 717       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 718       if (placeholder && placeholder->super_load_in_progress()) {
 719          super_load_in_progress = true;
 720          if (placeholder->havesupername() == true) {
 721            superclassname = placeholder->supername();
 722            havesupername = true;
 723          }
 724       }
 725     }
 726   }
 727 
 728   // If the class is in the placeholder table, class loading is in progress
 729   if (super_load_in_progress && havesupername==true) {
 730     k = handle_parallel_super_load(name,
 731                                    superclassname,


 775         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 776         if (oldprobe) {
 777           // only need check_seen_thread once, not on each loop
 778           // 6341374 java/lang/Instrument with -Xcomp
 779           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
 780             throw_circularity_error = true;
 781           } else {
 782             // case 1: traditional: should never see load_in_progress.
 783             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
 784 
 785               // case 4: bootstrap classloader: prevent futile classloading,
 786               // wait on first requestor
 787               if (class_loader.is_null()) {
 788                 SystemDictionary_lock->wait();
 789               } else {
 790               // case 2: traditional with broken classloader lock. wait on first
 791               // requestor.
 792                 double_lock_wait(lockObject, THREAD);
 793               }
 794               // Check if classloading completed while we were waiting
 795               InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
 796               if (check != NULL) {
 797                 // Klass is already loaded, so just return it
 798                 k = check;
 799                 class_has_been_loaded = true;
 800               }
 801               // check if other thread failed to load and cleaned up
 802               oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 803             }
 804           }
 805         }
 806       }
 807       // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
 808       // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
 809       // LOAD_INSTANCE in parallel
 810 
 811       if (!throw_circularity_error && !class_has_been_loaded) {
 812         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
 813         load_instance_added = true;
 814         // For class loaders that do not acquire the classloader object lock,
 815         // if they did not catch another thread holding LOAD_INSTANCE,
 816         // need a check analogous to the acquire ObjectLocker/find_class
 817         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
 818         // one final check if the load has already completed
 819         // class loaders holding the ObjectLock shouldn't find the class here
 820         InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
 821         if (check != NULL) {
 822         // Klass is already loaded, so return it after checking/adding protection domain
 823           k = check;
 824           class_has_been_loaded = true;
 825         }
 826       }
 827     }
 828 
 829     // must throw error outside of owning lock
 830     if (throw_circularity_error) {
 831       assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
 832       ResourceMark rm(THREAD);
 833       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
 834     }
 835 
 836     if (!class_has_been_loaded) {
 837 
 838       // Do actual loading
 839       k = load_instance_class(name, class_loader, THREAD);
 840 
 841       // For UnsyncloadClass only
 842       // If they got a linkageError, check if a parallel class load succeeded.
 843       // If it did, then for bytecode resolution the specification requires
 844       // that we return the same result we did for the other thread, i.e. the
 845       // successfully loaded InstanceKlass
 846       // Should not get here for classloaders that support parallelism
 847       // with the new cleaner mechanism, even with AllowParallelDefineClass
 848       // Bootstrap goes through here to allow for an extra guarantee check
 849       if (UnsyncloadClass || (class_loader.is_null())) {
 850         if (k == NULL && HAS_PENDING_EXCEPTION
 851           && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
 852           MutexLocker mu(SystemDictionary_lock, THREAD);
 853           InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
 854           if (check != NULL) {
 855             // Klass is already loaded, so just use it
 856             k = check;
 857             CLEAR_PENDING_EXCEPTION;
 858             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
 859           }
 860         }
 861       }
 862 
 863       // If everything was OK (no exceptions, no null return value), and
 864       // class_loader is NOT the defining loader, do a little more bookkeeping.
 865       if (!HAS_PENDING_EXCEPTION && k != NULL &&
 866         k->class_loader() != class_loader()) {
 867 
 868         check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
 869 
 870         // Need to check for a PENDING_EXCEPTION again; check_constraints
 871         // can throw and doesn't use the CHECK macro.
 872         if (!HAS_PENDING_EXCEPTION) {
 873           { // Grabbing the Compile_lock prevents systemDictionary updates
 874             // during compilations.
 875             MutexLocker mu(Compile_lock, THREAD);
 876             update_dictionary(d_index, d_hash, p_index, p_hash,
 877                               k, class_loader, THREAD);
 878           }
 879 
 880           if (JvmtiExport::should_post_class_load()) {
 881             Thread *thread = THREAD;
 882             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 883             JvmtiExport::post_class_load((JavaThread *) thread, k);
 884           }
 885         }
 886       }
 887     } // load_instance_class loop
 888 
 889     if (load_instance_added == true) {
 890       // clean up placeholder entries for LOAD_INSTANCE success or error
 891       // This brackets the SystemDictionary updates for both defining
 892       // and initiating loaders
 893       MutexLocker mu(SystemDictionary_lock, THREAD);
 894       placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
 895       SystemDictionary_lock->notify_all();
 896     }
 897   }
 898 
 899   if (HAS_PENDING_EXCEPTION || k == NULL) {
 900     return NULL;
 901   }
 902 
 903   post_class_load_event(class_load_start_time, k, loader_data);
 904 
 905 #ifdef ASSERT
 906   {
 907     ClassLoaderData* loader_data = k->class_loader_data();
 908     MutexLocker mu(SystemDictionary_lock, THREAD);
 909     Klass* kk = find_class(name, loader_data);
 910     assert(kk == k, "should be present in dictionary");
 911   }
 912 #endif
 913 
 914   // return if the protection domain in NULL
 915   if (protection_domain() == NULL) return k;
 916 
 917   // Check the protection domain has the right access
 918   {
 919     MutexLocker mu(SystemDictionary_lock, THREAD);
 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 NoSafepointVerifier 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     NoSafepointVerifier nosafepoint;
 927     if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
 928                                                  loader_data,
 929                                                  protection_domain)) {
 930       return k;
 931     }
 932   }
 933 
 934   // Verify protection domain. If it fails an exception is thrown
 935   validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
 936 
 937   return k;
 938 }
 939 
 940 
 941 // This routine does not lock the system dictionary.
 942 //
 943 // Since readers don't hold a lock, we must make sure that system
 944 // dictionary entries are only removed at a safepoint (when only one
 945 // thread is running), and are added to in a safe way (all links must
 946 // be updated in an MT-safe manner).
 947 //
 948 // Callers should be aware that an entry could be added just after
 949 // _dictionary->bucket(index) is read here, so the caller will not see
 950 // the new entry.
 951 
 952 Klass* SystemDictionary::find(Symbol* class_name,
 953                               Handle class_loader,
 954                               Handle protection_domain,
 955                               TRAPS) {
 956 
 957   // The result of this call should be consistent with the result
 958   // of the call to resolve_instance_class_or_null().
 959   // See evaluation 6790209 and 4474172 for more details.
 960   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 961   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
 962 
 963   if (loader_data == NULL) {
 964     // If the ClassLoaderData has not been setup,
 965     // then the class loader has no entries in the dictionary.
 966     return NULL;
 967   }
 968 
 969   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
 970   int d_index = dictionary()->hash_to_index(d_hash);
 971 
 972   {
 973     // Note that we have an entry, and entries can be deleted only during GC,
 974     // so we cannot allow GC to occur while we're holding this entry.
 975     // We're using a NoSafepointVerifier to catch any place where we
 976     // might potentially do a GC at all.
 977     // Dictionary::do_unloading() asserts that classes in SD are only
 978     // unloaded at a safepoint. Anonymous classes are not in SD.
 979     NoSafepointVerifier nosafepoint;
 980     return dictionary()->find(d_index, d_hash, class_name, loader_data,
 981                               protection_domain, THREAD);
 982   }
 983 }
 984 
 985 
 986 // Look for a loaded instance or array klass by name.  Do not do any loading.
 987 // return NULL in case of error.
 988 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
 989                                                       Handle class_loader,
 990                                                       Handle protection_domain,
 991                                                       TRAPS) {
 992   Klass* k = NULL;
 993   assert(class_name != NULL, "class name must be non NULL");
 994 
 995   if (FieldType::is_array(class_name)) {
 996     // The name refers to an array.  Parse the name.
 997     // dimension and object_key in FieldArrayInfo are assigned as a
 998     // side-effect of this call
 999     FieldArrayInfo fd;
1000     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
1001     if (t != T_OBJECT) {
1002       k = Universe::typeArrayKlassObj(t);


1016 // does not publish the classes via the SystemDictionary.
1017 // Handles unsafe_DefineAnonymousClass and redefineclasses
1018 // RedefinedClasses do not add to the class hierarchy
1019 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name,
1020                                               Handle class_loader,
1021                                               Handle protection_domain,
1022                                               ClassFileStream* st,
1023                                               const InstanceKlass* host_klass,
1024                                               GrowableArray<Handle>* cp_patches,
1025                                               TRAPS) {
1026 
1027   Ticks class_load_start_time = Ticks::now();
1028 
1029   ClassLoaderData* loader_data;
1030   if (host_klass != NULL) {
1031     // Create a new CLD for anonymous class, that uses the same class loader
1032     // as the host_klass
1033     guarantee(host_klass->class_loader() == class_loader(), "should be the same");
1034     guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
1035     loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);
1036     loader_data->record_dependency(host_klass, CHECK_NULL);
1037   } else {
1038     loader_data = ClassLoaderData::class_loader_data(class_loader());
1039   }
1040 
1041   assert(st != NULL, "invariant");
1042   assert(st->need_verify(), "invariant");
1043 
1044   // Parse stream and create a klass.
1045   // Note that we do this even though this klass might
1046   // already be present in the SystemDictionary, otherwise we would not
1047   // throw potential ClassFormatErrors.
1048 
1049   InstanceKlass* k = KlassFactory::create_from_stream(st,
1050                                                       class_name,
1051                                                       loader_data,
1052                                                       protection_domain,
1053                                                       host_klass,
1054                                                       cp_patches,
1055                                                       CHECK_NULL);
1056 
1057   if (host_klass != NULL && k != NULL) {
1058     // If it's anonymous, initialize it now, since nobody else will.
1059 
1060     {
1061       MutexLocker mu_r(Compile_lock, THREAD);
1062 
1063       // Add to class hierarchy, initialize vtables, and do possible
1064       // deoptimizations.
1065       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
1066 
1067       // But, do not add to system dictionary.
1068 
1069       // compiled code dependencies need to be validated anyway
1070       notice_modification();
1071     }
1072 
1073     // Rewrite and patch constant pool here.
1074     k->link_class(CHECK_NULL);
1075     if (cp_patches != NULL) {
1076       k->constants()->patch_resolved_references(cp_patches);
1077     }
1078     k->eager_initialize(CHECK_NULL);
1079 
1080     // notify jvmti
1081     if (JvmtiExport::should_post_class_load()) {
1082         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1083         JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1084     }
1085 
1086     post_class_load_event(class_load_start_time, k, loader_data);
1087   }


1170   if (HAS_PENDING_EXCEPTION) {
1171     assert(k != NULL, "Must have an instance klass here!");
1172     loader_data->add_to_deallocate_list(k);
1173     return NULL;
1174   }
1175 
1176   // Make sure we have an entry in the SystemDictionary on success
1177   debug_only( {
1178     MutexLocker mu(SystemDictionary_lock, THREAD);
1179 
1180     Klass* check = find_class(h_name, k->class_loader_data());
1181     assert(check == k, "should be present in the dictionary");
1182   } );
1183 
1184   return k;
1185 }
1186 
1187 #if INCLUDE_CDS
1188 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
1189                                              int number_of_entries) {
1190   assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
1191          "bad shared dictionary size.");
1192   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);

1193 }
1194 
1195 
1196 // If there is a shared dictionary, then find the entry for the
1197 // given shared system class, if any.
1198 
1199 InstanceKlass* SystemDictionary::find_shared_class(Symbol* class_name) {
1200   if (shared_dictionary() != NULL) {
1201     unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);
1202     int d_index = shared_dictionary()->hash_to_index(d_hash);
1203 
1204     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1205   } else {
1206     return NULL;
1207   }
1208 }
1209 
1210 
1211 // Load a class from the shared spaces (found through the shared system
1212 // dictionary).  Force the superclass and all interfaces to be loaded.
1213 // Update the class definition to include sibling classes and no
1214 // subclasses (yet).  [Classes in the shared space are not part of the
1215 // object hierarchy until loaded.]
1216 
1217 InstanceKlass* SystemDictionary::load_shared_class(
1218                  Symbol* class_name, Handle class_loader, TRAPS) {
1219   InstanceKlass* ik = find_shared_class(class_name);
1220   // Make sure we only return the boot class for the NULL classloader.
1221   if (ik != NULL &&


1607  // use placeholder token
1608  // If a parallelCapable class loader calls define_instance_class instead of
1609  // find_or_define_instance_class to get here, we have a timing
1610  // hole with systemDictionary updates and check_constraints
1611  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1612     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1613          compute_loader_lock_object(class_loader_h, THREAD)),
1614          "define called without lock");
1615   }
1616 
1617   // Check class-loading constraints. Throw exception if violation is detected.
1618   // Grabs and releases SystemDictionary_lock
1619   // The check_constraints/find_class call and update_dictionary sequence
1620   // must be "atomic" for a specific class/classloader pair so we never
1621   // define two different instanceKlasses for that class/classloader pair.
1622   // Existing classloaders will call define_instance_class with the
1623   // classloader lock held
1624   // Parallel classloaders will call find_or_define_instance_class
1625   // which will require a token to perform the define class
1626   Symbol*  name_h = k->name();
1627   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1628   int d_index = dictionary()->hash_to_index(d_hash);

1629   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1630 
1631   // Register class just loaded with class loader (placed in Vector)
1632   // Note we do this before updating the dictionary, as this can
1633   // fail with an OutOfMemoryError (if it does, we will *not* put this
1634   // class in the dictionary and will not update the class hierarchy).
1635   // JVMTI FollowReferences needs to find the classes this way.
1636   if (k->class_loader() != NULL) {
1637     methodHandle m(THREAD, Universe::loader_addClass_method());
1638     JavaValue result(T_VOID);
1639     JavaCallArguments args(class_loader_h);
1640     args.push_oop(Handle(THREAD, k->java_mirror()));
1641     JavaCalls::call(&result, m, &args, CHECK);
1642   }
1643 
1644   // Add the new class. We need recompile lock during update of CHA.
1645   {
1646     unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1647     int p_index = placeholders()->hash_to_index(p_hash);
1648 
1649     MutexLocker mu_r(Compile_lock, THREAD);
1650 
1651     // Add to class hierarchy, initialize vtables, and do possible
1652     // deoptimizations.
1653     add_to_hierarchy(k, CHECK); // No exception, but can block
1654 
1655     // Add to systemDictionary - so other classes can see it.
1656     // Grabs and releases SystemDictionary_lock
1657     update_dictionary(d_index, d_hash, p_index, p_hash,
1658                       k, class_loader_h, THREAD);
1659   }
1660   k->eager_initialize(THREAD);
1661 
1662   // notify jvmti
1663   if (JvmtiExport::should_post_class_load()) {
1664       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1665       JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1666 


1676 // FindLoadedClass/DefineClass, calls, we check for parallel
1677 // loading for them, wait if a defineClass is in progress
1678 // and return the initial requestor's results
1679 // This flag does not apply to the bootstrap classloader.
1680 // With AllowParallelDefine flag==false, call through to define_instance_class
1681 // which will throw LinkageError: duplicate class definition.
1682 // False is the requested default.
1683 // For better performance, the class loaders should synchronize
1684 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1685 // potentially waste time reading and parsing the bytestream.
1686 // Note: VM callers should ensure consistency of k/class_name,class_loader
1687 // Be careful when modifying this code: once you have run
1688 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1689 // you need to find_and_remove it before returning.
1690 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1691 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1692                                                                InstanceKlass* k, TRAPS) {
1693 
1694   Symbol*  name_h = k->name(); // passed in class_name may be null
1695   ClassLoaderData* loader_data = class_loader_data(class_loader);

1696 
1697   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1698   int d_index = dictionary()->hash_to_index(d_hash);
1699 
1700   // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1701   unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1702   int p_index = placeholders()->hash_to_index(p_hash);
1703   PlaceholderEntry* probe;
1704 
1705   {
1706     MutexLocker mu(SystemDictionary_lock, THREAD);
1707     // First check if class already defined
1708     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1709       InstanceKlass* check = find_class(d_index, d_hash, name_h, loader_data);
1710       if (check != NULL) {
1711         return check;
1712       }
1713     }
1714 
1715     // Acquire define token for this class/classloader
1716     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1717     // Wait if another thread defining in parallel
1718     // All threads wait - even those that will throw duplicate class: otherwise
1719     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1720     // if other thread has not finished updating dictionary
1721     while (probe->definer() != NULL) {
1722       SystemDictionary_lock->wait();
1723     }
1724     // Only special cases allow parallel defines and can use other thread's results
1725     // Other cases fall through, and may run into duplicate defines
1726     // caught by finding an entry in the SystemDictionary
1727     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1728         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1729         SystemDictionary_lock->notify_all();
1730 #ifdef ASSERT
1731         InstanceKlass* check = find_class(d_index, d_hash, name_h, loader_data);
1732         assert(check != NULL, "definer missed recording success");
1733 #endif
1734         return probe->instance_klass();
1735     } else {
1736       // This thread will define the class (even if earlier thread tried and had an error)
1737       probe->set_definer(THREAD);
1738     }
1739   }
1740 
1741   define_instance_class(k, THREAD);
1742 
1743   Handle linkage_exception = Handle(); // null handle
1744 
1745   // definer must notify any waiting threads
1746   {
1747     MutexLocker mu(SystemDictionary_lock, THREAD);
1748     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1749     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1750     if (probe != NULL) {
1751       if (HAS_PENDING_EXCEPTION) {
1752         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1753         CLEAR_PENDING_EXCEPTION;
1754       } else {
1755         probe->set_instance_klass(k);
1756       }
1757       probe->set_definer(NULL);
1758       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1759       SystemDictionary_lock->notify_all();
1760     }
1761   }
1762 
1763   // Can't throw exception while holding lock due to rank ordering
1764   if (linkage_exception() != NULL) {
1765     THROW_OOP_(linkage_exception(), NULL); // throws exception and returns
1766   }
1767 
1768   return k;
1769 }

1770 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1771   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1772   if (class_loader.is_null()) {
1773     return Handle(THREAD, _system_loader_lock_obj);
1774   } else {
1775     return class_loader;
1776   }
1777 }
1778 
1779 // This method is added to check how often we have to wait to grab loader
1780 // lock. The results are being recorded in the performance counters defined in
1781 // ClassLoader::_sync_systemLoaderLockContentionRate and
1782 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1783 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1784   if (!UsePerfData) {
1785     return;
1786   }
1787 
1788   assert(!loader_lock.is_null(), "NULL lock object");
1789 
1790   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1791       == ObjectSynchronizer::owner_other) {
1792     // contention will likely happen, so increment the corresponding
1793     // contention counter.
1794     if (loader_lock() == _system_loader_lock_obj) {
1795       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1796     } else {
1797       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1798     }
1799   }
1800 }
1801 
1802 // ----------------------------------------------------------------------------
1803 // Lookup
1804 
1805 InstanceKlass* SystemDictionary::find_class(int index, unsigned int hash,
1806                                             Symbol* class_name,
1807                                             ClassLoaderData* loader_data) {
1808   assert_locked_or_safepoint(SystemDictionary_lock);
1809   assert (index == dictionary()->index_for(class_name, loader_data),
1810           "incorrect index?");
1811 
1812   return dictionary()->find_class(index, hash, class_name, loader_data);
1813 }
1814 
1815 
1816 // Basic find on classes in the midst of being loaded
1817 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1818                                            ClassLoaderData* loader_data) {
1819   assert_locked_or_safepoint(SystemDictionary_lock);
1820   unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
1821   int p_index = placeholders()->hash_to_index(p_hash);
1822   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1823 }
1824 
1825 
1826 // Used for assertions and verification only


1827 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {

1828   #ifndef ASSERT
1829   guarantee(VerifyBeforeGC      ||
1830             VerifyDuringGC      ||
1831             VerifyBeforeExit    ||
1832             VerifyDuringStartup ||
1833             VerifyAfterGC, "too expensive");
1834   #endif
1835   assert_locked_or_safepoint(SystemDictionary_lock);
1836 
1837   // First look in the loaded class array
1838   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
1839   int d_index = dictionary()->hash_to_index(d_hash);
1840   return find_class(d_index, d_hash, class_name, loader_data);
1841 }
1842 
1843 
1844 // Get the next class in the dictionary.
1845 Klass* SystemDictionary::try_get_next_class() {
1846   return dictionary()->try_get_next_class();
1847 }
1848 
1849 
1850 // ----------------------------------------------------------------------------
1851 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1852 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1853 // before a new class is used.
1854 
1855 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) {
1856   assert(k != NULL, "just checking");
1857   assert_locked_or_safepoint(Compile_lock);
1858 
1859   // Link into hierachy. Make sure the vtables are initialized before linking into
1860   k->append_to_sibling_list();                    // add to superklass/sibling list
1861   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1862   k->set_init_state(InstanceKlass::loaded);
1863   // Now flush all code that depended on old class hierarchy.
1864   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1865   // Also, first reinitialize vtable because it may have gotten out of synch
1866   // while the new class wasn't connected to the class hierarchy.
1867   CodeCache::flush_dependents_on(k);
1868 }
1869 
1870 // ----------------------------------------------------------------------------
1871 // GC support
1872 
1873 // Following roots during mark-sweep is separated in two phases.
1874 //
1875 // The first phase follows preloaded classes and all other system
1876 // classes, since these will never get unloaded anyway.
1877 //
1878 // The second phase removes (unloads) unreachable classes from the
1879 // system dictionary and follows the remaining classes' contents.
1880 
1881 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1882   roots_oops_do(blk, NULL);
1883 }
1884 
1885 // Calculate a "good" systemdictionary size based
1886 // on predicted or current loaded classes count
1887 int SystemDictionary::calculate_systemdictionary_size(int classcount) {
1888   int newsize = _old_default_sdsize;
1889   if ((classcount > 0)  && !DumpSharedSpaces) {
1890     int desiredsize = classcount/_average_depth_goal;
1891     for (newsize = _primelist[_sdgeneration]; _sdgeneration < _prime_array_size -1;
1892          newsize = _primelist[++_sdgeneration]) {
1893       if (desiredsize <=  newsize) {
1894         break;
1895       }
1896     }
1897   }
1898   return newsize;
1899 }
1900 
1901 #ifdef ASSERT
1902 class VerifySDReachableAndLiveClosure : public OopClosure {
1903 private:
1904   BoolObjectClosure* _is_alive;
1905 
1906   template <class T> void do_oop_work(T* p) {
1907     oop obj = oopDesc::load_decode_heap_oop(p);
1908     guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live");
1909   }
1910 
1911 public:
1912   VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }
1913 
1914   virtual void do_oop(oop* p)       { do_oop_work(p); }
1915   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
1916 };
1917 #endif
1918 
1919 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1920 // Note: anonymous classes are not in the SD.
1921 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive,
1922                                     GCTimer* gc_timer,
1923                                     bool do_cleaning) {
1924 
1925 
1926   bool unloading_occurred;
1927   {
1928     GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1929 
1930     // First, mark for unload all ClassLoaderData referencing a dead class loader.
1931     unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive,
1932                                                             do_cleaning);
1933   }
1934 
1935   if (unloading_occurred) {
1936     GCTraceTime(Debug, gc, phases) t("Dictionary", gc_timer);
1937     dictionary()->do_unloading();
1938     constraints()->purge_loader_constraints();
1939     resolution_errors()->purge_resolution_errors();
1940   }
1941 
1942   {
1943     GCTraceTime(Debug, gc, phases) t("ProtectionDomainCacheTable", gc_timer);
1944     // Oops referenced by the system dictionary may get unreachable independently
1945     // of the class loader (eg. cached protection domain oops). So we need to
1946     // explicitly unlink them here instead of in Dictionary::do_unloading.
1947     dictionary()->unlink(is_alive);

1948 #ifdef ASSERT
1949     VerifySDReachableAndLiveClosure cl(is_alive);
1950     dictionary()->oops_do(&cl);
1951 #endif
1952   }
1953 
1954   if (do_cleaning) {
1955     GCTraceTime(Debug, gc, phases) t("ResolvedMethodTable", gc_timer);
1956     ResolvedMethodTable::unlink(is_alive);
1957   }
1958 
1959   return unloading_occurred;
1960 }
1961 
1962 void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
1963   strong->do_oop(&_java_system_loader);
1964   strong->do_oop(&_system_loader_lock_obj);
1965   CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
1966 
1967   // Adjust dictionary
1968   dictionary()->roots_oops_do(strong, weak);








1969 
1970   // Visit extra methods
1971   invoke_method_table()->oops_do(strong);
1972 
1973   if (weak != NULL) {
1974     ResolvedMethodTable::oops_do(weak);
1975   }
1976 }
1977 
1978 void SystemDictionary::oops_do(OopClosure* f) {
1979   f->do_oop(&_java_system_loader);
1980   f->do_oop(&_system_loader_lock_obj);
1981   CDS_ONLY(SystemDictionaryShared::oops_do(f);)
1982 
1983   // Adjust dictionary
1984   dictionary()->oops_do(f);

1985 
1986   // Visit extra methods
1987   invoke_method_table()->oops_do(f);
1988 
1989   ResolvedMethodTable::oops_do(f);
1990 }
1991 
1992 // Just the classes from defining class loaders
1993 // Don't iterate over placeholders
1994 void SystemDictionary::classes_do(void f(Klass*)) {
1995   dictionary()->classes_do(f);
1996 }
1997 
1998 // Added for initialize_itable_for_klass
1999 //   Just the classes from defining class loaders
2000 // Don't iterate over placeholders
2001 void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {
2002   dictionary()->classes_do(f, CHECK);
2003 }
2004 
2005 //   All classes, and their class loaders
2006 // Don't iterate over placeholders
2007 void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) {
2008   dictionary()->classes_do(f);
2009 }
2010 
2011 void SystemDictionary::methods_do(void f(Method*)) {
2012   // Walk methods in loaded classes
2013   ClassLoaderDataGraph::methods_do(f);
2014   // Walk method handle intrinsics
2015   invoke_method_table()->methods_do(f);
2016 }
2017 
2018 void SystemDictionary::remove_classes_in_error_state() {
2019   dictionary()->remove_classes_in_error_state();
2020 }
2021 
2022 // ----------------------------------------------------------------------------
2023 // Lazily load klasses
2024 
2025 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
2026   // if multiple threads calling this function, only one thread will load
2027   // the class.  The other threads will find the loaded version once the
2028   // class is loaded.
2029   Klass* aos = _abstract_ownable_synchronizer_klass;
2030   if (aos == NULL) {
2031     Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
2032     // Force a fence to prevent any read before the write completes
2033     OrderAccess::fence();
2034     _abstract_ownable_synchronizer_klass = InstanceKlass::cast(k);
2035   }
2036 }
2037 
2038 // ----------------------------------------------------------------------------
2039 // Initialization
2040 
2041 void SystemDictionary::initialize(TRAPS) {
2042   // Allocate arrays
2043   assert(dictionary() == NULL,
2044          "SystemDictionary should only be initialized once");
2045   _sdgeneration        = 0;
2046   _dictionary          = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));
2047   _placeholders        = new PlaceholderTable(_nof_buckets);
2048   _number_of_modifications = 0;
2049   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
2050   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
2051   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);

2052 
2053   // Allocate private object used as system class loader lock
2054   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
2055   // Initialize basic classes
2056   initialize_preloaded_classes(CHECK);
2057 }
2058 
2059 // Compact table of directions on the initialization of klasses:
2060 static const short wk_init_info[] = {
2061   #define WK_KLASS_INIT_INFO(name, symbol, option) \
2062     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
2063           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
2064       | (int)SystemDictionary::option ),
2065   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
2066   #undef WK_KLASS_INIT_INFO
2067   0
2068 };
2069 
2070 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
2071   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");


2182   { // Compute whether we should use checkPackageAccess or NOT
2183     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
2184     _has_checkPackageAccess = (method != NULL);
2185   }
2186 }
2187 
2188 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
2189 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
2190 BasicType SystemDictionary::box_klass_type(Klass* k) {
2191   assert(k != NULL, "");
2192   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
2193     if (_box_klasses[i] == k)
2194       return (BasicType)i;
2195   }
2196   return T_OBJECT;
2197 }
2198 
2199 // Constraints on class loaders. The details of the algorithm can be
2200 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2201 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
2202 // that the system dictionary needs to maintain a set of contraints that
2203 // must be satisfied by all classes in the dictionary.
2204 // if defining is true, then LinkageError if already in systemDictionary
2205 // if initiating loader, then ok if InstanceKlass matches existing entry
2206 
2207 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
2208                                          InstanceKlass* k,
2209                                          Handle class_loader, bool defining,
2210                                          TRAPS) {
2211   const char *linkage_error1 = NULL;
2212   const char *linkage_error2 = NULL;
2213   {
2214     Symbol*  name  = k->name();
2215     ClassLoaderData *loader_data = class_loader_data(class_loader);
2216 
2217     MutexLocker mu(SystemDictionary_lock, THREAD);
2218 
2219     InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
2220     if (check != NULL) {
2221       // if different InstanceKlass - duplicate class definition,
2222       // else - ok, class loaded by a different thread in parallel,
2223       // we should only have found it if it was done loading and ok to use
2224       // system dictionary only holds instance classes, placeholders
2225       // also holds array classes
2226 
2227       assert(check->is_instance_klass(), "noninstance in systemdictionary");
2228       if ((defining == true) || (k != check)) {
2229         linkage_error1 = "loader (instance of ";
2230         linkage_error2 = "): attempted duplicate class definition for name: \"";
2231       } else {
2232         return;
2233       }
2234     }
2235 
2236 #ifdef ASSERT
2237     Symbol* ph_check = find_placeholder(name, loader_data);
2238     assert(ph_check == NULL || ph_check == name, "invalid symbol");
2239 #endif
2240 
2241     if (linkage_error1 == NULL) {
2242       if (constraints()->check_or_update(k, class_loader, name) == false) {
2243         linkage_error1 = "loader constraint violation: loader (instance of ";
2244         linkage_error2 = ") previously initiated loading for a different type with name \"";
2245       }
2246     }
2247   }
2248 
2249   // Throw error now if needed (cannot throw while holding
2250   // SystemDictionary_lock because of rank ordering)
2251 
2252   if (linkage_error1) {
2253     ResourceMark rm(THREAD);
2254     const char* class_loader_name = loader_name(class_loader());
2255     char* type_name = k->name()->as_C_string();
2256     size_t buflen = strlen(linkage_error1) + strlen(class_loader_name) +
2257       strlen(linkage_error2) + strlen(type_name) + 2; // +2 for '"' and null byte.
2258     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
2259     jio_snprintf(buf, buflen, "%s%s%s%s\"", linkage_error1, class_loader_name, linkage_error2, type_name);
2260     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
2261   }
2262 }
2263 
2264 
2265 // Update system dictionary - done after check_constraint and add_to_hierachy
2266 // have been called.
2267 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
2268                                          int p_index, unsigned int p_hash,
2269                                          InstanceKlass* k,
2270                                          Handle class_loader,
2271                                          TRAPS) {
2272   // Compile_lock prevents systemDictionary updates during compilations
2273   assert_locked_or_safepoint(Compile_lock);
2274   Symbol*  name  = k->name();
2275   ClassLoaderData *loader_data = class_loader_data(class_loader);
2276 
2277   {
2278   MutexLocker mu1(SystemDictionary_lock, THREAD);
2279 
2280   // See whether biased locking is enabled and if so set it for this
2281   // klass.
2282   // Note that this must be done past the last potential blocking
2283   // point / safepoint. We enable biased locking lazily using a
2284   // VM_Operation to iterate the SystemDictionary and installing the
2285   // biasable mark word into each InstanceKlass's prototype header.
2286   // To avoid race conditions where we accidentally miss enabling the
2287   // optimization for one class in the process of being added to the
2288   // dictionary, we must not safepoint after the test of
2289   // BiasedLocking::enabled().
2290   if (UseBiasedLocking && BiasedLocking::enabled()) {
2291     // Set biased locking bit for all loaded classes; it will be
2292     // cleared if revocation occurs too often for this type
2293     // NOTE that we must only do this when the class is initally
2294     // defined, not each time it is referenced from a new class loader
2295     if (k->class_loader() == class_loader()) {
2296       k->set_prototype_header(markOopDesc::biased_locking_prototype());
2297     }
2298   }
2299 
2300   // Make a new system dictionary entry.
2301   InstanceKlass* sd_check = find_class(d_index, d_hash, name, loader_data);

2302   if (sd_check == NULL) {
2303     dictionary()->add_klass(name, loader_data, k);
2304     notice_modification();
2305   }
2306 #ifdef ASSERT
2307   sd_check = find_class(d_index, d_hash, name, loader_data);
2308   assert (sd_check != NULL, "should have entry in system dictionary");
2309   // Note: there may be a placeholder entry: for circularity testing
2310   // or for parallel defines
2311 #endif
2312     SystemDictionary_lock->notify_all();
2313   }
2314 }
2315 
2316 
2317 // Try to find a class name using the loader constraints.  The
2318 // loader constraints might know about a class that isn't fully loaded
2319 // yet and these will be ignored.
2320 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2321                     Symbol* class_name, Handle class_loader, TRAPS) {
2322 
2323   // First see if it has been loaded directly.
2324   // Force the protection domain to be null.  (This removes protection checks.)
2325   Handle no_protection_domain;
2326   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2327                                               no_protection_domain, CHECK_NULL);
2328   if (klass != NULL)
2329     return klass;
2330 
2331   // Now look to see if it has been loaded elsewhere, and is subject to


2361                                              Handle class_loader2,
2362                                              Thread* THREAD) {
2363   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2364   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2365 
2366   Symbol* constraint_name = NULL;
2367   if (!FieldType::is_array(class_name)) {
2368     constraint_name = class_name;
2369   } else {
2370     // For array classes, their Klass*s are not kept in the
2371     // constraint table. The element classes are.
2372     FieldArrayInfo fd;
2373     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2374     // primitive types always pass
2375     if (t != T_OBJECT) {
2376       return true;
2377     } else {
2378       constraint_name = fd.object_key();
2379     }
2380   }
2381   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
2382   int d_index1 = dictionary()->hash_to_index(d_hash1);
2383 
2384   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
2385   int d_index2 = dictionary()->hash_to_index(d_hash2);






2386   {
2387   MutexLocker mu_s(SystemDictionary_lock, THREAD);
2388 
2389   // Better never do a GC while we're holding these oops
2390   NoSafepointVerifier nosafepoint;
2391 
2392   InstanceKlass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
2393   InstanceKlass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
2394   return constraints()->add_entry(constraint_name, klass1, class_loader1,
2395                                   klass2, class_loader2);
2396   }
2397 }
2398 
2399 // Add entry to resolution error table to record the error when the first
2400 // attempt to resolve a reference to a class has failed.
2401 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2402                                             Symbol* error, Symbol* message) {
2403   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2404   int index = resolution_errors()->hash_to_index(hash);
2405   {
2406     MutexLocker ml(SystemDictionary_lock, Thread::current());
2407     resolution_errors()->add_entry(index, hash, pool, which, error, message);
2408   }
2409 }
2410 
2411 // Delete a resolution error for RedefineClasses for a constant pool is going away
2412 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2413   resolution_errors()->delete_entry(pool);


2825 
2826   // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2827   JavaCallArguments args;
2828   args.push_oop(Handle(THREAD, caller->java_mirror()));
2829   args.push_oop(bsm);
2830   args.push_oop(method_name);
2831   args.push_oop(method_type);
2832   args.push_oop(info);
2833   args.push_oop(appendix_box);
2834   JavaValue result(T_OBJECT);
2835   JavaCalls::call_static(&result,
2836                          SystemDictionary::MethodHandleNatives_klass(),
2837                          vmSymbols::linkCallSite_name(),
2838                          vmSymbols::linkCallSite_signature(),
2839                          &args, CHECK_(empty));
2840   Handle mname(THREAD, (oop) result.get_jobject());
2841   (*method_type_result) = method_type;
2842   return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);
2843 }
2844 
2845 // Since the identity hash code for symbols changes when the symbols are
2846 // moved from the regular perm gen (hash in the mark word) to the shared
2847 // spaces (hash is the address), the classes loaded into the dictionary
2848 // may be in the wrong buckets.


2849 
2850 void SystemDictionary::reorder_dictionary() {
2851   dictionary()->reorder_dictionary();
2852 }
2853 
2854 
2855 void SystemDictionary::copy_buckets(char** top, char* end) {
2856   dictionary()->copy_buckets(top, end);
2857 }
2858 
2859 
2860 void SystemDictionary::copy_table(char** top, char* end) {
2861   dictionary()->copy_table(top, end);
2862 }
2863 
2864 int SystemDictionary::number_of_classes() {
2865   return dictionary()->number_of_entries();
2866 }
2867 
2868 
2869 // ----------------------------------------------------------------------------
2870 void SystemDictionary::print_shared(bool details) {
2871   shared_dictionary()->print(details);
2872 }
2873 
2874 void SystemDictionary::print(bool details) {
2875   dictionary()->print(details);



2876 
2877   // Placeholders
2878   GCMutexLocker mu(SystemDictionary_lock);




2879   placeholders()->print();

2880 
2881   // loader constraints - print under SD_lock
2882   constraints()->print();




2883 }
2884 
2885 
2886 void SystemDictionary::verify() {
2887   guarantee(dictionary() != NULL, "Verify of system dictionary failed");
2888   guarantee(constraints() != NULL,
2889             "Verify of loader constraints failed");
2890   guarantee(dictionary()->number_of_entries() >= 0 &&
2891             placeholders()->number_of_entries() >= 0,
2892             "Verify of system dictionary failed");
2893 
2894   // Verify dictionary
2895   dictionary()->verify();
2896 
2897   GCMutexLocker mu(SystemDictionary_lock);
2898   placeholders()->verify();
2899 
2900   // Verify constraint table
2901   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2902   constraints()->verify(dictionary(), placeholders());


2903 }
2904 
2905 // caller needs ResourceMark
2906 const char* SystemDictionary::loader_name(const oop loader) {
2907   return ((loader) == NULL ? "<bootloader>" :
2908           InstanceKlass::cast((loader)->klass())->name()->as_C_string());
2909 }
2910 
2911 // caller needs ResourceMark
2912 const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) {
2913   return (loader_data->class_loader() == NULL ? "<bootloader>" :
2914           SystemDictionary::loader_name(loader_data->class_loader()));
2915 }


  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "aot/aotLoader.hpp"
  27 #include "classfile/classFileParser.hpp"
  28 #include "classfile/classFileStream.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/classLoaderData.inline.hpp"
  31 #include "classfile/classLoaderExt.hpp"
  32 #include "classfile/dictionary.hpp"
  33 #include "classfile/javaClasses.inline.hpp"
  34 #include "classfile/klassFactory.hpp"
  35 #include "classfile/loaderConstraints.hpp"
  36 #include "classfile/packageEntry.hpp"
  37 #include "classfile/placeholders.hpp"
  38 #include "classfile/protectionDomainCache.hpp"
  39 #include "classfile/resolutionErrors.hpp"
  40 #include "classfile/stringTable.hpp"
  41 #include "classfile/systemDictionary.hpp"
  42 #include "classfile/vmSymbols.hpp"
  43 #include "code/codeCache.hpp"
  44 #include "compiler/compileBroker.hpp"
  45 #include "gc/shared/gcLocker.hpp"
  46 #include "gc/shared/gcTraceTime.inline.hpp"
  47 #include "interpreter/bytecodeStream.hpp"
  48 #include "interpreter/interpreter.hpp"
  49 #include "logging/log.hpp"
  50 #include "memory/filemap.hpp"
  51 #include "memory/oopFactory.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "oops/instanceKlass.hpp"
  54 #include "oops/instanceRefKlass.hpp"
  55 #include "oops/klass.inline.hpp"
  56 #include "oops/methodData.hpp"
  57 #include "oops/objArrayKlass.hpp"
  58 #include "oops/objArrayOop.inline.hpp"


  71 #include "runtime/javaCalls.hpp"
  72 #include "runtime/mutexLocker.hpp"
  73 #include "runtime/orderAccess.inline.hpp"
  74 #include "runtime/signature.hpp"
  75 #include "services/classLoadingService.hpp"
  76 #include "services/threadService.hpp"
  77 #include "trace/traceMacros.hpp"
  78 #include "utilities/macros.hpp"
  79 #include "utilities/ticks.hpp"
  80 #if INCLUDE_CDS
  81 #include "classfile/sharedClassUtil.hpp"
  82 #include "classfile/systemDictionaryShared.hpp"
  83 #endif
  84 #if INCLUDE_JVMCI
  85 #include "jvmci/jvmciRuntime.hpp"
  86 #endif
  87 #if INCLUDE_TRACE
  88 #include "trace/tracing.hpp"
  89 #endif
  90 

  91 PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
  92 Dictionary*            SystemDictionary::_shared_dictionary   = NULL;
  93 LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
  94 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
  95 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
  96 ProtectionDomainCacheTable*   SystemDictionary::_pd_cache_table = NULL;
  97 
  98 int         SystemDictionary::_number_of_modifications = 0;




  99 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
 100 
 101 InstanceKlass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
 102                                                           =  { NULL /*, NULL...*/ };
 103 
 104 InstanceKlass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
 105 
 106 oop         SystemDictionary::_java_system_loader         =  NULL;
 107 
 108 bool        SystemDictionary::_has_loadClassInternal      =  false;
 109 bool        SystemDictionary::_has_checkPackageAccess     =  false;
 110 
 111 // lazily initialized klass variables
 112 InstanceKlass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
 113 
 114 // Default ProtectionDomainCacheSize value
 115 
 116 const int defaultProtectionDomainCacheSize = 1009;
 117 
 118 
 119 // ----------------------------------------------------------------------------
 120 // Java-level SystemLoader
 121 
 122 oop SystemDictionary::java_system_loader() {
 123   return _java_system_loader;
 124 }
 125 
 126 void SystemDictionary::compute_java_system_loader(TRAPS) {
 127   Klass* system_klass = WK_KLASS(ClassLoader_klass);
 128   JavaValue result(T_OBJECT);
 129   JavaCalls::call_static(&result,
 130                          WK_KLASS(ClassLoader_klass),
 131                          vmSymbols::getSystemClassLoader_name(),
 132                          vmSymbols::void_classloader_signature(),
 133                          CHECK);
 134 
 135   _java_system_loader = (oop)result.get_jobject();
 136 
 137   CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)


 325 // you need to find_and_remove it before returning.
 326 // So be careful to not exit with a CHECK_ macro betweeen these calls.
 327 Klass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,
 328                                                  Symbol* class_name,
 329                                                  Handle class_loader,
 330                                                  Handle protection_domain,
 331                                                  bool is_superclass,
 332                                                  TRAPS) {
 333 #if INCLUDE_CDS
 334   if (DumpSharedSpaces) {
 335     // Special processing for CDS dump time.
 336     Klass* k = SystemDictionaryShared::dump_time_resolve_super_or_fail(child_name,
 337         class_name, class_loader, protection_domain, is_superclass, CHECK_NULL);
 338     if (k) {
 339       return k;
 340     }
 341   }
 342 #endif // INCLUDE_CDS
 343 
 344   // Double-check, if child class is already loaded, just return super-class,interface
 345   // Don't add a placedholder if already loaded, i.e. already in appropriate class loader
 346   // dictionary.
 347   // Make sure there's a placeholder for the *child* before resolving.
 348   // Used as a claim that this thread is currently loading superclass/classloader
 349   // Used here for ClassCircularity checks and also for heap verification
 350   // (every InstanceKlass needs to be in its class loader dictionary or have a placeholder).
 351   // Must check ClassCircularity before checking if super class is already loaded.

 352   //
 353   // We might not already have a placeholder if this child_name was
 354   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
 355   // the name of the class might not be known until the stream is actually
 356   // parsed.
 357   // Bugs 4643874, 4715493

 358 
 359   ClassLoaderData* loader_data = class_loader_data(class_loader);
 360   Dictionary* dictionary = loader_data->dictionary();
 361   unsigned int d_hash = dictionary->compute_hash(child_name);
 362   int d_index = dictionary->hash_to_index(d_hash);
 363   unsigned int p_hash = placeholders()->compute_hash(child_name);
 364   int p_index = placeholders()->hash_to_index(p_hash);
 365   // can't throw error holding a lock
 366   bool child_already_loaded = false;
 367   bool throw_circularity_error = false;
 368   {
 369     MutexLocker mu(SystemDictionary_lock, THREAD);
 370     Klass* childk = find_class(d_index, d_hash, child_name, dictionary);
 371     Klass* quicksuperk;
 372     // to support // loading: if child done loading, just return superclass
 373     // if class_name, & class_loader don't match:
 374     // if initial define, SD update will give LinkageError
 375     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
 376     // so we don't throw an exception here.
 377     // see: nsk redefclass014 & java.lang.instrument Instrument032
 378     if ((childk != NULL ) && (is_superclass) &&
 379        ((quicksuperk = childk->super()) != NULL) &&
 380 
 381          ((quicksuperk->name() == class_name) &&
 382             (quicksuperk->class_loader()  == class_loader()))) {
 383            return quicksuperk;
 384     } else {
 385       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
 386       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
 387           throw_circularity_error = true;
 388       }
 389     }
 390     if (!throw_circularity_error) {


 426 
 427 void SystemDictionary::validate_protection_domain(InstanceKlass* klass,
 428                                                   Handle class_loader,
 429                                                   Handle protection_domain,
 430                                                   TRAPS) {
 431   if(!has_checkPackageAccess()) return;
 432 
 433   // Now we have to call back to java to check if the initating class has access
 434   JavaValue result(T_VOID);
 435   if (log_is_enabled(Debug, protectiondomain)) {
 436     ResourceMark rm;
 437     // Print out trace information
 438     outputStream* log = Log(protectiondomain)::debug_stream();
 439     log->print_cr("Checking package access");
 440     log->print("class loader: "); class_loader()->print_value_on(log);
 441     log->print(" protection domain: "); protection_domain()->print_value_on(log);
 442     log->print(" loading: "); klass->print_value_on(log);
 443     log->cr();
 444   }
 445 
 446   // This handle and the class_loader handle passed in keeps this class from
 447   // being unloaded through several GC points.
 448   // The class_loader handle passed in is the initiating loader.
 449   Handle mirror(THREAD, klass->java_mirror());
 450 
 451   InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass();
 452   JavaCalls::call_special(&result,
 453                          class_loader,
 454                          system_loader,
 455                          vmSymbols::checkPackageAccess_name(),
 456                          vmSymbols::class_protectiondomain_signature(),
 457                          mirror,
 458                          protection_domain,
 459                          THREAD);
 460 
 461   if (HAS_PENDING_EXCEPTION) {
 462     log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
 463   } else {
 464    log_debug(protectiondomain)("granted");
 465   }
 466 
 467   if (HAS_PENDING_EXCEPTION) return;
 468 
 469   // If no exception has been thrown, we have validated the protection domain
 470   // Insert the protection domain of the initiating class into the set.
 471   {


 472     ClassLoaderData* loader_data = class_loader_data(class_loader);
 473     Dictionary* dictionary = loader_data->dictionary();
 474 
 475     Symbol*  kn = klass->name();
 476     unsigned int d_hash = dictionary->compute_hash(kn);
 477     int d_index = dictionary->hash_to_index(d_hash);
 478 
 479     MutexLocker mu(SystemDictionary_lock, THREAD);
 480     dictionary->add_protection_domain(d_index, d_hash, klass,









 481                                       protection_domain, THREAD);
 482   }

 483 }
 484 
 485 // We only get here if this thread finds that another thread
 486 // has already claimed the placeholder token for the current operation,
 487 // but that other thread either never owned or gave up the
 488 // object lock
 489 // Waits on SystemDictionary_lock to indicate placeholder table updated
 490 // On return, caller must recheck placeholder table state
 491 //
 492 // We only get here if
 493 //  1) custom classLoader, i.e. not bootstrap classloader
 494 //  2) UnsyncloadClass not set
 495 //  3) custom classLoader has broken the class loader objectLock
 496 //     so another thread got here in parallel
 497 //
 498 // lockObject must be held.
 499 // Complicated dance due to lock ordering:
 500 // Must first release the classloader object lock to
 501 // allow initial definer to complete the class definition
 502 // and to avoid deadlock


 523 }
 524 
 525 // If the class in is in the placeholder table, class loading is in progress
 526 // For cases where the application changes threads to load classes, it
 527 // is critical to ClassCircularity detection that we try loading
 528 // the superclass on the same thread internally, so we do parallel
 529 // super class loading here.
 530 // This also is critical in cases where the original thread gets stalled
 531 // even in non-circularity situations.
 532 // Note: must call resolve_super_or_fail even if null super -
 533 // to force placeholder entry creation for this class for circularity detection
 534 // Caller must check for pending exception
 535 // Returns non-null Klass* if other thread has completed load
 536 // and we are done,
 537 // If return null Klass* and no pending exception, the caller must load the class
 538 InstanceKlass* SystemDictionary::handle_parallel_super_load(
 539     Symbol* name, Symbol* superclassname, Handle class_loader,
 540     Handle protection_domain, Handle lockObject, TRAPS) {
 541 
 542   ClassLoaderData* loader_data = class_loader_data(class_loader);
 543   Dictionary* dictionary = loader_data->dictionary();
 544   unsigned int d_hash = dictionary->compute_hash(name);
 545   int d_index = dictionary->hash_to_index(d_hash);
 546   unsigned int p_hash = placeholders()->compute_hash(name);
 547   int p_index = placeholders()->hash_to_index(p_hash);
 548 
 549   // superk is not used, resolve_super called for circularity check only
 550   // This code is reached in two situations. One if this thread
 551   // is loading the same class twice (e.g. ClassCircularity, or
 552   // java.lang.instrument).
 553   // The second is if another thread started the resolve_super first
 554   // and has not yet finished.
 555   // In both cases the original caller will clean up the placeholder
 556   // entry on error.
 557   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
 558                                                           superclassname,
 559                                                           class_loader,
 560                                                           protection_domain,
 561                                                           true,
 562                                                           CHECK_NULL);
 563 
 564   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
 565   // Serial class loaders and bootstrap classloader do wait for superclass loads
 566  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
 567     MutexLocker mu(SystemDictionary_lock, THREAD);
 568     // Check if classloading completed while we were loading superclass or waiting
 569     return find_class(d_index, d_hash, name, dictionary);
 570   }
 571 
 572   // must loop to both handle other placeholder updates
 573   // and spurious notifications
 574   bool super_load_in_progress = true;
 575   PlaceholderEntry* placeholder;
 576   while (super_load_in_progress) {
 577     MutexLocker mu(SystemDictionary_lock, THREAD);
 578     // Check if classloading completed while we were loading superclass or waiting
 579     InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
 580     if (check != NULL) {
 581       // Klass is already loaded, so just return it
 582       return check;
 583     } else {
 584       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 585       if (placeholder && placeholder->super_load_in_progress() ){
 586         // Before UnsyncloadClass:
 587         // We only get here if the application has released the
 588         // classloader lock when another thread was in the middle of loading a
 589         // superclass/superinterface for this class, and now
 590         // this thread is also trying to load this class.
 591         // To minimize surprises, the first thread that started to
 592         // load a class should be the one to complete the loading
 593         // with the classfile it initially expected.
 594         // This logic has the current thread wait once it has done
 595         // all the superclass/superinterface loading it can, until
 596         // the original thread completes the class loading or fails
 597         // If it completes we will use the resulting InstanceKlass
 598         // which we will find below in the systemDictionary.
 599         // We also get here for parallel bootstrap classloader


 639 }
 640 
 641 // Be careful when modifying this code: once you have run
 642 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
 643 // you need to find_and_remove it before returning.
 644 // So be careful to not exit with a CHECK_ macro betweeen these calls.
 645 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
 646                                                         Handle class_loader,
 647                                                         Handle protection_domain,
 648                                                         TRAPS) {
 649   assert(name != NULL && !FieldType::is_array(name) &&
 650          !FieldType::is_obj(name), "invalid class name");
 651 
 652   Ticks class_load_start_time = Ticks::now();
 653 
 654   HandleMark hm(THREAD);
 655 
 656   // Fix for 4474172; see evaluation for more details
 657   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 658   ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);
 659   Dictionary* dictionary = loader_data->dictionary();
 660 
 661   // Do lookup to see if class already exist and the protection domain
 662   // has the right access
 663   // This call uses find which checks protection domain already matches
 664   // All subsequent calls use find_class, and set has_loaded_class so that
 665   // before we return a result we call out to java to check for valid protection domain
 666   // to allow returning the Klass* and add it to the pd_set if it is valid
 667   unsigned int d_hash = dictionary->compute_hash(name);
 668   int d_index = dictionary->hash_to_index(d_hash);
 669   Klass* probe = dictionary->find(d_index, d_hash, name, protection_domain);

 670   if (probe != NULL) return probe;
 671 
 672 
 673   // Non-bootstrap class loaders will call out to class loader and
 674   // define via jvm/jni_DefineClass which will acquire the
 675   // class loader object lock to protect against multiple threads
 676   // defining the class in parallel by accident.
 677   // This lock must be acquired here so the waiter will find
 678   // any successful result in the SystemDictionary and not attempt
 679   // the define
 680   // ParallelCapable Classloaders and the bootstrap classloader,
 681   // or all classloaders with UnsyncloadClass do not acquire lock here
 682   bool DoObjectLock = true;
 683   if (is_parallelCapable(class_loader)) {
 684     DoObjectLock = false;
 685   }
 686 
 687   unsigned int p_hash = placeholders()->compute_hash(name);
 688   int p_index = placeholders()->hash_to_index(p_hash);
 689 
 690   // Class is not in SystemDictionary so we have to do loading.
 691   // Make sure we are synchronized on the class loader before we proceed
 692   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 693   check_loader_lock_contention(lockObject, THREAD);
 694   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 695 
 696   // Check again (after locking) if class already exist in SystemDictionary
 697   bool class_has_been_loaded   = false;
 698   bool super_load_in_progress  = false;
 699   bool havesupername = false;
 700   InstanceKlass* k = NULL;
 701   PlaceholderEntry* placeholder;
 702   Symbol* superclassname = NULL;
 703 
 704   {
 705     MutexLocker mu(SystemDictionary_lock, THREAD);
 706     InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
 707     if (check != NULL) {
 708       // Klass is already loaded, so just return it
 709       class_has_been_loaded = true;
 710       k = check;
 711     } else {
 712       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 713       if (placeholder && placeholder->super_load_in_progress()) {
 714          super_load_in_progress = true;
 715          if (placeholder->havesupername() == true) {
 716            superclassname = placeholder->supername();
 717            havesupername = true;
 718          }
 719       }
 720     }
 721   }
 722 
 723   // If the class is in the placeholder table, class loading is in progress
 724   if (super_load_in_progress && havesupername==true) {
 725     k = handle_parallel_super_load(name,
 726                                    superclassname,


 770         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 771         if (oldprobe) {
 772           // only need check_seen_thread once, not on each loop
 773           // 6341374 java/lang/Instrument with -Xcomp
 774           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
 775             throw_circularity_error = true;
 776           } else {
 777             // case 1: traditional: should never see load_in_progress.
 778             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
 779 
 780               // case 4: bootstrap classloader: prevent futile classloading,
 781               // wait on first requestor
 782               if (class_loader.is_null()) {
 783                 SystemDictionary_lock->wait();
 784               } else {
 785               // case 2: traditional with broken classloader lock. wait on first
 786               // requestor.
 787                 double_lock_wait(lockObject, THREAD);
 788               }
 789               // Check if classloading completed while we were waiting
 790               InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
 791               if (check != NULL) {
 792                 // Klass is already loaded, so just return it
 793                 k = check;
 794                 class_has_been_loaded = true;
 795               }
 796               // check if other thread failed to load and cleaned up
 797               oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 798             }
 799           }
 800         }
 801       }
 802       // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
 803       // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
 804       // LOAD_INSTANCE in parallel
 805 
 806       if (!throw_circularity_error && !class_has_been_loaded) {
 807         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
 808         load_instance_added = true;
 809         // For class loaders that do not acquire the classloader object lock,
 810         // if they did not catch another thread holding LOAD_INSTANCE,
 811         // need a check analogous to the acquire ObjectLocker/find_class
 812         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
 813         // one final check if the load has already completed
 814         // class loaders holding the ObjectLock shouldn't find the class here
 815         InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
 816         if (check != NULL) {
 817         // Klass is already loaded, so return it after checking/adding protection domain
 818           k = check;
 819           class_has_been_loaded = true;
 820         }
 821       }
 822     }
 823 
 824     // must throw error outside of owning lock
 825     if (throw_circularity_error) {
 826       assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
 827       ResourceMark rm(THREAD);
 828       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
 829     }
 830 
 831     if (!class_has_been_loaded) {
 832 
 833       // Do actual loading
 834       k = load_instance_class(name, class_loader, THREAD);
 835 
 836       // For UnsyncloadClass only
 837       // If they got a linkageError, check if a parallel class load succeeded.
 838       // If it did, then for bytecode resolution the specification requires
 839       // that we return the same result we did for the other thread, i.e. the
 840       // successfully loaded InstanceKlass
 841       // Should not get here for classloaders that support parallelism
 842       // with the new cleaner mechanism, even with AllowParallelDefineClass
 843       // Bootstrap goes through here to allow for an extra guarantee check
 844       if (UnsyncloadClass || (class_loader.is_null())) {
 845         if (k == NULL && HAS_PENDING_EXCEPTION
 846           && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
 847           MutexLocker mu(SystemDictionary_lock, THREAD);
 848           InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
 849           if (check != NULL) {
 850             // Klass is already loaded, so just use it
 851             k = check;
 852             CLEAR_PENDING_EXCEPTION;
 853             guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
 854           }
 855         }
 856       }
 857 
 858       // If everything was OK (no exceptions, no null return value), and
 859       // class_loader is NOT the defining loader, do a little more bookkeeping.
 860       if (!HAS_PENDING_EXCEPTION && k != NULL &&
 861         k->class_loader() != class_loader()) {
 862 
 863         check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
 864 
 865         // Need to check for a PENDING_EXCEPTION again; check_constraints
 866         // can throw and doesn't use the CHECK macro.
 867         if (!HAS_PENDING_EXCEPTION) {
 868           { // Grabbing the Compile_lock prevents systemDictionary updates
 869             // during compilations.
 870             MutexLocker mu(Compile_lock, THREAD);
 871             update_dictionary(d_index, d_hash, p_index, p_hash,
 872                               k, class_loader, THREAD);
 873           }
 874 
 875           if (JvmtiExport::should_post_class_load()) {
 876             Thread *thread = THREAD;
 877             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 878             JvmtiExport::post_class_load((JavaThread *) thread, k);
 879           }
 880         }
 881       }
 882     } // load_instance_class
 883 
 884     if (load_instance_added == true) {
 885       // clean up placeholder entries for LOAD_INSTANCE success or error
 886       // This brackets the SystemDictionary updates for both defining
 887       // and initiating loaders
 888       MutexLocker mu(SystemDictionary_lock, THREAD);
 889       placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
 890       SystemDictionary_lock->notify_all();
 891     }
 892   }
 893 
 894   if (HAS_PENDING_EXCEPTION || k == NULL) {
 895     return NULL;
 896   }
 897 
 898   post_class_load_event(class_load_start_time, k, loader_data);
 899 
 900 #ifdef ASSERT
 901   {
 902     ClassLoaderData* loader_data = k->class_loader_data();
 903     MutexLocker mu(SystemDictionary_lock, THREAD);
 904     Klass* kk = find_class(name, loader_data);
 905     assert(kk == k, "should be present in dictionary");
 906   }
 907 #endif
 908 
 909   // return if the protection domain in NULL
 910   if (protection_domain() == NULL) return k;
 911 
 912   // Check the protection domain has the right access
 913   {
 914     MutexLocker mu(SystemDictionary_lock, THREAD);
 915     if (dictionary->is_valid_protection_domain(d_index, d_hash, name,








 916                                                protection_domain)) {
 917       return k;
 918     }
 919   }
 920 
 921   // Verify protection domain. If it fails an exception is thrown
 922   validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
 923 
 924   return k;
 925 }
 926 
 927 
 928 // This routine does not lock the system dictionary.
 929 //
 930 // Since readers don't hold a lock, we must make sure that system
 931 // dictionary entries are only removed at a safepoint (when only one
 932 // thread is running), and are added to in a safe way (all links must
 933 // be updated in an MT-safe manner).
 934 //
 935 // Callers should be aware that an entry could be added just after
 936 // _dictionary->bucket(index) is read here, so the caller will not see
 937 // the new entry.
 938 
 939 Klass* SystemDictionary::find(Symbol* class_name,
 940                               Handle class_loader,
 941                               Handle protection_domain,
 942                               TRAPS) {
 943 
 944   // The result of this call should be consistent with the result
 945   // of the call to resolve_instance_class_or_null().
 946   // See evaluation 6790209 and 4474172 for more details.
 947   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
 948   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
 949 
 950   if (loader_data == NULL) {
 951     // If the ClassLoaderData has not been setup,
 952     // then the class loader has no entries in the dictionary.
 953     return NULL;
 954   }
 955 
 956   Dictionary* dictionary = loader_data->dictionary();
 957   unsigned int d_hash = dictionary->compute_hash(class_name);
 958   int d_index = dictionary->hash_to_index(d_hash);
 959   return dictionary->find(d_index, d_hash, class_name,
 960                           protection_domain);









 961 }
 962 
 963 
 964 // Look for a loaded instance or array klass by name.  Do not do any loading.
 965 // return NULL in case of error.
 966 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
 967                                                       Handle class_loader,
 968                                                       Handle protection_domain,
 969                                                       TRAPS) {
 970   Klass* k = NULL;
 971   assert(class_name != NULL, "class name must be non NULL");
 972 
 973   if (FieldType::is_array(class_name)) {
 974     // The name refers to an array.  Parse the name.
 975     // dimension and object_key in FieldArrayInfo are assigned as a
 976     // side-effect of this call
 977     FieldArrayInfo fd;
 978     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
 979     if (t != T_OBJECT) {
 980       k = Universe::typeArrayKlassObj(t);


 994 // does not publish the classes via the SystemDictionary.
 995 // Handles unsafe_DefineAnonymousClass and redefineclasses
 996 // RedefinedClasses do not add to the class hierarchy
 997 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name,
 998                                               Handle class_loader,
 999                                               Handle protection_domain,
1000                                               ClassFileStream* st,
1001                                               const InstanceKlass* host_klass,
1002                                               GrowableArray<Handle>* cp_patches,
1003                                               TRAPS) {
1004 
1005   Ticks class_load_start_time = Ticks::now();
1006 
1007   ClassLoaderData* loader_data;
1008   if (host_klass != NULL) {
1009     // Create a new CLD for anonymous class, that uses the same class loader
1010     // as the host_klass
1011     guarantee(host_klass->class_loader() == class_loader(), "should be the same");
1012     guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
1013     loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);

1014   } else {
1015     loader_data = ClassLoaderData::class_loader_data(class_loader());
1016   }
1017 
1018   assert(st != NULL, "invariant");
1019   assert(st->need_verify(), "invariant");
1020 
1021   // Parse stream and create a klass.
1022   // Note that we do this even though this klass might
1023   // already be present in the SystemDictionary, otherwise we would not
1024   // throw potential ClassFormatErrors.
1025 
1026   InstanceKlass* k = KlassFactory::create_from_stream(st,
1027                                                       class_name,
1028                                                       loader_data,
1029                                                       protection_domain,
1030                                                       host_klass,
1031                                                       cp_patches,
1032                                                       CHECK_NULL);
1033 
1034   if (host_klass != NULL && k != NULL) {
1035     // If it's anonymous, initialize it now, since nobody else will.
1036 
1037     {
1038       MutexLocker mu_r(Compile_lock, THREAD);
1039 
1040       // Add to class hierarchy, initialize vtables, and do possible
1041       // deoptimizations.
1042       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
1043 
1044       // But, do not add to dictionary.
1045 
1046       // compiled code dependencies need to be validated anyway
1047       notice_modification();
1048     }
1049 
1050     // Rewrite and patch constant pool here.
1051     k->link_class(CHECK_NULL);
1052     if (cp_patches != NULL) {
1053       k->constants()->patch_resolved_references(cp_patches);
1054     }
1055     k->eager_initialize(CHECK_NULL);
1056 
1057     // notify jvmti
1058     if (JvmtiExport::should_post_class_load()) {
1059         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1060         JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1061     }
1062 
1063     post_class_load_event(class_load_start_time, k, loader_data);
1064   }


1147   if (HAS_PENDING_EXCEPTION) {
1148     assert(k != NULL, "Must have an instance klass here!");
1149     loader_data->add_to_deallocate_list(k);
1150     return NULL;
1151   }
1152 
1153   // Make sure we have an entry in the SystemDictionary on success
1154   debug_only( {
1155     MutexLocker mu(SystemDictionary_lock, THREAD);
1156 
1157     Klass* check = find_class(h_name, k->class_loader_data());
1158     assert(check == k, "should be present in the dictionary");
1159   } );
1160 
1161   return k;
1162 }
1163 
1164 #if INCLUDE_CDS
1165 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
1166                                              int number_of_entries) {
1167   assert(length == _shared_dictionary_size * sizeof(HashtableBucket<mtClass>),
1168          "bad shared dictionary size.");
1169   _shared_dictionary = new Dictionary(ClassLoaderData::the_null_class_loader_data(),
1170                                       _shared_dictionary_size, t, number_of_entries);
1171 }
1172 
1173 
1174 // If there is a shared dictionary, then find the entry for the
1175 // given shared system class, if any.
1176 
1177 InstanceKlass* SystemDictionary::find_shared_class(Symbol* class_name) {
1178   if (shared_dictionary() != NULL) {
1179     unsigned int d_hash = shared_dictionary()->compute_hash(class_name);
1180     int d_index = shared_dictionary()->hash_to_index(d_hash);
1181 
1182     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1183   } else {
1184     return NULL;
1185   }
1186 }
1187 
1188 
1189 // Load a class from the shared spaces (found through the shared system
1190 // dictionary).  Force the superclass and all interfaces to be loaded.
1191 // Update the class definition to include sibling classes and no
1192 // subclasses (yet).  [Classes in the shared space are not part of the
1193 // object hierarchy until loaded.]
1194 
1195 InstanceKlass* SystemDictionary::load_shared_class(
1196                  Symbol* class_name, Handle class_loader, TRAPS) {
1197   InstanceKlass* ik = find_shared_class(class_name);
1198   // Make sure we only return the boot class for the NULL classloader.
1199   if (ik != NULL &&


1585  // use placeholder token
1586  // If a parallelCapable class loader calls define_instance_class instead of
1587  // find_or_define_instance_class to get here, we have a timing
1588  // hole with systemDictionary updates and check_constraints
1589  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1590     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1591          compute_loader_lock_object(class_loader_h, THREAD)),
1592          "define called without lock");
1593   }
1594 
1595   // Check class-loading constraints. Throw exception if violation is detected.
1596   // Grabs and releases SystemDictionary_lock
1597   // The check_constraints/find_class call and update_dictionary sequence
1598   // must be "atomic" for a specific class/classloader pair so we never
1599   // define two different instanceKlasses for that class/classloader pair.
1600   // Existing classloaders will call define_instance_class with the
1601   // classloader lock held
1602   // Parallel classloaders will call find_or_define_instance_class
1603   // which will require a token to perform the define class
1604   Symbol*  name_h = k->name();
1605   Dictionary* dictionary = loader_data->dictionary();
1606   unsigned int d_hash = dictionary->compute_hash(name_h);
1607   int d_index = dictionary->hash_to_index(d_hash);
1608   check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1609 
1610   // Register class just loaded with class loader (placed in Vector)
1611   // Note we do this before updating the dictionary, as this can
1612   // fail with an OutOfMemoryError (if it does, we will *not* put this
1613   // class in the dictionary and will not update the class hierarchy).
1614   // JVMTI FollowReferences needs to find the classes this way.
1615   if (k->class_loader() != NULL) {
1616     methodHandle m(THREAD, Universe::loader_addClass_method());
1617     JavaValue result(T_VOID);
1618     JavaCallArguments args(class_loader_h);
1619     args.push_oop(Handle(THREAD, k->java_mirror()));
1620     JavaCalls::call(&result, m, &args, CHECK);
1621   }
1622 
1623   // Add the new class. We need recompile lock during update of CHA.
1624   {
1625     unsigned int p_hash = placeholders()->compute_hash(name_h);
1626     int p_index = placeholders()->hash_to_index(p_hash);
1627 
1628     MutexLocker mu_r(Compile_lock, THREAD);
1629 
1630     // Add to class hierarchy, initialize vtables, and do possible
1631     // deoptimizations.
1632     add_to_hierarchy(k, CHECK); // No exception, but can block
1633 
1634     // Add to systemDictionary - so other classes can see it.
1635     // Grabs and releases SystemDictionary_lock
1636     update_dictionary(d_index, d_hash, p_index, p_hash,
1637                       k, class_loader_h, THREAD);
1638   }
1639   k->eager_initialize(THREAD);
1640 
1641   // notify jvmti
1642   if (JvmtiExport::should_post_class_load()) {
1643       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1644       JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1645 


1655 // FindLoadedClass/DefineClass, calls, we check for parallel
1656 // loading for them, wait if a defineClass is in progress
1657 // and return the initial requestor's results
1658 // This flag does not apply to the bootstrap classloader.
1659 // With AllowParallelDefine flag==false, call through to define_instance_class
1660 // which will throw LinkageError: duplicate class definition.
1661 // False is the requested default.
1662 // For better performance, the class loaders should synchronize
1663 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1664 // potentially waste time reading and parsing the bytestream.
1665 // Note: VM callers should ensure consistency of k/class_name,class_loader
1666 // Be careful when modifying this code: once you have run
1667 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1668 // you need to find_and_remove it before returning.
1669 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1670 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1671                                                                InstanceKlass* k, TRAPS) {
1672 
1673   Symbol*  name_h = k->name(); // passed in class_name may be null
1674   ClassLoaderData* loader_data = class_loader_data(class_loader);
1675   Dictionary* dictionary = loader_data->dictionary();
1676 
1677   unsigned int d_hash = dictionary->compute_hash(name_h);
1678   int d_index = dictionary->hash_to_index(d_hash);
1679 
1680   // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1681   unsigned int p_hash = placeholders()->compute_hash(name_h);
1682   int p_index = placeholders()->hash_to_index(p_hash);
1683   PlaceholderEntry* probe;
1684 
1685   {
1686     MutexLocker mu(SystemDictionary_lock, THREAD);
1687     // First check if class already defined
1688     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1689       InstanceKlass* check = find_class(d_index, d_hash, name_h, dictionary);
1690       if (check != NULL) {
1691         return check;
1692       }
1693     }
1694 
1695     // Acquire define token for this class/classloader
1696     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1697     // Wait if another thread defining in parallel
1698     // All threads wait - even those that will throw duplicate class: otherwise
1699     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1700     // if other thread has not finished updating dictionary
1701     while (probe->definer() != NULL) {
1702       SystemDictionary_lock->wait();
1703     }
1704     // Only special cases allow parallel defines and can use other thread's results
1705     // Other cases fall through, and may run into duplicate defines
1706     // caught by finding an entry in the SystemDictionary
1707     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1708         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1709         SystemDictionary_lock->notify_all();
1710 #ifdef ASSERT
1711         InstanceKlass* check = find_class(d_index, d_hash, name_h, dictionary);
1712         assert(check != NULL, "definer missed recording success");
1713 #endif
1714         return probe->instance_klass();
1715     } else {
1716       // This thread will define the class (even if earlier thread tried and had an error)
1717       probe->set_definer(THREAD);
1718     }
1719   }
1720 
1721   define_instance_class(k, THREAD);
1722 
1723   Handle linkage_exception = Handle(); // null handle
1724 
1725   // definer must notify any waiting threads
1726   {
1727     MutexLocker mu(SystemDictionary_lock, THREAD);
1728     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1729     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1730     if (probe != NULL) {
1731       if (HAS_PENDING_EXCEPTION) {
1732         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1733         CLEAR_PENDING_EXCEPTION;
1734       } else {
1735         probe->set_instance_klass(k);
1736       }
1737       probe->set_definer(NULL);
1738       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1739       SystemDictionary_lock->notify_all();
1740     }
1741   }
1742 
1743   // Can't throw exception while holding lock due to rank ordering
1744   if (linkage_exception() != NULL) {
1745     THROW_OOP_(linkage_exception(), NULL); // throws exception and returns
1746   }
1747 
1748   return k;
1749 }
1750 
1751 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1752   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1753   if (class_loader.is_null()) {
1754     return Handle(THREAD, _system_loader_lock_obj);
1755   } else {
1756     return class_loader;
1757   }
1758 }
1759 
1760 // This method is added to check how often we have to wait to grab loader
1761 // lock. The results are being recorded in the performance counters defined in
1762 // ClassLoader::_sync_systemLoaderLockContentionRate and
1763 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1764 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1765   if (!UsePerfData) {
1766     return;
1767   }
1768 
1769   assert(!loader_lock.is_null(), "NULL lock object");
1770 
1771   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1772       == ObjectSynchronizer::owner_other) {
1773     // contention will likely happen, so increment the corresponding
1774     // contention counter.
1775     if (loader_lock() == _system_loader_lock_obj) {
1776       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1777     } else {
1778       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1779     }
1780   }
1781 }
1782 
1783 // ----------------------------------------------------------------------------
1784 // Lookup
1785 
1786 InstanceKlass* SystemDictionary::find_class(int index, unsigned int hash,
1787                                             Symbol* class_name,
1788                                             Dictionary* dictionary) {
1789   assert_locked_or_safepoint(SystemDictionary_lock);
1790   return dictionary->find_class(index, hash, class_name);



1791 }
1792 
1793 
1794 // Basic find on classes in the midst of being loaded
1795 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1796                                            ClassLoaderData* loader_data) {
1797   assert_locked_or_safepoint(SystemDictionary_lock);
1798   unsigned int p_hash = placeholders()->compute_hash(class_name);
1799   int p_index = placeholders()->hash_to_index(p_hash);
1800   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1801 }
1802 
1803 
1804 // Used for assertions and verification only
1805 // Precalculating the hash and index is an optimization because there are many lookups
1806 // before adding the class.
1807 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1808   assert_locked_or_safepoint(SystemDictionary_lock);
1809   #ifndef ASSERT
1810   guarantee(VerifyBeforeGC      ||
1811             VerifyDuringGC      ||
1812             VerifyBeforeExit    ||
1813             VerifyDuringStartup ||
1814             VerifyAfterGC, "too expensive");
1815   #endif

1816 
1817   Dictionary* dictionary = loader_data->dictionary();
1818   unsigned int d_hash = dictionary->compute_hash(class_name);
1819   int d_index = dictionary->hash_to_index(d_hash);
1820   return find_class(d_index, d_hash, class_name, dictionary);






1821 }
1822 
1823 
1824 // ----------------------------------------------------------------------------
1825 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1826 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1827 // before a new class is used.
1828 
1829 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) {
1830   assert(k != NULL, "just checking");
1831   assert_locked_or_safepoint(Compile_lock);
1832 
1833   // Link into hierachy. Make sure the vtables are initialized before linking into
1834   k->append_to_sibling_list();                    // add to superklass/sibling list
1835   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1836   k->set_init_state(InstanceKlass::loaded);
1837   // Now flush all code that depended on old class hierarchy.
1838   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1839   // Also, first reinitialize vtable because it may have gotten out of synch
1840   // while the new class wasn't connected to the class hierarchy.
1841   CodeCache::flush_dependents_on(k);
1842 }
1843 
1844 // ----------------------------------------------------------------------------
1845 // GC support
1846 








1847 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1848   roots_oops_do(blk, NULL);
1849 }
1850 















1851 
1852 #ifdef ASSERT
1853 class VerifySDReachableAndLiveClosure : public OopClosure {
1854 private:
1855   BoolObjectClosure* _is_alive;
1856 
1857   template <class T> void do_oop_work(T* p) {
1858     oop obj = oopDesc::load_decode_heap_oop(p);
1859     guarantee(_is_alive->do_object_b(obj), "Oop in protection domain cache table must be live");
1860   }
1861 
1862 public:
1863   VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }
1864 
1865   virtual void do_oop(oop* p)       { do_oop_work(p); }
1866   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
1867 };
1868 #endif
1869 
1870 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1871 // Note: anonymous classes are not in the SD.
1872 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive,
1873                                     GCTimer* gc_timer,
1874                                     bool do_cleaning) {
1875 
1876 
1877   bool unloading_occurred;
1878   {
1879     GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1880 
1881     // First, mark for unload all ClassLoaderData referencing a dead class loader.
1882     unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive,
1883                                                             do_cleaning);
1884   }
1885 
1886   if (unloading_occurred) {
1887     GCTraceTime(Debug, gc, phases) t("Dictionary", gc_timer);

1888     constraints()->purge_loader_constraints();
1889     resolution_errors()->purge_resolution_errors();
1890   }
1891 
1892   {
1893     GCTraceTime(Debug, gc, phases) t("ProtectionDomainCacheTable", gc_timer);
1894     // Oops referenced by the protection domain cache table may get unreachable independently
1895     // of the class loader (eg. cached protection domain oops). So we need to
1896     // explicitly unlink them here.
1897     _pd_cache_table->unlink(is_alive);
1898 
1899 #ifdef ASSERT
1900     VerifySDReachableAndLiveClosure cl(is_alive);
1901     _pd_cache_table->oops_do(&cl);
1902 #endif
1903   }
1904 
1905   if (do_cleaning) {
1906     GCTraceTime(Debug, gc, phases) t("ResolvedMethodTable", gc_timer);
1907     ResolvedMethodTable::unlink(is_alive);
1908   }
1909 
1910   return unloading_occurred;
1911 }
1912 
1913 void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
1914   strong->do_oop(&_java_system_loader);
1915   strong->do_oop(&_system_loader_lock_obj);
1916   CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
1917 
1918   // Do strong roots marking if the closures are the same.
1919   if (strong == weak || !ClassUnloading) {
1920     // Only the protection domain oops contain references into the heap. Iterate
1921     // over all of them.
1922     _pd_cache_table->oops_do(strong);
1923   } else {
1924    if (weak != NULL) {
1925      _pd_cache_table->oops_do(weak);
1926    }
1927   }
1928 
1929   // Visit extra methods
1930   invoke_method_table()->oops_do(strong);
1931 
1932   if (weak != NULL) {
1933     ResolvedMethodTable::oops_do(weak);
1934   }
1935 }
1936 
1937 void SystemDictionary::oops_do(OopClosure* f) {
1938   f->do_oop(&_java_system_loader);
1939   f->do_oop(&_system_loader_lock_obj);
1940   CDS_ONLY(SystemDictionaryShared::oops_do(f);)
1941 
1942   // Only the protection domain oops contain references into the heap. Iterate
1943   // over all of them.
1944   _pd_cache_table->oops_do(f);
1945 
1946   // Visit extra methods
1947   invoke_method_table()->oops_do(f);
1948 
1949   ResolvedMethodTable::oops_do(f);
1950 }
1951 



















1952 void SystemDictionary::methods_do(void f(Method*)) {
1953   // Walk methods in loaded classes
1954   ClassLoaderDataGraph::methods_do(f);
1955   // Walk method handle intrinsics
1956   invoke_method_table()->methods_do(f);
1957 }
1958 
1959 void SystemDictionary::remove_classes_in_error_state() {
1960   ClassLoaderData::the_null_class_loader_data()->dictionary()->remove_classes_in_error_state();
1961 }
1962 
1963 // ----------------------------------------------------------------------------
1964 // Lazily load klasses
1965 
1966 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
1967   // if multiple threads calling this function, only one thread will load
1968   // the class.  The other threads will find the loaded version once the
1969   // class is loaded.
1970   Klass* aos = _abstract_ownable_synchronizer_klass;
1971   if (aos == NULL) {
1972     Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
1973     // Force a fence to prevent any read before the write completes
1974     OrderAccess::fence();
1975     _abstract_ownable_synchronizer_klass = InstanceKlass::cast(k);
1976   }
1977 }
1978 
1979 // ----------------------------------------------------------------------------
1980 // Initialization
1981 
1982 void SystemDictionary::initialize(TRAPS) {
1983   // Allocate arrays
1984   _placeholders        = new PlaceholderTable(_placeholder_table_size);




1985   _number_of_modifications = 0;
1986   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
1987   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
1988   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
1989   _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize);
1990 
1991   // Allocate private object used as system class loader lock
1992   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
1993   // Initialize basic classes
1994   initialize_preloaded_classes(CHECK);
1995 }
1996 
1997 // Compact table of directions on the initialization of klasses:
1998 static const short wk_init_info[] = {
1999   #define WK_KLASS_INIT_INFO(name, symbol, option) \
2000     ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
2001           << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
2002       | (int)SystemDictionary::option ),
2003   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
2004   #undef WK_KLASS_INIT_INFO
2005   0
2006 };
2007 
2008 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
2009   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");


2120   { // Compute whether we should use checkPackageAccess or NOT
2121     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::checkPackageAccess_name(), vmSymbols::class_protectiondomain_signature());
2122     _has_checkPackageAccess = (method != NULL);
2123   }
2124 }
2125 
2126 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
2127 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
2128 BasicType SystemDictionary::box_klass_type(Klass* k) {
2129   assert(k != NULL, "");
2130   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
2131     if (_box_klasses[i] == k)
2132       return (BasicType)i;
2133   }
2134   return T_OBJECT;
2135 }
2136 
2137 // Constraints on class loaders. The details of the algorithm can be
2138 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2139 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
2140 // that the dictionary needs to maintain a set of contraints that
2141 // must be satisfied by all classes in the dictionary.
2142 // if defining is true, then LinkageError if already in dictionary
2143 // if initiating loader, then ok if InstanceKlass matches existing entry
2144 
2145 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
2146                                          InstanceKlass* k,
2147                                          Handle class_loader, bool defining,
2148                                          TRAPS) {
2149   const char *linkage_error1 = NULL;
2150   const char *linkage_error2 = NULL;
2151   {
2152     Symbol*  name  = k->name();
2153     ClassLoaderData *loader_data = class_loader_data(class_loader);
2154 
2155     MutexLocker mu(SystemDictionary_lock, THREAD);
2156 
2157     InstanceKlass* check = find_class(d_index, d_hash, name, loader_data->dictionary());
2158     if (check != NULL) {
2159       // if different InstanceKlass - duplicate class definition,
2160       // else - ok, class loaded by a different thread in parallel,
2161       // we should only have found it if it was done loading and ok to use
2162       // dictionary only holds instance classes, placeholders
2163       // also holds array classes
2164 
2165       assert(check->is_instance_klass(), "noninstance in systemdictionary");
2166       if ((defining == true) || (k != check)) {
2167         linkage_error1 = "loader (instance of ";
2168         linkage_error2 = "): attempted duplicate class definition for name: \"";
2169       } else {
2170         return;
2171       }
2172     }
2173 
2174 #ifdef ASSERT
2175     Symbol* ph_check = find_placeholder(name, loader_data);
2176     assert(ph_check == NULL || ph_check == name, "invalid symbol");
2177 #endif
2178 
2179     if (linkage_error1 == NULL) {
2180       if (constraints()->check_or_update(k, class_loader, name) == false) {
2181         linkage_error1 = "loader constraint violation: loader (instance of ";
2182         linkage_error2 = ") previously initiated loading for a different type with name \"";
2183       }
2184     }
2185   }
2186 
2187   // Throw error now if needed (cannot throw while holding
2188   // SystemDictionary_lock because of rank ordering)
2189 
2190   if (linkage_error1) {
2191     ResourceMark rm(THREAD);
2192     const char* class_loader_name = loader_name(class_loader());
2193     char* type_name = k->name()->as_C_string();
2194     size_t buflen = strlen(linkage_error1) + strlen(class_loader_name) +
2195       strlen(linkage_error2) + strlen(type_name) + 2; // +2 for '"' and null byte.
2196     char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
2197     jio_snprintf(buf, buflen, "%s%s%s%s\"", linkage_error1, class_loader_name, linkage_error2, type_name);
2198     THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
2199   }
2200 }
2201 
2202 
2203 // Update class loader data dictionary - done after check_constraint and add_to_hierachy
2204 // have been called.
2205 void SystemDictionary::update_dictionary(int d_index, unsigned int d_hash,
2206                                          int p_index, unsigned int p_hash,
2207                                          InstanceKlass* k,
2208                                          Handle class_loader,
2209                                          TRAPS) {
2210   // Compile_lock prevents systemDictionary updates during compilations
2211   assert_locked_or_safepoint(Compile_lock);
2212   Symbol*  name  = k->name();
2213   ClassLoaderData *loader_data = class_loader_data(class_loader);
2214 
2215   {
2216     MutexLocker mu1(SystemDictionary_lock, THREAD);
2217 
2218     // See whether biased locking is enabled and if so set it for this
2219     // klass.
2220     // Note that this must be done past the last potential blocking
2221     // point / safepoint. We enable biased locking lazily using a
2222     // VM_Operation to iterate the SystemDictionary and installing the
2223     // biasable mark word into each InstanceKlass's prototype header.
2224     // To avoid race conditions where we accidentally miss enabling the
2225     // optimization for one class in the process of being added to the
2226     // dictionary, we must not safepoint after the test of
2227     // BiasedLocking::enabled().
2228     if (UseBiasedLocking && BiasedLocking::enabled()) {
2229       // Set biased locking bit for all loaded classes; it will be
2230       // cleared if revocation occurs too often for this type
2231       // NOTE that we must only do this when the class is initally
2232       // defined, not each time it is referenced from a new class loader
2233       if (k->class_loader() == class_loader()) {
2234         k->set_prototype_header(markOopDesc::biased_locking_prototype());
2235       }
2236     }
2237 
2238     // Make a new dictionary entry.
2239     Dictionary* dictionary = loader_data->dictionary();
2240     InstanceKlass* sd_check = find_class(d_index, d_hash, name, dictionary);
2241     if (sd_check == NULL) {
2242       dictionary->add_klass(d_index, d_hash, name, k);
2243       notice_modification();
2244     }
2245   #ifdef ASSERT
2246     sd_check = find_class(d_index, d_hash, name, dictionary);
2247     assert (sd_check != NULL, "should have entry in dictionary");
2248     // Note: there may be a placeholder entry: for circularity testing
2249     // or for parallel defines
2250   #endif
2251     SystemDictionary_lock->notify_all();
2252   }
2253 }
2254 
2255 
2256 // Try to find a class name using the loader constraints.  The
2257 // loader constraints might know about a class that isn't fully loaded
2258 // yet and these will be ignored.
2259 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2260                     Symbol* class_name, Handle class_loader, TRAPS) {
2261 
2262   // First see if it has been loaded directly.
2263   // Force the protection domain to be null.  (This removes protection checks.)
2264   Handle no_protection_domain;
2265   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2266                                               no_protection_domain, CHECK_NULL);
2267   if (klass != NULL)
2268     return klass;
2269 
2270   // Now look to see if it has been loaded elsewhere, and is subject to


2300                                              Handle class_loader2,
2301                                              Thread* THREAD) {
2302   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2303   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2304 
2305   Symbol* constraint_name = NULL;
2306   if (!FieldType::is_array(class_name)) {
2307     constraint_name = class_name;
2308   } else {
2309     // For array classes, their Klass*s are not kept in the
2310     // constraint table. The element classes are.
2311     FieldArrayInfo fd;
2312     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2313     // primitive types always pass
2314     if (t != T_OBJECT) {
2315       return true;
2316     } else {
2317       constraint_name = fd.object_key();
2318     }
2319   }


2320 
2321   Dictionary* dictionary1 = loader_data1->dictionary();
2322   unsigned int d_hash1 = dictionary1->compute_hash(constraint_name);
2323   int d_index1 = dictionary1->hash_to_index(d_hash1);
2324 
2325   Dictionary* dictionary2 = loader_data2->dictionary();
2326   unsigned int d_hash2 = dictionary2->compute_hash(constraint_name);
2327   int d_index2 = dictionary2->hash_to_index(d_hash2);
2328   
2329   {
2330     MutexLocker mu_s(SystemDictionary_lock, THREAD);
2331     InstanceKlass* klass1 = find_class(d_index1, d_hash1, constraint_name, dictionary1);
2332     InstanceKlass* klass2 = find_class(d_index2, d_hash2, constraint_name, dictionary2);




2333     return constraints()->add_entry(constraint_name, klass1, class_loader1,
2334                                     klass2, class_loader2);
2335   }
2336 }
2337 
2338 // Add entry to resolution error table to record the error when the first
2339 // attempt to resolve a reference to a class has failed.
2340 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2341                                             Symbol* error, Symbol* message) {
2342   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2343   int index = resolution_errors()->hash_to_index(hash);
2344   {
2345     MutexLocker ml(SystemDictionary_lock, Thread::current());
2346     resolution_errors()->add_entry(index, hash, pool, which, error, message);
2347   }
2348 }
2349 
2350 // Delete a resolution error for RedefineClasses for a constant pool is going away
2351 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2352   resolution_errors()->delete_entry(pool);


2764 
2765   // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2766   JavaCallArguments args;
2767   args.push_oop(Handle(THREAD, caller->java_mirror()));
2768   args.push_oop(bsm);
2769   args.push_oop(method_name);
2770   args.push_oop(method_type);
2771   args.push_oop(info);
2772   args.push_oop(appendix_box);
2773   JavaValue result(T_OBJECT);
2774   JavaCalls::call_static(&result,
2775                          SystemDictionary::MethodHandleNatives_klass(),
2776                          vmSymbols::linkCallSite_name(),
2777                          vmSymbols::linkCallSite_signature(),
2778                          &args, CHECK_(empty));
2779   Handle mname(THREAD, (oop) result.get_jobject());
2780   (*method_type_result) = method_type;
2781   return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);
2782 }
2783 
2784 // Protection domain cache table handling
2785 
2786 ProtectionDomainCacheEntry* SystemDictionary::cache_get(Handle protection_domain) {
2787   return _pd_cache_table->get(protection_domain);
2788 }
2789 
2790 
2791 void SystemDictionary::reorder_dictionary() {
2792   ClassLoaderData::the_null_class_loader_data()->dictionary()->reorder_dictionary();
2793 }
2794 
2795 
2796 void SystemDictionary::copy_buckets(char** top, char* end) {
2797   ClassLoaderData::the_null_class_loader_data()->dictionary()->copy_buckets(top, end);
2798 }
2799 
2800 
2801 void SystemDictionary::copy_table(char** top, char* end) {
2802   ClassLoaderData::the_null_class_loader_data()->dictionary()->copy_table(top, end);
2803 }
2804 





2805 // ----------------------------------------------------------------------------
2806 void SystemDictionary::print_shared(bool details) {
2807   shared_dictionary()->print(details);
2808 }
2809 
2810 void SystemDictionary::print(bool details) {
2811   if (shared_dictionary() != NULL) {
2812     tty->print_cr("Shared Dictionary");
2813     shared_dictionary()->print(details);
2814   }
2815 

2816   GCMutexLocker mu(SystemDictionary_lock);
2817 
2818   ClassLoaderDataGraph::print_dictionary(details);
2819 
2820   // Placeholders
2821   placeholders()->print();
2822   tty->cr();
2823 
2824   // loader constraints - print under SD_lock
2825   constraints()->print();
2826   tty->cr();
2827 
2828   _pd_cache_table->print();
2829   tty->cr();
2830 }
2831 
2832 
2833 void SystemDictionary::verify() {

2834   guarantee(constraints() != NULL,
2835             "Verify of loader constraints failed");
2836   guarantee(placeholders()->number_of_entries() >= 0,
2837             "Verify of placeholders failed");

2838 
2839   // Verify dictionary
2840   ClassLoaderDataGraph::verify_dictionary();
2841 
2842   GCMutexLocker mu(SystemDictionary_lock);
2843   placeholders()->verify();
2844 
2845   // Verify constraint table
2846   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2847   constraints()->verify(placeholders());
2848 
2849   _pd_cache_table->verify();
2850 }
2851 
2852 // caller needs ResourceMark
2853 const char* SystemDictionary::loader_name(const oop loader) {
2854   return ((loader) == NULL ? "<bootloader>" :
2855           InstanceKlass::cast((loader)->klass())->name()->as_C_string());
2856 }
2857 
2858 // caller needs ResourceMark
2859 const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) {
2860   return (loader_data->class_loader() == NULL ? "<bootloader>" :
2861           SystemDictionary::loader_name(loader_data->class_loader()));
2862 }
< prev index next >