18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "aot/aotLoader.hpp"
27 #include "classfile/classFileParser.hpp"
28 #include "classfile/classFileStream.hpp"
29 #include "classfile/classLoader.hpp"
30 #include "classfile/classLoaderData.inline.hpp"
31 #include "classfile/classLoaderExt.hpp"
32 #include "classfile/dictionary.hpp"
33 #include "classfile/javaClasses.inline.hpp"
34 #include "classfile/klassFactory.hpp"
35 #include "classfile/loaderConstraints.hpp"
36 #include "classfile/packageEntry.hpp"
37 #include "classfile/placeholders.hpp"
38 #include "classfile/resolutionErrors.hpp"
39 #include "classfile/stringTable.hpp"
40 #include "classfile/systemDictionary.hpp"
41 #include "classfile/vmSymbols.hpp"
42 #include "code/codeCache.hpp"
43 #include "compiler/compileBroker.hpp"
44 #include "gc/shared/gcLocker.hpp"
45 #include "gc/shared/gcTraceTime.inline.hpp"
46 #include "interpreter/bytecodeStream.hpp"
47 #include "interpreter/interpreter.hpp"
48 #include "logging/log.hpp"
49 #include "memory/filemap.hpp"
50 #include "memory/oopFactory.hpp"
51 #include "memory/resourceArea.hpp"
52 #include "oops/instanceKlass.hpp"
53 #include "oops/instanceRefKlass.hpp"
54 #include "oops/klass.inline.hpp"
55 #include "oops/methodData.hpp"
56 #include "oops/objArrayKlass.hpp"
57 #include "oops/objArrayOop.inline.hpp"
70 #include "runtime/javaCalls.hpp"
71 #include "runtime/mutexLocker.hpp"
72 #include "runtime/orderAccess.inline.hpp"
73 #include "runtime/signature.hpp"
74 #include "services/classLoadingService.hpp"
75 #include "services/threadService.hpp"
76 #include "trace/traceMacros.hpp"
77 #include "utilities/macros.hpp"
78 #include "utilities/ticks.hpp"
79 #if INCLUDE_CDS
80 #include "classfile/sharedClassUtil.hpp"
81 #include "classfile/systemDictionaryShared.hpp"
82 #endif
83 #if INCLUDE_JVMCI
84 #include "jvmci/jvmciRuntime.hpp"
85 #endif
86 #if INCLUDE_TRACE
87 #include "trace/tracing.hpp"
88 #endif
89
90 Dictionary* SystemDictionary::_dictionary = NULL;
91 PlaceholderTable* SystemDictionary::_placeholders = NULL;
92 Dictionary* SystemDictionary::_shared_dictionary = NULL;
93 LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL;
94 ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL;
95 SymbolPropertyTable* SystemDictionary::_invoke_method_table = NULL;
96
97
98 int SystemDictionary::_number_of_modifications = 0;
99 int SystemDictionary::_sdgeneration = 0;
100 const int SystemDictionary::_primelist[_prime_array_size] = {1009,2017,4049,5051,10103,
101 20201,40423,99991};
102
103 oop SystemDictionary::_system_loader_lock_obj = NULL;
104
105 InstanceKlass* SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
106 = { NULL /*, NULL...*/ };
107
108 InstanceKlass* SystemDictionary::_box_klasses[T_VOID+1] = { NULL /*, NULL...*/ };
109
110 oop SystemDictionary::_java_system_loader = NULL;
111
112 bool SystemDictionary::_has_loadClassInternal = false;
113 bool SystemDictionary::_has_checkPackageAccess = false;
114
115 // lazily initialized klass variables
116 InstanceKlass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
117
118
119 // ----------------------------------------------------------------------------
120 // Java-level SystemLoader
121
122 oop SystemDictionary::java_system_loader() {
123 return _java_system_loader;
124 }
125
126 void SystemDictionary::compute_java_system_loader(TRAPS) {
127 Klass* system_klass = WK_KLASS(ClassLoader_klass);
128 JavaValue result(T_OBJECT);
129 JavaCalls::call_static(&result,
130 WK_KLASS(ClassLoader_klass),
131 vmSymbols::getSystemClassLoader_name(),
132 vmSymbols::void_classloader_signature(),
133 CHECK);
134
135 _java_system_loader = (oop)result.get_jobject();
136
137 CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)
338 if (k) {
339 return k;
340 }
341 }
342 #endif // INCLUDE_CDS
343
344 // Double-check, if child class is already loaded, just return super-class,interface
345 // Don't add a placedholder if already loaded, i.e. already in system dictionary
346 // Make sure there's a placeholder for the *child* before resolving.
347 // Used as a claim that this thread is currently loading superclass/classloader
348 // Used here for ClassCircularity checks and also for heap verification
349 // (every InstanceKlass in the heap needs to be in the system dictionary
350 // or have a placeholder).
351 // Must check ClassCircularity before checking if super class is already loaded
352 //
353 // We might not already have a placeholder if this child_name was
354 // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
355 // the name of the class might not be known until the stream is actually
356 // parsed.
357 // Bugs 4643874, 4715493
358 // compute_hash can have a safepoint
359
360 ClassLoaderData* loader_data = class_loader_data(class_loader);
361 unsigned int d_hash = dictionary()->compute_hash(child_name, loader_data);
362 int d_index = dictionary()->hash_to_index(d_hash);
363 unsigned int p_hash = placeholders()->compute_hash(child_name, loader_data);
364 int p_index = placeholders()->hash_to_index(p_hash);
365 // can't throw error holding a lock
366 bool child_already_loaded = false;
367 bool throw_circularity_error = false;
368 {
369 MutexLocker mu(SystemDictionary_lock, THREAD);
370 Klass* childk = find_class(d_index, d_hash, child_name, loader_data);
371 Klass* quicksuperk;
372 // to support // loading: if child done loading, just return superclass
373 // if class_name, & class_loader don't match:
374 // if initial define, SD update will give LinkageError
375 // if redefine: compare_class_versions will give HIERARCHY_CHANGED
376 // so we don't throw an exception here.
377 // see: nsk redefclass014 & java.lang.instrument Instrument032
378 if ((childk != NULL ) && (is_superclass) &&
379 ((quicksuperk = childk->super()) != NULL) &&
380
381 ((quicksuperk->name() == class_name) &&
382 (quicksuperk->class_loader() == class_loader()))) {
383 return quicksuperk;
384 } else {
385 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
386 if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
387 throw_circularity_error = true;
388 }
389 }
390 if (!throw_circularity_error) {
426
427 void SystemDictionary::validate_protection_domain(InstanceKlass* klass,
428 Handle class_loader,
429 Handle protection_domain,
430 TRAPS) {
431 if(!has_checkPackageAccess()) return;
432
433 // Now we have to call back to java to check if the initating class has access
434 JavaValue result(T_VOID);
435 if (log_is_enabled(Debug, protectiondomain)) {
436 ResourceMark rm;
437 // Print out trace information
438 outputStream* log = Log(protectiondomain)::debug_stream();
439 log->print_cr("Checking package access");
440 log->print("class loader: "); class_loader()->print_value_on(log);
441 log->print(" protection domain: "); protection_domain()->print_value_on(log);
442 log->print(" loading: "); klass->print_value_on(log);
443 log->cr();
444 }
445
446 InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass();
447 JavaCalls::call_special(&result,
448 class_loader,
449 system_loader,
450 vmSymbols::checkPackageAccess_name(),
451 vmSymbols::class_protectiondomain_signature(),
452 Handle(THREAD, klass->java_mirror()),
453 protection_domain,
454 THREAD);
455
456 if (HAS_PENDING_EXCEPTION) {
457 log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
458 } else {
459 log_debug(protectiondomain)("granted");
460 }
461
462 if (HAS_PENDING_EXCEPTION) return;
463
464 // If no exception has been thrown, we have validated the protection domain
465 // Insert the protection domain of the initiating class into the set.
466 {
467 // We recalculate the entry here -- we've called out to java since
468 // the last time it was calculated.
469 ClassLoaderData* loader_data = class_loader_data(class_loader);
470
471 Symbol* kn = klass->name();
472 unsigned int d_hash = dictionary()->compute_hash(kn, loader_data);
473 int d_index = dictionary()->hash_to_index(d_hash);
474
475 MutexLocker mu(SystemDictionary_lock, THREAD);
476 {
477 // Note that we have an entry, and entries can be deleted only during GC,
478 // so we cannot allow GC to occur while we're holding this entry.
479
480 // We're using a NoSafepointVerifier to catch any place where we
481 // might potentially do a GC at all.
482 // Dictionary::do_unloading() asserts that classes in SD are only
483 // unloaded at a safepoint. Anonymous classes are not in SD.
484 NoSafepointVerifier nosafepoint;
485 dictionary()->add_protection_domain(d_index, d_hash, klass, loader_data,
486 protection_domain, THREAD);
487 }
488 }
489 }
490
491 // We only get here if this thread finds that another thread
492 // has already claimed the placeholder token for the current operation,
493 // but that other thread either never owned or gave up the
494 // object lock
495 // Waits on SystemDictionary_lock to indicate placeholder table updated
496 // On return, caller must recheck placeholder table state
497 //
498 // We only get here if
499 // 1) custom classLoader, i.e. not bootstrap classloader
500 // 2) UnsyncloadClass not set
501 // 3) custom classLoader has broken the class loader objectLock
502 // so another thread got here in parallel
503 //
504 // lockObject must be held.
505 // Complicated dance due to lock ordering:
506 // Must first release the classloader object lock to
507 // allow initial definer to complete the class definition
508 // and to avoid deadlock
529 }
530
531 // If the class in is in the placeholder table, class loading is in progress
532 // For cases where the application changes threads to load classes, it
533 // is critical to ClassCircularity detection that we try loading
534 // the superclass on the same thread internally, so we do parallel
535 // super class loading here.
536 // This also is critical in cases where the original thread gets stalled
537 // even in non-circularity situations.
538 // Note: must call resolve_super_or_fail even if null super -
539 // to force placeholder entry creation for this class for circularity detection
540 // Caller must check for pending exception
541 // Returns non-null Klass* if other thread has completed load
542 // and we are done,
543 // If return null Klass* and no pending exception, the caller must load the class
544 InstanceKlass* SystemDictionary::handle_parallel_super_load(
545 Symbol* name, Symbol* superclassname, Handle class_loader,
546 Handle protection_domain, Handle lockObject, TRAPS) {
547
548 ClassLoaderData* loader_data = class_loader_data(class_loader);
549 unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
550 int d_index = dictionary()->hash_to_index(d_hash);
551 unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
552 int p_index = placeholders()->hash_to_index(p_hash);
553
554 // superk is not used, resolve_super called for circularity check only
555 // This code is reached in two situations. One if this thread
556 // is loading the same class twice (e.g. ClassCircularity, or
557 // java.lang.instrument).
558 // The second is if another thread started the resolve_super first
559 // and has not yet finished.
560 // In both cases the original caller will clean up the placeholder
561 // entry on error.
562 Klass* superk = SystemDictionary::resolve_super_or_fail(name,
563 superclassname,
564 class_loader,
565 protection_domain,
566 true,
567 CHECK_NULL);
568
569 // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
570 // Serial class loaders and bootstrap classloader do wait for superclass loads
571 if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
572 MutexLocker mu(SystemDictionary_lock, THREAD);
573 // Check if classloading completed while we were loading superclass or waiting
574 return find_class(d_index, d_hash, name, loader_data);
575 }
576
577 // must loop to both handle other placeholder updates
578 // and spurious notifications
579 bool super_load_in_progress = true;
580 PlaceholderEntry* placeholder;
581 while (super_load_in_progress) {
582 MutexLocker mu(SystemDictionary_lock, THREAD);
583 // Check if classloading completed while we were loading superclass or waiting
584 InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
585 if (check != NULL) {
586 // Klass is already loaded, so just return it
587 return check;
588 } else {
589 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
590 if (placeholder && placeholder->super_load_in_progress() ){
591 // Before UnsyncloadClass:
592 // We only get here if the application has released the
593 // classloader lock when another thread was in the middle of loading a
594 // superclass/superinterface for this class, and now
595 // this thread is also trying to load this class.
596 // To minimize surprises, the first thread that started to
597 // load a class should be the one to complete the loading
598 // with the classfile it initially expected.
599 // This logic has the current thread wait once it has done
600 // all the superclass/superinterface loading it can, until
601 // the original thread completes the class loading or fails
602 // If it completes we will use the resulting InstanceKlass
603 // which we will find below in the systemDictionary.
604 // We also get here for parallel bootstrap classloader
644 }
645
646 // Be careful when modifying this code: once you have run
647 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
648 // you need to find_and_remove it before returning.
649 // So be careful to not exit with a CHECK_ macro betweeen these calls.
650 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
651 Handle class_loader,
652 Handle protection_domain,
653 TRAPS) {
654 assert(name != NULL && !FieldType::is_array(name) &&
655 !FieldType::is_obj(name), "invalid class name");
656
657 Ticks class_load_start_time = Ticks::now();
658
659 HandleMark hm(THREAD);
660
661 // Fix for 4474172; see evaluation for more details
662 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
663 ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);
664
665 // Do lookup to see if class already exist and the protection domain
666 // has the right access
667 // This call uses find which checks protection domain already matches
668 // All subsequent calls use find_class, and set has_loaded_class so that
669 // before we return a result we call out to java to check for valid protection domain
670 // to allow returning the Klass* and add it to the pd_set if it is valid
671 unsigned int d_hash = dictionary()->compute_hash(name, loader_data);
672 int d_index = dictionary()->hash_to_index(d_hash);
673 Klass* probe = dictionary()->find(d_index, d_hash, name, loader_data,
674 protection_domain, THREAD);
675 if (probe != NULL) return probe;
676
677
678 // Non-bootstrap class loaders will call out to class loader and
679 // define via jvm/jni_DefineClass which will acquire the
680 // class loader object lock to protect against multiple threads
681 // defining the class in parallel by accident.
682 // This lock must be acquired here so the waiter will find
683 // any successful result in the SystemDictionary and not attempt
684 // the define
685 // ParallelCapable Classloaders and the bootstrap classloader,
686 // or all classloaders with UnsyncloadClass do not acquire lock here
687 bool DoObjectLock = true;
688 if (is_parallelCapable(class_loader)) {
689 DoObjectLock = false;
690 }
691
692 unsigned int p_hash = placeholders()->compute_hash(name, loader_data);
693 int p_index = placeholders()->hash_to_index(p_hash);
694
695 // Class is not in SystemDictionary so we have to do loading.
696 // Make sure we are synchronized on the class loader before we proceed
697 Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
698 check_loader_lock_contention(lockObject, THREAD);
699 ObjectLocker ol(lockObject, THREAD, DoObjectLock);
700
701 // Check again (after locking) if class already exist in SystemDictionary
702 bool class_has_been_loaded = false;
703 bool super_load_in_progress = false;
704 bool havesupername = false;
705 InstanceKlass* k = NULL;
706 PlaceholderEntry* placeholder;
707 Symbol* superclassname = NULL;
708
709 {
710 MutexLocker mu(SystemDictionary_lock, THREAD);
711 InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
712 if (check != NULL) {
713 // Klass is already loaded, so just return it
714 class_has_been_loaded = true;
715 k = check;
716 } else {
717 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
718 if (placeholder && placeholder->super_load_in_progress()) {
719 super_load_in_progress = true;
720 if (placeholder->havesupername() == true) {
721 superclassname = placeholder->supername();
722 havesupername = true;
723 }
724 }
725 }
726 }
727
728 // If the class is in the placeholder table, class loading is in progress
729 if (super_load_in_progress && havesupername==true) {
730 k = handle_parallel_super_load(name,
731 superclassname,
775 PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
776 if (oldprobe) {
777 // only need check_seen_thread once, not on each loop
778 // 6341374 java/lang/Instrument with -Xcomp
779 if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
780 throw_circularity_error = true;
781 } else {
782 // case 1: traditional: should never see load_in_progress.
783 while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
784
785 // case 4: bootstrap classloader: prevent futile classloading,
786 // wait on first requestor
787 if (class_loader.is_null()) {
788 SystemDictionary_lock->wait();
789 } else {
790 // case 2: traditional with broken classloader lock. wait on first
791 // requestor.
792 double_lock_wait(lockObject, THREAD);
793 }
794 // Check if classloading completed while we were waiting
795 InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
796 if (check != NULL) {
797 // Klass is already loaded, so just return it
798 k = check;
799 class_has_been_loaded = true;
800 }
801 // check if other thread failed to load and cleaned up
802 oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
803 }
804 }
805 }
806 }
807 // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
808 // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
809 // LOAD_INSTANCE in parallel
810
811 if (!throw_circularity_error && !class_has_been_loaded) {
812 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
813 load_instance_added = true;
814 // For class loaders that do not acquire the classloader object lock,
815 // if they did not catch another thread holding LOAD_INSTANCE,
816 // need a check analogous to the acquire ObjectLocker/find_class
817 // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
818 // one final check if the load has already completed
819 // class loaders holding the ObjectLock shouldn't find the class here
820 InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
821 if (check != NULL) {
822 // Klass is already loaded, so return it after checking/adding protection domain
823 k = check;
824 class_has_been_loaded = true;
825 }
826 }
827 }
828
829 // must throw error outside of owning lock
830 if (throw_circularity_error) {
831 assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
832 ResourceMark rm(THREAD);
833 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
834 }
835
836 if (!class_has_been_loaded) {
837
838 // Do actual loading
839 k = load_instance_class(name, class_loader, THREAD);
840
841 // For UnsyncloadClass only
842 // If they got a linkageError, check if a parallel class load succeeded.
843 // If it did, then for bytecode resolution the specification requires
844 // that we return the same result we did for the other thread, i.e. the
845 // successfully loaded InstanceKlass
846 // Should not get here for classloaders that support parallelism
847 // with the new cleaner mechanism, even with AllowParallelDefineClass
848 // Bootstrap goes through here to allow for an extra guarantee check
849 if (UnsyncloadClass || (class_loader.is_null())) {
850 if (k == NULL && HAS_PENDING_EXCEPTION
851 && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
852 MutexLocker mu(SystemDictionary_lock, THREAD);
853 InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
854 if (check != NULL) {
855 // Klass is already loaded, so just use it
856 k = check;
857 CLEAR_PENDING_EXCEPTION;
858 guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
859 }
860 }
861 }
862
863 // If everything was OK (no exceptions, no null return value), and
864 // class_loader is NOT the defining loader, do a little more bookkeeping.
865 if (!HAS_PENDING_EXCEPTION && k != NULL &&
866 k->class_loader() != class_loader()) {
867
868 check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
869
870 // Need to check for a PENDING_EXCEPTION again; check_constraints
871 // can throw and doesn't use the CHECK macro.
872 if (!HAS_PENDING_EXCEPTION) {
873 { // Grabbing the Compile_lock prevents systemDictionary updates
874 // during compilations.
875 MutexLocker mu(Compile_lock, THREAD);
876 update_dictionary(d_index, d_hash, p_index, p_hash,
877 k, class_loader, THREAD);
878 }
879
880 if (JvmtiExport::should_post_class_load()) {
881 Thread *thread = THREAD;
882 assert(thread->is_Java_thread(), "thread->is_Java_thread()");
883 JvmtiExport::post_class_load((JavaThread *) thread, k);
884 }
885 }
886 }
887 } // load_instance_class loop
888
889 if (load_instance_added == true) {
890 // clean up placeholder entries for LOAD_INSTANCE success or error
891 // This brackets the SystemDictionary updates for both defining
892 // and initiating loaders
893 MutexLocker mu(SystemDictionary_lock, THREAD);
894 placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
895 SystemDictionary_lock->notify_all();
896 }
897 }
898
899 if (HAS_PENDING_EXCEPTION || k == NULL) {
900 return NULL;
901 }
902
903 post_class_load_event(class_load_start_time, k, loader_data);
904
905 #ifdef ASSERT
906 {
907 ClassLoaderData* loader_data = k->class_loader_data();
908 MutexLocker mu(SystemDictionary_lock, THREAD);
909 Klass* kk = find_class(name, loader_data);
910 assert(kk == k, "should be present in dictionary");
911 }
912 #endif
913
914 // return if the protection domain in NULL
915 if (protection_domain() == NULL) return k;
916
917 // Check the protection domain has the right access
918 {
919 MutexLocker mu(SystemDictionary_lock, THREAD);
920 // Note that we have an entry, and entries can be deleted only during GC,
921 // so we cannot allow GC to occur while we're holding this entry.
922 // We're using a NoSafepointVerifier to catch any place where we
923 // might potentially do a GC at all.
924 // Dictionary::do_unloading() asserts that classes in SD are only
925 // unloaded at a safepoint. Anonymous classes are not in SD.
926 NoSafepointVerifier nosafepoint;
927 if (dictionary()->is_valid_protection_domain(d_index, d_hash, name,
928 loader_data,
929 protection_domain)) {
930 return k;
931 }
932 }
933
934 // Verify protection domain. If it fails an exception is thrown
935 validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
936
937 return k;
938 }
939
940
941 // This routine does not lock the system dictionary.
942 //
943 // Since readers don't hold a lock, we must make sure that system
944 // dictionary entries are only removed at a safepoint (when only one
945 // thread is running), and are added to in a safe way (all links must
946 // be updated in an MT-safe manner).
947 //
948 // Callers should be aware that an entry could be added just after
949 // _dictionary->bucket(index) is read here, so the caller will not see
950 // the new entry.
951
952 Klass* SystemDictionary::find(Symbol* class_name,
953 Handle class_loader,
954 Handle protection_domain,
955 TRAPS) {
956
957 // The result of this call should be consistent with the result
958 // of the call to resolve_instance_class_or_null().
959 // See evaluation 6790209 and 4474172 for more details.
960 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
961 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
962
963 if (loader_data == NULL) {
964 // If the ClassLoaderData has not been setup,
965 // then the class loader has no entries in the dictionary.
966 return NULL;
967 }
968
969 unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
970 int d_index = dictionary()->hash_to_index(d_hash);
971
972 {
973 // Note that we have an entry, and entries can be deleted only during GC,
974 // so we cannot allow GC to occur while we're holding this entry.
975 // We're using a NoSafepointVerifier to catch any place where we
976 // might potentially do a GC at all.
977 // Dictionary::do_unloading() asserts that classes in SD are only
978 // unloaded at a safepoint. Anonymous classes are not in SD.
979 NoSafepointVerifier nosafepoint;
980 return dictionary()->find(d_index, d_hash, class_name, loader_data,
981 protection_domain, THREAD);
982 }
983 }
984
985
986 // Look for a loaded instance or array klass by name. Do not do any loading.
987 // return NULL in case of error.
988 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
989 Handle class_loader,
990 Handle protection_domain,
991 TRAPS) {
992 Klass* k = NULL;
993 assert(class_name != NULL, "class name must be non NULL");
994
995 if (FieldType::is_array(class_name)) {
996 // The name refers to an array. Parse the name.
997 // dimension and object_key in FieldArrayInfo are assigned as a
998 // side-effect of this call
999 FieldArrayInfo fd;
1000 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
1001 if (t != T_OBJECT) {
1002 k = Universe::typeArrayKlassObj(t);
1016 // does not publish the classes via the SystemDictionary.
1017 // Handles unsafe_DefineAnonymousClass and redefineclasses
1018 // RedefinedClasses do not add to the class hierarchy
1019 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name,
1020 Handle class_loader,
1021 Handle protection_domain,
1022 ClassFileStream* st,
1023 const InstanceKlass* host_klass,
1024 GrowableArray<Handle>* cp_patches,
1025 TRAPS) {
1026
1027 Ticks class_load_start_time = Ticks::now();
1028
1029 ClassLoaderData* loader_data;
1030 if (host_klass != NULL) {
1031 // Create a new CLD for anonymous class, that uses the same class loader
1032 // as the host_klass
1033 guarantee(host_klass->class_loader() == class_loader(), "should be the same");
1034 guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
1035 loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);
1036 loader_data->record_dependency(host_klass, CHECK_NULL);
1037 } else {
1038 loader_data = ClassLoaderData::class_loader_data(class_loader());
1039 }
1040
1041 assert(st != NULL, "invariant");
1042 assert(st->need_verify(), "invariant");
1043
1044 // Parse stream and create a klass.
1045 // Note that we do this even though this klass might
1046 // already be present in the SystemDictionary, otherwise we would not
1047 // throw potential ClassFormatErrors.
1048
1049 InstanceKlass* k = KlassFactory::create_from_stream(st,
1050 class_name,
1051 loader_data,
1052 protection_domain,
1053 host_klass,
1054 cp_patches,
1055 CHECK_NULL);
1056
1170 if (HAS_PENDING_EXCEPTION) {
1171 assert(k != NULL, "Must have an instance klass here!");
1172 loader_data->add_to_deallocate_list(k);
1173 return NULL;
1174 }
1175
1176 // Make sure we have an entry in the SystemDictionary on success
1177 debug_only( {
1178 MutexLocker mu(SystemDictionary_lock, THREAD);
1179
1180 Klass* check = find_class(h_name, k->class_loader_data());
1181 assert(check == k, "should be present in the dictionary");
1182 } );
1183
1184 return k;
1185 }
1186
1187 #if INCLUDE_CDS
1188 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
1189 int number_of_entries) {
1190 assert(length == _nof_buckets * sizeof(HashtableBucket<mtClass>),
1191 "bad shared dictionary size.");
1192 _shared_dictionary = new Dictionary(_nof_buckets, t, number_of_entries);
1193 }
1194
1195
1196 // If there is a shared dictionary, then find the entry for the
1197 // given shared system class, if any.
1198
1199 InstanceKlass* SystemDictionary::find_shared_class(Symbol* class_name) {
1200 if (shared_dictionary() != NULL) {
1201 unsigned int d_hash = shared_dictionary()->compute_hash(class_name, NULL);
1202 int d_index = shared_dictionary()->hash_to_index(d_hash);
1203
1204 return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1205 } else {
1206 return NULL;
1207 }
1208 }
1209
1210
1211 // Load a class from the shared spaces (found through the shared system
1212 // dictionary). Force the superclass and all interfaces to be loaded.
1213 // Update the class definition to include sibling classes and no
1214 // subclasses (yet). [Classes in the shared space are not part of the
1215 // object hierarchy until loaded.]
1216
1217 InstanceKlass* SystemDictionary::load_shared_class(
1218 Symbol* class_name, Handle class_loader, TRAPS) {
1219 InstanceKlass* ik = find_shared_class(class_name);
1220 // Make sure we only return the boot class for the NULL classloader.
1221 if (ik != NULL &&
1607 // use placeholder token
1608 // If a parallelCapable class loader calls define_instance_class instead of
1609 // find_or_define_instance_class to get here, we have a timing
1610 // hole with systemDictionary updates and check_constraints
1611 if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1612 assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1613 compute_loader_lock_object(class_loader_h, THREAD)),
1614 "define called without lock");
1615 }
1616
1617 // Check class-loading constraints. Throw exception if violation is detected.
1618 // Grabs and releases SystemDictionary_lock
1619 // The check_constraints/find_class call and update_dictionary sequence
1620 // must be "atomic" for a specific class/classloader pair so we never
1621 // define two different instanceKlasses for that class/classloader pair.
1622 // Existing classloaders will call define_instance_class with the
1623 // classloader lock held
1624 // Parallel classloaders will call find_or_define_instance_class
1625 // which will require a token to perform the define class
1626 Symbol* name_h = k->name();
1627 unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1628 int d_index = dictionary()->hash_to_index(d_hash);
1629 check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1630
1631 // Register class just loaded with class loader (placed in Vector)
1632 // Note we do this before updating the dictionary, as this can
1633 // fail with an OutOfMemoryError (if it does, we will *not* put this
1634 // class in the dictionary and will not update the class hierarchy).
1635 // JVMTI FollowReferences needs to find the classes this way.
1636 if (k->class_loader() != NULL) {
1637 methodHandle m(THREAD, Universe::loader_addClass_method());
1638 JavaValue result(T_VOID);
1639 JavaCallArguments args(class_loader_h);
1640 args.push_oop(Handle(THREAD, k->java_mirror()));
1641 JavaCalls::call(&result, m, &args, CHECK);
1642 }
1643
1644 // Add the new class. We need recompile lock during update of CHA.
1645 {
1646 unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1647 int p_index = placeholders()->hash_to_index(p_hash);
1648
1649 MutexLocker mu_r(Compile_lock, THREAD);
1650
1651 // Add to class hierarchy, initialize vtables, and do possible
1652 // deoptimizations.
1653 add_to_hierarchy(k, CHECK); // No exception, but can block
1654
1655 // Add to systemDictionary - so other classes can see it.
1656 // Grabs and releases SystemDictionary_lock
1657 update_dictionary(d_index, d_hash, p_index, p_hash,
1658 k, class_loader_h, THREAD);
1659 }
1660 k->eager_initialize(THREAD);
1661
1662 // notify jvmti
1663 if (JvmtiExport::should_post_class_load()) {
1664 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1665 JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1666
1676 // FindLoadedClass/DefineClass, calls, we check for parallel
1677 // loading for them, wait if a defineClass is in progress
1678 // and return the initial requestor's results
1679 // This flag does not apply to the bootstrap classloader.
1680 // With AllowParallelDefine flag==false, call through to define_instance_class
1681 // which will throw LinkageError: duplicate class definition.
1682 // False is the requested default.
1683 // For better performance, the class loaders should synchronize
1684 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1685 // potentially waste time reading and parsing the bytestream.
1686 // Note: VM callers should ensure consistency of k/class_name,class_loader
1687 // Be careful when modifying this code: once you have run
1688 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1689 // you need to find_and_remove it before returning.
1690 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1691 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1692 InstanceKlass* k, TRAPS) {
1693
1694 Symbol* name_h = k->name(); // passed in class_name may be null
1695 ClassLoaderData* loader_data = class_loader_data(class_loader);
1696
1697 unsigned int d_hash = dictionary()->compute_hash(name_h, loader_data);
1698 int d_index = dictionary()->hash_to_index(d_hash);
1699
1700 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1701 unsigned int p_hash = placeholders()->compute_hash(name_h, loader_data);
1702 int p_index = placeholders()->hash_to_index(p_hash);
1703 PlaceholderEntry* probe;
1704
1705 {
1706 MutexLocker mu(SystemDictionary_lock, THREAD);
1707 // First check if class already defined
1708 if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1709 InstanceKlass* check = find_class(d_index, d_hash, name_h, loader_data);
1710 if (check != NULL) {
1711 return check;
1712 }
1713 }
1714
1715 // Acquire define token for this class/classloader
1716 probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1717 // Wait if another thread defining in parallel
1718 // All threads wait - even those that will throw duplicate class: otherwise
1719 // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1720 // if other thread has not finished updating dictionary
1721 while (probe->definer() != NULL) {
1722 SystemDictionary_lock->wait();
1723 }
1724 // Only special cases allow parallel defines and can use other thread's results
1725 // Other cases fall through, and may run into duplicate defines
1726 // caught by finding an entry in the SystemDictionary
1727 if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1728 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1729 SystemDictionary_lock->notify_all();
1730 #ifdef ASSERT
1731 InstanceKlass* check = find_class(d_index, d_hash, name_h, loader_data);
1732 assert(check != NULL, "definer missed recording success");
1733 #endif
1734 return probe->instance_klass();
1735 } else {
1736 // This thread will define the class (even if earlier thread tried and had an error)
1737 probe->set_definer(THREAD);
1738 }
1739 }
1740
1741 define_instance_class(k, THREAD);
1742
1743 Handle linkage_exception = Handle(); // null handle
1744
1745 // definer must notify any waiting threads
1746 {
1747 MutexLocker mu(SystemDictionary_lock, THREAD);
1748 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1749 assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1750 if (probe != NULL) {
1751 if (HAS_PENDING_EXCEPTION) {
1752 linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1753 CLEAR_PENDING_EXCEPTION;
1754 } else {
1755 probe->set_instance_klass(k);
1756 }
1757 probe->set_definer(NULL);
1758 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1759 SystemDictionary_lock->notify_all();
1760 }
1761 }
1762
1763 // Can't throw exception while holding lock due to rank ordering
1764 if (linkage_exception() != NULL) {
1765 THROW_OOP_(linkage_exception(), NULL); // throws exception and returns
1766 }
1767
1768 return k;
1769 }
1770 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1771 // If class_loader is NULL we synchronize on _system_loader_lock_obj
1772 if (class_loader.is_null()) {
1773 return Handle(THREAD, _system_loader_lock_obj);
1774 } else {
1775 return class_loader;
1776 }
1777 }
1778
1779 // This method is added to check how often we have to wait to grab loader
1780 // lock. The results are being recorded in the performance counters defined in
1781 // ClassLoader::_sync_systemLoaderLockContentionRate and
1782 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1783 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1784 if (!UsePerfData) {
1785 return;
1786 }
1787
1788 assert(!loader_lock.is_null(), "NULL lock object");
1789
1790 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1791 == ObjectSynchronizer::owner_other) {
1792 // contention will likely happen, so increment the corresponding
1793 // contention counter.
1794 if (loader_lock() == _system_loader_lock_obj) {
1795 ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1796 } else {
1797 ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1798 }
1799 }
1800 }
1801
1802 // ----------------------------------------------------------------------------
1803 // Lookup
1804
1805 InstanceKlass* SystemDictionary::find_class(int index, unsigned int hash,
1806 Symbol* class_name,
1807 ClassLoaderData* loader_data) {
1808 assert_locked_or_safepoint(SystemDictionary_lock);
1809 assert (index == dictionary()->index_for(class_name, loader_data),
1810 "incorrect index?");
1811
1812 return dictionary()->find_class(index, hash, class_name, loader_data);
1813 }
1814
1815
1816 // Basic find on classes in the midst of being loaded
1817 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1818 ClassLoaderData* loader_data) {
1819 assert_locked_or_safepoint(SystemDictionary_lock);
1820 unsigned int p_hash = placeholders()->compute_hash(class_name, loader_data);
1821 int p_index = placeholders()->hash_to_index(p_hash);
1822 return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1823 }
1824
1825
1826 // Used for assertions and verification only
1827 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1828 #ifndef ASSERT
1829 guarantee(VerifyBeforeGC ||
1830 VerifyDuringGC ||
1831 VerifyBeforeExit ||
1832 VerifyDuringStartup ||
1833 VerifyAfterGC, "too expensive");
1834 #endif
1835 assert_locked_or_safepoint(SystemDictionary_lock);
1836
1837 // First look in the loaded class array
1838 unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
1839 int d_index = dictionary()->hash_to_index(d_hash);
1840 return find_class(d_index, d_hash, class_name, loader_data);
1841 }
1842
1843
1844 // Get the next class in the dictionary.
1845 Klass* SystemDictionary::try_get_next_class() {
1846 return dictionary()->try_get_next_class();
1847 }
1848
1849
1850 // ----------------------------------------------------------------------------
1851 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1852 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1853 // before a new class is used.
1854
1855 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) {
1856 assert(k != NULL, "just checking");
1857 assert_locked_or_safepoint(Compile_lock);
1858
1859 // Link into hierachy. Make sure the vtables are initialized before linking into
1860 k->append_to_sibling_list(); // add to superklass/sibling list
1861 k->process_interfaces(THREAD); // handle all "implements" declarations
1862 k->set_init_state(InstanceKlass::loaded);
1863 // Now flush all code that depended on old class hierarchy.
1864 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1865 // Also, first reinitialize vtable because it may have gotten out of synch
1866 // while the new class wasn't connected to the class hierarchy.
1867 CodeCache::flush_dependents_on(k);
1868 }
1869
1870 // ----------------------------------------------------------------------------
1871 // GC support
1872
1873 // Following roots during mark-sweep is separated in two phases.
1874 //
1875 // The first phase follows preloaded classes and all other system
1876 // classes, since these will never get unloaded anyway.
1877 //
1878 // The second phase removes (unloads) unreachable classes from the
1879 // system dictionary and follows the remaining classes' contents.
1880
1881 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1882 roots_oops_do(blk, NULL);
1883 }
1884
1885 // Calculate a "good" systemdictionary size based
1886 // on predicted or current loaded classes count
1887 int SystemDictionary::calculate_systemdictionary_size(int classcount) {
1888 int newsize = _old_default_sdsize;
1889 if ((classcount > 0) && !DumpSharedSpaces) {
1890 int desiredsize = classcount/_average_depth_goal;
1891 for (newsize = _primelist[_sdgeneration]; _sdgeneration < _prime_array_size -1;
1892 newsize = _primelist[++_sdgeneration]) {
1893 if (desiredsize <= newsize) {
1894 break;
1895 }
1896 }
1897 }
1898 return newsize;
1899 }
1900
1901 #ifdef ASSERT
1902 class VerifySDReachableAndLiveClosure : public OopClosure {
1903 private:
1904 BoolObjectClosure* _is_alive;
1905
1906 template <class T> void do_oop_work(T* p) {
1907 oop obj = oopDesc::load_decode_heap_oop(p);
1908 guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live");
1909 }
1910
1911 public:
1912 VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }
1913
1914 virtual void do_oop(oop* p) { do_oop_work(p); }
1915 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
1916 };
1917 #endif
1918
1919 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1920 // Note: anonymous classes are not in the SD.
1921 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive,
1922 GCTimer* gc_timer,
1923 bool do_cleaning) {
1924
1925
1926 bool unloading_occurred;
1927 {
1928 GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1929
1930 // First, mark for unload all ClassLoaderData referencing a dead class loader.
1931 unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive,
1932 do_cleaning);
1933 }
1934
1935 if (unloading_occurred) {
1936 GCTraceTime(Debug, gc, phases) t("Dictionary", gc_timer);
1937 dictionary()->do_unloading();
1938 constraints()->purge_loader_constraints();
1939 resolution_errors()->purge_resolution_errors();
1940 }
1941
1942 {
1943 GCTraceTime(Debug, gc, phases) t("ProtectionDomainCacheTable", gc_timer);
1944 // Oops referenced by the system dictionary may get unreachable independently
1945 // of the class loader (eg. cached protection domain oops). So we need to
1946 // explicitly unlink them here instead of in Dictionary::do_unloading.
1947 dictionary()->unlink(is_alive);
1948 #ifdef ASSERT
1949 VerifySDReachableAndLiveClosure cl(is_alive);
1950 dictionary()->oops_do(&cl);
1951 #endif
1952 }
1953
1954 if (do_cleaning) {
1955 GCTraceTime(Debug, gc, phases) t("ResolvedMethodTable", gc_timer);
1956 ResolvedMethodTable::unlink(is_alive);
1957 }
1958
1959 return unloading_occurred;
1960 }
1961
1962 void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
1963 strong->do_oop(&_java_system_loader);
1964 strong->do_oop(&_system_loader_lock_obj);
1965 CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
1966
1967 // Adjust dictionary
1968 dictionary()->roots_oops_do(strong, weak);
1969
1970 // Visit extra methods
1971 invoke_method_table()->oops_do(strong);
1972
1973 if (weak != NULL) {
1974 ResolvedMethodTable::oops_do(weak);
1975 }
1976 }
1977
1978 void SystemDictionary::oops_do(OopClosure* f) {
1979 f->do_oop(&_java_system_loader);
1980 f->do_oop(&_system_loader_lock_obj);
1981 CDS_ONLY(SystemDictionaryShared::oops_do(f);)
1982
1983 // Adjust dictionary
1984 dictionary()->oops_do(f);
1985
1986 // Visit extra methods
1987 invoke_method_table()->oops_do(f);
1988
1989 ResolvedMethodTable::oops_do(f);
1990 }
1991
1992 // Just the classes from defining class loaders
1993 // Don't iterate over placeholders
1994 void SystemDictionary::classes_do(void f(Klass*)) {
1995 dictionary()->classes_do(f);
1996 }
1997
1998 // Added for initialize_itable_for_klass
1999 // Just the classes from defining class loaders
2000 // Don't iterate over placeholders
2001 void SystemDictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {
2002 dictionary()->classes_do(f, CHECK);
2003 }
2004
2005 // All classes, and their class loaders
2006 // Don't iterate over placeholders
2007 void SystemDictionary::classes_do(void f(Klass*, ClassLoaderData*)) {
2008 dictionary()->classes_do(f);
2009 }
2010
2011 void SystemDictionary::methods_do(void f(Method*)) {
2012 // Walk methods in loaded classes
2013 ClassLoaderDataGraph::methods_do(f);
2014 // Walk method handle intrinsics
2015 invoke_method_table()->methods_do(f);
2016 }
2017
2018 void SystemDictionary::remove_classes_in_error_state() {
2019 dictionary()->remove_classes_in_error_state();
2020 }
2021
2022 // ----------------------------------------------------------------------------
2023 // Lazily load klasses
2024
2025 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
2026 // if multiple threads calling this function, only one thread will load
2027 // the class. The other threads will find the loaded version once the
2028 // class is loaded.
2029 Klass* aos = _abstract_ownable_synchronizer_klass;
2030 if (aos == NULL) {
2031 Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
2032 // Force a fence to prevent any read before the write completes
2033 OrderAccess::fence();
2034 _abstract_ownable_synchronizer_klass = InstanceKlass::cast(k);
2035 }
2036 }
2037
2038 // ----------------------------------------------------------------------------
2039 // Initialization
2040
2041 void SystemDictionary::initialize(TRAPS) {
2042 // Allocate arrays
2043 assert(dictionary() == NULL,
2044 "SystemDictionary should only be initialized once");
2045 _sdgeneration = 0;
2046 _dictionary = new Dictionary(calculate_systemdictionary_size(PredictedLoadedClassCount));
2047 _placeholders = new PlaceholderTable(_nof_buckets);
2048 _number_of_modifications = 0;
2049 _loader_constraints = new LoaderConstraintTable(_loader_constraint_size);
2050 _resolution_errors = new ResolutionErrorTable(_resolution_error_size);
2051 _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
2052
2053 // Allocate private object used as system class loader lock
2054 _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
2055 // Initialize basic classes
2056 initialize_preloaded_classes(CHECK);
2057 }
2058
2059 // Compact table of directions on the initialization of klasses:
2060 static const short wk_init_info[] = {
2061 #define WK_KLASS_INIT_INFO(name, symbol, option) \
2062 ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
2063 << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
2064 | (int)SystemDictionary::option ),
2065 WK_KLASSES_DO(WK_KLASS_INIT_INFO)
2066 #undef WK_KLASS_INIT_INFO
2067 0
2068 };
2069
2070 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
2071 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
2199 // Constraints on class loaders. The details of the algorithm can be
2200 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2201 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is
2202 // that the system dictionary needs to maintain a set of contraints that
2203 // must be satisfied by all classes in the dictionary.
2204 // if defining is true, then LinkageError if already in systemDictionary
2205 // if initiating loader, then ok if InstanceKlass matches existing entry
2206
2207 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
2208 InstanceKlass* k,
2209 Handle class_loader, bool defining,
2210 TRAPS) {
2211 const char *linkage_error1 = NULL;
2212 const char *linkage_error2 = NULL;
2213 {
2214 Symbol* name = k->name();
2215 ClassLoaderData *loader_data = class_loader_data(class_loader);
2216
2217 MutexLocker mu(SystemDictionary_lock, THREAD);
2218
2219 InstanceKlass* check = find_class(d_index, d_hash, name, loader_data);
2220 if (check != NULL) {
2221 // if different InstanceKlass - duplicate class definition,
2222 // else - ok, class loaded by a different thread in parallel,
2223 // we should only have found it if it was done loading and ok to use
2224 // system dictionary only holds instance classes, placeholders
2225 // also holds array classes
2226
2227 assert(check->is_instance_klass(), "noninstance in systemdictionary");
2228 if ((defining == true) || (k != check)) {
2229 linkage_error1 = "loader (instance of ";
2230 linkage_error2 = "): attempted duplicate class definition for name: \"";
2231 } else {
2232 return;
2233 }
2234 }
2235
2236 #ifdef ASSERT
2237 Symbol* ph_check = find_placeholder(name, loader_data);
2238 assert(ph_check == NULL || ph_check == name, "invalid symbol");
2239 #endif
2281 // klass.
2282 // Note that this must be done past the last potential blocking
2283 // point / safepoint. We enable biased locking lazily using a
2284 // VM_Operation to iterate the SystemDictionary and installing the
2285 // biasable mark word into each InstanceKlass's prototype header.
2286 // To avoid race conditions where we accidentally miss enabling the
2287 // optimization for one class in the process of being added to the
2288 // dictionary, we must not safepoint after the test of
2289 // BiasedLocking::enabled().
2290 if (UseBiasedLocking && BiasedLocking::enabled()) {
2291 // Set biased locking bit for all loaded classes; it will be
2292 // cleared if revocation occurs too often for this type
2293 // NOTE that we must only do this when the class is initally
2294 // defined, not each time it is referenced from a new class loader
2295 if (k->class_loader() == class_loader()) {
2296 k->set_prototype_header(markOopDesc::biased_locking_prototype());
2297 }
2298 }
2299
2300 // Make a new system dictionary entry.
2301 InstanceKlass* sd_check = find_class(d_index, d_hash, name, loader_data);
2302 if (sd_check == NULL) {
2303 dictionary()->add_klass(name, loader_data, k);
2304 notice_modification();
2305 }
2306 #ifdef ASSERT
2307 sd_check = find_class(d_index, d_hash, name, loader_data);
2308 assert (sd_check != NULL, "should have entry in system dictionary");
2309 // Note: there may be a placeholder entry: for circularity testing
2310 // or for parallel defines
2311 #endif
2312 SystemDictionary_lock->notify_all();
2313 }
2314 }
2315
2316
2317 // Try to find a class name using the loader constraints. The
2318 // loader constraints might know about a class that isn't fully loaded
2319 // yet and these will be ignored.
2320 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2321 Symbol* class_name, Handle class_loader, TRAPS) {
2322
2323 // First see if it has been loaded directly.
2324 // Force the protection domain to be null. (This removes protection checks.)
2325 Handle no_protection_domain;
2326 Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2327 no_protection_domain, CHECK_NULL);
2328 if (klass != NULL)
2329 return klass;
2330
2331 // Now look to see if it has been loaded elsewhere, and is subject to
2361 Handle class_loader2,
2362 Thread* THREAD) {
2363 ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2364 ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2365
2366 Symbol* constraint_name = NULL;
2367 if (!FieldType::is_array(class_name)) {
2368 constraint_name = class_name;
2369 } else {
2370 // For array classes, their Klass*s are not kept in the
2371 // constraint table. The element classes are.
2372 FieldArrayInfo fd;
2373 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2374 // primitive types always pass
2375 if (t != T_OBJECT) {
2376 return true;
2377 } else {
2378 constraint_name = fd.object_key();
2379 }
2380 }
2381 unsigned int d_hash1 = dictionary()->compute_hash(constraint_name, loader_data1);
2382 int d_index1 = dictionary()->hash_to_index(d_hash1);
2383
2384 unsigned int d_hash2 = dictionary()->compute_hash(constraint_name, loader_data2);
2385 int d_index2 = dictionary()->hash_to_index(d_hash2);
2386 {
2387 MutexLocker mu_s(SystemDictionary_lock, THREAD);
2388
2389 // Better never do a GC while we're holding these oops
2390 NoSafepointVerifier nosafepoint;
2391
2392 InstanceKlass* klass1 = find_class(d_index1, d_hash1, constraint_name, loader_data1);
2393 InstanceKlass* klass2 = find_class(d_index2, d_hash2, constraint_name, loader_data2);
2394 return constraints()->add_entry(constraint_name, klass1, class_loader1,
2395 klass2, class_loader2);
2396 }
2397 }
2398
2399 // Add entry to resolution error table to record the error when the first
2400 // attempt to resolve a reference to a class has failed.
2401 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2402 Symbol* error, Symbol* message) {
2403 unsigned int hash = resolution_errors()->compute_hash(pool, which);
2404 int index = resolution_errors()->hash_to_index(hash);
2405 {
2406 MutexLocker ml(SystemDictionary_lock, Thread::current());
2407 resolution_errors()->add_entry(index, hash, pool, which, error, message);
2408 }
2409 }
2410
2411 // Delete a resolution error for RedefineClasses for a constant pool is going away
2412 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2413 resolution_errors()->delete_entry(pool);
2825
2826 // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2827 JavaCallArguments args;
2828 args.push_oop(Handle(THREAD, caller->java_mirror()));
2829 args.push_oop(bsm);
2830 args.push_oop(method_name);
2831 args.push_oop(method_type);
2832 args.push_oop(info);
2833 args.push_oop(appendix_box);
2834 JavaValue result(T_OBJECT);
2835 JavaCalls::call_static(&result,
2836 SystemDictionary::MethodHandleNatives_klass(),
2837 vmSymbols::linkCallSite_name(),
2838 vmSymbols::linkCallSite_signature(),
2839 &args, CHECK_(empty));
2840 Handle mname(THREAD, (oop) result.get_jobject());
2841 (*method_type_result) = method_type;
2842 return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);
2843 }
2844
2845 // Since the identity hash code for symbols changes when the symbols are
2846 // moved from the regular perm gen (hash in the mark word) to the shared
2847 // spaces (hash is the address), the classes loaded into the dictionary
2848 // may be in the wrong buckets.
2849
2850 void SystemDictionary::reorder_dictionary() {
2851 dictionary()->reorder_dictionary();
2852 }
2853
2854
2855 void SystemDictionary::copy_buckets(char** top, char* end) {
2856 dictionary()->copy_buckets(top, end);
2857 }
2858
2859
2860 void SystemDictionary::copy_table(char** top, char* end) {
2861 dictionary()->copy_table(top, end);
2862 }
2863
2864 int SystemDictionary::number_of_classes() {
2865 return dictionary()->number_of_entries();
2866 }
2867
2868
2869 // ----------------------------------------------------------------------------
2870 void SystemDictionary::print_shared(bool details) {
2871 shared_dictionary()->print(details);
2872 }
2873
2874 void SystemDictionary::print(bool details) {
2875 dictionary()->print(details);
2876
2877 // Placeholders
2878 GCMutexLocker mu(SystemDictionary_lock);
2879 placeholders()->print();
2880
2881 // loader constraints - print under SD_lock
2882 constraints()->print();
2883 }
2884
2885
2886 void SystemDictionary::verify() {
2887 guarantee(dictionary() != NULL, "Verify of system dictionary failed");
2888 guarantee(constraints() != NULL,
2889 "Verify of loader constraints failed");
2890 guarantee(dictionary()->number_of_entries() >= 0 &&
2891 placeholders()->number_of_entries() >= 0,
2892 "Verify of system dictionary failed");
2893
2894 // Verify dictionary
2895 dictionary()->verify();
2896
2897 GCMutexLocker mu(SystemDictionary_lock);
2898 placeholders()->verify();
2899
2900 // Verify constraint table
2901 guarantee(constraints() != NULL, "Verify of loader constraints failed");
2902 constraints()->verify(dictionary(), placeholders());
2903 }
2904
2905 // caller needs ResourceMark
2906 const char* SystemDictionary::loader_name(const oop loader) {
2907 return ((loader) == NULL ? "<bootloader>" :
2908 InstanceKlass::cast((loader)->klass())->name()->as_C_string());
2909 }
2910
2911 // caller needs ResourceMark
2912 const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) {
2913 return (loader_data->class_loader() == NULL ? "<bootloader>" :
2914 SystemDictionary::loader_name(loader_data->class_loader()));
2915 }
|
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "aot/aotLoader.hpp"
27 #include "classfile/classFileParser.hpp"
28 #include "classfile/classFileStream.hpp"
29 #include "classfile/classLoader.hpp"
30 #include "classfile/classLoaderData.inline.hpp"
31 #include "classfile/classLoaderExt.hpp"
32 #include "classfile/dictionary.hpp"
33 #include "classfile/javaClasses.inline.hpp"
34 #include "classfile/klassFactory.hpp"
35 #include "classfile/loaderConstraints.hpp"
36 #include "classfile/packageEntry.hpp"
37 #include "classfile/placeholders.hpp"
38 #include "classfile/protectionDomainCache.hpp"
39 #include "classfile/resolutionErrors.hpp"
40 #include "classfile/stringTable.hpp"
41 #include "classfile/systemDictionary.hpp"
42 #include "classfile/vmSymbols.hpp"
43 #include "code/codeCache.hpp"
44 #include "compiler/compileBroker.hpp"
45 #include "gc/shared/gcLocker.hpp"
46 #include "gc/shared/gcTraceTime.inline.hpp"
47 #include "interpreter/bytecodeStream.hpp"
48 #include "interpreter/interpreter.hpp"
49 #include "logging/log.hpp"
50 #include "memory/filemap.hpp"
51 #include "memory/oopFactory.hpp"
52 #include "memory/resourceArea.hpp"
53 #include "oops/instanceKlass.hpp"
54 #include "oops/instanceRefKlass.hpp"
55 #include "oops/klass.inline.hpp"
56 #include "oops/methodData.hpp"
57 #include "oops/objArrayKlass.hpp"
58 #include "oops/objArrayOop.inline.hpp"
71 #include "runtime/javaCalls.hpp"
72 #include "runtime/mutexLocker.hpp"
73 #include "runtime/orderAccess.inline.hpp"
74 #include "runtime/signature.hpp"
75 #include "services/classLoadingService.hpp"
76 #include "services/threadService.hpp"
77 #include "trace/traceMacros.hpp"
78 #include "utilities/macros.hpp"
79 #include "utilities/ticks.hpp"
80 #if INCLUDE_CDS
81 #include "classfile/sharedClassUtil.hpp"
82 #include "classfile/systemDictionaryShared.hpp"
83 #endif
84 #if INCLUDE_JVMCI
85 #include "jvmci/jvmciRuntime.hpp"
86 #endif
87 #if INCLUDE_TRACE
88 #include "trace/tracing.hpp"
89 #endif
90
91 PlaceholderTable* SystemDictionary::_placeholders = NULL;
92 Dictionary* SystemDictionary::_shared_dictionary = NULL;
93 LoaderConstraintTable* SystemDictionary::_loader_constraints = NULL;
94 ResolutionErrorTable* SystemDictionary::_resolution_errors = NULL;
95 SymbolPropertyTable* SystemDictionary::_invoke_method_table = NULL;
96 ProtectionDomainCacheTable* SystemDictionary::_pd_cache_table = NULL;
97
98 int SystemDictionary::_number_of_modifications = 0;
99 oop SystemDictionary::_system_loader_lock_obj = NULL;
100
101 InstanceKlass* SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
102 = { NULL /*, NULL...*/ };
103
104 InstanceKlass* SystemDictionary::_box_klasses[T_VOID+1] = { NULL /*, NULL...*/ };
105
106 oop SystemDictionary::_java_system_loader = NULL;
107
108 bool SystemDictionary::_has_loadClassInternal = false;
109 bool SystemDictionary::_has_checkPackageAccess = false;
110
111 // lazily initialized klass variables
112 InstanceKlass* volatile SystemDictionary::_abstract_ownable_synchronizer_klass = NULL;
113
114 // Default ProtectionDomainCacheSize value
115
116 const int defaultProtectionDomainCacheSize = 1009;
117
118
119 // ----------------------------------------------------------------------------
120 // Java-level SystemLoader
121
122 oop SystemDictionary::java_system_loader() {
123 return _java_system_loader;
124 }
125
126 void SystemDictionary::compute_java_system_loader(TRAPS) {
127 Klass* system_klass = WK_KLASS(ClassLoader_klass);
128 JavaValue result(T_OBJECT);
129 JavaCalls::call_static(&result,
130 WK_KLASS(ClassLoader_klass),
131 vmSymbols::getSystemClassLoader_name(),
132 vmSymbols::void_classloader_signature(),
133 CHECK);
134
135 _java_system_loader = (oop)result.get_jobject();
136
137 CDS_ONLY(SystemDictionaryShared::initialize(CHECK);)
338 if (k) {
339 return k;
340 }
341 }
342 #endif // INCLUDE_CDS
343
344 // Double-check, if child class is already loaded, just return super-class,interface
345 // Don't add a placedholder if already loaded, i.e. already in system dictionary
346 // Make sure there's a placeholder for the *child* before resolving.
347 // Used as a claim that this thread is currently loading superclass/classloader
348 // Used here for ClassCircularity checks and also for heap verification
349 // (every InstanceKlass in the heap needs to be in the system dictionary
350 // or have a placeholder).
351 // Must check ClassCircularity before checking if super class is already loaded
352 //
353 // We might not already have a placeholder if this child_name was
354 // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
355 // the name of the class might not be known until the stream is actually
356 // parsed.
357 // Bugs 4643874, 4715493
358
359 ClassLoaderData* loader_data = class_loader_data(class_loader);
360 Dictionary* dictionary = loader_data->dictionary();
361 unsigned int d_hash = dictionary->compute_hash(child_name);
362 int d_index = dictionary->hash_to_index(d_hash);
363 unsigned int p_hash = placeholders()->compute_hash(child_name);
364 int p_index = placeholders()->hash_to_index(p_hash);
365 // can't throw error holding a lock
366 bool child_already_loaded = false;
367 bool throw_circularity_error = false;
368 {
369 MutexLocker mu(SystemDictionary_lock, THREAD);
370 Klass* childk = find_class(d_index, d_hash, child_name, dictionary);
371 Klass* quicksuperk;
372 // to support // loading: if child done loading, just return superclass
373 // if class_name, & class_loader don't match:
374 // if initial define, SD update will give LinkageError
375 // if redefine: compare_class_versions will give HIERARCHY_CHANGED
376 // so we don't throw an exception here.
377 // see: nsk redefclass014 & java.lang.instrument Instrument032
378 if ((childk != NULL ) && (is_superclass) &&
379 ((quicksuperk = childk->super()) != NULL) &&
380
381 ((quicksuperk->name() == class_name) &&
382 (quicksuperk->class_loader() == class_loader()))) {
383 return quicksuperk;
384 } else {
385 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
386 if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
387 throw_circularity_error = true;
388 }
389 }
390 if (!throw_circularity_error) {
426
427 void SystemDictionary::validate_protection_domain(InstanceKlass* klass,
428 Handle class_loader,
429 Handle protection_domain,
430 TRAPS) {
431 if(!has_checkPackageAccess()) return;
432
433 // Now we have to call back to java to check if the initating class has access
434 JavaValue result(T_VOID);
435 if (log_is_enabled(Debug, protectiondomain)) {
436 ResourceMark rm;
437 // Print out trace information
438 outputStream* log = Log(protectiondomain)::debug_stream();
439 log->print_cr("Checking package access");
440 log->print("class loader: "); class_loader()->print_value_on(log);
441 log->print(" protection domain: "); protection_domain()->print_value_on(log);
442 log->print(" loading: "); klass->print_value_on(log);
443 log->cr();
444 }
445
446 // This handle and the class_loader handle passed in keeps this class from
447 // being unloaded through several GC points.
448 Handle mirror(THREAD, klass->java_mirror());
449
450 InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass();
451 JavaCalls::call_special(&result,
452 class_loader,
453 system_loader,
454 vmSymbols::checkPackageAccess_name(),
455 vmSymbols::class_protectiondomain_signature(),
456 mirror,
457 protection_domain,
458 THREAD);
459
460 if (HAS_PENDING_EXCEPTION) {
461 log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
462 } else {
463 log_debug(protectiondomain)("granted");
464 }
465
466 if (HAS_PENDING_EXCEPTION) return;
467
468 // If no exception has been thrown, we have validated the protection domain
469 // Insert the protection domain of the initiating class into the set.
470 {
471 ClassLoaderData* loader_data = class_loader_data(class_loader);
472 Dictionary* dictionary = loader_data->dictionary();
473
474 Symbol* kn = klass->name();
475 unsigned int d_hash = dictionary->compute_hash(kn);
476 int d_index = dictionary->hash_to_index(d_hash);
477
478 MutexLocker mu(SystemDictionary_lock, THREAD);
479 dictionary->add_protection_domain(d_index, d_hash, klass,
480 protection_domain, THREAD);
481 }
482 }
483
484 // We only get here if this thread finds that another thread
485 // has already claimed the placeholder token for the current operation,
486 // but that other thread either never owned or gave up the
487 // object lock
488 // Waits on SystemDictionary_lock to indicate placeholder table updated
489 // On return, caller must recheck placeholder table state
490 //
491 // We only get here if
492 // 1) custom classLoader, i.e. not bootstrap classloader
493 // 2) UnsyncloadClass not set
494 // 3) custom classLoader has broken the class loader objectLock
495 // so another thread got here in parallel
496 //
497 // lockObject must be held.
498 // Complicated dance due to lock ordering:
499 // Must first release the classloader object lock to
500 // allow initial definer to complete the class definition
501 // and to avoid deadlock
522 }
523
524 // If the class in is in the placeholder table, class loading is in progress
525 // For cases where the application changes threads to load classes, it
526 // is critical to ClassCircularity detection that we try loading
527 // the superclass on the same thread internally, so we do parallel
528 // super class loading here.
529 // This also is critical in cases where the original thread gets stalled
530 // even in non-circularity situations.
531 // Note: must call resolve_super_or_fail even if null super -
532 // to force placeholder entry creation for this class for circularity detection
533 // Caller must check for pending exception
534 // Returns non-null Klass* if other thread has completed load
535 // and we are done,
536 // If return null Klass* and no pending exception, the caller must load the class
537 InstanceKlass* SystemDictionary::handle_parallel_super_load(
538 Symbol* name, Symbol* superclassname, Handle class_loader,
539 Handle protection_domain, Handle lockObject, TRAPS) {
540
541 ClassLoaderData* loader_data = class_loader_data(class_loader);
542 Dictionary* dictionary = loader_data->dictionary();
543 unsigned int d_hash = dictionary->compute_hash(name);
544 int d_index = dictionary->hash_to_index(d_hash);
545 unsigned int p_hash = placeholders()->compute_hash(name);
546 int p_index = placeholders()->hash_to_index(p_hash);
547
548 // superk is not used, resolve_super called for circularity check only
549 // This code is reached in two situations. One if this thread
550 // is loading the same class twice (e.g. ClassCircularity, or
551 // java.lang.instrument).
552 // The second is if another thread started the resolve_super first
553 // and has not yet finished.
554 // In both cases the original caller will clean up the placeholder
555 // entry on error.
556 Klass* superk = SystemDictionary::resolve_super_or_fail(name,
557 superclassname,
558 class_loader,
559 protection_domain,
560 true,
561 CHECK_NULL);
562
563 // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
564 // Serial class loaders and bootstrap classloader do wait for superclass loads
565 if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
566 MutexLocker mu(SystemDictionary_lock, THREAD);
567 // Check if classloading completed while we were loading superclass or waiting
568 return find_class(d_index, d_hash, name, dictionary);
569 }
570
571 // must loop to both handle other placeholder updates
572 // and spurious notifications
573 bool super_load_in_progress = true;
574 PlaceholderEntry* placeholder;
575 while (super_load_in_progress) {
576 MutexLocker mu(SystemDictionary_lock, THREAD);
577 // Check if classloading completed while we were loading superclass or waiting
578 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
579 if (check != NULL) {
580 // Klass is already loaded, so just return it
581 return check;
582 } else {
583 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
584 if (placeholder && placeholder->super_load_in_progress() ){
585 // Before UnsyncloadClass:
586 // We only get here if the application has released the
587 // classloader lock when another thread was in the middle of loading a
588 // superclass/superinterface for this class, and now
589 // this thread is also trying to load this class.
590 // To minimize surprises, the first thread that started to
591 // load a class should be the one to complete the loading
592 // with the classfile it initially expected.
593 // This logic has the current thread wait once it has done
594 // all the superclass/superinterface loading it can, until
595 // the original thread completes the class loading or fails
596 // If it completes we will use the resulting InstanceKlass
597 // which we will find below in the systemDictionary.
598 // We also get here for parallel bootstrap classloader
638 }
639
640 // Be careful when modifying this code: once you have run
641 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
642 // you need to find_and_remove it before returning.
643 // So be careful to not exit with a CHECK_ macro betweeen these calls.
644 Klass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
645 Handle class_loader,
646 Handle protection_domain,
647 TRAPS) {
648 assert(name != NULL && !FieldType::is_array(name) &&
649 !FieldType::is_obj(name), "invalid class name");
650
651 Ticks class_load_start_time = Ticks::now();
652
653 HandleMark hm(THREAD);
654
655 // Fix for 4474172; see evaluation for more details
656 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
657 ClassLoaderData *loader_data = register_loader(class_loader, CHECK_NULL);
658 Dictionary* dictionary = loader_data->dictionary();
659
660 // Do lookup to see if class already exist and the protection domain
661 // has the right access
662 // This call uses find which checks protection domain already matches
663 // All subsequent calls use find_class, and set has_loaded_class so that
664 // before we return a result we call out to java to check for valid protection domain
665 // to allow returning the Klass* and add it to the pd_set if it is valid
666 unsigned int d_hash = dictionary->compute_hash(name);
667 int d_index = dictionary->hash_to_index(d_hash);
668 Klass* probe = dictionary->find(d_index, d_hash, name, protection_domain);
669 if (probe != NULL) return probe;
670
671
672 // Non-bootstrap class loaders will call out to class loader and
673 // define via jvm/jni_DefineClass which will acquire the
674 // class loader object lock to protect against multiple threads
675 // defining the class in parallel by accident.
676 // This lock must be acquired here so the waiter will find
677 // any successful result in the SystemDictionary and not attempt
678 // the define
679 // ParallelCapable Classloaders and the bootstrap classloader,
680 // or all classloaders with UnsyncloadClass do not acquire lock here
681 bool DoObjectLock = true;
682 if (is_parallelCapable(class_loader)) {
683 DoObjectLock = false;
684 }
685
686 unsigned int p_hash = placeholders()->compute_hash(name);
687 int p_index = placeholders()->hash_to_index(p_hash);
688
689 // Class is not in SystemDictionary so we have to do loading.
690 // Make sure we are synchronized on the class loader before we proceed
691 Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
692 check_loader_lock_contention(lockObject, THREAD);
693 ObjectLocker ol(lockObject, THREAD, DoObjectLock);
694
695 // Check again (after locking) if class already exist in SystemDictionary
696 bool class_has_been_loaded = false;
697 bool super_load_in_progress = false;
698 bool havesupername = false;
699 InstanceKlass* k = NULL;
700 PlaceholderEntry* placeholder;
701 Symbol* superclassname = NULL;
702
703 {
704 MutexLocker mu(SystemDictionary_lock, THREAD);
705 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
706 if (check != NULL) {
707 // Klass is already loaded, so just return it
708 class_has_been_loaded = true;
709 k = check;
710 } else {
711 placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
712 if (placeholder && placeholder->super_load_in_progress()) {
713 super_load_in_progress = true;
714 if (placeholder->havesupername() == true) {
715 superclassname = placeholder->supername();
716 havesupername = true;
717 }
718 }
719 }
720 }
721
722 // If the class is in the placeholder table, class loading is in progress
723 if (super_load_in_progress && havesupername==true) {
724 k = handle_parallel_super_load(name,
725 superclassname,
769 PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
770 if (oldprobe) {
771 // only need check_seen_thread once, not on each loop
772 // 6341374 java/lang/Instrument with -Xcomp
773 if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
774 throw_circularity_error = true;
775 } else {
776 // case 1: traditional: should never see load_in_progress.
777 while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
778
779 // case 4: bootstrap classloader: prevent futile classloading,
780 // wait on first requestor
781 if (class_loader.is_null()) {
782 SystemDictionary_lock->wait();
783 } else {
784 // case 2: traditional with broken classloader lock. wait on first
785 // requestor.
786 double_lock_wait(lockObject, THREAD);
787 }
788 // Check if classloading completed while we were waiting
789 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
790 if (check != NULL) {
791 // Klass is already loaded, so just return it
792 k = check;
793 class_has_been_loaded = true;
794 }
795 // check if other thread failed to load and cleaned up
796 oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
797 }
798 }
799 }
800 }
801 // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
802 // case 3: UnsyncloadClass || case 5: parallelCapable: allow competing threads to try
803 // LOAD_INSTANCE in parallel
804
805 if (!throw_circularity_error && !class_has_been_loaded) {
806 PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
807 load_instance_added = true;
808 // For class loaders that do not acquire the classloader object lock,
809 // if they did not catch another thread holding LOAD_INSTANCE,
810 // need a check analogous to the acquire ObjectLocker/find_class
811 // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
812 // one final check if the load has already completed
813 // class loaders holding the ObjectLock shouldn't find the class here
814 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
815 if (check != NULL) {
816 // Klass is already loaded, so return it after checking/adding protection domain
817 k = check;
818 class_has_been_loaded = true;
819 }
820 }
821 }
822
823 // must throw error outside of owning lock
824 if (throw_circularity_error) {
825 assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
826 ResourceMark rm(THREAD);
827 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
828 }
829
830 if (!class_has_been_loaded) {
831
832 // Do actual loading
833 k = load_instance_class(name, class_loader, THREAD);
834
835 // For UnsyncloadClass only
836 // If they got a linkageError, check if a parallel class load succeeded.
837 // If it did, then for bytecode resolution the specification requires
838 // that we return the same result we did for the other thread, i.e. the
839 // successfully loaded InstanceKlass
840 // Should not get here for classloaders that support parallelism
841 // with the new cleaner mechanism, even with AllowParallelDefineClass
842 // Bootstrap goes through here to allow for an extra guarantee check
843 if (UnsyncloadClass || (class_loader.is_null())) {
844 if (k == NULL && HAS_PENDING_EXCEPTION
845 && PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
846 MutexLocker mu(SystemDictionary_lock, THREAD);
847 InstanceKlass* check = find_class(d_index, d_hash, name, dictionary);
848 if (check != NULL) {
849 // Klass is already loaded, so just use it
850 k = check;
851 CLEAR_PENDING_EXCEPTION;
852 guarantee((!class_loader.is_null()), "dup definition for bootstrap loader?");
853 }
854 }
855 }
856
857 // If everything was OK (no exceptions, no null return value), and
858 // class_loader is NOT the defining loader, do a little more bookkeeping.
859 if (!HAS_PENDING_EXCEPTION && k != NULL &&
860 k->class_loader() != class_loader()) {
861
862 check_constraints(d_index, d_hash, k, class_loader, false, THREAD);
863
864 // Need to check for a PENDING_EXCEPTION again; check_constraints
865 // can throw and doesn't use the CHECK macro.
866 if (!HAS_PENDING_EXCEPTION) {
867 { // Grabbing the Compile_lock prevents systemDictionary updates
868 // during compilations.
869 MutexLocker mu(Compile_lock, THREAD);
870 update_dictionary(d_index, d_hash, p_index, p_hash,
871 k, class_loader, THREAD);
872 }
873
874 if (JvmtiExport::should_post_class_load()) {
875 Thread *thread = THREAD;
876 assert(thread->is_Java_thread(), "thread->is_Java_thread()");
877 JvmtiExport::post_class_load((JavaThread *) thread, k);
878 }
879 }
880 }
881 } // load_instance_class
882
883 if (load_instance_added == true) {
884 // clean up placeholder entries for LOAD_INSTANCE success or error
885 // This brackets the SystemDictionary updates for both defining
886 // and initiating loaders
887 MutexLocker mu(SystemDictionary_lock, THREAD);
888 placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
889 SystemDictionary_lock->notify_all();
890 }
891 }
892
893 if (HAS_PENDING_EXCEPTION || k == NULL) {
894 return NULL;
895 }
896
897 post_class_load_event(class_load_start_time, k, loader_data);
898
899 #ifdef ASSERT
900 {
901 ClassLoaderData* loader_data = k->class_loader_data();
902 MutexLocker mu(SystemDictionary_lock, THREAD);
903 Klass* kk = find_class(name, loader_data);
904 assert(kk == k, "should be present in dictionary");
905 }
906 #endif
907
908 // return if the protection domain in NULL
909 if (protection_domain() == NULL) return k;
910
911 // Check the protection domain has the right access
912 {
913 MutexLocker mu(SystemDictionary_lock, THREAD);
914 if (dictionary->is_valid_protection_domain(d_index, d_hash, name,
915 protection_domain)) {
916 return k;
917 }
918 }
919
920 // Verify protection domain. If it fails an exception is thrown
921 validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
922
923 return k;
924 }
925
926
927 // This routine does not lock the system dictionary.
928 //
929 // Since readers don't hold a lock, we must make sure that system
930 // dictionary entries are only removed at a safepoint (when only one
931 // thread is running), and are added to in a safe way (all links must
932 // be updated in an MT-safe manner).
933 //
934 // Callers should be aware that an entry could be added just after
935 // _dictionary->bucket(index) is read here, so the caller will not see
936 // the new entry.
937
938 Klass* SystemDictionary::find(Symbol* class_name,
939 Handle class_loader,
940 Handle protection_domain,
941 TRAPS) {
942
943 // The result of this call should be consistent with the result
944 // of the call to resolve_instance_class_or_null().
945 // See evaluation 6790209 and 4474172 for more details.
946 class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
947 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
948
949 if (loader_data == NULL) {
950 // If the ClassLoaderData has not been setup,
951 // then the class loader has no entries in the dictionary.
952 return NULL;
953 }
954
955 Dictionary* dictionary = loader_data->dictionary_or_null();
956 // If ClassLoaderData has no dictionary, the class won't be found in it
957 if (dictionary == NULL) {
958 return NULL;
959 }
960
961 unsigned int d_hash = dictionary->compute_hash(class_name);
962 int d_index = dictionary->hash_to_index(d_hash);
963 return dictionary->find(d_index, d_hash, class_name,
964 protection_domain);
965 }
966
967
968 // Look for a loaded instance or array klass by name. Do not do any loading.
969 // return NULL in case of error.
970 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
971 Handle class_loader,
972 Handle protection_domain,
973 TRAPS) {
974 Klass* k = NULL;
975 assert(class_name != NULL, "class name must be non NULL");
976
977 if (FieldType::is_array(class_name)) {
978 // The name refers to an array. Parse the name.
979 // dimension and object_key in FieldArrayInfo are assigned as a
980 // side-effect of this call
981 FieldArrayInfo fd;
982 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
983 if (t != T_OBJECT) {
984 k = Universe::typeArrayKlassObj(t);
998 // does not publish the classes via the SystemDictionary.
999 // Handles unsafe_DefineAnonymousClass and redefineclasses
1000 // RedefinedClasses do not add to the class hierarchy
1001 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name,
1002 Handle class_loader,
1003 Handle protection_domain,
1004 ClassFileStream* st,
1005 const InstanceKlass* host_klass,
1006 GrowableArray<Handle>* cp_patches,
1007 TRAPS) {
1008
1009 Ticks class_load_start_time = Ticks::now();
1010
1011 ClassLoaderData* loader_data;
1012 if (host_klass != NULL) {
1013 // Create a new CLD for anonymous class, that uses the same class loader
1014 // as the host_klass
1015 guarantee(host_klass->class_loader() == class_loader(), "should be the same");
1016 guarantee(!DumpSharedSpaces, "must not create anonymous classes when dumping");
1017 loader_data = ClassLoaderData::anonymous_class_loader_data(class_loader(), CHECK_NULL);
1018 } else {
1019 loader_data = ClassLoaderData::class_loader_data(class_loader());
1020 }
1021
1022 assert(st != NULL, "invariant");
1023 assert(st->need_verify(), "invariant");
1024
1025 // Parse stream and create a klass.
1026 // Note that we do this even though this klass might
1027 // already be present in the SystemDictionary, otherwise we would not
1028 // throw potential ClassFormatErrors.
1029
1030 InstanceKlass* k = KlassFactory::create_from_stream(st,
1031 class_name,
1032 loader_data,
1033 protection_domain,
1034 host_klass,
1035 cp_patches,
1036 CHECK_NULL);
1037
1151 if (HAS_PENDING_EXCEPTION) {
1152 assert(k != NULL, "Must have an instance klass here!");
1153 loader_data->add_to_deallocate_list(k);
1154 return NULL;
1155 }
1156
1157 // Make sure we have an entry in the SystemDictionary on success
1158 debug_only( {
1159 MutexLocker mu(SystemDictionary_lock, THREAD);
1160
1161 Klass* check = find_class(h_name, k->class_loader_data());
1162 assert(check == k, "should be present in the dictionary");
1163 } );
1164
1165 return k;
1166 }
1167
1168 #if INCLUDE_CDS
1169 void SystemDictionary::set_shared_dictionary(HashtableBucket<mtClass>* t, int length,
1170 int number_of_entries) {
1171 assert(length == _shared_dictionary_size * sizeof(HashtableBucket<mtClass>),
1172 "bad shared dictionary size.");
1173 _shared_dictionary = new Dictionary(ClassLoaderData::the_null_class_loader_data(),
1174 _shared_dictionary_size, t, number_of_entries);
1175 }
1176
1177
1178 // If there is a shared dictionary, then find the entry for the
1179 // given shared system class, if any.
1180
1181 InstanceKlass* SystemDictionary::find_shared_class(Symbol* class_name) {
1182 if (shared_dictionary() != NULL) {
1183 unsigned int d_hash = shared_dictionary()->compute_hash(class_name);
1184 int d_index = shared_dictionary()->hash_to_index(d_hash);
1185
1186 return shared_dictionary()->find_shared_class(d_index, d_hash, class_name);
1187 } else {
1188 return NULL;
1189 }
1190 }
1191
1192
1193 // Load a class from the shared spaces (found through the shared system
1194 // dictionary). Force the superclass and all interfaces to be loaded.
1195 // Update the class definition to include sibling classes and no
1196 // subclasses (yet). [Classes in the shared space are not part of the
1197 // object hierarchy until loaded.]
1198
1199 InstanceKlass* SystemDictionary::load_shared_class(
1200 Symbol* class_name, Handle class_loader, TRAPS) {
1201 InstanceKlass* ik = find_shared_class(class_name);
1202 // Make sure we only return the boot class for the NULL classloader.
1203 if (ik != NULL &&
1589 // use placeholder token
1590 // If a parallelCapable class loader calls define_instance_class instead of
1591 // find_or_define_instance_class to get here, we have a timing
1592 // hole with systemDictionary updates and check_constraints
1593 if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1594 assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1595 compute_loader_lock_object(class_loader_h, THREAD)),
1596 "define called without lock");
1597 }
1598
1599 // Check class-loading constraints. Throw exception if violation is detected.
1600 // Grabs and releases SystemDictionary_lock
1601 // The check_constraints/find_class call and update_dictionary sequence
1602 // must be "atomic" for a specific class/classloader pair so we never
1603 // define two different instanceKlasses for that class/classloader pair.
1604 // Existing classloaders will call define_instance_class with the
1605 // classloader lock held
1606 // Parallel classloaders will call find_or_define_instance_class
1607 // which will require a token to perform the define class
1608 Symbol* name_h = k->name();
1609 Dictionary* dictionary = loader_data->dictionary();
1610 unsigned int d_hash = dictionary->compute_hash(name_h);
1611 int d_index = dictionary->hash_to_index(d_hash);
1612 check_constraints(d_index, d_hash, k, class_loader_h, true, CHECK);
1613
1614 // Register class just loaded with class loader (placed in Vector)
1615 // Note we do this before updating the dictionary, as this can
1616 // fail with an OutOfMemoryError (if it does, we will *not* put this
1617 // class in the dictionary and will not update the class hierarchy).
1618 // JVMTI FollowReferences needs to find the classes this way.
1619 if (k->class_loader() != NULL) {
1620 methodHandle m(THREAD, Universe::loader_addClass_method());
1621 JavaValue result(T_VOID);
1622 JavaCallArguments args(class_loader_h);
1623 args.push_oop(Handle(THREAD, k->java_mirror()));
1624 JavaCalls::call(&result, m, &args, CHECK);
1625 }
1626
1627 // Add the new class. We need recompile lock during update of CHA.
1628 {
1629 unsigned int p_hash = placeholders()->compute_hash(name_h);
1630 int p_index = placeholders()->hash_to_index(p_hash);
1631
1632 MutexLocker mu_r(Compile_lock, THREAD);
1633
1634 // Add to class hierarchy, initialize vtables, and do possible
1635 // deoptimizations.
1636 add_to_hierarchy(k, CHECK); // No exception, but can block
1637
1638 // Add to systemDictionary - so other classes can see it.
1639 // Grabs and releases SystemDictionary_lock
1640 update_dictionary(d_index, d_hash, p_index, p_hash,
1641 k, class_loader_h, THREAD);
1642 }
1643 k->eager_initialize(THREAD);
1644
1645 // notify jvmti
1646 if (JvmtiExport::should_post_class_load()) {
1647 assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1648 JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1649
1659 // FindLoadedClass/DefineClass, calls, we check for parallel
1660 // loading for them, wait if a defineClass is in progress
1661 // and return the initial requestor's results
1662 // This flag does not apply to the bootstrap classloader.
1663 // With AllowParallelDefine flag==false, call through to define_instance_class
1664 // which will throw LinkageError: duplicate class definition.
1665 // False is the requested default.
1666 // For better performance, the class loaders should synchronize
1667 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1668 // potentially waste time reading and parsing the bytestream.
1669 // Note: VM callers should ensure consistency of k/class_name,class_loader
1670 // Be careful when modifying this code: once you have run
1671 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1672 // you need to find_and_remove it before returning.
1673 // So be careful to not exit with a CHECK_ macro betweeen these calls.
1674 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1675 InstanceKlass* k, TRAPS) {
1676
1677 Symbol* name_h = k->name(); // passed in class_name may be null
1678 ClassLoaderData* loader_data = class_loader_data(class_loader);
1679 Dictionary* dictionary = loader_data->dictionary();
1680
1681 unsigned int d_hash = dictionary->compute_hash(name_h);
1682 int d_index = dictionary->hash_to_index(d_hash);
1683
1684 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1685 unsigned int p_hash = placeholders()->compute_hash(name_h);
1686 int p_index = placeholders()->hash_to_index(p_hash);
1687 PlaceholderEntry* probe;
1688
1689 {
1690 MutexLocker mu(SystemDictionary_lock, THREAD);
1691 // First check if class already defined
1692 if (UnsyncloadClass || (is_parallelDefine(class_loader))) {
1693 InstanceKlass* check = find_class(d_index, d_hash, name_h, dictionary);
1694 if (check != NULL) {
1695 return check;
1696 }
1697 }
1698
1699 // Acquire define token for this class/classloader
1700 probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1701 // Wait if another thread defining in parallel
1702 // All threads wait - even those that will throw duplicate class: otherwise
1703 // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1704 // if other thread has not finished updating dictionary
1705 while (probe->definer() != NULL) {
1706 SystemDictionary_lock->wait();
1707 }
1708 // Only special cases allow parallel defines and can use other thread's results
1709 // Other cases fall through, and may run into duplicate defines
1710 // caught by finding an entry in the SystemDictionary
1711 if ((UnsyncloadClass || is_parallelDefine(class_loader)) && (probe->instance_klass() != NULL)) {
1712 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1713 SystemDictionary_lock->notify_all();
1714 #ifdef ASSERT
1715 InstanceKlass* check = find_class(d_index, d_hash, name_h, dictionary);
1716 assert(check != NULL, "definer missed recording success");
1717 #endif
1718 return probe->instance_klass();
1719 } else {
1720 // This thread will define the class (even if earlier thread tried and had an error)
1721 probe->set_definer(THREAD);
1722 }
1723 }
1724
1725 define_instance_class(k, THREAD);
1726
1727 Handle linkage_exception = Handle(); // null handle
1728
1729 // definer must notify any waiting threads
1730 {
1731 MutexLocker mu(SystemDictionary_lock, THREAD);
1732 PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1733 assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1734 if (probe != NULL) {
1735 if (HAS_PENDING_EXCEPTION) {
1736 linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1737 CLEAR_PENDING_EXCEPTION;
1738 } else {
1739 probe->set_instance_klass(k);
1740 }
1741 probe->set_definer(NULL);
1742 placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1743 SystemDictionary_lock->notify_all();
1744 }
1745 }
1746
1747 // Can't throw exception while holding lock due to rank ordering
1748 if (linkage_exception() != NULL) {
1749 THROW_OOP_(linkage_exception(), NULL); // throws exception and returns
1750 }
1751
1752 return k;
1753 }
1754
1755 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1756 // If class_loader is NULL we synchronize on _system_loader_lock_obj
1757 if (class_loader.is_null()) {
1758 return Handle(THREAD, _system_loader_lock_obj);
1759 } else {
1760 return class_loader;
1761 }
1762 }
1763
1764 // This method is added to check how often we have to wait to grab loader
1765 // lock. The results are being recorded in the performance counters defined in
1766 // ClassLoader::_sync_systemLoaderLockContentionRate and
1767 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
1768 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1769 if (!UsePerfData) {
1770 return;
1771 }
1772
1773 assert(!loader_lock.is_null(), "NULL lock object");
1774
1775 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1776 == ObjectSynchronizer::owner_other) {
1777 // contention will likely happen, so increment the corresponding
1778 // contention counter.
1779 if (loader_lock() == _system_loader_lock_obj) {
1780 ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1781 } else {
1782 ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1783 }
1784 }
1785 }
1786
1787 // ----------------------------------------------------------------------------
1788 // Lookup
1789
1790 InstanceKlass* SystemDictionary::find_class(int index, unsigned int hash,
1791 Symbol* class_name,
1792 Dictionary* dictionary) {
1793 assert_locked_or_safepoint(SystemDictionary_lock);
1794 return dictionary->find_class(index, hash, class_name);
1795 }
1796
1797
1798 // Basic find on classes in the midst of being loaded
1799 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1800 ClassLoaderData* loader_data) {
1801 assert_locked_or_safepoint(SystemDictionary_lock);
1802 unsigned int p_hash = placeholders()->compute_hash(class_name);
1803 int p_index = placeholders()->hash_to_index(p_hash);
1804 return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1805 }
1806
1807
1808 // Used for assertions and verification only
1809 // Precalculating the hash and index is an optimization because there are many lookups
1810 // before adding the class.
1811 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1812 assert_locked_or_safepoint(SystemDictionary_lock);
1813 #ifndef ASSERT
1814 guarantee(VerifyBeforeGC ||
1815 VerifyDuringGC ||
1816 VerifyBeforeExit ||
1817 VerifyDuringStartup ||
1818 VerifyAfterGC, "too expensive");
1819 #endif
1820
1821 Dictionary* dictionary = loader_data->dictionary_or_null();
1822 if (dictionary == NULL) {
1823 return NULL;
1824 }
1825 unsigned int d_hash = dictionary->compute_hash(class_name);
1826 int d_index = dictionary->hash_to_index(d_hash);
1827 return find_class(d_index, d_hash, class_name, dictionary);
1828 }
1829
1830
1831 // ----------------------------------------------------------------------------
1832 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1833 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1834 // before a new class is used.
1835
1836 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) {
1837 assert(k != NULL, "just checking");
1838 assert_locked_or_safepoint(Compile_lock);
1839
1840 // Link into hierachy. Make sure the vtables are initialized before linking into
1841 k->append_to_sibling_list(); // add to superklass/sibling list
1842 k->process_interfaces(THREAD); // handle all "implements" declarations
1843 k->set_init_state(InstanceKlass::loaded);
1844 // Now flush all code that depended on old class hierarchy.
1845 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1846 // Also, first reinitialize vtable because it may have gotten out of synch
1847 // while the new class wasn't connected to the class hierarchy.
1848 CodeCache::flush_dependents_on(k);
1849 }
1850
1851 // ----------------------------------------------------------------------------
1852 // GC support
1853
1854 // Following roots during mark-sweep is separated in two phases.
1855 //
1856 // The first phase follows preloaded classes and all other system
1857 // classes, since these will never get unloaded anyway.
1858 //
1859 // The second phase removes (unloads) unreachable classes from the
1860 // system dictionary and follows the remaining classes' contents.
1861
1862 void SystemDictionary::always_strong_oops_do(OopClosure* blk) {
1863 roots_oops_do(blk, NULL);
1864 }
1865
1866
1867 #ifdef ASSERT
1868 class VerifySDReachableAndLiveClosure : public OopClosure {
1869 private:
1870 BoolObjectClosure* _is_alive;
1871
1872 template <class T> void do_oop_work(T* p) {
1873 oop obj = oopDesc::load_decode_heap_oop(p);
1874 guarantee(_is_alive->do_object_b(obj), "Oop in system dictionary must be live");
1875 }
1876
1877 public:
1878 VerifySDReachableAndLiveClosure(BoolObjectClosure* is_alive) : OopClosure(), _is_alive(is_alive) { }
1879
1880 virtual void do_oop(oop* p) { do_oop_work(p); }
1881 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
1882 };
1883 #endif
1884
1885 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1886 // Note: anonymous classes are not in the SD.
1887 bool SystemDictionary::do_unloading(BoolObjectClosure* is_alive,
1888 GCTimer* gc_timer,
1889 bool do_cleaning) {
1890
1891
1892 bool unloading_occurred;
1893 {
1894 GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1895
1896 // First, mark for unload all ClassLoaderData referencing a dead class loader.
1897 unloading_occurred = ClassLoaderDataGraph::do_unloading(is_alive,
1898 do_cleaning);
1899 }
1900
1901 if (unloading_occurred) {
1902 GCTraceTime(Debug, gc, phases) t("Dictionary", gc_timer);
1903 constraints()->purge_loader_constraints();
1904 resolution_errors()->purge_resolution_errors();
1905 }
1906
1907 {
1908 GCTraceTime(Debug, gc, phases) t("ProtectionDomainCacheTable", gc_timer);
1909 // Oops referenced by the system dictionary may get unreachable independently
1910 // of the class loader (eg. cached protection domain oops). So we need to
1911 // explicitly unlink them here.
1912 _pd_cache_table->unlink(is_alive);
1913
1914 #ifdef ASSERT
1915 VerifySDReachableAndLiveClosure cl(is_alive);
1916 _pd_cache_table->oops_do(&cl);
1917 #endif
1918 }
1919
1920 if (do_cleaning) {
1921 GCTraceTime(Debug, gc, phases) t("ResolvedMethodTable", gc_timer);
1922 ResolvedMethodTable::unlink(is_alive);
1923 }
1924
1925 return unloading_occurred;
1926 }
1927
1928 void SystemDictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
1929 strong->do_oop(&_java_system_loader);
1930 strong->do_oop(&_system_loader_lock_obj);
1931 CDS_ONLY(SystemDictionaryShared::roots_oops_do(strong);)
1932
1933 // Adjust dictionary
1934 // Do strong roots marking if the closures are the same.
1935 if (strong == weak || !ClassUnloading) {
1936 // Only the protection domain oops contain references into the heap. Iterate
1937 // over all of them.
1938 _pd_cache_table->oops_do(strong);
1939 } else {
1940 if (weak != NULL) {
1941 _pd_cache_table->oops_do(weak);
1942 }
1943 }
1944
1945 // Visit extra methods
1946 invoke_method_table()->oops_do(strong);
1947
1948 if (weak != NULL) {
1949 ResolvedMethodTable::oops_do(weak);
1950 }
1951 }
1952
1953 void SystemDictionary::oops_do(OopClosure* f) {
1954 f->do_oop(&_java_system_loader);
1955 f->do_oop(&_system_loader_lock_obj);
1956 CDS_ONLY(SystemDictionaryShared::oops_do(f);)
1957
1958 // Only the protection domain oops contain references into the heap. Iterate
1959 // over all of them.
1960 _pd_cache_table->oops_do(f);
1961
1962 // Visit extra methods
1963 invoke_method_table()->oops_do(f);
1964
1965 ResolvedMethodTable::oops_do(f);
1966 }
1967
1968 void SystemDictionary::methods_do(void f(Method*)) {
1969 // Walk methods in loaded classes
1970 ClassLoaderDataGraph::methods_do(f);
1971 // Walk method handle intrinsics
1972 invoke_method_table()->methods_do(f);
1973 }
1974
1975 void SystemDictionary::remove_classes_in_error_state() {
1976 ClassLoaderData::the_null_class_loader_data()->dictionary()->remove_classes_in_error_state();
1977 }
1978
1979 // ----------------------------------------------------------------------------
1980 // Lazily load klasses
1981
1982 void SystemDictionary::load_abstract_ownable_synchronizer_klass(TRAPS) {
1983 // if multiple threads calling this function, only one thread will load
1984 // the class. The other threads will find the loaded version once the
1985 // class is loaded.
1986 Klass* aos = _abstract_ownable_synchronizer_klass;
1987 if (aos == NULL) {
1988 Klass* k = resolve_or_fail(vmSymbols::java_util_concurrent_locks_AbstractOwnableSynchronizer(), true, CHECK);
1989 // Force a fence to prevent any read before the write completes
1990 OrderAccess::fence();
1991 _abstract_ownable_synchronizer_klass = InstanceKlass::cast(k);
1992 }
1993 }
1994
1995 // ----------------------------------------------------------------------------
1996 // Initialization
1997
1998 void SystemDictionary::initialize(TRAPS) {
1999 // Allocate arrays
2000 _placeholders = new PlaceholderTable(_placeholder_table_size);
2001 _number_of_modifications = 0;
2002 _loader_constraints = new LoaderConstraintTable(_loader_constraint_size);
2003 _resolution_errors = new ResolutionErrorTable(_resolution_error_size);
2004 _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
2005 _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize);
2006
2007 // Allocate private object used as system class loader lock
2008 _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
2009 // Initialize basic classes
2010 initialize_preloaded_classes(CHECK);
2011 }
2012
2013 // Compact table of directions on the initialization of klasses:
2014 static const short wk_init_info[] = {
2015 #define WK_KLASS_INIT_INFO(name, symbol, option) \
2016 ( ((int)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol) \
2017 << SystemDictionary::CEIL_LG_OPTION_LIMIT) \
2018 | (int)SystemDictionary::option ),
2019 WK_KLASSES_DO(WK_KLASS_INIT_INFO)
2020 #undef WK_KLASS_INIT_INFO
2021 0
2022 };
2023
2024 bool SystemDictionary::initialize_wk_klass(WKID id, int init_opt, TRAPS) {
2025 assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
2153 // Constraints on class loaders. The details of the algorithm can be
2154 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2155 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is
2156 // that the system dictionary needs to maintain a set of contraints that
2157 // must be satisfied by all classes in the dictionary.
2158 // if defining is true, then LinkageError if already in systemDictionary
2159 // if initiating loader, then ok if InstanceKlass matches existing entry
2160
2161 void SystemDictionary::check_constraints(int d_index, unsigned int d_hash,
2162 InstanceKlass* k,
2163 Handle class_loader, bool defining,
2164 TRAPS) {
2165 const char *linkage_error1 = NULL;
2166 const char *linkage_error2 = NULL;
2167 {
2168 Symbol* name = k->name();
2169 ClassLoaderData *loader_data = class_loader_data(class_loader);
2170
2171 MutexLocker mu(SystemDictionary_lock, THREAD);
2172
2173 InstanceKlass* check = find_class(d_index, d_hash, name, loader_data->dictionary());
2174 if (check != NULL) {
2175 // if different InstanceKlass - duplicate class definition,
2176 // else - ok, class loaded by a different thread in parallel,
2177 // we should only have found it if it was done loading and ok to use
2178 // system dictionary only holds instance classes, placeholders
2179 // also holds array classes
2180
2181 assert(check->is_instance_klass(), "noninstance in systemdictionary");
2182 if ((defining == true) || (k != check)) {
2183 linkage_error1 = "loader (instance of ";
2184 linkage_error2 = "): attempted duplicate class definition for name: \"";
2185 } else {
2186 return;
2187 }
2188 }
2189
2190 #ifdef ASSERT
2191 Symbol* ph_check = find_placeholder(name, loader_data);
2192 assert(ph_check == NULL || ph_check == name, "invalid symbol");
2193 #endif
2235 // klass.
2236 // Note that this must be done past the last potential blocking
2237 // point / safepoint. We enable biased locking lazily using a
2238 // VM_Operation to iterate the SystemDictionary and installing the
2239 // biasable mark word into each InstanceKlass's prototype header.
2240 // To avoid race conditions where we accidentally miss enabling the
2241 // optimization for one class in the process of being added to the
2242 // dictionary, we must not safepoint after the test of
2243 // BiasedLocking::enabled().
2244 if (UseBiasedLocking && BiasedLocking::enabled()) {
2245 // Set biased locking bit for all loaded classes; it will be
2246 // cleared if revocation occurs too often for this type
2247 // NOTE that we must only do this when the class is initally
2248 // defined, not each time it is referenced from a new class loader
2249 if (k->class_loader() == class_loader()) {
2250 k->set_prototype_header(markOopDesc::biased_locking_prototype());
2251 }
2252 }
2253
2254 // Make a new system dictionary entry.
2255 Dictionary* dictionary = loader_data->dictionary();
2256 InstanceKlass* sd_check = find_class(d_index, d_hash, name, dictionary);
2257 if (sd_check == NULL) {
2258 dictionary->add_klass(d_index, d_hash, name, k);
2259 notice_modification();
2260 }
2261 #ifdef ASSERT
2262 sd_check = find_class(d_index, d_hash, name, dictionary);
2263 assert (sd_check != NULL, "should have entry in system dictionary");
2264 // Note: there may be a placeholder entry: for circularity testing
2265 // or for parallel defines
2266 #endif
2267 SystemDictionary_lock->notify_all();
2268 }
2269 }
2270
2271
2272 // Try to find a class name using the loader constraints. The
2273 // loader constraints might know about a class that isn't fully loaded
2274 // yet and these will be ignored.
2275 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2276 Symbol* class_name, Handle class_loader, TRAPS) {
2277
2278 // First see if it has been loaded directly.
2279 // Force the protection domain to be null. (This removes protection checks.)
2280 Handle no_protection_domain;
2281 Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2282 no_protection_domain, CHECK_NULL);
2283 if (klass != NULL)
2284 return klass;
2285
2286 // Now look to see if it has been loaded elsewhere, and is subject to
2316 Handle class_loader2,
2317 Thread* THREAD) {
2318 ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2319 ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2320
2321 Symbol* constraint_name = NULL;
2322 if (!FieldType::is_array(class_name)) {
2323 constraint_name = class_name;
2324 } else {
2325 // For array classes, their Klass*s are not kept in the
2326 // constraint table. The element classes are.
2327 FieldArrayInfo fd;
2328 BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2329 // primitive types always pass
2330 if (t != T_OBJECT) {
2331 return true;
2332 } else {
2333 constraint_name = fd.object_key();
2334 }
2335 }
2336
2337 Dictionary* dictionary1 = loader_data1->dictionary();
2338 unsigned int d_hash1 = dictionary1->compute_hash(constraint_name);
2339 int d_index1 = dictionary1->hash_to_index(d_hash1);
2340
2341 Dictionary* dictionary2 = loader_data2->dictionary();
2342 unsigned int d_hash2 = dictionary2->compute_hash(constraint_name);
2343 int d_index2 = dictionary2->hash_to_index(d_hash2);
2344
2345 {
2346 MutexLocker mu_s(SystemDictionary_lock, THREAD);
2347 InstanceKlass* klass1 = find_class(d_index1, d_hash1, constraint_name, dictionary1);
2348 InstanceKlass* klass2 = find_class(d_index2, d_hash2, constraint_name, dictionary2);
2349 return constraints()->add_entry(constraint_name, klass1, class_loader1,
2350 klass2, class_loader2);
2351 }
2352 }
2353
2354 // Add entry to resolution error table to record the error when the first
2355 // attempt to resolve a reference to a class has failed.
2356 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2357 Symbol* error, Symbol* message) {
2358 unsigned int hash = resolution_errors()->compute_hash(pool, which);
2359 int index = resolution_errors()->hash_to_index(hash);
2360 {
2361 MutexLocker ml(SystemDictionary_lock, Thread::current());
2362 resolution_errors()->add_entry(index, hash, pool, which, error, message);
2363 }
2364 }
2365
2366 // Delete a resolution error for RedefineClasses for a constant pool is going away
2367 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2368 resolution_errors()->delete_entry(pool);
2780
2781 // call java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2782 JavaCallArguments args;
2783 args.push_oop(Handle(THREAD, caller->java_mirror()));
2784 args.push_oop(bsm);
2785 args.push_oop(method_name);
2786 args.push_oop(method_type);
2787 args.push_oop(info);
2788 args.push_oop(appendix_box);
2789 JavaValue result(T_OBJECT);
2790 JavaCalls::call_static(&result,
2791 SystemDictionary::MethodHandleNatives_klass(),
2792 vmSymbols::linkCallSite_name(),
2793 vmSymbols::linkCallSite_signature(),
2794 &args, CHECK_(empty));
2795 Handle mname(THREAD, (oop) result.get_jobject());
2796 (*method_type_result) = method_type;
2797 return unpack_method_and_appendix(mname, caller, appendix_box, appendix_result, THREAD);
2798 }
2799
2800 // Protection domain cache table handling
2801
2802 ProtectionDomainCacheEntry* SystemDictionary::cache_get(Handle protection_domain) {
2803 return _pd_cache_table->get(protection_domain);
2804 }
2805
2806
2807 void SystemDictionary::reorder_dictionary() {
2808 ClassLoaderData::the_null_class_loader_data()->dictionary()->reorder_dictionary();
2809 }
2810
2811
2812 void SystemDictionary::copy_buckets(char** top, char* end) {
2813 ClassLoaderData::the_null_class_loader_data()->dictionary()->copy_buckets(top, end);
2814 }
2815
2816
2817 void SystemDictionary::copy_table(char** top, char* end) {
2818 ClassLoaderData::the_null_class_loader_data()->dictionary()->copy_table(top, end);
2819 }
2820
2821 // ----------------------------------------------------------------------------
2822 void SystemDictionary::print_shared(bool details) {
2823 shared_dictionary()->print(details);
2824 }
2825
2826 void SystemDictionary::print(bool details) {
2827 if (shared_dictionary() != NULL) {
2828 tty->print_cr("Shared Dictionary");
2829 shared_dictionary()->print(details);
2830 }
2831
2832 GCMutexLocker mu(SystemDictionary_lock);
2833
2834 ClassLoaderDataGraph::print_dictionary(details);
2835
2836 // Placeholders
2837 placeholders()->print();
2838 tty->cr();
2839
2840 // loader constraints - print under SD_lock
2841 constraints()->print();
2842 tty->cr();
2843
2844 _pd_cache_table->print();
2845 tty->cr();
2846 }
2847
2848
2849 void SystemDictionary::verify() {
2850 guarantee(constraints() != NULL,
2851 "Verify of loader constraints failed");
2852 guarantee(placeholders()->number_of_entries() >= 0,
2853 "Verify of system dictionary failed");
2854
2855 // Verify dictionary
2856 ClassLoaderDataGraph::verify_dictionary();
2857
2858 GCMutexLocker mu(SystemDictionary_lock);
2859 placeholders()->verify();
2860
2861 // Verify constraint table
2862 guarantee(constraints() != NULL, "Verify of loader constraints failed");
2863 constraints()->verify(placeholders());
2864
2865 _pd_cache_table->verify();
2866 }
2867
2868 // caller needs ResourceMark
2869 const char* SystemDictionary::loader_name(const oop loader) {
2870 return ((loader) == NULL ? "<bootloader>" :
2871 InstanceKlass::cast((loader)->klass())->name()->as_C_string());
2872 }
2873
2874 // caller needs ResourceMark
2875 const char* SystemDictionary::loader_name(const ClassLoaderData* loader_data) {
2876 return (loader_data->class_loader() == NULL ? "<bootloader>" :
2877 SystemDictionary::loader_name(loader_data->class_loader()));
2878 }
|