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