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 *
38 #include "classfile/packageEntry.hpp"
39 #include "classfile/placeholders.hpp"
40 #include "classfile/resolutionErrors.hpp"
41 #include "classfile/stringTable.hpp"
42 #include "classfile/symbolTable.hpp"
43 #include "classfile/systemDictionary.hpp"
44 #include "classfile/vmClasses.hpp"
45 #include "classfile/vmSymbols.hpp"
46 #include "gc/shared/gcTraceTime.inline.hpp"
47 #include "interpreter/bootstrapInfo.hpp"
48 #include "jfr/jfrEvents.hpp"
49 #include "jvm.h"
50 #include "logging/log.hpp"
51 #include "logging/logStream.hpp"
52 #include "memory/metaspaceClosure.hpp"
53 #include "memory/oopFactory.hpp"
54 #include "memory/resourceArea.hpp"
55 #include "memory/universe.hpp"
56 #include "oops/access.inline.hpp"
57 #include "oops/constantPool.inline.hpp"
58 #include "oops/instanceKlass.hpp"
59 #include "oops/klass.inline.hpp"
60 #include "oops/method.inline.hpp"
61 #include "oops/objArrayKlass.hpp"
62 #include "oops/objArrayOop.inline.hpp"
63 #include "oops/oop.inline.hpp"
64 #include "oops/oopHandle.inline.hpp"
65 #include "oops/symbol.hpp"
66 #include "oops/typeArrayKlass.hpp"
67 #include "prims/jvmtiExport.hpp"
68 #include "prims/methodHandles.hpp"
69 #include "runtime/arguments.hpp"
70 #include "runtime/atomicAccess.hpp"
71 #include "runtime/handles.inline.hpp"
72 #include "runtime/java.hpp"
73 #include "runtime/javaCalls.hpp"
74 #include "runtime/mutexLocker.hpp"
75 #include "runtime/sharedRuntime.hpp"
76 #include "runtime/signature.hpp"
77 #include "runtime/synchronizer.hpp"
78 #include "services/classLoadingService.hpp"
79 #include "services/diagnosticCommand.hpp"
80 #include "services/finalizerService.hpp"
81 #include "services/threadService.hpp"
82 #include "utilities/growableArray.hpp"
83 #include "utilities/macros.hpp"
84 #include "utilities/utf8.hpp"
85 #if INCLUDE_CDS
86 #include "classfile/systemDictionaryShared.hpp"
87 #endif
88 #if INCLUDE_JFR
89 #include "jfr/jfr.hpp"
90 #endif
91
92 class InvokeMethodKey : public StackObj {
93 private:
94 Symbol* _symbol;
169 CHECK_NULL);
170 return result.get_oop();
171 }
172
173 oop SystemDictionary::get_platform_class_loader_impl(TRAPS) {
174 JavaValue result(T_OBJECT);
175 InstanceKlass* class_loader_klass = vmClasses::ClassLoader_klass();
176 JavaCalls::call_static(&result,
177 class_loader_klass,
178 vmSymbols::getPlatformClassLoader_name(),
179 vmSymbols::void_classloader_signature(),
180 CHECK_NULL);
181 return result.get_oop();
182 }
183
184 // Helper function
185 inline ClassLoaderData* class_loader_data(Handle class_loader) {
186 return ClassLoaderData::class_loader_data(class_loader());
187 }
188
189 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, bool create_mirror_cld) {
190 if (create_mirror_cld) {
191 // Add a new class loader data to the graph.
192 return ClassLoaderDataGraph::add(class_loader, true);
193 } else {
194 return (class_loader() == nullptr) ? ClassLoaderData::the_null_class_loader_data() :
195 ClassLoaderDataGraph::find_or_create(class_loader);
196 }
197 }
198
199 void SystemDictionary::set_system_loader(ClassLoaderData *cld) {
200 if (_java_system_loader.is_empty()) {
201 _java_system_loader = cld->class_loader_handle();
202 } else {
203 assert(_java_system_loader.resolve() == cld->class_loader(), "sanity");
204 }
205 }
206
207 void SystemDictionary::set_platform_loader(ClassLoaderData *cld) {
208 if (_java_platform_loader.is_empty()) {
209 _java_platform_loader = cld->class_loader_handle();
210 } else {
211 assert(_java_platform_loader.resolve() == cld->class_loader(), "sanity");
212 }
213 }
214
215 // ----------------------------------------------------------------------------
383 }
384 } else {
385 k = Universe::typeArrayKlass(t);
386 k = k->array_klass(ndims, CHECK_NULL);
387 }
388 return k;
389 }
390
391 static inline void log_circularity_error(Symbol* name, PlaceholderEntry* probe) {
392 LogTarget(Debug, class, load, placeholders) lt;
393 if (lt.is_enabled()) {
394 ResourceMark rm;
395 LogStream ls(lt);
396 ls.print("ClassCircularityError detected for placeholder entry %s", name->as_C_string());
397 probe->print_on(&ls);
398 ls.cr();
399 }
400 }
401
402 // Must be called for any superclass or superinterface resolution
403 // during class definition to allow class circularity checking
404 // superinterface callers:
405 // parse_interfaces - from defineClass
406 // superclass callers:
407 // ClassFileParser - from defineClass
408 // load_shared_class - while loading a class from shared archive
409 // resolve_instance_class_or_null:
410 // via: handle_parallel_super_load
411 // when resolving a class that has an existing placeholder with
412 // a saved superclass [i.e. a defineClass is currently in progress]
413 // If another thread is trying to resolve the class, it must do
414 // superclass checks on its own thread to catch class circularity and
415 // to avoid deadlock.
416 //
417 // resolve_with_circularity_detection adds a DETECT_CIRCULARITY placeholder to the placeholder table before calling
418 // resolve_instance_class_or_null. ClassCircularityError is detected when a DETECT_CIRCULARITY or LOAD_INSTANCE
419 // placeholder for the same thread, class, classloader is found.
420 // This can be seen with logging option: -Xlog:class+load+placeholders=debug.
421 //
422 InstanceKlass* SystemDictionary::resolve_with_circularity_detection(Symbol* class_name,
423 Symbol* next_name,
424 Handle class_loader,
425 bool is_superclass,
426 TRAPS) {
427
428 assert(next_name != nullptr, "null superclass for resolving");
429 assert(!Signature::is_array(next_name), "invalid superclass name");
430
431 ClassLoaderData* loader_data = class_loader_data(class_loader);
432
433 if (is_superclass) {
434 InstanceKlass* klassk = loader_data->dictionary()->find_class(THREAD, class_name);
435 if (klassk != nullptr) {
436 // We can come here for two reasons:
437 // (a) RedefineClasses -- the class is already loaded
438 // (b) Rarely, the class might have been loaded by a parallel thread
439 // We can do a quick check against the already assigned superclass's name and loader.
440 InstanceKlass* superk = klassk->super();
441 if (superk != nullptr &&
442 superk->name() == next_name &&
443 superk->class_loader() == class_loader()) {
444 return superk;
445 }
446 }
447 }
448
449 // can't throw error holding a lock
450 bool throw_circularity_error = false;
451 {
452 MutexLocker mu(THREAD, SystemDictionary_lock);
453
454 // Must check ClassCircularity before resolving next_name (superclass or interface).
455 PlaceholderEntry* probe = PlaceholderTable::get_entry(class_name, loader_data);
456 if (probe != nullptr && probe->check_seen_thread(THREAD, PlaceholderTable::DETECT_CIRCULARITY)) {
457 log_circularity_error(class_name, probe);
458 throw_circularity_error = true;
459 }
460
461 // Make sure there's a placeholder for the class_name before resolving.
462 // This is used as a claim that this thread is currently loading superclass/classloader
463 // and for ClassCircularity checks.
464 if (!throw_circularity_error) {
465 // Be careful not to exit resolve_with_circularity_detection without removing this placeholder.
466 PlaceholderEntry* newprobe = PlaceholderTable::find_and_add(class_name,
467 loader_data,
468 PlaceholderTable::DETECT_CIRCULARITY,
469 next_name, THREAD);
470 }
471 }
472
473 if (throw_circularity_error) {
474 ResourceMark rm(THREAD);
475 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), class_name->as_C_string());
476 }
477
478 // Resolve the superclass or superinterface, check results on return
479 InstanceKlass* superk =
480 SystemDictionary::resolve_instance_class_or_null(next_name,
481 class_loader,
482 THREAD);
483
484 // Clean up placeholder entry.
485 {
486 MutexLocker mu(THREAD, SystemDictionary_lock);
487 PlaceholderTable::find_and_remove(class_name, loader_data, PlaceholderTable::DETECT_CIRCULARITY, THREAD);
488 SystemDictionary_lock->notify_all();
489 }
490
491 // Check for pending exception or null superk, and throw exception
492 if (HAS_PENDING_EXCEPTION || superk == nullptr) {
493 handle_resolution_exception(next_name, true, CHECK_NULL);
494 }
495
496 return superk;
497 }
498
896
897 InstanceKlass* SystemDictionary::resolve_from_stream(ClassFileStream* st,
898 Symbol* class_name,
899 Handle class_loader,
900 const ClassLoadInfo& cl_info,
901 TRAPS) {
902 if (cl_info.is_hidden()) {
903 return resolve_hidden_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL);
904 } else {
905 return resolve_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL);
906 }
907 }
908
909
910 #if INCLUDE_CDS
911 // Check if a shared class can be loaded by the specific classloader.
912 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
913 InstanceKlass* ik,
914 PackageEntry* pkg_entry,
915 Handle class_loader) {
916 assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
917 "Cannot use sharing if java.base is patched");
918
919 // (1) Check if we are loading into the same loader as in dump time.
920
921 if (ik->defined_by_boot_loader()) {
922 if (class_loader() != nullptr) {
923 return false;
924 }
925 } else if (ik->defined_by_platform_loader()) {
926 if (class_loader() != java_platform_loader()) {
927 return false;
928 }
929 } else if (ik->defined_by_app_loader()) {
930 if (class_loader() != java_system_loader()) {
931 return false;
932 }
933 } else {
934 // ik was loaded by a custom loader during dump time
935 if (class_loader_data(class_loader)->is_builtin_class_loader_data()) {
1051 class_loader, true,
1052 CHECK_false);
1053 if (!check_super) {
1054 return false;
1055 }
1056 }
1057
1058 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1059 int num_interfaces = interfaces->length();
1060 for (int index = 0; index < num_interfaces; index++) {
1061 bool check_interface = check_shared_class_super_type(ik, interfaces->at(index), class_loader, false,
1062 CHECK_false);
1063 if (!check_interface) {
1064 return false;
1065 }
1066 }
1067
1068 return true;
1069 }
1070
1071 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik,
1072 Handle class_loader,
1073 Handle protection_domain,
1074 const ClassFileStream *cfs,
1075 PackageEntry* pkg_entry,
1076 TRAPS) {
1077 assert(ik != nullptr, "sanity");
1078 assert(ik->in_aot_cache(), "sanity");
1079 assert(!ik->is_unshareable_info_restored(), "shared class can be restored only once");
1080 assert(AtomicAccess::add(&ik->_shared_class_load_count, 1) == 1, "shared class loaded more than once");
1081 Symbol* class_name = ik->name();
1082
1083 if (!is_shared_class_visible(class_name, ik, pkg_entry, class_loader)) {
1084 ik->set_shared_loading_failed();
1085 return nullptr;
1086 }
1087
1088 bool check = check_shared_class_super_types(ik, class_loader, CHECK_NULL);
1089 if (!check) {
1090 ik->set_shared_loading_failed();
1091 return nullptr;
1092 }
1093
1094 InstanceKlass* new_ik = nullptr;
1095 // CFLH check is skipped for VM hidden classes (see KlassFactory::create_from_stream).
1096 // It will be skipped for shared VM hidden lambda proxy classes.
1097 if (!ik->is_hidden()) {
1098 new_ik = KlassFactory::check_shared_class_file_load_hook(
1099 ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL);
1100 }
1101 if (new_ik != nullptr) {
1102 // The class is changed by CFLH. Return the new class. The shared class is
1103 // not used.
1104 return new_ik;
1105 }
1106
1107 // Adjust methods to recover missing data. They need addresses for
1108 // interpreter entry points and their default native method address
1109 // must be reset.
1110
1111 // Shared classes are all currently loaded by either the bootstrap or
1112 // internal parallel class loaders, so this will never cause a deadlock
1113 // on a custom class loader lock.
1690 }
1691 }
1692
1693 // Update class loader data dictionary - done after check_constraint and add_to_hierarchy
1694 // have been called.
1695 void SystemDictionary::update_dictionary(JavaThread* current,
1696 InstanceKlass* k,
1697 ClassLoaderData* loader_data) {
1698 MonitorLocker mu1(SystemDictionary_lock);
1699
1700 // Make a new dictionary entry.
1701 Symbol* name = k->name();
1702 Dictionary* dictionary = loader_data->dictionary();
1703 InstanceKlass* sd_check = dictionary->find_class(current, name);
1704 if (sd_check == nullptr) {
1705 dictionary->add_klass(current, name, k);
1706 }
1707 mu1.notify_all();
1708 }
1709
1710 #if INCLUDE_CDS
1711 // Indicate that loader_data has initiated the loading of class k, which
1712 // has already been defined by a parent loader.
1713 // This API should be used only by AOTLinkedClassBulkLoader
1714 void SystemDictionary::add_to_initiating_loader(JavaThread* current,
1715 InstanceKlass* k,
1716 ClassLoaderData* loader_data) {
1717 assert(CDSConfig::is_using_aot_linked_classes(), "must be");
1718 assert_locked_or_safepoint(SystemDictionary_lock);
1719 Symbol* name = k->name();
1720 Dictionary* dictionary = loader_data->dictionary();
1721 assert(k->is_loaded(), "must be");
1722 assert(k->class_loader_data() != loader_data, "only for classes defined by a parent loader");
1723 assert(dictionary->find_class(current, name) == nullptr, "sanity");
1724 dictionary->add_klass(current, name, k);
1725 }
1726 #endif
1727
1728 // Try to find a class name using the loader constraints. The
1729 // loader constraints might know about a class that isn't fully loaded
1730 // yet and these will be ignored.
1731 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
1732 Thread* current, Symbol* class_name, Handle class_loader) {
1733
1734 // First see if it has been loaded directly.
1735 Klass* klass = find_instance_or_array_klass(current, class_name, class_loader);
1736 if (klass != nullptr)
1737 return klass;
1738
1739 // Now look to see if it has been loaded elsewhere, and is subject to
1740 // a loader constraint that would require this loader to return the
1741 // klass that is already loaded.
1742 if (Signature::is_array(class_name)) {
1743 // For array classes, their Klass*s are not kept in the
1744 // constraint table. The element Klass*s are.
1745 SignatureStream ss(class_name, false);
1746 int ndims = ss.skip_array_prefix(); // skip all '['s
2078 if (!m->has_compiled_code()) {
2079 ResourceMark rm(THREAD);
2080 vm_exit_during_initialization(err_msg("Failed to initialize method %s", m->external_name()));
2081 }
2082 }
2083
2084 // There's no need to grab the InvokeMethodIntrinsicTable_lock, as we are still very early in
2085 // VM start-up -- in init_globals2() -- so we are still running a single Java thread. It's not
2086 // possible to have a contention.
2087 const int iid_as_int = vmIntrinsics::as_int(m->intrinsic_id());
2088 InvokeMethodKey key(m->signature(), iid_as_int);
2089 bool created = _invoke_method_intrinsic_table->put(key, m());
2090 assert(created, "unexpected contention");
2091 }
2092 }
2093 #endif // INCLUDE_CDS
2094
2095 // Helper for unpacking the return value from linkMethod and linkCallSite.
2096 static Method* unpack_method_and_appendix(Handle mname,
2097 Klass* accessing_klass,
2098 objArrayHandle appendix_box,
2099 Handle* appendix_result,
2100 TRAPS) {
2101 if (mname.not_null()) {
2102 Method* m = java_lang_invoke_MemberName::vmtarget(mname());
2103 if (m != nullptr) {
2104 oop appendix = appendix_box->obj_at(0);
2105 LogTarget(Info, methodhandles) lt;
2106 if (lt.develop_is_enabled()) {
2107 ResourceMark rm(THREAD);
2108 LogStream ls(lt);
2109 ls.print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2110 m->print_on(&ls);
2111 if (appendix != nullptr) { ls.print("appendix = "); appendix->print_on(&ls); }
2112 ls.cr();
2113 }
2114
2115 (*appendix_result) = Handle(THREAD, appendix);
2116 // the target is stored in the cpCache and if a reference to this
2117 // MemberName is dropped we need a way to make sure the
2118 // class_loader containing this method is kept alive.
2121 this_key->record_dependency(m->method_holder());
2122 return mh();
2123 }
2124 }
2125 THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives");
2126 }
2127
2128 Method* SystemDictionary::find_method_handle_invoker(Klass* klass,
2129 Symbol* name,
2130 Symbol* signature,
2131 Klass* accessing_klass,
2132 Handle* appendix_result,
2133 TRAPS) {
2134 guarantee(THREAD->can_call_java(), "");
2135 Handle method_type =
2136 SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_NULL);
2137
2138 int ref_kind = JVM_REF_invokeVirtual;
2139 oop name_oop = StringTable::intern(name, CHECK_NULL);
2140 Handle name_str (THREAD, name_oop);
2141 objArrayHandle appendix_box = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 1, CHECK_NULL);
2142 assert(appendix_box->obj_at(0) == nullptr, "");
2143
2144 // This should not happen. JDK code should take care of that.
2145 if (accessing_klass == nullptr || method_type.is_null()) {
2146 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "bad invokehandle");
2147 }
2148
2149 // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2150 JavaCallArguments args;
2151 args.push_oop(Handle(THREAD, accessing_klass->java_mirror()));
2152 args.push_int(ref_kind);
2153 args.push_oop(Handle(THREAD, klass->java_mirror()));
2154 args.push_oop(name_str);
2155 args.push_oop(method_type);
2156 args.push_oop(appendix_box);
2157 JavaValue result(T_OBJECT);
2158 JavaCalls::call_static(&result,
2159 vmClasses::MethodHandleNatives_klass(),
2160 vmSymbols::linkMethod_name(),
2161 vmSymbols::linkMethod_signature(),
2232 {
2233 MutexLocker ml(THREAD, InvokeMethodTypeTable_lock);
2234 o = _invoke_method_type_table->get(signature);
2235 }
2236
2237 if (o != nullptr) {
2238 oop mt = o->resolve();
2239 assert(java_lang_invoke_MethodType::is_instance(mt), "");
2240 return Handle(THREAD, mt);
2241 } else if (!THREAD->can_call_java()) {
2242 warning("SystemDictionary::find_method_handle_type called from compiler thread"); // FIXME
2243 return Handle(); // do not attempt from within compiler, unless it was cached
2244 }
2245
2246 Handle class_loader;
2247 if (accessing_klass != nullptr) {
2248 class_loader = Handle(THREAD, accessing_klass->class_loader());
2249 }
2250 bool can_be_cached = true;
2251 int npts = ArgumentCount(signature).size();
2252 objArrayHandle pts = oopFactory::new_objArray_handle(vmClasses::Class_klass(), npts, CHECK_(empty));
2253 int arg = 0;
2254 Handle rt; // the return type from the signature
2255 ResourceMark rm(THREAD);
2256 for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2257 oop mirror = nullptr;
2258 if (can_be_cached) {
2259 // Use neutral class loader to lookup candidate classes to be placed in the cache.
2260 mirror = ss.as_java_mirror(Handle(), SignatureStream::ReturnNull, CHECK_(empty));
2261 if (mirror == nullptr || (ss.is_reference() && !is_always_visible_class(mirror))) {
2262 // Fall back to accessing_klass context.
2263 can_be_cached = false;
2264 }
2265 }
2266 if (!can_be_cached) {
2267 // Resolve, throwing a real error if it doesn't work.
2268 mirror = ss.as_java_mirror(class_loader, SignatureStream::NCDFError, CHECK_(empty));
2269 }
2270 assert(mirror != nullptr, "%s", ss.as_symbol()->as_C_string());
2271 if (ss.at_return_type())
2272 rt = Handle(THREAD, mirror);
2378 vmClasses::MethodHandleNatives_klass(),
2379 vmSymbols::linkMethodHandleConstant_name(),
2380 vmSymbols::linkMethodHandleConstant_signature(),
2381 &args, CHECK_(empty));
2382 return Handle(THREAD, result.get_oop());
2383 }
2384
2385 // Ask Java to run a bootstrap method, in order to create a dynamic call site
2386 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry
2387 // with linkage results being stored back into the bootstrap specifier.
2388 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) {
2389 // Resolve the bootstrap specifier, its name, type, and static arguments
2390 bootstrap_specifier.resolve_bsm(CHECK);
2391
2392 // This should not happen. JDK code should take care of that.
2393 if (bootstrap_specifier.caller() == nullptr || bootstrap_specifier.type_arg().is_null()) {
2394 THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument");
2395 }
2396
2397 bool is_indy = bootstrap_specifier.is_method_call();
2398 objArrayHandle appendix_box;
2399 if (is_indy) {
2400 // Some method calls may require an appendix argument. Arrange to receive it.
2401 appendix_box = oopFactory::new_objArray_handle(vmClasses::Object_klass(), 1, CHECK);
2402 assert(appendix_box->obj_at(0) == nullptr, "");
2403 }
2404
2405 // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, bsm, type, info)
2406 // indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2407 JavaCallArguments args;
2408 args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror()));
2409 args.push_oop(bootstrap_specifier.bsm());
2410 args.push_oop(bootstrap_specifier.name_arg());
2411 args.push_oop(bootstrap_specifier.type_arg());
2412 args.push_oop(bootstrap_specifier.arg_values());
2413 if (is_indy) {
2414 args.push_oop(appendix_box);
2415 }
2416 JavaValue result(T_OBJECT);
2417 JavaCalls::call_static(&result,
2418 vmClasses::MethodHandleNatives_klass(),
2419 is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(),
2420 is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(),
2421 &args, CHECK);
|
1 /*
2 * Copyright (c) 1997, 2026, 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 *
38 #include "classfile/packageEntry.hpp"
39 #include "classfile/placeholders.hpp"
40 #include "classfile/resolutionErrors.hpp"
41 #include "classfile/stringTable.hpp"
42 #include "classfile/symbolTable.hpp"
43 #include "classfile/systemDictionary.hpp"
44 #include "classfile/vmClasses.hpp"
45 #include "classfile/vmSymbols.hpp"
46 #include "gc/shared/gcTraceTime.inline.hpp"
47 #include "interpreter/bootstrapInfo.hpp"
48 #include "jfr/jfrEvents.hpp"
49 #include "jvm.h"
50 #include "logging/log.hpp"
51 #include "logging/logStream.hpp"
52 #include "memory/metaspaceClosure.hpp"
53 #include "memory/oopFactory.hpp"
54 #include "memory/resourceArea.hpp"
55 #include "memory/universe.hpp"
56 #include "oops/access.inline.hpp"
57 #include "oops/constantPool.inline.hpp"
58 #include "oops/fieldStreams.inline.hpp"
59 #include "oops/inlineKlass.inline.hpp"
60 #include "oops/instanceKlass.hpp"
61 #include "oops/klass.inline.hpp"
62 #include "oops/method.inline.hpp"
63 #include "oops/objArrayKlass.hpp"
64 #include "oops/objArrayOop.inline.hpp"
65 #include "oops/oop.inline.hpp"
66 #include "oops/oopHandle.inline.hpp"
67 #include "oops/symbol.hpp"
68 #include "oops/typeArrayKlass.hpp"
69 #include "prims/jvmtiExport.hpp"
70 #include "prims/methodHandles.hpp"
71 #include "runtime/arguments.hpp"
72 #include "runtime/atomicAccess.hpp"
73 #include "runtime/handles.inline.hpp"
74 #include "runtime/java.hpp"
75 #include "runtime/javaCalls.hpp"
76 #include "runtime/mutexLocker.hpp"
77 #include "runtime/os.hpp"
78 #include "runtime/sharedRuntime.hpp"
79 #include "runtime/signature.hpp"
80 #include "runtime/synchronizer.hpp"
81 #include "services/classLoadingService.hpp"
82 #include "services/diagnosticCommand.hpp"
83 #include "services/finalizerService.hpp"
84 #include "services/threadService.hpp"
85 #include "utilities/growableArray.hpp"
86 #include "utilities/macros.hpp"
87 #include "utilities/utf8.hpp"
88 #if INCLUDE_CDS
89 #include "classfile/systemDictionaryShared.hpp"
90 #endif
91 #if INCLUDE_JFR
92 #include "jfr/jfr.hpp"
93 #endif
94
95 class InvokeMethodKey : public StackObj {
96 private:
97 Symbol* _symbol;
172 CHECK_NULL);
173 return result.get_oop();
174 }
175
176 oop SystemDictionary::get_platform_class_loader_impl(TRAPS) {
177 JavaValue result(T_OBJECT);
178 InstanceKlass* class_loader_klass = vmClasses::ClassLoader_klass();
179 JavaCalls::call_static(&result,
180 class_loader_klass,
181 vmSymbols::getPlatformClassLoader_name(),
182 vmSymbols::void_classloader_signature(),
183 CHECK_NULL);
184 return result.get_oop();
185 }
186
187 // Helper function
188 inline ClassLoaderData* class_loader_data(Handle class_loader) {
189 return ClassLoaderData::class_loader_data(class_loader());
190 }
191
192 // These migrated value classes are loaded by the bootstrap class loader but are added to the initiating
193 // loaders automatically so that fields of these types can be found and potentially flattened during
194 // field layout.
195 static void add_migrated_value_classes(ClassLoaderData* cld) {
196 JavaThread* current = JavaThread::current();
197 auto add_klass = [&] (Symbol* classname) {
198 InstanceKlass* ik = SystemDictionary::find_instance_klass(current, classname, Handle(current, nullptr));
199 assert(ik != nullptr, "Must exist");
200 SystemDictionary::add_to_initiating_loader(current, ik, cld);
201 };
202
203 MonitorLocker mu1(SystemDictionary_lock);
204 vmSymbols::migrated_class_names_do(add_klass);
205 }
206
207 ClassLoaderData* SystemDictionary::register_loader(Handle class_loader, bool create_mirror_cld) {
208 if (create_mirror_cld) {
209 // Add a new class loader data to the graph.
210 return ClassLoaderDataGraph::add(class_loader, true);
211 } else {
212 if (class_loader() == nullptr) {
213 return ClassLoaderData::the_null_class_loader_data();
214 } else {
215 bool created = false;
216 ClassLoaderData* cld = ClassLoaderDataGraph::find_or_create(class_loader, created);
217 if (created && Arguments::enable_preview()) {
218 if (CDSConfig::is_using_aot_linked_classes() && java_system_loader() == nullptr) {
219 // We are inside AOTLinkedClassBulkLoader::preload_classes().
220 //
221 // AOTLinkedClassBulkLoader will automatically initiate the loading of all archived
222 // public classes from the boot loader into platform/system loaders, so there's
223 // no need to call add_migrated_value_classes().
224 } else {
225 add_migrated_value_classes(cld);
226 }
227 }
228 return cld;
229 }
230 }
231 }
232
233 void SystemDictionary::set_system_loader(ClassLoaderData *cld) {
234 if (_java_system_loader.is_empty()) {
235 _java_system_loader = cld->class_loader_handle();
236 } else {
237 assert(_java_system_loader.resolve() == cld->class_loader(), "sanity");
238 }
239 }
240
241 void SystemDictionary::set_platform_loader(ClassLoaderData *cld) {
242 if (_java_platform_loader.is_empty()) {
243 _java_platform_loader = cld->class_loader_handle();
244 } else {
245 assert(_java_platform_loader.resolve() == cld->class_loader(), "sanity");
246 }
247 }
248
249 // ----------------------------------------------------------------------------
417 }
418 } else {
419 k = Universe::typeArrayKlass(t);
420 k = k->array_klass(ndims, CHECK_NULL);
421 }
422 return k;
423 }
424
425 static inline void log_circularity_error(Symbol* name, PlaceholderEntry* probe) {
426 LogTarget(Debug, class, load, placeholders) lt;
427 if (lt.is_enabled()) {
428 ResourceMark rm;
429 LogStream ls(lt);
430 ls.print("ClassCircularityError detected for placeholder entry %s", name->as_C_string());
431 probe->print_on(&ls);
432 ls.cr();
433 }
434 }
435
436 // Must be called for any superclass or superinterface resolution
437 // during class definition, or may be called for inline field layout processing
438 // to detect class circularity errors.
439 // superinterface callers:
440 // parse_interfaces - from defineClass
441 // superclass callers:
442 // ClassFileParser - from defineClass
443 // load_shared_class - while loading a class from shared archive
444 // resolve_instance_class_or_null:
445 // via: handle_parallel_super_load
446 // when resolving a class that has an existing placeholder with
447 // a saved superclass [i.e. a defineClass is currently in progress]
448 // If another thread is trying to resolve the class, it must do
449 // superclass checks on its own thread to catch class circularity and
450 // to avoid deadlock.
451 // inline field layout callers:
452 // The field's class must be loaded to determine layout.
453 //
454 // resolve_with_circularity_detection adds a DETECT_CIRCULARITY placeholder to the placeholder table before calling
455 // resolve_instance_class_or_null. ClassCircularityError is detected when a DETECT_CIRCULARITY or LOAD_INSTANCE
456 // placeholder for the same thread, class, and classloader is found.
457 // This can be seen with logging option: -Xlog:class+load+placeholders=debug.
458 //
459 InstanceKlass* SystemDictionary::resolve_with_circularity_detection(Symbol* class_name,
460 Symbol* next_name,
461 Handle class_loader,
462 bool is_superclass,
463 TRAPS) {
464
465 assert(next_name != nullptr, "null superclass for resolving");
466 assert(!Signature::is_array(next_name), "invalid superclass name");
467
468 ClassLoaderData* loader_data = class_loader_data(class_loader);
469
470 if (is_superclass) {
471 InstanceKlass* klassk = loader_data->dictionary()->find_class(THREAD, class_name);
472 if (klassk != nullptr) {
473 // We can come here for two reasons:
474 // (a) RedefineClasses -- the class is already loaded
475 // (b) Rarely, the class might have been loaded by a parallel thread
476 // We can do a quick check against the already assigned superclass's name and loader.
477 InstanceKlass* superk = klassk->super();
478 if (superk != nullptr &&
479 superk->name() == next_name &&
480 superk->class_loader() == class_loader()) {
481 return superk;
482 }
483 }
484 }
485
486 // can't throw error holding a lock
487 bool throw_circularity_error = false;
488 {
489 MutexLocker mu(THREAD, SystemDictionary_lock);
490
491 // Must check ClassCircularity before resolving next_name (superclass, interface, field types or speculatively preloaded argument types).
492 PlaceholderEntry* probe = PlaceholderTable::get_entry(class_name, loader_data);
493 if (probe != nullptr && probe->check_seen_thread(THREAD, PlaceholderTable::DETECT_CIRCULARITY)) {
494 log_circularity_error(class_name, probe);
495 throw_circularity_error = true;
496 }
497
498 // Make sure there's a placeholder for the class_name before resolving.
499 // This is used as a claim that this thread is currently loading superclass/classloader
500 // and for ClassCircularity checks.
501 if (!throw_circularity_error) {
502 // Be careful not to exit resolve_with_circularity_detection without removing this placeholder.
503 PlaceholderEntry* newprobe = PlaceholderTable::find_and_add(class_name,
504 loader_data,
505 PlaceholderTable::DETECT_CIRCULARITY,
506 next_name, THREAD);
507 }
508 }
509
510 if (throw_circularity_error) {
511 ResourceMark rm(THREAD);
512 THROW_MSG_NULL(vmSymbols::java_lang_ClassCircularityError(), class_name->as_C_string());
513 }
514
515 // Resolve the superclass, superinterface, field type or speculatively preloaded argument types and check results on return.
516 InstanceKlass* superk =
517 SystemDictionary::resolve_instance_class_or_null(next_name,
518 class_loader,
519 THREAD);
520
521 // Clean up placeholder entry.
522 {
523 MutexLocker mu(THREAD, SystemDictionary_lock);
524 PlaceholderTable::find_and_remove(class_name, loader_data, PlaceholderTable::DETECT_CIRCULARITY, THREAD);
525 SystemDictionary_lock->notify_all();
526 }
527
528 // Check for pending exception or null superk, and throw exception
529 if (HAS_PENDING_EXCEPTION || superk == nullptr) {
530 handle_resolution_exception(next_name, true, CHECK_NULL);
531 }
532
533 return superk;
534 }
535
933
934 InstanceKlass* SystemDictionary::resolve_from_stream(ClassFileStream* st,
935 Symbol* class_name,
936 Handle class_loader,
937 const ClassLoadInfo& cl_info,
938 TRAPS) {
939 if (cl_info.is_hidden()) {
940 return resolve_hidden_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL);
941 } else {
942 return resolve_class_from_stream(st, class_name, class_loader, cl_info, CHECK_NULL);
943 }
944 }
945
946
947 #if INCLUDE_CDS
948 // Check if a shared class can be loaded by the specific classloader.
949 bool SystemDictionary::is_shared_class_visible(Symbol* class_name,
950 InstanceKlass* ik,
951 PackageEntry* pkg_entry,
952 Handle class_loader) {
953
954 assert(!ModuleEntryTable::javabase_moduleEntry()->is_patched(),
955 "Cannot use sharing if java.base is patched");
956
957 // (1) Check if we are loading into the same loader as in dump time.
958
959 if (ik->defined_by_boot_loader()) {
960 if (class_loader() != nullptr) {
961 return false;
962 }
963 } else if (ik->defined_by_platform_loader()) {
964 if (class_loader() != java_platform_loader()) {
965 return false;
966 }
967 } else if (ik->defined_by_app_loader()) {
968 if (class_loader() != java_system_loader()) {
969 return false;
970 }
971 } else {
972 // ik was loaded by a custom loader during dump time
973 if (class_loader_data(class_loader)->is_builtin_class_loader_data()) {
1089 class_loader, true,
1090 CHECK_false);
1091 if (!check_super) {
1092 return false;
1093 }
1094 }
1095
1096 Array<InstanceKlass*>* interfaces = ik->local_interfaces();
1097 int num_interfaces = interfaces->length();
1098 for (int index = 0; index < num_interfaces; index++) {
1099 bool check_interface = check_shared_class_super_type(ik, interfaces->at(index), class_loader, false,
1100 CHECK_false);
1101 if (!check_interface) {
1102 return false;
1103 }
1104 }
1105
1106 return true;
1107 }
1108
1109 // Pre-load class referred to in non-static null-free instance field. These fields trigger MANDATORY loading.
1110 // Some pre-loading does not fail fatally
1111 bool SystemDictionary::preload_from_null_free_field(InstanceKlass* ik, Handle class_loader, Symbol* sig, int field_index, TRAPS) {
1112 TempNewSymbol name = Signature::strip_envelope(sig);
1113 log_info(class, preload)("Preloading of class %s during loading of shared class %s. "
1114 "Cause: a null-free non-static field is declared with this type",
1115 name->as_C_string(), ik->name()->as_C_string());
1116 InstanceKlass* real_k = SystemDictionary::resolve_with_circularity_detection(ik->name(), name,
1117 class_loader, false, CHECK_false);
1118 if (HAS_PENDING_EXCEPTION) {
1119 log_info(class, preload)("Preloading of class %s during loading of class %s "
1120 "(cause: null-free non-static field) failed: %s",
1121 name->as_C_string(), ik->name()->as_C_string(),
1122 PENDING_EXCEPTION->klass()->name()->as_C_string());
1123 return false; // Exception is still pending
1124 }
1125
1126 InstanceKlass* k = ik->get_inline_type_field_klass_or_null(field_index);
1127 if (real_k != k) {
1128 // oops, the app has substituted a different version of k! Does not fail fatally
1129 log_info(class, preload)("Preloading of class %s during loading of shared class %s "
1130 "(cause: null-free non-static field) failed : "
1131 "app substituted a different version of %s",
1132 name->as_C_string(), ik->name()->as_C_string(),
1133 name->as_C_string());
1134 return false;
1135 }
1136 log_info(class, preload)("Preloading of class %s during loading of shared class %s "
1137 "(cause: null-free non-static field) succeeded",
1138 name->as_C_string(), ik->name()->as_C_string());
1139
1140 assert(real_k != nullptr, "Sanity check");
1141 InstanceKlass::check_can_be_annotated_with_NullRestricted(real_k, ik->name(), CHECK_false);
1142
1143 return true;
1144 }
1145
1146 // Tries to pre-load classes referred to in non-static nullable instance fields if they are found in the
1147 // loadable descriptors attribute. If loading fails, we can fail silently.
1148 void SystemDictionary::try_preload_from_loadable_descriptors(InstanceKlass* ik, Handle class_loader, Symbol* sig, int field_index, TRAPS) {
1149 TempNewSymbol name = Signature::strip_envelope(sig);
1150 if (name != ik->name() && ik->is_class_in_loadable_descriptors_attribute(sig)) {
1151 log_info(class, preload)("Preloading of class %s during loading of shared class %s. "
1152 "Cause: field type in LoadableDescriptors attribute",
1153 name->as_C_string(), ik->name()->as_C_string());
1154 InstanceKlass* real_k = SystemDictionary::resolve_with_circularity_detection(ik->name(), name,
1155 class_loader, false, THREAD);
1156 if (HAS_PENDING_EXCEPTION) {
1157 CLEAR_PENDING_EXCEPTION;
1158 }
1159
1160 InstanceKlass* k = ik->get_inline_type_field_klass_or_null(field_index);
1161 if (real_k != k) {
1162 // oops, the app has substituted a different version of k!
1163 log_info(class, preload)("Preloading of class %s during loading of shared class %s "
1164 "(cause: field type in LoadableDescriptors attribute) failed : "
1165 "app substituted a different version of %s",
1166 name->as_C_string(), ik->name()->as_C_string(),
1167 k->name()->as_C_string());
1168 return;
1169 } else if (real_k != nullptr) {
1170 log_info(class, preload)("Preloading of class %s during loading of shared class %s "
1171 "(cause: field type in LoadableDescriptors attribute) succeeded",
1172 name->as_C_string(), ik->name()->as_C_string());
1173 }
1174 }
1175 }
1176
1177
1178 InstanceKlass* SystemDictionary::load_shared_class(InstanceKlass* ik,
1179 Handle class_loader,
1180 Handle protection_domain,
1181 const ClassFileStream *cfs,
1182 PackageEntry* pkg_entry,
1183 TRAPS) {
1184 assert(ik != nullptr, "sanity");
1185 assert(ik->in_aot_cache(), "sanity");
1186 assert(!ik->is_unshareable_info_restored(), "shared class can be restored only once");
1187 assert(AtomicAccess::add(&ik->_shared_class_load_count, 1) == 1, "shared class loaded more than once");
1188 Symbol* class_name = ik->name();
1189
1190 if (!is_shared_class_visible(class_name, ik, pkg_entry, class_loader)) {
1191 ik->set_shared_loading_failed();
1192 return nullptr;
1193 }
1194
1195 bool check = check_shared_class_super_types(ik, class_loader, CHECK_NULL);
1196 if (!check) {
1197 ik->set_shared_loading_failed();
1198 return nullptr;
1199 }
1200
1201 if (ik->has_inlined_fields()) {
1202 for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
1203 if (fs.access_flags().is_static()) continue;
1204
1205 Symbol* sig = fs.signature();
1206 int field_index = fs.index();
1207
1208 if (fs.is_null_free_inline_type()) {
1209 // A false return means that the class didn't load for other reasons than an exception.
1210 bool check = preload_from_null_free_field(ik, class_loader, sig, field_index, CHECK_NULL);
1211 if (!check) {
1212 ik->set_shared_loading_failed();
1213 return nullptr;
1214 }
1215 } else if (Signature::has_envelope(sig)) {
1216 // Pending exceptions are cleared so we can fail silently
1217 try_preload_from_loadable_descriptors(ik, class_loader, sig, field_index, CHECK_NULL);
1218 }
1219 }
1220 }
1221
1222 InstanceKlass* new_ik = nullptr;
1223 // CFLH check is skipped for VM hidden classes (see KlassFactory::create_from_stream).
1224 // It will be skipped for shared VM hidden lambda proxy classes.
1225 if (!ik->is_hidden()) {
1226 new_ik = KlassFactory::check_shared_class_file_load_hook(
1227 ik, class_name, class_loader, protection_domain, cfs, CHECK_NULL);
1228 }
1229 if (new_ik != nullptr) {
1230 // The class is changed by CFLH. Return the new class. The shared class is
1231 // not used.
1232 return new_ik;
1233 }
1234
1235 // Adjust methods to recover missing data. They need addresses for
1236 // interpreter entry points and their default native method address
1237 // must be reset.
1238
1239 // Shared classes are all currently loaded by either the bootstrap or
1240 // internal parallel class loaders, so this will never cause a deadlock
1241 // on a custom class loader lock.
1818 }
1819 }
1820
1821 // Update class loader data dictionary - done after check_constraint and add_to_hierarchy
1822 // have been called.
1823 void SystemDictionary::update_dictionary(JavaThread* current,
1824 InstanceKlass* k,
1825 ClassLoaderData* loader_data) {
1826 MonitorLocker mu1(SystemDictionary_lock);
1827
1828 // Make a new dictionary entry.
1829 Symbol* name = k->name();
1830 Dictionary* dictionary = loader_data->dictionary();
1831 InstanceKlass* sd_check = dictionary->find_class(current, name);
1832 if (sd_check == nullptr) {
1833 dictionary->add_klass(current, name, k);
1834 }
1835 mu1.notify_all();
1836 }
1837
1838 // Indicate that loader_data has initiated the loading of class k, which
1839 // has already been defined by a parent loader.
1840 // This API is used by AOTLinkedClassBulkLoader and to register boxing
1841 // classes from java.lang in all class loaders to enable more value
1842 // classes optimizations
1843 void SystemDictionary::add_to_initiating_loader(JavaThread* current,
1844 InstanceKlass* k,
1845 ClassLoaderData* loader_data) {
1846 assert_locked_or_safepoint(SystemDictionary_lock);
1847 Symbol* name = k->name();
1848 Dictionary* dictionary = loader_data->dictionary();
1849 assert(k->is_loaded(), "must be");
1850 assert(k->class_loader_data() != loader_data, "only for classes defined by a parent loader");
1851 if (dictionary->find_class(current, name) == nullptr) {
1852 dictionary->add_klass(current, name, k);
1853 }
1854 }
1855
1856 // Try to find a class name using the loader constraints. The
1857 // loader constraints might know about a class that isn't fully loaded
1858 // yet and these will be ignored.
1859 Klass* SystemDictionary::find_constrained_instance_or_array_klass(
1860 Thread* current, Symbol* class_name, Handle class_loader) {
1861
1862 // First see if it has been loaded directly.
1863 Klass* klass = find_instance_or_array_klass(current, class_name, class_loader);
1864 if (klass != nullptr)
1865 return klass;
1866
1867 // Now look to see if it has been loaded elsewhere, and is subject to
1868 // a loader constraint that would require this loader to return the
1869 // klass that is already loaded.
1870 if (Signature::is_array(class_name)) {
1871 // For array classes, their Klass*s are not kept in the
1872 // constraint table. The element Klass*s are.
1873 SignatureStream ss(class_name, false);
1874 int ndims = ss.skip_array_prefix(); // skip all '['s
2206 if (!m->has_compiled_code()) {
2207 ResourceMark rm(THREAD);
2208 vm_exit_during_initialization(err_msg("Failed to initialize method %s", m->external_name()));
2209 }
2210 }
2211
2212 // There's no need to grab the InvokeMethodIntrinsicTable_lock, as we are still very early in
2213 // VM start-up -- in init_globals2() -- so we are still running a single Java thread. It's not
2214 // possible to have a contention.
2215 const int iid_as_int = vmIntrinsics::as_int(m->intrinsic_id());
2216 InvokeMethodKey key(m->signature(), iid_as_int);
2217 bool created = _invoke_method_intrinsic_table->put(key, m());
2218 assert(created, "unexpected contention");
2219 }
2220 }
2221 #endif // INCLUDE_CDS
2222
2223 // Helper for unpacking the return value from linkMethod and linkCallSite.
2224 static Method* unpack_method_and_appendix(Handle mname,
2225 Klass* accessing_klass,
2226 refArrayHandle appendix_box,
2227 Handle* appendix_result,
2228 TRAPS) {
2229 if (mname.not_null()) {
2230 Method* m = java_lang_invoke_MemberName::vmtarget(mname());
2231 if (m != nullptr) {
2232 oop appendix = appendix_box->obj_at(0);
2233 LogTarget(Info, methodhandles) lt;
2234 if (lt.develop_is_enabled()) {
2235 ResourceMark rm(THREAD);
2236 LogStream ls(lt);
2237 ls.print("Linked method=" INTPTR_FORMAT ": ", p2i(m));
2238 m->print_on(&ls);
2239 if (appendix != nullptr) { ls.print("appendix = "); appendix->print_on(&ls); }
2240 ls.cr();
2241 }
2242
2243 (*appendix_result) = Handle(THREAD, appendix);
2244 // the target is stored in the cpCache and if a reference to this
2245 // MemberName is dropped we need a way to make sure the
2246 // class_loader containing this method is kept alive.
2249 this_key->record_dependency(m->method_holder());
2250 return mh();
2251 }
2252 }
2253 THROW_MSG_NULL(vmSymbols::java_lang_LinkageError(), "bad value from MethodHandleNatives");
2254 }
2255
2256 Method* SystemDictionary::find_method_handle_invoker(Klass* klass,
2257 Symbol* name,
2258 Symbol* signature,
2259 Klass* accessing_klass,
2260 Handle* appendix_result,
2261 TRAPS) {
2262 guarantee(THREAD->can_call_java(), "");
2263 Handle method_type =
2264 SystemDictionary::find_method_handle_type(signature, accessing_klass, CHECK_NULL);
2265
2266 int ref_kind = JVM_REF_invokeVirtual;
2267 oop name_oop = StringTable::intern(name, CHECK_NULL);
2268 Handle name_str (THREAD, name_oop);
2269 refArrayHandle appendix_box = oopFactory::new_refArray_handle(vmClasses::Object_klass(), 1, CHECK_NULL);
2270 assert(appendix_box->obj_at(0) == nullptr, "");
2271
2272 // This should not happen. JDK code should take care of that.
2273 if (accessing_klass == nullptr || method_type.is_null()) {
2274 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "bad invokehandle");
2275 }
2276
2277 // call java.lang.invoke.MethodHandleNatives::linkMethod(... String, MethodType) -> MemberName
2278 JavaCallArguments args;
2279 args.push_oop(Handle(THREAD, accessing_klass->java_mirror()));
2280 args.push_int(ref_kind);
2281 args.push_oop(Handle(THREAD, klass->java_mirror()));
2282 args.push_oop(name_str);
2283 args.push_oop(method_type);
2284 args.push_oop(appendix_box);
2285 JavaValue result(T_OBJECT);
2286 JavaCalls::call_static(&result,
2287 vmClasses::MethodHandleNatives_klass(),
2288 vmSymbols::linkMethod_name(),
2289 vmSymbols::linkMethod_signature(),
2360 {
2361 MutexLocker ml(THREAD, InvokeMethodTypeTable_lock);
2362 o = _invoke_method_type_table->get(signature);
2363 }
2364
2365 if (o != nullptr) {
2366 oop mt = o->resolve();
2367 assert(java_lang_invoke_MethodType::is_instance(mt), "");
2368 return Handle(THREAD, mt);
2369 } else if (!THREAD->can_call_java()) {
2370 warning("SystemDictionary::find_method_handle_type called from compiler thread"); // FIXME
2371 return Handle(); // do not attempt from within compiler, unless it was cached
2372 }
2373
2374 Handle class_loader;
2375 if (accessing_klass != nullptr) {
2376 class_loader = Handle(THREAD, accessing_klass->class_loader());
2377 }
2378 bool can_be_cached = true;
2379 int npts = ArgumentCount(signature).size();
2380 refArrayHandle pts = oopFactory::new_refArray_handle(vmClasses::Class_klass(), npts, CHECK_(empty));
2381 int arg = 0;
2382 Handle rt; // the return type from the signature
2383 ResourceMark rm(THREAD);
2384 for (SignatureStream ss(signature); !ss.is_done(); ss.next()) {
2385 oop mirror = nullptr;
2386 if (can_be_cached) {
2387 // Use neutral class loader to lookup candidate classes to be placed in the cache.
2388 mirror = ss.as_java_mirror(Handle(), SignatureStream::ReturnNull, CHECK_(empty));
2389 if (mirror == nullptr || (ss.is_reference() && !is_always_visible_class(mirror))) {
2390 // Fall back to accessing_klass context.
2391 can_be_cached = false;
2392 }
2393 }
2394 if (!can_be_cached) {
2395 // Resolve, throwing a real error if it doesn't work.
2396 mirror = ss.as_java_mirror(class_loader, SignatureStream::NCDFError, CHECK_(empty));
2397 }
2398 assert(mirror != nullptr, "%s", ss.as_symbol()->as_C_string());
2399 if (ss.at_return_type())
2400 rt = Handle(THREAD, mirror);
2506 vmClasses::MethodHandleNatives_klass(),
2507 vmSymbols::linkMethodHandleConstant_name(),
2508 vmSymbols::linkMethodHandleConstant_signature(),
2509 &args, CHECK_(empty));
2510 return Handle(THREAD, result.get_oop());
2511 }
2512
2513 // Ask Java to run a bootstrap method, in order to create a dynamic call site
2514 // while linking an invokedynamic op, or compute a constant for Dynamic_info CP entry
2515 // with linkage results being stored back into the bootstrap specifier.
2516 void SystemDictionary::invoke_bootstrap_method(BootstrapInfo& bootstrap_specifier, TRAPS) {
2517 // Resolve the bootstrap specifier, its name, type, and static arguments
2518 bootstrap_specifier.resolve_bsm(CHECK);
2519
2520 // This should not happen. JDK code should take care of that.
2521 if (bootstrap_specifier.caller() == nullptr || bootstrap_specifier.type_arg().is_null()) {
2522 THROW_MSG(vmSymbols::java_lang_InternalError(), "Invalid bootstrap method invocation with no caller or type argument");
2523 }
2524
2525 bool is_indy = bootstrap_specifier.is_method_call();
2526 refArrayHandle appendix_box;
2527 if (is_indy) {
2528 // Some method calls may require an appendix argument. Arrange to receive it.
2529 appendix_box = oopFactory::new_refArray_handle(vmClasses::Object_klass(), 1, CHECK);
2530 assert(appendix_box->obj_at(0) == nullptr, "");
2531 }
2532
2533 // call condy: java.lang.invoke.MethodHandleNatives::linkDynamicConstant(caller, bsm, type, info)
2534 // indy: java.lang.invoke.MethodHandleNatives::linkCallSite(caller, bsm, name, mtype, info, &appendix)
2535 JavaCallArguments args;
2536 args.push_oop(Handle(THREAD, bootstrap_specifier.caller_mirror()));
2537 args.push_oop(bootstrap_specifier.bsm());
2538 args.push_oop(bootstrap_specifier.name_arg());
2539 args.push_oop(bootstrap_specifier.type_arg());
2540 args.push_oop(bootstrap_specifier.arg_values());
2541 if (is_indy) {
2542 args.push_oop(appendix_box);
2543 }
2544 JavaValue result(T_OBJECT);
2545 JavaCalls::call_static(&result,
2546 vmClasses::MethodHandleNatives_klass(),
2547 is_indy ? vmSymbols::linkCallSite_name() : vmSymbols::linkDynamicConstant_name(),
2548 is_indy ? vmSymbols::linkCallSite_signature() : vmSymbols::linkDynamicConstant_signature(),
2549 &args, CHECK);
|