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