1 /*
2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
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 "jvm.h"
27 #include "aot/aotLoader.hpp"
28 #include "classfile/classFileParser.hpp"
29 #include "classfile/classFileStream.hpp"
30 #include "classfile/classLoader.hpp"
31 #include "classfile/classLoaderData.inline.hpp"
32 #include "classfile/classLoaderDataGraph.inline.hpp"
33 #include "classfile/classLoaderExt.hpp"
34 #include "classfile/dictionary.hpp"
35 #include "classfile/javaClasses.inline.hpp"
36 #include "classfile/klassFactory.hpp"
37 #include "classfile/loaderConstraints.hpp"
38 #include "classfile/packageEntry.hpp"
39 #include "classfile/placeholders.hpp"
40 #include "classfile/protectionDomainCache.hpp"
41 #include "classfile/resolutionErrors.hpp"
42 #include "classfile/stringTable.hpp"
43 #include "classfile/symbolTable.hpp"
44 #include "classfile/systemDictionary.hpp"
45 #include "classfile/vmSymbols.hpp"
46 #include "code/codeCache.hpp"
47 #include "compiler/compileBroker.hpp"
48 #include "gc/shared/gcTraceTime.inline.hpp"
49 #include "gc/shared/oopStorage.inline.hpp"
50 #include "gc/shared/oopStorageSet.hpp"
51 #include "interpreter/bytecodeStream.hpp"
52 #include "interpreter/interpreter.hpp"
53 #include "jfr/jfrEvents.hpp"
54 #include "logging/log.hpp"
55 #include "logging/logStream.hpp"
56 #include "memory/filemap.hpp"
57 #include "memory/heapShared.hpp"
58 #include "memory/metaspaceClosure.hpp"
59 #include "memory/oopFactory.hpp"
60 #include "memory/resourceArea.hpp"
61 #include "memory/universe.hpp"
62 #include "oops/access.inline.hpp"
63 #include "oops/instanceKlass.hpp"
64 #include "oops/instanceRefKlass.hpp"
65 #include "oops/klass.inline.hpp"
66 #include "oops/method.inline.hpp"
67 #include "oops/methodData.hpp"
68 #include "oops/objArrayKlass.hpp"
69 #include "oops/objArrayOop.inline.hpp"
70 #include "oops/oop.inline.hpp"
71 #include "oops/symbol.hpp"
72 #include "oops/typeArrayKlass.hpp"
73 #include "prims/jvmtiExport.hpp"
74 #include "prims/methodHandles.hpp"
75 #include "runtime/arguments.hpp"
76 #include "runtime/biasedLocking.hpp"
77 #include "runtime/fieldType.hpp"
78 #include "runtime/handles.inline.hpp"
79 #include "runtime/java.hpp"
80 #include "runtime/javaCalls.hpp"
81 #include "runtime/mutexLocker.hpp"
82 #include "runtime/sharedRuntime.hpp"
83 #include "runtime/signature.hpp"
84 #include "services/classLoadingService.hpp"
85 #include "services/diagnosticCommand.hpp"
86 #include "services/threadService.hpp"
87 #include "utilities/macros.hpp"
88 #if INCLUDE_CDS
89 #include "classfile/systemDictionaryShared.hpp"
90 #endif
91 #if INCLUDE_JFR
92 #include "jfr/jfr.hpp"
93 #endif
94 
95 PlaceholderTable*      SystemDictionary::_placeholders        = NULL;
96 LoaderConstraintTable* SystemDictionary::_loader_constraints  = NULL;
97 ResolutionErrorTable*  SystemDictionary::_resolution_errors   = NULL;
98 SymbolPropertyTable*   SystemDictionary::_invoke_method_table = NULL;
99 ProtectionDomainCacheTable*   SystemDictionary::_pd_cache_table = NULL;
100 
101 oop         SystemDictionary::_system_loader_lock_obj     =  NULL;
102 
103 InstanceKlass*      SystemDictionary::_well_known_klasses[SystemDictionary::WKID_LIMIT]
104                                                           =  { NULL /*, NULL...*/ };
105 
106 InstanceKlass*      SystemDictionary::_box_klasses[T_VOID+1]      =  { NULL /*, NULL...*/ };
107 
108 oop         SystemDictionary::_java_system_loader         =  NULL;
109 oop         SystemDictionary::_java_platform_loader       =  NULL;
110 
111 // Default ProtectionDomainCacheSize value
112 
113 const int defaultProtectionDomainCacheSize = 1009;
114 
115 // ----------------------------------------------------------------------------
116 // Java-level SystemLoader and PlatformLoader
117 
java_system_loader()118 oop SystemDictionary::java_system_loader() {
119   return _java_system_loader;
120 }
121 
java_platform_loader()122 oop SystemDictionary::java_platform_loader() {
123   return _java_platform_loader;
124 }
125 
compute_java_loaders(TRAPS)126 void SystemDictionary::compute_java_loaders(TRAPS) {
127   JavaValue result(T_OBJECT);
128   InstanceKlass* class_loader_klass = SystemDictionary::ClassLoader_klass();
129   JavaCalls::call_static(&result,
130                          class_loader_klass,
131                          vmSymbols::getSystemClassLoader_name(),
132                          vmSymbols::void_classloader_signature(),
133                          CHECK);
134 
135   _java_system_loader = (oop)result.get_jobject();
136 
137   JavaCalls::call_static(&result,
138                          class_loader_klass,
139                          vmSymbols::getPlatformClassLoader_name(),
140                          vmSymbols::void_classloader_signature(),
141                          CHECK);
142 
143   _java_platform_loader = (oop)result.get_jobject();
144 }
145 
register_loader(Handle class_loader)146 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader) {
147   if (class_loader() == NULL) return ClassLoaderData::the_null_class_loader_data();
148   return ClassLoaderDataGraph::find_or_create(class_loader);
149 }
150 
151 // ----------------------------------------------------------------------------
152 // Parallel class loading check
153 
is_parallelCapable(Handle class_loader)154 bool SystemDictionary::is_parallelCapable(Handle class_loader) {
155   if (class_loader.is_null()) return true;
156   if (AlwaysLockClassLoader) return false;
157   return java_lang_ClassLoader::parallelCapable(class_loader());
158 }
159 // ----------------------------------------------------------------------------
160 // ParallelDefineClass flag does not apply to bootclass loader
is_parallelDefine(Handle class_loader)161 bool SystemDictionary::is_parallelDefine(Handle class_loader) {
162    if (class_loader.is_null()) return false;
163    if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {
164      return true;
165    }
166    return false;
167 }
168 
169 // Returns true if the passed class loader is the builtin application class loader
170 // or a custom system class loader. A customer system class loader can be
171 // specified via -Djava.system.class.loader.
is_system_class_loader(oop class_loader)172 bool SystemDictionary::is_system_class_loader(oop class_loader) {
173   if (class_loader == NULL) {
174     return false;
175   }
176   return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() ||
177          class_loader == _java_system_loader);
178 }
179 
180 // Returns true if the passed class loader is the platform class loader.
is_platform_class_loader(oop class_loader)181 bool SystemDictionary::is_platform_class_loader(oop class_loader) {
182   if (class_loader == NULL) {
183     return false;
184   }
185   return (class_loader->klass() == SystemDictionary::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass());
186 }
187 
188 // ----------------------------------------------------------------------------
189 // Resolving of classes
190 
191 // Forwards to resolve_or_null
192 
resolve_or_fail(Symbol * class_name,Handle class_loader,Handle protection_domain,bool throw_error,TRAPS)193 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader, Handle protection_domain, bool throw_error, TRAPS) {
194   Klass* klass = resolve_or_null(class_name, class_loader, protection_domain, THREAD);
195   if (HAS_PENDING_EXCEPTION || klass == NULL) {
196     // can return a null klass
197     klass = handle_resolution_exception(class_name, throw_error, klass, THREAD);
198   }
199   return klass;
200 }
201 
handle_resolution_exception(Symbol * class_name,bool throw_error,Klass * klass,TRAPS)202 Klass* SystemDictionary::handle_resolution_exception(Symbol* class_name,
203                                                      bool throw_error,
204                                                      Klass* klass, TRAPS) {
205   if (HAS_PENDING_EXCEPTION) {
206     // If we have a pending exception we forward it to the caller, unless throw_error is true,
207     // in which case we have to check whether the pending exception is a ClassNotFoundException,
208     // and if so convert it to a NoClassDefFoundError
209     // And chain the original ClassNotFoundException
210     if (throw_error && PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass())) {
211       ResourceMark rm(THREAD);
212       assert(klass == NULL, "Should not have result with exception pending");
213       Handle e(THREAD, PENDING_EXCEPTION);
214       CLEAR_PENDING_EXCEPTION;
215       THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
216     } else {
217       return NULL;
218     }
219   }
220   // Class not found, throw appropriate error or exception depending on value of throw_error
221   if (klass == NULL) {
222     ResourceMark rm(THREAD);
223     if (throw_error) {
224       THROW_MSG_NULL(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
225     } else {
226       THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
227     }
228   }
229   return klass;
230 }
231 
232 
resolve_or_fail(Symbol * class_name,bool throw_error,TRAPS)233 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name,
234                                            bool throw_error, TRAPS)
235 {
236   return resolve_or_fail(class_name, Handle(), Handle(), throw_error, THREAD);
237 }
238 
239 
240 // Forwards to resolve_array_class_or_null or resolve_instance_class_or_null
241 
resolve_or_null(Symbol * class_name,Handle class_loader,Handle protection_domain,TRAPS)242 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, Handle protection_domain, TRAPS) {
243   if (FieldType::is_array(class_name)) {
244     return resolve_array_class_or_null(class_name, class_loader, protection_domain, THREAD);
245   } else {
246     return resolve_instance_class_or_null_helper(class_name, class_loader, protection_domain, THREAD);
247   }
248 }
249 
250 // name may be in the form of "java/lang/Object" or "Ljava/lang/Object;"
resolve_instance_class_or_null_helper(Symbol * class_name,Handle class_loader,Handle protection_domain,TRAPS)251 InstanceKlass* SystemDictionary::resolve_instance_class_or_null_helper(Symbol* class_name,
252                                                                        Handle class_loader,
253                                                                        Handle protection_domain,
254                                                                        TRAPS) {
255   assert(class_name != NULL && !FieldType::is_array(class_name), "must be");
256   if (FieldType::is_obj(class_name)) {
257     ResourceMark rm(THREAD);
258     // Ignore wrapping L and ;.
259     TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,
260                                                  class_name->utf8_length() - 2);
261     return resolve_instance_class_or_null(name, class_loader, protection_domain, THREAD);
262   } else {
263     return resolve_instance_class_or_null(class_name, class_loader, protection_domain, THREAD);
264   }
265 }
266 
resolve_or_null(Symbol * class_name,TRAPS)267 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, TRAPS) {
268   return resolve_or_null(class_name, Handle(), Handle(), THREAD);
269 }
270 
271 // Forwards to resolve_instance_class_or_null
272 
resolve_array_class_or_null(Symbol * class_name,Handle class_loader,Handle protection_domain,TRAPS)273 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,
274                                                      Handle class_loader,
275                                                      Handle protection_domain,
276                                                      TRAPS) {
277   assert(FieldType::is_array(class_name), "must be array");
278   Klass* k = NULL;
279   FieldArrayInfo fd;
280   // dimension and object_key in FieldArrayInfo are assigned as a side-effect
281   // of this call
282   BasicType t = FieldType::get_array_info(class_name, fd, CHECK_NULL);
283   if (t == T_OBJECT) {
284     // naked oop "k" is OK here -- we assign back into it
285     k = SystemDictionary::resolve_instance_class_or_null(fd.object_key(),
286                                                          class_loader,
287                                                          protection_domain,
288                                                          CHECK_NULL);
289     if (k != NULL) {
290       k = k->array_klass(fd.dimension(), CHECK_NULL);
291     }
292   } else {
293     k = Universe::typeArrayKlassObj(t);
294     k = TypeArrayKlass::cast(k)->array_klass(fd.dimension(), CHECK_NULL);
295   }
296   return k;
297 }
298 
299 
300 // Must be called for any super-class or super-interface resolution
301 // during class definition to allow class circularity checking
302 // super-interface callers:
303 //    parse_interfaces - for defineClass & jvmtiRedefineClasses
304 // super-class callers:
305 //   ClassFileParser - for defineClass & jvmtiRedefineClasses
306 //   load_shared_class - while loading a class from shared archive
307 //   resolve_instance_class_or_null:
308 //     via: handle_parallel_super_load
309 //      when resolving a class that has an existing placeholder with
310 //      a saved superclass [i.e. a defineClass is currently in progress]
311 //      if another thread is trying to resolve the class, it must do
312 //      super-class checks on its own thread to catch class circularity
313 // This last call is critical in class circularity checking for cases
314 // where classloading is delegated to different threads and the
315 // classloader lock is released.
316 // Take the case: Base->Super->Base
317 //   1. If thread T1 tries to do a defineClass of class Base
318 //    resolve_super_or_fail creates placeholder: T1, Base (super Super)
319 //   2. resolve_instance_class_or_null does not find SD or placeholder for Super
320 //    so it tries to load Super
321 //   3. If we load the class internally, or user classloader uses same thread
322 //      loadClassFromxxx or defineClass via parseClassFile Super ...
323 //      3.1 resolve_super_or_fail creates placeholder: T1, Super (super Base)
324 //      3.3 resolve_instance_class_or_null Base, finds placeholder for Base
325 //      3.4 calls resolve_super_or_fail Base
326 //      3.5 finds T1,Base -> throws class circularity
327 //OR 4. If T2 tries to resolve Super via defineClass Super ...
328 //      4.1 resolve_super_or_fail creates placeholder: T2, Super (super Base)
329 //      4.2 resolve_instance_class_or_null Base, finds placeholder for Base (super Super)
330 //      4.3 calls resolve_super_or_fail Super in parallel on own thread T2
331 //      4.4 finds T2, Super -> throws class circularity
332 // Must be called, even if superclass is null, since this is
333 // where the placeholder entry is created which claims this
334 // thread is loading this class/classloader.
335 // Be careful when modifying this code: once you have run
336 // placeholders()->find_and_add(PlaceholderTable::LOAD_SUPER),
337 // you need to find_and_remove it before returning.
338 // So be careful to not exit with a CHECK_ macro betweeen these calls.
resolve_super_or_fail(Symbol * child_name,Symbol * super_name,Handle class_loader,Handle protection_domain,bool is_superclass,TRAPS)339 InstanceKlass* SystemDictionary::resolve_super_or_fail(Symbol* child_name,
340                                                        Symbol* super_name,
341                                                        Handle class_loader,
342                                                        Handle protection_domain,
343                                                        bool is_superclass,
344                                                        TRAPS) {
345   assert(!FieldType::is_array(super_name), "invalid super class name");
346 #if INCLUDE_CDS
347   if (DumpSharedSpaces) {
348     // Special processing for handling UNREGISTERED shared classes.
349     InstanceKlass* k = SystemDictionaryShared::dump_time_resolve_super_or_fail(child_name,
350         super_name, class_loader, protection_domain, is_superclass, CHECK_NULL);
351     if (k) {
352       return k;
353     }
354   }
355 #endif // INCLUDE_CDS
356 
357   // Double-check, if child class is already loaded, just return super-class,interface
358   // Don't add a placedholder if already loaded, i.e. already in appropriate class loader
359   // dictionary.
360   // Make sure there's a placeholder for the *child* before resolving.
361   // Used as a claim that this thread is currently loading superclass/classloader
362   // Used here for ClassCircularity checks and also for heap verification
363   // (every InstanceKlass needs to be in its class loader dictionary or have a placeholder).
364   // Must check ClassCircularity before checking if super class is already loaded.
365   //
366   // We might not already have a placeholder if this child_name was
367   // first seen via resolve_from_stream (jni_DefineClass or JVM_DefineClass);
368   // the name of the class might not be known until the stream is actually
369   // parsed.
370   // Bugs 4643874, 4715493
371 
372   ClassLoaderData* loader_data = class_loader_data(class_loader);
373   Dictionary* dictionary = loader_data->dictionary();
374   unsigned int d_hash = dictionary->compute_hash(child_name);
375   unsigned int p_hash = placeholders()->compute_hash(child_name);
376   int p_index = placeholders()->hash_to_index(p_hash);
377   // can't throw error holding a lock
378   bool child_already_loaded = false;
379   bool throw_circularity_error = false;
380   {
381     MutexLocker mu(SystemDictionary_lock, THREAD);
382     InstanceKlass* childk = find_class(d_hash, child_name, dictionary);
383     InstanceKlass* quicksuperk;
384     // to support // loading: if child done loading, just return superclass
385     // if super_name, & class_loader don't match:
386     // if initial define, SD update will give LinkageError
387     // if redefine: compare_class_versions will give HIERARCHY_CHANGED
388     // so we don't throw an exception here.
389     // see: nsk redefclass014 & java.lang.instrument Instrument032
390     if ((childk != NULL ) && (is_superclass) &&
391         ((quicksuperk = childk->java_super()) != NULL) &&
392          ((quicksuperk->name() == super_name) &&
393             (quicksuperk->class_loader() == class_loader()))) {
394            return quicksuperk;
395     } else {
396       PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, child_name, loader_data);
397       if (probe && probe->check_seen_thread(THREAD, PlaceholderTable::LOAD_SUPER)) {
398           throw_circularity_error = true;
399       }
400     }
401     if (!throw_circularity_error) {
402       // Be careful not to exit resolve_super
403       PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, super_name, THREAD);
404     }
405   }
406   if (throw_circularity_error) {
407       ResourceMark rm(THREAD);
408       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), child_name->as_C_string());
409   }
410 
411 // java.lang.Object should have been found above
412   assert(super_name != NULL, "null super class for resolving");
413   // Resolve the super class or interface, check results on return
414   InstanceKlass* superk =
415     SystemDictionary::resolve_instance_class_or_null_helper(super_name,
416                                                             class_loader,
417                                                             protection_domain,
418                                                             THREAD);
419 
420   // Clean up of placeholders moved so that each classloadAction registrar self-cleans up
421   // It is no longer necessary to keep the placeholder table alive until update_dictionary
422   // or error. GC used to walk the placeholder table as strong roots.
423   // The instanceKlass is kept alive because the class loader is on the stack,
424   // which keeps the loader_data alive, as well as all instanceKlasses in
425   // the loader_data. parseClassFile adds the instanceKlass to loader_data.
426   {
427     MutexLocker mu(SystemDictionary_lock, THREAD);
428     placeholders()->find_and_remove(p_index, p_hash, child_name, loader_data, PlaceholderTable::LOAD_SUPER, THREAD);
429     SystemDictionary_lock->notify_all();
430   }
431   if (HAS_PENDING_EXCEPTION || superk == NULL) {
432     // can null superk
433     Klass* k = handle_resolution_exception(super_name, true, superk, THREAD);
434     assert(k == NULL || k == superk, "must be");
435     if (k == NULL) {
436       superk = NULL;
437     }
438   }
439 
440   return superk;
441 }
442 
validate_protection_domain(InstanceKlass * klass,Handle class_loader,Handle protection_domain,TRAPS)443 void SystemDictionary::validate_protection_domain(InstanceKlass* klass,
444                                                   Handle class_loader,
445                                                   Handle protection_domain,
446                                                   TRAPS) {
447   // Now we have to call back to java to check if the initating class has access
448   JavaValue result(T_VOID);
449   LogTarget(Debug, protectiondomain) lt;
450   if (lt.is_enabled()) {
451     ResourceMark rm(THREAD);
452     // Print out trace information
453     LogStream ls(lt);
454     ls.print_cr("Checking package access");
455     if (class_loader() != NULL) {
456       ls.print("class loader: ");
457       class_loader()->print_value_on(&ls);
458     } else {
459       ls.print_cr("class loader: NULL");
460     }
461     if (protection_domain() != NULL) {
462       ls.print(" protection domain: ");
463       protection_domain()->print_value_on(&ls);
464     } else {
465       ls.print_cr(" protection domain: NULL");
466     }
467     ls.print(" loading: "); klass->print_value_on(&ls);
468     ls.cr();
469   }
470 
471   // This handle and the class_loader handle passed in keeps this class from
472   // being unloaded through several GC points.
473   // The class_loader handle passed in is the initiating loader.
474   Handle mirror(THREAD, klass->java_mirror());
475 
476   InstanceKlass* system_loader = SystemDictionary::ClassLoader_klass();
477   JavaCalls::call_special(&result,
478                          class_loader,
479                          system_loader,
480                          vmSymbols::checkPackageAccess_name(),
481                          vmSymbols::class_protectiondomain_signature(),
482                          mirror,
483                          protection_domain,
484                          THREAD);
485 
486   if (HAS_PENDING_EXCEPTION) {
487     log_debug(protectiondomain)("DENIED !!!!!!!!!!!!!!!!!!!!!");
488   } else {
489    log_debug(protectiondomain)("granted");
490   }
491 
492   if (HAS_PENDING_EXCEPTION) return;
493 
494   // If no exception has been thrown, we have validated the protection domain
495   // Insert the protection domain of the initiating class into the set.
496   {
497     ClassLoaderData* loader_data = class_loader_data(class_loader);
498     Dictionary* dictionary = loader_data->dictionary();
499 
500     Symbol*  kn = klass->name();
501     unsigned int d_hash = dictionary->compute_hash(kn);
502 
503     MutexLocker mu(SystemDictionary_lock, THREAD);
504     int d_index = dictionary->hash_to_index(d_hash);
505     dictionary->add_protection_domain(d_index, d_hash, klass,
506                                       protection_domain, THREAD);
507   }
508 }
509 
510 // We only get here if this thread finds that another thread
511 // has already claimed the placeholder token for the current operation,
512 // but that other thread either never owned or gave up the
513 // object lock
514 // Waits on SystemDictionary_lock to indicate placeholder table updated
515 // On return, caller must recheck placeholder table state
516 //
517 // We only get here if
518 //  1) custom classLoader, i.e. not bootstrap classloader
519 //  2) custom classLoader has broken the class loader objectLock
520 //     so another thread got here in parallel
521 //
522 // lockObject must be held.
523 // Complicated dance due to lock ordering:
524 // Must first release the classloader object lock to
525 // allow initial definer to complete the class definition
526 // and to avoid deadlock
527 // Reclaim classloader lock object with same original recursion count
528 // Must release SystemDictionary_lock after notify, since
529 // class loader lock must be claimed before SystemDictionary_lock
530 // to prevent deadlocks
531 //
532 // The notify allows applications that did an untimed wait() on
533 // the classloader object lock to not hang.
double_lock_wait(Handle lockObject,TRAPS)534 void SystemDictionary::double_lock_wait(Handle lockObject, TRAPS) {
535   assert_lock_strong(SystemDictionary_lock);
536 
537   bool calledholdinglock
538       = ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, lockObject);
539   assert(calledholdinglock,"must hold lock for notify");
540   assert((lockObject() != _system_loader_lock_obj && !is_parallelCapable(lockObject)), "unexpected double_lock_wait");
541   ObjectSynchronizer::notifyall(lockObject, THREAD);
542   intx recursions =  ObjectSynchronizer::complete_exit(lockObject, THREAD);
543   SystemDictionary_lock->wait();
544   SystemDictionary_lock->unlock();
545   ObjectSynchronizer::reenter(lockObject, recursions, THREAD);
546   SystemDictionary_lock->lock();
547 }
548 
549 // If the class in is in the placeholder table, class loading is in progress
550 // For cases where the application changes threads to load classes, it
551 // is critical to ClassCircularity detection that we try loading
552 // the superclass on the same thread internally, so we do parallel
553 // super class loading here.
554 // This also is critical in cases where the original thread gets stalled
555 // even in non-circularity situations.
556 // Note: must call resolve_super_or_fail even if null super -
557 // to force placeholder entry creation for this class for circularity detection
558 // Caller must check for pending exception
559 // Returns non-null Klass* if other thread has completed load
560 // and we are done,
561 // If return null Klass* and no pending exception, the caller must load the class
handle_parallel_super_load(Symbol * name,Symbol * superclassname,Handle class_loader,Handle protection_domain,Handle lockObject,TRAPS)562 InstanceKlass* SystemDictionary::handle_parallel_super_load(
563     Symbol* name, Symbol* superclassname, Handle class_loader,
564     Handle protection_domain, Handle lockObject, TRAPS) {
565 
566   ClassLoaderData* loader_data = class_loader_data(class_loader);
567   Dictionary* dictionary = loader_data->dictionary();
568   unsigned int d_hash = dictionary->compute_hash(name);
569   unsigned int p_hash = placeholders()->compute_hash(name);
570   int p_index = placeholders()->hash_to_index(p_hash);
571 
572   // superk is not used, resolve_super called for circularity check only
573   // This code is reached in two situations. One if this thread
574   // is loading the same class twice (e.g. ClassCircularity, or
575   // java.lang.instrument).
576   // The second is if another thread started the resolve_super first
577   // and has not yet finished.
578   // In both cases the original caller will clean up the placeholder
579   // entry on error.
580   Klass* superk = SystemDictionary::resolve_super_or_fail(name,
581                                                           superclassname,
582                                                           class_loader,
583                                                           protection_domain,
584                                                           true,
585                                                           CHECK_NULL);
586 
587   // parallelCapable class loaders do NOT wait for parallel superclass loads to complete
588   // Serial class loaders and bootstrap classloader do wait for superclass loads
589  if (!class_loader.is_null() && is_parallelCapable(class_loader)) {
590     MutexLocker mu(SystemDictionary_lock, THREAD);
591     // Check if classloading completed while we were loading superclass or waiting
592     return find_class(d_hash, name, dictionary);
593   }
594 
595   // must loop to both handle other placeholder updates
596   // and spurious notifications
597   bool super_load_in_progress = true;
598   PlaceholderEntry* placeholder;
599   while (super_load_in_progress) {
600     MutexLocker mu(SystemDictionary_lock, THREAD);
601     // Check if classloading completed while we were loading superclass or waiting
602     InstanceKlass* check = find_class(d_hash, name, dictionary);
603     if (check != NULL) {
604       // Klass is already loaded, so just return it
605       return check;
606     } else {
607       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
608       if (placeholder && placeholder->super_load_in_progress() ){
609         // We only get here if the application has released the
610         // classloader lock when another thread was in the middle of loading a
611         // superclass/superinterface for this class, and now
612         // this thread is also trying to load this class.
613         // To minimize surprises, the first thread that started to
614         // load a class should be the one to complete the loading
615         // with the classfile it initially expected.
616         // This logic has the current thread wait once it has done
617         // all the superclass/superinterface loading it can, until
618         // the original thread completes the class loading or fails
619         // If it completes we will use the resulting InstanceKlass
620         // which we will find below in the systemDictionary.
621         // We also get here for parallel bootstrap classloader
622         if (class_loader.is_null()) {
623           SystemDictionary_lock->wait();
624         } else {
625           double_lock_wait(lockObject, THREAD);
626         }
627       } else {
628         // If not in SD and not in PH, other thread's load must have failed
629         super_load_in_progress = false;
630       }
631     }
632   }
633   return NULL;
634 }
635 
post_class_load_event(EventClassLoad * event,const InstanceKlass * k,const ClassLoaderData * init_cld)636 static void post_class_load_event(EventClassLoad* event, const InstanceKlass* k, const ClassLoaderData* init_cld) {
637   assert(event != NULL, "invariant");
638   assert(k != NULL, "invariant");
639   assert(event->should_commit(), "invariant");
640   event->set_loadedClass(k);
641   event->set_definingClassLoader(k->class_loader_data());
642   event->set_initiatingClassLoader(init_cld);
643   event->commit();
644 }
645 
646 
647 // Be careful when modifying this code: once you have run
648 // placeholders()->find_and_add(PlaceholderTable::LOAD_INSTANCE),
649 // you need to find_and_remove it before returning.
650 // So be careful to not exit with a CHECK_ macro betweeen these calls.
651 //
652 // name must be in the form of "java/lang/Object" -- cannot be "Ljava/lang/Object;"
resolve_instance_class_or_null(Symbol * name,Handle class_loader,Handle protection_domain,TRAPS)653 InstanceKlass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
654                                                                 Handle class_loader,
655                                                                 Handle protection_domain,
656                                                                 TRAPS) {
657   assert(name != NULL && !FieldType::is_array(name) &&
658          !FieldType::is_obj(name), "invalid class name");
659 
660   EventClassLoad class_load_start_event;
661 
662   HandleMark hm(THREAD);
663 
664   // Fix for 4474172; see evaluation for more details
665   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
666   ClassLoaderData* loader_data = register_loader(class_loader);
667   Dictionary* dictionary = loader_data->dictionary();
668   unsigned int d_hash = dictionary->compute_hash(name);
669 
670   // Do lookup to see if class already exist and the protection domain
671   // has the right access
672   // This call uses find which checks protection domain already matches
673   // All subsequent calls use find_class, and set has_loaded_class so that
674   // before we return a result we call out to java to check for valid protection domain
675   // to allow returning the Klass* and add it to the pd_set if it is valid
676   {
677     InstanceKlass* probe = dictionary->find(d_hash, name, protection_domain);
678     if (probe != NULL) return probe;
679   }
680 
681   // Non-bootstrap class loaders will call out to class loader and
682   // define via jvm/jni_DefineClass which will acquire the
683   // class loader object lock to protect against multiple threads
684   // defining the class in parallel by accident.
685   // This lock must be acquired here so the waiter will find
686   // any successful result in the SystemDictionary and not attempt
687   // the define.
688   // ParallelCapable Classloaders and the bootstrap classloader
689   // do not acquire lock here.
690   bool DoObjectLock = true;
691   if (is_parallelCapable(class_loader)) {
692     DoObjectLock = false;
693   }
694 
695   unsigned int p_hash = placeholders()->compute_hash(name);
696   int p_index = placeholders()->hash_to_index(p_hash);
697 
698   // Class is not in SystemDictionary so we have to do loading.
699   // Make sure we are synchronized on the class loader before we proceed
700   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
701   check_loader_lock_contention(lockObject, THREAD);
702   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
703 
704   // Check again (after locking) if class already exist in SystemDictionary
705   bool class_has_been_loaded   = false;
706   bool super_load_in_progress  = false;
707   bool havesupername = false;
708   InstanceKlass* k = NULL;
709   PlaceholderEntry* placeholder;
710   Symbol* superclassname = NULL;
711 
712   assert(THREAD->can_call_java(),
713          "can not load classes with compiler thread: class=%s, classloader=%s",
714          name->as_C_string(),
715          class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string());
716   {
717     MutexLocker mu(SystemDictionary_lock, THREAD);
718     InstanceKlass* check = find_class(d_hash, name, dictionary);
719     if (check != NULL) {
720       // InstanceKlass is already loaded, so just return it
721       class_has_been_loaded = true;
722       k = check;
723     } else {
724       placeholder = placeholders()->get_entry(p_index, p_hash, name, loader_data);
725       if (placeholder && placeholder->super_load_in_progress()) {
726          super_load_in_progress = true;
727          if (placeholder->havesupername() == true) {
728            superclassname = placeholder->supername();
729            havesupername = true;
730          }
731       }
732     }
733   }
734 
735   // If the class is in the placeholder table, class loading is in progress
736   if (super_load_in_progress && havesupername==true) {
737     k = handle_parallel_super_load(name,
738                                    superclassname,
739                                    class_loader,
740                                    protection_domain,
741                                    lockObject, THREAD);
742     if (HAS_PENDING_EXCEPTION) {
743       return NULL;
744     }
745     if (k != NULL) {
746       class_has_been_loaded = true;
747     }
748   }
749 
750   bool throw_circularity_error = false;
751   if (!class_has_been_loaded) {
752     bool load_instance_added = false;
753 
754     // add placeholder entry to record loading instance class
755     // Five cases:
756     // All cases need to prevent modifying bootclasssearchpath
757     // in parallel with a classload of same classname
758     // Redefineclasses uses existence of the placeholder for the duration
759     // of the class load to prevent concurrent redefinition of not completely
760     // defined classes.
761     // case 1. traditional classloaders that rely on the classloader object lock
762     //   - no other need for LOAD_INSTANCE
763     // case 2. traditional classloaders that break the classloader object lock
764     //    as a deadlock workaround. Detection of this case requires that
765     //    this check is done while holding the classloader object lock,
766     //    and that lock is still held when calling classloader's loadClass.
767     //    For these classloaders, we ensure that the first requestor
768     //    completes the load and other requestors wait for completion.
769     // case 3. Bootstrap classloader - don't own objectLocker
770     //    This classloader supports parallelism at the classloader level,
771     //    but only allows a single load of a class/classloader pair.
772     //    No performance benefit and no deadlock issues.
773     // case 4. parallelCapable user level classloaders - without objectLocker
774     //    Allow parallel classloading of a class/classloader pair
775 
776     {
777       MutexLocker mu(SystemDictionary_lock, THREAD);
778       if (class_loader.is_null() || !is_parallelCapable(class_loader)) {
779         PlaceholderEntry* oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
780         if (oldprobe) {
781           // only need check_seen_thread once, not on each loop
782           // 6341374 java/lang/Instrument with -Xcomp
783           if (oldprobe->check_seen_thread(THREAD, PlaceholderTable::LOAD_INSTANCE)) {
784             throw_circularity_error = true;
785           } else {
786             // case 1: traditional: should never see load_in_progress.
787             while (!class_has_been_loaded && oldprobe && oldprobe->instance_load_in_progress()) {
788 
789               // case 3: bootstrap classloader: prevent futile classloading,
790               // wait on first requestor
791               if (class_loader.is_null()) {
792                 SystemDictionary_lock->wait();
793               } else {
794               // case 2: traditional with broken classloader lock. wait on first
795               // requestor.
796                 double_lock_wait(lockObject, THREAD);
797               }
798               // Check if classloading completed while we were waiting
799               InstanceKlass* check = find_class(d_hash, name, dictionary);
800               if (check != NULL) {
801                 // Klass is already loaded, so just return it
802                 k = check;
803                 class_has_been_loaded = true;
804               }
805               // check if other thread failed to load and cleaned up
806               oldprobe = placeholders()->get_entry(p_index, p_hash, name, loader_data);
807             }
808           }
809         }
810       }
811       // All cases: add LOAD_INSTANCE holding SystemDictionary_lock
812       // case 4: parallelCapable: allow competing threads to try
813       // LOAD_INSTANCE in parallel
814 
815       if (!throw_circularity_error && !class_has_been_loaded) {
816         PlaceholderEntry* newprobe = placeholders()->find_and_add(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, NULL, THREAD);
817         load_instance_added = true;
818         // For class loaders that do not acquire the classloader object lock,
819         // if they did not catch another thread holding LOAD_INSTANCE,
820         // need a check analogous to the acquire ObjectLocker/find_class
821         // i.e. now that we hold the LOAD_INSTANCE token on loading this class/CL
822         // one final check if the load has already completed
823         // class loaders holding the ObjectLock shouldn't find the class here
824         InstanceKlass* check = find_class(d_hash, name, dictionary);
825         if (check != NULL) {
826         // Klass is already loaded, so return it after checking/adding protection domain
827           k = check;
828           class_has_been_loaded = true;
829         }
830       }
831     }
832 
833     // must throw error outside of owning lock
834     if (throw_circularity_error) {
835       assert(!HAS_PENDING_EXCEPTION && load_instance_added == false,"circularity error cleanup");
836       ResourceMark rm(THREAD);
837       THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
838     }
839 
840     if (!class_has_been_loaded) {
841 
842       // Do actual loading
843       k = load_instance_class(name, class_loader, THREAD);
844 
845       // If everything was OK (no exceptions, no null return value), and
846       // class_loader is NOT the defining loader, do a little more bookkeeping.
847       if (!HAS_PENDING_EXCEPTION && k != NULL &&
848         k->class_loader() != class_loader()) {
849 
850         check_constraints(d_hash, k, class_loader, false, THREAD);
851 
852         // Need to check for a PENDING_EXCEPTION again; check_constraints
853         // can throw but we may have to remove entry from the placeholder table below.
854         if (!HAS_PENDING_EXCEPTION) {
855           // Record dependency for non-parent delegation.
856           // This recording keeps the defining class loader of the klass (k) found
857           // from being unloaded while the initiating class loader is loaded
858           // even if the reference to the defining class loader is dropped
859           // before references to the initiating class loader.
860           loader_data->record_dependency(k);
861 
862           { // Grabbing the Compile_lock prevents systemDictionary updates
863             // during compilations.
864             MutexLocker mu(Compile_lock, THREAD);
865             update_dictionary(d_hash, p_index, p_hash,
866               k, class_loader, THREAD);
867           }
868 
869           if (JvmtiExport::should_post_class_load()) {
870             Thread *thread = THREAD;
871             assert(thread->is_Java_thread(), "thread->is_Java_thread()");
872             JvmtiExport::post_class_load((JavaThread *) thread, k);
873           }
874         }
875       }
876     } // load_instance_class
877 
878     if (load_instance_added == true) {
879       // clean up placeholder entries for LOAD_INSTANCE success or error
880       // This brackets the SystemDictionary updates for both defining
881       // and initiating loaders
882       MutexLocker mu(SystemDictionary_lock, THREAD);
883       placeholders()->find_and_remove(p_index, p_hash, name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
884       SystemDictionary_lock->notify_all();
885     }
886   }
887 
888   if (HAS_PENDING_EXCEPTION || k == NULL) {
889     return NULL;
890   }
891   if (class_load_start_event.should_commit()) {
892     post_class_load_event(&class_load_start_event, k, loader_data);
893   }
894 #ifdef ASSERT
895   {
896     ClassLoaderData* loader_data = k->class_loader_data();
897     MutexLocker mu(SystemDictionary_lock, THREAD);
898     InstanceKlass* kk = find_class(name, loader_data);
899     assert(kk == k, "should be present in dictionary");
900   }
901 #endif
902 
903   // return if the protection domain in NULL
904   if (protection_domain() == NULL) return k;
905 
906   // Check the protection domain has the right access
907   if (dictionary->is_valid_protection_domain(d_hash, name,
908                                              protection_domain)) {
909     return k;
910   }
911 
912   // Verify protection domain. If it fails an exception is thrown
913   validate_protection_domain(k, class_loader, protection_domain, CHECK_NULL);
914 
915   return k;
916 }
917 
918 
919 // This routine does not lock the system dictionary.
920 //
921 // Since readers don't hold a lock, we must make sure that system
922 // dictionary entries are only removed at a safepoint (when only one
923 // thread is running), and are added to in a safe way (all links must
924 // be updated in an MT-safe manner).
925 //
926 // Callers should be aware that an entry could be added just after
927 // _dictionary->bucket(index) is read here, so the caller will not see
928 // the new entry.
929 
find(Symbol * class_name,Handle class_loader,Handle protection_domain,TRAPS)930 Klass* SystemDictionary::find(Symbol* class_name,
931                               Handle class_loader,
932                               Handle protection_domain,
933                               TRAPS) {
934 
935   // The result of this call should be consistent with the result
936   // of the call to resolve_instance_class_or_null().
937   // See evaluation 6790209 and 4474172 for more details.
938   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
939   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
940 
941   if (loader_data == NULL) {
942     // If the ClassLoaderData has not been setup,
943     // then the class loader has no entries in the dictionary.
944     return NULL;
945   }
946 
947   Dictionary* dictionary = loader_data->dictionary();
948   unsigned int d_hash = dictionary->compute_hash(class_name);
949   return dictionary->find(d_hash, class_name,
950                           protection_domain);
951 }
952 
953 
954 // Look for a loaded instance or array klass by name.  Do not do any loading.
955 // return NULL in case of error.
find_instance_or_array_klass(Symbol * class_name,Handle class_loader,Handle protection_domain,TRAPS)956 Klass* SystemDictionary::find_instance_or_array_klass(Symbol* class_name,
957                                                       Handle class_loader,
958                                                       Handle protection_domain,
959                                                       TRAPS) {
960   Klass* k = NULL;
961   assert(class_name != NULL, "class name must be non NULL");
962 
963   if (FieldType::is_array(class_name)) {
964     // The name refers to an array.  Parse the name.
965     // dimension and object_key in FieldArrayInfo are assigned as a
966     // side-effect of this call
967     FieldArrayInfo fd;
968     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
969     if (t != T_OBJECT) {
970       k = Universe::typeArrayKlassObj(t);
971     } else {
972       k = SystemDictionary::find(fd.object_key(), class_loader, protection_domain, THREAD);
973     }
974     if (k != NULL) {
975       k = k->array_klass_or_null(fd.dimension());
976     }
977   } else {
978     k = find(class_name, class_loader, protection_domain, THREAD);
979   }
980   return k;
981 }
982 
983 // Note: this method is much like resolve_from_stream, but
984 // does not publish the classes via the SystemDictionary.
985 // Handles unsafe_DefineAnonymousClass and redefineclasses
986 // RedefinedClasses do not add to the class hierarchy
parse_stream(Symbol * class_name,Handle class_loader,Handle protection_domain,ClassFileStream * st,const InstanceKlass * unsafe_anonymous_host,GrowableArray<Handle> * cp_patches,TRAPS)987 InstanceKlass* SystemDictionary::parse_stream(Symbol* class_name,
988                                               Handle class_loader,
989                                               Handle protection_domain,
990                                               ClassFileStream* st,
991                                               const InstanceKlass* unsafe_anonymous_host,
992                                               GrowableArray<Handle>* cp_patches,
993                                               TRAPS) {
994 
995   EventClassLoad class_load_start_event;
996 
997   ClassLoaderData* loader_data;
998   if (unsafe_anonymous_host != NULL) {
999     // Create a new CLD for an unsafe anonymous class, that uses the same class loader
1000     // as the unsafe_anonymous_host
1001     guarantee(unsafe_anonymous_host->class_loader() == class_loader(), "should be the same");
1002     loader_data = ClassLoaderData::unsafe_anonymous_class_loader_data(class_loader);
1003   } else {
1004     loader_data = ClassLoaderData::class_loader_data(class_loader());
1005   }
1006 
1007   assert(st != NULL, "invariant");
1008   assert(st->need_verify(), "invariant");
1009 
1010   // Parse stream and create a klass.
1011   // Note that we do this even though this klass might
1012   // already be present in the SystemDictionary, otherwise we would not
1013   // throw potential ClassFormatErrors.
1014 
1015   InstanceKlass* k = KlassFactory::create_from_stream(st,
1016                                                       class_name,
1017                                                       loader_data,
1018                                                       protection_domain,
1019                                                       unsafe_anonymous_host,
1020                                                       cp_patches,
1021                                                       CHECK_NULL);
1022 
1023   if (unsafe_anonymous_host != NULL && k != NULL) {
1024     // Unsafe anonymous classes must update ClassLoaderData holder (was unsafe_anonymous_host loader)
1025     // so that they can be unloaded when the mirror is no longer referenced.
1026     k->class_loader_data()->initialize_holder(Handle(THREAD, k->java_mirror()));
1027 
1028     {
1029       MutexLocker mu_r(Compile_lock, THREAD);
1030 
1031       // Add to class hierarchy, initialize vtables, and do possible
1032       // deoptimizations.
1033       add_to_hierarchy(k, CHECK_NULL); // No exception, but can block
1034       // But, do not add to dictionary.
1035     }
1036 
1037     // Rewrite and patch constant pool here.
1038     k->link_class(CHECK_NULL);
1039     if (cp_patches != NULL) {
1040       k->constants()->patch_resolved_references(cp_patches);
1041     }
1042 
1043     // If it's anonymous, initialize it now, since nobody else will.
1044     k->eager_initialize(CHECK_NULL);
1045 
1046     // notify jvmti
1047     if (JvmtiExport::should_post_class_load()) {
1048         assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1049         JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1050     }
1051     if (class_load_start_event.should_commit()) {
1052       post_class_load_event(&class_load_start_event, k, loader_data);
1053     }
1054   }
1055   assert(unsafe_anonymous_host != NULL || NULL == cp_patches,
1056          "cp_patches only found with unsafe_anonymous_host");
1057 
1058   return k;
1059 }
1060 
1061 // Add a klass to the system from a stream (called by jni_DefineClass and
1062 // JVM_DefineClass).
1063 // Note: class_name can be NULL. In that case we do not know the name of
1064 // the class until we have parsed the stream.
1065 
resolve_from_stream(Symbol * class_name,Handle class_loader,Handle protection_domain,ClassFileStream * st,TRAPS)1066 InstanceKlass* SystemDictionary::resolve_from_stream(Symbol* class_name,
1067                                                      Handle class_loader,
1068                                                      Handle protection_domain,
1069                                                      ClassFileStream* st,
1070                                                      TRAPS) {
1071 
1072   HandleMark hm(THREAD);
1073 
1074   // Classloaders that support parallelism, e.g. bootstrap classloader,
1075   // do not acquire lock here
1076   bool DoObjectLock = true;
1077   if (is_parallelCapable(class_loader)) {
1078     DoObjectLock = false;
1079   }
1080 
1081   ClassLoaderData* loader_data = register_loader(class_loader);
1082 
1083   // Make sure we are synchronized on the class loader before we proceed
1084   Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1085   check_loader_lock_contention(lockObject, THREAD);
1086   ObjectLocker ol(lockObject, THREAD, DoObjectLock);
1087 
1088   assert(st != NULL, "invariant");
1089 
1090   // Parse the stream and create a klass.
1091   // Note that we do this even though this klass might
1092   // already be present in the SystemDictionary, otherwise we would not
1093   // throw potential ClassFormatErrors.
1094  InstanceKlass* k = NULL;
1095 
1096 #if INCLUDE_CDS
1097   if (!DumpSharedSpaces) {
1098     k = SystemDictionaryShared::lookup_from_stream(class_name,
1099                                                    class_loader,
1100                                                    protection_domain,
1101                                                    st,
1102                                                    CHECK_NULL);
1103   }
1104 #endif
1105 
1106   if (k == NULL) {
1107     if (st->buffer() == NULL) {
1108       return NULL;
1109     }
1110     k = KlassFactory::create_from_stream(st,
1111                                          class_name,
1112                                          loader_data,
1113                                          protection_domain,
1114                                          NULL, // unsafe_anonymous_host
1115                                          NULL, // cp_patches
1116                                          CHECK_NULL);
1117   }
1118 
1119   assert(k != NULL, "no klass created");
1120   Symbol* h_name = k->name();
1121   assert(class_name == NULL || class_name == h_name, "name mismatch");
1122 
1123   // Add class just loaded
1124   // If a class loader supports parallel classloading handle parallel define requests
1125   // find_or_define_instance_class may return a different InstanceKlass
1126   if (is_parallelCapable(class_loader)) {
1127     InstanceKlass* defined_k = find_or_define_instance_class(h_name, class_loader, k, THREAD);
1128     if (!HAS_PENDING_EXCEPTION && defined_k != k) {
1129       // If a parallel capable class loader already defined this class, register 'k' for cleanup.
1130       assert(defined_k != NULL, "Should have a klass if there's no exception");
1131       loader_data->add_to_deallocate_list(k);
1132       k = defined_k;
1133     }
1134   } else {
1135     define_instance_class(k, THREAD);
1136   }
1137 
1138   // If defining the class throws an exception register 'k' for cleanup.
1139   if (HAS_PENDING_EXCEPTION) {
1140     assert(k != NULL, "Must have an instance klass here!");
1141     loader_data->add_to_deallocate_list(k);
1142     return NULL;
1143   }
1144 
1145   // Make sure we have an entry in the SystemDictionary on success
1146   debug_only( {
1147     MutexLocker mu(SystemDictionary_lock, THREAD);
1148 
1149     Klass* check = find_class(h_name, k->class_loader_data());
1150     assert(check == k, "should be present in the dictionary");
1151   } );
1152 
1153   return k;
1154 }
1155 
1156 #if INCLUDE_CDS
1157 // Load a class for boot loader from the shared spaces. This also
1158 // forces the super class and all interfaces to be loaded.
load_shared_boot_class(Symbol * class_name,TRAPS)1159 InstanceKlass* SystemDictionary::load_shared_boot_class(Symbol* class_name,
1160                                                         TRAPS) {
1161   InstanceKlass* ik = SystemDictionaryShared::find_builtin_class(class_name);
1162   if (ik != NULL && ik->is_shared_boot_class()) {
1163     return load_shared_class(ik, Handle(), Handle(), NULL, THREAD);
1164   }
1165   return NULL;
1166 }
1167 
1168 // Check if a shared class can be loaded by the specific classloader:
1169 //
1170 // NULL classloader:
1171 //   - Module class from "modules" jimage. ModuleEntry must be defined in the classloader.
1172 //   - Class from -Xbootclasspath/a. The class has no defined PackageEntry, or must
1173 //     be defined in an unnamed module.
is_shared_class_visible(Symbol * class_name,InstanceKlass * ik,Handle class_loader,TRAPS)1174 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
1175                                                InstanceKlass* ik,
1176                                                Handle class_loader, TRAPS) {
1177   assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
1178          "Cannot use sharing if java.base is patched");
1179   ResourceMark rm(THREAD);
1180   int path_index = ik->shared_classpath_index();
1181   ClassLoaderData* loader_data = class_loader_data(class_loader);
1182   if (path_index < 0) {
1183     // path_index < 0 indicates that the class is intended for a custom loader
1184     // and should not be loaded by boot/platform/app loaders
1185     if (loader_data->is_builtin_class_loader_data()) {
1186       return false;
1187     } else {
1188       return true;
1189     }
1190   }
1191   SharedClassPathEntry* ent =
1192             (SharedClassPathEntry*)FileMapInfo::shared_path(path_index);
1193   if (!Universe::is_module_initialized()) {
1194     assert(ent != NULL && ent->is_modules_image(),
1195            "Loading non-bootstrap classes before the module system is initialized");
1196     assert(class_loader.is_null(), "sanity");
1197     return true;
1198   }
1199   // Get the pkg_entry from the classloader
1200   TempNewSymbol pkg_name = NULL;
1201   PackageEntry* pkg_entry = NULL;
1202   ModuleEntry* mod_entry = NULL;
1203   pkg_name = InstanceKlass::package_from_name(class_name, CHECK_false);
1204   if (pkg_name != NULL) {
1205     if (loader_data != NULL) {
1206       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1207     }
1208     if (pkg_entry != NULL) {
1209       mod_entry = pkg_entry->module();
1210     }
1211   }
1212 
1213   // If the archived class is from a module that has been patched at runtime,
1214   // the class cannot be loaded from the archive.
1215   if (mod_entry != NULL && mod_entry->is_patched()) {
1216     return false;
1217   }
1218 
1219   if (class_loader.is_null()) {
1220     assert(ent != NULL, "Shared class for NULL classloader must have valid SharedClassPathEntry");
1221     // The NULL classloader can load archived class originated from the
1222     // "modules" jimage and the -Xbootclasspath/a. For class from the
1223     // "modules" jimage, the PackageEntry/ModuleEntry must be defined
1224     // by the NULL classloader.
1225     if (mod_entry != NULL) {
1226       // PackageEntry/ModuleEntry is found in the classloader. Check if the
1227       // ModuleEntry's location agrees with the archived class' origination.
1228       if (ent->is_modules_image() && mod_entry->location()->starts_with("jrt:")) {
1229         return true; // Module class from the "module" jimage
1230       }
1231     }
1232 
1233     // If the archived class is not from the "module" jimage, the class can be
1234     // loaded by the NULL classloader if
1235     //
1236     // 1. the class is from the unamed package
1237     // 2. or, the class is not from a module defined in the NULL classloader
1238     // 3. or, the class is from an unamed module
1239     if (!ent->is_modules_image() && ik->is_shared_boot_class()) {
1240       // the class is from the -Xbootclasspath/a
1241       if (pkg_name == NULL ||
1242           pkg_entry == NULL ||
1243           pkg_entry->in_unnamed_module()) {
1244         assert(mod_entry == NULL ||
1245                mod_entry == loader_data->unnamed_module(),
1246                "the unnamed module is not defined in the classloader");
1247         return true;
1248       }
1249     }
1250     return false;
1251   } else {
1252     bool res = SystemDictionaryShared::is_shared_class_visible_for_classloader(
1253               ik, class_loader, pkg_name, pkg_entry, mod_entry, CHECK_(false));
1254     return res;
1255   }
1256 }
1257 
load_shared_class(InstanceKlass * ik,Handle class_loader,Handle protection_domain,const ClassFileStream * cfs,TRAPS)1258 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik,
1259                                                    Handle class_loader,
1260                                                    Handle protection_domain,
1261                                                    const ClassFileStream *cfs,
1262                                                    TRAPS) {
1263   assert(ik != NULL, "sanity");
1264   assert(!ik->is_unshareable_info_restored(), "shared class can be loaded only once");
1265   Symbol* class_name = ik->name();
1266 
1267   bool visible = is_shared_class_visible(
1268                           class_name, ik, class_loader, CHECK_NULL);
1269   if (!visible) {
1270     return NULL;
1271   }
1272 
1273   // Resolve the superclass and interfaces. They must be the same
1274   // as in dump time, because the layout of <ik> depends on
1275   // the specific layout of ik->super() and ik->local_interfaces().
1276   //
1277   // If unexpected superclass or interfaces are found, we cannot
1278   // load <ik> from the shared archive.
1279 
1280   if (ik->super() != NULL) {
1281     Symbol*  cn = ik->super()->name();
1282     Klass *s = resolve_super_or_fail(class_name, cn,
1283                                      class_loader, protection_domain, true, CHECK_NULL);
1284     if (s != ik->super()) {
1285       // The dynamically resolved super class is not the same as the one we used during dump time,
1286       // so we cannot use ik.
1287       return NULL;
1288     } else {
1289       assert(s->is_shared(), "must be");
1290     }
1291   }
1292 
1293   Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1294   int num_interfaces = interfaces->length();
1295   for (int index = 0; index < num_interfaces; index++) {
1296     InstanceKlass* k = interfaces->at(index);
1297     Symbol* name  = k->name();
1298     Klass* i = resolve_super_or_fail(class_name, name, class_loader, protection_domain, false, CHECK_NULL);
1299     if (k != i) {
1300       // The dynamically resolved interface class is not the same as the one we used during dump time,
1301       // so we cannot use ik.
1302       return NULL;
1303     } else {
1304       assert(i->is_shared(), "must be");
1305     }
1306   }
1307 
1308   InstanceKlass* new_ik = KlassFactory::check_shared_class_file_load_hook(
1309       ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL);
1310   if (new_ik != NULL) {
1311     // The class is changed by CFLH. Return the new class. The shared class is
1312     // not used.
1313     return new_ik;
1314   }
1315 
1316   // Adjust methods to recover missing data.  They need addresses for
1317   // interpreter entry points and their default native method address
1318   // must be reset.
1319 
1320   // Updating methods must be done under a lock so multiple
1321   // threads don't update these in parallel
1322   //
1323   // Shared classes are all currently loaded by either the bootstrap or
1324   // internal parallel class loaders, so this will never cause a deadlock
1325   // on a custom class loader lock.
1326 
1327   ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1328   {
1329     HandleMark hm(THREAD);
1330     Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
1331     check_loader_lock_contention(lockObject, THREAD);
1332     ObjectLocker ol(lockObject, THREAD, true);
1333     // prohibited package check assumes all classes loaded from archive call
1334     // restore_unshareable_info which calls ik->set_package()
1335     ik->restore_unshareable_info(loader_data, protection_domain, CHECK_NULL);
1336   }
1337 
1338   ik->print_class_load_logging(loader_data, NULL, NULL);
1339 
1340   // For boot loader, ensure that GetSystemPackage knows that a class in this
1341   // package was loaded.
1342   if (class_loader.is_null()) {
1343     int path_index = ik->shared_classpath_index();
1344     ResourceMark rm(THREAD);
1345     ClassLoader::add_package(ik->name()->as_C_string(), path_index, THREAD);
1346   }
1347 
1348   if (DumpLoadedClassList != NULL && classlist_file->is_open()) {
1349     // Only dump the classes that can be stored into CDS archive
1350     if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
1351       ResourceMark rm(THREAD);
1352       classlist_file->print_cr("%s", ik->name()->as_C_string());
1353       classlist_file->flush();
1354     }
1355   }
1356 
1357   // notify a class loaded from shared object
1358   ClassLoadingService::notify_class_loaded(ik, true /* shared class */);
1359 
1360   ik->set_has_passed_fingerprint_check(false);
1361   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
1362     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
1363     uint64_t cds_fp = ik->get_stored_fingerprint();
1364     if (aot_fp != 0 && aot_fp == cds_fp) {
1365       // This class matches with a class saved in an AOT library
1366       ik->set_has_passed_fingerprint_check(true);
1367     } else {
1368       if (log_is_enabled(Info, class, fingerprint)) {
1369         ResourceMark rm(THREAD);
1370         log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT, ik->external_name(), aot_fp, cds_fp);
1371       }
1372     }
1373   }
1374 
1375   return ik;
1376 }
1377 #endif // INCLUDE_CDS
1378 
load_instance_class(Symbol * class_name,Handle class_loader,TRAPS)1379 InstanceKlass* SystemDictionary::load_instance_class(Symbol* class_name, Handle class_loader, TRAPS) {
1380 
1381   if (class_loader.is_null()) {
1382     ResourceMark rm(THREAD);
1383     PackageEntry* pkg_entry = NULL;
1384     bool search_only_bootloader_append = false;
1385     ClassLoaderData *loader_data = class_loader_data(class_loader);
1386 
1387     // Find the package in the boot loader's package entry table.
1388     TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK_NULL);
1389     if (pkg_name != NULL) {
1390       pkg_entry = loader_data->packages()->lookup_only(pkg_name);
1391     }
1392 
1393     // Prior to attempting to load the class, enforce the boot loader's
1394     // visibility boundaries.
1395     if (!Universe::is_module_initialized()) {
1396       // During bootstrapping, prior to module initialization, any
1397       // class attempting to be loaded must be checked against the
1398       // java.base packages in the boot loader's PackageEntryTable.
1399       // No class outside of java.base is allowed to be loaded during
1400       // this bootstrapping window.
1401       if (pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1402         // Class is either in the unnamed package or in
1403         // a named package within the unnamed module.  Either
1404         // case is outside of java.base, do not attempt to
1405         // load the class post java.base definition.  If
1406         // java.base has not been defined, let the class load
1407         // and its package will be checked later by
1408         // ModuleEntryTable::verify_javabase_packages.
1409         if (ModuleEntryTable::javabase_defined()) {
1410           return NULL;
1411         }
1412       } else {
1413         // Check that the class' package is defined within java.base.
1414         ModuleEntry* mod_entry = pkg_entry->module();
1415         Symbol* mod_entry_name = mod_entry->name();
1416         if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1417           return NULL;
1418         }
1419       }
1420     } else {
1421       // After the module system has been initialized, check if the class'
1422       // package is in a module defined to the boot loader.
1423       if (pkg_name == NULL || pkg_entry == NULL || pkg_entry->in_unnamed_module()) {
1424         // Class is either in the unnamed package, in a named package
1425         // within a module not defined to the boot loader or in a
1426         // a named package within the unnamed module.  In all cases,
1427         // limit visibility to search for the class only in the boot
1428         // loader's append path.
1429         if (!ClassLoader::has_bootclasspath_append()) {
1430            // If there is no bootclasspath append entry, no need to continue
1431            // searching.
1432            return NULL;
1433         }
1434         search_only_bootloader_append = true;
1435       }
1436     }
1437 
1438     // Prior to bootstrapping's module initialization, never load a class outside
1439     // of the boot loader's module path
1440     assert(Universe::is_module_initialized() ||
1441            !search_only_bootloader_append,
1442            "Attempt to load a class outside of boot loader's module path");
1443 
1444     // Search for classes in the CDS archive.
1445     InstanceKlass* k = NULL;
1446     {
1447 #if INCLUDE_CDS
1448       PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1449       k = load_shared_boot_class(class_name, THREAD);
1450 #endif
1451     }
1452 
1453     if (k == NULL) {
1454       // Use VM class loader
1455       PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1456       k = ClassLoader::load_class(class_name, search_only_bootloader_append, CHECK_NULL);
1457     }
1458 
1459     // find_or_define_instance_class may return a different InstanceKlass
1460     if (k != NULL) {
1461       InstanceKlass* defined_k =
1462         find_or_define_instance_class(class_name, class_loader, k, THREAD);
1463       if (!HAS_PENDING_EXCEPTION && defined_k != k) {
1464         // If a parallel capable class loader already defined this class, register 'k' for cleanup.
1465         assert(defined_k != NULL, "Should have a klass if there's no exception");
1466         loader_data->add_to_deallocate_list(k);
1467         k = defined_k;
1468       } else if (HAS_PENDING_EXCEPTION) {
1469         loader_data->add_to_deallocate_list(k);
1470         return NULL;
1471       }
1472     }
1473     return k;
1474   } else {
1475     // Use user specified class loader to load class. Call loadClass operation on class_loader.
1476     ResourceMark rm(THREAD);
1477 
1478     assert(THREAD->is_Java_thread(), "must be a JavaThread");
1479     JavaThread* jt = (JavaThread*) THREAD;
1480 
1481     PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1482                                ClassLoader::perf_app_classload_selftime(),
1483                                ClassLoader::perf_app_classload_count(),
1484                                jt->get_thread_stat()->perf_recursion_counts_addr(),
1485                                jt->get_thread_stat()->perf_timers_addr(),
1486                                PerfClassTraceTime::CLASS_LOAD);
1487 
1488     Handle s = java_lang_String::create_from_symbol(class_name, CHECK_NULL);
1489     // Translate to external class name format, i.e., convert '/' chars to '.'
1490     Handle string = java_lang_String::externalize_classname(s, CHECK_NULL);
1491 
1492     JavaValue result(T_OBJECT);
1493 
1494     InstanceKlass* spec_klass = SystemDictionary::ClassLoader_klass();
1495 
1496     // Call public unsynchronized loadClass(String) directly for all class loaders.
1497     // For parallelCapable class loaders, JDK >=7, loadClass(String, boolean) will
1498     // acquire a class-name based lock rather than the class loader object lock.
1499     // JDK < 7 already acquire the class loader lock in loadClass(String, boolean).
1500     JavaCalls::call_virtual(&result,
1501                             class_loader,
1502                             spec_klass,
1503                             vmSymbols::loadClass_name(),
1504                             vmSymbols::string_class_signature(),
1505                             string,
1506                             CHECK_NULL);
1507 
1508     assert(result.get_type() == T_OBJECT, "just checking");
1509     oop obj = (oop) result.get_jobject();
1510 
1511     // Primitive classes return null since forName() can not be
1512     // used to obtain any of the Class objects representing primitives or void
1513     if ((obj != NULL) && !(java_lang_Class::is_primitive(obj))) {
1514       InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(obj));
1515       // For user defined Java class loaders, check that the name returned is
1516       // the same as that requested.  This check is done for the bootstrap
1517       // loader when parsing the class file.
1518       if (class_name == k->name()) {
1519         return k;
1520       }
1521     }
1522     // Class is not found or has the wrong name, return NULL
1523     return NULL;
1524   }
1525 }
1526 
post_class_define_event(InstanceKlass * k,const ClassLoaderData * def_cld)1527 static void post_class_define_event(InstanceKlass* k, const ClassLoaderData* def_cld) {
1528   EventClassDefine event;
1529   if (event.should_commit()) {
1530     event.set_definedClass(k);
1531     event.set_definingClassLoader(def_cld);
1532     event.commit();
1533   }
1534 }
1535 
define_instance_class(InstanceKlass * k,TRAPS)1536 void SystemDictionary::define_instance_class(InstanceKlass* k, TRAPS) {
1537 
1538   HandleMark hm(THREAD);
1539   ClassLoaderData* loader_data = k->class_loader_data();
1540   Handle class_loader_h(THREAD, loader_data->class_loader());
1541 
1542  // for bootstrap and other parallel classloaders don't acquire lock,
1543  // use placeholder token
1544  // If a parallelCapable class loader calls define_instance_class instead of
1545  // find_or_define_instance_class to get here, we have a timing
1546  // hole with systemDictionary updates and check_constraints
1547  if (!class_loader_h.is_null() && !is_parallelCapable(class_loader_h)) {
1548     assert(ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD,
1549          compute_loader_lock_object(class_loader_h, THREAD)),
1550          "define called without lock");
1551   }
1552 
1553   // Check class-loading constraints. Throw exception if violation is detected.
1554   // Grabs and releases SystemDictionary_lock
1555   // The check_constraints/find_class call and update_dictionary sequence
1556   // must be "atomic" for a specific class/classloader pair so we never
1557   // define two different instanceKlasses for that class/classloader pair.
1558   // Existing classloaders will call define_instance_class with the
1559   // classloader lock held
1560   // Parallel classloaders will call find_or_define_instance_class
1561   // which will require a token to perform the define class
1562   Symbol*  name_h = k->name();
1563   Dictionary* dictionary = loader_data->dictionary();
1564   unsigned int d_hash = dictionary->compute_hash(name_h);
1565   check_constraints(d_hash, k, class_loader_h, true, CHECK);
1566 
1567   // Register class just loaded with class loader (placed in Vector)
1568   // Note we do this before updating the dictionary, as this can
1569   // fail with an OutOfMemoryError (if it does, we will *not* put this
1570   // class in the dictionary and will not update the class hierarchy).
1571   // JVMTI FollowReferences needs to find the classes this way.
1572   if (k->class_loader() != NULL) {
1573     methodHandle m(THREAD, Universe::loader_addClass_method());
1574     JavaValue result(T_VOID);
1575     JavaCallArguments args(class_loader_h);
1576     args.push_oop(Handle(THREAD, k->java_mirror()));
1577     JavaCalls::call(&result, m, &args, CHECK);
1578   }
1579 
1580   // Add the new class. We need recompile lock during update of CHA.
1581   {
1582     unsigned int p_hash = placeholders()->compute_hash(name_h);
1583     int p_index = placeholders()->hash_to_index(p_hash);
1584 
1585     MutexLocker mu_r(Compile_lock, THREAD);
1586 
1587     // Add to class hierarchy, initialize vtables, and do possible
1588     // deoptimizations.
1589     add_to_hierarchy(k, CHECK); // No exception, but can block
1590 
1591     // Add to systemDictionary - so other classes can see it.
1592     // Grabs and releases SystemDictionary_lock
1593     update_dictionary(d_hash, p_index, p_hash,
1594                       k, class_loader_h, THREAD);
1595   }
1596   k->eager_initialize(THREAD);
1597 
1598   // notify jvmti
1599   if (JvmtiExport::should_post_class_load()) {
1600       assert(THREAD->is_Java_thread(), "thread->is_Java_thread()");
1601       JvmtiExport::post_class_load((JavaThread *) THREAD, k);
1602 
1603   }
1604   post_class_define_event(k, loader_data);
1605 }
1606 
1607 // Support parallel classloading
1608 // All parallel class loaders, including bootstrap classloader
1609 // lock a placeholder entry for this class/class_loader pair
1610 // to allow parallel defines of different classes for this class loader
1611 // With AllowParallelDefine flag==true, in case they do not synchronize around
1612 // FindLoadedClass/DefineClass, calls, we check for parallel
1613 // loading for them, wait if a defineClass is in progress
1614 // and return the initial requestor's results
1615 // This flag does not apply to the bootstrap classloader.
1616 // With AllowParallelDefine flag==false, call through to define_instance_class
1617 // which will throw LinkageError: duplicate class definition.
1618 // False is the requested default.
1619 // For better performance, the class loaders should synchronize
1620 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1621 // potentially waste time reading and parsing the bytestream.
1622 // Note: VM callers should ensure consistency of k/class_name,class_loader
1623 // Be careful when modifying this code: once you have run
1624 // placeholders()->find_and_add(PlaceholderTable::DEFINE_CLASS),
1625 // you need to find_and_remove it before returning.
1626 // So be careful to not exit with a CHECK_ macro betweeen these calls.
find_or_define_instance_class(Symbol * class_name,Handle class_loader,InstanceKlass * k,TRAPS)1627 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1628                                                                InstanceKlass* k, TRAPS) {
1629 
1630   Symbol*  name_h = k->name(); // passed in class_name may be null
1631   ClassLoaderData* loader_data = class_loader_data(class_loader);
1632   Dictionary* dictionary = loader_data->dictionary();
1633 
1634   unsigned int d_hash = dictionary->compute_hash(name_h);
1635 
1636   // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1637   unsigned int p_hash = placeholders()->compute_hash(name_h);
1638   int p_index = placeholders()->hash_to_index(p_hash);
1639   PlaceholderEntry* probe;
1640 
1641   {
1642     MutexLocker mu(SystemDictionary_lock, THREAD);
1643     // First check if class already defined
1644     if (is_parallelDefine(class_loader)) {
1645       InstanceKlass* check = find_class(d_hash, name_h, dictionary);
1646       if (check != NULL) {
1647         return check;
1648       }
1649     }
1650 
1651     // Acquire define token for this class/classloader
1652     probe = placeholders()->find_and_add(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, NULL, THREAD);
1653     // Wait if another thread defining in parallel
1654     // All threads wait - even those that will throw duplicate class: otherwise
1655     // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1656     // if other thread has not finished updating dictionary
1657     while (probe->definer() != NULL) {
1658       SystemDictionary_lock->wait();
1659     }
1660     // Only special cases allow parallel defines and can use other thread's results
1661     // Other cases fall through, and may run into duplicate defines
1662     // caught by finding an entry in the SystemDictionary
1663     if (is_parallelDefine(class_loader) && (probe->instance_klass() != NULL)) {
1664         placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1665         SystemDictionary_lock->notify_all();
1666 #ifdef ASSERT
1667         InstanceKlass* check = find_class(d_hash, name_h, dictionary);
1668         assert(check != NULL, "definer missed recording success");
1669 #endif
1670         return probe->instance_klass();
1671     } else {
1672       // This thread will define the class (even if earlier thread tried and had an error)
1673       probe->set_definer(THREAD);
1674     }
1675   }
1676 
1677   define_instance_class(k, THREAD);
1678 
1679   Handle linkage_exception = Handle(); // null handle
1680 
1681   // definer must notify any waiting threads
1682   {
1683     MutexLocker mu(SystemDictionary_lock, THREAD);
1684     PlaceholderEntry* probe = placeholders()->get_entry(p_index, p_hash, name_h, loader_data);
1685     assert(probe != NULL, "DEFINE_CLASS placeholder lost?");
1686     if (probe != NULL) {
1687       if (HAS_PENDING_EXCEPTION) {
1688         linkage_exception = Handle(THREAD,PENDING_EXCEPTION);
1689         CLEAR_PENDING_EXCEPTION;
1690       } else {
1691         probe->set_instance_klass(k);
1692       }
1693       probe->set_definer(NULL);
1694       placeholders()->find_and_remove(p_index, p_hash, name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1695       SystemDictionary_lock->notify_all();
1696     }
1697   }
1698 
1699   // Can't throw exception while holding lock due to rank ordering
1700   if (linkage_exception() != NULL) {
1701     THROW_OOP_(linkage_exception(), NULL); // throws exception and returns
1702   }
1703 
1704   return k;
1705 }
1706 
compute_loader_lock_object(Handle class_loader,TRAPS)1707 Handle SystemDictionary::compute_loader_lock_object(Handle class_loader, TRAPS) {
1708   // If class_loader is NULL we synchronize on _system_loader_lock_obj
1709   if (class_loader.is_null()) {
1710     return Handle(THREAD, _system_loader_lock_obj);
1711   } else {
1712     return class_loader;
1713   }
1714 }
1715 
1716 // This method is added to check how often we have to wait to grab loader
1717 // lock. The results are being recorded in the performance counters defined in
1718 // ClassLoader::_sync_systemLoaderLockContentionRate and
1719 // ClassLoader::_sync_nonSystemLoaderLockConteionRate.
check_loader_lock_contention(Handle loader_lock,TRAPS)1720 void SystemDictionary::check_loader_lock_contention(Handle loader_lock, TRAPS) {
1721   if (!UsePerfData) {
1722     return;
1723   }
1724 
1725   assert(!loader_lock.is_null(), "NULL lock object");
1726 
1727   if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader_lock)
1728       == ObjectSynchronizer::owner_other) {
1729     // contention will likely happen, so increment the corresponding
1730     // contention counter.
1731     if (loader_lock() == _system_loader_lock_obj) {
1732       ClassLoader::sync_systemLoaderLockContentionRate()->inc();
1733     } else {
1734       ClassLoader::sync_nonSystemLoaderLockContentionRate()->inc();
1735     }
1736   }
1737 }
1738 
1739 // ----------------------------------------------------------------------------
1740 // Lookup
1741 
find_class(unsigned int hash,Symbol * class_name,Dictionary * dictionary)1742 InstanceKlass* SystemDictionary::find_class(unsigned int hash,
1743                                             Symbol* class_name,
1744                                             Dictionary* dictionary) {
1745   assert_locked_or_safepoint(SystemDictionary_lock);
1746   int index = dictionary->hash_to_index(hash);
1747   return dictionary->find_class(index, hash, class_name);
1748 }
1749 
1750 
1751 // Basic find on classes in the midst of being loaded
find_placeholder(Symbol * class_name,ClassLoaderData * loader_data)1752 Symbol* SystemDictionary::find_placeholder(Symbol* class_name,
1753                                            ClassLoaderData* loader_data) {
1754   assert_locked_or_safepoint(SystemDictionary_lock);
1755   unsigned int p_hash = placeholders()->compute_hash(class_name);
1756   int p_index = placeholders()->hash_to_index(p_hash);
1757   return placeholders()->find_entry(p_index, p_hash, class_name, loader_data);
1758 }
1759 
1760 
1761 // Used for assertions and verification only
1762 // Precalculating the hash and index is an optimization because there are many lookups
1763 // before adding the class.
find_class(Symbol * class_name,ClassLoaderData * loader_data)1764 InstanceKlass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
1765   assert_locked_or_safepoint(SystemDictionary_lock);
1766   #ifndef ASSERT
1767   guarantee(VerifyBeforeGC      ||
1768             VerifyDuringGC      ||
1769             VerifyBeforeExit    ||
1770             VerifyDuringStartup ||
1771             VerifyAfterGC, "too expensive");
1772   #endif
1773 
1774   Dictionary* dictionary = loader_data->dictionary();
1775   unsigned int d_hash = dictionary->compute_hash(class_name);
1776   return find_class(d_hash, class_name, dictionary);
1777 }
1778 
1779 
1780 // ----------------------------------------------------------------------------
1781 // Update hierachy. This is done before the new klass has been added to the SystemDictionary. The Recompile_lock
1782 // is held, to ensure that the compiler is not using the class hierachy, and that deoptimization will kick in
1783 // before a new class is used.
1784 
add_to_hierarchy(InstanceKlass * k,TRAPS)1785 void SystemDictionary::add_to_hierarchy(InstanceKlass* k, TRAPS) {
1786   assert(k != NULL, "just checking");
1787   assert_locked_or_safepoint(Compile_lock);
1788 
1789   k->set_init_state(InstanceKlass::loaded);
1790   // make sure init_state store is already done.
1791   // The compiler reads the hierarchy outside of the Compile_lock.
1792   // Access ordering is used to add to hierarchy.
1793 
1794   // Link into hierachy.
1795   k->append_to_sibling_list();                    // add to superklass/sibling list
1796   k->process_interfaces(THREAD);                  // handle all "implements" declarations
1797 
1798   // Now flush all code that depended on old class hierarchy.
1799   // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1800   CodeCache::flush_dependents_on(k);
1801 }
1802 
1803 // ----------------------------------------------------------------------------
1804 // GC support
1805 
1806 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1807 // Note: anonymous classes are not in the SD.
do_unloading(GCTimer * gc_timer)1808 bool SystemDictionary::do_unloading(GCTimer* gc_timer) {
1809 
1810   bool unloading_occurred;
1811   bool is_concurrent = !SafepointSynchronize::is_at_safepoint();
1812   {
1813     GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1814     assert_locked_or_safepoint(ClassLoaderDataGraph_lock);  // caller locks.
1815     // First, mark for unload all ClassLoaderData referencing a dead class loader.
1816     unloading_occurred = ClassLoaderDataGraph::do_unloading();
1817     if (unloading_occurred) {
1818       MutexLocker ml2(is_concurrent ? Module_lock : NULL);
1819       JFR_ONLY(Jfr::on_unloading_classes();)
1820 
1821       MutexLocker ml1(is_concurrent ? SystemDictionary_lock : NULL);
1822       ClassLoaderDataGraph::clean_module_and_package_info();
1823       constraints()->purge_loader_constraints();
1824       resolution_errors()->purge_resolution_errors();
1825     }
1826   }
1827 
1828   GCTraceTime(Debug, gc, phases) t("Trigger cleanups", gc_timer);
1829 
1830   if (unloading_occurred) {
1831     SymbolTable::trigger_cleanup();
1832 
1833     // Oops referenced by the protection domain cache table may get unreachable independently
1834     // of the class loader (eg. cached protection domain oops). So we need to
1835     // explicitly unlink them here.
1836     // All protection domain oops are linked to the caller class, so if nothing
1837     // unloads, this is not needed.
1838     _pd_cache_table->trigger_cleanup();
1839   }
1840 
1841   return unloading_occurred;
1842 }
1843 
oops_do(OopClosure * f,bool include_handles)1844 void SystemDictionary::oops_do(OopClosure* f, bool include_handles) {
1845   f->do_oop(&_java_system_loader);
1846   f->do_oop(&_java_platform_loader);
1847   f->do_oop(&_system_loader_lock_obj);
1848   CDS_ONLY(SystemDictionaryShared::oops_do(f);)
1849 
1850   // Visit extra methods
1851   invoke_method_table()->oops_do(f);
1852 
1853   if (include_handles) {
1854     OopStorageSet::vm_global()->oops_do(f);
1855   }
1856 }
1857 
1858 // CDS: scan and relocate all classes referenced by _well_known_klasses[].
well_known_klasses_do(MetaspaceClosure * it)1859 void SystemDictionary::well_known_klasses_do(MetaspaceClosure* it) {
1860   for (int id = FIRST_WKID; id < WKID_LIMIT; id++) {
1861     it->push(well_known_klass_addr((WKID)id));
1862   }
1863 }
1864 
methods_do(void f (Method *))1865 void SystemDictionary::methods_do(void f(Method*)) {
1866   // Walk methods in loaded classes
1867   MutexLocker ml(ClassLoaderDataGraph_lock);
1868   ClassLoaderDataGraph::methods_do(f);
1869   // Walk method handle intrinsics
1870   invoke_method_table()->methods_do(f);
1871 }
1872 
1873 // ----------------------------------------------------------------------------
1874 // Initialization
1875 
initialize(TRAPS)1876 void SystemDictionary::initialize(TRAPS) {
1877   // Allocate arrays
1878   _placeholders        = new PlaceholderTable(_placeholder_table_size);
1879   _loader_constraints  = new LoaderConstraintTable(_loader_constraint_size);
1880   _resolution_errors   = new ResolutionErrorTable(_resolution_error_size);
1881   _invoke_method_table = new SymbolPropertyTable(_invoke_method_size);
1882   _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize);
1883 
1884   // Allocate private object used as system class loader lock
1885   _system_loader_lock_obj = oopFactory::new_intArray(0, CHECK);
1886   // Initialize basic classes
1887   resolve_well_known_classes(CHECK);
1888 }
1889 
1890 // Compact table of directions on the initialization of klasses:
1891 static const short wk_init_info[] = {
1892   #define WK_KLASS_INIT_INFO(name, symbol) \
1893     ((short)vmSymbols::VM_SYMBOL_ENUM_NAME(symbol)),
1894 
1895   WK_KLASSES_DO(WK_KLASS_INIT_INFO)
1896   #undef WK_KLASS_INIT_INFO
1897   0
1898 };
1899 
1900 #ifdef ASSERT
is_well_known_klass(Symbol * class_name)1901 bool SystemDictionary::is_well_known_klass(Symbol* class_name) {
1902   int sid;
1903   for (int i = 0; (sid = wk_init_info[i]) != 0; i++) {
1904     Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
1905     if (class_name == symbol) {
1906       return true;
1907     }
1908   }
1909   return false;
1910 }
1911 #endif
1912 
resolve_wk_klass(WKID id,TRAPS)1913 bool SystemDictionary::resolve_wk_klass(WKID id, TRAPS) {
1914   assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1915   int sid = wk_init_info[id - FIRST_WKID];
1916   Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
1917   InstanceKlass** klassp = &_well_known_klasses[id];
1918 
1919   if ((*klassp) == NULL) {
1920     Klass* k = resolve_or_fail(symbol, true, CHECK_0);
1921     (*klassp) = InstanceKlass::cast(k);
1922   }
1923   return ((*klassp) != NULL);
1924 }
1925 
resolve_wk_klasses_until(WKID limit_id,WKID & start_id,TRAPS)1926 void SystemDictionary::resolve_wk_klasses_until(WKID limit_id, WKID &start_id, TRAPS) {
1927   assert((int)start_id <= (int)limit_id, "IDs are out of order!");
1928   for (int id = (int)start_id; id < (int)limit_id; id++) {
1929     assert(id >= (int)FIRST_WKID && id < (int)WKID_LIMIT, "oob");
1930     resolve_wk_klass((WKID)id, CHECK);
1931   }
1932 
1933   // move the starting value forward to the limit:
1934   start_id = limit_id;
1935 }
1936 
resolve_well_known_classes(TRAPS)1937 void SystemDictionary::resolve_well_known_classes(TRAPS) {
1938   assert(WK_KLASS(Object_klass) == NULL, "well-known classes should only be initialized once");
1939 
1940   // Create the ModuleEntry for java.base.  This call needs to be done here,
1941   // after vmSymbols::initialize() is called but before any classes are pre-loaded.
1942   ClassLoader::classLoader_init2(CHECK);
1943 
1944   // Preload commonly used klasses
1945   WKID scan = FIRST_WKID;
1946   // first do Object, then String, Class
1947 #if INCLUDE_CDS
1948   if (UseSharedSpaces) {
1949     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Object_klass), scan, CHECK);
1950 
1951     // It's unsafe to access the archived heap regions before they
1952     // are fixed up, so we must do the fixup as early as possible
1953     // before the archived java objects are accessed by functions
1954     // such as java_lang_Class::restore_archived_mirror and
1955     // ConstantPool::restore_unshareable_info (restores the archived
1956     // resolved_references array object).
1957     //
1958     // HeapShared::fixup_mapped_heap_regions() fills the empty
1959     // spaces in the archived heap regions and may use
1960     // SystemDictionary::Object_klass(), so we can do this only after
1961     // Object_klass is resolved. See the above resolve_wk_klasses_through()
1962     // call. No mirror objects are accessed/restored in the above call.
1963     // Mirrors are restored after java.lang.Class is loaded.
1964     HeapShared::fixup_mapped_heap_regions();
1965 
1966     // Initialize the constant pool for the Object_class
1967     assert(Object_klass()->is_shared(), "must be");
1968     Object_klass()->constants()->restore_unshareable_info(CHECK);
1969     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
1970   } else
1971 #endif
1972   {
1973     resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Class_klass), scan, CHECK);
1974   }
1975 
1976   assert(WK_KLASS(Object_klass) != NULL, "well-known classes should now be initialized");
1977 
1978   java_lang_Object::register_natives(CHECK);
1979 
1980   // Calculate offsets for String and Class classes since they are loaded and
1981   // can be used after this point.
1982   java_lang_String::compute_offsets();
1983   java_lang_Class::compute_offsets();
1984 
1985   // Fixup mirrors for classes loaded before java.lang.Class.
1986   // These calls iterate over the objects currently in the perm gen
1987   // so calling them at this point is matters (not before when there
1988   // are fewer objects and not later after there are more objects
1989   // in the perm gen.
1990   Universe::initialize_basic_type_mirrors(CHECK);
1991   Universe::fixup_mirrors(CHECK);
1992 
1993   // do a bunch more:
1994   resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(Reference_klass), scan, CHECK);
1995 
1996   // Preload ref klasses and set reference types
1997   WK_KLASS(Reference_klass)->set_reference_type(REF_OTHER);
1998   InstanceRefKlass::update_nonstatic_oop_maps(WK_KLASS(Reference_klass));
1999 
2000   resolve_wk_klasses_through(WK_KLASS_ENUM_NAME(PhantomReference_klass), scan, CHECK);
2001   WK_KLASS(SoftReference_klass)->set_reference_type(REF_SOFT);
2002   WK_KLASS(WeakReference_klass)->set_reference_type(REF_WEAK);
2003   WK_KLASS(FinalReference_klass)->set_reference_type(REF_FINAL);
2004   WK_KLASS(PhantomReference_klass)->set_reference_type(REF_PHANTOM);
2005 
2006   // JSR 292 classes
2007   WKID jsr292_group_start = WK_KLASS_ENUM_NAME(MethodHandle_klass);
2008   WKID jsr292_group_end   = WK_KLASS_ENUM_NAME(VolatileCallSite_klass);
2009   resolve_wk_klasses_until(jsr292_group_start, scan, CHECK);
2010   resolve_wk_klasses_through(jsr292_group_end, scan, CHECK);
2011   WKID last = WKID_LIMIT;
2012   resolve_wk_klasses_until(last, scan, CHECK);
2013 
2014   _box_klasses[T_BOOLEAN] = WK_KLASS(Boolean_klass);
2015   _box_klasses[T_CHAR]    = WK_KLASS(Character_klass);
2016   _box_klasses[T_FLOAT]   = WK_KLASS(Float_klass);
2017   _box_klasses[T_DOUBLE]  = WK_KLASS(Double_klass);
2018   _box_klasses[T_BYTE]    = WK_KLASS(Byte_klass);
2019   _box_klasses[T_SHORT]   = WK_KLASS(Short_klass);
2020   _box_klasses[T_INT]     = WK_KLASS(Integer_klass);
2021   _box_klasses[T_LONG]    = WK_KLASS(Long_klass);
2022   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
2023   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
2024 
2025 #ifdef ASSERT
2026   if (UseSharedSpaces) {
2027     assert(JvmtiExport::is_early_phase(),
2028            "All well known classes must be resolved in JVMTI early phase");
2029     for (int i = FIRST_WKID; i < last; i++) {
2030       InstanceKlass* k = _well_known_klasses[i];
2031       assert(k->is_shared(), "must not be replaced by JVMTI class file load hook");
2032     }
2033   }
2034 #endif
2035 }
2036 
2037 // Tells if a given klass is a box (wrapper class, such as java.lang.Integer).
2038 // If so, returns the basic type it holds.  If not, returns T_OBJECT.
box_klass_type(Klass * k)2039 BasicType SystemDictionary::box_klass_type(Klass* k) {
2040   assert(k != NULL, "");
2041   for (int i = T_BOOLEAN; i < T_VOID+1; i++) {
2042     if (_box_klasses[i] == k)
2043       return (BasicType)i;
2044   }
2045   return T_OBJECT;
2046 }
2047 
2048 // Constraints on class loaders. The details of the algorithm can be
2049 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
2050 // Virtual Machine" by Sheng Liang and Gilad Bracha.  The basic idea is
2051 // that the dictionary needs to maintain a set of contraints that
2052 // must be satisfied by all classes in the dictionary.
2053 // if defining is true, then LinkageError if already in dictionary
2054 // if initiating loader, then ok if InstanceKlass matches existing entry
2055 
check_constraints(unsigned int d_hash,InstanceKlass * k,Handle class_loader,bool defining,TRAPS)2056 void SystemDictionary::check_constraints(unsigned int d_hash,
2057                                          InstanceKlass* k,
2058                                          Handle class_loader,
2059                                          bool defining,
2060                                          TRAPS) {
2061   ResourceMark rm(THREAD);
2062   stringStream ss;
2063   bool throwException = false;
2064 
2065   {
2066     Symbol *name = k->name();
2067     ClassLoaderData *loader_data = class_loader_data(class_loader);
2068 
2069     MutexLocker mu(SystemDictionary_lock, THREAD);
2070 
2071     InstanceKlass* check = find_class(d_hash, name, loader_data->dictionary());
2072     if (check != NULL) {
2073       // If different InstanceKlass - duplicate class definition,
2074       // else - ok, class loaded by a different thread in parallel.
2075       // We should only have found it if it was done loading and ok to use.
2076       // The dictionary only holds instance classes, placeholders
2077       // also hold array classes.
2078 
2079       assert(check->is_instance_klass(), "noninstance in systemdictionary");
2080       if ((defining == true) || (k != check)) {
2081         throwException = true;
2082         ss.print("loader %s", loader_data->loader_name_and_id());
2083         ss.print(" attempted duplicate %s definition for %s. (%s)",
2084                  k->external_kind(), k->external_name(), k->class_in_module_of_loader(false, true));
2085       } else {
2086         return;
2087       }
2088     }
2089 
2090 #ifdef ASSERT
2091     Symbol* ph_check = find_placeholder(name, loader_data);
2092     assert(ph_check == NULL || ph_check == name, "invalid symbol");
2093 #endif
2094 
2095     if (throwException == false) {
2096       if (constraints()->check_or_update(k, class_loader, name) == false) {
2097         throwException = true;
2098         ss.print("loader constraint violation: loader %s", loader_data->loader_name_and_id());
2099         ss.print(" wants to load %s %s.",
2100                  k->external_kind(), k->external_name());
2101         Klass *existing_klass = constraints()->find_constrained_klass(name, class_loader);
2102         if (existing_klass != NULL && existing_klass->class_loader() != class_loader()) {
2103           ss.print(" A different %s with the same name was previously loaded by %s. (%s)",
2104                    existing_klass->external_kind(),
2105                    existing_klass->class_loader_data()->loader_name_and_id(),
2106                    existing_klass->class_in_module_of_loader(false, true));
2107         } else {
2108           ss.print(" (%s)", k->class_in_module_of_loader(false, true));
2109         }
2110       }
2111     }
2112   }
2113 
2114   // Throw error now if needed (cannot throw while holding
2115   // SystemDictionary_lock because of rank ordering)
2116   if (throwException == true) {
2117     THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
2118   }
2119 }
2120 
2121 // Update class loader data dictionary - done after check_constraint and add_to_hierachy
2122 // have been called.
update_dictionary(unsigned int d_hash,int p_index,unsigned int p_hash,InstanceKlass * k,Handle class_loader,TRAPS)2123 void SystemDictionary::update_dictionary(unsigned int d_hash,
2124                                          int p_index, unsigned int p_hash,
2125                                          InstanceKlass* k,
2126                                          Handle class_loader,
2127                                          TRAPS) {
2128   // Compile_lock prevents systemDictionary updates during compilations
2129   assert_locked_or_safepoint(Compile_lock);
2130   Symbol*  name  = k->name();
2131   ClassLoaderData *loader_data = class_loader_data(class_loader);
2132 
2133   {
2134     MutexLocker mu1(SystemDictionary_lock, THREAD);
2135 
2136     // Make a new dictionary entry.
2137     Dictionary* dictionary = loader_data->dictionary();
2138     InstanceKlass* sd_check = find_class(d_hash, name, dictionary);
2139     if (sd_check == NULL) {
2140       dictionary->add_klass(d_hash, name, k);
2141     }
2142   #ifdef ASSERT
2143     sd_check = find_class(d_hash, name, dictionary);
2144     assert (sd_check != NULL, "should have entry in dictionary");
2145     // Note: there may be a placeholder entry: for circularity testing
2146     // or for parallel defines
2147   #endif
2148     SystemDictionary_lock->notify_all();
2149   }
2150 }
2151 
2152 
2153 // Try to find a class name using the loader constraints.  The
2154 // loader constraints might know about a class that isn't fully loaded
2155 // yet and these will be ignored.
find_constrained_instance_or_array_klass(Symbol * class_name,Handle class_loader,TRAPS)2156 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
2157                     Symbol* class_name, Handle class_loader, TRAPS) {
2158 
2159   // First see if it has been loaded directly.
2160   // Force the protection domain to be null.  (This removes protection checks.)
2161   Handle no_protection_domain;
2162   Klass* klass = find_instance_or_array_klass(class_name, class_loader,
2163                                               no_protection_domain, CHECK_NULL);
2164   if (klass != NULL)
2165     return klass;
2166 
2167   // Now look to see if it has been loaded elsewhere, and is subject to
2168   // a loader constraint that would require this loader to return the
2169   // klass that is already loaded.
2170   if (FieldType::is_array(class_name)) {
2171     // For array classes, their Klass*s are not kept in the
2172     // constraint table. The element Klass*s are.
2173     FieldArrayInfo fd;
2174     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(NULL));
2175     if (t != T_OBJECT) {
2176       klass = Universe::typeArrayKlassObj(t);
2177     } else {
2178       MutexLocker mu(SystemDictionary_lock, THREAD);
2179       klass = constraints()->find_constrained_klass(fd.object_key(), class_loader);
2180     }
2181     // If element class already loaded, allocate array klass
2182     if (klass != NULL) {
2183       klass = klass->array_klass_or_null(fd.dimension());
2184     }
2185   } else {
2186     MutexLocker mu(SystemDictionary_lock, THREAD);
2187     // Non-array classes are easy: simply check the constraint table.
2188     klass = constraints()->find_constrained_klass(class_name, class_loader);
2189   }
2190 
2191   return klass;
2192 }
2193 
2194 
add_loader_constraint(Symbol * class_name,Handle class_loader1,Handle class_loader2,Thread * THREAD)2195 bool SystemDictionary::add_loader_constraint(Symbol* class_name,
2196                                              Handle class_loader1,
2197                                              Handle class_loader2,
2198                                              Thread* THREAD) {
2199   ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
2200   ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
2201 
2202   Symbol* constraint_name = NULL;
2203   // Needs to be in same scope as constraint_name in case a Symbol is created and
2204   // assigned to constraint_name.
2205   FieldArrayInfo fd;
2206   if (!FieldType::is_array(class_name)) {
2207     constraint_name = class_name;
2208   } else {
2209     // For array classes, their Klass*s are not kept in the
2210     // constraint table. The element classes are.
2211     BasicType t = FieldType::get_array_info(class_name, fd, CHECK_(false));
2212     // primitive types always pass
2213     if (t != T_OBJECT) {
2214       return true;
2215     } else {
2216       constraint_name = fd.object_key();
2217     }
2218   }
2219 
2220   Dictionary* dictionary1 = loader_data1->dictionary();
2221   unsigned int d_hash1 = dictionary1->compute_hash(constraint_name);
2222 
2223   Dictionary* dictionary2 = loader_data2->dictionary();
2224   unsigned int d_hash2 = dictionary2->compute_hash(constraint_name);
2225 
2226   {
2227     MutexLocker mu_s(SystemDictionary_lock, THREAD);
2228     InstanceKlass* klass1 = find_class(d_hash1, constraint_name, dictionary1);
2229     InstanceKlass* klass2 = find_class(d_hash2, constraint_name, dictionary2);
2230     return constraints()->add_entry(constraint_name, klass1, class_loader1,
2231                                     klass2, class_loader2);
2232   }
2233 }
2234 
2235 // Add entry to resolution error table to record the error when the first
2236 // attempt to resolve a reference to a class has failed.
add_resolution_error(const constantPoolHandle & pool,int which,Symbol * error,Symbol * message)2237 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
2238                                             Symbol* error, Symbol* message) {
2239   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2240   int index = resolution_errors()->hash_to_index(hash);
2241   {
2242     MutexLocker ml(SystemDictionary_lock, Thread::current());
2243     resolution_errors()->add_entry(index, hash, pool, which, error, message);
2244   }
2245 }
2246 
2247 // Delete a resolution error for RedefineClasses for a constant pool is going away
delete_resolution_error(ConstantPool * pool)2248 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
2249   resolution_errors()->delete_entry(pool);
2250 }
2251 
2252 // Lookup resolution error table. Returns error if found, otherwise NULL.
find_resolution_error(const constantPoolHandle & pool,int which,Symbol ** message)2253 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which,
2254                                                 Symbol** message) {
2255   unsigned int hash = resolution_errors()->compute_hash(pool, which);
2256   int index = resolution_errors()->hash_to_index(hash);
2257   {
2258     MutexLocker ml(SystemDictionary_lock, Thread::current());
2259     ResolutionErrorEntry* entry = resolution_errors()->find_entry(index, hash, pool, which);
2260     if (entry != NULL) {
2261       *message = entry->message();
2262       return entry->error();
2263     } else {
2264       return NULL;
2265     }
2266   }
2267 }
2268 
2269 
2270 // Signature constraints ensure that callers and callees agree about
2271 // the meaning of type names in their signatures.  This routine is the
2272 // intake for constraints.  It collects them from several places:
2273 //
2274 //  * LinkResolver::resolve_method (if check_access is true) requires
2275 //    that the resolving class (the caller) and the defining class of
2276 //    the resolved method (the callee) agree on each type in the
2277 //    method's signature.
2278 //
2279 //  * LinkResolver::resolve_interface_method performs exactly the same
2280 //    checks.
2281 //
2282 //  * LinkResolver::resolve_field requires that the constant pool
2283 //    attempting to link to a field agree with the field's defining
2284 //    class about the type of the field signature.
2285 //
2286 //  * klassVtable::initialize_vtable requires that, when a class
2287 //    overrides a vtable entry allocated by a superclass, that the
2288 //    overriding method (i.e., the callee) agree with the superclass
2289 //    on each type in the method's signature.
2290 //
2291 //  * klassItable::initialize_itable requires that, when a class fills
2292 //    in its itables, for each non-abstract method installed in an
2293 //    itable, the method (i.e., the callee) agree with the interface
2294 //    on each type in the method's signature.
2295 //
2296 // All those methods have a boolean (check_access, checkconstraints)
2297 // which turns off the checks.  This is used from specialized contexts
2298 // such as bootstrapping, dumping, and debugging.
2299 //
2300 // No direct constraint is placed between the class and its
2301 // supertypes.  Constraints are only placed along linked relations
2302 // between callers and callees.  When a method overrides or implements
2303 // an abstract method in a supertype (superclass or interface), the
2304 // constraints are placed as if the supertype were the caller to the
2305 // overriding method.  (This works well, since callers to the
2306 // supertype have already established agreement between themselves and
2307 // the supertype.)  As a result of all this, a class can disagree with
2308 // its supertype about the meaning of a type name, as long as that
2309 // class neither calls a relevant method of the supertype, nor is
2310 // called (perhaps via an override) from the supertype.
2311 //
2312 //
2313 // SystemDictionary::check_signature_loaders(sig, l1, l2)
2314 //
2315 // Make sure all class components (including arrays) in the given
2316 // signature will be resolved to the same class in both loaders.
2317 // Returns the name of the type that failed a loader constraint check, or
2318 // NULL if no constraint failed.  No exception except OOME is thrown.
2319 // Arrays are not added to the loader constraint table, their elements are.
check_signature_loaders(Symbol * signature,Handle loader1,Handle loader2,bool is_method,TRAPS)2320 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
2321                                                Handle loader1, Handle loader2,
2322                                                bool is_method, TRAPS)  {
2323   // Nothing to do if loaders are the same.
2324   if (loader1() == loader2()) {
2325     return NULL;
2326   }
2327 
2328   SignatureStream sig_strm(signature, is_method);
2329   while (!sig_strm.is_done()) {
2330     if (sig_strm.is_object()) {
2331       Symbol* sig = sig_strm.as_symbol();
2332       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
2333         return sig;
2334       }
2335     }
2336     sig_strm.next();
2337   }
2338   return NULL;
2339 }
2340 
2341 
find_method_handle_intrinsic(vmIntrinsics::ID iid,Symbol * signature,TRAPS)2342 Method* SystemDictionary::find_method_handle_intrinsic(vmIntrinsics::ID iid,
2343                                                        Symbol* signature,
2344                                                        TRAPS) {
2345   methodHandle empty;
2346   assert(MethodHandles::is_signature_polymorphic(iid) &&
2347          MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
2348          iid != vmIntrinsics::_invokeGeneric,
2349          "must be a known MH intrinsic iid=%d: %s", iid, vmIntrinsics::name_at(iid));
2350 
2351   unsigned int hash  = invoke_method_table()->compute_hash(signature, iid);
2352   int          index = invoke_method_table()->hash_to_index(hash);
2353   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2354   methodHandle m;
2355   if (spe == NULL || spe->method() == NULL) {
2356     spe = NULL;
2357     // Must create lots of stuff here, but outside of the SystemDictionary lock.
2358     m = Method::make_method_handle_intrinsic(iid, signature, CHECK_NULL);
2359     if (!Arguments::is_interpreter_only()) {
2360       // Generate a compiled form of the MH intrinsic.
2361       AdapterHandlerLibrary::create_native_wrapper(m);
2362       // Check if have the compiled code.
2363       if (!m->has_compiled_code()) {
2364         THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(),
2365                        "Out of space in CodeCache for method handle intrinsic");
2366       }
2367     }
2368     // Now grab the lock.  We might have to throw away the new method,
2369     // if a racing thread has managed to install one at the same time.
2370     {
2371       MutexLocker ml(SystemDictionary_lock, THREAD);
2372       spe = invoke_method_table()->find_entry(index, hash, signature, iid);
2373       if (spe == NULL)
2374         spe = invoke_method_table()->add_entry(index, hash, signature, iid);
2375       if (spe->method() == NULL)
2376         spe->set_method(m());
2377     }
2378   }
2379 
2380   assert(spe != NULL && spe->method() != NULL, "");
2381   assert(Arguments::is_interpreter_only() || (spe->method()->has_compiled_code() &&
2382          spe->method()->code()->entry_point() == spe->method()->from_compiled_entry()),
2383          "MH intrinsic invariant");
2384   return spe->method();
2385 }
2386 
2387 // Helper for unpacking the return value from linkMethod and linkCallSite.
unpack_method_and_appendix(Handle mname,Klass * accessing_klass,objArrayHandle appendix_box,Handle * appendix_result,TRAPS)2388 static Method* unpack_method_and_appendix(Handle mname,
2389                                           Klass* accessing_klass,
2390                                           objArrayHandle appendix_box,
2391                                           Handle* appendix_result,
2392                                           TRAPS) {
2393   if (mname.not_null()) {
2394     Method* m = java_lang_invoke_MemberName::vmtarget(mname());
2395     if (m != NULL) {
2396       oop appendix = appendix_box->obj_at(0);
2397       if (TraceMethodHandles) {
2398     #ifndef PRODUCT
2399         ttyLocker ttyl;
2400         tty->print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2401         m->print();
2402         if (appendix != NULL) { tty->print("appendix = "); appendix->print(); }
2403         tty->cr();
2404     #endif //PRODUCT
2405       }
2406       (*appendix_result) = Handle(THREAD, appendix);
2407       // the target is stored in the cpCache and if a reference to this
2408       // MemberName is dropped we need a way to make sure the
2409       // class_loader containing this method is kept alive.
2410       methodHandle mh(THREAD, m); // record_dependency can safepoint.
2411       ClassLoaderData* this_key = accessing_klass->class_loader_data();
2412       this_key->record_dependency(m->method_holder());
2413       return mh();
2414     }
2415   }
2416   THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives");
2417 }
2418 
find_method_handle_invoker(Klass * klass,Symbol * name,Symbol * signature,Klass * accessing_klass,Handle * appendix_result,TRAPS)2419 Method* SystemDictionary::find_method_handle_invoker(Klass* klass,
2420                                                      Symbol* name,
2421                                                      Symbol* signature,
2422                                                      Klass* accessing_klass,
2423                                                      Handle *appendix_result,
2424                                                      TRAPS) {
2425   assert(THREAD->can_call_java() ,"");
2426   Handle method_type =
2427     SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_NULL);
2428 
2429   int ref_kind = JVM_REF_invokeVirtual;
2430   oop name_oop = StringTable::intern(name, CHECK_NULL);
2431   Handle name_str (THREAD, name_oop);
2432   objArrayHandle appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK_NULL);
2433   assert(appendix_box->obj_at(0) == NULL, "");
2434 
2435   // This should not happen.  JDK code should take care of that.
2436   if (accessing_klass == NULL || method_type.is_null()) {
2437     THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "bad invokehandle");
2438   }
2439 
2440   // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2441   JavaCallArguments args;
2442   args.push_oop(Handle(THREAD, accessing_klass->java_mirror()));
2443   args.push_int(ref_kind);
2444   args.push_oop(Handle(THREAD, klass->java_mirror()));
2445   args.push_oop(name_str);
2446   args.push_oop(method_type);
2447   args.push_oop(appendix_box);
2448   JavaValue result(T_OBJECT);
2449   JavaCalls::call_static(&result,
2450                          SystemDictionary::MethodHandleNatives_klass(),
2451                          vmSymbols::linkMethod_name(),
2452                          vmSymbols::linkMethod_signature(),
2453                          &args, CHECK_NULL);
2454   Handle mname(THREAD, (oop) result.get_jobject());
2455   return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2456 }
2457 
2458 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2459 // We must ensure that all class loaders everywhere will reach this class, for any client.
2460 // This is a safe bet for public classes in java.lang, such as Object and String.
2461 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2462 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
is_always_visible_class(oop mirror)2463 static bool is_always_visible_class(oop mirror) {
2464   Klass* klass = java_lang_Class::as_Klass(mirror);
2465   if (klass->is_objArray_klass()) {
2466     klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2467   }
2468   if (klass->is_typeArray_klass()) {
2469     return true; // primitive array
2470   }
2471   assert(klass->is_instance_klass(), "%s", klass->external_name());
2472   return klass->is_public() &&
2473          (InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::Object_klass()) ||       // java.lang
2474           InstanceKlass::cast(klass)->is_same_class_package(SystemDictionary::MethodHandle_klass()));  // java.lang.invoke
2475 }
2476 
2477 
2478 // Return the Java mirror (java.lang.Class instance) for a single-character
2479 // descriptor.  This result, when available, is the same as produced by the
2480 // heavier API point of the same name that takes a Symbol.
find_java_mirror_for_type(char signature_char)2481 oop SystemDictionary::find_java_mirror_for_type(char signature_char) {
2482   return java_lang_Class::primitive_mirror(char2type(signature_char));
2483 }
2484 
2485 // Find or construct the Java mirror (java.lang.Class instance) for a
2486 // for the given field type signature, as interpreted relative to the
2487 // given class loader.  Handles primitives, void, references, arrays,
2488 // and all other reflectable types, except method types.
2489 // N.B.  Code in reflection should use this entry point.
find_java_mirror_for_type(Symbol * signature,Klass * accessing_klass,Handle class_loader,Handle protection_domain,SignatureStream::FailureMode failure_mode,TRAPS)2490 Handle SystemDictionary::find_java_mirror_for_type(Symbol* signature,
2491                                                    Klass* accessing_klass,
2492                                                    Handle class_loader,
2493                                                    Handle protection_domain,
2494                                                    SignatureStream::FailureMode failure_mode,
2495                                                    TRAPS) {
2496   Handle empty;
2497 
2498   assert(accessing_klass == NULL || (class_loader.is_null() && protection_domain.is_null()),
2499          "one or the other, or perhaps neither");
2500 
2501   Symbol* type = signature;
2502 
2503   // What we have here must be a valid field descriptor,
2504   // and all valid field descriptors are supported.
2505   // Produce the same java.lang.Class that reflection reports.
2506   if (type->utf8_length() == 1) {
2507 
2508     // It's a primitive.  (Void has a primitive mirror too.)
2509     char ch = type->char_at(0);
2510     assert(is_java_primitive(char2type(ch)) || ch == JVM_SIGNATURE_VOID, "");
2511     return Handle(THREAD, find_java_mirror_for_type(ch));
2512 
2513   } else if (FieldType::is_obj(type) || FieldType::is_array(type)) {
2514 
2515     // It's a reference type.
2516     if (accessing_klass != NULL) {
2517       class_loader      = Handle(THREAD, accessing_klass->class_loader());
2518       protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2519     }
2520     Klass* constant_type_klass;
2521     if (failure_mode == SignatureStream::ReturnNull) {
2522       constant_type_klass = resolve_or_null(type, class_loader, protection_domain,
2523                                             CHECK_(empty));
2524     } else {
2525       bool throw_error = (failure_mode == SignatureStream::NCDFError);
2526       constant_type_klass = resolve_or_fail(type, class_loader, protection_domain,
2527                                             throw_error, CHECK_(empty));
2528     }
2529     if (constant_type_klass == NULL) {
2530       return Handle();  // report failure this way
2531     }
2532     Handle mirror(THREAD, constant_type_klass->java_mirror());
2533 
2534     // Check accessibility, emulating ConstantPool::verify_constant_pool_resolve.
2535     if (accessing_klass != NULL) {
2536       Klass* sel_klass = constant_type_klass;
2537       bool fold_type_to_class = true;
2538       LinkResolver::check_klass_accessability(accessing_klass, sel_klass,
2539                                               fold_type_to_class, CHECK_(empty));
2540     }
2541 
2542     return mirror;
2543 
2544   }
2545 
2546   // Fall through to an error.
2547   assert(false, "unsupported mirror syntax");
2548   THROW_MSG_(vmSymbols::java_lang_InternalError(), "unsupported mirror syntax", empty);
2549 }
2550 
2551 
2552 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2553 // signature, as interpreted relative to the given class loader.
2554 // Because of class loader constraints, all method handle usage must be
2555 // consistent with this loader.
find_method_handle_type(Symbol * signature,Klass * accessing_klass,TRAPS)2556 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2557                                                  Klass* accessing_klass,
2558                                                  TRAPS) {
2559   Handle empty;
2560   vmIntrinsics::ID null_iid = vmIntrinsics::_none;  // distinct from all method handle invoker intrinsics
2561   unsigned int hash  = invoke_method_table()->compute_hash(signature, null_iid);
2562   int          index = invoke_method_table()->hash_to_index(hash);
2563   SymbolPropertyEntry* spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2564   if (spe != NULL && spe->method_type() != NULL) {
2565     assert(java_lang_invoke_MethodType::is_instance(spe->method_type()), "");
2566     return Handle(THREAD, spe->method_type());
2567   } else if (!THREAD->can_call_java()) {
2568     warning("SystemDictionary::find_method_handle_type called from compiler thread");  // FIXME
2569     return Handle();  // do not attempt from within compiler, unless it was cached
2570   }
2571 
2572   Handle class_loader, protection_domain;
2573   if (accessing_klass != NULL) {
2574     class_loader      = Handle(THREAD, accessing_klass->class_loader());
2575     protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2576   }
2577   bool can_be_cached = true;
2578   int npts = ArgumentCount(signature).size();
2579   objArrayHandle pts = oopFactory::new_objArray_handle(SystemDictionary::Class_klass(), npts, CHECK_(empty));
2580   int arg = 0;
2581   Handle rt; // the return type from the signature
2582   ResourceMark rm(THREAD);
2583   for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2584     oop mirror = NULL;
2585     if (can_be_cached) {
2586       // Use neutral class loader to lookup candidate classes to be placed in the cache.
2587       mirror = ss.as_java_mirror(Handle(), Handle(),
2588                                  SignatureStream::ReturnNull, CHECK_(empty));
2589       if (mirror == NULL || (ss.is_object() && !is_always_visible_class(mirror))) {
2590         // Fall back to accessing_klass context.
2591         can_be_cached = false;
2592       }
2593     }
2594     if (!can_be_cached) {
2595       // Resolve, throwing a real error if it doesn't work.
2596       mirror = ss.as_java_mirror(class_loader, protection_domain,
2597                                  SignatureStream::NCDFError, CHECK_(empty));
2598     }
2599     assert(mirror != NULL, "%s", ss.as_symbol()->as_C_string());
2600     if (ss.at_return_type())
2601       rt = Handle(THREAD, mirror);
2602     else
2603       pts->obj_at_put(arg++, mirror);
2604 
2605     // Check accessibility.
2606     if (!java_lang_Class::is_primitive(mirror) && accessing_klass != NULL) {
2607       Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2608       mirror = NULL;  // safety
2609       // Emulate ConstantPool::verify_constant_pool_resolve.
2610       bool fold_type_to_class = true;
2611       LinkResolver::check_klass_accessability(accessing_klass, sel_klass,
2612                                               fold_type_to_class, CHECK_(empty));
2613     }
2614   }
2615   assert(arg == npts, "");
2616 
2617   // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType
2618   JavaCallArguments args(Handle(THREAD, rt()));
2619   args.push_oop(pts);
2620   JavaValue result(T_OBJECT);
2621   JavaCalls::call_static(&result,
2622                          SystemDictionary::MethodHandleNatives_klass(),
2623                          vmSymbols::findMethodHandleType_name(),
2624                          vmSymbols::findMethodHandleType_signature(),
2625                          &args, CHECK_(empty));
2626   Handle method_type(THREAD, (oop) result.get_jobject());
2627 
2628   if (can_be_cached) {
2629     // We can cache this MethodType inside the JVM.
2630     MutexLocker ml(SystemDictionary_lock, THREAD);
2631     spe = invoke_method_table()->find_entry(index, hash, signature, null_iid);
2632     if (spe == NULL)
2633       spe = invoke_method_table()->add_entry(index, hash, signature, null_iid);
2634     if (spe->method_type() == NULL) {
2635       spe->set_method_type(method_type());
2636     }
2637   }
2638 
2639   // report back to the caller with the MethodType
2640   return method_type;
2641 }
2642 
find_field_handle_type(Symbol * signature,Klass * accessing_klass,TRAPS)2643 Handle SystemDictionary::find_field_handle_type(Symbol* signature,
2644                                                 Klass* accessing_klass,
2645                                                 TRAPS) {
2646   Handle empty;
2647   ResourceMark rm(THREAD);
2648   SignatureStream ss(signature, /*is_method=*/ false);
2649   if (!ss.is_done()) {
2650     Handle class_loader, protection_domain;
2651     if (accessing_klass != NULL) {
2652       class_loader      = Handle(THREAD, accessing_klass->class_loader());
2653       protection_domain = Handle(THREAD, accessing_klass->protection_domain());
2654     }
2655     oop mirror = ss.as_java_mirror(class_loader, protection_domain, SignatureStream::NCDFError, CHECK_(empty));
2656     ss.next();
2657     if (ss.is_done()) {
2658       return Handle(THREAD, mirror);
2659     }
2660   }
2661   return empty;
2662 }
2663 
2664 // Ask Java code to find or construct a method handle constant.
link_method_handle_constant(Klass * caller,int ref_kind,Klass * callee,Symbol * name,Symbol * signature,TRAPS)2665 Handle SystemDictionary::link_method_handle_constant(Klass* caller,
2666                                                      int ref_kind, //e.g., JVM_REF_invokeVirtual
2667                                                      Klass* callee,
2668                                                      Symbol* name,
2669                                                      Symbol* signature,
2670                                                      TRAPS) {
2671   Handle empty;
2672   if (caller == NULL) {
2673     THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2674   }
2675   Handle name_str      = java_lang_String::create_from_symbol(name,      CHECK_(empty));
2676   Handle signature_str = java_lang_String::create_from_symbol(signature, CHECK_(empty));
2677 
2678   // Put symbolic info from the MH constant into freshly created MemberName and resolve it.
2679   Handle mname = MemberName_klass()->allocate_instance_handle(CHECK_(empty));
2680   java_lang_invoke_MemberName::set_clazz(mname(), callee->java_mirror());
2681   java_lang_invoke_MemberName::set_name (mname(), name_str());
2682   java_lang_invoke_MemberName::set_type (mname(), signature_str());
2683   java_lang_invoke_MemberName::set_flags(mname(), MethodHandles::ref_kind_to_flags(ref_kind));
2684 
2685   if (ref_kind == JVM_REF_invokeVirtual &&
2686       MethodHandles::is_signature_polymorphic_public_name(callee, name)) {
2687     // Skip resolution for public signature polymorphic methods such as
2688     // j.l.i.MethodHandle.invoke()/invokeExact() and those on VarHandle
2689     // They require appendix argument which MemberName resolution doesn't handle.
2690     // There's special logic on JDK side to handle them
2691     // (see MethodHandles.linkMethodHandleConstant() and MethodHandles.findVirtualForMH()).
2692   } else {
2693     MethodHandles::resolve_MemberName(mname, caller, /*speculative_resolve*/false, CHECK_(empty));
2694   }
2695 
2696   // After method/field resolution succeeded, it's safe to resolve MH signature as well.
2697   Handle type = MethodHandles::resolve_MemberName_type(mname, caller, CHECK_(empty));
2698 
2699   // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2700   JavaCallArguments args;
2701   args.push_oop(Handle(THREAD, caller->java_mirror()));  // the referring class
2702   args.push_int(ref_kind);
2703   args.push_oop(Handle(THREAD, callee->java_mirror()));  // the target class
2704   args.push_oop(name_str);
2705   args.push_oop(type);
2706   JavaValue result(T_OBJECT);
2707   JavaCalls::call_static(&result,
2708                          SystemDictionary::MethodHandleNatives_klass(),
2709                          vmSymbols::linkMethodHandleConstant_name(),
2710                          vmSymbols::linkMethodHandleConstant_signature(),
2711                          &args, CHECK_(empty));
2712   return Handle(THREAD, (oop) result.get_jobject());
2713 }
2714 
2715 // Ask Java to run a bootstrap method, in order to create a dynamic call site
2716 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry
2717 // with linkage results being stored back into the bootstrap specifier.
invoke_bootstrap_method(BootstrapInfo & bootstrap_specifier,TRAPS)2718 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) {
2719   // Resolve the bootstrap specifier, its name, type, and static arguments
2720   bootstrap_specifier.resolve_bsm(CHECK);
2721 
2722   // This should not happen.  JDK code should take care of that.
2723   if (bootstrap_specifier.caller() == NULL || bootstrap_specifier.type_arg().is_null()) {
2724     THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument");
2725   }
2726 
2727   bool is_indy = bootstrap_specifier.is_method_call();
2728   objArrayHandle appendix_box;
2729   if (is_indy) {
2730     // Some method calls may require an appendix argument.  Arrange to receive it.
2731     appendix_box = oopFactory::new_objArray_handle(SystemDictionary::Object_klass(), 1, CHECK);
2732     assert(appendix_box->obj_at(0) == NULL, "");
2733   }
2734 
2735   // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, condy_index, bsm, type, info)
2736   //       indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, indy_index, bsm, name, mtype, info, &appendix)
2737   JavaCallArguments args;
2738   args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror()));
2739   args.push_int(bootstrap_specifier.bss_index());
2740   args.push_oop(bootstrap_specifier.bsm());
2741   args.push_oop(bootstrap_specifier.name_arg());
2742   args.push_oop(bootstrap_specifier.type_arg());
2743   args.push_oop(bootstrap_specifier.arg_values());
2744   if (is_indy) {
2745     args.push_oop(appendix_box);
2746   }
2747   JavaValue result(T_OBJECT);
2748   JavaCalls::call_static(&result,
2749                          SystemDictionary::MethodHandleNatives_klass(),
2750                          is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(),
2751                          is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(),
2752                          &args, CHECK);
2753 
2754   Handle value(THREAD, (oop) result.get_jobject());
2755   if (is_indy) {
2756     Handle appendix;
2757     Method* method = unpack_method_and_appendix(value,
2758                                                 bootstrap_specifier.caller(),
2759                                                 appendix_box,
2760                                                 &appendix, CHECK);
2761     methodHandle mh(THREAD, method);
2762     bootstrap_specifier.set_resolved_method(mh, appendix);
2763   } else {
2764     bootstrap_specifier.set_resolved_value(value);
2765   }
2766 
2767   // sanity check
2768   assert(bootstrap_specifier.is_resolved() ||
2769          (bootstrap_specifier.is_method_call() &&
2770           bootstrap_specifier.resolved_method().not_null()), "bootstrap method call failed");
2771 }
2772 
2773 // Protection domain cache table handling
2774 
cache_get(Handle protection_domain)2775 ProtectionDomainCacheEntry* SystemDictionary::cache_get(Handle protection_domain) {
2776   return _pd_cache_table->get(protection_domain);
2777 }
2778 
2779 // ----------------------------------------------------------------------------
2780 
print_on(outputStream * st)2781 void SystemDictionary::print_on(outputStream *st) {
2782   CDS_ONLY(SystemDictionaryShared::print_on(st));
2783   GCMutexLocker mu(SystemDictionary_lock);
2784 
2785   ClassLoaderDataGraph::print_dictionary(st);
2786 
2787   // Placeholders
2788   placeholders()->print_on(st);
2789   st->cr();
2790 
2791   // loader constraints - print under SD_lock
2792   constraints()->print_on(st);
2793   st->cr();
2794 
2795   _pd_cache_table->print_on(st);
2796   st->cr();
2797 }
2798 
print()2799 void SystemDictionary::print() { print_on(tty); }
2800 
verify()2801 void SystemDictionary::verify() {
2802   guarantee(constraints() != NULL,
2803             "Verify of loader constraints failed");
2804   guarantee(placeholders()->number_of_entries() >= 0,
2805             "Verify of placeholders failed");
2806 
2807   GCMutexLocker mu(SystemDictionary_lock);
2808 
2809   // Verify dictionary
2810   ClassLoaderDataGraph::verify_dictionary();
2811 
2812   placeholders()->verify();
2813 
2814   // Verify constraint table
2815   guarantee(constraints() != NULL, "Verify of loader constraints failed");
2816   constraints()->verify(placeholders());
2817 
2818   _pd_cache_table->verify();
2819 }
2820 
dump(outputStream * st,bool verbose)2821 void SystemDictionary::dump(outputStream *st, bool verbose) {
2822   assert_locked_or_safepoint(SystemDictionary_lock);
2823   if (verbose) {
2824     print_on(st);
2825   } else {
2826     CDS_ONLY(SystemDictionaryShared::print_table_statistics(st));
2827     ClassLoaderDataGraph::print_table_statistics(st);
2828     placeholders()->print_table_statistics(st, "Placeholder Table");
2829     constraints()->print_table_statistics(st, "LoaderConstraints Table");
2830     pd_cache_table()->print_table_statistics(st, "ProtectionDomainCache Table");
2831   }
2832 }
2833 
placeholders_statistics()2834 TableStatistics SystemDictionary::placeholders_statistics() {
2835   MutexLocker ml(SystemDictionary_lock);
2836   return placeholders()->statistics_calculate();
2837 }
2838 
loader_constraints_statistics()2839 TableStatistics SystemDictionary::loader_constraints_statistics() {
2840   MutexLocker ml(SystemDictionary_lock);
2841   return constraints()->statistics_calculate();
2842 }
2843 
protection_domain_cache_statistics()2844 TableStatistics SystemDictionary::protection_domain_cache_statistics() {
2845   MutexLocker ml(SystemDictionary_lock);
2846   return pd_cache_table()->statistics_calculate();
2847 }
2848 
2849 // Utility for dumping dictionaries.
SystemDictionaryDCmd(outputStream * output,bool heap)2850 SystemDictionaryDCmd::SystemDictionaryDCmd(outputStream* output, bool heap) :
2851                                  DCmdWithParser(output, heap),
2852   _verbose("-verbose", "Dump the content of each dictionary entry for all class loaders",
2853            "BOOLEAN", false, "false") {
2854   _dcmdparser.add_dcmd_option(&_verbose);
2855 }
2856 
execute(DCmdSource source,TRAPS)2857 void SystemDictionaryDCmd::execute(DCmdSource source, TRAPS) {
2858   VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpSysDict,
2859                          _verbose.value());
2860   VMThread::execute(&dumper);
2861 }
2862 
num_arguments()2863 int SystemDictionaryDCmd::num_arguments() {
2864   ResourceMark rm;
2865   SystemDictionaryDCmd* dcmd = new SystemDictionaryDCmd(NULL, false);
2866   if (dcmd != NULL) {
2867     DCmdMark mark(dcmd);
2868     return dcmd->_dcmdparser.num_arguments();
2869   } else {
2870     return 0;
2871   }
2872 }
2873