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/aotClassInitializer.hpp"
26 #include "cds/aotConstantPoolResolver.hpp"
27 #include "cds/aotMetaspace.hpp"
28 #include "cds/cdsConfig.hpp"
29 #include "cds/classListParser.hpp"
30 #include "cds/classListWriter.hpp"
31 #include "cds/dynamicArchive.hpp"
32 #include "cds/heapShared.hpp"
33 #include "cds/lambdaFormInvokers.hpp"
34 #include "cds/lambdaProxyClassDictionary.hpp"
35 #include "classfile/classFileStream.hpp"
36 #include "classfile/classLoader.inline.hpp"
37 #include "classfile/classLoaderData.inline.hpp"
38 #include "classfile/classLoadInfo.hpp"
39 #include "classfile/javaAssertions.hpp"
40 #include "classfile/javaClasses.inline.hpp"
41 #include "classfile/moduleEntry.hpp"
42 #include "classfile/modules.hpp"
43 #include "classfile/packageEntry.hpp"
44 #include "classfile/stringTable.hpp"
45 #include "classfile/symbolTable.hpp"
46 #include "classfile/systemDictionary.hpp"
47 #include "classfile/vmClasses.hpp"
48 #include "classfile/vmSymbols.hpp"
49 #include "gc/shared/collectedHeap.inline.hpp"
50 #include "interpreter/bytecode.hpp"
51 #include "interpreter/bytecodeUtils.hpp"
52 #include "jfr/jfrEvents.hpp"
53 #include "jvm.h"
54 #include "logging/log.hpp"
55 #include "memory/oopFactory.hpp"
56 #include "memory/referenceType.hpp"
57 #include "memory/resourceArea.hpp"
58 #include "memory/universe.hpp"
59 #include "oops/access.inline.hpp"
60 #include "oops/constantPool.hpp"
61 #include "oops/fieldStreams.inline.hpp"
62 #include "oops/instanceKlass.hpp"
63 #include "oops/klass.inline.hpp"
64 #include "oops/method.hpp"
65 #include "oops/objArrayKlass.hpp"
66 #include "oops/objArrayOop.inline.hpp"
67 #include "oops/oop.inline.hpp"
68 #include "oops/recordComponent.hpp"
69 #include "prims/foreignGlobals.hpp"
70 #include "prims/jvm_misc.hpp"
71 #include "prims/jvmtiExport.hpp"
72 #include "prims/jvmtiThreadState.inline.hpp"
73 #include "prims/stackwalk.hpp"
74 #include "runtime/arguments.hpp"
75 #include "runtime/atomicAccess.hpp"
76 #include "runtime/continuation.hpp"
77 #include "runtime/deoptimization.hpp"
78 #include "runtime/globals_extension.hpp"
79 #include "runtime/handles.inline.hpp"
80 #include "runtime/handshake.hpp"
81 #include "runtime/init.hpp"
82 #include "runtime/interfaceSupport.inline.hpp"
83 #include "runtime/java.hpp"
84 #include "runtime/javaCalls.hpp"
85 #include "runtime/javaThread.hpp"
86 #include "runtime/jfieldIDWorkaround.hpp"
87 #include "runtime/jniHandles.inline.hpp"
88 #include "runtime/os.inline.hpp"
89 #include "runtime/osThread.hpp"
90 #include "runtime/perfData.inline.hpp"
91 #include "runtime/reflection.hpp"
92 #include "runtime/synchronizer.hpp"
93 #include "runtime/threadIdentifier.hpp"
94 #include "runtime/threadSMR.hpp"
95 #include "runtime/vframe.inline.hpp"
96 #include "runtime/vm_version.hpp"
97 #include "runtime/vmOperations.hpp"
98 #include "services/attachListener.hpp"
99 #include "services/management.hpp"
100 #include "services/threadService.hpp"
101 #include "utilities/checkedCast.hpp"
102 #include "utilities/copy.hpp"
103 #include "utilities/defaultStream.hpp"
104 #include "utilities/dtrace.hpp"
105 #include "utilities/events.hpp"
106 #include "utilities/macros.hpp"
107 #include "utilities/utf8.hpp"
108 #include "utilities/zipLibrary.hpp"
109 #if INCLUDE_CDS
110 #include "classfile/systemDictionaryShared.hpp"
111 #endif
112 #if INCLUDE_JFR
113 #include "jfr/jfr.hpp"
114 #endif
115 #if INCLUDE_MANAGEMENT
116 #include "services/finalizerService.hpp"
117 #endif
118 #ifdef LINUX
119 #include "osContainer_linux.hpp"
120 #endif
121
122 #include <errno.h>
123
124 /*
125 NOTE about use of any ctor or function call that can trigger a safepoint/GC:
126 such ctors and calls MUST NOT come between an oop declaration/init and its
127 usage because if objects are move this may cause various memory stomps, bus
128 errors and segfaults. Here is a cookbook for causing so called "naked oop
129 failures":
130
131 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields<etc> {
132 // Object address to be held directly in mirror & not visible to GC
133 oop mirror = JNIHandles::resolve_non_null(ofClass);
134
135 // If this ctor can hit a safepoint, moving objects around, then
136 ComplexConstructor foo;
137
138 // Boom! mirror may point to JUNK instead of the intended object
139 (some dereference of mirror)
140
141 // Here's another call that may block for GC, making mirror stale
142 MutexLocker ml(some_lock);
143
144 // And here's an initializer that can result in a stale oop
145 // all in one step.
146 oop o = call_that_can_throw_exception(TRAPS);
147
148
149 The solution is to keep the oop declaration BELOW the ctor or function
150 call that might cause a GC, do another resolve to reassign the oop, or
151 consider use of a Handle instead of an oop so there is immunity from object
152 motion. But note that the "QUICK" entries below do not have a handlemark
153 and thus can only support use of handles passed in.
154 */
155
156 extern void trace_class_resolution(Klass* to_class) {
157 ResourceMark rm;
158 int line_number = -1;
159 const char * source_file = nullptr;
160 const char * trace = "explicit";
161 InstanceKlass* caller = nullptr;
162 JavaThread* jthread = JavaThread::current();
163 if (jthread->has_last_Java_frame()) {
164 vframeStream vfst(jthread);
165
166 // Scan up the stack skipping ClassLoader frames.
167 Method* last_caller = nullptr;
168
169 while (!vfst.at_end()) {
170 Method* m = vfst.method();
171 if (!vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass())) {
172 break;
173 }
174 last_caller = m;
175 vfst.next();
176 }
177 // if this is called from Class.forName0 and that is called from Class.forName,
178 // then print the caller of Class.forName. If this is Class.loadClass, then print
179 // that caller, otherwise keep quiet since this should be picked up elsewhere.
180 bool found_it = false;
181 if (!vfst.at_end() &&
182 vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
183 vfst.method()->name() == vmSymbols::forName0_name()) {
184 vfst.next();
185 if (!vfst.at_end() &&
186 vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
187 vfst.method()->name() == vmSymbols::forName_name()) {
188 vfst.next();
189 found_it = true;
190 }
191 } else if (last_caller != nullptr &&
192 last_caller->method_holder()->name() ==
193 vmSymbols::java_lang_ClassLoader() &&
194 last_caller->name() == vmSymbols::loadClass_name()) {
195 found_it = true;
196 } else if (!vfst.at_end()) {
197 if (vfst.method()->is_native()) {
198 // JNI call
199 found_it = true;
200 }
201 }
202 if (found_it && !vfst.at_end()) {
203 // found the caller
204 caller = vfst.method()->method_holder();
205 line_number = vfst.method()->line_number_from_bci(vfst.bci());
206 if (line_number == -1) {
207 // show method name if it's a native method
208 trace = vfst.method()->name_and_sig_as_C_string();
209 }
210 Symbol* s = caller->source_file_name();
211 if (s != nullptr) {
212 source_file = s->as_C_string();
213 }
214 }
215 }
216 if (caller != nullptr) {
217 if (to_class != caller) {
218 const char * from = caller->external_name();
219 const char * to = to_class->external_name();
220 // print in a single call to reduce interleaving between threads
221 if (source_file != nullptr) {
222 log_debug(class, resolve)("%s %s %s:%d (%s)", from, to, source_file, line_number, trace);
223 } else {
224 log_debug(class, resolve)("%s %s (%s)", from, to, trace);
225 }
226 }
227 }
228 }
229
230 // java.lang.System //////////////////////////////////////////////////////////////////////
231
232
233 JVM_LEAF_PROF(jboolean, JVM_AOTIsTraining, JVM_AOTIsTraining(JNIEnv *env))
234 #if INCLUDE_CDS
235 return AOTMetaspace::is_recording_preimage_static_archive();
236 #else
237 return JNI_FALSE;
238 #endif // INCLUDE_CDS
239 JVM_END
240
241 JVM_ENTRY_PROF(jboolean, JVM_AOTEndTraining, JVM_AOTEndTraining(JNIEnv *env))
242 #if INCLUDE_CDS
243 if (AOTMetaspace::is_recording_preimage_static_archive()) {
244 AOTMetaspace::dump_static_archive(THREAD);
245 return JNI_TRUE;
246 }
247 return JNI_FALSE;
248 #else
249 return JNI_FALSE;
250 #endif // INCLUDE_CDS
251 JVM_END
252
253 JVM_ENTRY_PROF(jstring, JVM_AOTGetMode, JVM_AOTGetMode(JNIEnv *env))
254 HandleMark hm(THREAD);
255 #if INCLUDE_CDS
256 const char* mode = AOTMode == nullptr ? "auto" : AOTMode;
257 Handle h = java_lang_String::create_from_platform_dependent_str(mode, CHECK_NULL);
258 return (jstring) JNIHandles::make_local(THREAD, h());
259 #else
260 return nullptr;
261 #endif // INCLUDE_CDS
262 JVM_END
263
264 JVM_LEAF_PROF(jlong, JVM_AOTGetRecordingDuration, JVM_AOTGetRecordingDuration(JNIEnv *env))
265 #if INCLUDE_CDS
266 return AOTMetaspace::get_preimage_static_archive_recording_duration();
267 #else
268 return 0;
269 #endif // INCLUDE_CDS
270 JVM_END
271
272 JVM_LEAF_PROF(jlong, JVM_CurrentTimeMillis, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored))
273 return os::javaTimeMillis();
274 JVM_END
275
276 JVM_LEAF_PROF(jlong, JVM_NanoTime, JVM_NanoTime(JNIEnv *env, jclass ignored))
277 return os::javaTimeNanos();
278 JVM_END
279
280 // The function below is actually exposed by jdk.internal.misc.VM and not
281 // java.lang.System, but we choose to keep it here so that it stays next
282 // to JVM_CurrentTimeMillis and JVM_NanoTime
283
284 const jlong MAX_DIFF_SECS = CONST64(0x0100000000); // 2^32
285 const jlong MIN_DIFF_SECS = -MAX_DIFF_SECS; // -2^32
286
287 JVM_LEAF_PROF(jlong, JVM_GetNanoTimeAdjustment, JVM_GetNanoTimeAdjustment(JNIEnv *env, jclass ignored, jlong offset_secs))
288 jlong seconds;
289 jlong nanos;
290
291 os::javaTimeSystemUTC(seconds, nanos);
292
293 // We're going to verify that the result can fit in a long.
294 // For that we need the difference in seconds between 'seconds'
295 // and 'offset_secs' to be such that:
296 // |seconds - offset_secs| < (2^63/10^9)
297 // We're going to approximate 10^9 ~< 2^30 (1000^3 ~< 1024^3)
298 // which makes |seconds - offset_secs| < 2^33
299 // and we will prefer +/- 2^32 as the maximum acceptable diff
300 // as 2^32 has a more natural feel than 2^33...
301 //
302 // So if |seconds - offset_secs| >= 2^32 - we return a special
303 // sentinel value (-1) which the caller should take as an
304 // exception value indicating that the offset given to us is
305 // too far from range of the current time - leading to too big
306 // a nano adjustment. The caller is expected to recover by
307 // computing a more accurate offset and calling this method
308 // again. (For the record 2^32 secs is ~136 years, so that
309 // should rarely happen)
310 //
311 jlong diff = seconds - offset_secs;
312 if (diff >= MAX_DIFF_SECS || diff <= MIN_DIFF_SECS) {
313 return -1; // sentinel value: the offset is too far off the target
314 }
315
316 // return the adjustment. If you compute a time by adding
317 // this number of nanoseconds along with the number of seconds
318 // in the offset you should get the current UTC time.
319 return (diff * (jlong)1000000000) + nanos;
320 JVM_END
321
322 JVM_ENTRY_PROF(void, JVM_ArrayCopy, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos,
323 jobject dst, jint dst_pos, jint length))
324 // Check if we have null pointers
325 if (src == nullptr || dst == nullptr) {
326 THROW(vmSymbols::java_lang_NullPointerException());
327 }
328 arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));
329 arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));
330 assert(oopDesc::is_oop(s), "JVM_ArrayCopy: src not an oop");
331 assert(oopDesc::is_oop(d), "JVM_ArrayCopy: dst not an oop");
332 // Do copy
333 s->klass()->copy_array(s, src_pos, d, dst_pos, length, thread);
334 JVM_END
335
336
337 static void set_property(Handle props, const char* key, const char* value, TRAPS) {
338 JavaValue r(T_OBJECT);
339 // public synchronized Object put(Object key, Object value);
340 HandleMark hm(THREAD);
341 Handle key_str = java_lang_String::create_from_platform_dependent_str(key, CHECK);
342 Handle value_str = java_lang_String::create_from_platform_dependent_str((value != nullptr ? value : ""), CHECK);
343 JavaCalls::call_virtual(&r,
344 props,
345 vmClasses::Properties_klass(),
346 vmSymbols::put_name(),
347 vmSymbols::object_object_object_signature(),
348 key_str,
349 value_str,
350 THREAD);
351 }
352
353
354 #define PUTPROP(props, name, value) set_property((props), (name), (value), CHECK_(properties));
355
356 /*
357 * Return all of the system properties in a Java String array with alternating
358 * names and values from the jvm SystemProperty.
359 * Which includes some internal and all commandline -D defined properties.
360 */
361 JVM_ENTRY_PROF(jobjectArray, JVM_GetProperties, JVM_GetProperties(JNIEnv *env))
362 ResourceMark rm(THREAD);
363 HandleMark hm(THREAD);
364 int ndx = 0;
365 int fixedCount = 2;
366
367 SystemProperty* p = Arguments::system_properties();
368 int count = Arguments::PropertyList_count(p);
369
370 // Allocate result String array
371 InstanceKlass* ik = vmClasses::String_klass();
372 objArrayOop r = oopFactory::new_objArray(ik, (count + fixedCount) * 2, CHECK_NULL);
373 objArrayHandle result_h(THREAD, r);
374
375 while (p != nullptr) {
376 const char * key = p->key();
377 if (strcmp(key, "sun.nio.MaxDirectMemorySize") != 0) {
378 const char * value = p->value();
379 Handle key_str = java_lang_String::create_from_platform_dependent_str(key, CHECK_NULL);
380 Handle value_str = java_lang_String::create_from_platform_dependent_str((value != nullptr ? value : ""), CHECK_NULL);
381 result_h->obj_at_put(ndx * 2, key_str());
382 result_h->obj_at_put(ndx * 2 + 1, value_str());
383 ndx++;
384 }
385 p = p->next();
386 }
387
388 // Convert the -XX:MaxDirectMemorySize= command line flag
389 // to the sun.nio.MaxDirectMemorySize property.
390 // Do this after setting user properties to prevent people
391 // from setting the value with a -D option, as requested.
392 // Leave empty if not supplied
393 if (!FLAG_IS_DEFAULT(MaxDirectMemorySize)) {
394 char as_chars[256];
395 jio_snprintf(as_chars, sizeof(as_chars), JULONG_FORMAT, MaxDirectMemorySize);
396 Handle key_str = java_lang_String::create_from_platform_dependent_str("sun.nio.MaxDirectMemorySize", CHECK_NULL);
397 Handle value_str = java_lang_String::create_from_platform_dependent_str(as_chars, CHECK_NULL);
398 result_h->obj_at_put(ndx * 2, key_str());
399 result_h->obj_at_put(ndx * 2 + 1, value_str());
400 ndx++;
401 }
402
403 // JVM monitoring and management support
404 // Add the sun.management.compiler property for the compiler's name
405 {
406 #undef CSIZE
407 #if defined(_LP64)
408 #define CSIZE "64-Bit "
409 #else
410 #define CSIZE
411 #endif // 64bit
412
413 #if COMPILER1_AND_COMPILER2
414 const char* compiler_name = "HotSpot " CSIZE "Tiered Compilers";
415 #else
416 #if defined(COMPILER1)
417 const char* compiler_name = "HotSpot " CSIZE "Client Compiler";
418 #elif defined(COMPILER2)
419 const char* compiler_name = "HotSpot " CSIZE "Server Compiler";
420 #elif INCLUDE_JVMCI
421 #error "INCLUDE_JVMCI should imply COMPILER1_OR_COMPILER2"
422 #else
423 const char* compiler_name = "";
424 #endif // compilers
425 #endif // COMPILER1_AND_COMPILER2
426
427 if (*compiler_name != '\0' &&
428 (Arguments::mode() != Arguments::_int)) {
429 Handle key_str = java_lang_String::create_from_platform_dependent_str("sun.management.compiler", CHECK_NULL);
430 Handle value_str = java_lang_String::create_from_platform_dependent_str(compiler_name, CHECK_NULL);
431 result_h->obj_at_put(ndx * 2, key_str());
432 result_h->obj_at_put(ndx * 2 + 1, value_str());
433 ndx++;
434 }
435 }
436
437 return (jobjectArray) JNIHandles::make_local(THREAD, result_h());
438 JVM_END
439
440
441 /*
442 * Return the temporary directory that the VM uses for the attach
443 * and perf data files.
444 *
445 * It is important that this directory is well-known and the
446 * same for all VM instances. It cannot be affected by configuration
447 * variables such as java.io.tmpdir.
448 */
449 JVM_ENTRY_PROF(jstring, JVM_GetTemporaryDirectory, JVM_GetTemporaryDirectory(JNIEnv *env))
450 HandleMark hm(THREAD);
451 const char* temp_dir = os::get_temp_directory();
452 Handle h = java_lang_String::create_from_platform_dependent_str(temp_dir, CHECK_NULL);
453 return (jstring) JNIHandles::make_local(THREAD, h());
454 JVM_END
455
456
457 // java.lang.Runtime /////////////////////////////////////////////////////////////////////////
458
459 extern volatile jint vm_created;
460
461 JVM_ENTRY_NO_ENV_PROF(void, JVM_BeforeHalt, JVM_BeforeHalt())
462 EventShutdown event;
463 if (event.should_commit()) {
464 event.set_reason("Shutdown requested from Java");
465 event.commit();
466 }
467 JVM_END
468
469
470 JVM_ENTRY_NO_ENV_PROF(void, JVM_Halt, JVM_Halt(jint code))
471 before_exit(thread, true);
472 vm_exit(code);
473 JVM_END
474
475
476 JVM_ENTRY_NO_ENV_PROF(void, JVM_GC, JVM_GC(void))
477 if (!DisableExplicitGC) {
478 EventSystemGC event;
479 event.set_invokedConcurrent(ExplicitGCInvokesConcurrent);
480 Universe::heap()->collect(GCCause::_java_lang_system_gc);
481 event.commit();
482 }
483 JVM_END
484
485
486 JVM_LEAF_PROF(jlong, JVM_MaxObjectInspectionAge, JVM_MaxObjectInspectionAge(void))
487 return Universe::heap()->millis_since_last_whole_heap_examined();
488 JVM_END
489
490
491 static inline jlong convert_size_t_to_jlong(size_t val) {
492 // In the 64-bit vm, a size_t can overflow a jlong (which is signed).
493 NOT_LP64 (return (jlong)val;)
494 LP64_ONLY(return (jlong)MIN2(val, (size_t)max_jlong);)
495 }
496
497 JVM_ENTRY_NO_ENV_PROF(jlong, JVM_TotalMemory, JVM_TotalMemory(void))
498 size_t n = Universe::heap()->capacity();
499 return convert_size_t_to_jlong(n);
500 JVM_END
501
502
503 JVM_ENTRY_NO_ENV_PROF(jlong, JVM_FreeMemory, JVM_FreeMemory(void))
504 size_t n = Universe::heap()->unused();
505 return convert_size_t_to_jlong(n);
506 JVM_END
507
508
509 JVM_ENTRY_NO_ENV_PROF(jlong, JVM_MaxMemory, JVM_MaxMemory(void))
510 size_t n = Universe::heap()->max_capacity();
511 return convert_size_t_to_jlong(n);
512 JVM_END
513
514
515 JVM_ENTRY_NO_ENV_PROF(jint, JVM_ActiveProcessorCount, JVM_ActiveProcessorCount(void))
516 return os::active_processor_count();
517 JVM_END
518
519 JVM_LEAF_PROF(jboolean, JVM_IsUseContainerSupport, JVM_IsUseContainerSupport(void))
520 #ifdef LINUX
521 if (UseContainerSupport) {
522 return JNI_TRUE;
523 }
524 #endif
525 return JNI_FALSE;
526 JVM_END
527
528 JVM_LEAF(jboolean, JVM_IsContainerized(void))
529 #ifdef LINUX
530 if (OSContainer::is_containerized()) {
531 return JNI_TRUE;
532 }
533 #endif
534 return JNI_FALSE;
535 JVM_END
536
537 // java.lang.Throwable //////////////////////////////////////////////////////
538
539 JVM_ENTRY_PROF(void, JVM_FillInStackTrace, JVM_FillInStackTrace(JNIEnv *env, jobject receiver))
540 Handle exception(thread, JNIHandles::resolve_non_null(receiver));
541 java_lang_Throwable::fill_in_stack_trace(exception);
542 JVM_END
543
544 // java.lang.NullPointerException ///////////////////////////////////////////
545
546 JVM_ENTRY_PROF(jstring, JVM_GetExtendedNPEMessage, JVM_GetExtendedNPEMessage(JNIEnv *env, jthrowable throwable))
547 if (!ShowCodeDetailsInExceptionMessages) return nullptr;
548
549 oop exc = JNIHandles::resolve_non_null(throwable);
550
551 Method* method;
552 int bci;
553 if (!java_lang_Throwable::get_top_method_and_bci(exc, &method, &bci)) {
554 return nullptr;
555 }
556 if (method->is_native()) {
557 return nullptr;
558 }
559
560 stringStream ss;
561 bool ok = BytecodeUtils::get_NPE_message_at(&ss, method, bci);
562 if (ok) {
563 oop result = java_lang_String::create_oop_from_str(ss.base(), CHECK_NULL);
564 return (jstring) JNIHandles::make_local(THREAD, result);
565 } else {
566 return nullptr;
567 }
568 JVM_END
569
570 // java.lang.StackTraceElement //////////////////////////////////////////////
571
572
573 JVM_ENTRY_PROF(void, JVM_InitStackTraceElementArray, JVM_InitStackTraceElementArray(JNIEnv *env, jobjectArray elements, jobject backtrace, jint depth))
574 Handle backtraceh(THREAD, JNIHandles::resolve(backtrace));
575 objArrayOop st = objArrayOop(JNIHandles::resolve(elements));
576 objArrayHandle stack_trace(THREAD, st);
577 // Fill in the allocated stack trace
578 java_lang_Throwable::get_stack_trace_elements(depth, backtraceh, stack_trace, CHECK);
579 JVM_END
580
581
582 JVM_ENTRY_PROF(void, JVM_InitStackTraceElement, JVM_InitStackTraceElement(JNIEnv* env, jobject element, jobject stackFrameInfo))
583 Handle stack_frame_info(THREAD, JNIHandles::resolve_non_null(stackFrameInfo));
584 Handle stack_trace_element(THREAD, JNIHandles::resolve_non_null(element));
585 java_lang_StackFrameInfo::to_stack_trace_element(stack_frame_info, stack_trace_element, CHECK);
586 JVM_END
587
588
589 // java.lang.StackWalker //////////////////////////////////////////////////////
590 JVM_ENTRY_PROF(void, JVM_ExpandStackFrameInfo, JVM_ExpandStackFrameInfo(JNIEnv *env, jobject obj))
591 Handle stack_frame_info(THREAD, JNIHandles::resolve_non_null(obj));
592
593 bool have_name = (java_lang_StackFrameInfo::name(stack_frame_info()) != nullptr);
594 bool have_type = (java_lang_StackFrameInfo::type(stack_frame_info()) != nullptr);
595 Method* method = java_lang_StackFrameInfo::get_method(stack_frame_info());
596 if (!have_name) {
597 oop name = StringTable::intern(method->name(), CHECK);
598 java_lang_StackFrameInfo::set_name(stack_frame_info(), name);
599 }
600 if (!have_type) {
601 Handle type = java_lang_String::create_from_symbol(method->signature(), CHECK);
602 java_lang_StackFrameInfo::set_type(stack_frame_info(), type());
603 }
604 JVM_END
605
606 JVM_ENTRY_PROF(jobject, JVM_CallStackWalk, JVM_CallStackWalk(JNIEnv *env, jobject stackStream, jint mode,
607 jint skip_frames, jobject contScope, jobject cont,
608 jint buffer_size, jint start_index, jobjectArray frames))
609 if (!thread->has_last_Java_frame()) {
610 THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: no stack trace", nullptr);
611 }
612
613 Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream));
614 Handle contScope_h(THREAD, JNIHandles::resolve(contScope));
615 Handle cont_h(THREAD, JNIHandles::resolve(cont));
616 // frames array is a ClassFrameInfo[] array when only getting caller reference,
617 // and a StackFrameInfo[] array (or derivative) otherwise. It should never
618 // be null.
619 objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames));
620 objArrayHandle frames_array_h(THREAD, fa);
621
622 if (frames_array_h->length() < buffer_size) {
623 THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "not enough space in buffers", nullptr);
624 }
625
626 oop result = StackWalk::walk(stackStream_h, mode, skip_frames, contScope_h, cont_h,
627 buffer_size, start_index, frames_array_h, CHECK_NULL);
628 return JNIHandles::make_local(THREAD, result);
629 JVM_END
630
631
632 JVM_ENTRY_PROF(jint, JVM_MoreStackWalk, JVM_MoreStackWalk(JNIEnv *env, jobject stackStream, jint mode, jlong anchor,
633 jint last_batch_count, jint buffer_size, jint start_index,
634 jobjectArray frames))
635 // frames array is a ClassFrameInfo[] array when only getting caller reference,
636 // and a StackFrameInfo[] array (or derivative) otherwise. It should never
637 // be null.
638 objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames));
639 objArrayHandle frames_array_h(THREAD, fa);
640
641 if (frames_array_h->length() < buffer_size) {
642 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "not enough space in buffers");
643 }
644
645 Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream));
646 return StackWalk::fetchNextBatch(stackStream_h, mode, anchor, last_batch_count, buffer_size,
647 start_index, frames_array_h, THREAD);
648 JVM_END
649
650 JVM_ENTRY_PROF(void, JVM_SetStackWalkContinuation, JVM_SetStackWalkContinuation(JNIEnv *env, jobject stackStream, jlong anchor, jobjectArray frames, jobject cont))
651 objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames));
652 objArrayHandle frames_array_h(THREAD, fa);
653 Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream));
654 Handle cont_h(THREAD, JNIHandles::resolve_non_null(cont));
655
656 StackWalk::setContinuation(stackStream_h, anchor, frames_array_h, cont_h, THREAD);
657 JVM_END
658
659 // java.lang.Object ///////////////////////////////////////////////
660
661
662 JVM_ENTRY_PROF(jint, JVM_IHashCode, JVM_IHashCode(JNIEnv* env, jobject handle))
663 // as implemented in the classic virtual machine; return 0 if object is null
664 return handle == nullptr ? 0 :
665 checked_cast<jint>(ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)));
666 JVM_END
667
668
669 JVM_ENTRY_PROF(void, JVM_MonitorWait, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
670 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
671 ObjectSynchronizer::wait(obj, ms, CHECK);
672 JVM_END
673
674
675 JVM_ENTRY_PROF(void, JVM_MonitorNotify, JVM_MonitorNotify(JNIEnv* env, jobject handle))
676 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
677 ObjectSynchronizer::notify(obj, CHECK);
678 JVM_END
679
680
681 JVM_ENTRY_PROF(void, JVM_MonitorNotifyAll, JVM_MonitorNotifyAll(JNIEnv* env, jobject handle))
682 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
683 ObjectSynchronizer::notifyall(obj, CHECK);
684 JVM_END
685
686
687 JVM_ENTRY_PROF(jobject, JVM_Clone, JVM_Clone(JNIEnv* env, jobject handle))
688 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
689 Klass* klass = obj->klass();
690 JvmtiVMObjectAllocEventCollector oam;
691
692 #ifdef ASSERT
693 // Just checking that the cloneable flag is set correct
694 if (obj->is_array()) {
695 guarantee(klass->is_cloneable(), "all arrays are cloneable");
696 } else {
697 guarantee(obj->is_instance(), "should be instanceOop");
698 bool cloneable = klass->is_subtype_of(vmClasses::Cloneable_klass());
699 guarantee(cloneable == klass->is_cloneable(), "incorrect cloneable flag");
700 }
701 #endif
702
703 // Check if class of obj supports the Cloneable interface.
704 // All arrays are considered to be cloneable (See JLS 20.1.5).
705 // All j.l.r.Reference classes are considered non-cloneable.
706 if (!klass->is_cloneable() ||
707 (klass->is_instance_klass() &&
708 InstanceKlass::cast(klass)->reference_type() != REF_NONE)) {
709 ResourceMark rm(THREAD);
710 THROW_MSG_NULL(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());
711 }
712
713 // Make shallow object copy
714 const size_t size = obj->size();
715 oop new_obj_oop = nullptr;
716 if (obj->is_array()) {
717 const int length = ((arrayOop)obj())->length();
718 new_obj_oop = Universe::heap()->array_allocate(klass, size, length,
719 /* do_zero */ true, CHECK_NULL);
720 } else {
721 new_obj_oop = Universe::heap()->obj_allocate(klass, size, CHECK_NULL);
722 }
723
724 HeapAccess<>::clone(obj(), new_obj_oop, size);
725
726 Handle new_obj(THREAD, new_obj_oop);
727 // Caution: this involves a java upcall, so the clone should be
728 // "gc-robust" by this stage.
729 if (klass->has_finalizer()) {
730 assert(obj->is_instance(), "should be instanceOop");
731 new_obj_oop = InstanceKlass::register_finalizer(instanceOop(new_obj()), CHECK_NULL);
732 new_obj = Handle(THREAD, new_obj_oop);
733 }
734
735 return JNIHandles::make_local(THREAD, new_obj());
736 JVM_END
737
738 // java.lang.ref.Finalizer ////////////////////////////////////////////////////
739
740 JVM_ENTRY_PROF(void, JVM_ReportFinalizationComplete, JVM_ReportFinalizationComplete(JNIEnv * env, jobject finalizee))
741 MANAGEMENT_ONLY(FinalizerService::on_complete(JNIHandles::resolve_non_null(finalizee), THREAD);)
742 JVM_END
743
744 JVM_LEAF_PROF(jboolean, JVM_IsFinalizationEnabled, JVM_IsFinalizationEnabled(JNIEnv * env))
745 return InstanceKlass::is_finalization_enabled();
746 JVM_END
747
748 // jdk.internal.vm.Continuation /////////////////////////////////////////////////////
749
750 JVM_ENTRY_PROF(void, JVM_RegisterContinuationMethods, JVM_RegisterContinuationMethods(JNIEnv *env, jclass cls))
751 CONT_RegisterNativeMethods(env, cls);
752 JVM_END
753
754 // java.io.File ///////////////////////////////////////////////////////////////
755
756 JVM_LEAF_PROF(char*, JVM_NativePath, JVM_NativePath(char* path))
757 return os::native_path(path);
758 JVM_END
759
760
761 // Misc. class handling ///////////////////////////////////////////////////////////
762
763
764 JVM_ENTRY_PROF(jclass, JVM_GetCallerClass, JVM_GetCallerClass(JNIEnv* env))
765 // Getting the class of the caller frame.
766 //
767 // The call stack at this point looks something like this:
768 //
769 // [0] [ @CallerSensitive public jdk.internal.reflect.Reflection.getCallerClass ]
770 // [1] [ @CallerSensitive API.method ]
771 // [.] [ (skipped intermediate frames) ]
772 // [n] [ caller ]
773 vframeStream vfst(thread);
774 // Cf. LibraryCallKit::inline_native_Reflection_getCallerClass
775 for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {
776 Method* m = vfst.method();
777 assert(m != nullptr, "sanity");
778 switch (n) {
779 case 0:
780 // This must only be called from Reflection.getCallerClass
781 if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {
782 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");
783 }
784 // fall-through
785 case 1:
786 // Frame 0 and 1 must be caller sensitive.
787 if (!m->caller_sensitive()) {
788 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));
789 }
790 break;
791 default:
792 if (!m->is_ignored_by_security_stack_walk()) {
793 // We have reached the desired frame; return the holder class.
794 return (jclass) JNIHandles::make_local(THREAD, m->method_holder()->java_mirror());
795 }
796 break;
797 }
798 }
799 return nullptr;
800 JVM_END
801
802
803 JVM_ENTRY_PROF(jclass, JVM_FindPrimitiveClass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))
804 oop mirror = nullptr;
805 BasicType t = name2type(utf);
806 if (t != T_ILLEGAL && !is_reference_type(t)) {
807 mirror = Universe::java_mirror(t);
808 }
809 if (mirror == nullptr) {
810 THROW_MSG_NULL(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);
811 } else {
812 return (jclass) JNIHandles::make_local(THREAD, mirror);
813 }
814 JVM_END
815
816
817 // Returns a class loaded by the bootstrap class loader; or null
818 // if not found. ClassNotFoundException is not thrown.
819 // FindClassFromBootLoader is exported to the launcher for windows.
820 JVM_ENTRY_PROF(jclass, JVM_FindClassFromBootLoader, JVM_FindClassFromBootLoader(JNIEnv* env, const char* name))
821 // Java libraries should ensure that name is never null or illegal.
822 if (name == nullptr || (int)strlen(name) > Symbol::max_length()) {
823 // It's impossible to create this class; the name cannot fit
824 // into the constant pool.
825 return nullptr;
826 }
827 assert(UTF8::is_legal_utf8((const unsigned char*)name, strlen(name), false), "illegal UTF name");
828
829 TempNewSymbol h_name = SymbolTable::new_symbol(name);
830 Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
831 if (k == nullptr) {
832 return nullptr;
833 }
834
835 if (log_is_enabled(Debug, class, resolve)) {
836 trace_class_resolution(k);
837 }
838 return (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
839 JVM_END
840
841 // Find a class with this name in this loader.
842 JVM_ENTRY_PROF(jclass, JVM_FindClassFromLoader, JVM_FindClassFromLoader(JNIEnv* env, const char* name,
843 jboolean init, jobject loader))
844 TempNewSymbol h_name =
845 SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_ClassNotFoundException(),
846 CHECK_NULL);
847
848 oop loader_oop = JNIHandles::resolve(loader);
849 Handle h_loader(THREAD, loader_oop);
850
851 jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
852 false, THREAD);
853
854 if (log_is_enabled(Debug, class, resolve) && result != nullptr) {
855 trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
856 }
857 return result;
858 JVM_END
859
860 // Currently only called from the old verifier.
861 JVM_ENTRY_PROF(jclass, JVM_FindClassFromClass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
862 jboolean init, jclass from))
863 TempNewSymbol h_name =
864 SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_ClassNotFoundException(),
865 CHECK_NULL);
866 oop from_class_oop = JNIHandles::resolve(from);
867 assert(from_class_oop != nullptr, "must be");
868 Klass* from_class = java_lang_Class::as_Klass(from_class_oop);
869 assert(from_class != nullptr, "must be");
870 oop class_loader = from_class->class_loader();
871
872 Handle h_loader(THREAD, class_loader);
873 jclass result = find_class_from_class_loader(env, h_name, init, h_loader, true, thread);
874
875 if (log_is_enabled(Debug, class, resolve) && result != nullptr) {
876 // this function is generally only used for class loading during verification.
877 ResourceMark rm;
878 const char* from_name = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(from))->external_name();
879 const char* to_name = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result))->external_name();
880 log_debug(class, resolve)("%s %s (verification)", from_name, to_name);
881 }
882
883 #if INCLUDE_CDS
884 if (CDSConfig::is_preserving_verification_constraints() && from_class->is_instance_klass()) {
885 InstanceKlass* ik = InstanceKlass::cast(from_class);
886 SystemDictionaryShared::add_old_verification_constraint(THREAD, ik, h_name);
887 }
888 #endif
889
890 return result;
891 JVM_END
892
893 // common code for JVM_DefineClass() and JVM_DefineClassWithSource()
894 static jclass jvm_define_class_common(const char *name,
895 jobject loader, const jbyte *buf,
896 jsize len, jobject pd, const char *source,
897 TRAPS) {
898 if (source == nullptr) source = "__JVM_DefineClass__";
899
900 JavaThread* jt = THREAD;
901
902 PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
903 ClassLoader::perf_define_appclass_selftime(),
904 ClassLoader::perf_define_appclasses(),
905 jt->get_thread_stat()->perf_recursion_counts_addr(),
906 jt->get_thread_stat()->perf_timers_addr(),
907 PerfClassTraceTime::DEFINE_CLASS);
908
909 if (UsePerfData) {
910 ClassLoader::perf_app_classfile_bytes_read()->inc(len);
911 }
912
913 // Class resolution will get the class name from the .class stream if the name is null.
914 TempNewSymbol class_name = name == nullptr ? nullptr :
915 SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_NoClassDefFoundError(),
916 CHECK_NULL);
917
918 ResourceMark rm(THREAD);
919 ClassFileStream st((u1*)buf, len, source);
920 Handle class_loader (THREAD, JNIHandles::resolve(loader));
921 Handle protection_domain (THREAD, JNIHandles::resolve(pd));
922 ClassLoadInfo cl_info(protection_domain);
923 Klass* k = SystemDictionary::resolve_from_stream(&st, class_name,
924 class_loader,
925 cl_info,
926 CHECK_NULL);
927
928 if (log_is_enabled(Debug, class, resolve)) {
929 trace_class_resolution(k);
930 }
931
932 return (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
933 }
934
935 enum {
936 NESTMATE = java_lang_invoke_MemberName::MN_NESTMATE_CLASS,
937 HIDDEN_CLASS = java_lang_invoke_MemberName::MN_HIDDEN_CLASS,
938 STRONG_LOADER_LINK = java_lang_invoke_MemberName::MN_STRONG_LOADER_LINK,
939 ACCESS_VM_ANNOTATIONS = java_lang_invoke_MemberName::MN_ACCESS_VM_ANNOTATIONS
940 };
941
942 /*
943 * Define a class with the specified flags that indicates if it's a nestmate,
944 * hidden, or strongly referenced from class loader.
945 */
946 static jclass jvm_lookup_define_class(jclass lookup, const char *name,
947 const jbyte *buf, jsize len, jobject pd,
948 jboolean init, int flags, jobject classData, TRAPS) {
949 ResourceMark rm(THREAD);
950
951 InstanceKlass* lookup_k = java_lang_Class::as_InstanceKlass(JNIHandles::resolve_non_null(lookup));
952 // Lookup class must not be a primitive class (whose mirror has a null Klass*)
953 if (lookup_k == nullptr) {
954 // The error message is wrong. We come here only if lookup is a primitive class
955 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Lookup class is null");
956 }
957
958 Handle class_loader (THREAD, lookup_k->class_loader());
959
960 bool is_nestmate = (flags & NESTMATE) == NESTMATE;
961 bool is_hidden = (flags & HIDDEN_CLASS) == HIDDEN_CLASS;
962 bool is_strong = (flags & STRONG_LOADER_LINK) == STRONG_LOADER_LINK;
963 bool vm_annotations = (flags & ACCESS_VM_ANNOTATIONS) == ACCESS_VM_ANNOTATIONS;
964
965 InstanceKlass* host_class = nullptr;
966 if (is_nestmate) {
967 host_class = lookup_k->nest_host(CHECK_NULL);
968 }
969
970 log_info(class, nestmates)("LookupDefineClass: %s - %s%s, %s, %s, %s",
971 name,
972 is_nestmate ? "with dynamic nest-host " : "non-nestmate",
973 is_nestmate ? host_class->external_name() : "",
974 is_hidden ? "hidden" : "not hidden",
975 is_strong ? "strong" : "weak",
976 vm_annotations ? "with vm annotations" : "without vm annotation");
977
978 if (!is_hidden) {
979 // classData is only applicable for hidden classes
980 if (classData != nullptr) {
981 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "classData is only applicable for hidden classes");
982 }
983 if (is_nestmate) {
984 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "dynamic nestmate is only applicable for hidden classes");
985 }
986 if (!is_strong) {
987 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "an ordinary class must be strongly referenced by its defining loader");
988 }
989 if (vm_annotations) {
990 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "vm annotations only allowed for hidden classes");
991 }
992 if (flags != STRONG_LOADER_LINK) {
993 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
994 err_msg("invalid flag 0x%x", flags));
995 }
996 }
997
998 // Class resolution will get the class name from the .class stream if the name is null.
999 TempNewSymbol class_name = name == nullptr ? nullptr :
1000 SystemDictionary::class_name_symbol(name, vmSymbols::java_lang_NoClassDefFoundError(),
1001 CHECK_NULL);
1002
1003 Handle protection_domain (THREAD, JNIHandles::resolve(pd));
1004 const char* source = is_nestmate ? host_class->external_name() : "__JVM_LookupDefineClass__";
1005 ClassFileStream st((u1*)buf, len, source);
1006
1007 InstanceKlass* ik = nullptr;
1008 if (!is_hidden) {
1009 ClassLoadInfo cl_info(protection_domain);
1010 ik = SystemDictionary::resolve_from_stream(&st, class_name,
1011 class_loader,
1012 cl_info,
1013 CHECK_NULL);
1014
1015 if (log_is_enabled(Debug, class, resolve)) {
1016 trace_class_resolution(ik);
1017 }
1018 } else { // hidden
1019 Handle classData_h(THREAD, JNIHandles::resolve(classData));
1020 ClassLoadInfo cl_info(protection_domain,
1021 host_class,
1022 classData_h,
1023 is_hidden,
1024 is_strong,
1025 vm_annotations);
1026 ik = SystemDictionary::resolve_from_stream(&st, class_name,
1027 class_loader,
1028 cl_info,
1029 CHECK_NULL);
1030
1031 // The hidden class loader data has been artificially been kept alive to
1032 // this point. The mirror and any instances of this class have to keep
1033 // it alive afterwards.
1034 ik->class_loader_data()->dec_keep_alive_ref_count();
1035
1036 if (is_nestmate && log_is_enabled(Debug, class, nestmates)) {
1037 ModuleEntry* module = ik->module();
1038 const char * module_name = module->is_named() ? module->name()->as_C_string() : UNNAMED_MODULE;
1039 log_debug(class, nestmates)("Dynamic nestmate: %s/%s, nest_host %s, %s",
1040 module_name,
1041 ik->external_name(),
1042 host_class->external_name(),
1043 ik->is_hidden() ? "is hidden" : "is not hidden");
1044 }
1045 }
1046
1047 if ((!is_hidden || is_nestmate) && !Reflection::is_same_class_package(lookup_k, ik)) {
1048 // non-hidden class or nestmate class must be in the same package as the Lookup class
1049 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Lookup class and defined class are in different packages");
1050 }
1051
1052 if (init) {
1053 ik->initialize(CHECK_NULL);
1054 } else {
1055 ik->link_class(CHECK_NULL);
1056 }
1057
1058 return (jclass) JNIHandles::make_local(THREAD, ik->java_mirror());
1059 }
1060
1061 JVM_ENTRY_PROF(jclass, JVM_DefineClass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
1062 return jvm_define_class_common(name, loader, buf, len, pd, nullptr, THREAD);
1063 JVM_END
1064
1065 /*
1066 * Define a class with the specified lookup class.
1067 * lookup: Lookup class
1068 * name: the name of the class
1069 * buf: class bytes
1070 * len: length of class bytes
1071 * pd: protection domain
1072 * init: initialize the class
1073 * flags: properties of the class
1074 * classData: private static pre-initialized field
1075 */
1076 JVM_ENTRY_PROF(jclass, JVM_LookupDefineClass, JVM_LookupDefineClass(JNIEnv *env, jclass lookup, const char *name, const jbyte *buf,
1077 jsize len, jobject pd, jboolean initialize, int flags, jobject classData))
1078
1079 if (lookup == nullptr) {
1080 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Lookup class is null");
1081 }
1082
1083 assert(buf != nullptr, "buf must not be null");
1084
1085 return jvm_lookup_define_class(lookup, name, buf, len, pd, initialize, flags, classData, THREAD);
1086 JVM_END
1087
1088 JVM_ENTRY_PROF(jclass, JVM_DefineClassWithSource, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
1089 return jvm_define_class_common(name, loader, buf, len, pd, source, THREAD);
1090 JVM_END
1091
1092 JVM_ENTRY_PROF(jclass, JVM_FindLoadedClass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
1093 ResourceMark rm(THREAD);
1094
1095 Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
1096 char* str = java_lang_String::as_utf8_string(h_name());
1097
1098 // Sanity check, don't expect null
1099 if (str == nullptr) return nullptr;
1100
1101 // Internalize the string, converting '.' to '/' in string.
1102 char* p = (char*)str;
1103 while (*p != '\0') {
1104 if (*p == '.') {
1105 *p = '/';
1106 }
1107 p++;
1108 }
1109
1110 const int str_len = (int)(p - str);
1111 if (str_len > Symbol::max_length()) {
1112 // It's impossible to create this class; the name cannot fit
1113 // into the constant pool.
1114 return nullptr;
1115 }
1116 TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len);
1117
1118 // Security Note:
1119 // The Java level wrapper will perform the necessary security check allowing
1120 // us to pass the null as the initiating class loader.
1121 Handle h_loader(THREAD, JNIHandles::resolve(loader));
1122 Klass* k = SystemDictionary::find_instance_or_array_klass(THREAD, klass_name, h_loader);
1123 #if INCLUDE_CDS
1124 if (k == nullptr) {
1125 // If the class is not already loaded, try to see if it's in the shared
1126 // archive for the current classloader (h_loader).
1127 k = SystemDictionaryShared::find_or_load_shared_class(klass_name, h_loader, CHECK_NULL);
1128 }
1129 #endif
1130 return (k == nullptr) ? nullptr :
1131 (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
1132 JVM_END
1133
1134 // Module support //////////////////////////////////////////////////////////////////////////////
1135
1136 JVM_ENTRY_PROF(void, JVM_DefineModule, JVM_DefineModule(JNIEnv *env, jobject module, jboolean is_open, jstring version,
1137 jstring location, jobjectArray packages))
1138 Handle h_module (THREAD, JNIHandles::resolve(module));
1139 Modules::define_module(h_module, is_open, version, location, packages, CHECK);
1140 JVM_END
1141
1142 JVM_ENTRY_PROF(void, JVM_SetBootLoaderUnnamedModule, JVM_SetBootLoaderUnnamedModule(JNIEnv *env, jobject module))
1143 Handle h_module (THREAD, JNIHandles::resolve(module));
1144 Modules::set_bootloader_unnamed_module(h_module, CHECK);
1145 JVM_END
1146
1147 JVM_ENTRY_PROF(void, JVM_AddModuleExports, JVM_AddModuleExports(JNIEnv *env, jobject from_module, jstring package, jobject to_module))
1148 Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1149 Handle h_to_module (THREAD, JNIHandles::resolve(to_module));
1150 Modules::add_module_exports_qualified(h_from_module, package, h_to_module, CHECK);
1151 JVM_END
1152
1153 JVM_ENTRY_PROF(void, JVM_AddModuleExportsToAllUnnamed, JVM_AddModuleExportsToAllUnnamed(JNIEnv *env, jobject from_module, jstring package))
1154 Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1155 Modules::add_module_exports_to_all_unnamed(h_from_module, package, CHECK);
1156 JVM_END
1157
1158 JVM_ENTRY_PROF(void, JVM_AddModuleExportsToAll, JVM_AddModuleExportsToAll(JNIEnv *env, jobject from_module, jstring package))
1159 Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1160 Modules::add_module_exports(h_from_module, package, Handle(), CHECK);
1161 JVM_END
1162
1163 JVM_ENTRY_PROF(void, JVM_AddReadsModule, JVM_AddReadsModule(JNIEnv *env, jobject from_module, jobject source_module))
1164 Handle h_from_module (THREAD, JNIHandles::resolve(from_module));
1165 Handle h_source_module (THREAD, JNIHandles::resolve(source_module));
1166 Modules::add_reads_module(h_from_module, h_source_module, CHECK);
1167 JVM_END
1168
1169 JVM_ENTRY_PROF(void, JVM_DefineArchivedModules, JVM_DefineArchivedModules(JNIEnv *env, jobject platform_loader, jobject system_loader))
1170 Handle h_platform_loader (THREAD, JNIHandles::resolve(platform_loader));
1171 Handle h_system_loader (THREAD, JNIHandles::resolve(system_loader));
1172 Modules::define_archived_modules(h_platform_loader, h_system_loader, CHECK);
1173 JVM_END
1174
1175 // Reflection support //////////////////////////////////////////////////////////////////////////////
1176
1177 JVM_ENTRY_PROF(jstring, JVM_InitClassName, JVM_InitClassName(JNIEnv *env, jclass cls))
1178 assert (cls != nullptr, "illegal class");
1179 JvmtiVMObjectAllocEventCollector oam;
1180 ResourceMark rm(THREAD);
1181 HandleMark hm(THREAD);
1182 Handle java_class(THREAD, JNIHandles::resolve(cls));
1183 oop result = java_lang_Class::name(java_class, CHECK_NULL);
1184 return (jstring) JNIHandles::make_local(THREAD, result);
1185 JVM_END
1186
1187
1188 JVM_ENTRY_PROF(jobjectArray, JVM_GetClassInterfaces, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
1189 JvmtiVMObjectAllocEventCollector oam;
1190 oop mirror = JNIHandles::resolve_non_null(cls);
1191
1192 // Special handling for primitive objects
1193 if (java_lang_Class::is_primitive(mirror)) {
1194 // Primitive objects does not have any interfaces
1195 objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_NULL);
1196 return (jobjectArray) JNIHandles::make_local(THREAD, r);
1197 }
1198
1199 Klass* klass = java_lang_Class::as_Klass(mirror);
1200 // Figure size of result array
1201 int size;
1202 if (klass->is_instance_klass()) {
1203 size = InstanceKlass::cast(klass)->local_interfaces()->length();
1204 } else {
1205 assert(klass->is_objArray_klass() || klass->is_typeArray_klass(), "Illegal mirror klass");
1206 size = 2;
1207 }
1208
1209 // Allocate result array
1210 objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(), size, CHECK_NULL);
1211 objArrayHandle result (THREAD, r);
1212 // Fill in result
1213 if (klass->is_instance_klass()) {
1214 // Regular instance klass, fill in all local interfaces
1215 for (int index = 0; index < size; index++) {
1216 InstanceKlass* k = InstanceKlass::cast(klass)->local_interfaces()->at(index);
1217 result->obj_at_put(index, k->java_mirror());
1218 }
1219 } else {
1220 // All arrays implement java.lang.Cloneable and java.io.Serializable
1221 result->obj_at_put(0, vmClasses::Cloneable_klass()->java_mirror());
1222 result->obj_at_put(1, vmClasses::Serializable_klass()->java_mirror());
1223 }
1224 return (jobjectArray) JNIHandles::make_local(THREAD, result());
1225 JVM_END
1226
1227
1228 JVM_ENTRY_PROF(jboolean, JVM_IsHiddenClass, JVM_IsHiddenClass(JNIEnv *env, jclass cls))
1229 oop mirror = JNIHandles::resolve_non_null(cls);
1230 if (java_lang_Class::is_primitive(mirror)) {
1231 return JNI_FALSE;
1232 }
1233 Klass* k = java_lang_Class::as_Klass(mirror);
1234 return k->is_hidden();
1235 JVM_END
1236
1237 class ScopedValueBindingsResolver {
1238 public:
1239 InstanceKlass* Carrier_klass;
1240 ScopedValueBindingsResolver(JavaThread* THREAD) {
1241 Klass *k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ScopedValue_Carrier(), true, THREAD);
1242 Carrier_klass = InstanceKlass::cast(k);
1243 }
1244 };
1245
1246 JVM_ENTRY_PROF(jobject, JVM_FindScopedValueBindings, JVM_FindScopedValueBindings(JNIEnv *env, jclass cls))
1247 ResourceMark rm(THREAD);
1248 GrowableArray<Handle>* local_array = new GrowableArray<Handle>(12);
1249 JvmtiVMObjectAllocEventCollector oam;
1250
1251 static ScopedValueBindingsResolver resolver(THREAD);
1252
1253 // Iterate through Java frames
1254 vframeStream vfst(thread);
1255 for(; !vfst.at_end(); vfst.next()) {
1256 int loc = -1;
1257 // get method of frame
1258 Method* method = vfst.method();
1259
1260 Symbol *name = method->name();
1261
1262 InstanceKlass* holder = method->method_holder();
1263 if (name == vmSymbols::runWith_method_name()) {
1264 if (holder == vmClasses::Thread_klass()
1265 || holder == resolver.Carrier_klass) {
1266 loc = 1;
1267 }
1268 }
1269
1270 if (loc != -1) {
1271 javaVFrame *frame = vfst.asJavaVFrame();
1272 StackValueCollection* locals = frame->locals();
1273 StackValue* head_sv = locals->at(loc); // java/lang/ScopedValue$Snapshot
1274 Handle result = head_sv->get_obj();
1275 assert(!head_sv->obj_is_scalar_replaced(), "found scalar-replaced object");
1276 if (result() != nullptr) {
1277 return JNIHandles::make_local(THREAD, result());
1278 }
1279 }
1280 }
1281
1282 return nullptr;
1283 JVM_END
1284
1285
1286 JVM_ENTRY_PROF(jobjectArray, JVM_GetDeclaredClasses, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1287 JvmtiVMObjectAllocEventCollector oam;
1288 // ofClass is a reference to a java_lang_Class object. The mirror object
1289 // of an InstanceKlass
1290 oop ofMirror = JNIHandles::resolve_non_null(ofClass);
1291 if (java_lang_Class::is_primitive(ofMirror) ||
1292 ! java_lang_Class::as_Klass(ofMirror)->is_instance_klass()) {
1293 oop result = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_NULL);
1294 return (jobjectArray)JNIHandles::make_local(THREAD, result);
1295 }
1296
1297 InstanceKlass* k = java_lang_Class::as_InstanceKlass(ofMirror);
1298 InnerClassesIterator iter(k);
1299
1300 if (iter.length() == 0) {
1301 // Neither an inner nor outer class
1302 oop result = oopFactory::new_objArray(vmClasses::Class_klass(), 0, CHECK_NULL);
1303 return (jobjectArray)JNIHandles::make_local(THREAD, result);
1304 }
1305
1306 // find inner class info
1307 constantPoolHandle cp(thread, k->constants());
1308 int length = iter.length();
1309
1310 // Allocate temp. result array
1311 objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(), length/4, CHECK_NULL);
1312 objArrayHandle result (THREAD, r);
1313 int members = 0;
1314
1315 for (; !iter.done(); iter.next()) {
1316 int ioff = iter.inner_class_info_index();
1317 int ooff = iter.outer_class_info_index();
1318
1319 if (ioff != 0 && ooff != 0) {
1320 // Check to see if the name matches the class we're looking for
1321 // before attempting to find the class.
1322 if (cp->klass_name_at_matches(k, ooff)) {
1323 Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);
1324 if (outer_klass == k) {
1325 Klass* ik = cp->klass_at(ioff, CHECK_NULL);
1326 InstanceKlass* inner_klass = InstanceKlass::cast(ik);
1327
1328 // Throws an exception if outer klass has not declared k as
1329 // an inner klass
1330 Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1331
1332 result->obj_at_put(members, inner_klass->java_mirror());
1333 members++;
1334 }
1335 }
1336 }
1337 }
1338
1339 if (members != length) {
1340 // Return array of right length
1341 objArrayOop res = oopFactory::new_objArray(vmClasses::Class_klass(), members, CHECK_NULL);
1342 for(int i = 0; i < members; i++) {
1343 res->obj_at_put(i, result->obj_at(i));
1344 }
1345 return (jobjectArray)JNIHandles::make_local(THREAD, res);
1346 }
1347
1348 return (jobjectArray)JNIHandles::make_local(THREAD, result());
1349 JVM_END
1350
1351
1352 JVM_ENTRY_PROF(jclass, JVM_GetDeclaringClass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1353 {
1354 // ofClass is a reference to a java_lang_Class object.
1355 oop ofMirror = JNIHandles::resolve_non_null(ofClass);
1356 if (java_lang_Class::is_primitive(ofMirror)) {
1357 return nullptr;
1358 }
1359 Klass* klass = java_lang_Class::as_Klass(ofMirror);
1360 if (!klass->is_instance_klass()) {
1361 return nullptr;
1362 }
1363
1364 bool inner_is_member = false;
1365 Klass* outer_klass
1366 = InstanceKlass::cast(klass)->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1367 if (outer_klass == nullptr) return nullptr; // already a top-level class
1368 if (!inner_is_member) return nullptr; // a hidden class (inside a method)
1369 return (jclass) JNIHandles::make_local(THREAD, outer_klass->java_mirror());
1370 }
1371 JVM_END
1372
1373 JVM_ENTRY_PROF(jstring, JVM_GetSimpleBinaryName, JVM_GetSimpleBinaryName(JNIEnv *env, jclass cls))
1374 {
1375 oop mirror = JNIHandles::resolve_non_null(cls);
1376 if (java_lang_Class::is_primitive(mirror)) {
1377 return nullptr;
1378 }
1379 Klass* klass = java_lang_Class::as_Klass(mirror);
1380 if (!klass->is_instance_klass()) {
1381 return nullptr;
1382 }
1383 InstanceKlass* k = InstanceKlass::cast(klass);
1384 int ooff = 0, noff = 0;
1385 if (k->find_inner_classes_attr(&ooff, &noff, THREAD)) {
1386 if (noff != 0) {
1387 constantPoolHandle i_cp(thread, k->constants());
1388 Symbol* name = i_cp->symbol_at(noff);
1389 Handle str = java_lang_String::create_from_symbol(name, CHECK_NULL);
1390 return (jstring) JNIHandles::make_local(THREAD, str());
1391 }
1392 }
1393 return nullptr;
1394 }
1395 JVM_END
1396
1397 JVM_ENTRY_PROF(jstring, JVM_GetClassSignature, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1398 assert (cls != nullptr, "illegal class");
1399 JvmtiVMObjectAllocEventCollector oam;
1400 ResourceMark rm(THREAD);
1401 oop mirror = JNIHandles::resolve_non_null(cls);
1402 // Return null for arrays and primitives
1403 if (!java_lang_Class::is_primitive(mirror)) {
1404 Klass* k = java_lang_Class::as_Klass(mirror);
1405 if (k->is_instance_klass()) {
1406 Symbol* sym = InstanceKlass::cast(k)->generic_signature();
1407 if (sym == nullptr) return nullptr;
1408 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1409 return (jstring) JNIHandles::make_local(THREAD, str());
1410 }
1411 }
1412 return nullptr;
1413 JVM_END
1414
1415
1416 JVM_ENTRY_PROF(jbyteArray, JVM_GetClassAnnotations, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1417 assert (cls != nullptr, "illegal class");
1418 oop mirror = JNIHandles::resolve_non_null(cls);
1419 // Return null for arrays and primitives
1420 if (!java_lang_Class::is_primitive(mirror)) {
1421 Klass* k = java_lang_Class::as_Klass(mirror);
1422 if (k->is_instance_klass()) {
1423 typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);
1424 return (jbyteArray) JNIHandles::make_local(THREAD, a);
1425 }
1426 }
1427 return nullptr;
1428 JVM_END
1429
1430
1431 static bool jvm_get_field_common(jobject field, fieldDescriptor& fd) {
1432 // some of this code was adapted from from jni_FromReflectedField
1433
1434 oop reflected = JNIHandles::resolve_non_null(field);
1435 oop mirror = java_lang_reflect_Field::clazz(reflected);
1436 int slot = java_lang_reflect_Field::slot(reflected);
1437 int modifiers = java_lang_reflect_Field::modifiers(reflected);
1438
1439 InstanceKlass* ik = java_lang_Class::as_InstanceKlass(mirror);
1440 int offset = ik->field_offset(slot);
1441
1442 if (modifiers & JVM_ACC_STATIC) {
1443 // for static fields we only look in the current class
1444 if (!ik->find_local_field_from_offset(offset, true, &fd)) {
1445 assert(false, "cannot find static field");
1446 return false;
1447 }
1448 } else {
1449 // for instance fields we start with the current class and work
1450 // our way up through the superclass chain
1451 if (!ik->find_field_from_offset(offset, false, &fd)) {
1452 assert(false, "cannot find instance field");
1453 return false;
1454 }
1455 }
1456 return true;
1457 }
1458
1459 static Method* jvm_get_method_common(jobject method) {
1460 // some of this code was adapted from from jni_FromReflectedMethod
1461
1462 oop reflected = JNIHandles::resolve_non_null(method);
1463 oop mirror = nullptr;
1464 int slot = 0;
1465
1466 if (reflected->klass() == vmClasses::reflect_Constructor_klass()) {
1467 mirror = java_lang_reflect_Constructor::clazz(reflected);
1468 slot = java_lang_reflect_Constructor::slot(reflected);
1469 } else {
1470 assert(reflected->klass() == vmClasses::reflect_Method_klass(),
1471 "wrong type");
1472 mirror = java_lang_reflect_Method::clazz(reflected);
1473 slot = java_lang_reflect_Method::slot(reflected);
1474 }
1475 InstanceKlass* ik = java_lang_Class::as_InstanceKlass(mirror);
1476
1477 Method* m = ik->method_with_idnum(slot);
1478 assert(m != nullptr, "cannot find method");
1479 return m; // caller has to deal with null in product mode
1480 }
1481
1482 /* Type use annotations support (JDK 1.8) */
1483
1484 JVM_ENTRY_PROF(jbyteArray, JVM_GetClassTypeAnnotations, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))
1485 assert (cls != nullptr, "illegal class");
1486 ResourceMark rm(THREAD);
1487 // Return null for arrays and primitives
1488 if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1489 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1490 if (k->is_instance_klass()) {
1491 AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
1492 if (type_annotations != nullptr) {
1493 typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1494 return (jbyteArray) JNIHandles::make_local(THREAD, a);
1495 }
1496 }
1497 }
1498 return nullptr;
1499 JVM_END
1500
1501 JVM_ENTRY_PROF(jbyteArray, JVM_GetMethodTypeAnnotations, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
1502 assert (method != nullptr, "illegal method");
1503 // method is a handle to a java.lang.reflect.Method object
1504 Method* m = jvm_get_method_common(method);
1505 if (m == nullptr) {
1506 return nullptr;
1507 }
1508
1509 AnnotationArray* type_annotations = m->type_annotations();
1510 if (type_annotations != nullptr) {
1511 typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1512 return (jbyteArray) JNIHandles::make_local(THREAD, a);
1513 }
1514
1515 return nullptr;
1516 JVM_END
1517
1518 JVM_ENTRY_PROF(jbyteArray, JVM_GetFieldTypeAnnotations, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
1519 assert (field != nullptr, "illegal field");
1520 fieldDescriptor fd;
1521 bool gotFd = jvm_get_field_common(field, fd);
1522 if (!gotFd) {
1523 return nullptr;
1524 }
1525
1526 return (jbyteArray) JNIHandles::make_local(THREAD, Annotations::make_java_array(fd.type_annotations(), THREAD));
1527 JVM_END
1528
1529 static void bounds_check(const constantPoolHandle& cp, jint index, TRAPS) {
1530 if (!cp->is_within_bounds(index)) {
1531 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1532 }
1533 }
1534
1535 JVM_ENTRY_PROF(jobjectArray, JVM_GetMethodParameters, JVM_GetMethodParameters(JNIEnv *env, jobject method))
1536 {
1537 // method is a handle to a java.lang.reflect.Method object
1538 Method* method_ptr = jvm_get_method_common(method);
1539 methodHandle mh (THREAD, method_ptr);
1540 Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
1541 const int num_params = mh->method_parameters_length();
1542
1543 if (num_params < 0) {
1544 // A -1 return value from method_parameters_length means there is no
1545 // parameter data. Return null to indicate this to the reflection
1546 // API.
1547 assert(num_params == -1, "num_params should be -1 if it is less than zero");
1548 return (jobjectArray)nullptr;
1549 } else {
1550 // Otherwise, we return something up to reflection, even if it is
1551 // a zero-length array. Why? Because in some cases this can
1552 // trigger a MalformedParametersException.
1553
1554 // make sure all the symbols are properly formatted
1555 for (int i = 0; i < num_params; i++) {
1556 MethodParametersElement* params = mh->method_parameters_start();
1557 int index = params[i].name_cp_index;
1558 constantPoolHandle cp(THREAD, mh->constants());
1559 bounds_check(cp, index, CHECK_NULL);
1560
1561 if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
1562 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(),
1563 "Wrong type at constant pool index");
1564 }
1565
1566 }
1567
1568 objArrayOop result_oop = oopFactory::new_objArray(vmClasses::reflect_Parameter_klass(), num_params, CHECK_NULL);
1569 objArrayHandle result (THREAD, result_oop);
1570
1571 for (int i = 0; i < num_params; i++) {
1572 MethodParametersElement* params = mh->method_parameters_start();
1573 // For a 0 index, give a null symbol
1574 Symbol* sym = 0 != params[i].name_cp_index ?
1575 mh->constants()->symbol_at(params[i].name_cp_index) : nullptr;
1576 int flags = params[i].flags;
1577 oop param = Reflection::new_parameter(reflected_method, i, sym,
1578 flags, CHECK_NULL);
1579 result->obj_at_put(i, param);
1580 }
1581 return (jobjectArray)JNIHandles::make_local(THREAD, result());
1582 }
1583 }
1584 JVM_END
1585
1586 // New (JDK 1.4) reflection implementation /////////////////////////////////////
1587
1588 JVM_ENTRY_PROF(jobjectArray, JVM_GetClassDeclaredFields, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1589 {
1590 JvmtiVMObjectAllocEventCollector oam;
1591
1592 oop ofMirror = JNIHandles::resolve_non_null(ofClass);
1593 // Exclude primitive types and array types
1594 if (java_lang_Class::is_primitive(ofMirror) ||
1595 java_lang_Class::as_Klass(ofMirror)->is_array_klass()) {
1596 // Return empty array
1597 oop res = oopFactory::new_objArray(vmClasses::reflect_Field_klass(), 0, CHECK_NULL);
1598 return (jobjectArray) JNIHandles::make_local(THREAD, res);
1599 }
1600
1601 InstanceKlass* k = java_lang_Class::as_InstanceKlass(ofMirror);
1602 constantPoolHandle cp(THREAD, k->constants());
1603
1604 // Ensure class is linked
1605 k->link_class(CHECK_NULL);
1606
1607 // Allocate result
1608 int num_fields;
1609
1610 if (publicOnly) {
1611 num_fields = 0;
1612 for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1613 if (fs.access_flags().is_public()) ++num_fields;
1614 }
1615 } else {
1616 num_fields = k->java_fields_count();
1617 }
1618
1619 objArrayOop r = oopFactory::new_objArray(vmClasses::reflect_Field_klass(), num_fields, CHECK_NULL);
1620 objArrayHandle result (THREAD, r);
1621
1622 int out_idx = 0;
1623 fieldDescriptor fd;
1624 for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
1625 if (!publicOnly || fs.access_flags().is_public()) {
1626 fd.reinitialize(k, fs.to_FieldInfo());
1627 oop field = Reflection::new_field(&fd, CHECK_NULL);
1628 result->obj_at_put(out_idx, field);
1629 ++out_idx;
1630 }
1631 }
1632 assert(out_idx == num_fields, "just checking");
1633 return (jobjectArray) JNIHandles::make_local(THREAD, result());
1634 }
1635 JVM_END
1636
1637 // A class is a record if and only if it is final and a direct subclass of
1638 // java.lang.Record and has a Record attribute; otherwise, it is not a record.
1639 JVM_ENTRY_PROF(jboolean, JVM_IsRecord, JVM_IsRecord(JNIEnv *env, jclass cls))
1640 {
1641 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1642 if (k != nullptr && k->is_instance_klass()) {
1643 InstanceKlass* ik = InstanceKlass::cast(k);
1644 return ik->is_record();
1645 } else {
1646 return false;
1647 }
1648 }
1649 JVM_END
1650
1651 // Returns an array containing the components of the Record attribute,
1652 // or null if the attribute is not present.
1653 //
1654 // Note that this function returns the components of the Record attribute
1655 // even if the class is not a record.
1656 JVM_ENTRY_PROF(jobjectArray, JVM_GetRecordComponents, JVM_GetRecordComponents(JNIEnv* env, jclass ofClass))
1657 {
1658 InstanceKlass* ik = java_lang_Class::as_InstanceKlass(JNIHandles::resolve_non_null(ofClass));
1659
1660 Array<RecordComponent*>* components = ik->record_components();
1661 if (components != nullptr) {
1662 JvmtiVMObjectAllocEventCollector oam;
1663 constantPoolHandle cp(THREAD, ik->constants());
1664 int length = components->length();
1665 assert(length >= 0, "unexpected record_components length");
1666 objArrayOop record_components =
1667 oopFactory::new_objArray(vmClasses::RecordComponent_klass(), length, CHECK_NULL);
1668 objArrayHandle components_h (THREAD, record_components);
1669
1670 for (int x = 0; x < length; x++) {
1671 RecordComponent* component = components->at(x);
1672 assert(component != nullptr, "unexpected null record component");
1673 oop component_oop = java_lang_reflect_RecordComponent::create(ik, component, CHECK_NULL);
1674 components_h->obj_at_put(x, component_oop);
1675 }
1676 return (jobjectArray)JNIHandles::make_local(THREAD, components_h());
1677 }
1678
1679 return nullptr;
1680 }
1681 JVM_END
1682
1683 static jobjectArray get_class_declared_methods_helper(
1684 JNIEnv *env,
1685 jclass ofClass, jboolean publicOnly,
1686 bool want_constructor,
1687 Klass* klass, TRAPS) {
1688
1689 JvmtiVMObjectAllocEventCollector oam;
1690
1691 oop ofMirror = JNIHandles::resolve_non_null(ofClass);
1692 // Exclude primitive types and array types
1693 if (java_lang_Class::is_primitive(ofMirror)
1694 || java_lang_Class::as_Klass(ofMirror)->is_array_klass()) {
1695 // Return empty array
1696 oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
1697 return (jobjectArray) JNIHandles::make_local(THREAD, res);
1698 }
1699
1700 InstanceKlass* k = java_lang_Class::as_InstanceKlass(ofMirror);
1701
1702 // Ensure class is linked
1703 k->link_class(CHECK_NULL);
1704
1705 Array<Method*>* methods = k->methods();
1706 int methods_length = methods->length();
1707
1708 // Save original method_idnum in case of redefinition, which can change
1709 // the idnum of obsolete methods. The new method will have the same idnum
1710 // but if we refresh the methods array, the counts will be wrong.
1711 ResourceMark rm(THREAD);
1712 GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
1713 int num_methods = 0;
1714
1715 // Select methods matching the criteria.
1716 for (int i = 0; i < methods_length; i++) {
1717 Method* method = methods->at(i);
1718 if (want_constructor && !method->is_object_initializer()) {
1719 continue;
1720 }
1721 if (!want_constructor &&
1722 (method->is_object_initializer() || method->is_static_initializer() ||
1723 method->is_overpass())) {
1724 continue;
1725 }
1726 if (publicOnly && !method->is_public()) {
1727 continue;
1728 }
1729 idnums->push(method->method_idnum());
1730 ++num_methods;
1731 }
1732
1733 // Allocate result
1734 objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
1735 objArrayHandle result (THREAD, r);
1736
1737 // Now just put the methods that we selected above, but go by their idnum
1738 // in case of redefinition. The methods can be redefined at any safepoint,
1739 // so above when allocating the oop array and below when creating reflect
1740 // objects.
1741 for (int i = 0; i < num_methods; i++) {
1742 methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
1743 if (method.is_null()) {
1744 // Method may have been deleted and seems this API can handle null
1745 // Otherwise should probably put a method that throws NSME
1746 result->obj_at_put(i, nullptr);
1747 } else {
1748 oop m;
1749 if (want_constructor) {
1750 m = Reflection::new_constructor(method, CHECK_NULL);
1751 } else {
1752 m = Reflection::new_method(method, false, CHECK_NULL);
1753 }
1754 result->obj_at_put(i, m);
1755 }
1756 }
1757
1758 return (jobjectArray) JNIHandles::make_local(THREAD, result());
1759 }
1760
1761 JVM_ENTRY_PROF(jobjectArray, JVM_GetClassDeclaredMethods, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1762 {
1763 return get_class_declared_methods_helper(env, ofClass, publicOnly,
1764 /*want_constructor*/ false,
1765 vmClasses::reflect_Method_klass(), THREAD);
1766 }
1767 JVM_END
1768
1769 JVM_ENTRY_PROF(jobjectArray, JVM_GetClassDeclaredConstructors, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1770 {
1771 return get_class_declared_methods_helper(env, ofClass, publicOnly,
1772 /*want_constructor*/ true,
1773 vmClasses::reflect_Constructor_klass(), THREAD);
1774 }
1775 JVM_END
1776
1777 JVM_ENTRY_PROF(jboolean, JVM_AreNestMates, JVM_AreNestMates(JNIEnv *env, jclass current, jclass member))
1778 {
1779 InstanceKlass* c = java_lang_Class::as_InstanceKlass(JNIHandles::resolve_non_null(current));
1780 InstanceKlass* m = java_lang_Class::as_InstanceKlass(JNIHandles::resolve_non_null(member));
1781 return c->has_nestmate_access_to(m, THREAD);
1782 }
1783 JVM_END
1784
1785 JVM_ENTRY_PROF(jclass, JVM_GetNestHost, JVM_GetNestHost(JNIEnv* env, jclass current))
1786 {
1787 // current is not a primitive or array class
1788 InstanceKlass* c = java_lang_Class::as_InstanceKlass(JNIHandles::resolve_non_null(current));
1789 InstanceKlass* host = c->nest_host(THREAD);
1790 return (jclass) (host == nullptr ? nullptr :
1791 JNIHandles::make_local(THREAD, host->java_mirror()));
1792 }
1793 JVM_END
1794
1795 JVM_ENTRY_PROF(jobjectArray, JVM_GetNestMembers, JVM_GetNestMembers(JNIEnv* env, jclass current))
1796 {
1797 // current is not a primitive or array class
1798 ResourceMark rm(THREAD);
1799 InstanceKlass* c = java_lang_Class::as_InstanceKlass(JNIHandles::resolve_non_null(current));
1800 InstanceKlass* host = c->nest_host(THREAD);
1801
1802 log_trace(class, nestmates)("Calling GetNestMembers for type %s with nest-host %s",
1803 c->external_name(), host->external_name());
1804 {
1805 JvmtiVMObjectAllocEventCollector oam;
1806 Array<u2>* members = host->nest_members();
1807 int length = members == nullptr ? 0 : members->length();
1808
1809 log_trace(class, nestmates)(" - host has %d listed nest members", length);
1810
1811 // nest host is first in the array so make it one bigger
1812 objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(),
1813 length + 1, CHECK_NULL);
1814 objArrayHandle result(THREAD, r);
1815 result->obj_at_put(0, host->java_mirror());
1816 if (length != 0) {
1817 int count = 0;
1818 for (int i = 0; i < length; i++) {
1819 int cp_index = members->at(i);
1820 Klass* k = host->constants()->klass_at(cp_index, THREAD);
1821 if (HAS_PENDING_EXCEPTION) {
1822 if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
1823 return nullptr; // propagate VMEs
1824 }
1825 if (log_is_enabled(Trace, class, nestmates)) {
1826 stringStream ss;
1827 char* target_member_class = host->constants()->klass_name_at(cp_index)->as_C_string();
1828 ss.print(" - resolution of nest member %s failed: ", target_member_class);
1829 java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
1830 log_trace(class, nestmates)("%s", ss.as_string());
1831 }
1832 CLEAR_PENDING_EXCEPTION;
1833 continue;
1834 }
1835 if (k->is_instance_klass()) {
1836 InstanceKlass* ik = InstanceKlass::cast(k);
1837 InstanceKlass* nest_host_k = ik->nest_host(CHECK_NULL);
1838 if (nest_host_k == host) {
1839 result->obj_at_put(count+1, k->java_mirror());
1840 count++;
1841 log_trace(class, nestmates)(" - [%d] = %s", count, ik->external_name());
1842 } else {
1843 log_trace(class, nestmates)(" - skipping member %s with different host %s",
1844 ik->external_name(), nest_host_k->external_name());
1845 }
1846 } else {
1847 log_trace(class, nestmates)(" - skipping member %s that is not an instance class",
1848 k->external_name());
1849 }
1850 }
1851 if (count < length) {
1852 // we had invalid entries so we need to compact the array
1853 log_trace(class, nestmates)(" - compacting array from length %d to %d",
1854 length + 1, count + 1);
1855
1856 objArrayOop r2 = oopFactory::new_objArray(vmClasses::Class_klass(),
1857 count + 1, CHECK_NULL);
1858 objArrayHandle result2(THREAD, r2);
1859 for (int i = 0; i < count + 1; i++) {
1860 result2->obj_at_put(i, result->obj_at(i));
1861 }
1862 return (jobjectArray)JNIHandles::make_local(THREAD, result2());
1863 }
1864 }
1865 else {
1866 assert(host == c || c->is_hidden(), "must be singleton nest or dynamic nestmate");
1867 }
1868 return (jobjectArray)JNIHandles::make_local(THREAD, result());
1869 }
1870 }
1871 JVM_END
1872
1873 JVM_ENTRY_PROF(jobjectArray, JVM_GetPermittedSubclasses, JVM_GetPermittedSubclasses(JNIEnv* env, jclass current))
1874 {
1875 oop mirror = JNIHandles::resolve_non_null(current);
1876 assert(!java_lang_Class::is_primitive(mirror), "should not be");
1877 InstanceKlass* ik = java_lang_Class::as_InstanceKlass(mirror);
1878
1879 ResourceMark rm(THREAD);
1880 log_trace(class, sealed)("Calling GetPermittedSubclasses for %s type %s",
1881 ik->is_sealed() ? "sealed" : "non-sealed", ik->external_name());
1882 if (ik->is_sealed()) {
1883 JvmtiVMObjectAllocEventCollector oam;
1884 Array<u2>* subclasses = ik->permitted_subclasses();
1885 int length = subclasses->length();
1886
1887 log_trace(class, sealed)(" - sealed class has %d permitted subclasses", length);
1888
1889 objArrayOop r = oopFactory::new_objArray(vmClasses::Class_klass(),
1890 length, CHECK_NULL);
1891 objArrayHandle result(THREAD, r);
1892 int count = 0;
1893 for (int i = 0; i < length; i++) {
1894 int cp_index = subclasses->at(i);
1895 Klass* k = ik->constants()->klass_at(cp_index, THREAD);
1896 if (HAS_PENDING_EXCEPTION) {
1897 if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
1898 return nullptr; // propagate VMEs
1899 }
1900 if (log_is_enabled(Trace, class, sealed)) {
1901 stringStream ss;
1902 char* permitted_subclass = ik->constants()->klass_name_at(cp_index)->as_C_string();
1903 ss.print(" - resolution of permitted subclass %s failed: ", permitted_subclass);
1904 java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
1905 log_trace(class, sealed)("%s", ss.as_string());
1906 }
1907
1908 CLEAR_PENDING_EXCEPTION;
1909 continue;
1910 }
1911 if (k->is_instance_klass()) {
1912 result->obj_at_put(count++, k->java_mirror());
1913 log_trace(class, sealed)(" - [%d] = %s", count, k->external_name());
1914 }
1915 }
1916 if (count < length) {
1917 // we had invalid entries so we need to compact the array
1918 objArrayOop r2 = oopFactory::new_objArray(vmClasses::Class_klass(),
1919 count, CHECK_NULL);
1920 objArrayHandle result2(THREAD, r2);
1921 for (int i = 0; i < count; i++) {
1922 result2->obj_at_put(i, result->obj_at(i));
1923 }
1924 return (jobjectArray)JNIHandles::make_local(THREAD, result2());
1925 }
1926 return (jobjectArray)JNIHandles::make_local(THREAD, result());
1927 } else {
1928 return nullptr;
1929 }
1930 }
1931 JVM_END
1932
1933 // Constant pool access //////////////////////////////////////////////////////////
1934
1935 JVM_ENTRY_PROF(jobject, JVM_GetClassConstantPool, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
1936 {
1937 JvmtiVMObjectAllocEventCollector oam;
1938 oop mirror = JNIHandles::resolve_non_null(cls);
1939 // Return null for primitives and arrays
1940 if (!java_lang_Class::is_primitive(mirror)) {
1941 Klass* k = java_lang_Class::as_Klass(mirror);
1942 if (k->is_instance_klass()) {
1943 InstanceKlass* k_h = InstanceKlass::cast(k);
1944 Handle jcp = reflect_ConstantPool::create(CHECK_NULL);
1945 reflect_ConstantPool::set_cp(jcp(), k_h->constants());
1946 return JNIHandles::make_local(THREAD, jcp());
1947 }
1948 }
1949 return nullptr;
1950 }
1951 JVM_END
1952
1953
1954 JVM_ENTRY_PROF(jint, JVM_ConstantPoolGetSize, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj))
1955 {
1956 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1957 return cp->length();
1958 }
1959 JVM_END
1960
1961
1962 JVM_ENTRY_PROF(jclass, JVM_ConstantPoolGetClassAt, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jint index))
1963 {
1964 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1965 bounds_check(cp, index, CHECK_NULL);
1966 constantTag tag = cp->tag_at(index);
1967 if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1968 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1969 }
1970 Klass* k = cp->klass_at(index, CHECK_NULL);
1971 return (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
1972 }
1973 JVM_END
1974
1975 JVM_ENTRY_PROF(jclass, JVM_ConstantPoolGetClassAtIfLoaded, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jint index))
1976 {
1977 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
1978 bounds_check(cp, index, CHECK_NULL);
1979 constantTag tag = cp->tag_at(index);
1980 if (!tag.is_klass() && !tag.is_unresolved_klass()) {
1981 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1982 }
1983 Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
1984 if (k == nullptr) return nullptr;
1985 return (jclass) JNIHandles::make_local(THREAD, k->java_mirror());
1986 }
1987 JVM_END
1988
1989 static jobject get_method_at_helper(const constantPoolHandle& cp, jint index, bool force_resolution, TRAPS) {
1990 constantTag tag = cp->tag_at(index);
1991 if (!tag.is_method() && !tag.is_interface_method()) {
1992 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
1993 }
1994 int klass_ref = cp->uncached_klass_ref_index_at(index);
1995 Klass* k_o;
1996 if (force_resolution) {
1997 k_o = cp->klass_at(klass_ref, CHECK_NULL);
1998 } else {
1999 k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2000 if (k_o == nullptr) return nullptr;
2001 }
2002 InstanceKlass* k = InstanceKlass::cast(k_o);
2003 Symbol* name = cp->uncached_name_ref_at(index);
2004 Symbol* sig = cp->uncached_signature_ref_at(index);
2005 methodHandle m (THREAD, k->find_method(name, sig));
2006 if (m.is_null()) {
2007 THROW_MSG_NULL(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
2008 }
2009 oop method;
2010 if (m->is_object_initializer()) {
2011 method = Reflection::new_constructor(m, CHECK_NULL);
2012 } else {
2013 // new_method accepts <clinit> as Method here
2014 method = Reflection::new_method(m, true, CHECK_NULL);
2015 }
2016 return JNIHandles::make_local(THREAD, method);
2017 }
2018
2019 JVM_ENTRY_PROF(jobject, JVM_ConstantPoolGetMethodAt, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jint index))
2020 {
2021 JvmtiVMObjectAllocEventCollector oam;
2022 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2023 bounds_check(cp, index, CHECK_NULL);
2024 jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
2025 return res;
2026 }
2027 JVM_END
2028
2029 JVM_ENTRY_PROF(jobject, JVM_ConstantPoolGetMethodAtIfLoaded, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jint index))
2030 {
2031 JvmtiVMObjectAllocEventCollector oam;
2032 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2033 bounds_check(cp, index, CHECK_NULL);
2034 jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2035 return res;
2036 }
2037 JVM_END
2038
2039 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2040 constantTag tag = cp->tag_at(index);
2041 if (!tag.is_field()) {
2042 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2043 }
2044 int klass_ref = cp->uncached_klass_ref_index_at(index);
2045 Klass* k_o;
2046 if (force_resolution) {
2047 k_o = cp->klass_at(klass_ref, CHECK_NULL);
2048 } else {
2049 k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2050 if (k_o == nullptr) return nullptr;
2051 }
2052 InstanceKlass* k = InstanceKlass::cast(k_o);
2053 Symbol* name = cp->uncached_name_ref_at(index);
2054 Symbol* sig = cp->uncached_signature_ref_at(index);
2055 fieldDescriptor fd;
2056 Klass* target_klass = k->find_field(name, sig, &fd);
2057 if (target_klass == nullptr) {
2058 THROW_MSG_NULL(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2059 }
2060 oop field = Reflection::new_field(&fd, CHECK_NULL);
2061 return JNIHandles::make_local(THREAD, field);
2062 }
2063
2064 JVM_ENTRY_PROF(jobject, JVM_ConstantPoolGetFieldAt, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jint index))
2065 {
2066 JvmtiVMObjectAllocEventCollector oam;
2067 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2068 bounds_check(cp, index, CHECK_NULL);
2069 jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2070 return res;
2071 }
2072 JVM_END
2073
2074 JVM_ENTRY_PROF(jobject, JVM_ConstantPoolGetFieldAtIfLoaded, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jint index))
2075 {
2076 JvmtiVMObjectAllocEventCollector oam;
2077 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2078 bounds_check(cp, index, CHECK_NULL);
2079 jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2080 return res;
2081 }
2082 JVM_END
2083
2084 JVM_ENTRY_PROF(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jint index))
2085 {
2086 JvmtiVMObjectAllocEventCollector oam;
2087 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2088 bounds_check(cp, index, CHECK_NULL);
2089 constantTag tag = cp->tag_at(index);
2090 if (!tag.is_field_or_method()) {
2091 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2092 }
2093 int klass_ref = cp->uncached_klass_ref_index_at(index);
2094 Symbol* klass_name = cp->klass_name_at(klass_ref);
2095 Symbol* member_name = cp->uncached_name_ref_at(index);
2096 Symbol* member_sig = cp->uncached_signature_ref_at(index);
2097 objArrayOop dest_o = oopFactory::new_objArray(vmClasses::String_klass(), 3, CHECK_NULL);
2098 objArrayHandle dest(THREAD, dest_o);
2099 Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2100 dest->obj_at_put(0, str());
2101 str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2102 dest->obj_at_put(1, str());
2103 str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2104 dest->obj_at_put(2, str());
2105 return (jobjectArray) JNIHandles::make_local(THREAD, dest());
2106 }
2107 JVM_END
2108
2109 JVM_ENTRY_PROF(jint, JVM_ConstantPoolGetClassRefIndexAt, JVM_ConstantPoolGetClassRefIndexAt(JNIEnv *env, jobject obj, jint index))
2110 {
2111 JvmtiVMObjectAllocEventCollector oam;
2112 constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2113 bounds_check(cp, index, CHECK_0);
2114 constantTag tag = cp->tag_at(index);
2115 if (!tag.is_field_or_method()) {
2116 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2117 }
2118 return (jint) cp->uncached_klass_ref_index_at(index);
2119 }
2120 JVM_END
2121
2122 JVM_ENTRY_PROF(jint, JVM_ConstantPoolGetNameAndTypeRefIndexAt, JVM_ConstantPoolGetNameAndTypeRefIndexAt(JNIEnv *env, jobject obj, jint index))
2123 {
2124 JvmtiVMObjectAllocEventCollector oam;
2125 constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2126 bounds_check(cp, index, CHECK_0);
2127 constantTag tag = cp->tag_at(index);
2128 if (!tag.is_invoke_dynamic() && !tag.is_field_or_method()) {
2129 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2130 }
2131 return (jint) cp->uncached_name_and_type_ref_index_at(index);
2132 }
2133 JVM_END
2134
2135 JVM_ENTRY_PROF(jobjectArray, JVM_ConstantPoolGetNameAndTypeRefInfoAt, JVM_ConstantPoolGetNameAndTypeRefInfoAt(JNIEnv *env, jobject obj, jint index))
2136 {
2137 JvmtiVMObjectAllocEventCollector oam;
2138 constantPoolHandle cp(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2139 bounds_check(cp, index, CHECK_NULL);
2140 constantTag tag = cp->tag_at(index);
2141 if (!tag.is_name_and_type()) {
2142 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2143 }
2144 Symbol* member_name = cp->symbol_at(cp->name_ref_index_at(index));
2145 Symbol* member_sig = cp->symbol_at(cp->signature_ref_index_at(index));
2146 objArrayOop dest_o = oopFactory::new_objArray(vmClasses::String_klass(), 2, CHECK_NULL);
2147 objArrayHandle dest(THREAD, dest_o);
2148 Handle str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2149 dest->obj_at_put(0, str());
2150 str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2151 dest->obj_at_put(1, str());
2152 return (jobjectArray) JNIHandles::make_local(THREAD, dest());
2153 }
2154 JVM_END
2155
2156 JVM_ENTRY_PROF(jint, JVM_ConstantPoolGetIntAt, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jint index))
2157 {
2158 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2159 bounds_check(cp, index, CHECK_0);
2160 constantTag tag = cp->tag_at(index);
2161 if (!tag.is_int()) {
2162 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2163 }
2164 return cp->int_at(index);
2165 }
2166 JVM_END
2167
2168 JVM_ENTRY_PROF(jlong, JVM_ConstantPoolGetLongAt, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jint index))
2169 {
2170 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2171 bounds_check(cp, index, CHECK_(0L));
2172 constantTag tag = cp->tag_at(index);
2173 if (!tag.is_long()) {
2174 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2175 }
2176 return cp->long_at(index);
2177 }
2178 JVM_END
2179
2180 JVM_ENTRY_PROF(jfloat, JVM_ConstantPoolGetFloatAt, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jint index))
2181 {
2182 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2183 bounds_check(cp, index, CHECK_(0.0f));
2184 constantTag tag = cp->tag_at(index);
2185 if (!tag.is_float()) {
2186 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2187 }
2188 return cp->float_at(index);
2189 }
2190 JVM_END
2191
2192 JVM_ENTRY_PROF(jdouble, JVM_ConstantPoolGetDoubleAt, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jint index))
2193 {
2194 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2195 bounds_check(cp, index, CHECK_(0.0));
2196 constantTag tag = cp->tag_at(index);
2197 if (!tag.is_double()) {
2198 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2199 }
2200 return cp->double_at(index);
2201 }
2202 JVM_END
2203
2204 JVM_ENTRY_PROF(jstring, JVM_ConstantPoolGetStringAt, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jint index))
2205 {
2206 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2207 bounds_check(cp, index, CHECK_NULL);
2208 constantTag tag = cp->tag_at(index);
2209 if (!tag.is_string()) {
2210 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2211 }
2212 oop str = cp->string_at(index, CHECK_NULL);
2213 return (jstring) JNIHandles::make_local(THREAD, str);
2214 }
2215 JVM_END
2216
2217 JVM_ENTRY_PROF(jstring, JVM_ConstantPoolGetUTF8At, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jint index))
2218 {
2219 JvmtiVMObjectAllocEventCollector oam;
2220 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2221 bounds_check(cp, index, CHECK_NULL);
2222 constantTag tag = cp->tag_at(index);
2223 if (!tag.is_symbol()) {
2224 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2225 }
2226 Symbol* sym = cp->symbol_at(index);
2227 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2228 return (jstring) JNIHandles::make_local(THREAD, str());
2229 }
2230 JVM_END
2231
2232 JVM_ENTRY_PROF(jbyte, JVM_ConstantPoolGetTagAt, JVM_ConstantPoolGetTagAt(JNIEnv *env, jobject obj, jint index))
2233 {
2234 constantPoolHandle cp = constantPoolHandle(THREAD, reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2235 bounds_check(cp, index, CHECK_0);
2236 constantTag tag = cp->tag_at(index);
2237 jbyte result = tag.value();
2238 // If returned tag values are not from the JVM spec, e.g. tags from 100 to 105,
2239 // they are changed to the corresponding tags from the JVM spec, so that java code in
2240 // sun.reflect.ConstantPool will return only tags from the JVM spec, not internal ones.
2241 if (tag.is_klass_or_reference()) {
2242 result = JVM_CONSTANT_Class;
2243 } else if (tag.is_string_index()) {
2244 result = JVM_CONSTANT_String;
2245 } else if (tag.is_method_type_in_error()) {
2246 result = JVM_CONSTANT_MethodType;
2247 } else if (tag.is_method_handle_in_error()) {
2248 result = JVM_CONSTANT_MethodHandle;
2249 } else if (tag.is_dynamic_constant_in_error()) {
2250 result = JVM_CONSTANT_Dynamic;
2251 }
2252 return result;
2253 }
2254 JVM_END
2255
2256 // Assertion support. //////////////////////////////////////////////////////////
2257
2258 JVM_ENTRY_PROF(jboolean, JVM_DesiredAssertionStatus, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2259 assert(cls != nullptr, "bad class");
2260
2261 oop r = JNIHandles::resolve(cls);
2262 assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2263 if (java_lang_Class::is_primitive(r)) return false;
2264
2265 Klass* k = java_lang_Class::as_Klass(r);
2266 assert(k->is_instance_klass(), "must be an instance klass");
2267 if (!k->is_instance_klass()) return false;
2268
2269 ResourceMark rm(THREAD);
2270 const char* name = k->name()->as_C_string();
2271 bool system_class = k->class_loader() == nullptr;
2272 return JavaAssertions::enabled(name, system_class);
2273
2274 JVM_END
2275
2276
2277 // Return a new AssertionStatusDirectives object with the fields filled in with
2278 // command-line assertion arguments (i.e., -ea, -da).
2279 JVM_ENTRY_PROF(jobject, JVM_AssertionStatusDirectives, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2280 JvmtiVMObjectAllocEventCollector oam;
2281 oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2282 return JNIHandles::make_local(THREAD, asd);
2283 JVM_END
2284
2285 // Verification ////////////////////////////////////////////////////////////////////////////////
2286
2287 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2288
2289 // RedefineClasses support: bug 6214132 caused verification to fail.
2290 // All functions from this section, unless noted otherwise, should call the functions
2291 // get_klass_considering_redefinition(), or
2292 // get_instance_klass_considering_redefinition()
2293 // These functions return JvmtiThreadState::_scratch_class if the verifier
2294 // was invoked in the middle of the redefinition of cls.
2295 // See jvmtiThreadState.hpp for details.
2296
2297 inline Klass* get_klass_considering_redefinition(jclass cls, JavaThread* thread) {
2298 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2299 if (k->is_instance_klass()) {
2300 return JvmtiThreadState::class_to_verify_considering_redefinition(InstanceKlass::cast(k), thread);
2301 } else {
2302 return k;
2303 }
2304 }
2305
2306 inline InstanceKlass* get_instance_klass_considering_redefinition(jclass cls, JavaThread* thread) {
2307 InstanceKlass* ik = java_lang_Class::as_InstanceKlass(JNIHandles::resolve_non_null(cls));
2308 return JvmtiThreadState::class_to_verify_considering_redefinition(ik, thread);
2309 }
2310
2311 JVM_ENTRY_PROF(jboolean, JVM_IsInterface, JVM_IsInterface(JNIEnv *env, jclass cls))
2312 oop mirror = JNIHandles::resolve_non_null(cls);
2313 if (java_lang_Class::is_primitive(mirror)) {
2314 return JNI_FALSE;
2315 }
2316 Klass* k = java_lang_Class::as_Klass(mirror);
2317 // This isn't necessary since answer is the same because redefinition
2318 // has already checked this matches for the scratch class.
2319 // k = get_klass_considering_redefinition(cls, thread)
2320 jboolean result = k->is_interface();
2321 assert(!result || k->is_instance_klass(),
2322 "all interfaces are instance types");
2323 return result;
2324 JVM_END
2325
2326 JVM_ENTRY_PROF(const char*, JVM_GetClassNameUTF, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2327 // No need to call get_klass_considering_redefinition() as redefinition cannot change a class's name.
2328 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2329 return k->name()->as_utf8();
2330 JVM_END
2331
2332
2333 JVM_ENTRY_PROF(void, JVM_GetClassCPTypes, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2334 Klass* k = get_klass_considering_redefinition(cls, thread);
2335 // types will have length zero if this is not an InstanceKlass
2336 // (length is determined by call to JVM_GetClassCPEntriesCount)
2337 if (k->is_instance_klass()) {
2338 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2339 for (int index = cp->length() - 1; index >= 0; index--) {
2340 constantTag tag = cp->tag_at(index);
2341 types[index] = (tag.is_unresolved_klass()) ? (unsigned char) JVM_CONSTANT_Class : tag.value();
2342 }
2343 }
2344 JVM_END
2345
2346
2347 JVM_ENTRY_PROF(jint, JVM_GetClassCPEntriesCount, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2348 Klass* k = get_klass_considering_redefinition(cls, thread);
2349 return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->constants()->length();
2350 JVM_END
2351
2352
2353 JVM_ENTRY_PROF(jint, JVM_GetClassFieldsCount, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2354 Klass* k = get_klass_considering_redefinition(cls, thread);
2355 return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->java_fields_count();
2356 JVM_END
2357
2358
2359 JVM_ENTRY_PROF(jint, JVM_GetClassMethodsCount, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2360 Klass* k = get_klass_considering_redefinition(cls, thread);
2361 return (!k->is_instance_klass()) ? 0 : InstanceKlass::cast(k)->methods()->length();
2362 JVM_END
2363
2364
2365 // The following methods, used for the verifier, are never called with
2366 // array klasses, so a direct cast to InstanceKlass is safe.
2367 // Typically, these methods are called in a loop with bounds determined
2368 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2369 // zero for arrays.
2370 JVM_ENTRY_PROF(void, JVM_GetMethodIxExceptionIndexes, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2371 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2372 Method* method = ik->methods()->at(method_index);
2373 int length = method->checked_exceptions_length();
2374 if (length > 0) {
2375 CheckedExceptionElement* table= method->checked_exceptions_start();
2376 for (int i = 0; i < length; i++) {
2377 exceptions[i] = table[i].class_cp_index;
2378 }
2379 }
2380 JVM_END
2381
2382
2383 JVM_ENTRY_PROF(jint, JVM_GetMethodIxExceptionsCount, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2384 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2385 Method* method = ik->methods()->at(method_index);
2386 return method->checked_exceptions_length();
2387 JVM_END
2388
2389
2390 JVM_ENTRY_PROF(void, JVM_GetMethodIxByteCode, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2391 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2392 Method* method = ik->methods()->at(method_index);
2393 memcpy(code, method->code_base(), method->code_size());
2394 JVM_END
2395
2396
2397 JVM_ENTRY_PROF(jint, JVM_GetMethodIxByteCodeLength, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2398 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2399 Method* method = ik->methods()->at(method_index);
2400 return method->code_size();
2401 JVM_END
2402
2403
2404 JVM_ENTRY_PROF(void, JVM_GetMethodIxExceptionTableEntry, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2405 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2406 Method* method = ik->methods()->at(method_index);
2407 ExceptionTable extable(method);
2408 entry->start_pc = extable.start_pc(entry_index);
2409 entry->end_pc = extable.end_pc(entry_index);
2410 entry->handler_pc = extable.handler_pc(entry_index);
2411 entry->catchType = extable.catch_type_index(entry_index);
2412 JVM_END
2413
2414
2415 JVM_ENTRY_PROF(jint, JVM_GetMethodIxExceptionTableLength, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2416 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2417 Method* method = ik->methods()->at(method_index);
2418 return method->exception_table_length();
2419 JVM_END
2420
2421
2422 JVM_ENTRY_PROF(jint, JVM_GetMethodIxModifiers, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2423 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2424 Method* method = ik->methods()->at(method_index);
2425 return method->access_flags().as_method_flags();
2426 JVM_END
2427
2428
2429
2430 JVM_ENTRY_PROF(jint, JVM_GetFieldIxModifiers, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2431 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2432 return ik->field_access_flags(field_index);
2433 JVM_END
2434
2435
2436 JVM_ENTRY_PROF(jint, JVM_GetMethodIxLocalsCount, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2437 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2438 Method* method = ik->methods()->at(method_index);
2439 return method->max_locals();
2440 JVM_END
2441
2442
2443 JVM_ENTRY_PROF(jint, JVM_GetMethodIxArgsSize, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2444 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2445 Method* method = ik->methods()->at(method_index);
2446 return method->size_of_parameters();
2447 JVM_END
2448
2449
2450 JVM_ENTRY_PROF(jint, JVM_GetMethodIxMaxStack, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2451 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2452 Method* method = ik->methods()->at(method_index);
2453 return method->verifier_max_stack();
2454 JVM_END
2455
2456
2457 JVM_ENTRY_PROF(jboolean, JVM_IsConstructorIx, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2458 ResourceMark rm(THREAD);
2459 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2460 Method* method = ik->methods()->at(method_index);
2461 return method->name() == vmSymbols::object_initializer_name();
2462 JVM_END
2463
2464
2465 JVM_ENTRY_PROF(jboolean, JVM_IsVMGeneratedMethodIx, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2466 ResourceMark rm(THREAD);
2467 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2468 Method* method = ik->methods()->at(method_index);
2469 return method->is_overpass();
2470 JVM_END
2471
2472 JVM_ENTRY_PROF(const char*, JVM_GetMethodIxNameUTF, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2473 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2474 Method* method = ik->methods()->at(method_index);
2475 return method->name()->as_utf8();
2476 JVM_END
2477
2478
2479 JVM_ENTRY_PROF(const char*, JVM_GetMethodIxSignatureUTF, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2480 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2481 Method* method = ik->methods()->at(method_index);
2482 return method->signature()->as_utf8();
2483 JVM_END
2484
2485 /**
2486 * All of these JVM_GetCP-xxx methods are used by the old verifier to
2487 * read entries in the constant pool. Since the old verifier always
2488 * works on a copy of the code, it will not see any rewriting that
2489 * may possibly occur in the middle of verification. So it is important
2490 * that nothing it calls tries to use the cpCache instead of the raw
2491 * constant pool, so we must use cp->uncached_x methods when appropriate.
2492 */
2493 JVM_ENTRY_PROF(const char*, JVM_GetCPFieldNameUTF, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2494 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2495 ConstantPool* cp = ik->constants();
2496 switch (cp->tag_at(cp_index).value()) {
2497 case JVM_CONSTANT_Fieldref:
2498 return cp->uncached_name_ref_at(cp_index)->as_utf8();
2499 default:
2500 fatal("JVM_GetCPFieldNameUTF: illegal constant");
2501 }
2502 ShouldNotReachHere();
2503 return nullptr;
2504 JVM_END
2505
2506
2507 JVM_ENTRY_PROF(const char*, JVM_GetCPMethodNameUTF, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2508 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2509 ConstantPool* cp = ik->constants();
2510 switch (cp->tag_at(cp_index).value()) {
2511 case JVM_CONSTANT_InterfaceMethodref:
2512 case JVM_CONSTANT_Methodref:
2513 return cp->uncached_name_ref_at(cp_index)->as_utf8();
2514 default:
2515 fatal("JVM_GetCPMethodNameUTF: illegal constant");
2516 }
2517 ShouldNotReachHere();
2518 return nullptr;
2519 JVM_END
2520
2521
2522 JVM_ENTRY_PROF(const char*, JVM_GetCPMethodSignatureUTF, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2523 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2524 ConstantPool* cp = ik->constants();
2525 switch (cp->tag_at(cp_index).value()) {
2526 case JVM_CONSTANT_InterfaceMethodref:
2527 case JVM_CONSTANT_Methodref:
2528 return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2529 default:
2530 fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2531 }
2532 ShouldNotReachHere();
2533 return nullptr;
2534 JVM_END
2535
2536
2537 JVM_ENTRY_PROF(const char*, JVM_GetCPFieldSignatureUTF, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2538 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2539 ConstantPool* cp = ik->constants();
2540 switch (cp->tag_at(cp_index).value()) {
2541 case JVM_CONSTANT_Fieldref:
2542 return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2543 default:
2544 fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2545 }
2546 ShouldNotReachHere();
2547 return nullptr;
2548 JVM_END
2549
2550
2551 JVM_ENTRY_PROF(const char*, JVM_GetCPClassNameUTF, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2552 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2553 ConstantPool* cp = ik->constants();
2554 Symbol* classname = cp->klass_name_at(cp_index);
2555 return classname->as_utf8();
2556 JVM_END
2557
2558
2559 JVM_ENTRY_PROF(const char*, JVM_GetCPFieldClassNameUTF, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2560 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2561 ConstantPool* cp = ik->constants();
2562 switch (cp->tag_at(cp_index).value()) {
2563 case JVM_CONSTANT_Fieldref: {
2564 int class_index = cp->uncached_klass_ref_index_at(cp_index);
2565 Symbol* classname = cp->klass_name_at(class_index);
2566 return classname->as_utf8();
2567 }
2568 default:
2569 fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2570 }
2571 ShouldNotReachHere();
2572 return nullptr;
2573 JVM_END
2574
2575
2576 JVM_ENTRY_PROF(const char*, JVM_GetCPMethodClassNameUTF, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2577 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2578 ConstantPool* cp = ik->constants();
2579 switch (cp->tag_at(cp_index).value()) {
2580 case JVM_CONSTANT_Methodref:
2581 case JVM_CONSTANT_InterfaceMethodref: {
2582 int class_index = cp->uncached_klass_ref_index_at(cp_index);
2583 Symbol* classname = cp->klass_name_at(class_index);
2584 return classname->as_utf8();
2585 }
2586 default:
2587 fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2588 }
2589 ShouldNotReachHere();
2590 return nullptr;
2591 JVM_END
2592
2593
2594 JVM_ENTRY_PROF(jint, JVM_GetCPFieldModifiers, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2595 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2596 InstanceKlass* ik_called = get_instance_klass_considering_redefinition(called_cls, thread);
2597 ConstantPool* cp = ik->constants();
2598 ConstantPool* cp_called = ik_called->constants();
2599 switch (cp->tag_at(cp_index).value()) {
2600 case JVM_CONSTANT_Fieldref: {
2601 Symbol* name = cp->uncached_name_ref_at(cp_index);
2602 Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2603 for (JavaFieldStream fs(ik_called); !fs.done(); fs.next()) {
2604 if (fs.name() == name && fs.signature() == signature) {
2605 return fs.access_flags().as_field_flags();
2606 }
2607 }
2608 return -1;
2609 }
2610 default:
2611 fatal("JVM_GetCPFieldModifiers: illegal constant");
2612 }
2613 ShouldNotReachHere();
2614 return 0;
2615 JVM_END
2616
2617
2618 JVM_ENTRY_PROF(jint, JVM_GetCPMethodModifiers, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2619 InstanceKlass* ik = get_instance_klass_considering_redefinition(cls, thread);
2620 InstanceKlass* ik_called = get_instance_klass_considering_redefinition(called_cls, thread);
2621 ConstantPool* cp = ik->constants();
2622 switch (cp->tag_at(cp_index).value()) {
2623 case JVM_CONSTANT_Methodref:
2624 case JVM_CONSTANT_InterfaceMethodref: {
2625 Symbol* name = cp->uncached_name_ref_at(cp_index);
2626 Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2627 Array<Method*>* methods = ik_called->methods();
2628 int methods_count = methods->length();
2629 for (int i = 0; i < methods_count; i++) {
2630 Method* method = methods->at(i);
2631 if (method->name() == name && method->signature() == signature) {
2632 return method->access_flags().as_method_flags();
2633 }
2634 }
2635 return -1;
2636 }
2637 default:
2638 fatal("JVM_GetCPMethodModifiers: illegal constant");
2639 }
2640 ShouldNotReachHere();
2641 return 0;
2642 JVM_END
2643
2644
2645 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2646
2647 JVM_LEAF_PROF(void, JVM_ReleaseUTF, JVM_ReleaseUTF(const char *utf))
2648 // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2649 JVM_END
2650
2651
2652 JVM_ENTRY_PROF(jboolean, JVM_IsSameClassPackage, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2653 oop class1_mirror = JNIHandles::resolve_non_null(class1);
2654 oop class2_mirror = JNIHandles::resolve_non_null(class2);
2655 Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2656 Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2657 return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2658 JVM_END
2659
2660 // Printing support //////////////////////////////////////////////////
2661 extern "C" {
2662
2663 ATTRIBUTE_PRINTF(3, 0)
2664 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2665 // Reject count values that are negative signed values converted to
2666 // unsigned; see bug 4399518, 4417214
2667 if ((intptr_t)count <= 0) return -1;
2668
2669 int result = os::vsnprintf(str, count, fmt, args);
2670 if (result > 0 && (size_t)result >= count) {
2671 result = -1;
2672 }
2673
2674 return result;
2675 }
2676
2677 ATTRIBUTE_PRINTF(3, 4)
2678 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2679 va_list args;
2680 int len;
2681 va_start(args, fmt);
2682 len = jio_vsnprintf(str, count, fmt, args);
2683 va_end(args);
2684 return len;
2685 }
2686
2687 ATTRIBUTE_PRINTF(2, 3)
2688 int jio_fprintf(FILE* f, const char *fmt, ...) {
2689 int len;
2690 va_list args;
2691 va_start(args, fmt);
2692 len = jio_vfprintf(f, fmt, args);
2693 va_end(args);
2694 return len;
2695 }
2696
2697 ATTRIBUTE_PRINTF(2, 0)
2698 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2699 if (Arguments::vfprintf_hook() != nullptr) {
2700 return Arguments::vfprintf_hook()(f, fmt, args);
2701 } else {
2702 return vfprintf(f, fmt, args);
2703 }
2704 }
2705
2706 ATTRIBUTE_PRINTF(1, 2)
2707 JNIEXPORT int jio_printf(const char *fmt, ...) {
2708 int len;
2709 va_list args;
2710 va_start(args, fmt);
2711 len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2712 va_end(args);
2713 return len;
2714 }
2715
2716 // HotSpot specific jio method
2717 void jio_print(const char* s, size_t len) {
2718 // Try to make this function as atomic as possible.
2719 if (Arguments::vfprintf_hook() != nullptr) {
2720 jio_fprintf(defaultStream::output_stream(), "%.*s", (int)len, s);
2721 } else {
2722 // Make an unused local variable to avoid warning from gcc compiler.
2723 bool dummy = os::write(defaultStream::output_fd(), s, len);
2724 }
2725 }
2726
2727 } // Extern C
2728
2729 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2730
2731 // In most of the JVM thread support functions we need to access the
2732 // thread through a ThreadsListHandle to prevent it from exiting and
2733 // being reclaimed while we try to operate on it. The exceptions to this
2734 // rule are when operating on the current thread, or if the monitor of
2735 // the target java.lang.Thread is locked at the Java level - in both
2736 // cases the target cannot exit.
2737
2738 static void thread_entry(JavaThread* thread, TRAPS) {
2739 HandleMark hm(THREAD);
2740 Handle obj(THREAD, thread->threadObj());
2741 JavaValue result(T_VOID);
2742 JavaCalls::call_virtual(&result,
2743 obj,
2744 vmClasses::Thread_klass(),
2745 vmSymbols::run_method_name(),
2746 vmSymbols::void_method_signature(),
2747 THREAD);
2748 }
2749
2750
2751 JVM_ENTRY_PROF(void, JVM_StartThread, JVM_StartThread(JNIEnv* env, jobject jthread))
2752 #if INCLUDE_CDS
2753 if (CDSConfig::allow_only_single_java_thread()) {
2754 // During java -Xshare:dump, if we allow multiple Java threads to
2755 // execute in parallel, symbols and classes may be loaded in
2756 // random orders which will make the resulting CDS archive
2757 // non-deterministic.
2758 //
2759 // Lucikly, during java -Xshare:dump, it's important to run only
2760 // the code in the main Java thread (which is NOT started here) that
2761 // creates the module graph, etc. It's safe to not start the other
2762 // threads which are launched by class static initializers
2763 // (ReferenceHandler, FinalizerThread and CleanerImpl).
2764 if (log_is_enabled(Info, aot)) {
2765 ResourceMark rm;
2766 oop t = JNIHandles::resolve_non_null(jthread);
2767 log_info(aot)("JVM_StartThread() ignored: %s", t->klass()->external_name());
2768 }
2769 return;
2770 }
2771 #endif
2772 JavaThread *native_thread = nullptr;
2773
2774 // We cannot hold the Threads_lock when we throw an exception,
2775 // due to rank ordering issues. Example: we might need to grab the
2776 // Heap_lock while we construct the exception.
2777 bool throw_illegal_thread_state = false;
2778
2779 // We must release the Threads_lock before we can post a jvmti event
2780 // in Thread::start.
2781 {
2782 ConditionalMutexLocker throttle_ml(ThreadsLockThrottle_lock, UseThreadsLockThrottleLock);
2783 // Ensure that the C++ Thread and OSThread structures aren't freed before
2784 // we operate.
2785 MutexLocker ml(Threads_lock);
2786
2787 // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
2788 // re-starting an already started thread, so we should usually find
2789 // that the JavaThread is null. However for a JNI attached thread
2790 // there is a small window between the Thread object being created
2791 // (with its JavaThread set) and the update to its threadStatus, so we
2792 // have to check for this
2793 if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != nullptr) {
2794 throw_illegal_thread_state = true;
2795 } else {
2796 jlong size =
2797 java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
2798 // Allocate the C++ Thread structure and create the native thread. The
2799 // stack size retrieved from java is 64-bit signed, but the constructor takes
2800 // size_t (an unsigned type), which may be 32 or 64-bit depending on the platform.
2801 // - Avoid truncating on 32-bit platforms if size is greater than UINT_MAX.
2802 // - Avoid passing negative values which would result in really large stacks.
2803 NOT_LP64(if (size > SIZE_MAX) size = SIZE_MAX;)
2804 size_t sz = size > 0 ? (size_t) size : 0;
2805 native_thread = new JavaThread(&thread_entry, sz);
2806
2807 // At this point it may be possible that no osthread was created for the
2808 // JavaThread due to lack of memory. Check for this situation and throw
2809 // an exception if necessary. Eventually we may want to change this so
2810 // that we only grab the lock if the thread was created successfully -
2811 // then we can also do this check and throw the exception in the
2812 // JavaThread constructor.
2813 if (native_thread->osthread() != nullptr) {
2814 // Note: the current thread is not being used within "prepare".
2815 native_thread->prepare(jthread);
2816 }
2817 }
2818 }
2819
2820 if (throw_illegal_thread_state) {
2821 THROW(vmSymbols::java_lang_IllegalThreadStateException());
2822 }
2823
2824 assert(native_thread != nullptr, "Starting null thread?");
2825
2826 if (native_thread->osthread() == nullptr) {
2827 ResourceMark rm(thread);
2828 log_warning(os, thread)("Failed to start the native thread for java.lang.Thread \"%s\"",
2829 JavaThread::name_for(JNIHandles::resolve_non_null(jthread)));
2830 // No one should hold a reference to the 'native_thread'.
2831 native_thread->smr_delete();
2832 if (JvmtiExport::should_post_resource_exhausted()) {
2833 JvmtiExport::post_resource_exhausted(
2834 JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
2835 os::native_thread_creation_failed_msg());
2836 }
2837 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
2838 os::native_thread_creation_failed_msg());
2839 }
2840
2841 JFR_ONLY(Jfr::on_java_thread_start(thread, native_thread);)
2842
2843 Thread::start(native_thread);
2844
2845 JVM_END
2846
2847
2848 JVM_ENTRY_PROF(void, JVM_SetThreadPriority, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
2849 ThreadsListHandle tlh(thread);
2850 oop java_thread = nullptr;
2851 JavaThread* receiver = nullptr;
2852 bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, &java_thread);
2853 java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
2854
2855 if (is_alive) {
2856 // jthread refers to a live JavaThread.
2857 Thread::set_priority(receiver, (ThreadPriority)prio);
2858 }
2859 // Implied else: If the JavaThread hasn't started yet, then the
2860 // priority set in the java.lang.Thread object above will be pushed
2861 // down when it does start.
2862 JVM_END
2863
2864
2865 JVM_LEAF_PROF(void, JVM_Yield, JVM_Yield(JNIEnv *env, jclass threadClass))
2866 HOTSPOT_THREAD_YIELD();
2867 os::naked_yield();
2868 JVM_END
2869
2870 JVM_ENTRY_PROF(void, JVM_SleepNanos, JVM_SleepNanos(JNIEnv* env, jclass threadClass, jlong nanos))
2871 if (nanos < 0) {
2872 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "nanosecond timeout value out of range");
2873 }
2874
2875 if (thread->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
2876 THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2877 }
2878
2879 // Save current thread state and restore it at the end of this block.
2880 // And set new thread state to SLEEPING.
2881 JavaThreadSleepState jtss(thread);
2882
2883 HOTSPOT_THREAD_SLEEP_BEGIN(nanos / NANOSECS_PER_MILLISEC);
2884
2885 if (nanos == 0) {
2886 os::naked_yield();
2887 } else {
2888 ThreadState old_state = thread->osthread()->get_state();
2889 thread->osthread()->set_state(SLEEPING);
2890 if (!thread->sleep_nanos(nanos)) { // interrupted or async exception was installed
2891 // An asynchronous exception could have been thrown on
2892 // us while we were sleeping. We do not overwrite those.
2893 if (!HAS_PENDING_EXCEPTION) {
2894 HOTSPOT_THREAD_SLEEP_END(1);
2895 if (!thread->has_async_exception_condition()) {
2896 // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
2897 // to properly restore the thread state. That's likely wrong.
2898 THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
2899 }
2900 }
2901 }
2902 thread->osthread()->set_state(old_state);
2903 }
2904 HOTSPOT_THREAD_SLEEP_END(0);
2905 JVM_END
2906
2907 JVM_ENTRY_PROF(jobject, JVM_CurrentCarrierThread, JVM_CurrentCarrierThread(JNIEnv* env, jclass threadClass))
2908 oop jthread = thread->threadObj();
2909 assert(jthread != nullptr, "no current carrier thread!");
2910 return JNIHandles::make_local(THREAD, jthread);
2911 JVM_END
2912
2913 JVM_ENTRY_PROF(jobject, JVM_CurrentThread, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
2914 oop theThread = thread->vthread();
2915 assert(theThread != (oop)nullptr, "no current thread!");
2916 return JNIHandles::make_local(THREAD, theThread);
2917 JVM_END
2918
2919 JVM_ENTRY_PROF(void, JVM_SetCurrentThread, JVM_SetCurrentThread(JNIEnv* env, jobject thisThread,
2920 jobject theThread))
2921 oop threadObj = JNIHandles::resolve(theThread);
2922 thread->set_vthread(threadObj);
2923
2924 // Set _monitor_owner_id of new current Thread
2925 thread->set_monitor_owner_id(java_lang_Thread::thread_id(threadObj));
2926
2927 JFR_ONLY(Jfr::on_set_current_thread(thread, threadObj);)
2928 JVM_END
2929
2930 JVM_ENTRY_PROF(jlong, JVM_GetNextThreadIdOffset, JVM_GetNextThreadIdOffset(JNIEnv* env, jclass threadClass))
2931 return ThreadIdentifier::unsafe_offset();
2932 JVM_END
2933
2934 JVM_ENTRY_PROF(void, JVM_Interrupt, JVM_Interrupt(JNIEnv* env, jobject jthread))
2935 ThreadsListHandle tlh(thread);
2936 JavaThread* receiver = nullptr;
2937 bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, nullptr);
2938 if (is_alive) {
2939 // jthread refers to a live JavaThread.
2940 receiver->interrupt();
2941 }
2942 JVM_END
2943
2944 // Return true iff the current thread has locked the object passed in
2945
2946 JVM_ENTRY_PROF(jboolean, JVM_HoldsLock, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
2947 if (obj == nullptr) {
2948 THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
2949 }
2950 Handle h_obj(THREAD, JNIHandles::resolve(obj));
2951 return ObjectSynchronizer::current_thread_holds_lock(thread, h_obj);
2952 JVM_END
2953
2954 JVM_ENTRY_PROF(jobject, JVM_GetStackTrace, JVM_GetStackTrace(JNIEnv *env, jobject jthread))
2955 oop trace = java_lang_Thread::async_get_stack_trace(jthread, THREAD);
2956 return JNIHandles::make_local(THREAD, trace);
2957 JVM_END
2958
2959 JVM_ENTRY_PROF(jobject, JVM_CreateThreadSnapshot, JVM_CreateThreadSnapshot(JNIEnv* env, jobject jthread))
2960 #if INCLUDE_JVMTI
2961 oop snapshot = ThreadSnapshotFactory::get_thread_snapshot(jthread, THREAD);
2962 return JNIHandles::make_local(THREAD, snapshot);
2963 #else
2964 THROW_NULL(vmSymbols::java_lang_UnsupportedOperationException());
2965 #endif
2966 JVM_END
2967
2968 JVM_ENTRY_PROF(void, JVM_SetNativeThreadName, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
2969 // We don't use a ThreadsListHandle here because the current thread
2970 // must be alive.
2971 oop java_thread = JNIHandles::resolve_non_null(jthread);
2972 JavaThread* thr = java_lang_Thread::thread(java_thread);
2973 if (thread == thr && !thr->has_attached_via_jni()) {
2974 // Thread naming is only supported for the current thread and
2975 // we don't set the name of an attached thread to avoid stepping
2976 // on other programs.
2977 ResourceMark rm(thread);
2978 const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
2979 os::set_native_thread_name(thread_name);
2980 }
2981 JVM_END
2982
2983 JVM_ENTRY_PROF(jobject, JVM_ScopedValueCache, JVM_ScopedValueCache(JNIEnv* env, jclass threadClass))
2984 oop theCache = thread->scopedValueCache();
2985 return JNIHandles::make_local(THREAD, theCache);
2986 JVM_END
2987
2988 JVM_ENTRY_PROF(void, JVM_SetScopedValueCache, JVM_SetScopedValueCache(JNIEnv* env, jclass threadClass,
2989 jobject theCache))
2990 arrayOop objs = arrayOop(JNIHandles::resolve(theCache));
2991 thread->set_scopedValueCache(objs);
2992 JVM_END
2993
2994 // java.lang.Package ////////////////////////////////////////////////////////////////
2995
2996
2997 JVM_ENTRY_PROF(jstring, JVM_GetSystemPackage, JVM_GetSystemPackage(JNIEnv *env, jstring name))
2998 ResourceMark rm(THREAD);
2999 JvmtiVMObjectAllocEventCollector oam;
3000 char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3001 oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3002 return (jstring) JNIHandles::make_local(THREAD, result);
3003 JVM_END
3004
3005
3006 JVM_ENTRY_PROF(jobjectArray, JVM_GetSystemPackages, JVM_GetSystemPackages(JNIEnv *env))
3007 JvmtiVMObjectAllocEventCollector oam;
3008 objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3009 return (jobjectArray) JNIHandles::make_local(THREAD, result);
3010 JVM_END
3011
3012
3013 // java.lang.ref.Reference ///////////////////////////////////////////////////////////////
3014
3015
3016 JVM_ENTRY_PROF(jobject, JVM_GetAndClearReferencePendingList, JVM_GetAndClearReferencePendingList(JNIEnv* env))
3017 MonitorLocker ml(Heap_lock);
3018 oop ref = Universe::reference_pending_list();
3019 if (ref != nullptr) {
3020 Universe::clear_reference_pending_list();
3021 }
3022 return JNIHandles::make_local(THREAD, ref);
3023 JVM_END
3024
3025 JVM_ENTRY_PROF(jboolean, JVM_HasReferencePendingList, JVM_HasReferencePendingList(JNIEnv* env))
3026 MonitorLocker ml(Heap_lock);
3027 return Universe::has_reference_pending_list();
3028 JVM_END
3029
3030 JVM_ENTRY_PROF(void, JVM_WaitForReferencePendingList, JVM_WaitForReferencePendingList(JNIEnv* env))
3031 MonitorLocker ml(Heap_lock);
3032 while (!Universe::has_reference_pending_list()) {
3033 ml.wait();
3034 }
3035 JVM_END
3036
3037 JVM_ENTRY_PROF(jobject, JVM_ReferenceGet, JVM_ReferenceGet(JNIEnv* env, jobject ref))
3038 oop ref_oop = JNIHandles::resolve_non_null(ref);
3039 // PhantomReference has its own implementation of get().
3040 assert(!java_lang_ref_Reference::is_phantom(ref_oop), "precondition");
3041 oop referent = java_lang_ref_Reference::weak_referent(ref_oop);
3042 return JNIHandles::make_local(THREAD, referent);
3043 JVM_END
3044
3045 JVM_ENTRY_PROF(jboolean, JVM_ReferenceRefersTo, JVM_ReferenceRefersTo(JNIEnv* env, jobject ref, jobject o))
3046 oop ref_oop = JNIHandles::resolve_non_null(ref);
3047 // PhantomReference has its own implementation of refersTo().
3048 // See: JVM_PhantomReferenceRefersTo
3049 assert(!java_lang_ref_Reference::is_phantom(ref_oop), "precondition");
3050 oop referent = java_lang_ref_Reference::weak_referent_no_keepalive(ref_oop);
3051 return referent == JNIHandles::resolve(o);
3052 JVM_END
3053
3054 JVM_ENTRY_PROF(void, JVM_ReferenceClear, JVM_ReferenceClear(JNIEnv* env, jobject ref))
3055 oop ref_oop = JNIHandles::resolve_non_null(ref);
3056 // FinalReference has it's own implementation of clear().
3057 assert(!java_lang_ref_Reference::is_final(ref_oop), "precondition");
3058 if (java_lang_ref_Reference::unknown_referent_no_keepalive(ref_oop) == nullptr) {
3059 // If the referent has already been cleared then done.
3060 // However, if the referent is dead but has not yet been cleared by
3061 // concurrent reference processing, it should NOT be cleared here.
3062 // Instead, clearing should be left to the GC. Clearing it here could
3063 // detectably lose an expected notification, which is impossible with
3064 // STW reference processing. The clearing in enqueue() doesn't have
3065 // this problem, since the enqueue covers the notification, but it's not
3066 // worth the effort to handle that case specially.
3067 return;
3068 }
3069 java_lang_ref_Reference::clear_referent(ref_oop);
3070 JVM_END
3071
3072
3073 // java.lang.ref.PhantomReference //////////////////////////////////////////////////
3074
3075
3076 JVM_ENTRY_PROF(jboolean, JVM_PhantomReferenceRefersTo, JVM_PhantomReferenceRefersTo(JNIEnv* env, jobject ref, jobject o))
3077 oop ref_oop = JNIHandles::resolve_non_null(ref);
3078 oop referent = java_lang_ref_Reference::phantom_referent_no_keepalive(ref_oop);
3079 return referent == JNIHandles::resolve(o);
3080 JVM_END
3081
3082
3083 // ObjectInputStream ///////////////////////////////////////////////////////////////
3084
3085 // Return the first user-defined class loader up the execution stack, or null
3086 // if only code from the bootstrap or platform class loader is on the stack.
3087
3088 JVM_ENTRY_PROF(jobject, JVM_LatestUserDefinedLoader, JVM_LatestUserDefinedLoader(JNIEnv *env))
3089 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3090 InstanceKlass* ik = vfst.method()->method_holder();
3091 oop loader = ik->class_loader();
3092 if (loader != nullptr && !SystemDictionary::is_platform_class_loader(loader)) {
3093 return JNIHandles::make_local(THREAD, loader);
3094 }
3095 }
3096 return nullptr;
3097 JVM_END
3098
3099
3100 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3101
3102
3103 // resolve array handle and check arguments
3104 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3105 if (arr == nullptr) {
3106 THROW_NULL(vmSymbols::java_lang_NullPointerException());
3107 }
3108 oop a = JNIHandles::resolve_non_null(arr);
3109 if (!a->is_array()) {
3110 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3111 } else if (type_array_only && !a->is_typeArray()) {
3112 THROW_MSG_NULL(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array of primitive type");
3113 }
3114 return arrayOop(a);
3115 }
3116
3117
3118 JVM_ENTRY_PROF(jint, JVM_GetArrayLength, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3119 arrayOop a = check_array(env, arr, false, CHECK_0);
3120 return a->length();
3121 JVM_END
3122
3123
3124 JVM_ENTRY_PROF(jobject, JVM_GetArrayElement, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3125 JvmtiVMObjectAllocEventCollector oam;
3126 arrayOop a = check_array(env, arr, false, CHECK_NULL);
3127 jvalue value;
3128 BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3129 oop box = Reflection::box(&value, type, CHECK_NULL);
3130 return JNIHandles::make_local(THREAD, box);
3131 JVM_END
3132
3133
3134 JVM_ENTRY_PROF(jvalue, JVM_GetPrimitiveArrayElement, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3135 jvalue value;
3136 value.i = 0; // to initialize value before getting used in CHECK
3137 arrayOop a = check_array(env, arr, true, CHECK_(value));
3138 assert(a->is_typeArray(), "just checking");
3139 BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3140 BasicType wide_type = (BasicType) wCode;
3141 if (type != wide_type) {
3142 Reflection::widen(&value, type, wide_type, CHECK_(value));
3143 }
3144 return value;
3145 JVM_END
3146
3147
3148 JVM_ENTRY_PROF(void, JVM_SetArrayElement, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3149 arrayOop a = check_array(env, arr, false, CHECK);
3150 oop box = JNIHandles::resolve(val);
3151 jvalue value;
3152 value.i = 0; // to initialize value before getting used in CHECK
3153 BasicType value_type;
3154 if (a->is_objArray()) {
3155 // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3156 value_type = Reflection::unbox_for_regular_object(box, &value);
3157 } else {
3158 value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3159 }
3160 Reflection::array_set(&value, a, index, value_type, CHECK);
3161 JVM_END
3162
3163
3164 JVM_ENTRY_PROF(void, JVM_SetPrimitiveArrayElement, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3165 arrayOop a = check_array(env, arr, true, CHECK);
3166 assert(a->is_typeArray(), "just checking");
3167 BasicType value_type = (BasicType) vCode;
3168 Reflection::array_set(&v, a, index, value_type, CHECK);
3169 JVM_END
3170
3171
3172 JVM_ENTRY_PROF(jobject, JVM_NewArray, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3173 JvmtiVMObjectAllocEventCollector oam;
3174 oop element_mirror = JNIHandles::resolve(eltClass);
3175 oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3176 return JNIHandles::make_local(THREAD, result);
3177 JVM_END
3178
3179
3180 JVM_ENTRY_PROF(jobject, JVM_NewMultiArray, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3181 JvmtiVMObjectAllocEventCollector oam;
3182 arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3183 oop element_mirror = JNIHandles::resolve(eltClass);
3184 assert(dim_array->is_typeArray(), "just checking");
3185 oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3186 return JNIHandles::make_local(THREAD, result);
3187 JVM_END
3188
3189
3190 // Library support ///////////////////////////////////////////////////////////////////////////
3191
3192 JVM_LEAF_PROF(void*, JVM_LoadZipLibrary, JVM_LoadZipLibrary())
3193 return ZipLibrary::handle();
3194 JVM_END
3195
3196 JVM_ENTRY_NO_ENV_PROF(void*, JVM_LoadLibrary, JVM_LoadLibrary(const char* name, jboolean throwException))
3197 //%note jvm_ct
3198 char ebuf[1024];
3199 void *load_result;
3200 {
3201 ThreadToNativeFromVM ttnfvm(thread);
3202 load_result = os::dll_load(name, ebuf, sizeof ebuf);
3203 }
3204 if (load_result == nullptr) {
3205 if (throwException) {
3206 char msg[1024];
3207 jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
3208 // Since 'ebuf' may contain a string encoded using
3209 // platform encoding scheme, we need to pass
3210 // Exceptions::unsafe_to_utf8 to the new_exception method
3211 // as the last argument. See bug 6367357.
3212 Handle h_exception =
3213 Exceptions::new_exception(thread,
3214 vmSymbols::java_lang_UnsatisfiedLinkError(),
3215 msg, Exceptions::unsafe_to_utf8);
3216
3217 THROW_HANDLE_NULL(h_exception);
3218 } else {
3219 log_info(library)("Failed to load library %s", name);
3220 return load_result;
3221 }
3222 }
3223 log_info(library)("Loaded library %s, handle " INTPTR_FORMAT, name, p2i(load_result));
3224 return load_result;
3225 JVM_END
3226
3227
3228 JVM_LEAF_PROF(void, JVM_UnloadLibrary, JVM_UnloadLibrary(void* handle))
3229 os::dll_unload(handle);
3230 log_info(library)("Unloaded library with handle " INTPTR_FORMAT, p2i(handle));
3231 JVM_END
3232
3233
3234 JVM_LEAF_PROF(void*, JVM_FindLibraryEntry, JVM_FindLibraryEntry(void* handle, const char* name))
3235 void* find_result = os::dll_lookup(handle, name);
3236 log_info(library)("%s %s in library with handle " INTPTR_FORMAT,
3237 find_result != nullptr ? "Found" : "Failed to find",
3238 name, p2i(handle));
3239 return find_result;
3240 JVM_END
3241
3242
3243 // JNI version ///////////////////////////////////////////////////////////////////////////////
3244
3245 JVM_LEAF_PROF(jboolean, JVM_IsSupportedJNIVersion, JVM_IsSupportedJNIVersion(jint version))
3246 return Threads::is_supported_jni_version_including_1_1(version);
3247 JVM_END
3248
3249
3250 JVM_LEAF_PROF(jboolean, JVM_IsPreviewEnabled, JVM_IsPreviewEnabled(void))
3251 return Arguments::enable_preview() ? JNI_TRUE : JNI_FALSE;
3252 JVM_END
3253
3254 JVM_LEAF_PROF(jboolean, JVM_IsContinuationsSupported, JVM_IsContinuationsSupported(void))
3255 return VMContinuations ? JNI_TRUE : JNI_FALSE;
3256 JVM_END
3257
3258 JVM_LEAF_PROF(jboolean, JVM_IsForeignLinkerSupported, JVM_IsForeignLinkerSupported(void))
3259 return ForeignGlobals::is_foreign_linker_supported() ? JNI_TRUE : JNI_FALSE;
3260 JVM_END
3261
3262 JVM_LEAF(jboolean, JVM_IsStaticallyLinked(void))
3263 return is_vm_statically_linked() ? JNI_TRUE : JNI_FALSE;
3264 JVM_END
3265
3266 // String support ///////////////////////////////////////////////////////////////////////////
3267
3268 JVM_ENTRY_PROF(jstring, JVM_InternString, JVM_InternString(JNIEnv *env, jstring str))
3269 JvmtiVMObjectAllocEventCollector oam;
3270 if (str == nullptr) return nullptr;
3271 oop string = JNIHandles::resolve_non_null(str);
3272 oop result = StringTable::intern(string, CHECK_NULL);
3273 return (jstring) JNIHandles::make_local(THREAD, result);
3274 JVM_END
3275
3276
3277 // VM Raw monitor support //////////////////////////////////////////////////////////////////////
3278
3279 // VM Raw monitors (not to be confused with JvmtiRawMonitors) are a simple mutual exclusion
3280 // lock (not actually monitors: no wait/notify) that is exported by the VM for use by JDK
3281 // library code. They may be used by JavaThreads and non-JavaThreads and do not participate
3282 // in the safepoint protocol, thread suspension, thread interruption, or most things of that
3283 // nature, except JavaThreads will be blocked by VM_Exit::block_if_vm_exited if the VM has
3284 // shutdown. JavaThreads will be "in native" when using this API from JDK code.
3285
3286
3287 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
3288 VM_Exit::block_if_vm_exited();
3289 return new PlatformMutex();
3290 }
3291
3292
3293 JNIEXPORT void JNICALL JVM_RawMonitorDestroy(void *mon) {
3294 VM_Exit::block_if_vm_exited();
3295 delete ((PlatformMutex*) mon);
3296 }
3297
3298
3299 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
3300 VM_Exit::block_if_vm_exited();
3301 ((PlatformMutex*) mon)->lock();
3302 return 0;
3303 }
3304
3305
3306 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
3307 VM_Exit::block_if_vm_exited();
3308 ((PlatformMutex*) mon)->unlock();
3309 }
3310
3311
3312 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
3313
3314 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
3315 Handle loader, jboolean throwError, TRAPS) {
3316 Klass* klass = SystemDictionary::resolve_or_fail(name, loader, throwError != 0, CHECK_NULL);
3317
3318 // Check if we should initialize the class
3319 if (init && klass->is_instance_klass()) {
3320 klass->initialize(CHECK_NULL);
3321 }
3322 return (jclass) JNIHandles::make_local(THREAD, klass->java_mirror());
3323 }
3324
3325
3326 // Method ///////////////////////////////////////////////////////////////////////////////////////////
3327
3328 JVM_ENTRY_PROF(jobject, JVM_InvokeMethod, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
3329 Handle method_handle;
3330 if (thread->stack_overflow_state()->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
3331 method_handle = Handle(THREAD, JNIHandles::resolve(method));
3332 Handle receiver(THREAD, JNIHandles::resolve(obj));
3333 objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3334 oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
3335 jobject res = JNIHandles::make_local(THREAD, result);
3336 if (JvmtiExport::should_post_vm_object_alloc()) {
3337 oop ret_type = java_lang_reflect_Method::return_type(method_handle());
3338 assert(ret_type != nullptr, "sanity check: ret_type oop must not be null!");
3339 if (java_lang_Class::is_primitive(ret_type)) {
3340 // Only for primitive type vm allocates memory for java object.
3341 // See box() method.
3342 JvmtiExport::post_vm_object_alloc(thread, result);
3343 }
3344 }
3345 return res;
3346 } else {
3347 THROW_NULL(vmSymbols::java_lang_StackOverflowError());
3348 }
3349 JVM_END
3350
3351
3352 JVM_ENTRY_PROF(jobject, JVM_NewInstanceFromConstructor, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
3353 oop constructor_mirror = JNIHandles::resolve(c);
3354 objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
3355 oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
3356 jobject res = JNIHandles::make_local(THREAD, result);
3357 if (JvmtiExport::should_post_vm_object_alloc()) {
3358 JvmtiExport::post_vm_object_alloc(thread, result);
3359 }
3360 return res;
3361 JVM_END
3362
3363 JVM_ENTRY_PROF(void, JVM_InitializeFromArchive, JVM_InitializeFromArchive(JNIEnv* env, jclass cls))
3364 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
3365 HeapShared::initialize_from_archived_subgraph(THREAD, k);
3366 JVM_END
3367
3368 JVM_ENTRY_PROF(void, JVM_RegisterLambdaProxyClassForArchiving, JVM_RegisterLambdaProxyClassForArchiving(JNIEnv* env,
3369 jclass caller,
3370 jstring interfaceMethodName,
3371 jobject factoryType,
3372 jobject interfaceMethodType,
3373 jobject implementationMember,
3374 jobject dynamicMethodType,
3375 jclass lambdaProxyClass))
3376 #if INCLUDE_CDS
3377 if (!CDSConfig::is_dumping_archive() || !CDSConfig::is_dumping_lambdas_in_legacy_mode()) {
3378 return;
3379 }
3380
3381 InstanceKlass* caller_ik = java_lang_Class::as_InstanceKlass(JNIHandles::resolve(caller));
3382 if (caller_ik->is_hidden()) {
3383 // Hidden classes not of type lambda proxy classes are currently not being archived.
3384 // If the caller_ik is of one of the above types, the corresponding lambda proxy class won't be
3385 // registered for archiving.
3386 return;
3387 }
3388 InstanceKlass* lambda_ik = java_lang_Class::as_InstanceKlass(JNIHandles::resolve(lambdaProxyClass));
3389 assert(lambda_ik->is_hidden(), "must be a hidden class");
3390 assert(!lambda_ik->is_non_strong_hidden(), "expected a strong hidden class");
3391
3392 Symbol* interface_method_name = nullptr;
3393 if (interfaceMethodName != nullptr) {
3394 interface_method_name = java_lang_String::as_symbol(JNIHandles::resolve_non_null(interfaceMethodName));
3395 }
3396 Handle factory_type_oop(THREAD, JNIHandles::resolve_non_null(factoryType));
3397 Symbol* factory_type = java_lang_invoke_MethodType::as_signature(factory_type_oop(), true);
3398
3399 Handle interface_method_type_oop(THREAD, JNIHandles::resolve_non_null(interfaceMethodType));
3400 Symbol* interface_method_type = java_lang_invoke_MethodType::as_signature(interface_method_type_oop(), true);
3401
3402 Handle implementation_member_oop(THREAD, JNIHandles::resolve_non_null(implementationMember));
3403 assert(java_lang_invoke_MemberName::is_method(implementation_member_oop()), "must be");
3404 Method* m = java_lang_invoke_MemberName::vmtarget(implementation_member_oop());
3405
3406 Handle dynamic_method_type_oop(THREAD, JNIHandles::resolve_non_null(dynamicMethodType));
3407 Symbol* dynamic_method_type = java_lang_invoke_MethodType::as_signature(dynamic_method_type_oop(), true);
3408
3409 LambdaProxyClassDictionary::add_lambda_proxy_class(caller_ik, lambda_ik, interface_method_name, factory_type,
3410 interface_method_type, m, dynamic_method_type, THREAD);
3411 #endif // INCLUDE_CDS
3412 JVM_END
3413
3414 JVM_ENTRY_PROF(jclass, JVM_LookupLambdaProxyClassFromArchive, JVM_LookupLambdaProxyClassFromArchive(JNIEnv* env,
3415 jclass caller,
3416 jstring interfaceMethodName,
3417 jobject factoryType,
3418 jobject interfaceMethodType,
3419 jobject implementationMember,
3420 jobject dynamicMethodType))
3421 #if INCLUDE_CDS
3422
3423 if (interfaceMethodName == nullptr || factoryType == nullptr || interfaceMethodType == nullptr ||
3424 implementationMember == nullptr || dynamicMethodType == nullptr) {
3425 THROW_(vmSymbols::java_lang_NullPointerException(), nullptr);
3426 }
3427
3428 InstanceKlass* caller_ik = java_lang_Class::as_InstanceKlass(JNIHandles::resolve(caller));
3429 if (!caller_ik->in_aot_cache()) {
3430 // there won't be a shared lambda class if the caller_ik is not in the shared archive.
3431 return nullptr;
3432 }
3433
3434 Symbol* interface_method_name = java_lang_String::as_symbol(JNIHandles::resolve_non_null(interfaceMethodName));
3435 Handle factory_type_oop(THREAD, JNIHandles::resolve_non_null(factoryType));
3436 Symbol* factory_type = java_lang_invoke_MethodType::as_signature(factory_type_oop(), true);
3437
3438 Handle interface_method_type_oop(THREAD, JNIHandles::resolve_non_null(interfaceMethodType));
3439 Symbol* interface_method_type = java_lang_invoke_MethodType::as_signature(interface_method_type_oop(), true);
3440
3441 Handle implementation_member_oop(THREAD, JNIHandles::resolve_non_null(implementationMember));
3442 assert(java_lang_invoke_MemberName::is_method(implementation_member_oop()), "must be");
3443 Method* m = java_lang_invoke_MemberName::vmtarget(implementation_member_oop());
3444
3445 Handle dynamic_method_type_oop(THREAD, JNIHandles::resolve_non_null(dynamicMethodType));
3446 Symbol* dynamic_method_type = java_lang_invoke_MethodType::as_signature(dynamic_method_type_oop(), true);
3447
3448 InstanceKlass* loaded_lambda =
3449 LambdaProxyClassDictionary::load_shared_lambda_proxy_class(caller_ik, interface_method_name, factory_type,
3450 interface_method_type, m, dynamic_method_type,
3451 CHECK_(nullptr));
3452 return loaded_lambda == nullptr ? nullptr : (jclass) JNIHandles::make_local(THREAD, loaded_lambda->java_mirror());
3453 #else
3454 return nullptr;
3455 #endif // INCLUDE_CDS
3456 JVM_END
3457
3458 JVM_ENTRY_NO_ENV_PROF(jlong, JVM_GetRandomSeedForDumping, JVM_GetRandomSeedForDumping())
3459 if (CDSConfig::is_dumping_static_archive()) {
3460 // We do this so that the default CDS archive can be deterministic.
3461 const char* release = VM_Version::vm_release();
3462 const char* dbg_level = VM_Version::jdk_debug_level();
3463 const char* version = VM_Version::internal_vm_info_string();
3464 jlong seed = (jlong)(java_lang_String::hash_code((const jbyte*)release, (int)strlen(release)) ^
3465 java_lang_String::hash_code((const jbyte*)dbg_level, (int)strlen(dbg_level)) ^
3466 java_lang_String::hash_code((const jbyte*)version, (int)strlen(version)));
3467 seed += (jlong)VM_Version::vm_major_version();
3468 seed += (jlong)VM_Version::vm_minor_version();
3469 seed += (jlong)VM_Version::vm_security_version();
3470 seed += (jlong)VM_Version::vm_patch_version();
3471 if (seed == 0) { // don't let this ever be zero.
3472 seed = 0x87654321;
3473 }
3474 log_debug(aot)("JVM_GetRandomSeedForDumping() = " JLONG_FORMAT, seed);
3475 return seed;
3476 } else {
3477 return 0;
3478 }
3479 JVM_END
3480
3481 JVM_ENTRY_NO_ENV_PROF(jint, JVM_GetCDSConfigStatus, JVM_GetCDSConfigStatus())
3482 return CDSConfig::get_status();
3483 JVM_END
3484
3485 JVM_ENTRY_PROF(void, JVM_LogLambdaFormInvoker, JVM_LogLambdaFormInvoker(JNIEnv *env, jstring line))
3486 #if INCLUDE_CDS
3487 assert(CDSConfig::is_logging_lambda_form_invokers(), "sanity");
3488 if (line != nullptr) {
3489 ResourceMark rm(THREAD);
3490 Handle h_line (THREAD, JNIHandles::resolve_non_null(line));
3491 char* c_line = java_lang_String::as_utf8_string(h_line());
3492 if (CDSConfig::is_dumping_dynamic_archive() || CDSConfig::is_dumping_preimage_static_archive()) {
3493 // Note: LambdaFormInvokers::append take same format which is not
3494 // same as below the print format. The line does not include LAMBDA_FORM_TAG.
3495 LambdaFormInvokers::append(os::strdup((const char*)c_line, mtInternal));
3496 }
3497 if (ClassListWriter::is_enabled()) {
3498 ClassListWriter w;
3499 w.stream()->print_cr("%s %s", ClassListParser::lambda_form_tag(), c_line);
3500 }
3501 }
3502 #endif // INCLUDE_CDS
3503 JVM_END
3504
3505 JVM_ENTRY_PROF(void, JVM_LogDynamicProxy, JVM_LogDynamicProxy(JNIEnv *env, jobject loader, jstring proxy_name, jobjectArray interfaces, jint access_flags))
3506 #if INCLUDE_CDS
3507 assert(CDSConfig::is_logging_dynamic_proxies(), "sanity");
3508
3509 ResourceMark rm(THREAD);
3510 oop proxy_name_oop = JNIHandles::resolve_non_null(proxy_name);
3511 char* proxy_name_str = java_lang_String::as_utf8_string(proxy_name_oop);
3512 oop loader_oop = JNIHandles::resolve(loader);
3513 objArrayOop interfaces_oop = objArrayOop(JNIHandles::resolve_non_null(interfaces));
3514
3515 AOTConstantPoolResolver::trace_dynamic_proxy_class(loader_oop, proxy_name_str, interfaces_oop, access_flags);
3516 #endif // INCLUDE_CDS
3517 JVM_END
3518
3519 JVM_ENTRY_PROF(void, JVM_DumpClassListToFile, JVM_DumpClassListToFile(JNIEnv *env, jstring listFileName))
3520 #if INCLUDE_CDS
3521 ResourceMark rm(THREAD);
3522 Handle file_handle(THREAD, JNIHandles::resolve_non_null(listFileName));
3523 char* file_name = java_lang_String::as_utf8_string(file_handle());
3524 AOTMetaspace::dump_loaded_classes(file_name, THREAD);
3525 #endif // INCLUDE_CDS
3526 JVM_END
3527
3528 JVM_ENTRY_PROF(void, JVM_DumpDynamicArchive, JVM_DumpDynamicArchive(JNIEnv *env, jstring archiveName))
3529 #if INCLUDE_CDS
3530 ResourceMark rm(THREAD);
3531 Handle file_handle(THREAD, JNIHandles::resolve_non_null(archiveName));
3532 char* archive_name = java_lang_String::as_utf8_string(file_handle());
3533 DynamicArchive::dump_for_jcmd(archive_name, CHECK);
3534 #endif // INCLUDE_CDS
3535 JVM_END
3536
3537 JVM_ENTRY(jboolean, JVM_NeedsClassInitBarrierForCDS(JNIEnv* env, jclass cls))
3538 #if INCLUDE_CDS
3539 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
3540 if (!k->is_instance_klass()) {
3541 return false;
3542 } else {
3543 if (InstanceKlass::cast(k)->is_enum_subclass() ||
3544 AOTClassInitializer::can_archive_initialized_mirror(InstanceKlass::cast(k))) {
3545 // This class will be cached in AOT-initialized state. No need for init barriers.
3546 return false;
3547 } else {
3548 // If we cannot cache the class in AOT-initialized state, java.lang.invoke handles
3549 // must emit barriers to ensure class initialization during production run.
3550 ResourceMark rm(THREAD);
3551 log_debug(aot)("NeedsClassInitBarrierForCDS: %s", k->external_name());
3552 return true;
3553 }
3554 }
3555 #else
3556 return false;
3557 #endif // INCLUDE_CDS
3558 JVM_END
3559
3560 // Returns an array of all live Thread objects (VM internal JavaThreads,
3561 // jvmti agent threads, and JNI attaching threads are skipped)
3562 // See CR 6404306 regarding JNI attaching threads
3563 JVM_ENTRY_PROF(jobjectArray, JVM_GetAllThreads, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
3564 ResourceMark rm(THREAD);
3565 ThreadsListEnumerator tle(THREAD, false, false);
3566 JvmtiVMObjectAllocEventCollector oam;
3567
3568 int num_threads = tle.num_threads();
3569 objArrayOop r = oopFactory::new_objArray(vmClasses::Thread_klass(), num_threads, CHECK_NULL);
3570 objArrayHandle threads_ah(THREAD, r);
3571
3572 for (int i = 0; i < num_threads; i++) {
3573 Handle h = tle.get_threadObj(i);
3574 threads_ah->obj_at_put(i, h());
3575 }
3576
3577 return (jobjectArray) JNIHandles::make_local(THREAD, threads_ah());
3578 JVM_END
3579
3580
3581 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
3582 // Return StackTraceElement[][], each element is the stack trace of a thread in
3583 // the corresponding entry in the given threads array
3584 JVM_ENTRY_PROF(jobjectArray, JVM_DumpThreads, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
3585 JvmtiVMObjectAllocEventCollector oam;
3586
3587 // Check if threads is null
3588 if (threads == nullptr) {
3589 THROW_NULL(vmSymbols::java_lang_NullPointerException());
3590 }
3591
3592 objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
3593 objArrayHandle ah(THREAD, a);
3594 int num_threads = ah->length();
3595 // check if threads is non-empty array
3596 if (num_threads == 0) {
3597 THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
3598 }
3599
3600 // check if threads is not an array of objects of Thread class
3601 Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
3602 if (k != vmClasses::Thread_klass()) {
3603 THROW_NULL(vmSymbols::java_lang_IllegalArgumentException());
3604 }
3605
3606 ResourceMark rm(THREAD);
3607
3608 GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
3609 for (int i = 0; i < num_threads; i++) {
3610 oop thread_obj = ah->obj_at(i);
3611 instanceHandle h(THREAD, (instanceOop) thread_obj);
3612 thread_handle_array->append(h);
3613 }
3614
3615 // The JavaThread references in thread_handle_array are validated
3616 // in VM_ThreadDump::doit().
3617 Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
3618 return (jobjectArray)JNIHandles::make_local(THREAD, stacktraces());
3619
3620 JVM_END
3621
3622 // JVM monitoring and management support
3623 JVM_LEAF_PROF(void*, JVM_GetManagement, JVM_GetManagement(jint version))
3624 return Management::get_jmm_interface(version);
3625 JVM_END
3626
3627 // com.sun.tools.attach.VirtualMachine agent properties support
3628 //
3629 // Initialize the agent properties with the properties maintained in the VM
3630 JVM_ENTRY_PROF(jobject, JVM_InitAgentProperties, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
3631 ResourceMark rm;
3632
3633 Handle props(THREAD, JNIHandles::resolve_non_null(properties));
3634
3635 PUTPROP(props, "sun.java.command", Arguments::java_command());
3636 PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
3637 PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
3638 return properties;
3639 JVM_END
3640
3641 JVM_ENTRY_PROF(jobjectArray, JVM_GetEnclosingMethodInfo, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
3642 {
3643 JvmtiVMObjectAllocEventCollector oam;
3644
3645 if (ofClass == nullptr) {
3646 return nullptr;
3647 }
3648 Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
3649 // Special handling for primitive objects
3650 if (java_lang_Class::is_primitive(mirror())) {
3651 return nullptr;
3652 }
3653 Klass* k = java_lang_Class::as_Klass(mirror());
3654 if (!k->is_instance_klass()) {
3655 return nullptr;
3656 }
3657 InstanceKlass* ik = InstanceKlass::cast(k);
3658 int encl_method_class_idx = ik->enclosing_method_class_index();
3659 if (encl_method_class_idx == 0) {
3660 return nullptr;
3661 }
3662 objArrayOop dest_o = oopFactory::new_objArray(vmClasses::Object_klass(), 3, CHECK_NULL);
3663 objArrayHandle dest(THREAD, dest_o);
3664 Klass* enc_k = ik->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
3665 dest->obj_at_put(0, enc_k->java_mirror());
3666 int encl_method_method_idx = ik->enclosing_method_method_index();
3667 if (encl_method_method_idx != 0) {
3668 Symbol* sym = ik->constants()->symbol_at(
3669 extract_low_short_from_int(
3670 ik->constants()->name_and_type_at(encl_method_method_idx)));
3671 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3672 dest->obj_at_put(1, str());
3673 sym = ik->constants()->symbol_at(
3674 extract_high_short_from_int(
3675 ik->constants()->name_and_type_at(encl_method_method_idx)));
3676 str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
3677 dest->obj_at_put(2, str());
3678 }
3679 return (jobjectArray) JNIHandles::make_local(THREAD, dest());
3680 }
3681 JVM_END
3682
3683 // Returns an array of java.lang.String objects containing the input arguments to the VM.
3684 JVM_ENTRY_PROF(jobjectArray, JVM_GetVmArguments, JVM_GetVmArguments(JNIEnv *env))
3685 ResourceMark rm(THREAD);
3686
3687 if (Arguments::num_jvm_args() == 0 && Arguments::num_jvm_flags() == 0) {
3688 return nullptr;
3689 }
3690
3691 char** vm_flags = Arguments::jvm_flags_array();
3692 char** vm_args = Arguments::jvm_args_array();
3693 int num_flags = Arguments::num_jvm_flags();
3694 int num_args = Arguments::num_jvm_args();
3695
3696 InstanceKlass* ik = vmClasses::String_klass();
3697 objArrayOop r = oopFactory::new_objArray(ik, num_args + num_flags, CHECK_NULL);
3698 objArrayHandle result_h(THREAD, r);
3699
3700 int index = 0;
3701 for (int j = 0; j < num_flags; j++, index++) {
3702 Handle h = java_lang_String::create_from_platform_dependent_str(vm_flags[j], CHECK_NULL);
3703 result_h->obj_at_put(index, h());
3704 }
3705 for (int i = 0; i < num_args; i++, index++) {
3706 Handle h = java_lang_String::create_from_platform_dependent_str(vm_args[i], CHECK_NULL);
3707 result_h->obj_at_put(index, h());
3708 }
3709 return (jobjectArray) JNIHandles::make_local(THREAD, result_h());
3710 JVM_END
3711
3712 JVM_LEAF_PROF(jint, JVM_FindSignal, JVM_FindSignal(const char *name))
3713 return os::get_signal_number(name);
3714 JVM_END
3715
3716 JVM_ENTRY_PROF(void, JVM_VirtualThreadStart, JVM_VirtualThreadStart(JNIEnv* env, jobject vthread))
3717 #if INCLUDE_JVMTI
3718 if (!DoJVMTIVirtualThreadTransitions) {
3719 assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3720 return;
3721 }
3722 if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
3723 JvmtiVTMSTransitionDisabler::VTMS_vthread_start(vthread);
3724 } else {
3725 // set VTMS transition bit value in JavaThread and java.lang.VirtualThread object
3726 JvmtiVTMSTransitionDisabler::set_is_in_VTMS_transition(thread, vthread, false);
3727 }
3728 #endif
3729 JVM_END
3730
3731 JVM_ENTRY_PROF(void, JVM_VirtualThreadEnd, JVM_VirtualThreadEnd(JNIEnv* env, jobject vthread))
3732 #if INCLUDE_JVMTI
3733 if (!DoJVMTIVirtualThreadTransitions) {
3734 assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3735 return;
3736 }
3737 if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
3738 JvmtiVTMSTransitionDisabler::VTMS_vthread_end(vthread);
3739 } else {
3740 // set VTMS transition bit value in JavaThread and java.lang.VirtualThread object
3741 JvmtiVTMSTransitionDisabler::set_is_in_VTMS_transition(thread, vthread, true);
3742 }
3743 #endif
3744 JVM_END
3745
3746 // If notifications are disabled then just update the VTMS transition bit and return.
3747 // Otherwise, the bit is updated in the given jvmtiVTMSTransitionDisabler function call.
3748 JVM_ENTRY_PROF(void, JVM_VirtualThreadMount, JVM_VirtualThreadMount(JNIEnv* env, jobject vthread, jboolean hide))
3749 #if INCLUDE_JVMTI
3750 if (!DoJVMTIVirtualThreadTransitions) {
3751 assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3752 return;
3753 }
3754 if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
3755 JvmtiVTMSTransitionDisabler::VTMS_vthread_mount(vthread, hide);
3756 } else {
3757 // set VTMS transition bit value in JavaThread and java.lang.VirtualThread object
3758 JvmtiVTMSTransitionDisabler::set_is_in_VTMS_transition(thread, vthread, hide);
3759 }
3760 #endif
3761 JVM_END
3762
3763 // If notifications are disabled then just update the VTMS transition bit and return.
3764 // Otherwise, the bit is updated in the given jvmtiVTMSTransitionDisabler function call below.
3765 JVM_ENTRY_PROF(void, JVM_VirtualThreadUnmount, JVM_VirtualThreadUnmount(JNIEnv* env, jobject vthread, jboolean hide))
3766 #if INCLUDE_JVMTI
3767 if (!DoJVMTIVirtualThreadTransitions) {
3768 assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3769 return;
3770 }
3771 if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
3772 JvmtiVTMSTransitionDisabler::VTMS_vthread_unmount(vthread, hide);
3773 } else {
3774 // set VTMS transition bit value in JavaThread and java.lang.VirtualThread object
3775 JvmtiVTMSTransitionDisabler::set_is_in_VTMS_transition(thread, vthread, hide);
3776 }
3777 #endif
3778 JVM_END
3779
3780 // Notification from VirtualThread about disabling JVMTI Suspend in a sync critical section.
3781 // Needed to avoid deadlocks with JVMTI suspend mechanism.
3782 JVM_ENTRY(void, JVM_VirtualThreadDisableSuspend(JNIEnv* env, jclass clazz, jboolean enter))
3783 #if INCLUDE_JVMTI
3784 if (!DoJVMTIVirtualThreadTransitions) {
3785 assert(!JvmtiExport::can_support_virtual_threads(), "sanity check");
3786 return;
3787 }
3788 assert(thread->is_disable_suspend() != (bool)enter,
3789 "nested or unbalanced monitor enter/exit is not allowed");
3790 thread->toggle_is_disable_suspend();
3791 #endif
3792 JVM_END
3793
3794 JVM_ENTRY(void, JVM_VirtualThreadPinnedEvent(JNIEnv* env, jclass ignored, jstring op))
3795 #if INCLUDE_JFR
3796 freeze_result result = THREAD->last_freeze_fail_result();
3797 assert(result != freeze_ok, "sanity check");
3798 EventVirtualThreadPinned event(UNTIMED);
3799 event.set_starttime(THREAD->last_freeze_fail_time());
3800 if (event.should_commit()) {
3801 ResourceMark rm(THREAD);
3802 const char *str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(op));
3803 THREAD->post_vthread_pinned_event(&event, str, result);
3804 }
3805 #endif
3806 JVM_END
3807
3808 JVM_ENTRY(jobject, JVM_TakeVirtualThreadListToUnblock(JNIEnv* env, jclass ignored))
3809 ParkEvent* parkEvent = ObjectMonitor::vthread_unparker_ParkEvent();
3810 assert(parkEvent != nullptr, "not initialized");
3811
3812 OopHandle& list_head = ObjectMonitor::vthread_list_head();
3813 oop vthread_head = nullptr;
3814 while (true) {
3815 if (list_head.peek() != nullptr) {
3816 for (;;) {
3817 oop head = list_head.resolve();
3818 if (list_head.cmpxchg(head, nullptr) == head) {
3819 return JNIHandles::make_local(THREAD, head);
3820 }
3821 }
3822 }
3823 ThreadBlockInVM tbivm(THREAD);
3824 parkEvent->park();
3825 }
3826 JVM_END
3827 /*
3828 * Return the current class's class file version. The low order 16 bits of the
3829 * returned jint contain the class's major version. The high order 16 bits
3830 * contain the class's minor version.
3831 */
3832 JVM_ENTRY_PROF(jint, JVM_GetClassFileVersion, JVM_GetClassFileVersion(JNIEnv* env, jclass current))
3833 oop mirror = JNIHandles::resolve_non_null(current);
3834 if (java_lang_Class::is_primitive(mirror)) {
3835 // return latest major version and minor version of 0.
3836 return JVM_CLASSFILE_MAJOR_VERSION;
3837 }
3838 InstanceKlass* ik = java_lang_Class::as_InstanceKlass(mirror);
3839 return (ik->minor_version() << 16) | ik->major_version();
3840 JVM_END
3841
3842 /*
3843 * Ensure that code doing a stackwalk and using javaVFrame::locals() to
3844 * get the value will see a materialized value and not a scalar-replaced
3845 * null value.
3846 */
3847 JVM_ENTRY_PROF(void, JVM_EnsureMaterializedForStackWalk_func, JVM_EnsureMaterializedForStackWalk_func(JNIEnv* env, jobject vthread, jobject value))
3848 JVM_EnsureMaterializedForStackWalk(env, value);
3849 JVM_END
3850
3851 /*
3852 * Return JNI_TRUE if warnings are printed when agents are dynamically loaded.
3853 */
3854 JVM_LEAF_PROF(jboolean, JVM_PrintWarningAtDynamicAgentLoad, JVM_PrintWarningAtDynamicAgentLoad(void))
3855 return (EnableDynamicAgentLoading && !FLAG_IS_CMDLINE(EnableDynamicAgentLoading)) ? JNI_TRUE : JNI_FALSE;
3856 JVM_END
3857
3858 #define DO_COUNTERS(macro) \
3859 macro(JVM_CurrentTimeMillis) \
3860 macro(JVM_NanoTime) \
3861 macro(JVM_GetNanoTimeAdjustment) \
3862 macro(JVM_ArrayCopy) \
3863 macro(JVM_GetProperties) \
3864 macro(JVM_GetTemporaryDirectory) \
3865 macro(JVM_BeforeHalt) \
3866 macro(JVM_Halt) \
3867 macro(JVM_GC) \
3868 macro(JVM_MaxObjectInspectionAge) \
3869 macro(JVM_TotalMemory) \
3870 macro(JVM_FreeMemory) \
3871 macro(JVM_MaxMemory) \
3872 macro(JVM_ActiveProcessorCount) \
3873 macro(JVM_IsUseContainerSupport) \
3874 macro(JVM_FillInStackTrace) \
3875 macro(JVM_GetExtendedNPEMessage) \
3876 macro(JVM_InitStackTraceElementArray) \
3877 macro(JVM_InitStackTraceElement) \
3878 macro(JVM_ExpandStackFrameInfo) \
3879 macro(JVM_CallStackWalk) \
3880 macro(JVM_MoreStackWalk) \
3881 macro(JVM_SetStackWalkContinuation) \
3882 macro(JVM_IHashCode) \
3883 macro(JVM_MonitorWait) \
3884 macro(JVM_MonitorNotify) \
3885 macro(JVM_MonitorNotifyAll) \
3886 macro(JVM_Clone) \
3887 macro(JVM_ReportFinalizationComplete) \
3888 macro(JVM_IsFinalizationEnabled) \
3889 macro(JVM_RegisterContinuationMethods) \
3890 macro(JVM_NativePath) \
3891 macro(JVM_GetCallerClass) \
3892 macro(JVM_FindPrimitiveClass) \
3893 macro(JVM_FindClassFromBootLoader) \
3894 macro(JVM_FindClassFromLoader) \
3895 macro(JVM_FindClassFromClass) \
3896 macro(JVM_DefineClass) \
3897 macro(JVM_LookupDefineClass) \
3898 macro(JVM_DefineClassWithSource) \
3899 macro(JVM_FindLoadedClass) \
3900 macro(JVM_DefineModule) \
3901 macro(JVM_SetBootLoaderUnnamedModule) \
3902 macro(JVM_AddModuleExports) \
3903 macro(JVM_AddModuleExportsToAllUnnamed) \
3904 macro(JVM_AddModuleExportsToAll) \
3905 macro(JVM_AddReadsModule) \
3906 macro(JVM_DefineArchivedModules) \
3907 macro(JVM_InitClassName) \
3908 macro(JVM_GetClassInterfaces) \
3909 macro(JVM_IsInterface) \
3910 macro(JVM_IsHiddenClass) \
3911 macro(JVM_FindScopedValueBindings) \
3912 macro(JVM_GetDeclaredClasses) \
3913 macro(JVM_GetDeclaringClass) \
3914 macro(JVM_GetSimpleBinaryName) \
3915 macro(JVM_GetClassSignature) \
3916 macro(JVM_GetClassAnnotations) \
3917 macro(JVM_GetClassTypeAnnotations) \
3918 macro(JVM_GetMethodTypeAnnotations) \
3919 macro(JVM_GetFieldTypeAnnotations) \
3920 macro(JVM_GetMethodParameters) \
3921 macro(JVM_GetClassDeclaredFields) \
3922 macro(JVM_IsRecord) \
3923 macro(JVM_GetRecordComponents) \
3924 macro(JVM_GetClassDeclaredMethods) \
3925 macro(JVM_GetClassDeclaredConstructors) \
3926 macro(JVM_AreNestMates) \
3927 macro(JVM_GetNestHost) \
3928 macro(JVM_GetNestMembers) \
3929 macro(JVM_GetPermittedSubclasses) \
3930 macro(JVM_GetClassConstantPool) \
3931 macro(JVM_ConstantPoolGetSize) \
3932 macro(JVM_ConstantPoolGetClassAt) \
3933 macro(JVM_ConstantPoolGetClassAtIfLoaded) \
3934 macro(JVM_ConstantPoolGetMethodAt) \
3935 macro(JVM_ConstantPoolGetMethodAtIfLoaded) \
3936 macro(JVM_ConstantPoolGetFieldAt) \
3937 macro(JVM_ConstantPoolGetFieldAtIfLoaded) \
3938 macro(JVM_ConstantPoolGetMemberRefInfoAt) \
3939 macro(JVM_ConstantPoolGetClassRefIndexAt) \
3940 macro(JVM_ConstantPoolGetNameAndTypeRefIndexAt) \
3941 macro(JVM_ConstantPoolGetNameAndTypeRefInfoAt) \
3942 macro(JVM_ConstantPoolGetIntAt) \
3943 macro(JVM_ConstantPoolGetLongAt) \
3944 macro(JVM_ConstantPoolGetFloatAt) \
3945 macro(JVM_ConstantPoolGetDoubleAt) \
3946 macro(JVM_ConstantPoolGetStringAt) \
3947 macro(JVM_ConstantPoolGetUTF8At) \
3948 macro(JVM_ConstantPoolGetTagAt) \
3949 macro(JVM_DesiredAssertionStatus) \
3950 macro(JVM_AssertionStatusDirectives) \
3951 macro(JVM_GetClassNameUTF) \
3952 macro(JVM_GetClassCPTypes) \
3953 macro(JVM_GetClassCPEntriesCount) \
3954 macro(JVM_GetClassFieldsCount) \
3955 macro(JVM_GetClassMethodsCount) \
3956 macro(JVM_GetMethodIxExceptionIndexes) \
3957 macro(JVM_GetMethodIxExceptionsCount) \
3958 macro(JVM_GetMethodIxByteCode) \
3959 macro(JVM_GetMethodIxByteCodeLength) \
3960 macro(JVM_GetMethodIxExceptionTableEntry) \
3961 macro(JVM_GetMethodIxExceptionTableLength) \
3962 macro(JVM_GetMethodIxModifiers) \
3963 macro(JVM_GetFieldIxModifiers) \
3964 macro(JVM_GetMethodIxLocalsCount) \
3965 macro(JVM_GetMethodIxArgsSize) \
3966 macro(JVM_GetMethodIxMaxStack) \
3967 macro(JVM_IsConstructorIx) \
3968 macro(JVM_IsVMGeneratedMethodIx) \
3969 macro(JVM_GetMethodIxNameUTF) \
3970 macro(JVM_GetMethodIxSignatureUTF) \
3971 macro(JVM_GetCPFieldNameUTF) \
3972 macro(JVM_GetCPMethodNameUTF) \
3973 macro(JVM_GetCPMethodSignatureUTF) \
3974 macro(JVM_GetCPFieldSignatureUTF) \
3975 macro(JVM_GetCPClassNameUTF) \
3976 macro(JVM_GetCPFieldClassNameUTF) \
3977 macro(JVM_GetCPMethodClassNameUTF) \
3978 macro(JVM_GetCPFieldModifiers) \
3979 macro(JVM_GetCPMethodModifiers) \
3980 macro(JVM_ReleaseUTF) \
3981 macro(JVM_IsSameClassPackage) \
3982 macro(JVM_StartThread) \
3983 macro(JVM_SetThreadPriority) \
3984 macro(JVM_Yield) \
3985 macro(JVM_SleepNanos) \
3986 macro(JVM_CurrentCarrierThread) \
3987 macro(JVM_CurrentThread) \
3988 macro(JVM_SetCurrentThread) \
3989 macro(JVM_GetNextThreadIdOffset) \
3990 macro(JVM_Interrupt) \
3991 macro(JVM_HoldsLock) \
3992 macro(JVM_GetStackTrace) \
3993 macro(JVM_CreateThreadSnapshot) \
3994 macro(JVM_SetNativeThreadName) \
3995 macro(JVM_ScopedValueCache) \
3996 macro(JVM_SetScopedValueCache) \
3997 macro(JVM_GetSystemPackage) \
3998 macro(JVM_GetSystemPackages) \
3999 macro(JVM_GetAndClearReferencePendingList) \
4000 macro(JVM_HasReferencePendingList) \
4001 macro(JVM_WaitForReferencePendingList) \
4002 macro(JVM_ReferenceGet) \
4003 macro(JVM_ReferenceRefersTo) \
4004 macro(JVM_ReferenceClear) \
4005 macro(JVM_PhantomReferenceRefersTo) \
4006 macro(JVM_LatestUserDefinedLoader) \
4007 macro(JVM_GetArrayLength) \
4008 macro(JVM_GetArrayElement) \
4009 macro(JVM_GetPrimitiveArrayElement) \
4010 macro(JVM_SetArrayElement) \
4011 macro(JVM_SetPrimitiveArrayElement) \
4012 macro(JVM_NewArray) \
4013 macro(JVM_NewMultiArray) \
4014 macro(JVM_LoadZipLibrary) \
4015 macro(JVM_LoadLibrary) \
4016 macro(JVM_UnloadLibrary) \
4017 macro(JVM_FindLibraryEntry) \
4018 macro(JVM_IsSupportedJNIVersion) \
4019 macro(JVM_IsPreviewEnabled) \
4020 macro(JVM_IsContinuationsSupported) \
4021 macro(JVM_IsForeignLinkerSupported) \
4022 macro(JVM_InternString) \
4023 macro(JVM_InvokeMethod) \
4024 macro(JVM_NewInstanceFromConstructor) \
4025 macro(JVM_InitializeFromArchive) \
4026 macro(JVM_RegisterLambdaProxyClassForArchiving) \
4027 macro(JVM_LookupLambdaProxyClassFromArchive) \
4028 macro(JVM_GetRandomSeedForDumping) \
4029 macro(JVM_LogLambdaFormInvoker) \
4030 macro(JVM_LogDynamicProxy) \
4031 macro(JVM_DumpClassListToFile) \
4032 macro(JVM_DumpDynamicArchive) \
4033 macro(JVM_GetAllThreads) \
4034 macro(JVM_DumpThreads) \
4035 macro(JVM_GetManagement) \
4036 macro(JVM_InitAgentProperties) \
4037 macro(JVM_GetEnclosingMethodInfo) \
4038 macro(JVM_GetVmArguments) \
4039 macro(JVM_FindSignal) \
4040 macro(JVM_VirtualThreadStart) \
4041 macro(JVM_VirtualThreadEnd) \
4042 macro(JVM_VirtualThreadMount) \
4043 macro(JVM_VirtualThreadUnmount) \
4044 macro(JVM_GetClassFileVersion) \
4045 macro(JVM_EnsureMaterializedForStackWalk_func) \
4046 macro(JVM_PrintWarningAtDynamicAgentLoad)
4047
4048 #define INIT_COUNTER(name) \
4049 NEWPERFTICKCOUNTERS(_perf_##name##_timer, SUN_RT, #name); \
4050 NEWPERFEVENTCOUNTER(_perf_##name##_count, SUN_RT, #name "_count"); \
4051
4052 void perf_jvm_init() {
4053 if (ProfileVMCalls && UsePerfData) {
4054 EXCEPTION_MARK;
4055
4056 DO_COUNTERS(INIT_COUNTER)
4057
4058 if (HAS_PENDING_EXCEPTION) {
4059 vm_exit_during_initialization("jvm_perf_init failed unexpectedly");
4060 }
4061 }
4062 }
4063
4064 #undef INIT_COUNTER
4065
4066 #define PRINT_COUNTER(name) {\
4067 jlong count = _perf_##name##_count->get_value(); \
4068 if (count > 0) { \
4069 st->print_cr(" %-40s = " JLONG_FORMAT_W(6) "us (elapsed) " JLONG_FORMAT_W(6) "us (thread) (" JLONG_FORMAT_W(5) " events)", \
4070 #name, \
4071 _perf_##name##_timer->elapsed_counter_value_us(), \
4072 _perf_##name##_timer->thread_counter_value_us(), count); \
4073 }}
4074
4075 void perf_jvm_print_on(outputStream* st) {
4076 if (ProfileVMCalls && UsePerfData) {
4077 DO_COUNTERS(PRINT_COUNTER)
4078 } else {
4079 st->print_cr(" JVM: no info (%s is disabled)", (UsePerfData ? "ProfileVMCalls" : "UsePerfData"));
4080 }
4081 }
4082
4083 #undef PRINT_COUNTER