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