1 /*
2 * Copyright (c) 1997, 2025, 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 "cds/aotClassLocation.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "cds/heapShared.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/classLoadInfo.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/resolutionErrors.hpp"
41 #include "classfile/stringTable.hpp"
42 #include "classfile/symbolTable.hpp"
43 #include "classfile/systemDictionary.hpp"
44 #include "classfile/vmClasses.hpp"
45 #include "classfile/vmSymbols.hpp"
46 #include "gc/shared/gcTraceTime.inline.hpp"
47 #include "interpreter/bootstrapInfo.hpp"
48 #include "jfr/jfrEvents.hpp"
49 #include "jvm.h"
50 #include "logging/log.hpp"
51 #include "logging/logStream.hpp"
52 #include "memory/metaspaceClosure.hpp"
53 #include "memory/oopFactory.hpp"
54 #include "memory/resourceArea.hpp"
55 #include "memory/universe.hpp"
56 #include "oops/access.inline.hpp"
57 #include "oops/instanceKlass.hpp"
58 #include "oops/klass.inline.hpp"
59 #include "oops/method.inline.hpp"
60 #include "oops/objArrayKlass.hpp"
61 #include "oops/objArrayOop.inline.hpp"
62 #include "oops/oop.inline.hpp"
63 #include "oops/oopHandle.inline.hpp"
64 #include "oops/symbol.hpp"
65 #include "oops/typeArrayKlass.hpp"
66 #include "prims/jvmtiExport.hpp"
67 #include "prims/methodHandles.hpp"
68 #include "runtime/arguments.hpp"
69 #include "runtime/atomicAccess.hpp"
70 #include "runtime/handles.inline.hpp"
71 #include "runtime/java.hpp"
72 #include "runtime/javaCalls.hpp"
73 #include "runtime/mutexLocker.hpp"
74 #include "runtime/sharedRuntime.hpp"
75 #include "runtime/signature.hpp"
76 #include "runtime/synchronizer.hpp"
77 #include "services/classLoadingService.hpp"
78 #include "services/diagnosticCommand.hpp"
79 #include "services/finalizerService.hpp"
80 #include "services/threadService.hpp"
81 #include "utilities/growableArray.hpp"
82 #include "utilities/macros.hpp"
83 #include "utilities/utf8.hpp"
84 #if INCLUDE_CDS
85 #include "classfile/systemDictionaryShared.hpp"
86 #endif
87 #if INCLUDE_JFR
88 #include "jfr/jfr.hpp"
89 #endif
90
91 class InvokeMethodKey : public StackObj {
92 private:
93 Symbol* _symbol;
94 intptr_t _iid;
95
96 public:
97 InvokeMethodKey(Symbol* symbol, intptr_t iid) :
98 _symbol(symbol),
99 _iid(iid) {}
100
101 static bool key_comparison(InvokeMethodKey const &k1, InvokeMethodKey const &k2){
102 return k1._symbol == k2._symbol && k1._iid == k2._iid;
103 }
104
105 static unsigned int compute_hash(const InvokeMethodKey &k) {
106 Symbol* sym = k._symbol;
107 intptr_t iid = k._iid;
108 unsigned int hash = (unsigned int) sym -> identity_hash();
109 return (unsigned int) (hash ^ iid);
110 }
111
112 };
113
114 using InvokeMethodIntrinsicTable = HashTable<InvokeMethodKey, Method*, 139, AnyObj::C_HEAP, mtClass,
115 InvokeMethodKey::compute_hash, InvokeMethodKey::key_comparison>;
116 static InvokeMethodIntrinsicTable* _invoke_method_intrinsic_table;
117 using InvokeMethodTypeTable = HashTable<SymbolHandle, OopHandle, 139, AnyObj::C_HEAP, mtClass, SymbolHandle::compute_hash>;
118 static InvokeMethodTypeTable* _invoke_method_type_table;
119
120 OopHandle SystemDictionary::_java_system_loader;
121 OopHandle SystemDictionary::_java_platform_loader;
122
123 // ----------------------------------------------------------------------------
124 // Java-level SystemLoader and PlatformLoader
125 oop SystemDictionary::java_system_loader() {
126 return _java_system_loader.resolve();
127 }
128
129 oop SystemDictionary::java_platform_loader() {
130 return _java_platform_loader.resolve();
131 }
132
133 void SystemDictionary::compute_java_loaders(TRAPS) {
134 if (_java_platform_loader.is_empty()) {
135 oop platform_loader = get_platform_class_loader_impl(CHECK);
136 _java_platform_loader = OopHandle(Universe::vm_global(), platform_loader);
137 } else {
138 // It must have been restored from the archived module graph
139 assert(CDSConfig::is_using_archive(), "must be");
140 assert(CDSConfig::is_using_full_module_graph(), "must be");
141 DEBUG_ONLY(
142 oop platform_loader = get_platform_class_loader_impl(CHECK);
143 assert(_java_platform_loader.resolve() == platform_loader, "must be");
144 )
145 }
146
147 if (_java_system_loader.is_empty()) {
148 oop system_loader = get_system_class_loader_impl(CHECK);
149 _java_system_loader = OopHandle(Universe::vm_global(), system_loader);
150 } else {
151 // It must have been restored from the archived module graph
152 assert(CDSConfig::is_using_archive(), "must be");
153 assert(CDSConfig::is_using_full_module_graph(), "must be");
154 DEBUG_ONLY(
155 oop system_loader = get_system_class_loader_impl(CHECK);
156 assert(_java_system_loader.resolve() == system_loader, "must be");
157 )
158 }
159 }
160
161 oop SystemDictionary::get_system_class_loader_impl(TRAPS) {
162 JavaValue result(T_OBJECT);
163 InstanceKlass* class_loader_klass = vmClasses::ClassLoader_klass();
164 JavaCalls::call_static(&result,
165 class_loader_klass,
166 vmSymbols::getSystemClassLoader_name(),
167 vmSymbols::void_classloader_signature(),
168 CHECK_NULL);
169 return result.get_oop();
170 }
171
172 oop SystemDictionary::get_platform_class_loader_impl(TRAPS) {
173 JavaValue result(T_OBJECT);
174 InstanceKlass* class_loader_klass = vmClasses::ClassLoader_klass();
175 JavaCalls::call_static(&result,
176 class_loader_klass,
177 vmSymbols::getPlatformClassLoader_name(),
178 vmSymbols::void_classloader_signature(),
179 CHECK_NULL);
180 return result.get_oop();
181 }
182
183 // Helper function
184 inline ClassLoaderData* class_loader_data(Handle class_loader) {
185 return ClassLoaderData::class_loader_data(class_loader());
186 }
187
188 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, bool create_mirror_cld) {
189 if (create_mirror_cld) {
190 // Add a new class loader data to the graph.
191 return ClassLoaderDataGraph::add(class_loader, true);
192 } else {
193 return (class_loader() == nullptr) ? ClassLoaderData::the_null_class_loader_data() :
194 ClassLoaderDataGraph::find_or_create(class_loader);
195 }
196 }
197
198 void SystemDictionary::set_system_loader(ClassLoaderData *cld) {
199 if (_java_system_loader.is_empty()) {
200 _java_system_loader = cld->class_loader_handle();
201 } else {
202 assert(_java_system_loader.resolve() == cld->class_loader(), "sanity");
203 }
204 }
205
206 void SystemDictionary::set_platform_loader(ClassLoaderData *cld) {
207 if (_java_platform_loader.is_empty()) {
208 _java_platform_loader = cld->class_loader_handle();
209 } else {
210 assert(_java_platform_loader.resolve() == cld->class_loader(), "sanity");
211 }
212 }
213
214 // ----------------------------------------------------------------------------
215 // Parallel class loading check
216
217 static bool is_parallelCapable(Handle class_loader) {
218 if (class_loader.is_null()) return true;
219 return java_lang_ClassLoader::parallelCapable(class_loader());
220 }
221 // ----------------------------------------------------------------------------
222 // ParallelDefineClass flag does not apply to bootclass loader
223 static bool is_parallelDefine(Handle class_loader) {
224 if (class_loader.is_null()) return false;
225 if (AllowParallelDefineClass && java_lang_ClassLoader::parallelCapable(class_loader())) {
226 return true;
227 }
228 return false;
229 }
230
231 // Returns true if the passed class loader is the builtin application class loader
232 // or a custom system class loader. A customer system class loader can be
233 // specified via -Djava.system.class.loader.
234 bool SystemDictionary::is_system_class_loader(oop class_loader) {
235 if (class_loader == nullptr) {
236 return false;
237 }
238 return (class_loader->klass() == vmClasses::jdk_internal_loader_ClassLoaders_AppClassLoader_klass() ||
239 class_loader == _java_system_loader.peek());
240 }
241
242 // Returns true if the passed class loader is the platform class loader.
243 bool SystemDictionary::is_platform_class_loader(oop class_loader) {
244 if (class_loader == nullptr) {
245 return false;
246 }
247 return (class_loader->klass() == vmClasses::jdk_internal_loader_ClassLoaders_PlatformClassLoader_klass());
248 }
249
250 Handle SystemDictionary::get_loader_lock_or_null(Handle class_loader) {
251 // If class_loader is null or parallelCapable, the JVM doesn't acquire a lock while loading.
252 if (is_parallelCapable(class_loader)) {
253 return Handle();
254 } else {
255 return class_loader;
256 }
257 }
258
259 // ----------------------------------------------------------------------------
260 // Resolving of classes
261
262 Symbol* SystemDictionary::class_name_symbol(const char* name, Symbol* exception, TRAPS) {
263 if (name == nullptr) {
264 THROW_MSG_NULL(exception, "No class name given");
265 }
266 size_t name_len = strlen(name);
267 if (name_len > static_cast<size_t>(Symbol::max_length())) {
268 // It's impossible to create this class; the name cannot fit
269 // into the constant pool. If necessary report an abridged name
270 // in the exception message.
271 if (name_len > static_cast<size_t>(MaxStringPrintSize)) {
272 Exceptions::fthrow(THREAD_AND_LOCATION, exception,
273 "Class name exceeds maximum length of %d: %.*s ... (%zu characters omitted) ... %.*s",
274 Symbol::max_length(),
275 MaxStringPrintSize / 2,
276 name,
277 name_len - 2 * (MaxStringPrintSize / 2), // allows for odd value
278 MaxStringPrintSize / 2,
279 name + name_len - MaxStringPrintSize / 2);
280 }
281 else {
282 Exceptions::fthrow(THREAD_AND_LOCATION, exception,
283 "Class name exceeds maximum length of %d: %s",
284 Symbol::max_length(),
285 name);
286 }
287 return nullptr;
288 }
289 // Callers should ensure that the name is never an illegal UTF8 string.
290 assert(UTF8::is_legal_utf8((const unsigned char*)name, name_len, false),
291 "Class name is not a valid utf8 string.");
292
293 // Make a new symbol for the class name.
294 return SymbolTable::new_symbol(name);
295 }
296
297 #ifdef ASSERT
298 // Used to verify that class loading succeeded in adding k to the dictionary.
299 static void verify_dictionary_entry(Symbol* class_name, InstanceKlass* k) {
300 MutexLocker mu(SystemDictionary_lock);
301 ClassLoaderData* loader_data = k->class_loader_data();
302 Dictionary* dictionary = loader_data->dictionary();
303 assert(class_name == k->name(), "Must be the same");
304 InstanceKlass* kk = dictionary->find_class(JavaThread::current(), class_name);
305 assert(kk == k, "should be present in dictionary");
306 }
307 #endif
308
309 static void handle_resolution_exception(Symbol* class_name, bool throw_error, TRAPS) {
310 if (HAS_PENDING_EXCEPTION) {
311 // If we have a pending exception we forward it to the caller, unless throw_error is true,
312 // in which case we have to check whether the pending exception is a ClassNotFoundException,
313 // and convert it to a NoClassDefFoundError and chain the original ClassNotFoundException.
314 if (throw_error && PENDING_EXCEPTION->is_a(vmClasses::ClassNotFoundException_klass())) {
315 ResourceMark rm(THREAD);
316 Handle e(THREAD, PENDING_EXCEPTION);
317 CLEAR_PENDING_EXCEPTION;
318 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string(), e);
319 } else {
320 return; // the caller will throw the incoming exception
321 }
322 }
323 // If the class is not found, ie, caller has checked that klass is null, throw the appropriate
324 // error or exception depending on the value of throw_error.
325 ResourceMark rm(THREAD);
326 if (throw_error) {
327 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), class_name->as_C_string());
328 } else {
329 THROW_MSG(vmSymbols::java_lang_ClassNotFoundException(), class_name->as_C_string());
330 }
331 }
332
333 // Forwards to resolve_or_null
334
335 Klass* SystemDictionary::resolve_or_fail(Symbol* class_name, Handle class_loader,
336 bool throw_error, TRAPS) {
337 Klass* klass = resolve_or_null(class_name, class_loader, THREAD);
338 // Check for pending exception or null klass, and throw exception
339 if (HAS_PENDING_EXCEPTION || klass == nullptr) {
340 handle_resolution_exception(class_name, throw_error, CHECK_NULL);
341 }
342 return klass;
343 }
344
345 // Forwards to resolve_array_class_or_null or resolve_instance_class_or_null
346
347 Klass* SystemDictionary::resolve_or_null(Symbol* class_name, Handle class_loader, TRAPS) {
348 if (Signature::is_array(class_name)) {
349 return resolve_array_class_or_null(class_name, class_loader, THREAD);
350 } else {
351 assert(class_name != nullptr && !Signature::is_array(class_name), "must be");
352 if (Signature::has_envelope(class_name)) {
353 ResourceMark rm(THREAD);
354 // Ignore wrapping L and ;.
355 TempNewSymbol name = SymbolTable::new_symbol(class_name->as_C_string() + 1,
356 class_name->utf8_length() - 2);
357 return resolve_instance_class_or_null(name, class_loader, THREAD);
358 } else {
359 return resolve_instance_class_or_null(class_name, class_loader, THREAD);
360 }
361 }
362 }
363
364 // Forwards to resolve_instance_class_or_null
365
366 Klass* SystemDictionary::resolve_array_class_or_null(Symbol* class_name,
367 Handle class_loader,
368 TRAPS) {
369 assert(Signature::is_array(class_name), "must be array");
370 ResourceMark rm(THREAD);
371 SignatureStream ss(class_name, false);
372 int ndims = ss.skip_array_prefix(); // skip all '['s
373 Klass* k = nullptr;
374 BasicType t = ss.type();
375 if (ss.has_envelope()) {
376 Symbol* obj_class = ss.as_symbol();
377 k = SystemDictionary::resolve_instance_class_or_null(obj_class,
378 class_loader,
379 CHECK_NULL);
380 if (k != nullptr) {
381 k = k->array_klass(ndims, CHECK_NULL);
382 }
383 } else {
384 k = Universe::typeArrayKlass(t);
385 k = k->array_klass(ndims, CHECK_NULL);
386 }
387 return k;
388 }
389
390 static inline void log_circularity_error(Symbol* name, PlaceholderEntry* probe) {
391 LogTarget(Debug, class, load, placeholders) lt;
392 if (lt.is_enabled()) {
393 ResourceMark rm;
394 LogStream ls(lt);
395 ls.print("ClassCircularityError detected for placeholder entry %s", name->as_C_string());
396 probe->print_on(&ls);
397 ls.cr();
398 }
399 }
400
401 // Must be called for any superclass or superinterface resolution
402 // during class definition to allow class circularity checking
403 // superinterface callers:
404 // parse_interfaces - from defineClass
405 // superclass callers:
406 // ClassFileParser - from defineClass
407 // load_shared_class - while loading a class from shared archive
408 // resolve_instance_class_or_null:
409 // via: handle_parallel_super_load
410 // when resolving a class that has an existing placeholder with
411 // a saved superclass [i.e. a defineClass is currently in progress]
412 // If another thread is trying to resolve the class, it must do
413 // superclass checks on its own thread to catch class circularity and
414 // to avoid deadlock.
415 //
416 // resolve_with_circularity_detection adds a DETECT_CIRCULARITY placeholder to the placeholder table before calling
417 // resolve_instance_class_or_null. ClassCircularityError is detected when a DETECT_CIRCULARITY or LOAD_INSTANCE
418 // placeholder for the same thread, class, classloader is found.
419 // This can be seen with logging option: -Xlog:class+load+placeholders=debug.
420 //
421 InstanceKlass* SystemDictionary::resolve_with_circularity_detection(Symbol* class_name,
422 Symbol* next_name,
423 Handle class_loader,
424 bool is_superclass,
425 TRAPS) {
426
427 assert(next_name != nullptr, "null superclass for resolving");
428 assert(!Signature::is_array(next_name), "invalid superclass name");
429
430 ClassLoaderData* loader_data = class_loader_data(class_loader);
431
432 if (is_superclass) {
433 InstanceKlass* klassk = loader_data->dictionary()->find_class(THREAD, class_name);
434 if (klassk != nullptr) {
435 // We can come here for two reasons:
436 // (a) RedefineClasses -- the class is already loaded
437 // (b) Rarely, the class might have been loaded by a parallel thread
438 // We can do a quick check against the already assigned superclass's name and loader.
439 InstanceKlass* superk = klassk->super();
440 if (superk != nullptr &&
441 superk->name() == next_name &&
442 superk->class_loader() == class_loader()) {
443 return superk;
444 }
445 }
446 }
447
448 // can't throw error holding a lock
449 bool throw_circularity_error = false;
450 {
451 MutexLocker mu(THREAD, SystemDictionary_lock);
452
453 // Must check ClassCircularity before resolving next_name (superclass or interface).
454 PlaceholderEntry* probe = PlaceholderTable::get_entry(class_name, loader_data);
455 if (probe != nullptr && probe->check_seen_thread(THREAD, PlaceholderTable::DETECT_CIRCULARITY)) {
456 log_circularity_error(class_name, probe);
457 throw_circularity_error = true;
458 }
459
460 // Make sure there's a placeholder for the class_name before resolving.
461 // This is used as a claim that this thread is currently loading superclass/classloader
462 // and for ClassCircularity checks.
463 if (!throw_circularity_error) {
464 // Be careful not to exit resolve_with_circularity_detection without removing this placeholder.
465 PlaceholderEntry* newprobe = PlaceholderTable::find_and_add(class_name,
466 loader_data,
467 PlaceholderTable::DETECT_CIRCULARITY,
468 next_name, THREAD);
469 }
470 }
471
472 if (throw_circularity_error) {
473 ResourceMark rm(THREAD);
474 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), class_name->as_C_string());
475 }
476
477 // Resolve the superclass or superinterface, check results on return
478 InstanceKlass* superk =
479 SystemDictionary::resolve_instance_class_or_null(next_name,
480 class_loader,
481 THREAD);
482
483 // Clean up placeholder entry.
484 {
485 MutexLocker mu(THREAD, SystemDictionary_lock);
486 PlaceholderTable::find_and_remove(class_name, loader_data, PlaceholderTable::DETECT_CIRCULARITY, THREAD);
487 SystemDictionary_lock->notify_all();
488 }
489
490 // Check for pending exception or null superk, and throw exception
491 if (HAS_PENDING_EXCEPTION || superk == nullptr) {
492 handle_resolution_exception(next_name, true, CHECK_NULL);
493 }
494
495 return superk;
496 }
497
498 // If the class in is in the placeholder table, class loading is in progress.
499 // For cases where the application changes threads to load classes, it
500 // is critical to ClassCircularity detection that we try loading
501 // the superclass on the new thread internally, so we do parallel
502 // superclass loading here. This avoids deadlock for ClassCircularity
503 // detection for parallelCapable class loaders that lock on a per-class lock.
504 static void handle_parallel_super_load(Symbol* name,
505 Symbol* superclassname,
506 Handle class_loader,
507 TRAPS) {
508
509 // The result superk is not used; resolve_with_circularity_detection is called for circularity check only.
510 // This passes false to is_superclass to skip doing the unlikely optimization.
511 Klass* superk = SystemDictionary::resolve_with_circularity_detection(name,
512 superclassname,
513 class_loader,
514 false,
515 CHECK);
516 }
517
518 // Bootstrap and non-parallel capable class loaders use the LOAD_INSTANCE placeholder to
519 // wait for parallel class loading and/or to check for circularity error for Xcomp when loading.
520 static bool needs_load_placeholder(Handle class_loader) {
521 return class_loader.is_null() || !is_parallelCapable(class_loader);
522 }
523
524 // Check for other threads loading this class either to throw CCE or wait in the case of the boot loader.
525 static InstanceKlass* handle_parallel_loading(JavaThread* current,
526 Symbol* name,
527 ClassLoaderData* loader_data,
528 bool must_wait_for_class_loading,
529 bool* throw_circularity_error) {
530 PlaceholderEntry* oldprobe = PlaceholderTable::get_entry(name, loader_data);
531 if (oldprobe != nullptr) {
532 // -Xcomp calls load_signature_classes which might result in loading
533 // a class that's already in the process of loading, so we detect CCE here also.
534 // Only need check_seen_thread once, not on each loop
535 if (oldprobe->check_seen_thread(current, PlaceholderTable::LOAD_INSTANCE)) {
536 log_circularity_error(name, oldprobe);
537 *throw_circularity_error = true;
538 return nullptr;
539 } else if (must_wait_for_class_loading) {
540 // Wait until the first thread has finished loading this class. Also wait until all the
541 // threads trying to load its superclass have removed their placeholders.
542 while (oldprobe != nullptr &&
543 (oldprobe->instance_load_in_progress() || oldprobe->circularity_detection_in_progress())) {
544
545 // LOAD_INSTANCE placeholders are used to implement parallel capable class loading
546 // for the bootclass loader.
547 SystemDictionary_lock->wait();
548
549 // Check if classloading completed while we were waiting
550 InstanceKlass* check = loader_data->dictionary()->find_class(current, name);
551 if (check != nullptr) {
552 // Klass is already loaded, so just return it
553 return check;
554 }
555 // check if other thread failed to load and cleaned up
556 oldprobe = PlaceholderTable::get_entry(name, loader_data);
557 }
558 }
559 }
560 return nullptr;
561 }
562
563 // SystemDictionary::resolve_instance_class_or_null is the main function for class name resolution.
564 // After checking if the InstanceKlass already exists, it checks for ClassCircularityError and
565 // whether the thread must wait for loading in parallel. It eventually calls load_instance_class,
566 // which will load the class via the bootstrap loader or call ClassLoader.loadClass().
567 // This can return null, an exception or an InstanceKlass.
568 InstanceKlass* SystemDictionary::resolve_instance_class_or_null(Symbol* name,
569 Handle class_loader,
570 TRAPS) {
571 // name must be in the form of "java/lang/Object" -- cannot be "Ljava/lang/Object;"
572 DEBUG_ONLY(ResourceMark rm(THREAD));
573 assert(name != nullptr && !Signature::is_array(name) &&
574 !Signature::has_envelope(name), "invalid class name: %s", name == nullptr ? "nullptr" : name->as_C_string());
575
576 EventClassLoad class_load_event;
577
578 HandleMark hm(THREAD);
579
580 ClassLoaderData* loader_data = register_loader(class_loader);
581 Dictionary* dictionary = loader_data->dictionary();
582
583 // Do lookup to see if class already exists.
584 InstanceKlass* probe = dictionary->find_class(THREAD, name);
585 if (probe != nullptr) return probe;
586
587 // Non-bootstrap class loaders will call out to class loader and
588 // define via jvm/jni_DefineClass which will acquire the
589 // class loader object lock to protect against multiple threads
590 // defining the class in parallel by accident.
591 // This lock must be acquired here so the waiter will find
592 // any successful result in the SystemDictionary and not attempt
593 // the define.
594 // ParallelCapable class loaders and the bootstrap classloader
595 // do not acquire lock here.
596 Handle lockObject = get_loader_lock_or_null(class_loader);
597 ObjectLocker ol(lockObject, THREAD);
598
599 bool circularity_detection_in_progress = false;
600 InstanceKlass* loaded_class = nullptr;
601 SymbolHandle superclassname; // Keep alive while loading in parallel thread.
602
603 guarantee(THREAD->can_call_java(),
604 "can not load classes with compiler thread: class=%s, classloader=%s",
605 name->as_C_string(),
606 class_loader.is_null() ? "null" : class_loader->klass()->name()->as_C_string());
607
608 // Check again (after locking) if the class already exists in SystemDictionary
609 {
610 MutexLocker mu(THREAD, SystemDictionary_lock);
611 InstanceKlass* check = dictionary->find_class(THREAD, name);
612 if (check != nullptr) {
613 // InstanceKlass is already loaded, but we still need to check protection domain below.
614 loaded_class = check;
615 } else {
616 PlaceholderEntry* placeholder = PlaceholderTable::get_entry(name, loader_data);
617 if (placeholder != nullptr && placeholder->circularity_detection_in_progress()) {
618 circularity_detection_in_progress = true;
619 superclassname = placeholder->next_klass_name();
620 assert(superclassname != nullptr, "superclass has to have a name");
621 }
622 }
623 }
624
625 // If the class is in the placeholder table with super_class set,
626 // handle superclass loading in progress.
627 if (circularity_detection_in_progress) {
628 handle_parallel_super_load(name, superclassname,
629 class_loader,
630 CHECK_NULL);
631 }
632
633 bool throw_circularity_error = false;
634 if (loaded_class == nullptr) {
635 bool load_placeholder_added = false;
636
637 // Add placeholder entry to record loading instance class
638 // case 1. Bootstrap classloader
639 // This classloader supports parallelism at the classloader level
640 // but only allows a single thread to load a class/classloader pair.
641 // The LOAD_INSTANCE placeholder is the mechanism for mutual exclusion.
642 // case 2. parallelCapable user level classloaders
643 // These class loaders lock a per-class object lock when ClassLoader.loadClass()
644 // is called. A LOAD_INSTANCE placeholder isn't used for mutual exclusion.
645 // case 3. traditional classloaders that rely on the classloader object lock
646 // There should be no need for need for LOAD_INSTANCE for mutual exclusion,
647 // except the LOAD_INSTANCE placeholder is used to detect CCE for -Xcomp.
648 // TODO: should also be used to detect CCE for parallel capable class loaders but it's not.
649 {
650 MutexLocker mu(THREAD, SystemDictionary_lock);
651 if (needs_load_placeholder(class_loader)) {
652 loaded_class = handle_parallel_loading(THREAD,
653 name,
654 loader_data,
655 class_loader.is_null(),
656 &throw_circularity_error);
657 }
658
659 // Recheck if the class has been loaded for all class loader cases and
660 // add a LOAD_INSTANCE placeholder while holding the SystemDictionary_lock.
661 if (!throw_circularity_error && loaded_class == nullptr) {
662 InstanceKlass* check = dictionary->find_class(THREAD, name);
663 if (check != nullptr) {
664 loaded_class = check;
665 } else if (needs_load_placeholder(class_loader)) {
666 // Add the LOAD_INSTANCE token. Threads will wait on loading to complete for this thread.
667 PlaceholderEntry* newprobe = PlaceholderTable::find_and_add(name, loader_data,
668 PlaceholderTable::LOAD_INSTANCE,
669 nullptr,
670 THREAD);
671 load_placeholder_added = true;
672 }
673 }
674 }
675
676 // Must throw error outside of owning lock
677 if (throw_circularity_error) {
678 assert(!HAS_PENDING_EXCEPTION && !load_placeholder_added, "circularity error cleanup");
679 ResourceMark rm(THREAD);
680 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), name->as_C_string());
681 }
682
683 // Be careful when modifying this code: once you have run
684 // PlaceholderTable::find_and_add(PlaceholderTable::LOAD_INSTANCE),
685 // you need to find_and_remove it before returning.
686 // So be careful to not exit with a CHECK_ macro between these calls.
687
688 if (loaded_class == nullptr) {
689 // Do actual loading
690 loaded_class = load_instance_class(name, class_loader, THREAD);
691 }
692
693 if (load_placeholder_added) {
694 // clean up placeholder entries for LOAD_INSTANCE success or error
695 // This brackets the SystemDictionary updates for both defining
696 // and initiating loaders
697 MutexLocker mu(THREAD, SystemDictionary_lock);
698 PlaceholderTable::find_and_remove(name, loader_data, PlaceholderTable::LOAD_INSTANCE, THREAD);
699 SystemDictionary_lock->notify_all();
700 }
701 }
702
703 if (HAS_PENDING_EXCEPTION || loaded_class == nullptr) {
704 return nullptr;
705 }
706
707 if (class_load_event.should_commit()) {
708 JFR_ONLY(post_class_load_event(&class_load_event, loaded_class, loader_data);)
709 }
710
711 // Make sure we have the right class in the dictionary
712 DEBUG_ONLY(verify_dictionary_entry(name, loaded_class));
713
714 return loaded_class;
715 }
716
717
718 // This routine does not lock the system dictionary.
719 //
720 // Since readers don't hold a lock, we must make sure that system
721 // dictionary entries are added to in a safe way (all links must
722 // be updated in an MT-safe manner). All entries are removed during class
723 // unloading, when this class loader is no longer referenced.
724 //
725 // Callers should be aware that an entry could be added just after
726 // Dictionary is read here, so the caller will not see
727 // the new entry.
728
729 InstanceKlass* SystemDictionary::find_instance_klass(Thread* current,
730 Symbol* class_name,
731 Handle class_loader) {
732
733 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
734 if (loader_data == nullptr) {
735 // If the ClassLoaderData has not been setup,
736 // then the class loader has no entries in the dictionary.
737 return nullptr;
738 }
739
740 Dictionary* dictionary = loader_data->dictionary();
741 return dictionary->find_class(current, class_name);
742 }
743
744 // Look for a loaded instance or array klass by name. Do not do any loading.
745 // return null in case of error.
746 Klass* SystemDictionary::find_instance_or_array_klass(Thread* current,
747 Symbol* class_name,
748 Handle class_loader) {
749 Klass* k = nullptr;
750 assert(class_name != nullptr, "class name must be non nullptr");
751
752 if (Signature::is_array(class_name)) {
753 // The name refers to an array. Parse the name.
754 // dimension and object_key in FieldArrayInfo are assigned as a
755 // side-effect of this call
756 SignatureStream ss(class_name, false);
757 int ndims = ss.skip_array_prefix(); // skip all '['s
758 BasicType t = ss.type();
759 if (t != T_OBJECT) {
760 k = Universe::typeArrayKlass(t);
761 } else {
762 k = SystemDictionary::find_instance_klass(current, ss.as_symbol(), class_loader);
763 }
764 if (k != nullptr) {
765 k = k->array_klass_or_null(ndims);
766 }
767 } else {
768 k = find_instance_klass(current, class_name, class_loader);
769 }
770 return k;
771 }
772
773 // Note: this method is much like resolve_class_from_stream, but
774 // does not publish the classes in the SystemDictionary.
775 // Handles Lookup.defineClass hidden.
776 InstanceKlass* SystemDictionary::resolve_hidden_class_from_stream(
777 ClassFileStream* st,
778 Symbol* class_name,
779 Handle class_loader,
780 const ClassLoadInfo& cl_info,
781 TRAPS) {
782
783 EventClassLoad class_load_event;
784 ClassLoaderData* loader_data;
785
786 // - for hidden classes that are not strong: create a new CLD that has a class holder and
787 // whose loader is the Lookup class's loader.
788 // - for hidden class: add the class to the Lookup class's loader's CLD.
789 assert (cl_info.is_hidden(), "only used for hidden classes");
790 bool create_mirror_cld = !cl_info.is_strong_hidden();
791 loader_data = register_loader(class_loader, create_mirror_cld);
792
793 assert(st != nullptr, "invariant");
794
795 // Parse stream and create a klass.
796 InstanceKlass* k = KlassFactory::create_from_stream(st,
797 class_name,
798 loader_data,
799 cl_info,
800 CHECK_NULL);
801 assert(k != nullptr, "no klass created");
802
803 // Hidden classes that are not strong must update ClassLoaderData holder
804 // so that they can be unloaded when the mirror is no longer referenced.
805 if (!cl_info.is_strong_hidden()) {
806 k->class_loader_data()->initialize_holder(Handle(THREAD, k->java_mirror()));
807 }
808
809 // Add to class hierarchy, and do possible deoptimizations.
810 k->add_to_hierarchy(THREAD);
811 // But, do not add to dictionary.
812
813 if (class_load_event.should_commit()) {
814 JFR_ONLY(post_class_load_event(&class_load_event, k, loader_data);)
815 }
816
817 k->link_class(CHECK_NULL);
818
819 // notify jvmti
820 if (JvmtiExport::should_post_class_load()) {
821 JvmtiExport::post_class_load(THREAD, k);
822 }
823
824 return k;
825 }
826
827 // Add a klass to the system from a stream (called by jni_DefineClass and
828 // JVM_DefineClass).
829 // Note: class_name can be null. In that case we do not know the name of
830 // the class until we have parsed the stream.
831 // This function either returns an InstanceKlass or throws an exception. It does
832 // not return null without a pending exception.
833 InstanceKlass* SystemDictionary::resolve_class_from_stream(
834 ClassFileStream* st,
835 Symbol* class_name,
836 Handle class_loader,
837 const ClassLoadInfo& cl_info,
838 TRAPS) {
839
840 HandleMark hm(THREAD);
841
842 ClassLoaderData* loader_data = register_loader(class_loader);
843
844 // Classloaders that support parallelism, e.g. bootstrap classloader,
845 // do not acquire lock here
846 Handle lockObject = get_loader_lock_or_null(class_loader);
847 ObjectLocker ol(lockObject, THREAD);
848
849 // Parse the stream and create a klass.
850 // Note that we do this even though this klass might
851 // already be present in the SystemDictionary, otherwise we would not
852 // throw potential ClassFormatErrors.
853 InstanceKlass* k = nullptr;
854
855 #if INCLUDE_CDS
856 if (!CDSConfig::is_dumping_static_archive()) {
857 k = SystemDictionaryShared::lookup_from_stream(class_name,
858 class_loader,
859 cl_info.protection_domain(),
860 st,
861 CHECK_NULL);
862 }
863 #endif
864
865 if (k == nullptr) {
866 k = KlassFactory::create_from_stream(st, class_name, loader_data, cl_info, CHECK_NULL);
867 }
868
869 assert(k != nullptr, "no klass created");
870 Symbol* h_name = k->name();
871 assert(class_name == nullptr || class_name == h_name, "name mismatch");
872
873 // Add class just loaded
874 // If a class loader supports parallel classloading, handle parallel define requests.
875 // find_or_define_instance_class may return a different InstanceKlass,
876 // in which case the old k would be deallocated
877 if (is_parallelCapable(class_loader)) {
878 k = find_or_define_instance_class(h_name, class_loader, k, CHECK_NULL);
879 } else {
880 define_instance_class(k, class_loader, THREAD);
881
882 // If defining the class throws an exception register 'k' for cleanup.
883 if (HAS_PENDING_EXCEPTION) {
884 assert(k != nullptr, "Must have an instance klass here!");
885 loader_data->add_to_deallocate_list(k);
886 return nullptr;
887 }
888 }
889
890 // Make sure we have an entry in the SystemDictionary on success
891 DEBUG_ONLY(verify_dictionary_entry(h_name, k));
892
893 return k;
894 }
895
896 InstanceKlass* SystemDictionary::resolve_from_stream(ClassFileStream* st,
897 Symbol* class_name,
898 Handle class_loader,
899 const ClassLoadInfo& cl_info,
900 TRAPS) {
901 if (cl_info.is_hidden()) {
902 return resolve_hidden_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL);
903 } else {
904 return resolve_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL);
905 }
906 }
907
908
909 #if INCLUDE_CDS
910 // Check if a shared class can be loaded by the specific classloader.
911 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
912 InstanceKlass* ik,
913 PackageEntry* pkg_entry,
914 Handle class_loader) {
915 assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
916 "Cannot use sharing if java.base is patched");
917
918 // (1) Check if we are loading into the same loader as in dump time.
919
920 if (ik->defined_by_boot_loader()) {
921 if (class_loader() != nullptr) {
922 return false;
923 }
924 } else if (ik->defined_by_platform_loader()) {
925 if (class_loader() != java_platform_loader()) {
926 return false;
927 }
928 } else if (ik->defined_by_app_loader()) {
929 if (class_loader() != java_system_loader()) {
930 return false;
931 }
932 } else {
933 // ik was loaded by a custom loader during dump time
934 if (class_loader_data(class_loader)->is_builtin_class_loader_data()) {
935 return false;
936 } else {
937 return true;
938 }
939 }
940
941 // (2) Check if we are loading into the same module from the same location as in dump time.
942
943 if (CDSConfig::is_using_optimized_module_handling()) {
944 // Class visibility has not changed between dump time and run time, so a class
945 // that was visible (and thus archived) during dump time is always visible during runtime.
946 assert(SystemDictionary::is_shared_class_visible_impl(class_name, ik, pkg_entry, class_loader),
947 "visibility cannot change between dump time and runtime");
948 return true;
949 }
950 return is_shared_class_visible_impl(class_name, ik, pkg_entry, class_loader);
951 }
952
953 bool SystemDictionary::is_shared_class_visible_impl(Symbol* class_name,
954 InstanceKlass* ik,
955 PackageEntry* pkg_entry,
956 Handle class_loader) {
957 int scp_index = ik->shared_classpath_index();
958 assert(!ik->defined_by_other_loaders(), "this function should be called for built-in classes only");
959 assert(scp_index >= 0, "must be");
960 const AOTClassLocation* cl = AOTClassLocationConfig::runtime()->class_location_at(scp_index);
961 if (!Universe::is_module_initialized()) {
962 assert(cl != nullptr, "must be");
963 // At this point, no modules have been defined yet. KlassSubGraphInfo::check_allowed_klass()
964 // has restricted the classes can be loaded at this step to be only:
965 // [1] cs->is_modules_image(): classes in java.base, or,
966 // [2] HeapShared::is_a_test_class_in_unnamed_module(ik): classes in bootstrap/unnamed module
967 assert(cl->is_modules_image() || HeapShared::is_a_test_class_in_unnamed_module(ik),
968 "only these classes can be loaded before the module system is initialized");
969 assert(class_loader.is_null(), "sanity");
970 return true;
971 }
972
973 if (pkg_entry == nullptr) {
974 // We might have looked up pkg_entry before the module system was initialized.
975 // Need to reload it now.
976 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
977 if (pkg_name != nullptr) {
978 pkg_entry = class_loader_data(class_loader)->packages()->lookup_only(pkg_name);
979 }
980 }
981
982 ModuleEntry* mod_entry = (pkg_entry == nullptr) ? nullptr : pkg_entry->module();
983 bool should_be_in_named_module = (mod_entry != nullptr && mod_entry->is_named());
984 bool was_archived_from_named_module = !cl->has_unnamed_module();
985 bool visible;
986
987 if (was_archived_from_named_module) {
988 if (should_be_in_named_module) {
989 // Is the module loaded from the same location as during dump time?
990 visible = mod_entry->shared_path_index() == scp_index;
991 if (visible) {
992 assert(!mod_entry->is_patched(), "cannot load archived classes for patched module");
993 }
994 } else {
995 // During dump time, this class was in a named module, but at run time, this class should be
996 // in an unnamed module.
997 visible = false;
998 }
999 } else {
1000 if (should_be_in_named_module) {
1001 // During dump time, this class was in an unnamed, but at run time, this class should be
1002 // in a named module.
1003 visible = false;
1004 } else {
1005 visible = true;
1006 }
1007 }
1008
1009 return visible;
1010 }
1011
1012 bool SystemDictionary::check_shared_class_super_type(InstanceKlass* klass, InstanceKlass* super_type,
1013 Handle class_loader, bool is_superclass, TRAPS) {
1014 assert(super_type->in_aot_cache(), "must be");
1015
1016 // Quick check if the super type has been already loaded.
1017 // + Don't do it for unregistered classes -- they can be unloaded so
1018 // super_type->class_loader_data() could be stale.
1019 // + Don't check if loader data is null, ie. the super_type isn't fully loaded.
1020 if (!super_type->defined_by_other_loaders() && super_type->class_loader_data() != nullptr) {
1021 // Check if the superclass is loaded by the current class_loader
1022 Symbol* name = super_type->name();
1023 InstanceKlass* check = find_instance_klass(THREAD, name, class_loader);
1024 if (check == super_type) {
1025 return true;
1026 }
1027 }
1028
1029 Klass *found = resolve_with_circularity_detection(klass->name(), super_type->name(),
1030 class_loader, is_superclass, CHECK_false);
1031 if (found == super_type) {
1032 return true;
1033 } else {
1034 // The dynamically resolved super type is not the same as the one we used during dump time,
1035 // so we cannot use the class.
1036 return false;
1037 }
1038 }
1039
1040 bool SystemDictionary::check_shared_class_super_types(InstanceKlass* ik, Handle class_loader, TRAPS) {
1041 // Check the superclass and interfaces. They must be the same
1042 // as in dump time, because the layout of <ik> depends on
1043 // the specific layout of ik->super() and ik->local_interfaces().
1044 //
1045 // If unexpected superclass or interfaces are found, we cannot
1046 // load <ik> from the shared archive.
1047
1048 if (ik->super() != nullptr) {
1049 bool check_super = check_shared_class_super_type(ik, ik->super(),
1050 class_loader, true,
1051 CHECK_false);
1052 if (!check_super) {
1053 return false;
1054 }
1055 }
1056
1057 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1058 int num_interfaces = interfaces->length();
1059 for (int index = 0; index < num_interfaces; index++) {
1060 bool check_interface = check_shared_class_super_type(ik, interfaces->at(index), class_loader, false,
1061 CHECK_false);
1062 if (!check_interface) {
1063 return false;
1064 }
1065 }
1066
1067 return true;
1068 }
1069
1070 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik,
1071 Handle class_loader,
1072 Handle protection_domain,
1073 const ClassFileStream *cfs,
1074 PackageEntry* pkg_entry,
1075 TRAPS) {
1076 assert(ik != nullptr, "sanity");
1077 assert(ik->in_aot_cache(), "sanity");
1078 assert(!ik->is_unshareable_info_restored(), "shared class can be restored only once");
1079 assert(AtomicAccess::add(&ik->_shared_class_load_count, 1) == 1, "shared class loaded more than once");
1080 Symbol* class_name = ik->name();
1081
1082 if (!is_shared_class_visible(class_name, ik, pkg_entry, class_loader)) {
1083 ik->set_shared_loading_failed();
1084 return nullptr;
1085 }
1086
1087 bool check = check_shared_class_super_types(ik, class_loader, CHECK_NULL);
1088 if (!check) {
1089 ik->set_shared_loading_failed();
1090 return nullptr;
1091 }
1092
1093 InstanceKlass* new_ik = nullptr;
1094 // CFLH check is skipped for VM hidden classes (see KlassFactory::create_from_stream).
1095 // It will be skipped for shared VM hidden lambda proxy classes.
1096 if (!ik->is_hidden()) {
1097 new_ik = KlassFactory::check_shared_class_file_load_hook(
1098 ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL);
1099 }
1100 if (new_ik != nullptr) {
1101 // The class is changed by CFLH. Return the new class. The shared class is
1102 // not used.
1103 return new_ik;
1104 }
1105
1106 // Adjust methods to recover missing data. They need addresses for
1107 // interpreter entry points and their default native method address
1108 // must be reset.
1109
1110 // Shared classes are all currently loaded by either the bootstrap or
1111 // internal parallel class loaders, so this will never cause a deadlock
1112 // on a custom class loader lock.
1113 // Since this class is already locked with parallel capable class
1114 // loaders, including the bootstrap loader via the placeholder table,
1115 // this lock is currently a nop.
1116
1117 ClassLoaderData* loader_data = class_loader_data(class_loader);
1118 {
1119 HandleMark hm(THREAD);
1120 Handle lockObject = get_loader_lock_or_null(class_loader);
1121 ObjectLocker ol(lockObject, THREAD);
1122 // prohibited package check assumes all classes loaded from archive call
1123 // restore_unshareable_info which calls ik->set_package()
1124 ik->restore_unshareable_info(loader_data, protection_domain, pkg_entry, CHECK_NULL);
1125 }
1126
1127 load_shared_class_misc(ik, loader_data);
1128 return ik;
1129 }
1130
1131 void SystemDictionary::load_shared_class_misc(InstanceKlass* ik, ClassLoaderData* loader_data) {
1132 ik->print_class_load_logging(loader_data, nullptr, nullptr);
1133
1134 // For boot loader, ensure that GetSystemPackage knows that a class in this
1135 // package was loaded.
1136 if (loader_data->is_the_null_class_loader_data()) {
1137 s2 path_index = ik->shared_classpath_index();
1138 ik->set_classpath_index(path_index);
1139 }
1140
1141 // notify a class loaded from shared object
1142 ClassLoadingService::notify_class_loaded(ik, true /* shared class */);
1143
1144 if (CDSConfig::is_dumping_final_static_archive()) {
1145 SystemDictionaryShared::init_dumptime_info_from_preimage(ik);
1146 }
1147 }
1148
1149 // This is much more lightweight than SystemDictionary::resolve_or_null
1150 // - There's only a single Java thread at this point. No need for placeholder.
1151 // - All supertypes of ik have been loaded
1152 // - There's no circularity (checked in AOT assembly phase)
1153 // - There's no need to call java.lang.ClassLoader::load_class() because the boot/platform/app
1154 // loaders are well-behaved
1155 void SystemDictionary::preload_class(Handle class_loader, InstanceKlass* ik, TRAPS) {
1156 precond(Universe::is_bootstrapping());
1157 precond(java_platform_loader() != nullptr && java_system_loader() != nullptr);
1158 precond(class_loader() == nullptr || class_loader() == java_platform_loader() ||class_loader() == java_system_loader());
1159 precond(CDSConfig::is_using_aot_linked_classes());
1160 precond(AOTMetaspace::in_aot_cache_static_region((void*)ik));
1161 precond(!ik->is_loaded());
1162
1163 #ifdef ASSERT
1164 // preload_class() must be called in the correct order -- all super types must have
1165 // already been loaded.
1166 if (ik->java_super() != nullptr) {
1167 assert(ik->java_super()->is_loaded(), "must be");
1168 }
1169
1170 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1171 int num_interfaces = interfaces->length();
1172 for (int index = 0; index < num_interfaces; index++) {
1173 assert(interfaces->at(index)->is_loaded(), "must be");
1174 }
1175 #endif
1176
1177 EventClassLoad class_load_event;
1178
1179 ClassLoaderData* loader_data = ClassLoaderData::class_loader_data(class_loader());
1180 oop java_mirror = ik->archived_java_mirror();
1181 precond(java_mirror != nullptr);
1182 assert(java_lang_Class::module(java_mirror) != nullptr, "must have been archived");
1183
1184 Handle pd(THREAD, java_lang_Class::protection_domain(java_mirror));
1185 PackageEntry* pkg_entry = ik->package();
1186 assert(pkg_entry != nullptr || ClassLoader::package_from_class_name(ik->name()) == nullptr,
1187 "non-empty packages must have been archived");
1188
1189 // TODO: the following assert requires JDK-8365580
1190 // assert(is_shared_class_visible(ik->name(), ik, pkg_entry, class_loader), "must be");
1191
1192 ik->restore_unshareable_info(loader_data, pd, pkg_entry, CHECK);
1193 load_shared_class_misc(ik, loader_data);
1194 ik->add_to_hierarchy(THREAD);
1195
1196 if (!ik->is_hidden()) {
1197 update_dictionary(THREAD, ik, loader_data);
1198 }
1199
1200 if (class_load_event.should_commit()) {
1201 JFR_ONLY(post_class_load_event(&class_load_event, ik, loader_data);)
1202 }
1203
1204 assert(ik->is_loaded(), "Must be in at least loaded state");
1205 }
1206
1207 #endif // INCLUDE_CDS
1208
1209 #if INCLUDE_JFR
1210 void SystemDictionary::post_class_load_event(EventClassLoad* event, const InstanceKlass* k, const ClassLoaderData* init_cld) {
1211 assert(event != nullptr, "invariant");
1212 assert(k != nullptr, "invariant");
1213 event->set_loadedClass(k);
1214 event->set_definingClassLoader(k->class_loader_data());
1215 event->set_initiatingClassLoader(init_cld);
1216 event->commit();
1217 }
1218 #endif // INCLUDE_JFR
1219
1220 InstanceKlass* SystemDictionary::load_instance_class_impl(Symbol* class_name, Handle class_loader, TRAPS) {
1221
1222 if (class_loader.is_null()) {
1223 ResourceMark rm(THREAD);
1224 PackageEntry* pkg_entry = nullptr;
1225 bool search_only_bootloader_append = false;
1226
1227 // Find the package in the boot loader's package entry table.
1228 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
1229 if (pkg_name != nullptr) {
1230 pkg_entry = class_loader_data(class_loader)->packages()->lookup_only(pkg_name);
1231 }
1232
1233 // Prior to attempting to load the class, enforce the boot loader's
1234 // visibility boundaries.
1235 if (!Universe::is_module_initialized()) {
1236 // During bootstrapping, prior to module initialization, any
1237 // class attempting to be loaded must be checked against the
1238 // java.base packages in the boot loader's PackageEntryTable.
1239 // No class outside of java.base is allowed to be loaded during
1240 // this bootstrapping window.
1241 if (pkg_entry == nullptr || pkg_entry->in_unnamed_module()) {
1242 // Class is either in the unnamed package or in
1243 // a named package within the unnamed module. Either
1244 // case is outside of java.base, do not attempt to
1245 // load the class post java.base definition. If
1246 // java.base has not been defined, let the class load
1247 // and its package will be checked later by
1248 // ModuleEntryTable::verify_javabase_packages.
1249 if (ModuleEntryTable::javabase_defined()) {
1250 return nullptr;
1251 }
1252 } else {
1253 // Check that the class' package is defined within java.base.
1254 ModuleEntry* mod_entry = pkg_entry->module();
1255 Symbol* mod_entry_name = mod_entry->name();
1256 if (mod_entry_name->fast_compare(vmSymbols::java_base()) != 0) {
1257 return nullptr;
1258 }
1259 }
1260 } else {
1261 // After the module system has been initialized, check if the class'
1262 // package is in a module defined to the boot loader.
1263 if (pkg_name == nullptr || pkg_entry == nullptr || pkg_entry->in_unnamed_module()) {
1264 // Class is either in the unnamed package, in a named package
1265 // within a module not defined to the boot loader or in a
1266 // a named package within the unnamed module. In all cases,
1267 // limit visibility to search for the class only in the boot
1268 // loader's append path.
1269 if (!ClassLoader::has_bootclasspath_append()) {
1270 // If there is no bootclasspath append entry, no need to continue
1271 // searching.
1272 return nullptr;
1273 }
1274 search_only_bootloader_append = true;
1275 }
1276 }
1277
1278 // Prior to bootstrapping's module initialization, never load a class outside
1279 // of the boot loader's module path
1280 assert(Universe::is_module_initialized() ||
1281 !search_only_bootloader_append,
1282 "Attempt to load a class outside of boot loader's module path");
1283
1284 // Search for classes in the CDS archive.
1285 InstanceKlass* k = nullptr;
1286
1287 #if INCLUDE_CDS
1288 if (CDSConfig::is_using_archive())
1289 {
1290 PerfTraceTime vmtimer(ClassLoader::perf_shared_classload_time());
1291 InstanceKlass* ik = SystemDictionaryShared::find_builtin_class(class_name);
1292 if (ik != nullptr && ik->defined_by_boot_loader() && !ik->shared_loading_failed()) {
1293 SharedClassLoadingMark slm(THREAD, ik);
1294 k = load_shared_class(ik, class_loader, Handle(), nullptr, pkg_entry, CHECK_NULL);
1295 }
1296 }
1297 #endif
1298
1299 if (k == nullptr) {
1300 // Use VM class loader
1301 PerfTraceTime vmtimer(ClassLoader::perf_sys_classload_time());
1302 k = ClassLoader::load_class(class_name, pkg_entry, search_only_bootloader_append, CHECK_NULL);
1303 }
1304
1305 // find_or_define_instance_class may return a different InstanceKlass
1306 if (k != nullptr) {
1307 CDS_ONLY(SharedClassLoadingMark slm(THREAD, k);)
1308 k = find_or_define_instance_class(class_name, class_loader, k, CHECK_NULL);
1309 }
1310 return k;
1311 } else {
1312 // Use user specified class loader to load class. Call loadClass operation on class_loader.
1313 ResourceMark rm(THREAD);
1314
1315 JavaThread* jt = THREAD;
1316
1317 PerfClassTraceTime vmtimer(ClassLoader::perf_app_classload_time(),
1318 ClassLoader::perf_app_classload_selftime(),
1319 ClassLoader::perf_app_classload_count(),
1320 jt->get_thread_stat()->perf_recursion_counts_addr(),
1321 jt->get_thread_stat()->perf_timers_addr(),
1322 PerfClassTraceTime::CLASS_LOAD);
1323
1324 // Translate to external class name format, i.e., convert '/' chars to '.'
1325 Handle string = java_lang_String::externalize_classname(class_name, CHECK_NULL);
1326
1327 JavaValue result(T_OBJECT);
1328
1329 InstanceKlass* spec_klass = vmClasses::ClassLoader_klass();
1330
1331 // Call public unsynchronized loadClass(String) directly for all class loaders.
1332 // For parallelCapable class loaders, JDK >=7, loadClass(String, boolean) will
1333 // acquire a class-name based lock rather than the class loader object lock.
1334 // JDK < 7 already acquire the class loader lock in loadClass(String, boolean).
1335 JavaCalls::call_virtual(&result,
1336 class_loader,
1337 spec_klass,
1338 vmSymbols::loadClass_name(),
1339 vmSymbols::string_class_signature(),
1340 string,
1341 CHECK_NULL);
1342
1343 assert(result.get_type() == T_OBJECT, "just checking");
1344 oop obj = result.get_oop();
1345
1346 // Primitive classes return null since forName() cannot be
1347 // used to obtain any of the Class objects representing primitives or void
1348 if ((obj != nullptr) && !(java_lang_Class::is_primitive(obj))) {
1349 InstanceKlass* k = java_lang_Class::as_InstanceKlass(obj);
1350 // For user defined Java class loaders, check that the name returned is
1351 // the same as that requested. This check is done for the bootstrap
1352 // loader when parsing the class file.
1353 if (class_name == k->name()) {
1354 return k;
1355 }
1356 }
1357 // Class is not found or has the wrong name, return null
1358 return nullptr;
1359 }
1360 }
1361
1362 InstanceKlass* SystemDictionary::load_instance_class(Symbol* name,
1363 Handle class_loader,
1364 TRAPS) {
1365
1366 InstanceKlass* loaded_class = load_instance_class_impl(name, class_loader, CHECK_NULL);
1367
1368 // If everything was OK (no exceptions, no null return value), and
1369 // class_loader is NOT the defining loader, do a little more bookkeeping.
1370 if (loaded_class != nullptr &&
1371 loaded_class->class_loader() != class_loader()) {
1372
1373 ClassLoaderData* loader_data = class_loader_data(class_loader);
1374 check_constraints(loaded_class, loader_data, false, CHECK_NULL);
1375
1376 // Record dependency for non-parent delegation.
1377 // This recording keeps the defining class loader of the klass (loaded_class) found
1378 // from being unloaded while the initiating class loader is loaded
1379 // even if the reference to the defining class loader is dropped
1380 // before references to the initiating class loader.
1381 loader_data->record_dependency(loaded_class);
1382
1383 update_dictionary(THREAD, loaded_class, loader_data);
1384
1385 if (JvmtiExport::should_post_class_load()) {
1386 JvmtiExport::post_class_load(THREAD, loaded_class);
1387 }
1388 }
1389 return loaded_class;
1390 }
1391
1392 void SystemDictionary::define_instance_class(InstanceKlass* k, Handle class_loader, TRAPS) {
1393
1394 ClassLoaderData* loader_data = k->class_loader_data();
1395 assert(loader_data->class_loader() == class_loader(), "they must be the same");
1396
1397 // Bootstrap and other parallel classloaders don't acquire a lock,
1398 // they use placeholder token.
1399 // If a parallelCapable class loader calls define_instance_class instead of
1400 // find_or_define_instance_class to get here, we have a timing
1401 // hole with systemDictionary updates and check_constraints
1402 if (!is_parallelCapable(class_loader)) {
1403 assert(ObjectSynchronizer::current_thread_holds_lock(THREAD,
1404 get_loader_lock_or_null(class_loader)),
1405 "define called without lock");
1406 }
1407
1408 // Check class-loading constraints. Throw exception if violation is detected.
1409 // Grabs and releases SystemDictionary_lock
1410 // The check_constraints/find_class call and update_dictionary sequence
1411 // must be "atomic" for a specific class/classloader pair so we never
1412 // define two different instanceKlasses for that class/classloader pair.
1413 // Existing classloaders will call define_instance_class with the
1414 // classloader lock held
1415 // Parallel classloaders will call find_or_define_instance_class
1416 // which will require a token to perform the define class
1417 check_constraints(k, loader_data, true, CHECK);
1418
1419 // Register class just loaded with class loader (placed in ArrayList)
1420 // Note we do this before updating the dictionary, as this can
1421 // fail with an OutOfMemoryError (if it does, we will *not* put this
1422 // class in the dictionary and will not update the class hierarchy).
1423 // JVMTI FollowReferences needs to find the classes this way.
1424 if (k->class_loader() != nullptr) {
1425 methodHandle m(THREAD, Universe::loader_addClass_method());
1426 JavaValue result(T_VOID);
1427 JavaCallArguments args(class_loader);
1428 args.push_oop(Handle(THREAD, k->java_mirror()));
1429 JavaCalls::call(&result, m, &args, CHECK);
1430 }
1431
1432 // Add to class hierarchy, and do possible deoptimizations.
1433 k->add_to_hierarchy(THREAD);
1434
1435 // Add to systemDictionary - so other classes can see it.
1436 // Grabs and releases SystemDictionary_lock
1437 update_dictionary(THREAD, k, loader_data);
1438
1439 // notify jvmti
1440 if (JvmtiExport::should_post_class_load()) {
1441 JvmtiExport::post_class_load(THREAD, k);
1442 }
1443 }
1444
1445 // Support parallel classloading
1446 // All parallel class loaders, including bootstrap classloader
1447 // lock a placeholder entry for this class/class_loader pair
1448 // to allow parallel defines of different classes for this class loader
1449 // With AllowParallelDefine flag==true, in case they do not synchronize around
1450 // FindLoadedClass/DefineClass, calls, we check for parallel
1451 // loading for them, wait if a defineClass is in progress
1452 // and return the initial requestor's results
1453 // This flag does not apply to the bootstrap classloader.
1454 // With AllowParallelDefine flag==false, call through to define_instance_class
1455 // which will throw LinkageError: duplicate class definition.
1456 // False is the requested default.
1457 // For better performance, the class loaders should synchronize
1458 // findClass(), i.e. FindLoadedClass/DefineClassIfAbsent or they
1459 // potentially waste time reading and parsing the bytestream.
1460 // Note: VM callers should ensure consistency of k/class_name,class_loader
1461 // Be careful when modifying this code: once you have run
1462 // PlaceholderTable::find_and_add(PlaceholderTable::DEFINE_CLASS),
1463 // you need to find_and_remove it before returning.
1464 // So be careful to not exit with a CHECK_ macro between these calls.
1465 InstanceKlass* SystemDictionary::find_or_define_helper(Symbol* class_name, Handle class_loader,
1466 InstanceKlass* k, TRAPS) {
1467
1468 Symbol* name_h = k->name();
1469 ClassLoaderData* loader_data = class_loader_data(class_loader);
1470 Dictionary* dictionary = loader_data->dictionary();
1471
1472 // Hold SD lock around find_class and placeholder creation for DEFINE_CLASS
1473 {
1474 MutexLocker mu(THREAD, SystemDictionary_lock);
1475 // First check if class already defined
1476 if (is_parallelDefine(class_loader)) {
1477 InstanceKlass* check = dictionary->find_class(THREAD, name_h);
1478 if (check != nullptr) {
1479 return check;
1480 }
1481 }
1482
1483 // Acquire define token for this class/classloader
1484 PlaceholderEntry* probe = PlaceholderTable::find_and_add(name_h, loader_data,
1485 PlaceholderTable::DEFINE_CLASS, nullptr, THREAD);
1486 // Wait if another thread defining in parallel
1487 // All threads wait - even those that will throw duplicate class: otherwise
1488 // caller is surprised by LinkageError: duplicate, but findLoadedClass fails
1489 // if other thread has not finished updating dictionary
1490 while (probe->definer() != nullptr) {
1491 SystemDictionary_lock->wait();
1492 }
1493 // Only special cases allow parallel defines and can use other thread's results
1494 // Other cases fall through, and may run into duplicate defines
1495 // caught by finding an entry in the SystemDictionary
1496 if (is_parallelDefine(class_loader) && (probe->instance_klass() != nullptr)) {
1497 InstanceKlass* ik = probe->instance_klass();
1498 PlaceholderTable::find_and_remove(name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1499 SystemDictionary_lock->notify_all();
1500 #ifdef ASSERT
1501 InstanceKlass* check = dictionary->find_class(THREAD, name_h);
1502 assert(check != nullptr, "definer missed recording success");
1503 #endif
1504 return ik;
1505 } else {
1506 // This thread will define the class (even if earlier thread tried and had an error)
1507 probe->set_definer(THREAD);
1508 }
1509 }
1510
1511 define_instance_class(k, class_loader, THREAD);
1512
1513 // definer must notify any waiting threads
1514 {
1515 MutexLocker mu(THREAD, SystemDictionary_lock);
1516 PlaceholderEntry* probe = PlaceholderTable::get_entry(name_h, loader_data);
1517 assert(probe != nullptr, "DEFINE_CLASS placeholder lost?");
1518 if (!HAS_PENDING_EXCEPTION) {
1519 probe->set_instance_klass(k);
1520 }
1521 probe->set_definer(nullptr);
1522 PlaceholderTable::find_and_remove(name_h, loader_data, PlaceholderTable::DEFINE_CLASS, THREAD);
1523 SystemDictionary_lock->notify_all();
1524 }
1525
1526 return HAS_PENDING_EXCEPTION ? nullptr : k;
1527 }
1528
1529 // If a class loader supports parallel classloading handle parallel define requests.
1530 // find_or_define_instance_class may return a different InstanceKlass
1531 InstanceKlass* SystemDictionary::find_or_define_instance_class(Symbol* class_name, Handle class_loader,
1532 InstanceKlass* k, TRAPS) {
1533 InstanceKlass* defined_k = find_or_define_helper(class_name, class_loader, k, THREAD);
1534 // Clean up original InstanceKlass if duplicate or error
1535 if (!HAS_PENDING_EXCEPTION && defined_k != k) {
1536 // If a parallel capable class loader already defined this class, register 'k' for cleanup.
1537 assert(defined_k != nullptr, "Should have a klass if there's no exception");
1538 k->class_loader_data()->add_to_deallocate_list(k);
1539 } else if (HAS_PENDING_EXCEPTION) {
1540 // Remove this InstanceKlass from the LoaderConstraintTable if added.
1541 LoaderConstraintTable::remove_failed_loaded_klass(k, class_loader_data(class_loader));
1542 assert(defined_k == nullptr, "Should not have a klass if there's an exception");
1543 k->class_loader_data()->add_to_deallocate_list(k);
1544 }
1545 return defined_k;
1546 }
1547
1548
1549 // ----------------------------------------------------------------------------
1550 // GC support
1551
1552 // Assumes classes in the SystemDictionary are only unloaded at a safepoint
1553 bool SystemDictionary::do_unloading(GCTimer* gc_timer) {
1554
1555 bool unloading_occurred;
1556 bool is_concurrent = !SafepointSynchronize::is_at_safepoint();
1557 {
1558 GCTraceTime(Debug, gc, phases) t("ClassLoaderData", gc_timer);
1559 assert_locked_or_safepoint(ClassLoaderDataGraph_lock); // caller locks.
1560 // First, mark for unload all ClassLoaderData referencing a dead class loader.
1561 unloading_occurred = ClassLoaderDataGraph::do_unloading();
1562 if (unloading_occurred) {
1563 ConditionalMutexLocker ml2(Module_lock, is_concurrent);
1564 JFR_ONLY(Jfr::on_unloading_classes();)
1565 MANAGEMENT_ONLY(FinalizerService::purge_unloaded();)
1566 ConditionalMutexLocker ml1(SystemDictionary_lock, is_concurrent);
1567 ClassLoaderDataGraph::clean_module_and_package_info();
1568 LoaderConstraintTable::purge_loader_constraints();
1569 ResolutionErrorTable::purge_resolution_errors();
1570 }
1571 }
1572
1573 GCTraceTime(Debug, gc, phases) t("Trigger cleanups", gc_timer);
1574
1575 if (unloading_occurred) {
1576 SymbolTable::trigger_cleanup();
1577
1578 ConditionalMutexLocker ml(ClassInitError_lock, is_concurrent);
1579 InstanceKlass::clean_initialization_error_table();
1580 }
1581
1582 return unloading_occurred;
1583 }
1584
1585 void SystemDictionary::methods_do(void f(Method*)) {
1586 // Walk methods in loaded classes
1587
1588 {
1589 MutexLocker ml(ClassLoaderDataGraph_lock);
1590 ClassLoaderDataGraph::methods_do(f);
1591 }
1592
1593 auto doit = [&] (InvokeMethodKey key, Method* method) {
1594 if (method != nullptr) {
1595 f(method);
1596 }
1597 };
1598
1599 {
1600 MutexLocker ml(InvokeMethodIntrinsicTable_lock);
1601 _invoke_method_intrinsic_table->iterate_all(doit);
1602 }
1603
1604 }
1605
1606 // ----------------------------------------------------------------------------
1607 // Initialization
1608
1609 void SystemDictionary::initialize(TRAPS) {
1610 _invoke_method_intrinsic_table = new (mtClass) InvokeMethodIntrinsicTable();
1611 _invoke_method_type_table = new (mtClass) InvokeMethodTypeTable();
1612 ResolutionErrorTable::initialize();
1613 LoaderConstraintTable::initialize();
1614 PlaceholderTable::initialize();
1615 #if INCLUDE_CDS
1616 SystemDictionaryShared::initialize();
1617 if (CDSConfig::is_dumping_archive()) {
1618 AOTClassLocationConfig::dumptime_init(THREAD);
1619 }
1620 #endif
1621 // Resolve basic classes
1622 vmClasses::resolve_all(CHECK);
1623 // Resolve classes used by archived heap objects
1624 if (CDSConfig::is_using_archive()) {
1625 HeapShared::resolve_classes(THREAD);
1626 }
1627 }
1628
1629 // Constraints on class loaders. The details of the algorithm can be
1630 // found in the OOPSLA'98 paper "Dynamic Class Loading in the Java
1631 // Virtual Machine" by Sheng Liang and Gilad Bracha. The basic idea is
1632 // that the dictionary needs to maintain a set of constraints that
1633 // must be satisfied by all classes in the dictionary.
1634 // if defining is true, then LinkageError if already in dictionary
1635 // if initiating loader, then ok if InstanceKlass matches existing entry
1636
1637 void SystemDictionary::check_constraints(InstanceKlass* k,
1638 ClassLoaderData* loader_data,
1639 bool defining,
1640 TRAPS) {
1641 ResourceMark rm(THREAD);
1642 stringStream ss;
1643 bool throwException = false;
1644
1645 {
1646 Symbol* name = k->name();
1647
1648 MutexLocker mu(THREAD, SystemDictionary_lock);
1649
1650 InstanceKlass* check = loader_data->dictionary()->find_class(THREAD, name);
1651 if (check != nullptr) {
1652 // If different InstanceKlass - duplicate class definition,
1653 // else - ok, class loaded by a different thread in parallel.
1654 // We should only have found it if it was done loading and ok to use.
1655
1656 if ((defining == true) || (k != check)) {
1657 throwException = true;
1658 ss.print("loader %s", loader_data->loader_name_and_id());
1659 ss.print(" attempted duplicate %s definition for %s. (%s)",
1660 k->external_kind(), k->external_name(), k->class_in_module_of_loader(false, true));
1661 } else {
1662 return;
1663 }
1664 }
1665
1666 if (throwException == false) {
1667 if (LoaderConstraintTable::check_or_update(k, loader_data, name) == false) {
1668 throwException = true;
1669 ss.print("loader constraint violation: loader %s", loader_data->loader_name_and_id());
1670 ss.print(" wants to load %s %s.",
1671 k->external_kind(), k->external_name());
1672 Klass *existing_klass = LoaderConstraintTable::find_constrained_klass(name, loader_data);
1673 if (existing_klass != nullptr && existing_klass->class_loader_data() != loader_data) {
1674 ss.print(" A different %s with the same name was previously loaded by %s. (%s)",
1675 existing_klass->external_kind(),
1676 existing_klass->class_loader_data()->loader_name_and_id(),
1677 existing_klass->class_in_module_of_loader(false, true));
1678 } else {
1679 ss.print(" (%s)", k->class_in_module_of_loader(false, true));
1680 }
1681 }
1682 }
1683 }
1684
1685 // Throw error now if needed (cannot throw while holding
1686 // SystemDictionary_lock because of rank ordering)
1687 if (throwException == true) {
1688 THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
1689 }
1690 }
1691
1692 // Update class loader data dictionary - done after check_constraint and add_to_hierarchy
1693 // have been called.
1694 void SystemDictionary::update_dictionary(JavaThread* current,
1695 InstanceKlass* k,
1696 ClassLoaderData* loader_data) {
1697 MonitorLocker mu1(SystemDictionary_lock);
1698
1699 // Make a new dictionary entry.
1700 Symbol* name = k->name();
1701 Dictionary* dictionary = loader_data->dictionary();
1702 InstanceKlass* sd_check = dictionary->find_class(current, name);
1703 if (sd_check == nullptr) {
1704 dictionary->add_klass(current, name, k);
1705 }
1706 mu1.notify_all();
1707 }
1708
1709 #if INCLUDE_CDS
1710 // Indicate that loader_data has initiated the loading of class k, which
1711 // has already been defined by a parent loader.
1712 // This API should be used only by AOTLinkedClassBulkLoader
1713 void SystemDictionary::add_to_initiating_loader(JavaThread* current,
1714 InstanceKlass* k,
1715 ClassLoaderData* loader_data) {
1716 assert(CDSConfig::is_using_aot_linked_classes(), "must be");
1717 assert_locked_or_safepoint(SystemDictionary_lock);
1718 Symbol* name = k->name();
1719 Dictionary* dictionary = loader_data->dictionary();
1720 assert(k->is_loaded(), "must be");
1721 assert(k->class_loader_data() != loader_data, "only for classes defined by a parent loader");
1722 assert(dictionary->find_class(current, name) == nullptr, "sanity");
1723 dictionary->add_klass(current, name, k);
1724 }
1725 #endif
1726
1727 // Try to find a class name using the loader constraints. The
1728 // loader constraints might know about a class that isn't fully loaded
1729 // yet and these will be ignored.
1730 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
1731 Thread* current, Symbol* class_name, Handle class_loader) {
1732
1733 // First see if it has been loaded directly.
1734 Klass* klass = find_instance_or_array_klass(current, class_name, class_loader);
1735 if (klass != nullptr)
1736 return klass;
1737
1738 // Now look to see if it has been loaded elsewhere, and is subject to
1739 // a loader constraint that would require this loader to return the
1740 // klass that is already loaded.
1741 if (Signature::is_array(class_name)) {
1742 // For array classes, their Klass*s are not kept in the
1743 // constraint table. The element Klass*s are.
1744 SignatureStream ss(class_name, false);
1745 int ndims = ss.skip_array_prefix(); // skip all '['s
1746 BasicType t = ss.type();
1747 if (t != T_OBJECT) {
1748 klass = Universe::typeArrayKlass(t);
1749 } else {
1750 MutexLocker mu(current, SystemDictionary_lock);
1751 klass = LoaderConstraintTable::find_constrained_klass(ss.as_symbol(), class_loader_data(class_loader));
1752 }
1753 // If element class already loaded, allocate array klass
1754 if (klass != nullptr) {
1755 klass = klass->array_klass_or_null(ndims);
1756 }
1757 } else {
1758 MutexLocker mu(current, SystemDictionary_lock);
1759 // Non-array classes are easy: simply check the constraint table.
1760 klass = LoaderConstraintTable::find_constrained_klass(class_name, class_loader_data(class_loader));
1761 }
1762
1763 return klass;
1764 }
1765
1766 bool SystemDictionary::add_loader_constraint(Symbol* class_name,
1767 Klass* klass_being_linked,
1768 Handle class_loader1,
1769 Handle class_loader2) {
1770 ClassLoaderData* loader_data1 = class_loader_data(class_loader1);
1771 ClassLoaderData* loader_data2 = class_loader_data(class_loader2);
1772
1773 Symbol* constraint_name = nullptr;
1774
1775 if (!Signature::is_array(class_name)) {
1776 constraint_name = class_name;
1777 } else {
1778 // For array classes, their Klass*s are not kept in the
1779 // constraint table. The element classes are.
1780 SignatureStream ss(class_name, false);
1781 ss.skip_array_prefix(); // skip all '['s
1782 if (!ss.has_envelope()) {
1783 return true; // primitive types always pass
1784 }
1785 constraint_name = ss.as_symbol();
1786 // Increment refcount to keep constraint_name alive after
1787 // SignatureStream is destructed. It will be decremented below
1788 // before returning.
1789 constraint_name->increment_refcount();
1790 }
1791
1792 Dictionary* dictionary1 = loader_data1->dictionary();
1793 Dictionary* dictionary2 = loader_data2->dictionary();
1794
1795 JavaThread* current = JavaThread::current();
1796 {
1797 MutexLocker mu_s(SystemDictionary_lock);
1798 InstanceKlass* klass1 = dictionary1->find_class(current, constraint_name);
1799 InstanceKlass* klass2 = dictionary2->find_class(current, constraint_name);
1800 bool result = LoaderConstraintTable::add_entry(constraint_name, klass1, loader_data1,
1801 klass2, loader_data2);
1802 #if INCLUDE_CDS
1803 if (CDSConfig::is_dumping_archive() && klass_being_linked != nullptr &&
1804 !klass_being_linked->in_aot_cache()) {
1805 SystemDictionaryShared::record_linking_constraint(constraint_name,
1806 InstanceKlass::cast(klass_being_linked),
1807 class_loader1, class_loader2);
1808 }
1809 #endif // INCLUDE_CDS
1810 if (Signature::is_array(class_name)) {
1811 constraint_name->decrement_refcount();
1812 }
1813 return result;
1814 }
1815 }
1816
1817 // Add entry to resolution error table to record the error when the first
1818 // attempt to resolve a reference to a class has failed.
1819 void SystemDictionary::add_resolution_error(const constantPoolHandle& pool, int which,
1820 Symbol* error, const char* message,
1821 Symbol* cause, const char* cause_msg) {
1822 {
1823 MutexLocker ml(Thread::current(), SystemDictionary_lock);
1824 ResolutionErrorEntry* entry = ResolutionErrorTable::find_entry(pool, which);
1825 if (entry == nullptr) {
1826 ResolutionErrorTable::add_entry(pool, which, error, message, cause, cause_msg);
1827 }
1828 }
1829 }
1830
1831 // Delete a resolution error for RedefineClasses for a constant pool is going away
1832 void SystemDictionary::delete_resolution_error(ConstantPool* pool) {
1833 ResolutionErrorTable::delete_entry(pool);
1834 }
1835
1836 // Lookup resolution error table. Returns error if found, otherwise null.
1837 Symbol* SystemDictionary::find_resolution_error(const constantPoolHandle& pool, int which,
1838 const char** message,
1839 Symbol** cause, const char** cause_msg) {
1840
1841 {
1842 MutexLocker ml(Thread::current(), SystemDictionary_lock);
1843 ResolutionErrorEntry* entry = ResolutionErrorTable::find_entry(pool, which);
1844 if (entry != nullptr) {
1845 *message = entry->message();
1846 *cause = entry->cause();
1847 *cause_msg = entry->cause_msg();
1848 return entry->error();
1849 } else {
1850 return nullptr;
1851 }
1852 }
1853 }
1854
1855 // Add an entry to resolution error table to record an error in resolving or
1856 // validating a nest host. This is used to construct informative error
1857 // messages when IllegalAccessError's occur. If an entry already exists it will
1858 // be updated with the nest host error message.
1859
1860 void SystemDictionary::add_nest_host_error(const constantPoolHandle& pool,
1861 int which,
1862 const stringStream& message) {
1863 {
1864 MutexLocker ml(Thread::current(), SystemDictionary_lock);
1865 ResolutionErrorEntry* entry = ResolutionErrorTable::find_entry(pool, which);
1866 if (entry == nullptr) {
1867 // Only add a new entry to the resolution error table if one hasn't been found for this
1868 // constant pool index. In this case resolution succeeded but there's an error in this nest host
1869 // that we use the table to record.
1870 assert(pool->resolved_klass_at(which) != nullptr, "klass should be resolved if there is no entry");
1871 ResolutionErrorTable::add_entry(pool, which, message.as_string(true /* on C-heap */));
1872 } else {
1873 // An existing entry means we had a true resolution failure (LinkageError) with our nest host, but we
1874 // still want to add the error message for the higher-level access checks to report. We should
1875 // only reach here under the same error condition, so we can ignore the potential race with setting
1876 // the message.
1877 const char* nhe = entry->nest_host_error();
1878 if (nhe == nullptr) {
1879 entry->set_nest_host_error(message.as_string(true /* on C-heap */));
1880 } else {
1881 DEBUG_ONLY(const char* msg = message.base();)
1882 assert(strcmp(nhe, msg) == 0, "New message %s, differs from original %s", msg, nhe);
1883 }
1884 }
1885 }
1886 }
1887
1888 // Lookup any nest host error
1889 const char* SystemDictionary::find_nest_host_error(const constantPoolHandle& pool, int which) {
1890 {
1891 MutexLocker ml(Thread::current(), SystemDictionary_lock);
1892 ResolutionErrorEntry* entry = ResolutionErrorTable::find_entry(pool, which);
1893 if (entry != nullptr) {
1894 return entry->nest_host_error();
1895 } else {
1896 return nullptr;
1897 }
1898 }
1899 }
1900
1901 // Signature constraints ensure that callers and callees agree about
1902 // the meaning of type names in their signatures. This routine is the
1903 // intake for constraints. It collects them from several places:
1904 //
1905 // * LinkResolver::resolve_method (if check_access is true) requires
1906 // that the resolving class (the caller) and the defining class of
1907 // the resolved method (the callee) agree on each type in the
1908 // method's signature.
1909 //
1910 // * LinkResolver::resolve_interface_method performs exactly the same
1911 // checks.
1912 //
1913 // * LinkResolver::resolve_field requires that the constant pool
1914 // attempting to link to a field agree with the field's defining
1915 // class about the type of the field signature.
1916 //
1917 // * klassVtable::initialize_vtable requires that, when a class
1918 // overrides a vtable entry allocated by a superclass, that the
1919 // overriding method (i.e., the callee) agree with the superclass
1920 // on each type in the method's signature.
1921 //
1922 // * klassItable::initialize_itable requires that, when a class fills
1923 // in its itables, for each non-abstract method installed in an
1924 // itable, the method (i.e., the callee) agree with the interface
1925 // on each type in the method's signature.
1926 //
1927 // All those methods have a boolean (check_access, checkconstraints)
1928 // which turns off the checks. This is used from specialized contexts
1929 // such as bootstrapping, dumping, and debugging.
1930 //
1931 // No direct constraint is placed between the class and its
1932 // supertypes. Constraints are only placed along linked relations
1933 // between callers and callees. When a method overrides or implements
1934 // an abstract method in a supertype (superclass or interface), the
1935 // constraints are placed as if the supertype were the caller to the
1936 // overriding method. (This works well, since callers to the
1937 // supertype have already established agreement between themselves and
1938 // the supertype.) As a result of all this, a class can disagree with
1939 // its supertype about the meaning of a type name, as long as that
1940 // class neither calls a relevant method of the supertype, nor is
1941 // called (perhaps via an override) from the supertype.
1942 //
1943 //
1944 // SystemDictionary::check_signature_loaders(sig, klass_being_linked, l1, l2)
1945 //
1946 // Make sure all class components (including arrays) in the given
1947 // signature will be resolved to the same class in both loaders.
1948 // Returns the name of the type that failed a loader constraint check, or
1949 // null if no constraint failed. No exception except OOME is thrown.
1950 // Arrays are not added to the loader constraint table, their elements are.
1951 Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
1952 Klass* klass_being_linked,
1953 Handle loader1, Handle loader2,
1954 bool is_method) {
1955 // Nothing to do if loaders are the same.
1956 if (loader1() == loader2()) {
1957 return nullptr;
1958 }
1959
1960 for (SignatureStream ss(signature, is_method); !ss.is_done(); ss.next()) {
1961 if (ss.is_reference()) {
1962 Symbol* sig = ss.as_symbol();
1963 // Note: In the future, if template-like types can take
1964 // arguments, we will want to recognize them and dig out class
1965 // names hiding inside the argument lists.
1966 if (!add_loader_constraint(sig, klass_being_linked, loader1, loader2)) {
1967 return sig;
1968 }
1969 }
1970 }
1971 return nullptr;
1972 }
1973
1974 Method* SystemDictionary::find_method_handle_intrinsic(vmIntrinsicID iid,
1975 Symbol* signature,
1976 TRAPS) {
1977
1978 const int iid_as_int = vmIntrinsics::as_int(iid);
1979 assert(MethodHandles::is_signature_polymorphic(iid) &&
1980 MethodHandles::is_signature_polymorphic_intrinsic(iid) &&
1981 iid != vmIntrinsics::_invokeGeneric,
1982 "must be a known MH intrinsic iid=%d: %s", iid_as_int, vmIntrinsics::name_at(iid));
1983
1984 InvokeMethodKey key(signature, iid_as_int);
1985 Method** met = nullptr;
1986
1987 // We only want one entry in the table for this (signature/id, method) pair but the code
1988 // to create the intrinsic method needs to be outside the lock.
1989 // The first thread claims the entry by adding the key and the other threads wait, until the
1990 // Method has been added as the value.
1991 {
1992 MonitorLocker ml(THREAD, InvokeMethodIntrinsicTable_lock);
1993 while (true) {
1994 bool created;
1995 met = _invoke_method_intrinsic_table->put_if_absent(key, &created);
1996 assert(met != nullptr, "either created or found");
1997 if (*met != nullptr) {
1998 return *met;
1999 } else if (created) {
2000 // The current thread won the race and will try to create the full entry.
2001 break;
2002 } else {
2003 // Another thread beat us to it, so wait for them to complete
2004 // and return *met; or if they hit an error we get another try.
2005 ml.wait();
2006 // Note it is not safe to read *met here as that entry could have
2007 // been deleted, so we must loop and try put_if_absent again.
2008 }
2009 }
2010 }
2011
2012 methodHandle m = Method::make_method_handle_intrinsic(iid, signature, THREAD);
2013 bool throw_error = HAS_PENDING_EXCEPTION;
2014 if (!throw_error && (!Arguments::is_interpreter_only() || iid == vmIntrinsics::_linkToNative)) {
2015 // Generate a compiled form of the MH intrinsic
2016 // linkToNative doesn't have interpreter-specific implementation, so always has to go through compiled version.
2017 AdapterHandlerLibrary::create_native_wrapper(m);
2018 // Check if have the compiled code.
2019 throw_error = (!m->has_compiled_code());
2020 }
2021
2022 {
2023 MonitorLocker ml(THREAD, InvokeMethodIntrinsicTable_lock);
2024 if (throw_error) {
2025 // Remove the entry and let another thread try, or get the same exception.
2026 bool removed = _invoke_method_intrinsic_table->remove(key);
2027 assert(removed, "must be the owner");
2028 ml.notify_all();
2029 } else {
2030 signature->make_permanent(); // The signature is never unloaded.
2031 assert(Arguments::is_interpreter_only() || (m->has_compiled_code() &&
2032 m->code()->entry_point() == m->from_compiled_entry()),
2033 "MH intrinsic invariant");
2034 *met = m(); // insert the element
2035 ml.notify_all();
2036 return m();
2037 }
2038 }
2039
2040 // Throw OOM or the pending exception in the JavaThread
2041 if (throw_error && !HAS_PENDING_EXCEPTION) {
2042 THROW_MSG_NULL(vmSymbols::java_lang_OutOfMemoryError(),
2043 "Out of space in CodeCache for method handle intrinsic");
2044 }
2045 return nullptr;
2046 }
2047
2048 #if INCLUDE_CDS
2049 void SystemDictionary::get_all_method_handle_intrinsics(GrowableArray<Method*>* methods) {
2050 assert(SafepointSynchronize::is_at_safepoint(), "must be");
2051 auto do_method = [&] (InvokeMethodKey& key, Method*& m) {
2052 methods->append(m);
2053 };
2054 _invoke_method_intrinsic_table->iterate_all(do_method);
2055 }
2056
2057 void SystemDictionary::restore_archived_method_handle_intrinsics() {
2058 if (UseSharedSpaces) {
2059 EXCEPTION_MARK;
2060 restore_archived_method_handle_intrinsics_impl(THREAD);
2061 if (HAS_PENDING_EXCEPTION) {
2062 // This is probably caused by OOM -- other parts of the CDS archive have direct pointers to
2063 // the archived method handle intrinsics, so we can't really recover from this failure.
2064 vm_exit_during_initialization(err_msg("Failed to restore archived method handle intrinsics. Try to increase heap size."));
2065 }
2066 }
2067 }
2068
2069 void SystemDictionary::restore_archived_method_handle_intrinsics_impl(TRAPS) {
2070 Array<Method*>* list = AOTMetaspace::archived_method_handle_intrinsics();
2071 for (int i = 0; i < list->length(); i++) {
2072 methodHandle m(THREAD, list->at(i));
2073 Method::restore_archived_method_handle_intrinsic(m, CHECK);
2074 m->constants()->restore_unshareable_info(CHECK);
2075 if (!Arguments::is_interpreter_only() || m->intrinsic_id() == vmIntrinsics::_linkToNative) {
2076 AdapterHandlerLibrary::create_native_wrapper(m);
2077 if (!m->has_compiled_code()) {
2078 ResourceMark rm(THREAD);
2079 vm_exit_during_initialization(err_msg("Failed to initialize method %s", m->external_name()));
2080 }
2081 }
2082
2083 // There's no need to grab the InvokeMethodIntrinsicTable_lock, as we are still very early in
2084 // VM start-up -- in init_globals2() -- so we are still running a single Java thread. It's not
2085 // possible to have a contention.
2086 const int iid_as_int = vmIntrinsics::as_int(m->intrinsic_id());
2087 InvokeMethodKey key(m->signature(), iid_as_int);
2088 bool created = _invoke_method_intrinsic_table->put(key, m());
2089 assert(created, "unexpected contention");
2090 }
2091 }
2092 #endif // INCLUDE_CDS
2093
2094 // Helper for unpacking the return value from linkMethod and linkCallSite.
2095 static Method* unpack_method_and_appendix(Handle mname,
2096 Klass* accessing_klass,
2097 objArrayHandle appendix_box,
2098 Handle* appendix_result,
2099 TRAPS) {
2100 if (mname.not_null()) {
2101 Method* m = java_lang_invoke_MemberName::vmtarget(mname());
2102 if (m != nullptr) {
2103 oop appendix = appendix_box->obj_at(0);
2104 LogTarget(Info, methodhandles) lt;
2105 if (lt.develop_is_enabled()) {
2106 ResourceMark rm(THREAD);
2107 LogStream ls(lt);
2108 ls.print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2109 m->print_on(&ls);
2110 if (appendix != nullptr) { ls.print("appendix = "); appendix->print_on(&ls); }
2111 ls.cr();
2112 }
2113
2114 (*appendix_result) = Handle(THREAD, appendix);
2115 // the target is stored in the cpCache and if a reference to this
2116 // MemberName is dropped we need a way to make sure the
2117 // class_loader containing this method is kept alive.
2118 methodHandle mh(THREAD, m); // record_dependency can safepoint.
2119 ClassLoaderData* this_key = accessing_klass->class_loader_data();
2120 this_key->record_dependency(m->method_holder());
2121 return mh();
2122 }
2123 }
2124 THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives");
2125 }
2126
2127 Method* SystemDictionary::find_method_handle_invoker(Klass* klass,
2128 Symbol* name,
2129 Symbol* signature,
2130 Klass* accessing_klass,
2131 Handle* appendix_result,
2132 TRAPS) {
2133 guarantee(THREAD->can_call_java(), "");
2134 Handle method_type =
2135 SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_NULL);
2136
2137 int ref_kind = JVM_REF_invokeVirtual;
2138 oop name_oop = StringTable::intern(name, CHECK_NULL);
2139 Handle name_str (THREAD, name_oop);
2140 objArrayHandle appendix_box = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 1, CHECK_NULL);
2141 assert(appendix_box->obj_at(0) == nullptr, "");
2142
2143 // This should not happen. JDK code should take care of that.
2144 if (accessing_klass == nullptr || method_type.is_null()) {
2145 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "bad invokehandle");
2146 }
2147
2148 // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2149 JavaCallArguments args;
2150 args.push_oop(Handle(THREAD, accessing_klass->java_mirror()));
2151 args.push_int(ref_kind);
2152 args.push_oop(Handle(THREAD, klass->java_mirror()));
2153 args.push_oop(name_str);
2154 args.push_oop(method_type);
2155 args.push_oop(appendix_box);
2156 JavaValue result(T_OBJECT);
2157 JavaCalls::call_static(&result,
2158 vmClasses::MethodHandleNatives_klass(),
2159 vmSymbols::linkMethod_name(),
2160 vmSymbols::linkMethod_signature(),
2161 &args, CHECK_NULL);
2162 Handle mname(THREAD, result.get_oop());
2163 return unpack_method_and_appendix(mname, accessing_klass, appendix_box, appendix_result, THREAD);
2164 }
2165
2166 // Decide if we can globally cache a lookup of this class, to be returned to any client that asks.
2167 // We must ensure that all class loaders everywhere will reach this class, for any client.
2168 // This is a safe bet for public classes in java.lang, such as Object and String.
2169 // We also include public classes in java.lang.invoke, because they appear frequently in system-level method types.
2170 // Out of an abundance of caution, we do not include any other classes, not even for packages like java.util.
2171 static bool is_always_visible_class(oop mirror) {
2172 Klass* klass = java_lang_Class::as_Klass(mirror);
2173 if (klass->is_objArray_klass()) {
2174 klass = ObjArrayKlass::cast(klass)->bottom_klass(); // check element type
2175 }
2176 if (klass->is_typeArray_klass()) {
2177 return true; // primitive array
2178 }
2179 assert(klass->is_instance_klass(), "%s", klass->external_name());
2180 InstanceKlass* ik = InstanceKlass::cast(klass);
2181 return ik->is_public() &&
2182 (ik->is_same_class_package(vmClasses::Object_klass()) || // java.lang
2183 ik->is_same_class_package(vmClasses::MethodHandle_klass())); // java.lang.invoke
2184 }
2185
2186 // Find or construct the Java mirror (java.lang.Class instance) for
2187 // the given field type signature, as interpreted relative to the
2188 // given class loader. Handles primitives, void, references, arrays,
2189 // and all other reflectable types, except method types.
2190 // N.B. Code in reflection should use this entry point.
2191 Handle SystemDictionary::find_java_mirror_for_type(Symbol* signature,
2192 Klass* accessing_klass,
2193 SignatureStream::FailureMode failure_mode,
2194 TRAPS) {
2195
2196 Handle class_loader;
2197
2198 // What we have here must be a valid field descriptor,
2199 // and all valid field descriptors are supported.
2200 // Produce the same java.lang.Class that reflection reports.
2201 if (accessing_klass != nullptr) {
2202 class_loader = Handle(THREAD, accessing_klass->class_loader());
2203 }
2204 ResolvingSignatureStream ss(signature, class_loader, false);
2205 oop mirror_oop = ss.as_java_mirror(failure_mode, CHECK_NH);
2206 if (mirror_oop == nullptr) {
2207 return Handle(); // report failure this way
2208 }
2209 Handle mirror(THREAD, mirror_oop);
2210
2211 if (accessing_klass != nullptr) {
2212 // Check accessibility, emulating ConstantPool::verify_constant_pool_resolve.
2213 Klass* sel_klass = java_lang_Class::as_Klass(mirror());
2214 if (sel_klass != nullptr) {
2215 LinkResolver::check_klass_accessibility(accessing_klass, sel_klass, CHECK_NH);
2216 }
2217 }
2218 return mirror;
2219 }
2220
2221
2222 // Ask Java code to find or construct a java.lang.invoke.MethodType for the given
2223 // signature, as interpreted relative to the given class loader.
2224 // Because of class loader constraints, all method handle usage must be
2225 // consistent with this loader.
2226 Handle SystemDictionary::find_method_handle_type(Symbol* signature,
2227 Klass* accessing_klass,
2228 TRAPS) {
2229 Handle empty;
2230 OopHandle* o;
2231 {
2232 MutexLocker ml(THREAD, InvokeMethodTypeTable_lock);
2233 o = _invoke_method_type_table->get(signature);
2234 }
2235
2236 if (o != nullptr) {
2237 oop mt = o->resolve();
2238 assert(java_lang_invoke_MethodType::is_instance(mt), "");
2239 return Handle(THREAD, mt);
2240 } else if (!THREAD->can_call_java()) {
2241 warning("SystemDictionary::find_method_handle_type called from compiler thread"); // FIXME
2242 return Handle(); // do not attempt from within compiler, unless it was cached
2243 }
2244
2245 Handle class_loader;
2246 if (accessing_klass != nullptr) {
2247 class_loader = Handle(THREAD, accessing_klass->class_loader());
2248 }
2249 bool can_be_cached = true;
2250 int npts = ArgumentCount(signature).size();
2251 objArrayHandle pts = oopFactory::new_objArray_handle(vmClasses::Class_klass(), npts, CHECK_(empty));
2252 int arg = 0;
2253 Handle rt; // the return type from the signature
2254 ResourceMark rm(THREAD);
2255 for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2256 oop mirror = nullptr;
2257 if (can_be_cached) {
2258 // Use neutral class loader to lookup candidate classes to be placed in the cache.
2259 mirror = ss.as_java_mirror(Handle(), SignatureStream::ReturnNull, CHECK_(empty));
2260 if (mirror == nullptr || (ss.is_reference() && !is_always_visible_class(mirror))) {
2261 // Fall back to accessing_klass context.
2262 can_be_cached = false;
2263 }
2264 }
2265 if (!can_be_cached) {
2266 // Resolve, throwing a real error if it doesn't work.
2267 mirror = ss.as_java_mirror(class_loader, SignatureStream::NCDFError, CHECK_(empty));
2268 }
2269 assert(mirror != nullptr, "%s", ss.as_symbol()->as_C_string());
2270 if (ss.at_return_type())
2271 rt = Handle(THREAD, mirror);
2272 else
2273 pts->obj_at_put(arg++, mirror);
2274
2275 // Check accessibility.
2276 if (!java_lang_Class::is_primitive(mirror) && accessing_klass != nullptr) {
2277 Klass* sel_klass = java_lang_Class::as_Klass(mirror);
2278 mirror = nullptr; // safety
2279 // Emulate ConstantPool::verify_constant_pool_resolve.
2280 LinkResolver::check_klass_accessibility(accessing_klass, sel_klass, CHECK_(empty));
2281 }
2282 }
2283 assert(arg == npts, "");
2284
2285 // call java.lang.invoke.MethodHandleNatives::findMethodHandleType(Class rt, Class[] pts) -> MethodType
2286 JavaCallArguments args(Handle(THREAD, rt()));
2287 args.push_oop(pts);
2288 JavaValue result(T_OBJECT);
2289 JavaCalls::call_static(&result,
2290 vmClasses::MethodHandleNatives_klass(),
2291 vmSymbols::findMethodHandleType_name(),
2292 vmSymbols::findMethodHandleType_signature(),
2293 &args, CHECK_(empty));
2294 Handle method_type(THREAD, result.get_oop());
2295
2296 if (can_be_cached) {
2297 // We can cache this MethodType inside the JVM.
2298 MutexLocker ml(THREAD, InvokeMethodTypeTable_lock);
2299 bool created = false;
2300 assert(method_type != nullptr, "unexpected null");
2301 OopHandle* h = _invoke_method_type_table->get(signature);
2302 if (h == nullptr) {
2303 signature->make_permanent(); // The signature is never unloaded.
2304 OopHandle elem = OopHandle(Universe::vm_global(), method_type());
2305 bool created = _invoke_method_type_table->put(signature, elem);
2306 assert(created, "better be created");
2307 }
2308 }
2309 // report back to the caller with the MethodType
2310 return method_type;
2311 }
2312
2313 Handle SystemDictionary::find_field_handle_type(Symbol* signature,
2314 Klass* accessing_klass,
2315 TRAPS) {
2316 Handle empty;
2317 ResourceMark rm(THREAD);
2318 SignatureStream ss(signature, /*is_method=*/ false);
2319 if (!ss.is_done()) {
2320 Handle class_loader;
2321 if (accessing_klass != nullptr) {
2322 class_loader = Handle(THREAD, accessing_klass->class_loader());
2323 }
2324 oop mirror = ss.as_java_mirror(class_loader, SignatureStream::NCDFError, CHECK_(empty));
2325 ss.next();
2326 if (ss.is_done()) {
2327 return Handle(THREAD, mirror);
2328 }
2329 }
2330 return empty;
2331 }
2332
2333 // Ask Java code to find or construct a method handle constant.
2334 Handle SystemDictionary::link_method_handle_constant(Klass* caller,
2335 int ref_kind, //e.g., JVM_REF_invokeVirtual
2336 Klass* callee,
2337 Symbol* name,
2338 Symbol* signature,
2339 TRAPS) {
2340 Handle empty;
2341 if (caller == nullptr) {
2342 THROW_MSG_(vmSymbols::java_lang_InternalError(), "bad MH constant", empty);
2343 }
2344 Handle name_str = java_lang_String::create_from_symbol(name, CHECK_(empty));
2345 Handle signature_str = java_lang_String::create_from_symbol(signature, CHECK_(empty));
2346
2347 // Put symbolic info from the MH constant into freshly created MemberName and resolve it.
2348 Handle mname = vmClasses::MemberName_klass()->allocate_instance_handle(CHECK_(empty));
2349 java_lang_invoke_MemberName::set_clazz(mname(), callee->java_mirror());
2350 java_lang_invoke_MemberName::set_name (mname(), name_str());
2351 java_lang_invoke_MemberName::set_type (mname(), signature_str());
2352 java_lang_invoke_MemberName::set_flags(mname(), MethodHandles::ref_kind_to_flags(ref_kind));
2353
2354 if (ref_kind == JVM_REF_invokeVirtual &&
2355 MethodHandles::is_signature_polymorphic_public_name(callee, name)) {
2356 // Skip resolution for public signature polymorphic methods such as
2357 // j.l.i.MethodHandle.invoke()/invokeExact() and those on VarHandle
2358 // They require appendix argument which MemberName resolution doesn't handle.
2359 // There's special logic on JDK side to handle them
2360 // (see MethodHandles.linkMethodHandleConstant() and MethodHandles.findVirtualForMH()).
2361 } else {
2362 MethodHandles::resolve_MemberName(mname, caller, 0, false /*speculative_resolve*/, CHECK_(empty));
2363 }
2364
2365 // After method/field resolution succeeded, it's safe to resolve MH signature as well.
2366 Handle type = MethodHandles::resolve_MemberName_type(mname, caller, CHECK_(empty));
2367
2368 // call java.lang.invoke.MethodHandleNatives::linkMethodHandleConstant(Class caller, int refKind, Class callee, String name, Object type) -> MethodHandle
2369 JavaCallArguments args;
2370 args.push_oop(Handle(THREAD, caller->java_mirror())); // the referring class
2371 args.push_int(ref_kind);
2372 args.push_oop(Handle(THREAD, callee->java_mirror())); // the target class
2373 args.push_oop(name_str);
2374 args.push_oop(type);
2375 JavaValue result(T_OBJECT);
2376 JavaCalls::call_static(&result,
2377 vmClasses::MethodHandleNatives_klass(),
2378 vmSymbols::linkMethodHandleConstant_name(),
2379 vmSymbols::linkMethodHandleConstant_signature(),
2380 &args, CHECK_(empty));
2381 return Handle(THREAD, result.get_oop());
2382 }
2383
2384 // Ask Java to run a bootstrap method, in order to create a dynamic call site
2385 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry
2386 // with linkage results being stored back into the bootstrap specifier.
2387 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) {
2388 // Resolve the bootstrap specifier, its name, type, and static arguments
2389 bootstrap_specifier.resolve_bsm(CHECK);
2390
2391 // This should not happen. JDK code should take care of that.
2392 if (bootstrap_specifier.caller() == nullptr || bootstrap_specifier.type_arg().is_null()) {
2393 THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument");
2394 }
2395
2396 bool is_indy = bootstrap_specifier.is_method_call();
2397 objArrayHandle appendix_box;
2398 if (is_indy) {
2399 // Some method calls may require an appendix argument. Arrange to receive it.
2400 appendix_box = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 1, CHECK);
2401 assert(appendix_box->obj_at(0) == nullptr, "");
2402 }
2403
2404 // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, bsm, type, info)
2405 // indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2406 JavaCallArguments args;
2407 args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror()));
2408 args.push_oop(bootstrap_specifier.bsm());
2409 args.push_oop(bootstrap_specifier.name_arg());
2410 args.push_oop(bootstrap_specifier.type_arg());
2411 args.push_oop(bootstrap_specifier.arg_values());
2412 if (is_indy) {
2413 args.push_oop(appendix_box);
2414 }
2415 JavaValue result(T_OBJECT);
2416 JavaCalls::call_static(&result,
2417 vmClasses::MethodHandleNatives_klass(),
2418 is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(),
2419 is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(),
2420 &args, CHECK);
2421
2422 Handle value(THREAD, result.get_oop());
2423 if (is_indy) {
2424 Handle appendix;
2425 Method* method = unpack_method_and_appendix(value,
2426 bootstrap_specifier.caller(),
2427 appendix_box,
2428 &appendix, CHECK);
2429 methodHandle mh(THREAD, method);
2430 bootstrap_specifier.set_resolved_method(mh, appendix);
2431 } else {
2432 bootstrap_specifier.set_resolved_value(value);
2433 }
2434
2435 // sanity check
2436 assert(bootstrap_specifier.is_resolved() ||
2437 (bootstrap_specifier.is_method_call() &&
2438 bootstrap_specifier.resolved_method().not_null()), "bootstrap method call failed");
2439 }
2440
2441
2442 bool SystemDictionary::is_nonpublic_Object_method(Method* m) {
2443 assert(m != nullptr, "Unexpected nullptr Method*");
2444 return !m->is_public() && m->method_holder() == vmClasses::Object_klass();
2445 }
2446
2447 // ----------------------------------------------------------------------------
2448
2449 void SystemDictionary::print_on(outputStream *st) {
2450 CDS_ONLY(SystemDictionaryShared::print_on(st));
2451 GCMutexLocker mu(SystemDictionary_lock);
2452
2453 ClassLoaderDataGraph::print_dictionary(st);
2454
2455 // Placeholders
2456 PlaceholderTable::print_on(st);
2457 st->cr();
2458
2459 // loader constraints - print under SD_lock
2460 LoaderConstraintTable::print_on(st);
2461 st->cr();
2462 }
2463
2464 void SystemDictionary::print() { print_on(tty); }
2465
2466 void SystemDictionary::verify() {
2467
2468 GCMutexLocker mu(SystemDictionary_lock);
2469
2470 // Verify dictionary
2471 ClassLoaderDataGraph::verify_dictionary();
2472
2473 // Verify constraint table
2474 LoaderConstraintTable::verify();
2475 }
2476
2477 void SystemDictionary::dump(outputStream *st, bool verbose) {
2478 assert_locked_or_safepoint(SystemDictionary_lock);
2479 if (verbose) {
2480 print_on(st);
2481 } else {
2482 CDS_ONLY(SystemDictionaryShared::print_table_statistics(st));
2483 ClassLoaderDataGraph::print_table_statistics(st);
2484 LoaderConstraintTable::print_table_statistics(st);
2485 }
2486 }
2487
2488 // Utility for dumping dictionaries.
2489 SystemDictionaryDCmd::SystemDictionaryDCmd(outputStream* output, bool heap) :
2490 DCmdWithParser(output, heap),
2491 _verbose("-verbose", "Dump the content of each dictionary entry for all class loaders",
2492 "BOOLEAN", false, "false") {
2493 _dcmdparser.add_dcmd_option(&_verbose);
2494 }
2495
2496 void SystemDictionaryDCmd::execute(DCmdSource source, TRAPS) {
2497 VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpSysDict,
2498 _verbose.value());
2499 VMThread::execute(&dumper);
2500 }