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