< prev index next >

src/share/vm/classfile/systemDictionary.cpp

Print this page




 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 
 115 // ----------------------------------------------------------------------------
 116 // Java-level SystemLoader
 117 
 118 oop SystemDictionary::java_system_loader() {
 119   return _java_system_loader;
 120 }
 121 
 122 void SystemDictionary::compute_java_system_loader(TRAPS) {
 123   KlassHandle system_klass(THREAD, WK_KLASS(ClassLoader_klass));
 124   JavaValue result(T_OBJECT);
 125   JavaCalls::call_static(&result,
 126                          KlassHandle(THREAD, WK_KLASS(ClassLoader_klass)),
 127                          vmSymbols::getSystemClassLoader_name(),
 128                          vmSymbols::void_classloader_signature(),
 129                          CHECK);
 130 
 131   _java_system_loader = (oop)result.get_jobject();
 132 
 133   CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)
 134 }
 135 
 136 
 137 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, TRAPS) {
 138   if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();
 139   return ClassLoaderDataGraph::find_or_create(class_loader, THREAD);
 140 }
 141 
 142 // ----------------------------------------------------------------------------
 143 // Parallel class loading check
 144 
 145 bool SystemDictionary::is_parallelCapable(Handle class_loader) {
 146   if (UnsyncloadClass || class_loader.is_null()) return true;


 167   return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() ||
 168           class_loader == _java_system_loader);
 169 }
 170 
 171 // Returns true if the passed class loader is the platform class loader.
 172 bool SystemDictionary::is_platform_class_loader(oop class_loader) {
 173   if (class_loader == NULL) {
 174     return false;
 175   }
 176   return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass());
 177 }
 178 
 179 // ----------------------------------------------------------------------------
 180 // Resolving of classes
 181 
 182 // Forwards to resolve_or_null
 183 
 184 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
 185   Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
 186   if (HAS_PENDING_EXCEPTION || klass == NULL) {
 187     KlassHandle k_h(THREAD, klass);
 188     // can return a null klass
 189     klass = handle_resolution_exception(class_name, throw_error, k_h, THREAD);
 190   }
 191   return klass;
 192 }
 193 
 194 Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name,
 195                                                      bool throw_error,
 196                                                      KlassHandle klass_h, TRAPS) {
 197   if (HAS_PENDING_EXCEPTION) {
 198     // If we have a pending exception we forward it to the caller, unless throw_error is true,
 199     // in which case we have to check whether the pending exception is a ClassNotFoundException,
 200     // and if so convert it to a NoClassDefFoundError
 201     // And chain the original ClassNotFoundException
 202     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
 203       ResourceMark rm(THREAD);
 204       assert(klass_h() == NULL, "Should not have result with exception pending");
 205       Handle e(THREAD, PENDING_EXCEPTION);
 206       CLEAR_PENDING_EXCEPTION;
 207       THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
 208     } else {
 209       return NULL;
 210     }
 211   }
 212   // Class not found, throw appropriate error or exception depending on value of throw_error
 213   if (klass_h() == NULL) {
 214     ResourceMark rm(THREAD);
 215     if (throw_error) {
 216       THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
 217     } else {
 218       THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
 219     }
 220   }
 221   return (Klass*)klass_h();
 222 }
 223 
 224 
 225 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,
 226                                            bool throw_error, TRAPS)
 227 {
 228   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
 229 }
 230 
 231 
 232 // Forwards to resolve_instance_class_or_null
 233 
 234 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
 235   assert(THREAD->can_call_java(),
 236          "can not load classes with compiler thread: class=%s, classloader=%s",
 237          class_name->as_C_string(),
 238          class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string());
 239   if (FieldType::is_array(class_name)) {
 240     return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD);
 241   } else if (FieldType::is_obj(class_name)) {


 385       }
 386     }
 387     if (!throw_circularity_error) {
 388       // Be careful not to exit resolve_super
 389       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
 390     }
 391   }
 392   if (throw_circularity_error) {
 393       ResourceMark rm(THREAD);
 394       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
 395   }
 396 
 397 // java.lang.Object should have been found above
 398   assert(class_name != NULL, "null super class for resolving");
 399   // Resolve the super class or interface, check results on return
 400   Klass* superk = SystemDictionary::resolve_or_null(class_name,
 401                                                  class_loader,
 402                                                  protection_domain,
 403                                                  THREAD);
 404 
 405   KlassHandle superk_h(THREAD, superk);
 406 
 407   // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
 408   // It is no longer necessary to keep the placeholder table alive until update_dictionary
 409   // or error. GC used to walk the placeholder table as strong roots.
 410   // The instanceKlass is kept alive because the class loader is on the stack,
 411   // which keeps the loader_data alive, as well as all instanceKlasses in
 412   // the loader_data. parseClassFile adds the instanceKlass to loader_data.
 413   {
 414     MutexLocker mu(SystemDictionary_lock, THREAD);
 415     placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
 416     SystemDictionary_lock->notify_all();
 417   }
 418   if (HAS_PENDING_EXCEPTION || superk_h() == NULL) {
 419     // can null superk
 420     superk_h = KlassHandle(THREAD, handle_resolution_exception(class_name, true, superk_h, THREAD));
 421   }
 422 
 423   return superk_h();
 424 }
 425 
 426 void SystemDictionary::validate_protection_domain(instanceKlassHandle klass,
 427                                                   Handle class_loader,
 428                                                   Handle protection_domain,
 429                                                   TRAPS) {
 430   if(!has_checkPackageAccess()) return;
 431 
 432   // Now we have to call back to java to check if the initating class has access
 433   JavaValue result(T_VOID);
 434   if (log_is_enabled(Debug, protectiondomain)) {
 435     ResourceMark rm;
 436     // Print out trace information
 437     outputStream* log = Log(protectiondomain)::debug_stream();
 438     log->print_cr("Checking package access");
 439     log->print("class loader: "); class_loader()->print_value_on(log);
 440     log->print(" protection domain: "); protection_domain()->print_value_on(log);
 441     log->print(" loading: "); klass()->print_value_on(log);
 442     log->cr();
 443   }
 444 
 445   KlassHandle system_loader(THREAD, SystemDictionary::ClassLoader_klass());
 446   JavaCalls::call_special(&result,
 447                          class_loader,
 448                          system_loader,
 449                          vmSymbols::checkPackageAccess_name(),
 450                          vmSymbols::class_protectiondomain_signature(),
 451                          Handle(THREAD, klass->java_mirror()),
 452                          protection_domain,
 453                          THREAD);
 454 
 455   if (HAS_PENDING_EXCEPTION) {
 456     log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
 457   } else {
 458    log_debug(protectiondomain)("granted");
 459   }
 460 
 461   if (HAS_PENDING_EXCEPTION) return;
 462 
 463   // If no exception has been thrown, we have validated the protection domain
 464   // Insert the protection domain of the initiating class into the set.
 465   {


 523   intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
 524   SystemDictionary_lock->wait();
 525   SystemDictionary_lock->unlock();
 526   ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
 527   SystemDictionary_lock->lock();
 528 }
 529 
 530 // If the class in is in the placeholder table, class loading is in progress
 531 // For cases where the application changes threads to load classes, it
 532 // is critical to ClassCircularity detection that we try loading
 533 // the superclass on the same thread internally, so we do parallel
 534 // super class loading here.
 535 // This also is critical in cases where the original thread gets stalled
 536 // even in non-circularity situations.
 537 // Note: must call resolve_super_or_fail even if null super -
 538 // to force placeholder entry creation for this class for circularity detection
 539 // Caller must check for pending exception
 540 // Returns non-null Klass* if other thread has completed load
 541 // and we are done,
 542 // If return null Klass* and no pending exception, the caller must load the class
 543 instanceKlassHandle SystemDictionary::handle_parallel_super_load(
 544     Symbol* name, Symbol* superclassname, Handle class_loader,
 545     Handle protection_domain, Handle lockObject, TRAPS) {
 546 
 547   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
 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_(nh));
 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     Klass* check = find_class(d_index, d_hash, name, loader_data);
 575     if (check != NULL) {
 576       // Klass is already loaded, so just return it
 577       return(instanceKlassHandle(THREAD, check));
 578     } else {
 579       return nh;
 580     }
 581   }
 582 
 583   // must loop to both handle other placeholder updates
 584   // and spurious notifications
 585   bool super_load_in_progress = true;
 586   PlaceholderEntry* placeholder;
 587   while (super_load_in_progress) {
 588     MutexLocker mu(SystemDictionary_lock, THREAD);
 589     // Check if classloading completed while we were loading superclass or waiting
 590     Klass* check = find_class(d_index, d_hash, name, loader_data);
 591     if (check != NULL) {
 592       // Klass is already loaded, so just return it
 593       return(instanceKlassHandle(THREAD, check));
 594     } else {
 595       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 596       if (placeholder && placeholder->super_load_in_progress() ){
 597         // Before UnsyncloadClass:
 598         // We only get here if the application has released the
 599         // classloader lock when another thread was in the middle of loading a
 600         // superclass/superinterface for this class, and now
 601         // this thread is also trying to load this class.
 602         // To minimize surprises, the first thread that started to
 603         // load a class should be the one to complete the loading
 604         // with the classfile it initially expected.
 605         // This logic has the current thread wait once it has done
 606         // all the superclass/superinterface loading it can, until
 607         // the original thread completes the class loading or fails
 608         // If it completes we will use the resulting InstanceKlass
 609         // which we will find below in the systemDictionary.
 610         // We also get here for parallel bootstrap classloader
 611         if (class_loader.is_null()) {
 612           SystemDictionary_lock->wait();
 613         } else {
 614           double_lock_wait(lockObject, THREAD);
 615         }
 616       } else {
 617         // If not in SD and not in PH, other thread's load must have failed
 618         super_load_in_progress = false;
 619       }
 620     }
 621   }
 622   return (nh);
 623 }
 624 
 625 static void post_class_load_event(const Ticks& start_time,
 626                                   instanceKlassHandle k,
 627                                   const ClassLoaderData* init_cld) {
 628 #if INCLUDE_TRACE
 629   EventClassLoad event(UNTIMED);
 630   if (event.should_commit()) {
 631     event.set_starttime(start_time);
 632     event.set_loadedClass(k());
 633     event.set_definingClassLoader(k->class_loader_data());
 634     event.set_initiatingClassLoader(init_cld);
 635     event.commit();
 636   }
 637 #endif // INCLUDE_TRACE
 638 }
 639 
 640 static void class_define_event(instanceKlassHandle k,
 641                                const ClassLoaderData* def_cld) {
 642 #if INCLUDE_TRACE
 643   EventClassDefine event;
 644   if (event.should_commit()) {
 645     event.set_definedClass(k());
 646     event.set_definingClassLoader(def_cld);
 647     event.commit();
 648   }
 649 #endif // INCLUDE_TRACE
 650 }
 651 
 652 // Be careful when modifying this code: once you have run
 653 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
 654 // you need to find_and_remove it before returning.
 655 // So be careful to not exit with a CHECK_ macro betweeen these calls.
 656 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
 657                                                         Handle class_loader,
 658                                                         Handle protection_domain,
 659                                                         TRAPS) {
 660   assert(name != NULL && !FieldType::is_array(name) &&
 661          !FieldType::is_obj(name), "invalid class name");
 662 
 663   Ticks class_load_start_time = Ticks::now();
 664 
 665   HandleMark hm(THREAD);


 691   // ParallelCapable Classloaders and the bootstrap classloader,
 692   // or all classloaders with UnsyncloadClass do not acquire lock here
 693   bool DoObjectLock = true;
 694   if (is_parallelCapable(class_loader)) {
 695     DoObjectLock = false;
 696   }
 697 
 698   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
 699   int p_index = placeholders()->hash_to_index(p_hash);
 700 
 701   // Class is not in SystemDictionary so we have to do loading.
 702   // Make sure we are synchronized on the class loader before we proceed
 703   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 704   check_loader_lock_contention(lockObject, THREAD);
 705   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 706 
 707   // Check again (after locking) if class already exist in SystemDictionary
 708   bool class_has_been_loaded   = false;
 709   bool super_load_in_progress  = false;
 710   bool havesupername = false;
 711   instanceKlassHandle k;
 712   PlaceholderEntry* placeholder;
 713   Symbol* superclassname = NULL;
 714 
 715   {
 716     MutexLocker mu(SystemDictionary_lock, THREAD);
 717     Klass* check = find_class(d_index, d_hash, name, loader_data);
 718     if (check != NULL) {
 719       // Klass is already loaded, so just return it
 720       class_has_been_loaded = true;
 721       k = instanceKlassHandle(THREAD, check);
 722     } else {
 723       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 724       if (placeholder && placeholder->super_load_in_progress()) {
 725          super_load_in_progress = true;
 726          if (placeholder->havesupername() == true) {
 727            superclassname = placeholder->supername();
 728            havesupername = true;
 729          }
 730       }
 731     }
 732   }
 733 
 734   // If the class is in the placeholder table, class loading is in progress
 735   if (super_load_in_progress && havesupername==true) {
 736     k = SystemDictionary::handle_parallel_super_load(name, superclassname,
 737         class_loader, protection_domain, lockObject, THREAD);



 738     if (HAS_PENDING_EXCEPTION) {
 739       return NULL;
 740     }
 741     if (!k.is_null()) {
 742       class_has_been_loaded = true;
 743     }
 744   }
 745 
 746   bool throw_circularity_error = false;
 747   if (!class_has_been_loaded) {
 748     bool load_instance_added = false;
 749 
 750     // add placeholder entry to record loading instance class
 751     // Five cases:
 752     // All cases need to prevent modifying bootclasssearchpath
 753     // in parallel with a classload of same classname
 754     // Redefineclasses uses existence of the placeholder for the duration
 755     // of the class load to prevent concurrent redefinition of not completely
 756     // defined classes.
 757     // case 1. traditional classloaders that rely on the classloader object lock
 758     //   - no other need for LOAD_INSTANCE
 759     // case 2. traditional classloaders that break the classloader object lock
 760     //    as a deadlock workaround. Detection of this case requires that
 761     //    this check is done while holding the classloader object lock,


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


1002     FieldArrayInfo fd;
1003     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
1004     if (t != T_OBJECT) {
1005       k = Universe::typeArrayKlassObj(t);
1006     } else {
1007       k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD);
1008     }
1009     if (k != NULL) {
1010       k = k->array_klass_or_null(fd.dimension());
1011     }
1012   } else {
1013     k = find(class_name, class_loader, protection_domain, THREAD);
1014   }
1015   return k;
1016 }
1017 
1018 // Note: this method is much like resolve_from_stream, but
1019 // does not publish the classes via the SystemDictionary.
1020 // Handles unsafe_DefineAnonymousClass and redefineclasses
1021 // RedefinedClasses do not add to the class hierarchy
1022 Klass* SystemDictionary::parse_stream(Symbol* class_name,
1023                                       Handle class_loader,
1024                                       Handle protection_domain,
1025                                       ClassFileStream* st,
1026                                       const InstanceKlass* host_klass,
1027                                       GrowableArray<Handle>* cp_patches,
1028                                       TRAPS) {
1029 
1030   Ticks class_load_start_time = Ticks::now();
1031 
1032   ClassLoaderData* loader_data;
1033   if (host_klass != NULL) {
1034     // Create a new CLD for anonymous class, that uses the same class loader
1035     // as the host_klass
1036     guarantee(host_klass->class_loader() == class_loader(), "should be the same");
1037     guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
1038     loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);
1039     loader_data->record_dependency(host_klass, CHECK_NULL);
1040   } else {
1041     loader_data = ClassLoaderData::class_loader_data(class_loader());
1042   }
1043 
1044   assert(st != NULL, "invariant");
1045   assert(st->need_verify(), "invariant");
1046 
1047   // Parse stream and create a klass.
1048   // Note that we do this even though this klass might
1049   // already be present in the SystemDictionary, otherwise we would not
1050   // throw potential ClassFormatErrors.
1051 
1052   instanceKlassHandle k = KlassFactory::create_from_stream(st,
1053                                                            class_name,
1054                                                            loader_data,
1055                                                            protection_domain,
1056                                                            host_klass,
1057                                                            cp_patches,
1058                                                            CHECK_NULL);
1059 
1060   if (host_klass != NULL && k.not_null()) {
1061     // If it's anonymous, initialize it now, since nobody else will.
1062 
1063     {
1064       MutexLocker mu_r(Compile_lock, THREAD);
1065 
1066       // Add to class hierarchy, initialize vtables, and do possible
1067       // deoptimizations.
1068       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
1069 
1070       // But, do not add to system dictionary.
1071 
1072       // compiled code dependencies need to be validated anyway
1073       notice_modification();
1074     }
1075 
1076     // Rewrite and patch constant pool here.
1077     k->link_class(CHECK_NULL);
1078     if (cp_patches != NULL) {
1079       k->constants()->patch_resolved_references(cp_patches);
1080     }
1081     k->eager_initialize(CHECK_NULL);
1082 
1083     // notify jvmti
1084     if (JvmtiExport::should_post_class_load()) {
1085         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1086         JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1087     }
1088 
1089     post_class_load_event(class_load_start_time, k, loader_data);
1090   }
1091   assert(host_klass != NULL || NULL == cp_patches,
1092          "cp_patches only found with host_klass");
1093 
1094   return k();
1095 }
1096 
1097 // Add a klass to the system from a stream (called by jni_DefineClass and
1098 // JVM_DefineClass).
1099 // Note: class_name can be NULL. In that case we do not know the name of
1100 // the class until we have parsed the stream.
1101 
1102 Klass* SystemDictionary::resolve_from_stream(Symbol* class_name,
1103                                              Handle class_loader,
1104                                              Handle protection_domain,
1105                                              ClassFileStream* st,
1106                                              TRAPS) {
1107 
1108   HandleMark hm(THREAD);
1109 
1110   // Classloaders that support parallelism, e.g. bootstrap classloader,
1111   // or all classloaders with UnsyncloadClass do not acquire lock here
1112   bool DoObjectLock = true;
1113   if (is_parallelCapable(class_loader)) {
1114     DoObjectLock = false;
1115   }
1116 
1117   ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL);
1118 
1119   // Make sure we are synchronized on the class loader before we proceed
1120   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1121   check_loader_lock_contention(lockObject, THREAD);
1122   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
1123 
1124   assert(st != NULL, "invariant");
1125 
1126   // Parse the stream and create a klass.
1127   // Note that we do this even though this klass might
1128   // already be present in the SystemDictionary, otherwise we would not
1129   // throw potential ClassFormatErrors.
1130   //
1131 
1132  instanceKlassHandle k;
1133 
1134 #if INCLUDE_CDS
1135   k = SystemDictionaryShared::lookup_from_stream(class_name,
1136                                                  class_loader,
1137                                                  protection_domain,
1138                                                  st,
1139                                                  CHECK_NULL);
1140 #endif
1141 
1142   if (k.is_null()) {
1143     if (st->buffer() == NULL) {
1144       return NULL;
1145     }
1146     k = KlassFactory::create_from_stream(st,
1147                                          class_name,
1148                                          loader_data,
1149                                          protection_domain,
1150                                          NULL, // host_klass
1151                                          NULL, // cp_patches
1152                                          CHECK_NULL);
1153   }
1154 
1155   assert(k.not_null(), "no klass created");
1156   Symbol* h_name = k->name();
1157   assert(class_name == NULL || class_name == h_name, "name mismatch");
1158 
1159   bool define_succeeded = false;
1160   // Add class just loaded
1161   // If a class loader supports parallel classloading handle parallel define requests
1162   // find_or_define_instance_class may return a different InstanceKlass
1163   if (is_parallelCapable(class_loader)) {
1164     instanceKlassHandle defined_k = find_or_define_instance_class(h_name, class_loader, k, CHECK_NULL);
1165     if (k() == defined_k()) {
1166       // we have won over other concurrent threads (if any) that are
1167       // competing to define the same class.
1168       define_succeeded = true;
1169     }
1170     k = defined_k;
1171   } else {
1172     define_instance_class(k, CHECK_NULL);
1173     define_succeeded = true;
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 Klass* 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 instanceKlassHandle SystemDictionary::load_shared_class(
1218                  Symbol* class_name, Handle class_loader, TRAPS) {
1219   instanceKlassHandle ik (THREAD, find_shared_class(class_name));
1220   // Make sure we only return the boot class for the NULL classloader.
1221   if (ik.not_null() &&
1222       ik->is_shared_boot_class() && class_loader.is_null()) {
1223     Handle protection_domain;
1224     return load_shared_class(ik, class_loader, protection_domain, THREAD);
1225   }
1226   return instanceKlassHandle();
1227 }
1228 
1229 // Check if a shared class can be loaded by the specific classloader:
1230 //
1231 // NULL classloader:
1232 //   - Module class from "modules" jimage. ModuleEntry must be defined in the classloader.
1233 //   - Class from -Xbootclasspath/a. The class has no defined PackageEntry, or must
1234 //     be defined in an unnamed module.
1235 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
1236                                                instanceKlassHandle ik,
1237                                                Handle class_loader, TRAPS) {
1238   assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
1239          "Cannot use sharing if java.base is patched");
1240   ResourceMark rm;
1241   int path_index = ik->shared_classpath_index();
1242   SharedClassPathEntry* ent =
1243             (SharedClassPathEntry*)FileMapInfo::shared_classpath(path_index);
1244   if (!Universe::is_module_initialized()) {
1245     assert(ent != NULL && ent->is_jrt(),
1246            "Loading non-bootstrap classes before the module system is initialized");
1247     assert(class_loader.is_null(), "sanity");
1248     return true;
1249   }
1250   // Get the pkg_entry from the classloader
1251   TempNewSymbol pkg_name = NULL;
1252   PackageEntry* pkg_entry = NULL;
1253   ModuleEntry* mod_entry = NULL;
1254   const char* pkg_string = NULL;
1255   ClassLoaderData* loader_data = class_loader_data(class_loader);
1256   pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false);


1293     if (!ent->is_jrt() && ik->is_shared_boot_class()) {
1294       // the class is from the -Xbootclasspath/a
1295       if (pkg_string == NULL ||
1296           pkg_entry == NULL ||
1297           pkg_entry->in_unnamed_module()) {
1298         assert(mod_entry == NULL ||
1299                mod_entry == loader_data->modules()->unnamed_module(),
1300                "the unnamed module is not defined in the classloader");
1301         return true;
1302       }
1303     }
1304     return false;
1305   } else {
1306     bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader(
1307               ik, class_loader, pkg_string, pkg_name,
1308               pkg_entry, mod_entry, CHECK_(false));
1309     return res;
1310   }
1311 }
1312 
1313 instanceKlassHandle SystemDictionary::load_shared_class(instanceKlassHandle ik,
1314                                                         Handle class_loader,
1315                                                         Handle protection_domain, TRAPS) {
1316   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1317 
1318   if (ik.not_null()) {
1319     Symbol* class_name = ik->name();
1320 
1321     bool visible = is_shared_class_visible(
1322                             class_name, ik, class_loader, CHECK_(nh));
1323     if (!visible) {
1324       return nh;
1325     }
1326 
1327     // Resolve the superclass and interfaces. They must be the same
1328     // as in dump time, because the layout of <ik> depends on
1329     // the specific layout of ik->super() and ik->local_interfaces().
1330     //
1331     // If unexpected superclass or interfaces are found, we cannot
1332     // load <ik> from the shared archive.
1333 
1334     if (ik->super() != NULL) {
1335       Symbol*  cn = ik->super()->name();
1336       Klass *s = resolve_super_or_fail(class_name, cn,
1337                                        class_loader, protection_domain, true, CHECK_(nh));
1338       if (s != ik->super()) {
1339         // The dynamically resolved super class is not the same as the one we used during dump time,
1340         // so we cannot use ik.
1341         return nh;
1342       } else {
1343         assert(s->is_shared(), "must be");
1344       }
1345     }
1346 
1347     Array<Klass*>* interfaces = ik->local_interfaces();
1348     int num_interfaces = interfaces->length();
1349     for (int index = 0; index < num_interfaces; index++) {
1350       Klass* k = interfaces->at(index);
1351 
1352       // Note: can not use InstanceKlass::cast here because
1353       // interfaces' InstanceKlass's C++ vtbls haven't been
1354       // reinitialized yet (they will be once the interface classes
1355       // are loaded)
1356       Symbol*  name  = k->name();
1357       Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_(nh));
1358       if (k != i) {
1359         // The dynamically resolved interface class is not the same as the one we used during dump time,
1360         // so we cannot use ik.
1361         return nh;
1362       } else {
1363         assert(i->is_shared(), "must be");
1364       }
1365     }
1366 
1367     instanceKlassHandle new_ik = KlassFactory::check_shared_class_file_load_hook(
1368         ik, class_name, class_loader, protection_domain, CHECK_(nh));
1369     if (new_ik.not_null()) {
1370       // The class is changed by CFLH. Return the new class. The shared class is
1371       // not used.
1372       return new_ik;
1373     }
1374 
1375     // Adjust methods to recover missing data.  They need addresses for
1376     // interpreter entry points and their default native method address
1377     // must be reset.
1378 
1379     // Updating methods must be done under a lock so multiple
1380     // threads don't update these in parallel
1381     //
1382     // Shared classes are all currently loaded by either the bootstrap or
1383     // internal parallel class loaders, so this will never cause a deadlock
1384     // on a custom class loader lock.
1385 
1386     ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1387     {
1388       HandleMark hm(THREAD);
1389       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1390       check_loader_lock_contention(lockObject, THREAD);
1391       ObjectLocker ol(lockObject, THREAD, true);
1392       // prohibited package check assumes all classes loaded from archive call
1393       // restore_unshareable_info which calls ik->set_package()
1394       ik->restore_unshareable_info(loader_data, protection_domain, CHECK_(nh));
1395     }
1396 
1397     if (log_is_enabled(Info, class, load)) {
1398       ik()->print_loading_log(LogLevel::Info, loader_data, NULL, NULL);
1399     }
1400     // No 'else' here as logging levels are not mutually exclusive
1401 
1402     if (log_is_enabled(Debug, class, load)) {
1403       ik()->print_loading_log(LogLevel::Debug, loader_data, NULL, NULL);
1404     }
1405 
1406     // For boot loader, ensure that GetSystemPackage knows that a class in this
1407     // package was loaded.
1408     if (class_loader.is_null()) {
1409       int path_index = ik->shared_classpath_index();
1410       ResourceMark rm;
1411       ClassLoader::add_package(ik->name()->as_C_string(), path_index, THREAD);
1412     }
1413 
1414     if (DumpLoadedClassList != NULL && classlist_file->is_open()) {
1415       // Only dump the classes that can be stored into CDS archive
1416       if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
1417         ResourceMark rm(THREAD);
1418         classlist_file->print_cr("%s", ik->name()->as_C_string());
1419         classlist_file->flush();
1420       }
1421     }
1422 
1423     // notify a class loaded from shared object
1424     ClassLoadingService::notify_class_loaded(ik(), true /* shared class */);
1425   }
1426 
1427   ik->set_has_passed_fingerprint_check(false);
1428   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
1429     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik());
1430     uint64_t cds_fp = ik->get_stored_fingerprint();
1431     if (aot_fp != 0 && aot_fp == cds_fp) {
1432       // This class matches with a class saved in an AOT library
1433       ik->set_has_passed_fingerprint_check(true);
1434     } else {
1435       ResourceMark rm;
1436       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT, ik->external_name(), aot_fp, cds_fp);
1437     }
1438   }
1439   return ik;
1440 }
1441 #endif // INCLUDE_CDS
1442 
1443 instanceKlassHandle SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
1444   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1445 
1446   if (class_loader.is_null()) {
1447     ResourceMark rm;
1448     PackageEntry* pkg_entry = NULL;
1449     bool search_only_bootloader_append = false;
1450     ClassLoaderData *loader_data = class_loader_data(class_loader);
1451 
1452     // Find the package in the boot loader's package entry table.
1453     TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_NULL);
1454     if (pkg_name != NULL) {
1455       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1456     }
1457 
1458     // Prior to attempting to load the class, enforce the boot loader's
1459     // visibility boundaries.
1460     if (!Universe::is_module_initialized()) {
1461       // During bootstrapping, prior to module initialization, any
1462       // class attempting to be loaded must be checked against the
1463       // java.base packages in the boot loader's PackageEntryTable.
1464       // No class outside of java.base is allowed to be loaded during
1465       // this bootstrapping window.
1466       if (!DumpSharedSpaces) {
1467         if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1468           // Class is either in the unnamed package or in
1469           // a named package within the unnamed module.  Either
1470           // case is outside of java.base, do not attempt to
1471           // load the class post java.base definition.  If
1472           // java.base has not been defined, let the class load
1473           // and its package will be checked later by
1474           // ModuleEntryTable::verify_javabase_packages.
1475           if (ModuleEntryTable::javabase_defined()) {
1476             return nh;
1477           }
1478         } else {
1479           // Check that the class' package is defined within java.base.
1480           ModuleEntry* mod_entry = pkg_entry->module();
1481           Symbol* mod_entry_name = mod_entry->name();
1482           if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1483             return nh;
1484           }
1485         }
1486       }
1487     } else {
1488       assert(!DumpSharedSpaces, "Archive dumped after module system initialization");
1489       // After the module system has been initialized, check if the class'
1490       // package is in a module defined to the boot loader.
1491       if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1492         // Class is either in the unnamed package, in a named package
1493         // within a module not defined to the boot loader or in a
1494         // a named package within the unnamed module.  In all cases,
1495         // limit visibility to search for the class only in the boot
1496         // loader's append path.
1497         search_only_bootloader_append = true;
1498       }
1499     }
1500 
1501     // Prior to bootstrapping's module initialization, never load a class outside
1502     // of the boot loader's module path
1503     assert(Universe::is_module_initialized() || DumpSharedSpaces ||
1504            !search_only_bootloader_append,
1505            "Attempt to load a class outside of boot loader's module path");
1506 
1507     // Search the shared system dictionary for classes preloaded into the
1508     // shared spaces.
1509     instanceKlassHandle k;
1510     {
1511 #if INCLUDE_CDS
1512       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1513       k = load_shared_class(class_name, class_loader, THREAD);
1514 #endif
1515     }
1516 
1517     if (k.is_null()) {
1518       // Use VM class loader
1519       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1520       k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_(nh));
1521     }
1522 
1523     // find_or_define_instance_class may return a different InstanceKlass
1524     if (!k.is_null()) {
1525       instanceKlassHandle defined_k =
1526         find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
1527       k = defined_k;
1528     }
1529     return k;
1530   } else {
1531     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1532     ResourceMark rm(THREAD);
1533 
1534     assert(THREAD->is_Java_thread(), "must be a JavaThread");
1535     JavaThread* jt = (JavaThread*) THREAD;
1536 
1537     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1538                                ClassLoader::perf_app_classload_selftime(),
1539                                ClassLoader::perf_app_classload_count(),
1540                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1541                                jt->get_thread_stat()->perf_timers_addr(),
1542                                PerfClassTraceTime::CLASS_LOAD);
1543 
1544     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nh));
1545     // Translate to external class name format, i.e., convert '/' chars to '.'
1546     Handle string = java_lang_String::externalize_classname(s, CHECK_(nh));
1547 
1548     JavaValue result(T_OBJECT);
1549 
1550     KlassHandle spec_klass (THREAD, SystemDictionary::ClassLoader_klass());
1551 
1552     // Call public unsynchronized loadClass(String) directly for all class loaders
1553     // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
1554     // acquire a class-name based lock rather than the class loader object lock.
1555     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
1556     // so the call to loadClassInternal() was not required.
1557     //
1558     // UnsyncloadClass flag means both call loadClass(String) and do
1559     // not acquire the class loader lock even for class loaders that are
1560     // not parallelCapable. This was a risky transitional
1561     // flag for diagnostic purposes only. It is risky to call
1562     // custom class loaders without synchronization.
1563     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1564     // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
1565     // Do NOT assume this will be supported in future releases.
1566     //
1567     // Added MustCallLoadClassInternal in case we discover in the field
1568     // a customer that counts on this call
1569     if (MustCallLoadClassInternal && has_loadClassInternal()) {
1570       JavaCalls::call_special(&result,
1571                               class_loader,
1572                               spec_klass,
1573                               vmSymbols::loadClassInternal_name(),
1574                               vmSymbols::string_class_signature(),
1575                               string,
1576                               CHECK_(nh));
1577     } else {
1578       JavaCalls::call_virtual(&result,
1579                               class_loader,
1580                               spec_klass,
1581                               vmSymbols::loadClass_name(),
1582                               vmSymbols::string_class_signature(),
1583                               string,
1584                               CHECK_(nh));
1585     }
1586 
1587     assert(result.get_type() == T_OBJECT, "just checking");
1588     oop obj = (oop) result.get_jobject();
1589 
1590     // Primitive classes return null since forName() can not be
1591     // used to obtain any of the Class objects representing primitives or void
1592     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1593       instanceKlassHandle k =
1594                 instanceKlassHandle(THREAD, java_lang_Class::as_Klass(obj));
1595       // For user defined Java class loaders, check that the name returned is
1596       // the same as that requested.  This check is done for the bootstrap
1597       // loader when parsing the class file.
1598       if (class_name == k->name()) {
1599         return k;
1600       }
1601     }
1602     // Class is not found or has the wrong name, return NULL
1603     return nh;
1604   }
1605 }
1606 
1607 void SystemDictionary::define_instance_class(instanceKlassHandle k, TRAPS) {
1608 
1609   HandleMark hm(THREAD);
1610   ClassLoaderData* loader_data = k->class_loader_data();
1611   Handle class_loader_h(THREAD, loader_data->class_loader());
1612 
1613  // for bootstrap and other parallel classloaders don't acquire lock,
1614  // use placeholder token
1615  // If a parallelCapable class loader calls define_instance_class instead of
1616  // find_or_define_instance_class to get here, we have a timing
1617  // hole with systemDictionary updates and check_constraints
1618  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1619     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1620          compute_loader_lock_object(class_loader_h, THREAD)),
1621          "define called without lock");
1622   }
1623 
1624   // Check class-loading constraints. Throw exception if violation is detected.
1625   // Grabs and releases SystemDictionary_lock
1626   // The check_constraints/find_class call and update_dictionary sequence
1627   // must be "atomic" for a specific class/classloader pair so we never


1652   {
1653     unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1654     int p_index = placeholders()->hash_to_index(p_hash);
1655 
1656     MutexLocker mu_r(Compile_lock, THREAD);
1657 
1658     // Add to class hierarchy, initialize vtables, and do possible
1659     // deoptimizations.
1660     add_to_hierarchy(k, CHECK); // No exception, but can block
1661 
1662     // Add to systemDictionary - so other classes can see it.
1663     // Grabs and releases SystemDictionary_lock
1664     update_dictionary(d_index, d_hash, p_index, p_hash,
1665                       k, class_loader_h, THREAD);
1666   }
1667   k->eager_initialize(THREAD);
1668 
1669   // notify jvmti
1670   if (JvmtiExport::should_post_class_load()) {
1671       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1672       JvmtiExport::post_class_load((JavaThread *) THREAD, k());
1673 
1674   }
1675   class_define_event(k, loader_data);
1676 }
1677 
1678 // Support parallel classloading
1679 // All parallel class loaders, including bootstrap classloader
1680 // lock a placeholder entry for this class/class_loader pair
1681 // to allow parallel defines of different classes for this class loader
1682 // With AllowParallelDefine flag==true, in case they do not synchronize around
1683 // FindLoadedClass/DefineClass, calls, we check for parallel
1684 // loading for them, wait if a defineClass is in progress
1685 // and return the initial requestor's results
1686 // This flag does not apply to the bootstrap classloader.
1687 // With AllowParallelDefine flag==false, call through to define_instance_class
1688 // which will throw LinkageError: duplicate class definition.
1689 // False is the requested default.
1690 // For better performance, the class loaders should synchronize
1691 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1692 // potentially waste time reading and parsing the bytestream.
1693 // Note: VM callers should ensure consistency of k/class_name,class_loader
1694 // Be careful when modifying this code: once you have run
1695 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1696 // you need to find_and_remove it before returning.
1697 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1698 instanceKlassHandle SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader, instanceKlassHandle k, TRAPS) {

1699 
1700   instanceKlassHandle nh = instanceKlassHandle(); // null Handle
1701   Symbol*  name_h = k->name(); // passed in class_name may be null
1702   ClassLoaderData* loader_data = class_loader_data(class_loader);
1703 
1704   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1705   int d_index = dictionary()->hash_to_index(d_hash);
1706 
1707 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1708   unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1709   int p_index = placeholders()->hash_to_index(p_hash);
1710   PlaceholderEntry* probe;
1711 
1712   {
1713     MutexLocker mu(SystemDictionary_lock, THREAD);
1714     // First check if class already defined
1715     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1716       Klass* check = find_class(d_index, d_hash, name_h, loader_data);
1717       if (check != NULL) {
1718         return(instanceKlassHandle(THREAD, check));
1719       }
1720     }
1721 
1722     // Acquire define token for this class/classloader
1723     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1724     // Wait if another thread defining in parallel
1725     // All threads wait - even those that will throw duplicate class: otherwise
1726     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1727     // if other thread has not finished updating dictionary
1728     while (probe->definer() != NULL) {
1729       SystemDictionary_lock->wait();
1730     }
1731     // Only special cases allow parallel defines and can use other thread's results
1732     // Other cases fall through, and may run into duplicate defines
1733     // caught by finding an entry in the SystemDictionary
1734     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1735         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1736         SystemDictionary_lock->notify_all();
1737 #ifdef ASSERT
1738         Klass* check = find_class(d_index, d_hash, name_h, loader_data);
1739         assert(check != NULL, "definer missed recording success");
1740 #endif
1741         return(instanceKlassHandle(THREAD, probe->instance_klass()));
1742     } else {
1743       // This thread will define the class (even if earlier thread tried and had an error)
1744       probe->set_definer(THREAD);
1745     }
1746   }
1747 
1748   define_instance_class(k, THREAD);
1749 
1750   Handle linkage_exception = Handle(); // null handle
1751 
1752   // definer must notify any waiting threads
1753   {
1754     MutexLocker mu(SystemDictionary_lock, THREAD);
1755     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1756     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1757     if (probe != NULL) {
1758       if (HAS_PENDING_EXCEPTION) {
1759         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1760         CLEAR_PENDING_EXCEPTION;
1761       } else {
1762         probe->set_instance_klass(k());
1763       }
1764       probe->set_definer(NULL);
1765       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1766       SystemDictionary_lock->notify_all();
1767     }
1768   }
1769 
1770   // Can't throw exception while holding lock due to rank ordering
1771   if (linkage_exception() != NULL) {
1772     THROW_OOP_(linkage_exception(), nh); // throws exception and returns
1773   }
1774 
1775   return k;
1776 }
1777 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1778   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1779   if (class_loader.is_null()) {
1780     return Handle(THREAD, _system_loader_lock_obj);
1781   } else {
1782     return class_loader;
1783   }
1784 }
1785 
1786 // This method is added to check how often we have to wait to grab loader
1787 // lock. The results are being recorded in the performance counters defined in
1788 // ClassLoader::_sync_systemLoaderLockContentionRate and
1789 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1790 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1791   if (!UsePerfData) {
1792     return;
1793   }
1794 
1795   assert(!loader_lock.is_null(), "NULL lock object");
1796 
1797   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1798       == ObjectSynchronizer::owner_other) {
1799     // contention will likely happen, so increment the corresponding
1800     // contention counter.
1801     if (loader_lock() == _system_loader_lock_obj) {
1802       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1803     } else {
1804       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1805     }
1806   }
1807 }
1808 
1809 // ----------------------------------------------------------------------------
1810 // Lookup
1811 
1812 Klass* SystemDictionary::find_class(int index, unsigned int hash,
1813                                       Symbol* class_name,
1814                                       ClassLoaderData* loader_data) {
1815   assert_locked_or_safepoint(SystemDictionary_lock);
1816   assert (index == dictionary()->index_for(class_name, loader_data),
1817           "incorrect index?");
1818 
1819   Klass* k = dictionary()->find_class(index, hash, class_name, loader_data);
1820   return k;
1821 }
1822 
1823 
1824 // Basic find on classes in the midst of being loaded
1825 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1826                                            ClassLoaderData* loader_data) {
1827   assert_locked_or_safepoint(SystemDictionary_lock);
1828   unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
1829   int p_index = placeholders()->hash_to_index(p_hash);
1830   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1831 }
1832 
1833 
1834 // Used for assertions and verification only
1835 Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1836   #ifndef ASSERT
1837   guarantee(VerifyBeforeGC      ||
1838             VerifyDuringGC      ||
1839             VerifyBeforeExit    ||
1840             VerifyDuringStartup ||
1841             VerifyAfterGC, "too expensive");
1842   #endif
1843   assert_locked_or_safepoint(SystemDictionary_lock);
1844 
1845   // First look in the loaded class array
1846   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
1847   int d_index = dictionary()->hash_to_index(d_hash);
1848   return find_class(d_index, d_hash, class_name, loader_data);
1849 }
1850 
1851 
1852 // Get the next class in the dictionary.
1853 Klass* SystemDictionary::try_get_next_class() {
1854   return dictionary()->try_get_next_class();
1855 }
1856 
1857 
1858 // ----------------------------------------------------------------------------
1859 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1860 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1861 // before a new class is used.
1862 
1863 void SystemDictionary::add_to_hierarchy(instanceKlassHandle k, TRAPS) {
1864   assert(k.not_null(), "just checking");
1865   assert_locked_or_safepoint(Compile_lock);
1866 
1867   // Link into hierachy. Make sure the vtables are initialized before linking into
1868   k->append_to_sibling_list();                    // add to superklass/sibling list
1869   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1870   k->set_init_state(InstanceKlass::loaded);
1871   // Now flush all code that depended on old class hierarchy.
1872   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1873   // Also, first reinitialize vtable because it may have gotten out of synch
1874   // while the new class wasn't connected to the class hierarchy.
1875   CodeCache::flush_dependents_on(k);
1876 }
1877 
1878 // ----------------------------------------------------------------------------
1879 // GC support
1880 
1881 // Following roots during mark-sweep is separated in two phases.
1882 //
1883 // The first phase follows preloaded classes and all other system
1884 // classes, since these will never get unloaded anyway.


2125     initialize_wk_klass((WKID)id, opt, CHECK);
2126   }
2127 
2128   // move the starting value forward to the limit:
2129   start_id = limit_id;
2130 }
2131 
2132 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
2133   assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
2134 
2135   // Create the ModuleEntry for java.base.  This call needs to be done here,
2136   // after vmSymbols::initialize() is called but before any classes are pre-loaded.
2137   ClassLoader::classLoader_init2(CHECK);
2138 
2139   // Preload commonly used klasses
2140   WKID scan = FIRST_WKID;
2141   // first do Object, then String, Class
2142   if (UseSharedSpaces) {
2143     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
2144     // Initialize the constant pool for the Object_class
2145     InstanceKlass* ik = InstanceKlass::cast(Object_klass());
2146     ik->constants()->restore_unshareable_info(CHECK);
2147     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2148   } else {
2149     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2150   }
2151 
2152   // Calculate offsets for String and Class classes since they are loaded and
2153   // can be used after this point.
2154   java_lang_String::compute_offsets();
2155   java_lang_Class::compute_offsets();
2156 
2157   // Fixup mirrors for classes loaded before java.lang.Class.
2158   // These calls iterate over the objects currently in the perm gen
2159   // so calling them at this point is matters (not before when there
2160   // are fewer objects and not later after there are more objects
2161   // in the perm gen.
2162   Universe::initialize_basic_type_mirrors(CHECK);
2163   Universe::fixup_mirrors(CHECK);
2164 
2165   // do a bunch more:
2166   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);


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


2390     FieldArrayInfo fd;
2391     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2392     // primitive types always pass
2393     if (t != T_OBJECT) {
2394       return true;
2395     } else {
2396       constraint_name = fd.object_key();
2397     }
2398   }
2399   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
2400   int d_index1 = dictionary()->hash_to_index(d_hash1);
2401 
2402   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
2403   int d_index2 = dictionary()->hash_to_index(d_hash2);
2404   {
2405   MutexLocker mu_s(SystemDictionary_lock, THREAD);
2406 
2407   // Better never do a GC while we're holding these oops
2408   NoSafepointVerifier nosafepoint;
2409 
2410   Klass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
2411   Klass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
2412   return constraints()->add_entry(constraint_name, klass1, class_loader1,
2413                                   klass2, class_loader2);
2414   }
2415 }
2416 
2417 // Add entry to resolution error table to record the error when the first
2418 // attempt to resolve a reference to a class has failed.
2419 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2420                                             Symbol* error, Symbol* message) {
2421   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2422   int index = resolution_errors()->hash_to_index(hash);
2423   {
2424     MutexLocker ml(SystemDictionary_lock, Thread::current());
2425     resolution_errors()->add_entry(index, hash, pool, which, error, message);
2426   }
2427 }
2428 
2429 // Delete a resolution error for RedefineClasses for a constant pool is going away
2430 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2431   resolution_errors()->delete_entry(pool);


2551     // if a racing thread has managed to install one at the same time.
2552     {
2553       MutexLocker ml(SystemDictionary_lock, THREAD);
2554       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2555       if (spe == NULL)
2556         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
2557       if (spe->method() == NULL)
2558         spe->set_method(m());
2559     }
2560   }
2561 
2562   assert(spe != NULL && spe->method() != NULL, "");
2563   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2564          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
2565          "MH intrinsic invariant");
2566   return spe->method();
2567 }
2568 
2569 // Helper for unpacking the return value from linkMethod and linkCallSite.
2570 static methodHandle unpack_method_and_appendix(Handle mname,
2571                                                KlassHandle accessing_klass,
2572                                                objArrayHandle appendix_box,
2573                                                Handle* appendix_result,
2574                                                TRAPS) {
2575   methodHandle empty;
2576   if (mname.not_null()) {
2577     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
2578     if (vmtarget != NULL && vmtarget->is_method()) {
2579       Method* m = (Method*)vmtarget;
2580       oop appendix = appendix_box->obj_at(0);
2581       if (TraceMethodHandles) {
2582     #ifndef PRODUCT
2583         ttyLocker ttyl;
2584         tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2585         m->print();
2586         if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
2587         tty->cr();
2588     #endif //PRODUCT
2589       }
2590       (*appendix_result) = Handle(THREAD, appendix);
2591       // the target is stored in the cpCache and if a reference to this
2592       // MethodName is dropped we need a way to make sure the
2593       // class_loader containing this method is kept alive.
2594       // FIXME: the appendix might also preserve this dependency.
2595       ClassLoaderData* this_key = InstanceKlass::cast(accessing_klass())->class_loader_data();
2596       this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM
2597       return methodHandle(THREAD, m);
2598     }
2599   }
2600   THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);
2601   return empty;
2602 }
2603 
2604 methodHandle SystemDictionary::find_method_handle_invoker(KlassHandle klass,
2605                                                           Symbol* name,
2606                                                           Symbol* signature,
2607                                                           KlassHandle accessing_klass,
2608                                                           Handle *appendix_result,
2609                                                           Handle *method_type_result,
2610                                                           TRAPS) {
2611   methodHandle empty;
2612   assert(THREAD->can_call_java() ,"");
2613   Handle method_type =
2614     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));
2615 
2616   int ref_kind = JVM_REF_invokeVirtual;
2617   oop name_oop = StringTable::intern(name, CHECK_(empty));
2618   Handle name_str (THREAD, name_oop);
2619   objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2620   assert(appendix_box->obj_at(0) == NULL, "");
2621 
2622   // This should not happen.  JDK code should take care of that.
2623   if (accessing_klass.is_null() || method_type.is_null()) {
2624     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty);
2625   }
2626 
2627   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2628   JavaCallArguments args;
2629   args.push_oop(Handle(THREAD, accessing_klass()->java_mirror()));
2630   args.push_int(ref_kind);
2631   args.push_oop(Handle(THREAD, klass()->java_mirror()));
2632   args.push_oop(name_str);
2633   args.push_oop(method_type);
2634   args.push_oop(appendix_box);
2635   JavaValue result(T_OBJECT);
2636   JavaCalls::call_static(&result,
2637                          SystemDictionary::MethodHandleNatives_klass(),
2638                          vmSymbols::linkMethod_name(),
2639                          vmSymbols::linkMethod_signature(),
2640                          &args, CHECK_(empty));
2641   Handle mname(THREAD, (oop) result.get_jobject());
2642   (*method_type_result) = method_type;
2643   return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2644 }
2645 
2646 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2647 // We must ensure that all class loaders everywhere will reach this class, for any client.
2648 // This is a safe bet for public classes in java.lang, such as Object and String.
2649 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2650 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
2651 static bool is_always_visible_class(oop mirror) {
2652   Klass* klass = java_lang_Class::as_Klass(mirror);
2653   if (klass->is_objArray_klass()) {
2654     klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2655   }
2656   if (klass->is_typeArray_klass()) {
2657     return true; // primitive array
2658   }
2659   assert(klass->is_instance_klass(), "%s", klass->external_name());
2660   return klass->is_public() &&
2661          (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
2662           InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
2663 }
2664 
2665 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2666 // signature, as interpreted relative to the given class loader.
2667 // Because of class loader constraints, all method handle usage must be
2668 // consistent with this loader.
2669 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2670                                                  KlassHandle accessing_klass,
2671                                                  TRAPS) {
2672   Handle empty;
2673   vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
2674   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
2675   int          index = invoke_method_table()->hash_to_index(hash);
2676   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2677   if (spe != NULL && spe->method_type() != NULL) {
2678     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
2679     return Handle(THREAD, spe->method_type());
2680   } else if (!THREAD->can_call_java()) {
2681     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
2682     return Handle();  // do not attempt from within compiler, unless it was cached
2683   }
2684 
2685   Handle class_loader, protection_domain;
2686   if (accessing_klass.not_null()) {
2687     class_loader      = Handle(THREAD, InstanceKlass::cast(accessing_klass())->class_loader());
2688     protection_domain = Handle(THREAD, InstanceKlass::cast(accessing_klass())->protection_domain());
2689   }
2690   bool can_be_cached = true;
2691   int npts = ArgumentCount(signature).size();
2692   objArrayHandle pts = oopFactory::new_objArray_handle(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2693   int arg = 0;
2694   Handle rt; // the return type from the signature
2695   ResourceMark rm(THREAD);
2696   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2697     oop mirror = NULL;
2698     if (can_be_cached) {
2699       // Use neutral class loader to lookup candidate classes to be placed in the cache.
2700       mirror = ss.as_java_mirror(Handle(), Handle(),
2701                                  SignatureStream::ReturnNull, CHECK_(empty));
2702       if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {
2703         // Fall back to accessing_klass context.
2704         can_be_cached = false;
2705       }
2706     }
2707     if (!can_be_cached) {
2708       // Resolve, throwing a real error if it doesn't work.
2709       mirror = ss.as_java_mirror(class_loader, protection_domain,
2710                                  SignatureStream::NCDFError, CHECK_(empty));
2711     }
2712     assert(!oopDesc::is_null(mirror), "%s", ss.as_symbol(THREAD)->as_C_string());
2713     if (ss.at_return_type())
2714       rt = Handle(THREAD, mirror);
2715     else
2716       pts->obj_at_put(arg++, mirror);
2717 
2718     // Check accessibility.
2719     if (ss.is_object() && accessing_klass.not_null()) {
2720       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2721       mirror = NULL;  // safety
2722       // Emulate ConstantPool::verify_constant_pool_resolve.
2723       if (sel_klass->is_objArray_klass())
2724         sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();
2725       if (sel_klass->is_instance_klass()) {
2726         KlassHandle sel_kh(THREAD, sel_klass);
2727         LinkResolver::check_klass_accessability(accessing_klass, sel_kh, CHECK_(empty));
2728       }
2729     }
2730   }
2731   assert(arg == npts, "");
2732 
2733   // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType
2734   JavaCallArguments args(Handle(THREAD, rt()));
2735   args.push_oop(pts);
2736   JavaValue result(T_OBJECT);
2737   JavaCalls::call_static(&result,
2738                          SystemDictionary::MethodHandleNatives_klass(),
2739                          vmSymbols::findMethodHandleType_name(),
2740                          vmSymbols::findMethodHandleType_signature(),
2741                          &args, CHECK_(empty));
2742   Handle method_type(THREAD, (oop) result.get_jobject());
2743 
2744   if (can_be_cached) {
2745     // We can cache this MethodType inside the JVM.
2746     MutexLocker ml(SystemDictionary_lock, THREAD);
2747     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2748     if (spe == NULL)
2749       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2750     if (spe->method_type() == NULL) {
2751       spe->set_method_type(method_type());
2752     }
2753   }
2754 
2755   // report back to the caller with the MethodType
2756   return method_type;
2757 }
2758 
2759 // Ask Java code to find or construct a method handle constant.
2760 Handle SystemDictionary::link_method_handle_constant(KlassHandle caller,
2761                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
2762                                                      KlassHandle callee,
2763                                                      Symbol* name_sym,
2764                                                      Symbol* signature,
2765                                                      TRAPS) {
2766   Handle empty;
2767   Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty));
2768   Handle type;
2769   if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
2770     type = find_method_handle_type(signature, caller, CHECK_(empty));
2771   } else if (caller.is_null()) {
2772     // This should not happen.  JDK code should take care of that.
2773     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2774   } else {
2775     ResourceMark rm(THREAD);
2776     SignatureStream ss(signature, false);
2777     if (!ss.is_done()) {
2778       oop mirror = ss.as_java_mirror(Handle(THREAD, caller->class_loader()),
2779                                      Handle(THREAD, caller->protection_domain()),
2780                                      SignatureStream::NCDFError, CHECK_(empty));
2781       type = Handle(THREAD, mirror);
2782       ss.next();
2783       if (!ss.is_done())  type = Handle();  // error!
2784     }
2785   }
2786   if (type.is_null()) {
2787     THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
2788   }
2789 
2790   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2791   JavaCallArguments args;
2792   args.push_oop(Handle(THREAD, caller->java_mirror()));  // the referring class
2793   args.push_int(ref_kind);
2794   args.push_oop(Handle(THREAD, callee->java_mirror()));  // the target class
2795   args.push_oop(name);
2796   args.push_oop(type);
2797   JavaValue result(T_OBJECT);
2798   JavaCalls::call_static(&result,
2799                          SystemDictionary::MethodHandleNatives_klass(),
2800                          vmSymbols::linkMethodHandleConstant_name(),
2801                          vmSymbols::linkMethodHandleConstant_signature(),
2802                          &args, CHECK_(empty));
2803   return Handle(THREAD, (oop) result.get_jobject());
2804 }
2805 
2806 // Ask Java code to find or construct a java.lang.invoke.CallSite for the given
2807 // name and signature, as interpreted relative to the given class loader.
2808 methodHandle SystemDictionary::find_dynamic_call_site_invoker(KlassHandle caller,
2809                                                               Handle bootstrap_specifier,
2810                                                               Symbol* name,
2811                                                               Symbol* type,
2812                                                               Handle *appendix_result,
2813                                                               Handle *method_type_result,
2814                                                               TRAPS) {
2815   methodHandle empty;
2816   Handle bsm, info;
2817   if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) {
2818     bsm = bootstrap_specifier;
2819   } else {
2820     assert(bootstrap_specifier->is_objArray(), "");
2821     objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier());
2822     int len = args->length();
2823     assert(len >= 1, "");
2824     bsm = Handle(THREAD, args->obj_at(0));
2825     if (len > 1) {
2826       objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));
2827       for (int i = 1; i < len; i++)
2828         args1->obj_at_put(i-1, args->obj_at(i));
2829       info = Handle(THREAD, args1);
2830     }
2831   }
2832   guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()),
2833             "caller must supply a valid BSM");
2834 
2835   Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty));
2836   Handle method_type = find_method_handle_type(type, caller, CHECK_(empty));
2837 
2838   // This should not happen.  JDK code should take care of that.
2839   if (caller.is_null() || method_type.is_null()) {
2840     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty);
2841   }
2842 
2843   objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2844   assert(appendix_box->obj_at(0) == NULL, "");
2845 
2846   // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2847   JavaCallArguments args;
2848   args.push_oop(Handle(THREAD, caller->java_mirror()));
2849   args.push_oop(bsm);
2850   args.push_oop(method_name);
2851   args.push_oop(method_type);
2852   args.push_oop(info);
2853   args.push_oop(appendix_box);
2854   JavaValue result(T_OBJECT);
2855   JavaCalls::call_static(&result,
2856                          SystemDictionary::MethodHandleNatives_klass(),
2857                          vmSymbols::linkCallSite_name(),
2858                          vmSymbols::linkCallSite_signature(),
2859                          &args, CHECK_(empty));




 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 
 115 // ----------------------------------------------------------------------------
 116 // Java-level SystemLoader
 117 
 118 oop SystemDictionary::java_system_loader() {
 119   return _java_system_loader;
 120 }
 121 
 122 void SystemDictionary::compute_java_system_loader(TRAPS) {
 123   Klass* system_klass = WK_KLASS(ClassLoader_klass);
 124   JavaValue result(T_OBJECT);
 125   JavaCalls::call_static(&result,
 126                          WK_KLASS(ClassLoader_klass),
 127                          vmSymbols::getSystemClassLoader_name(),
 128                          vmSymbols::void_classloader_signature(),
 129                          CHECK);
 130 
 131   _java_system_loader = (oop)result.get_jobject();
 132 
 133   CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)
 134 }
 135 
 136 
 137 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, TRAPS) {
 138   if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();
 139   return ClassLoaderDataGraph::find_or_create(class_loader, THREAD);
 140 }
 141 
 142 // ----------------------------------------------------------------------------
 143 // Parallel class loading check
 144 
 145 bool SystemDictionary::is_parallelCapable(Handle class_loader) {
 146   if (UnsyncloadClass || class_loader.is_null()) return true;


 167   return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() ||
 168           class_loader == _java_system_loader);
 169 }
 170 
 171 // Returns true if the passed class loader is the platform class loader.
 172 bool SystemDictionary::is_platform_class_loader(oop class_loader) {
 173   if (class_loader == NULL) {
 174     return false;
 175   }
 176   return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass());
 177 }
 178 
 179 // ----------------------------------------------------------------------------
 180 // Resolving of classes
 181 
 182 // Forwards to resolve_or_null
 183 
 184 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
 185   Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
 186   if (HAS_PENDING_EXCEPTION || klass == NULL) {

 187     // can return a null klass
 188     klass = handle_resolution_exception(class_name, throw_error, klass, THREAD);
 189   }
 190   return klass;
 191 }
 192 
 193 Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name,
 194                                                      bool throw_error,
 195                                                      Klass* klass, TRAPS) {
 196   if (HAS_PENDING_EXCEPTION) {
 197     // If we have a pending exception we forward it to the caller, unless throw_error is true,
 198     // in which case we have to check whether the pending exception is a ClassNotFoundException,
 199     // and if so convert it to a NoClassDefFoundError
 200     // And chain the original ClassNotFoundException
 201     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
 202       ResourceMark rm(THREAD);
 203       assert(klass == NULL, "Should not have result with exception pending");
 204       Handle e(THREAD, PENDING_EXCEPTION);
 205       CLEAR_PENDING_EXCEPTION;
 206       THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
 207     } else {
 208       return NULL;
 209     }
 210   }
 211   // Class not found, throw appropriate error or exception depending on value of throw_error
 212   if (klass == NULL) {
 213     ResourceMark rm(THREAD);
 214     if (throw_error) {
 215       THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
 216     } else {
 217       THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
 218     }
 219   }
 220   return klass;
 221 }
 222 
 223 
 224 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,
 225                                            bool throw_error, TRAPS)
 226 {
 227   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
 228 }
 229 
 230 
 231 // Forwards to resolve_instance_class_or_null
 232 
 233 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
 234   assert(THREAD->can_call_java(),
 235          "can not load classes with compiler thread: class=%s, classloader=%s",
 236          class_name->as_C_string(),
 237          class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string());
 238   if (FieldType::is_array(class_name)) {
 239     return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD);
 240   } else if (FieldType::is_obj(class_name)) {


 384       }
 385     }
 386     if (!throw_circularity_error) {
 387       // Be careful not to exit resolve_super
 388       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, class_name, THREAD);
 389     }
 390   }
 391   if (throw_circularity_error) {
 392       ResourceMark rm(THREAD);
 393       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
 394   }
 395 
 396 // java.lang.Object should have been found above
 397   assert(class_name != NULL, "null super class for resolving");
 398   // Resolve the super class or interface, check results on return
 399   Klass* superk = SystemDictionary::resolve_or_null(class_name,
 400                                                     class_loader,
 401                                                     protection_domain,
 402                                                     THREAD);
 403 


 404   // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
 405   // It is no longer necessary to keep the placeholder table alive until update_dictionary
 406   // or error. GC used to walk the placeholder table as strong roots.
 407   // The instanceKlass is kept alive because the class loader is on the stack,
 408   // which keeps the loader_data alive, as well as all instanceKlasses in
 409   // the loader_data. parseClassFile adds the instanceKlass to loader_data.
 410   {
 411     MutexLocker mu(SystemDictionary_lock, THREAD);
 412     placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
 413     SystemDictionary_lock->notify_all();
 414   }
 415   if (HAS_PENDING_EXCEPTION || superk == NULL) {
 416     // can null superk
 417     superk = handle_resolution_exception(class_name, true, superk, THREAD);
 418   }
 419 
 420   return superk;
 421 }
 422 
 423 void SystemDictionary::validate_protection_domain(InstanceKlass* klass,
 424                                                   Handle class_loader,
 425                                                   Handle protection_domain,
 426                                                   TRAPS) {
 427   if(!has_checkPackageAccess()) return;
 428 
 429   // Now we have to call back to java to check if the initating class has access
 430   JavaValue result(T_VOID);
 431   if (log_is_enabled(Debug, protectiondomain)) {
 432     ResourceMark rm;
 433     // Print out trace information
 434     outputStream* log = Log(protectiondomain)::debug_stream();
 435     log->print_cr("Checking package access");
 436     log->print("class loader: "); class_loader()->print_value_on(log);
 437     log->print(" protection domain: "); protection_domain()->print_value_on(log);
 438     log->print(" loading: "); klass->print_value_on(log);
 439     log->cr();
 440   }
 441 
 442   InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass();
 443   JavaCalls::call_special(&result,
 444                          class_loader,
 445                          system_loader,
 446                          vmSymbols::checkPackageAccess_name(),
 447                          vmSymbols::class_protectiondomain_signature(),
 448                          Handle(THREAD, klass->java_mirror()),
 449                          protection_domain,
 450                          THREAD);
 451 
 452   if (HAS_PENDING_EXCEPTION) {
 453     log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
 454   } else {
 455    log_debug(protectiondomain)("granted");
 456   }
 457 
 458   if (HAS_PENDING_EXCEPTION) return;
 459 
 460   // If no exception has been thrown, we have validated the protection domain
 461   // Insert the protection domain of the initiating class into the set.
 462   {


 520   intptr_t recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
 521   SystemDictionary_lock->wait();
 522   SystemDictionary_lock->unlock();
 523   ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
 524   SystemDictionary_lock->lock();
 525 }
 526 
 527 // If the class in is in the placeholder table, class loading is in progress
 528 // For cases where the application changes threads to load classes, it
 529 // is critical to ClassCircularity detection that we try loading
 530 // the superclass on the same thread internally, so we do parallel
 531 // super class loading here.
 532 // This also is critical in cases where the original thread gets stalled
 533 // even in non-circularity situations.
 534 // Note: must call resolve_super_or_fail even if null super -
 535 // to force placeholder entry creation for this class for circularity detection
 536 // Caller must check for pending exception
 537 // Returns non-null Klass* if other thread has completed load
 538 // and we are done,
 539 // If return null Klass* and no pending exception, the caller must load the class
 540 InstanceKlass* SystemDictionary::handle_parallel_super_load(
 541     Symbol* name, Symbol* superclassname, Handle class_loader,
 542     Handle protection_domain, Handle lockObject, TRAPS) {
 543 

 544   ClassLoaderData* loader_data = class_loader_data(class_loader);
 545   unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
 546   int d_index = dictionary()->hash_to_index(d_hash);
 547   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
 548   int p_index = placeholders()->hash_to_index(p_hash);
 549 
 550   // superk is not used, resolve_super called for circularity check only
 551   // This code is reached in two situations. One if this thread
 552   // is loading the same class twice (e.g. ClassCircularity, or
 553   // java.lang.instrument).
 554   // The second is if another thread started the resolve_super first
 555   // and has not yet finished.
 556   // In both cases the original caller will clean up the placeholder
 557   // entry on error.
 558   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
 559                                                           superclassname,
 560                                                           class_loader,
 561                                                           protection_domain,
 562                                                           true,
 563                                                           CHECK_NULL);
 564 
 565   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
 566   // Serial class loaders and bootstrap classloader do wait for superclass loads
 567  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
 568     MutexLocker mu(SystemDictionary_lock, THREAD);
 569     // Check if classloading completed while we were loading superclass or waiting
 570     return find_class(d_index, d_hash, name, loader_data);






 571   }
 572 
 573   // must loop to both handle other placeholder updates
 574   // and spurious notifications
 575   bool super_load_in_progress = true;
 576   PlaceholderEntry* placeholder;
 577   while (super_load_in_progress) {
 578     MutexLocker mu(SystemDictionary_lock, THREAD);
 579     // Check if classloading completed while we were loading superclass or waiting
 580     InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
 581     if (check != NULL) {
 582       // Klass is already loaded, so just return it
 583       return check;
 584     } else {
 585       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 586       if (placeholder && placeholder->super_load_in_progress() ){
 587         // Before UnsyncloadClass:
 588         // We only get here if the application has released the
 589         // classloader lock when another thread was in the middle of loading a
 590         // superclass/superinterface for this class, and now
 591         // this thread is also trying to load this class.
 592         // To minimize surprises, the first thread that started to
 593         // load a class should be the one to complete the loading
 594         // with the classfile it initially expected.
 595         // This logic has the current thread wait once it has done
 596         // all the superclass/superinterface loading it can, until
 597         // the original thread completes the class loading or fails
 598         // If it completes we will use the resulting InstanceKlass
 599         // which we will find below in the systemDictionary.
 600         // We also get here for parallel bootstrap classloader
 601         if (class_loader.is_null()) {
 602           SystemDictionary_lock->wait();
 603         } else {
 604           double_lock_wait(lockObject, THREAD);
 605         }
 606       } else {
 607         // If not in SD and not in PH, other thread's load must have failed
 608         super_load_in_progress = false;
 609       }
 610     }
 611   }
 612   return NULL;
 613 }
 614 
 615 static void post_class_load_event(const Ticks& start_time,
 616                                   InstanceKlass* k,
 617                                   const ClassLoaderData* init_cld) {
 618 #if INCLUDE_TRACE
 619   EventClassLoad event(UNTIMED);
 620   if (event.should_commit()) {
 621     event.set_starttime(start_time);
 622     event.set_loadedClass(k);
 623     event.set_definingClassLoader(k->class_loader_data());
 624     event.set_initiatingClassLoader(init_cld);
 625     event.commit();
 626   }
 627 #endif // INCLUDE_TRACE
 628 }
 629 
 630 static void class_define_event(InstanceKlass* k,
 631                                const ClassLoaderData* def_cld) {
 632 #if INCLUDE_TRACE
 633   EventClassDefine event;
 634   if (event.should_commit()) {
 635     event.set_definedClass(k);
 636     event.set_definingClassLoader(def_cld);
 637     event.commit();
 638   }
 639 #endif // INCLUDE_TRACE
 640 }
 641 
 642 // Be careful when modifying this code: once you have run
 643 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
 644 // you need to find_and_remove it before returning.
 645 // So be careful to not exit with a CHECK_ macro betweeen these calls.
 646 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
 647                                                         Handle class_loader,
 648                                                         Handle protection_domain,
 649                                                         TRAPS) {
 650   assert(name != NULL && !FieldType::is_array(name) &&
 651          !FieldType::is_obj(name), "invalid class name");
 652 
 653   Ticks class_load_start_time = Ticks::now();
 654 
 655   HandleMark hm(THREAD);


 681   // ParallelCapable Classloaders and the bootstrap classloader,
 682   // or all classloaders with UnsyncloadClass do not acquire lock here
 683   bool DoObjectLock = true;
 684   if (is_parallelCapable(class_loader)) {
 685     DoObjectLock = false;
 686   }
 687 
 688   unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
 689   int p_index = placeholders()->hash_to_index(p_hash);
 690 
 691   // Class is not in SystemDictionary so we have to do loading.
 692   // Make sure we are synchronized on the class loader before we proceed
 693   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
 694   check_loader_lock_contention(lockObject, THREAD);
 695   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
 696 
 697   // Check again (after locking) if class already exist in SystemDictionary
 698   bool class_has_been_loaded   = false;
 699   bool super_load_in_progress  = false;
 700   bool havesupername = false;
 701   InstanceKlass* k = NULL;
 702   PlaceholderEntry* placeholder;
 703   Symbol* superclassname = NULL;
 704 
 705   {
 706     MutexLocker mu(SystemDictionary_lock, THREAD);
 707     InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
 708     if (check != NULL) {
 709       // Klass is already loaded, so just return it
 710       class_has_been_loaded = true;
 711       k = check;
 712     } else {
 713       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
 714       if (placeholder && placeholder->super_load_in_progress()) {
 715          super_load_in_progress = true;
 716          if (placeholder->havesupername() == true) {
 717            superclassname = placeholder->supername();
 718            havesupername = true;
 719          }
 720       }
 721     }
 722   }
 723 
 724   // If the class is in the placeholder table, class loading is in progress
 725   if (super_load_in_progress && havesupername==true) {
 726     k = handle_parallel_super_load(name,
 727                                    superclassname,
 728                                    class_loader,
 729                                    protection_domain,
 730                                    lockObject, THREAD);
 731     if (HAS_PENDING_EXCEPTION) {
 732       return NULL;
 733     }
 734     if (k != NULL) {
 735       class_has_been_loaded = true;
 736     }
 737   }
 738 
 739   bool throw_circularity_error = false;
 740   if (!class_has_been_loaded) {
 741     bool load_instance_added = false;
 742 
 743     // add placeholder entry to record loading instance class
 744     // Five cases:
 745     // All cases need to prevent modifying bootclasssearchpath
 746     // in parallel with a classload of same classname
 747     // Redefineclasses uses existence of the placeholder for the duration
 748     // of the class load to prevent concurrent redefinition of not completely
 749     // defined classes.
 750     // case 1. traditional classloaders that rely on the classloader object lock
 751     //   - no other need for LOAD_INSTANCE
 752     // case 2. traditional classloaders that break the classloader object lock
 753     //    as a deadlock workaround. Detection of this case requires that
 754     //    this check is done while holding the classloader object lock,


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


 995     FieldArrayInfo fd;
 996     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
 997     if (t != T_OBJECT) {
 998       k = Universe::typeArrayKlassObj(t);
 999     } else {
1000       k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD);
1001     }
1002     if (k != NULL) {
1003       k = k->array_klass_or_null(fd.dimension());
1004     }
1005   } else {
1006     k = find(class_name, class_loader, protection_domain, THREAD);
1007   }
1008   return k;
1009 }
1010 
1011 // Note: this method is much like resolve_from_stream, but
1012 // does not publish the classes via the SystemDictionary.
1013 // Handles unsafe_DefineAnonymousClass and redefineclasses
1014 // RedefinedClasses do not add to the class hierarchy
1015 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name,
1016                                               Handle class_loader,
1017                                               Handle protection_domain,
1018                                               ClassFileStream* st,
1019                                               const InstanceKlass* host_klass,
1020                                               GrowableArray<Handle>* cp_patches,
1021                                               TRAPS) {
1022 
1023   Ticks class_load_start_time = Ticks::now();
1024 
1025   ClassLoaderData* loader_data;
1026   if (host_klass != NULL) {
1027     // Create a new CLD for anonymous class, that uses the same class loader
1028     // as the host_klass
1029     guarantee(host_klass->class_loader() == class_loader(), "should be the same");
1030     guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
1031     loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);
1032     loader_data->record_dependency(host_klass, CHECK_NULL);
1033   } else {
1034     loader_data = ClassLoaderData::class_loader_data(class_loader());
1035   }
1036 
1037   assert(st != NULL, "invariant");
1038   assert(st->need_verify(), "invariant");
1039 
1040   // Parse stream and create a klass.
1041   // Note that we do this even though this klass might
1042   // already be present in the SystemDictionary, otherwise we would not
1043   // throw potential ClassFormatErrors.
1044 
1045   InstanceKlass* k = KlassFactory::create_from_stream(st,
1046                                                       class_name,
1047                                                       loader_data,
1048                                                       protection_domain,
1049                                                       host_klass,
1050                                                       cp_patches,
1051                                                       CHECK_NULL);
1052 
1053   if (host_klass != NULL && k != NULL) {
1054     // If it's anonymous, initialize it now, since nobody else will.
1055 
1056     {
1057       MutexLocker mu_r(Compile_lock, THREAD);
1058 
1059       // Add to class hierarchy, initialize vtables, and do possible
1060       // deoptimizations.
1061       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
1062 
1063       // But, do not add to system dictionary.
1064 
1065       // compiled code dependencies need to be validated anyway
1066       notice_modification();
1067     }
1068 
1069     // Rewrite and patch constant pool here.
1070     k->link_class(CHECK_NULL);
1071     if (cp_patches != NULL) {
1072       k->constants()->patch_resolved_references(cp_patches);
1073     }
1074     k->eager_initialize(CHECK_NULL);
1075 
1076     // notify jvmti
1077     if (JvmtiExport::should_post_class_load()) {
1078         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1079         JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1080     }
1081 
1082     post_class_load_event(class_load_start_time, k, loader_data);
1083   }
1084   assert(host_klass != NULL || NULL == cp_patches,
1085          "cp_patches only found with host_klass");
1086 
1087   return k;
1088 }
1089 
1090 // Add a klass to the system from a stream (called by jni_DefineClass and
1091 // JVM_DefineClass).
1092 // Note: class_name can be NULL. In that case we do not know the name of
1093 // the class until we have parsed the stream.
1094 
1095 InstanceKlass* SystemDictionary::resolve_from_stream(Symbol* class_name,
1096                                                      Handle class_loader,
1097                                                      Handle protection_domain,
1098                                                      ClassFileStream* st,
1099                                                      TRAPS) {
1100 
1101   HandleMark hm(THREAD);
1102 
1103   // Classloaders that support parallelism, e.g. bootstrap classloader,
1104   // or all classloaders with UnsyncloadClass do not acquire lock here
1105   bool DoObjectLock = true;
1106   if (is_parallelCapable(class_loader)) {
1107     DoObjectLock = false;
1108   }
1109 
1110   ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL);
1111 
1112   // Make sure we are synchronized on the class loader before we proceed
1113   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1114   check_loader_lock_contention(lockObject, THREAD);
1115   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
1116 
1117   assert(st != NULL, "invariant");
1118 
1119   // Parse the stream and create a klass.
1120   // Note that we do this even though this klass might
1121   // already be present in the SystemDictionary, otherwise we would not
1122   // throw potential ClassFormatErrors.

1123   
1124  InstanceKlass* k = NULL;
1125 
1126 #if INCLUDE_CDS
1127   k = SystemDictionaryShared::lookup_from_stream(class_name,
1128                                                  class_loader,
1129                                                  protection_domain,
1130                                                  st,
1131                                                  CHECK_NULL);
1132 #endif
1133 
1134   if (k == NULL) {
1135     if (st->buffer() == NULL) {
1136       return NULL;
1137     }
1138     k = KlassFactory::create_from_stream(st,
1139                                          class_name,
1140                                          loader_data,
1141                                          protection_domain,
1142                                          NULL, // host_klass
1143                                          NULL, // cp_patches
1144                                          CHECK_NULL);
1145   }
1146 
1147   assert(k != NULL, "no klass created");
1148   Symbol* h_name = k->name();
1149   assert(class_name == NULL || class_name == h_name, "name mismatch");
1150 
1151   bool define_succeeded = false;
1152   // Add class just loaded
1153   // If a class loader supports parallel classloading handle parallel define requests
1154   // find_or_define_instance_class may return a different InstanceKlass
1155   if (is_parallelCapable(class_loader)) {
1156     InstanceKlass* defined_k = find_or_define_instance_class(h_name, class_loader, k, CHECK_NULL);
1157     if (k == defined_k) {
1158       // we have won over other concurrent threads (if any) that are
1159       // competing to define the same class.
1160       define_succeeded = true;
1161     }
1162     k = defined_k;
1163   } else {
1164     define_instance_class(k, CHECK_NULL);
1165     define_succeeded = true;
1166   }
1167 
1168   // Make sure we have an entry in the SystemDictionary on success
1169   debug_only( {
1170     MutexLocker mu(SystemDictionary_lock, THREAD);
1171 
1172     Klass* check = find_class(h_name, k->class_loader_data());
1173     assert(check == k, "should be present in the dictionary");
1174   } );
1175 
1176   return k;
1177 }
1178 
1179 #if INCLUDE_CDS
1180 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
1181                                              int number_of_entries) {
1182   assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
1183          "bad shared dictionary size.");
1184   _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
1185 }
1186 
1187 
1188 // If there is a shared dictionary, then find the entry for the
1189 // given shared system class, if any.
1190 
1191 InstanceKlass* SystemDictionary::find_shared_class(Symbol* class_name) {
1192   if (shared_dictionary() != NULL) {
1193     unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);
1194     int d_index = shared_dictionary()->hash_to_index(d_hash);
1195 
1196     return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1197   } else {
1198     return NULL;
1199   }
1200 }
1201 
1202 
1203 // Load a class from the shared spaces (found through the shared system
1204 // dictionary).  Force the superclass and all interfaces to be loaded.
1205 // Update the class definition to include sibling classes and no
1206 // subclasses (yet).  [Classes in the shared space are not part of the
1207 // object hierarchy until loaded.]
1208 
1209 InstanceKlass* SystemDictionary::load_shared_class(
1210                  Symbol* class_name, Handle class_loader, TRAPS) {
1211   InstanceKlass* ik = find_shared_class(class_name);
1212   // Make sure we only return the boot class for the NULL classloader.
1213   if (ik != NULL &&
1214       ik->is_shared_boot_class() && class_loader.is_null()) {
1215     Handle protection_domain;
1216     return load_shared_class(ik, class_loader, protection_domain, THREAD);
1217   }
1218   return NULL;
1219 }
1220 
1221 // Check if a shared class can be loaded by the specific classloader:
1222 //
1223 // NULL classloader:
1224 //   - Module class from "modules" jimage. ModuleEntry must be defined in the classloader.
1225 //   - Class from -Xbootclasspath/a. The class has no defined PackageEntry, or must
1226 //     be defined in an unnamed module.
1227 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
1228                                                InstanceKlass* ik,
1229                                                Handle class_loader, TRAPS) {
1230   assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
1231          "Cannot use sharing if java.base is patched");
1232   ResourceMark rm;
1233   int path_index = ik->shared_classpath_index();
1234   SharedClassPathEntry* ent =
1235             (SharedClassPathEntry*)FileMapInfo::shared_classpath(path_index);
1236   if (!Universe::is_module_initialized()) {
1237     assert(ent != NULL && ent->is_jrt(),
1238            "Loading non-bootstrap classes before the module system is initialized");
1239     assert(class_loader.is_null(), "sanity");
1240     return true;
1241   }
1242   // Get the pkg_entry from the classloader
1243   TempNewSymbol pkg_name = NULL;
1244   PackageEntry* pkg_entry = NULL;
1245   ModuleEntry* mod_entry = NULL;
1246   const char* pkg_string = NULL;
1247   ClassLoaderData* loader_data = class_loader_data(class_loader);
1248   pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false);


1285     if (!ent->is_jrt() && ik->is_shared_boot_class()) {
1286       // the class is from the -Xbootclasspath/a
1287       if (pkg_string == NULL ||
1288           pkg_entry == NULL ||
1289           pkg_entry->in_unnamed_module()) {
1290         assert(mod_entry == NULL ||
1291                mod_entry == loader_data->modules()->unnamed_module(),
1292                "the unnamed module is not defined in the classloader");
1293         return true;
1294       }
1295     }
1296     return false;
1297   } else {
1298     bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader(
1299               ik, class_loader, pkg_string, pkg_name,
1300               pkg_entry, mod_entry, CHECK_(false));
1301     return res;
1302   }
1303 }
1304 
1305 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik,
1306                                                    Handle class_loader,
1307                                                    Handle protection_domain, TRAPS) {

1308 
1309   if (ik != NULL) {
1310     Symbol* class_name = ik->name();
1311 
1312     bool visible = is_shared_class_visible(
1313                             class_name, ik, class_loader, CHECK_NULL);
1314     if (!visible) {
1315       return NULL;
1316     }
1317 
1318     // Resolve the superclass and interfaces. They must be the same
1319     // as in dump time, because the layout of <ik> depends on
1320     // the specific layout of ik->super() and ik->local_interfaces().
1321     //
1322     // If unexpected superclass or interfaces are found, we cannot
1323     // load <ik> from the shared archive.
1324 
1325     if (ik->super() != NULL) {
1326       Symbol*  cn = ik->super()->name();
1327       Klass *s = resolve_super_or_fail(class_name, cn,
1328                                        class_loader, protection_domain, true, CHECK_NULL);
1329       if (s != ik->super()) {
1330         // The dynamically resolved super class is not the same as the one we used during dump time,
1331         // so we cannot use ik.
1332         return NULL;
1333       } else {
1334         assert(s->is_shared(), "must be");
1335       }
1336     }
1337 
1338     Array<Klass*>* interfaces = ik->local_interfaces();
1339     int num_interfaces = interfaces->length();
1340     for (int index = 0; index < num_interfaces; index++) {
1341       Klass* k = interfaces->at(index);
1342 
1343       // Note: can not use InstanceKlass::cast here because
1344       // interfaces' InstanceKlass's C++ vtbls haven't been
1345       // reinitialized yet (they will be once the interface classes
1346       // are loaded)
1347       Symbol*  name  = k->name();
1348       Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_NULL);
1349       if (k != i) {
1350         // The dynamically resolved interface class is not the same as the one we used during dump time,
1351         // so we cannot use ik.
1352         return NULL;
1353       } else {
1354         assert(i->is_shared(), "must be");
1355       }
1356     }
1357 
1358     InstanceKlass* new_ik = KlassFactory::check_shared_class_file_load_hook(
1359         ik, class_name, class_loader, protection_domain, CHECK_NULL);
1360     if (new_ik != NULL) {
1361       // The class is changed by CFLH. Return the new class. The shared class is
1362       // not used.
1363       return new_ik;
1364     }
1365 
1366     // Adjust methods to recover missing data.  They need addresses for
1367     // interpreter entry points and their default native method address
1368     // must be reset.
1369 
1370     // Updating methods must be done under a lock so multiple
1371     // threads don't update these in parallel
1372     //
1373     // Shared classes are all currently loaded by either the bootstrap or
1374     // internal parallel class loaders, so this will never cause a deadlock
1375     // on a custom class loader lock.
1376 
1377     ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1378     {
1379       HandleMark hm(THREAD);
1380       Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1381       check_loader_lock_contention(lockObject, THREAD);
1382       ObjectLocker ol(lockObject, THREAD, true);
1383       // prohibited package check assumes all classes loaded from archive call
1384       // restore_unshareable_info which calls ik->set_package()
1385       ik->restore_unshareable_info(loader_data, protection_domain, CHECK_NULL);
1386     }
1387 
1388     if (log_is_enabled(Info, class, load)) {
1389       ik->print_loading_log(LogLevel::Info, loader_data, NULL, NULL);
1390     }
1391     // No 'else' here as logging levels are not mutually exclusive
1392 
1393     if (log_is_enabled(Debug, class, load)) {
1394       ik->print_loading_log(LogLevel::Debug, loader_data, NULL, NULL);
1395     }
1396 
1397     // For boot loader, ensure that GetSystemPackage knows that a class in this
1398     // package was loaded.
1399     if (class_loader.is_null()) {
1400       int path_index = ik->shared_classpath_index();
1401       ResourceMark rm;
1402       ClassLoader::add_package(ik->name()->as_C_string(), path_index, THREAD);
1403     }
1404 
1405     if (DumpLoadedClassList != NULL && classlist_file->is_open()) {
1406       // Only dump the classes that can be stored into CDS archive
1407       if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
1408         ResourceMark rm(THREAD);
1409         classlist_file->print_cr("%s", ik->name()->as_C_string());
1410         classlist_file->flush();
1411       }
1412     }
1413 
1414     // notify a class loaded from shared object
1415     ClassLoadingService::notify_class_loaded(ik, true /* shared class */);
1416   }
1417 
1418   ik->set_has_passed_fingerprint_check(false);
1419   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
1420     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
1421     uint64_t cds_fp = ik->get_stored_fingerprint();
1422     if (aot_fp != 0 && aot_fp == cds_fp) {
1423       // This class matches with a class saved in an AOT library
1424       ik->set_has_passed_fingerprint_check(true);
1425     } else {
1426       ResourceMark rm;
1427       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT, ik->external_name(), aot_fp, cds_fp);
1428     }
1429   }
1430   return ik;
1431 }
1432 #endif // INCLUDE_CDS
1433 
1434 InstanceKlass* SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {

1435 
1436   if (class_loader.is_null()) {
1437     ResourceMark rm;
1438     PackageEntry* pkg_entry = NULL;
1439     bool search_only_bootloader_append = false;
1440     ClassLoaderData *loader_data = class_loader_data(class_loader);
1441 
1442     // Find the package in the boot loader's package entry table.
1443     TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_NULL);
1444     if (pkg_name != NULL) {
1445       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1446     }
1447 
1448     // Prior to attempting to load the class, enforce the boot loader's
1449     // visibility boundaries.
1450     if (!Universe::is_module_initialized()) {
1451       // During bootstrapping, prior to module initialization, any
1452       // class attempting to be loaded must be checked against the
1453       // java.base packages in the boot loader's PackageEntryTable.
1454       // No class outside of java.base is allowed to be loaded during
1455       // this bootstrapping window.
1456       if (!DumpSharedSpaces) {
1457         if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1458           // Class is either in the unnamed package or in
1459           // a named package within the unnamed module.  Either
1460           // case is outside of java.base, do not attempt to
1461           // load the class post java.base definition.  If
1462           // java.base has not been defined, let the class load
1463           // and its package will be checked later by
1464           // ModuleEntryTable::verify_javabase_packages.
1465           if (ModuleEntryTable::javabase_defined()) {
1466             return NULL;
1467           }
1468         } else {
1469           // Check that the class' package is defined within java.base.
1470           ModuleEntry* mod_entry = pkg_entry->module();
1471           Symbol* mod_entry_name = mod_entry->name();
1472           if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1473             return NULL;
1474           }
1475         }
1476       }
1477     } else {
1478       assert(!DumpSharedSpaces, "Archive dumped after module system initialization");
1479       // After the module system has been initialized, check if the class'
1480       // package is in a module defined to the boot loader.
1481       if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1482         // Class is either in the unnamed package, in a named package
1483         // within a module not defined to the boot loader or in a
1484         // a named package within the unnamed module.  In all cases,
1485         // limit visibility to search for the class only in the boot
1486         // loader's append path.
1487         search_only_bootloader_append = true;
1488       }
1489     }
1490 
1491     // Prior to bootstrapping's module initialization, never load a class outside
1492     // of the boot loader's module path
1493     assert(Universe::is_module_initialized() || DumpSharedSpaces ||
1494            !search_only_bootloader_append,
1495            "Attempt to load a class outside of boot loader's module path");
1496 
1497     // Search the shared system dictionary for classes preloaded into the
1498     // shared spaces.
1499     InstanceKlass* k = NULL;
1500     {
1501 #if INCLUDE_CDS
1502       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1503       k = load_shared_class(class_name, class_loader, THREAD);
1504 #endif
1505     }
1506 
1507     if (k == NULL) {
1508       // Use VM class loader
1509       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1510       k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_NULL);
1511     }
1512 
1513     // find_or_define_instance_class may return a different InstanceKlass
1514     if (k != NULL) {
1515       k = find_or_define_instance_class(class_name, class_loader, k, CHECK_NULL);


1516     }
1517     return k;
1518   } else {
1519     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1520     ResourceMark rm(THREAD);
1521 
1522     assert(THREAD->is_Java_thread(), "must be a JavaThread");
1523     JavaThread* jt = (JavaThread*) THREAD;
1524 
1525     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1526                                ClassLoader::perf_app_classload_selftime(),
1527                                ClassLoader::perf_app_classload_count(),
1528                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1529                                jt->get_thread_stat()->perf_timers_addr(),
1530                                PerfClassTraceTime::CLASS_LOAD);
1531 
1532     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_NULL);
1533     // Translate to external class name format, i.e., convert '/' chars to '.'
1534     Handle string = java_lang_String::externalize_classname(s, CHECK_NULL);
1535 
1536     JavaValue result(T_OBJECT);
1537 
1538     InstanceKlass* spec_klass = SystemDictionary::ClassLoader_klass();
1539 
1540     // Call public unsynchronized loadClass(String) directly for all class loaders
1541     // for parallelCapable class loaders. JDK >=7, loadClass(String, boolean) will
1542     // acquire a class-name based lock rather than the class loader object lock.
1543     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean),
1544     // so the call to loadClassInternal() was not required.
1545     //
1546     // UnsyncloadClass flag means both call loadClass(String) and do
1547     // not acquire the class loader lock even for class loaders that are
1548     // not parallelCapable. This was a risky transitional
1549     // flag for diagnostic purposes only. It is risky to call
1550     // custom class loaders without synchronization.
1551     // WARNING If a custom class loader does NOT synchronizer findClass, or callers of
1552     // findClass, the UnsyncloadClass flag risks unexpected timing bugs in the field.
1553     // Do NOT assume this will be supported in future releases.
1554     //
1555     // Added MustCallLoadClassInternal in case we discover in the field
1556     // a customer that counts on this call
1557     if (MustCallLoadClassInternal && has_loadClassInternal()) {
1558       JavaCalls::call_special(&result,
1559                               class_loader,
1560                               spec_klass,
1561                               vmSymbols::loadClassInternal_name(),
1562                               vmSymbols::string_class_signature(),
1563                               string,
1564                               CHECK_NULL);
1565     } else {
1566       JavaCalls::call_virtual(&result,
1567                               class_loader,
1568                               spec_klass,
1569                               vmSymbols::loadClass_name(),
1570                               vmSymbols::string_class_signature(),
1571                               string,
1572                               CHECK_NULL);
1573     }
1574 
1575     assert(result.get_type() == T_OBJECT, "just checking");
1576     oop obj = (oop) result.get_jobject();
1577 
1578     // Primitive classes return null since forName() can not be
1579     // used to obtain any of the Class objects representing primitives or void
1580     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1581       InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(obj));

1582       // For user defined Java class loaders, check that the name returned is
1583       // the same as that requested.  This check is done for the bootstrap
1584       // loader when parsing the class file.
1585       if (class_name == k->name()) {
1586         return k;
1587       }
1588     }
1589     // Class is not found or has the wrong name, return NULL
1590     return NULL;
1591   }
1592 }
1593 
1594 void SystemDictionary::define_instance_class(InstanceKlass* k, TRAPS) {
1595 
1596   HandleMark hm(THREAD);
1597   ClassLoaderData* loader_data = k->class_loader_data();
1598   Handle class_loader_h(THREAD, loader_data->class_loader());
1599 
1600  // for bootstrap and other parallel classloaders don't acquire lock,
1601  // use placeholder token
1602  // If a parallelCapable class loader calls define_instance_class instead of
1603  // find_or_define_instance_class to get here, we have a timing
1604  // hole with systemDictionary updates and check_constraints
1605  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1606     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1607          compute_loader_lock_object(class_loader_h, THREAD)),
1608          "define called without lock");
1609   }
1610 
1611   // Check class-loading constraints. Throw exception if violation is detected.
1612   // Grabs and releases SystemDictionary_lock
1613   // The check_constraints/find_class call and update_dictionary sequence
1614   // must be "atomic" for a specific class/classloader pair so we never


1639   {
1640     unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1641     int p_index = placeholders()->hash_to_index(p_hash);
1642 
1643     MutexLocker mu_r(Compile_lock, THREAD);
1644 
1645     // Add to class hierarchy, initialize vtables, and do possible
1646     // deoptimizations.
1647     add_to_hierarchy(k, CHECK); // No exception, but can block
1648 
1649     // Add to systemDictionary - so other classes can see it.
1650     // Grabs and releases SystemDictionary_lock
1651     update_dictionary(d_index, d_hash, p_index, p_hash,
1652                       k, class_loader_h, THREAD);
1653   }
1654   k->eager_initialize(THREAD);
1655 
1656   // notify jvmti
1657   if (JvmtiExport::should_post_class_load()) {
1658       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1659       JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1660 
1661   }
1662   class_define_event(k, loader_data);
1663 }
1664 
1665 // Support parallel classloading
1666 // All parallel class loaders, including bootstrap classloader
1667 // lock a placeholder entry for this class/class_loader pair
1668 // to allow parallel defines of different classes for this class loader
1669 // With AllowParallelDefine flag==true, in case they do not synchronize around
1670 // FindLoadedClass/DefineClass, calls, we check for parallel
1671 // loading for them, wait if a defineClass is in progress
1672 // and return the initial requestor's results
1673 // This flag does not apply to the bootstrap classloader.
1674 // With AllowParallelDefine flag==false, call through to define_instance_class
1675 // which will throw LinkageError: duplicate class definition.
1676 // False is the requested default.
1677 // For better performance, the class loaders should synchronize
1678 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1679 // potentially waste time reading and parsing the bytestream.
1680 // Note: VM callers should ensure consistency of k/class_name,class_loader
1681 // Be careful when modifying this code: once you have run
1682 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1683 // you need to find_and_remove it before returning.
1684 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1685 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1686                                                                InstanceKlass* k, TRAPS) {
1687 

1688   Symbol*  name_h = k->name(); // passed in class_name may be null
1689   ClassLoaderData* loader_data = class_loader_data(class_loader);
1690 
1691   unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1692   int d_index = dictionary()->hash_to_index(d_hash);
1693 
1694   // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1695   unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1696   int p_index = placeholders()->hash_to_index(p_hash);
1697   PlaceholderEntry* probe;
1698 
1699   {
1700     MutexLocker mu(SystemDictionary_lock, THREAD);
1701     // First check if class already defined
1702     if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1703       InstanceKlass* check = find_class(d_index, d_hash, name_h, loader_data);
1704       if (check != NULL) {
1705         return check;
1706       }
1707     }
1708 
1709     // Acquire define token for this class/classloader
1710     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1711     // Wait if another thread defining in parallel
1712     // All threads wait - even those that will throw duplicate class: otherwise
1713     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1714     // if other thread has not finished updating dictionary
1715     while (probe->definer() != NULL) {
1716       SystemDictionary_lock->wait();
1717     }
1718     // Only special cases allow parallel defines and can use other thread's results
1719     // Other cases fall through, and may run into duplicate defines
1720     // caught by finding an entry in the SystemDictionary
1721     if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1722         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1723         SystemDictionary_lock->notify_all();
1724 #ifdef ASSERT
1725         InstanceKlass* check = find_class(d_index, d_hash, name_h, loader_data);
1726         assert(check != NULL, "definer missed recording success");
1727 #endif
1728         return probe->instance_klass();
1729     } else {
1730       // This thread will define the class (even if earlier thread tried and had an error)
1731       probe->set_definer(THREAD);
1732     }
1733   }
1734 
1735   define_instance_class(k, THREAD);
1736 
1737   Handle linkage_exception = Handle(); // null handle
1738 
1739   // definer must notify any waiting threads
1740   {
1741     MutexLocker mu(SystemDictionary_lock, THREAD);
1742     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1743     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1744     if (probe != NULL) {
1745       if (HAS_PENDING_EXCEPTION) {
1746         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1747         CLEAR_PENDING_EXCEPTION;
1748       } else {
1749         probe->set_instance_klass(k);
1750       }
1751       probe->set_definer(NULL);
1752       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1753       SystemDictionary_lock->notify_all();
1754     }
1755   }
1756 
1757   // Can't throw exception while holding lock due to rank ordering
1758   if (linkage_exception() != NULL) {
1759     THROW_OOP_(linkage_exception(), NULL); // throws exception and returns
1760   }
1761 
1762   return k;
1763 }
1764 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1765   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1766   if (class_loader.is_null()) {
1767     return Handle(THREAD, _system_loader_lock_obj);
1768   } else {
1769     return class_loader;
1770   }
1771 }
1772 
1773 // This method is added to check how often we have to wait to grab loader
1774 // lock. The results are being recorded in the performance counters defined in
1775 // ClassLoader::_sync_systemLoaderLockContentionRate and
1776 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1777 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1778   if (!UsePerfData) {
1779     return;
1780   }
1781 
1782   assert(!loader_lock.is_null(), "NULL lock object");
1783 
1784   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1785       == ObjectSynchronizer::owner_other) {
1786     // contention will likely happen, so increment the corresponding
1787     // contention counter.
1788     if (loader_lock() == _system_loader_lock_obj) {
1789       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1790     } else {
1791       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1792     }
1793   }
1794 }
1795 
1796 // ----------------------------------------------------------------------------
1797 // Lookup
1798 
1799 InstanceKlass* SystemDictionary::find_class(int index, unsigned int hash,
1800                                             Symbol* class_name,
1801                                             ClassLoaderData* loader_data) {
1802   assert_locked_or_safepoint(SystemDictionary_lock);
1803   assert (index == dictionary()->index_for(class_name, loader_data),
1804           "incorrect index?");
1805 
1806   return dictionary()->find_class(index, hash, class_name, loader_data);

1807 }
1808 
1809 
1810 // Basic find on classes in the midst of being loaded
1811 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1812                                            ClassLoaderData* loader_data) {
1813   assert_locked_or_safepoint(SystemDictionary_lock);
1814   unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
1815   int p_index = placeholders()->hash_to_index(p_hash);
1816   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1817 }
1818 
1819 
1820 // Used for assertions and verification only
1821 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1822   #ifndef ASSERT
1823   guarantee(VerifyBeforeGC      ||
1824             VerifyDuringGC      ||
1825             VerifyBeforeExit    ||
1826             VerifyDuringStartup ||
1827             VerifyAfterGC, "too expensive");
1828   #endif
1829   assert_locked_or_safepoint(SystemDictionary_lock);
1830 
1831   // First look in the loaded class array
1832   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
1833   int d_index = dictionary()->hash_to_index(d_hash);
1834   return find_class(d_index, d_hash, class_name, loader_data);
1835 }
1836 
1837 
1838 // Get the next class in the dictionary.
1839 Klass* SystemDictionary::try_get_next_class() {
1840   return dictionary()->try_get_next_class();
1841 }
1842 
1843 
1844 // ----------------------------------------------------------------------------
1845 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1846 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1847 // before a new class is used.
1848 
1849 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) {
1850   assert(k != NULL, "just checking");
1851   assert_locked_or_safepoint(Compile_lock);
1852 
1853   // Link into hierachy. Make sure the vtables are initialized before linking into
1854   k->append_to_sibling_list();                    // add to superklass/sibling list
1855   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1856   k->set_init_state(InstanceKlass::loaded);
1857   // Now flush all code that depended on old class hierarchy.
1858   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1859   // Also, first reinitialize vtable because it may have gotten out of synch
1860   // while the new class wasn't connected to the class hierarchy.
1861   CodeCache::flush_dependents_on(k);
1862 }
1863 
1864 // ----------------------------------------------------------------------------
1865 // GC support
1866 
1867 // Following roots during mark-sweep is separated in two phases.
1868 //
1869 // The first phase follows preloaded classes and all other system
1870 // classes, since these will never get unloaded anyway.


2111     initialize_wk_klass((WKID)id, opt, CHECK);
2112   }
2113 
2114   // move the starting value forward to the limit:
2115   start_id = limit_id;
2116 }
2117 
2118 void SystemDictionary::initialize_preloaded_classes(TRAPS) {
2119   assert(WK_KLASS(Object_klass) == NULL, "preloaded classes should only be initialized once");
2120 
2121   // Create the ModuleEntry for java.base.  This call needs to be done here,
2122   // after vmSymbols::initialize() is called but before any classes are pre-loaded.
2123   ClassLoader::classLoader_init2(CHECK);
2124 
2125   // Preload commonly used klasses
2126   WKID scan = FIRST_WKID;
2127   // first do Object, then String, Class
2128   if (UseSharedSpaces) {
2129     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
2130     // Initialize the constant pool for the Object_class
2131     Object_klass()->constants()->restore_unshareable_info(CHECK);

2132     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2133   } else {
2134     initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
2135   }
2136 
2137   // Calculate offsets for String and Class classes since they are loaded and
2138   // can be used after this point.
2139   java_lang_String::compute_offsets();
2140   java_lang_Class::compute_offsets();
2141 
2142   // Fixup mirrors for classes loaded before java.lang.Class.
2143   // These calls iterate over the objects currently in the perm gen
2144   // so calling them at this point is matters (not before when there
2145   // are fewer objects and not later after there are more objects
2146   // in the perm gen.
2147   Universe::initialize_basic_type_mirrors(CHECK);
2148   Universe::fixup_mirrors(CHECK);
2149 
2150   // do a bunch more:
2151   initialize_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);


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


2375     FieldArrayInfo fd;
2376     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2377     // primitive types always pass
2378     if (t != T_OBJECT) {
2379       return true;
2380     } else {
2381       constraint_name = fd.object_key();
2382     }
2383   }
2384   unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
2385   int d_index1 = dictionary()->hash_to_index(d_hash1);
2386 
2387   unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
2388   int d_index2 = dictionary()->hash_to_index(d_hash2);
2389   {
2390   MutexLocker mu_s(SystemDictionary_lock, THREAD);
2391 
2392   // Better never do a GC while we're holding these oops
2393   NoSafepointVerifier nosafepoint;
2394 
2395   InstanceKlass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
2396   InstanceKlass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
2397   return constraints()->add_entry(constraint_name, klass1, class_loader1,
2398                                   klass2, class_loader2);
2399   }
2400 }
2401 
2402 // Add entry to resolution error table to record the error when the first
2403 // attempt to resolve a reference to a class has failed.
2404 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2405                                             Symbol* error, Symbol* message) {
2406   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2407   int index = resolution_errors()->hash_to_index(hash);
2408   {
2409     MutexLocker ml(SystemDictionary_lock, Thread::current());
2410     resolution_errors()->add_entry(index, hash, pool, which, error, message);
2411   }
2412 }
2413 
2414 // Delete a resolution error for RedefineClasses for a constant pool is going away
2415 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2416   resolution_errors()->delete_entry(pool);


2536     // if a racing thread has managed to install one at the same time.
2537     {
2538       MutexLocker ml(SystemDictionary_lock, THREAD);
2539       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2540       if (spe == NULL)
2541         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
2542       if (spe->method() == NULL)
2543         spe->set_method(m());
2544     }
2545   }
2546 
2547   assert(spe != NULL && spe->method() != NULL, "");
2548   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2549          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
2550          "MH intrinsic invariant");
2551   return spe->method();
2552 }
2553 
2554 // Helper for unpacking the return value from linkMethod and linkCallSite.
2555 static methodHandle unpack_method_and_appendix(Handle mname,
2556                                                Klass* accessing_klass,
2557                                                objArrayHandle appendix_box,
2558                                                Handle* appendix_result,
2559                                                TRAPS) {
2560   methodHandle empty;
2561   if (mname.not_null()) {
2562     Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(mname());
2563     if (vmtarget != NULL && vmtarget->is_method()) {
2564       Method* m = (Method*)vmtarget;
2565       oop appendix = appendix_box->obj_at(0);
2566       if (TraceMethodHandles) {
2567     #ifndef PRODUCT
2568         ttyLocker ttyl;
2569         tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2570         m->print();
2571         if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
2572         tty->cr();
2573     #endif //PRODUCT
2574       }
2575       (*appendix_result) = Handle(THREAD, appendix);
2576       // the target is stored in the cpCache and if a reference to this
2577       // MethodName is dropped we need a way to make sure the
2578       // class_loader containing this method is kept alive.
2579       // FIXME: the appendix might also preserve this dependency.
2580       ClassLoaderData* this_key = accessing_klass->class_loader_data();
2581       this_key->record_dependency(m->method_holder(), CHECK_NULL); // Can throw OOM
2582       return methodHandle(THREAD, m);
2583     }
2584   }
2585   THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives", empty);
2586   return empty;
2587 }
2588 
2589 methodHandle SystemDictionary::find_method_handle_invoker(Klass* klass,
2590                                                           Symbol* name,
2591                                                           Symbol* signature,
2592                                                           Klass* accessing_klass,
2593                                                           Handle *appendix_result,
2594                                                           Handle *method_type_result,
2595                                                           TRAPS) {
2596   methodHandle empty;
2597   assert(THREAD->can_call_java() ,"");
2598   Handle method_type =
2599     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_(empty));
2600 
2601   int ref_kind = JVM_REF_invokeVirtual;
2602   oop name_oop = StringTable::intern(name, CHECK_(empty));
2603   Handle name_str (THREAD, name_oop);
2604   objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2605   assert(appendix_box->obj_at(0) == NULL, "");
2606 
2607   // This should not happen.  JDK code should take care of that.
2608   if (accessing_klass == NULL || method_type.is_null()) {
2609     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokehandle", empty);
2610   }
2611 
2612   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2613   JavaCallArguments args;
2614   args.push_oop(Handle(THREAD, accessing_klass->java_mirror()));
2615   args.push_int(ref_kind);
2616   args.push_oop(Handle(THREAD, klass->java_mirror()));
2617   args.push_oop(name_str);
2618   args.push_oop(method_type);
2619   args.push_oop(appendix_box);
2620   JavaValue result(T_OBJECT);
2621   JavaCalls::call_static(&result,
2622                          SystemDictionary::MethodHandleNatives_klass(),
2623                          vmSymbols::linkMethod_name(),
2624                          vmSymbols::linkMethod_signature(),
2625                          &args, CHECK_(empty));
2626   Handle mname(THREAD, (oop) result.get_jobject());
2627   (*method_type_result) = method_type;
2628   return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2629 }
2630 
2631 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2632 // We must ensure that all class loaders everywhere will reach this class, for any client.
2633 // This is a safe bet for public classes in java.lang, such as Object and String.
2634 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2635 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
2636 static bool is_always_visible_class(oop mirror) {
2637   Klass* klass = java_lang_Class::as_Klass(mirror);
2638   if (klass->is_objArray_klass()) {
2639     klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2640   }
2641   if (klass->is_typeArray_klass()) {
2642     return true; // primitive array
2643   }
2644   assert(klass->is_instance_klass(), "%s", klass->external_name());
2645   return klass->is_public() &&
2646          (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
2647           InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
2648 }
2649 
2650 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2651 // signature, as interpreted relative to the given class loader.
2652 // Because of class loader constraints, all method handle usage must be
2653 // consistent with this loader.
2654 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2655                                                  Klass* accessing_klass,
2656                                                  TRAPS) {
2657   Handle empty;
2658   vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
2659   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
2660   int          index = invoke_method_table()->hash_to_index(hash);
2661   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2662   if (spe != NULL && spe->method_type() != NULL) {
2663     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
2664     return Handle(THREAD, spe->method_type());
2665   } else if (!THREAD->can_call_java()) {
2666     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
2667     return Handle();  // do not attempt from within compiler, unless it was cached
2668   }
2669 
2670   Handle class_loader, protection_domain;
2671   if (accessing_klass != NULL) {
2672     class_loader      = Handle(THREAD, accessing_klass->class_loader());
2673     protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2674   }
2675   bool can_be_cached = true;
2676   int npts = ArgumentCount(signature).size();
2677   objArrayHandle pts = oopFactory::new_objArray_handle(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2678   int arg = 0;
2679   Handle rt; // the return type from the signature
2680   ResourceMark rm(THREAD);
2681   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2682     oop mirror = NULL;
2683     if (can_be_cached) {
2684       // Use neutral class loader to lookup candidate classes to be placed in the cache.
2685       mirror = ss.as_java_mirror(Handle(), Handle(),
2686                                  SignatureStream::ReturnNull, CHECK_(empty));
2687       if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {
2688         // Fall back to accessing_klass context.
2689         can_be_cached = false;
2690       }
2691     }
2692     if (!can_be_cached) {
2693       // Resolve, throwing a real error if it doesn't work.
2694       mirror = ss.as_java_mirror(class_loader, protection_domain,
2695                                  SignatureStream::NCDFError, CHECK_(empty));
2696     }
2697     assert(!oopDesc::is_null(mirror), "%s", ss.as_symbol(THREAD)->as_C_string());
2698     if (ss.at_return_type())
2699       rt = Handle(THREAD, mirror);
2700     else
2701       pts->obj_at_put(arg++, mirror);
2702 
2703     // Check accessibility.
2704     if (ss.is_object() && accessing_klass != NULL) {
2705       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2706       mirror = NULL;  // safety
2707       // Emulate ConstantPool::verify_constant_pool_resolve.
2708       if (sel_klass->is_objArray_klass())
2709         sel_klass = ObjArrayKlass::cast(sel_klass)->bottom_klass();
2710       if (sel_klass->is_instance_klass()) {
2711         LinkResolver::check_klass_accessability(accessing_klass, sel_klass, CHECK_(empty));

2712       }
2713     }
2714   }
2715   assert(arg == npts, "");
2716 
2717   // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType
2718   JavaCallArguments args(Handle(THREAD, rt()));
2719   args.push_oop(pts);
2720   JavaValue result(T_OBJECT);
2721   JavaCalls::call_static(&result,
2722                          SystemDictionary::MethodHandleNatives_klass(),
2723                          vmSymbols::findMethodHandleType_name(),
2724                          vmSymbols::findMethodHandleType_signature(),
2725                          &args, CHECK_(empty));
2726   Handle method_type(THREAD, (oop) result.get_jobject());
2727 
2728   if (can_be_cached) {
2729     // We can cache this MethodType inside the JVM.
2730     MutexLocker ml(SystemDictionary_lock, THREAD);
2731     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2732     if (spe == NULL)
2733       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2734     if (spe->method_type() == NULL) {
2735       spe->set_method_type(method_type());
2736     }
2737   }
2738 
2739   // report back to the caller with the MethodType
2740   return method_type;
2741 }
2742 
2743 // Ask Java code to find or construct a method handle constant.
2744 Handle SystemDictionary::link_method_handle_constant(Klass* caller,
2745                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
2746                                                      Klass* callee,
2747                                                      Symbol* name_sym,
2748                                                      Symbol* signature,
2749                                                      TRAPS) {
2750   Handle empty;
2751   Handle name = java_lang_String::create_from_symbol(name_sym, CHECK_(empty));
2752   Handle type;
2753   if (signature->utf8_length() > 0 && signature->byte_at(0) == '(') {
2754     type = find_method_handle_type(signature, caller, CHECK_(empty));
2755   } else if (caller == NULL) {
2756     // This should not happen.  JDK code should take care of that.
2757     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2758   } else {
2759     ResourceMark rm(THREAD);
2760     SignatureStream ss(signature, false);
2761     if (!ss.is_done()) {
2762       oop mirror = ss.as_java_mirror(Handle(THREAD, caller->class_loader()),
2763                                      Handle(THREAD, caller->protection_domain()),
2764                                      SignatureStream::NCDFError, CHECK_(empty));
2765       type = Handle(THREAD, mirror);
2766       ss.next();
2767       if (!ss.is_done())  type = Handle();  // error!
2768     }
2769   }
2770   if (type.is_null()) {
2771     THROW_MSG_(vmSymbols::java_lang_LinkageError(), "bad signature", empty);
2772   }
2773 
2774   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2775   JavaCallArguments args;
2776   args.push_oop(Handle(THREAD, caller->java_mirror()));  // the referring class
2777   args.push_int(ref_kind);
2778   args.push_oop(Handle(THREAD, callee->java_mirror()));  // the target class
2779   args.push_oop(name);
2780   args.push_oop(type);
2781   JavaValue result(T_OBJECT);
2782   JavaCalls::call_static(&result,
2783                          SystemDictionary::MethodHandleNatives_klass(),
2784                          vmSymbols::linkMethodHandleConstant_name(),
2785                          vmSymbols::linkMethodHandleConstant_signature(),
2786                          &args, CHECK_(empty));
2787   return Handle(THREAD, (oop) result.get_jobject());
2788 }
2789 
2790 // Ask Java code to find or construct a java.lang.invoke.CallSite for the given
2791 // name and signature, as interpreted relative to the given class loader.
2792 methodHandle SystemDictionary::find_dynamic_call_site_invoker(Klass* caller,
2793                                                               Handle bootstrap_specifier,
2794                                                               Symbol* name,
2795                                                               Symbol* type,
2796                                                               Handle *appendix_result,
2797                                                               Handle *method_type_result,
2798                                                               TRAPS) {
2799   methodHandle empty;
2800   Handle bsm, info;
2801   if (java_lang_invoke_MethodHandle::is_instance(bootstrap_specifier())) {
2802     bsm = bootstrap_specifier;
2803   } else {
2804     assert(bootstrap_specifier->is_objArray(), "");
2805     objArrayHandle args(THREAD, (objArrayOop) bootstrap_specifier());
2806     int len = args->length();
2807     assert(len >= 1, "");
2808     bsm = Handle(THREAD, args->obj_at(0));
2809     if (len > 1) {
2810       objArrayOop args1 = oopFactory::new_objArray(SystemDictionary::Object_klass(), len-1, CHECK_(empty));
2811       for (int i = 1; i < len; i++)
2812         args1->obj_at_put(i-1, args->obj_at(i));
2813       info = Handle(THREAD, args1);
2814     }
2815   }
2816   guarantee(java_lang_invoke_MethodHandle::is_instance(bsm()),
2817             "caller must supply a valid BSM");
2818 
2819   Handle method_name = java_lang_String::create_from_symbol(name, CHECK_(empty));
2820   Handle method_type = find_method_handle_type(type, caller, CHECK_(empty));
2821 
2822   // This should not happen.  JDK code should take care of that.
2823   if (caller == NULL || method_type.is_null()) {
2824     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad invokedynamic", empty);
2825   }
2826 
2827   objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_(empty));
2828   assert(appendix_box->obj_at(0) == NULL, "");
2829 
2830   // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2831   JavaCallArguments args;
2832   args.push_oop(Handle(THREAD, caller->java_mirror()));
2833   args.push_oop(bsm);
2834   args.push_oop(method_name);
2835   args.push_oop(method_type);
2836   args.push_oop(info);
2837   args.push_oop(appendix_box);
2838   JavaValue result(T_OBJECT);
2839   JavaCalls::call_static(&result,
2840                          SystemDictionary::MethodHandleNatives_klass(),
2841                          vmSymbols::linkCallSite_name(),
2842                          vmSymbols::linkCallSite_signature(),
2843                          &args, CHECK_(empty));


< prev index next >