Mon, 15 Oct 2018 14:58:52 +0100
Merge
1 /*
2 * Copyright (c) 1997, 2018, 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 */
25 #include "precompiled.hpp"
26 #include "classfile/classLoader.hpp"
27 #include "classfile/classLoaderData.inline.hpp"
28 #include "classfile/classLoaderExt.hpp"
29 #include "classfile/javaAssertions.hpp"
30 #include "classfile/javaClasses.hpp"
31 #include "classfile/symbolTable.hpp"
32 #include "classfile/systemDictionary.hpp"
33 #if INCLUDE_CDS
34 #include "classfile/sharedClassUtil.hpp"
35 #include "classfile/systemDictionaryShared.hpp"
36 #endif
37 #include "classfile/vmSymbols.hpp"
38 #include "gc_interface/collectedHeap.inline.hpp"
39 #include "interpreter/bytecode.hpp"
40 #include "memory/oopFactory.hpp"
41 #include "memory/referenceType.hpp"
42 #include "memory/universe.inline.hpp"
43 #include "oops/fieldStreams.hpp"
44 #include "oops/instanceKlass.hpp"
45 #include "oops/objArrayKlass.hpp"
46 #include "oops/method.hpp"
47 #include "prims/jvm.h"
48 #include "prims/jvm_misc.hpp"
49 #include "prims/jvmtiExport.hpp"
50 #include "prims/jvmtiThreadState.hpp"
51 #include "prims/nativeLookup.hpp"
52 #include "prims/privilegedStack.hpp"
53 #include "runtime/arguments.hpp"
54 #include "runtime/dtraceJSDT.hpp"
55 #include "runtime/handles.inline.hpp"
56 #include "runtime/init.hpp"
57 #include "runtime/interfaceSupport.hpp"
58 #include "runtime/java.hpp"
59 #include "runtime/javaCalls.hpp"
60 #include "runtime/jfieldIDWorkaround.hpp"
61 #include "runtime/orderAccess.inline.hpp"
62 #include "runtime/os.hpp"
63 #include "runtime/perfData.hpp"
64 #include "runtime/reflection.hpp"
65 #include "runtime/vframe.hpp"
66 #include "runtime/vm_operations.hpp"
67 #include "services/attachListener.hpp"
68 #include "services/management.hpp"
69 #include "services/threadService.hpp"
70 #include "trace/tracing.hpp"
71 #include "utilities/copy.hpp"
72 #include "utilities/defaultStream.hpp"
73 #include "utilities/dtrace.hpp"
74 #include "utilities/events.hpp"
75 #include "utilities/histogram.hpp"
76 #include "utilities/top.hpp"
77 #include "utilities/utf8.hpp"
78 #ifdef TARGET_OS_FAMILY_linux
79 # include "jvm_linux.h"
80 #endif
81 #ifdef TARGET_OS_FAMILY_solaris
82 # include "jvm_solaris.h"
83 #endif
84 #ifdef TARGET_OS_FAMILY_windows
85 # include "jvm_windows.h"
86 #endif
87 #ifdef TARGET_OS_FAMILY_aix
88 # include "jvm_aix.h"
89 #endif
90 #ifdef TARGET_OS_FAMILY_bsd
91 # include "jvm_bsd.h"
92 #endif
94 #if INCLUDE_ALL_GCS
95 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
96 #endif // INCLUDE_ALL_GCS
98 #include <errno.h>
100 #ifndef USDT2
101 HS_DTRACE_PROBE_DECL1(hotspot, thread__sleep__begin, long long);
102 HS_DTRACE_PROBE_DECL1(hotspot, thread__sleep__end, int);
103 HS_DTRACE_PROBE_DECL0(hotspot, thread__yield);
104 #endif /* !USDT2 */
106 /*
107 NOTE about use of any ctor or function call that can trigger a safepoint/GC:
108 such ctors and calls MUST NOT come between an oop declaration/init and its
109 usage because if objects are move this may cause various memory stomps, bus
110 errors and segfaults. Here is a cookbook for causing so called "naked oop
111 failures":
113 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields<etc> {
114 JVMWrapper("JVM_GetClassDeclaredFields");
116 // Object address to be held directly in mirror & not visible to GC
117 oop mirror = JNIHandles::resolve_non_null(ofClass);
119 // If this ctor can hit a safepoint, moving objects around, then
120 ComplexConstructor foo;
122 // Boom! mirror may point to JUNK instead of the intended object
123 (some dereference of mirror)
125 // Here's another call that may block for GC, making mirror stale
126 MutexLocker ml(some_lock);
128 // And here's an initializer that can result in a stale oop
129 // all in one step.
130 oop o = call_that_can_throw_exception(TRAPS);
133 The solution is to keep the oop declaration BELOW the ctor or function
134 call that might cause a GC, do another resolve to reassign the oop, or
135 consider use of a Handle instead of an oop so there is immunity from object
136 motion. But note that the "QUICK" entries below do not have a handlemark
137 and thus can only support use of handles passed in.
138 */
140 static void trace_class_resolution_impl(Klass* to_class, TRAPS) {
141 ResourceMark rm;
142 int line_number = -1;
143 const char * source_file = NULL;
144 const char * trace = "explicit";
145 InstanceKlass* caller = NULL;
146 JavaThread* jthread = JavaThread::current();
147 if (jthread->has_last_Java_frame()) {
148 vframeStream vfst(jthread);
150 // scan up the stack skipping ClassLoader, AccessController and PrivilegedAction frames
151 TempNewSymbol access_controller = SymbolTable::new_symbol("java/security/AccessController", CHECK);
152 Klass* access_controller_klass = SystemDictionary::resolve_or_fail(access_controller, false, CHECK);
153 TempNewSymbol privileged_action = SymbolTable::new_symbol("java/security/PrivilegedAction", CHECK);
154 Klass* privileged_action_klass = SystemDictionary::resolve_or_fail(privileged_action, false, CHECK);
156 Method* last_caller = NULL;
158 while (!vfst.at_end()) {
159 Method* m = vfst.method();
160 if (!vfst.method()->method_holder()->is_subclass_of(SystemDictionary::ClassLoader_klass())&&
161 !vfst.method()->method_holder()->is_subclass_of(access_controller_klass) &&
162 !vfst.method()->method_holder()->is_subclass_of(privileged_action_klass)) {
163 break;
164 }
165 last_caller = m;
166 vfst.next();
167 }
168 // if this is called from Class.forName0 and that is called from Class.forName,
169 // then print the caller of Class.forName. If this is Class.loadClass, then print
170 // that caller, otherwise keep quiet since this should be picked up elsewhere.
171 bool found_it = false;
172 if (!vfst.at_end() &&
173 vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
174 vfst.method()->name() == vmSymbols::forName0_name()) {
175 vfst.next();
176 if (!vfst.at_end() &&
177 vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
178 vfst.method()->name() == vmSymbols::forName_name()) {
179 vfst.next();
180 found_it = true;
181 }
182 } else if (last_caller != NULL &&
183 last_caller->method_holder()->name() ==
184 vmSymbols::java_lang_ClassLoader() &&
185 (last_caller->name() == vmSymbols::loadClassInternal_name() ||
186 last_caller->name() == vmSymbols::loadClass_name())) {
187 found_it = true;
188 } else if (!vfst.at_end()) {
189 if (vfst.method()->is_native()) {
190 // JNI call
191 found_it = true;
192 }
193 }
194 if (found_it && !vfst.at_end()) {
195 // found the caller
196 caller = vfst.method()->method_holder();
197 line_number = vfst.method()->line_number_from_bci(vfst.bci());
198 if (line_number == -1) {
199 // show method name if it's a native method
200 trace = vfst.method()->name_and_sig_as_C_string();
201 }
202 Symbol* s = caller->source_file_name();
203 if (s != NULL) {
204 source_file = s->as_C_string();
205 }
206 }
207 }
208 if (caller != NULL) {
209 if (to_class != caller) {
210 const char * from = caller->external_name();
211 const char * to = to_class->external_name();
212 // print in a single call to reduce interleaving between threads
213 if (source_file != NULL) {
214 tty->print("RESOLVE %s %s %s:%d (%s)\n", from, to, source_file, line_number, trace);
215 } else {
216 tty->print("RESOLVE %s %s (%s)\n", from, to, trace);
217 }
218 }
219 }
220 }
222 void trace_class_resolution(Klass* to_class) {
223 EXCEPTION_MARK;
224 trace_class_resolution_impl(to_class, THREAD);
225 if (HAS_PENDING_EXCEPTION) {
226 CLEAR_PENDING_EXCEPTION;
227 }
228 }
230 // Wrapper to trace JVM functions
232 #ifdef ASSERT
233 class JVMTraceWrapper : public StackObj {
234 public:
235 JVMTraceWrapper(const char* format, ...) ATTRIBUTE_PRINTF(2, 3) {
236 if (TraceJVMCalls) {
237 va_list ap;
238 va_start(ap, format);
239 tty->print("JVM ");
240 tty->vprint_cr(format, ap);
241 va_end(ap);
242 }
243 }
244 };
246 Histogram* JVMHistogram;
247 volatile jint JVMHistogram_lock = 0;
249 class JVMHistogramElement : public HistogramElement {
250 public:
251 JVMHistogramElement(const char* name);
252 };
254 JVMHistogramElement::JVMHistogramElement(const char* elementName) {
255 _name = elementName;
256 uintx count = 0;
258 while (Atomic::cmpxchg(1, &JVMHistogram_lock, 0) != 0) {
259 while (OrderAccess::load_acquire(&JVMHistogram_lock) != 0) {
260 count +=1;
261 if ( (WarnOnStalledSpinLock > 0)
262 && (count % WarnOnStalledSpinLock == 0)) {
263 warning("JVMHistogram_lock seems to be stalled");
264 }
265 }
266 }
268 if(JVMHistogram == NULL)
269 JVMHistogram = new Histogram("JVM Call Counts",100);
271 JVMHistogram->add_element(this);
272 Atomic::dec(&JVMHistogram_lock);
273 }
275 #define JVMCountWrapper(arg) \
276 static JVMHistogramElement* e = new JVMHistogramElement(arg); \
277 if (e != NULL) e->increment_count(); // Due to bug in VC++, we need a NULL check here eventhough it should never happen!
279 #define JVMWrapper(arg1) JVMCountWrapper(arg1); JVMTraceWrapper(arg1)
280 #define JVMWrapper2(arg1, arg2) JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2)
281 #define JVMWrapper3(arg1, arg2, arg3) JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2, arg3)
282 #define JVMWrapper4(arg1, arg2, arg3, arg4) JVMCountWrapper(arg1); JVMTraceWrapper(arg1, arg2, arg3, arg4)
283 #else
284 #define JVMWrapper(arg1)
285 #define JVMWrapper2(arg1, arg2)
286 #define JVMWrapper3(arg1, arg2, arg3)
287 #define JVMWrapper4(arg1, arg2, arg3, arg4)
288 #endif
291 // Interface version /////////////////////////////////////////////////////////////////////
294 JVM_LEAF(jint, JVM_GetInterfaceVersion())
295 return JVM_INTERFACE_VERSION;
296 JVM_END
299 // java.lang.System //////////////////////////////////////////////////////////////////////
302 JVM_LEAF(jlong, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored))
303 JVMWrapper("JVM_CurrentTimeMillis");
304 return os::javaTimeMillis();
305 JVM_END
307 JVM_LEAF(jlong, JVM_NanoTime(JNIEnv *env, jclass ignored))
308 JVMWrapper("JVM_NanoTime");
309 return os::javaTimeNanos();
310 JVM_END
313 JVM_ENTRY(void, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos,
314 jobject dst, jint dst_pos, jint length))
315 JVMWrapper("JVM_ArrayCopy");
316 // Check if we have null pointers
317 if (src == NULL || dst == NULL) {
318 THROW(vmSymbols::java_lang_NullPointerException());
319 }
320 arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));
321 arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));
322 assert(s->is_oop(), "JVM_ArrayCopy: src not an oop");
323 assert(d->is_oop(), "JVM_ArrayCopy: dst not an oop");
324 // Do copy
325 s->klass()->copy_array(s, src_pos, d, dst_pos, length, thread);
326 JVM_END
329 static void set_property(Handle props, const char* key, const char* value, TRAPS) {
330 JavaValue r(T_OBJECT);
331 // public synchronized Object put(Object key, Object value);
332 HandleMark hm(THREAD);
333 Handle key_str = java_lang_String::create_from_platform_dependent_str(key, CHECK);
334 Handle value_str = java_lang_String::create_from_platform_dependent_str((value != NULL ? value : ""), CHECK);
335 JavaCalls::call_virtual(&r,
336 props,
337 KlassHandle(THREAD, SystemDictionary::Properties_klass()),
338 vmSymbols::put_name(),
339 vmSymbols::object_object_object_signature(),
340 key_str,
341 value_str,
342 THREAD);
343 }
346 #define PUTPROP(props, name, value) set_property((props), (name), (value), CHECK_(properties));
349 JVM_ENTRY(jobject, JVM_InitProperties(JNIEnv *env, jobject properties))
350 JVMWrapper("JVM_InitProperties");
351 ResourceMark rm;
353 Handle props(THREAD, JNIHandles::resolve_non_null(properties));
355 // System property list includes both user set via -D option and
356 // jvm system specific properties.
357 for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
358 PUTPROP(props, p->key(), p->value());
359 }
361 // Convert the -XX:MaxDirectMemorySize= command line flag
362 // to the sun.nio.MaxDirectMemorySize property.
363 // Do this after setting user properties to prevent people
364 // from setting the value with a -D option, as requested.
365 {
366 if (FLAG_IS_DEFAULT(MaxDirectMemorySize)) {
367 PUTPROP(props, "sun.nio.MaxDirectMemorySize", "-1");
368 } else {
369 char as_chars[256];
370 jio_snprintf(as_chars, sizeof(as_chars), UINTX_FORMAT, MaxDirectMemorySize);
371 PUTPROP(props, "sun.nio.MaxDirectMemorySize", as_chars);
372 }
373 }
375 // JVM monitoring and management support
376 // Add the sun.management.compiler property for the compiler's name
377 {
378 #undef CSIZE
379 #if defined(_LP64) || defined(_WIN64)
380 #define CSIZE "64-Bit "
381 #else
382 #define CSIZE
383 #endif // 64bit
385 #ifdef TIERED
386 const char* compiler_name = "HotSpot " CSIZE "Tiered Compilers";
387 #else
388 #if defined(COMPILER1)
389 const char* compiler_name = "HotSpot " CSIZE "Client Compiler";
390 #elif defined(COMPILER2)
391 const char* compiler_name = "HotSpot " CSIZE "Server Compiler";
392 #else
393 const char* compiler_name = "";
394 #endif // compilers
395 #endif // TIERED
397 if (*compiler_name != '\0' &&
398 (Arguments::mode() != Arguments::_int)) {
399 PUTPROP(props, "sun.management.compiler", compiler_name);
400 }
401 }
403 const char* enableSharedLookupCache = "false";
404 #if INCLUDE_CDS
405 if (ClassLoaderExt::is_lookup_cache_enabled()) {
406 enableSharedLookupCache = "true";
407 }
408 #endif
409 PUTPROP(props, "sun.cds.enableSharedLookupCache", enableSharedLookupCache);
411 return properties;
412 JVM_END
415 /*
416 * Return the temporary directory that the VM uses for the attach
417 * and perf data files.
418 *
419 * It is important that this directory is well-known and the
420 * same for all VM instances. It cannot be affected by configuration
421 * variables such as java.io.tmpdir.
422 */
423 JVM_ENTRY(jstring, JVM_GetTemporaryDirectory(JNIEnv *env))
424 JVMWrapper("JVM_GetTemporaryDirectory");
425 HandleMark hm(THREAD);
426 const char* temp_dir = os::get_temp_directory();
427 Handle h = java_lang_String::create_from_platform_dependent_str(temp_dir, CHECK_NULL);
428 return (jstring) JNIHandles::make_local(env, h());
429 JVM_END
432 // java.lang.Runtime /////////////////////////////////////////////////////////////////////////
434 extern volatile jint vm_created;
436 JVM_ENTRY_NO_ENV(void, JVM_Exit(jint code))
437 if (vm_created != 0 && (code == 0)) {
438 // The VM is about to exit. We call back into Java to check whether finalizers should be run
439 Universe::run_finalizers_on_exit();
440 }
441 before_exit(thread);
442 vm_exit(code);
443 JVM_END
446 JVM_ENTRY_NO_ENV(void, JVM_Halt(jint code))
447 before_exit(thread);
448 vm_exit(code);
449 JVM_END
452 JVM_LEAF(void, JVM_OnExit(void (*func)(void)))
453 register_on_exit_function(func);
454 JVM_END
457 JVM_ENTRY_NO_ENV(void, JVM_GC(void))
458 JVMWrapper("JVM_GC");
459 if (!DisableExplicitGC) {
460 Universe::heap()->collect(GCCause::_java_lang_system_gc);
461 }
462 JVM_END
465 JVM_LEAF(jlong, JVM_MaxObjectInspectionAge(void))
466 JVMWrapper("JVM_MaxObjectInspectionAge");
467 return Universe::heap()->millis_since_last_gc();
468 JVM_END
471 JVM_LEAF(void, JVM_TraceInstructions(jboolean on))
472 if (PrintJVMWarnings) warning("JVM_TraceInstructions not supported");
473 JVM_END
476 JVM_LEAF(void, JVM_TraceMethodCalls(jboolean on))
477 if (PrintJVMWarnings) warning("JVM_TraceMethodCalls not supported");
478 JVM_END
480 static inline jlong convert_size_t_to_jlong(size_t val) {
481 // In the 64-bit vm, a size_t can overflow a jlong (which is signed).
482 NOT_LP64 (return (jlong)val;)
483 LP64_ONLY(return (jlong)MIN2(val, (size_t)max_jlong);)
484 }
486 JVM_ENTRY_NO_ENV(jlong, JVM_TotalMemory(void))
487 JVMWrapper("JVM_TotalMemory");
488 size_t n = Universe::heap()->capacity();
489 return convert_size_t_to_jlong(n);
490 JVM_END
493 JVM_ENTRY_NO_ENV(jlong, JVM_FreeMemory(void))
494 JVMWrapper("JVM_FreeMemory");
495 CollectedHeap* ch = Universe::heap();
496 size_t n;
497 {
498 MutexLocker x(Heap_lock);
499 n = ch->capacity() - ch->used();
500 }
501 return convert_size_t_to_jlong(n);
502 JVM_END
505 JVM_ENTRY_NO_ENV(jlong, JVM_MaxMemory(void))
506 JVMWrapper("JVM_MaxMemory");
507 size_t n = Universe::heap()->max_capacity();
508 return convert_size_t_to_jlong(n);
509 JVM_END
512 JVM_ENTRY_NO_ENV(jint, JVM_ActiveProcessorCount(void))
513 JVMWrapper("JVM_ActiveProcessorCount");
514 return os::active_processor_count();
515 JVM_END
519 // java.lang.Throwable //////////////////////////////////////////////////////
522 JVM_ENTRY(void, JVM_FillInStackTrace(JNIEnv *env, jobject receiver))
523 JVMWrapper("JVM_FillInStackTrace");
524 Handle exception(thread, JNIHandles::resolve_non_null(receiver));
525 java_lang_Throwable::fill_in_stack_trace(exception);
526 JVM_END
529 JVM_ENTRY(jint, JVM_GetStackTraceDepth(JNIEnv *env, jobject throwable))
530 JVMWrapper("JVM_GetStackTraceDepth");
531 oop exception = JNIHandles::resolve(throwable);
532 return java_lang_Throwable::get_stack_trace_depth(exception, THREAD);
533 JVM_END
536 JVM_ENTRY(jobject, JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index))
537 JVMWrapper("JVM_GetStackTraceElement");
538 JvmtiVMObjectAllocEventCollector oam; // This ctor (throughout this module) may trigger a safepoint/GC
539 oop exception = JNIHandles::resolve(throwable);
540 oop element = java_lang_Throwable::get_stack_trace_element(exception, index, CHECK_NULL);
541 return JNIHandles::make_local(env, element);
542 JVM_END
545 // java.lang.Object ///////////////////////////////////////////////
548 JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
549 JVMWrapper("JVM_IHashCode");
550 // as implemented in the classic virtual machine; return 0 if object is NULL
551 return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
552 JVM_END
555 JVM_ENTRY(void, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
556 JVMWrapper("JVM_MonitorWait");
557 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
558 JavaThreadInObjectWaitState jtiows(thread, ms != 0);
559 if (JvmtiExport::should_post_monitor_wait()) {
560 JvmtiExport::post_monitor_wait((JavaThread *)THREAD, (oop)obj(), ms);
562 // The current thread already owns the monitor and it has not yet
563 // been added to the wait queue so the current thread cannot be
564 // made the successor. This means that the JVMTI_EVENT_MONITOR_WAIT
565 // event handler cannot accidentally consume an unpark() meant for
566 // the ParkEvent associated with this ObjectMonitor.
567 }
568 ObjectSynchronizer::wait(obj, ms, CHECK);
569 JVM_END
572 JVM_ENTRY(void, JVM_MonitorNotify(JNIEnv* env, jobject handle))
573 JVMWrapper("JVM_MonitorNotify");
574 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
575 ObjectSynchronizer::notify(obj, CHECK);
576 JVM_END
579 JVM_ENTRY(void, JVM_MonitorNotifyAll(JNIEnv* env, jobject handle))
580 JVMWrapper("JVM_MonitorNotifyAll");
581 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
582 ObjectSynchronizer::notifyall(obj, CHECK);
583 JVM_END
586 static void fixup_cloned_reference(ReferenceType ref_type, oop src, oop clone) {
587 // If G1 is enabled then we need to register a non-null referent
588 // with the SATB barrier.
589 #if INCLUDE_ALL_GCS
590 if (UseG1GC) {
591 oop referent = java_lang_ref_Reference::referent(clone);
592 if (referent != NULL) {
593 G1SATBCardTableModRefBS::enqueue(referent);
594 }
595 }
596 #endif // INCLUDE_ALL_GCS
597 if ((java_lang_ref_Reference::next(clone) != NULL) ||
598 (java_lang_ref_Reference::queue(clone) == java_lang_ref_ReferenceQueue::ENQUEUED_queue())) {
599 // If the source has been enqueued or is being enqueued, don't
600 // register the clone with a queue.
601 java_lang_ref_Reference::set_queue(clone, java_lang_ref_ReferenceQueue::NULL_queue());
602 }
603 // discovered and next are list links; the clone is not in those lists.
604 java_lang_ref_Reference::set_discovered(clone, NULL);
605 java_lang_ref_Reference::set_next(clone, NULL);
606 }
608 JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
609 JVMWrapper("JVM_Clone");
610 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
611 const KlassHandle klass (THREAD, obj->klass());
612 JvmtiVMObjectAllocEventCollector oam;
614 #ifdef ASSERT
615 // Just checking that the cloneable flag is set correct
616 if (obj->is_array()) {
617 guarantee(klass->is_cloneable(), "all arrays are cloneable");
618 } else {
619 guarantee(obj->is_instance(), "should be instanceOop");
620 bool cloneable = klass->is_subtype_of(SystemDictionary::Cloneable_klass());
621 guarantee(cloneable == klass->is_cloneable(), "incorrect cloneable flag");
622 }
623 #endif
625 // Check if class of obj supports the Cloneable interface.
626 // All arrays are considered to be cloneable (See JLS 20.1.5)
627 if (!klass->is_cloneable()) {
628 ResourceMark rm(THREAD);
629 THROW_MSG_0(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());
630 }
632 // Make shallow object copy
633 ReferenceType ref_type = REF_NONE;
634 const int size = obj->size();
635 oop new_obj_oop = NULL;
636 if (obj->is_array()) {
637 const int length = ((arrayOop)obj())->length();
638 new_obj_oop = CollectedHeap::array_allocate(klass, size, length, CHECK_NULL);
639 } else {
640 ref_type = InstanceKlass::cast(klass())->reference_type();
641 assert((ref_type == REF_NONE) ==
642 !klass->is_subclass_of(SystemDictionary::Reference_klass()),
643 "invariant");
644 new_obj_oop = CollectedHeap::obj_allocate(klass, size, CHECK_NULL);
645 }
647 // 4839641 (4840070): We must do an oop-atomic copy, because if another thread
648 // is modifying a reference field in the clonee, a non-oop-atomic copy might
649 // be suspended in the middle of copying the pointer and end up with parts
650 // of two different pointers in the field. Subsequent dereferences will crash.
651 // 4846409: an oop-copy of objects with long or double fields or arrays of same
652 // won't copy the longs/doubles atomically in 32-bit vm's, so we copy jlongs instead
653 // of oops. We know objects are aligned on a minimum of an jlong boundary.
654 // The same is true of StubRoutines::object_copy and the various oop_copy
655 // variants, and of the code generated by the inline_native_clone intrinsic.
656 assert(MinObjAlignmentInBytes >= BytesPerLong, "objects misaligned");
657 Copy::conjoint_jlongs_atomic((jlong*)obj(), (jlong*)new_obj_oop,
658 (size_t)align_object_size(size) / HeapWordsPerLong);
659 // Clear the header
660 new_obj_oop->init_mark();
662 // Store check (mark entire object and let gc sort it out)
663 BarrierSet* bs = Universe::heap()->barrier_set();
664 assert(bs->has_write_region_opt(), "Barrier set does not have write_region");
665 bs->write_region(MemRegion((HeapWord*)new_obj_oop, size));
667 // If cloning a Reference, set Reference fields to a safe state.
668 // Fixup must be completed before any safepoint.
669 if (ref_type != REF_NONE) {
670 fixup_cloned_reference(ref_type, obj(), new_obj_oop);
671 }
673 Handle new_obj(THREAD, new_obj_oop);
674 // Special handling for MemberNames. Since they contain Method* metadata, they
675 // must be registered so that RedefineClasses can fix metadata contained in them.
676 if (java_lang_invoke_MemberName::is_instance(new_obj()) &&
677 java_lang_invoke_MemberName::is_method(new_obj())) {
678 Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(new_obj());
679 // MemberName may be unresolved, so doesn't need registration until resolved.
680 if (method != NULL) {
681 methodHandle m(THREAD, method);
682 // This can safepoint and redefine method, so need both new_obj and method
683 // in a handle, for two different reasons. new_obj can move, method can be
684 // deleted if nothing is using it on the stack.
685 m->method_holder()->add_member_name(new_obj(), false);
686 }
687 }
689 // Caution: this involves a java upcall, so the clone should be
690 // "gc-robust" by this stage.
691 if (klass->has_finalizer()) {
692 assert(obj->is_instance(), "should be instanceOop");
693 new_obj_oop = InstanceKlass::register_finalizer(instanceOop(new_obj()), CHECK_NULL);
694 new_obj = Handle(THREAD, new_obj_oop);
695 }
697 return JNIHandles::make_local(env, new_obj());
698 JVM_END
700 // java.lang.Compiler ////////////////////////////////////////////////////
702 // The initial cuts of the HotSpot VM will not support JITs, and all existing
703 // JITs would need extensive changes to work with HotSpot. The JIT-related JVM
704 // functions are all silently ignored unless JVM warnings are printed.
706 JVM_LEAF(void, JVM_InitializeCompiler (JNIEnv *env, jclass compCls))
707 if (PrintJVMWarnings) warning("JVM_InitializeCompiler not supported");
708 JVM_END
711 JVM_LEAF(jboolean, JVM_IsSilentCompiler(JNIEnv *env, jclass compCls))
712 if (PrintJVMWarnings) warning("JVM_IsSilentCompiler not supported");
713 return JNI_FALSE;
714 JVM_END
717 JVM_LEAF(jboolean, JVM_CompileClass(JNIEnv *env, jclass compCls, jclass cls))
718 if (PrintJVMWarnings) warning("JVM_CompileClass not supported");
719 return JNI_FALSE;
720 JVM_END
723 JVM_LEAF(jboolean, JVM_CompileClasses(JNIEnv *env, jclass cls, jstring jname))
724 if (PrintJVMWarnings) warning("JVM_CompileClasses not supported");
725 return JNI_FALSE;
726 JVM_END
729 JVM_LEAF(jobject, JVM_CompilerCommand(JNIEnv *env, jclass compCls, jobject arg))
730 if (PrintJVMWarnings) warning("JVM_CompilerCommand not supported");
731 return NULL;
732 JVM_END
735 JVM_LEAF(void, JVM_EnableCompiler(JNIEnv *env, jclass compCls))
736 if (PrintJVMWarnings) warning("JVM_EnableCompiler not supported");
737 JVM_END
740 JVM_LEAF(void, JVM_DisableCompiler(JNIEnv *env, jclass compCls))
741 if (PrintJVMWarnings) warning("JVM_DisableCompiler not supported");
742 JVM_END
746 // Error message support //////////////////////////////////////////////////////
748 JVM_LEAF(jint, JVM_GetLastErrorString(char *buf, int len))
749 JVMWrapper("JVM_GetLastErrorString");
750 return (jint)os::lasterror(buf, len);
751 JVM_END
754 // java.io.File ///////////////////////////////////////////////////////////////
756 JVM_LEAF(char*, JVM_NativePath(char* path))
757 JVMWrapper2("JVM_NativePath (%s)", path);
758 return os::native_path(path);
759 JVM_END
762 // Misc. class handling ///////////////////////////////////////////////////////////
765 JVM_ENTRY(jclass, JVM_GetCallerClass(JNIEnv* env, int depth))
766 JVMWrapper("JVM_GetCallerClass");
768 // Pre-JDK 8 and early builds of JDK 8 don't have a CallerSensitive annotation; or
769 // sun.reflect.Reflection.getCallerClass with a depth parameter is provided
770 // temporarily for existing code to use until a replacement API is defined.
771 if (SystemDictionary::reflect_CallerSensitive_klass() == NULL || depth != JVM_CALLER_DEPTH) {
772 Klass* k = thread->security_get_caller_class(depth);
773 return (k == NULL) ? NULL : (jclass) JNIHandles::make_local(env, k->java_mirror());
774 }
776 // Getting the class of the caller frame.
777 //
778 // The call stack at this point looks something like this:
779 //
780 // [0] [ @CallerSensitive public sun.reflect.Reflection.getCallerClass ]
781 // [1] [ @CallerSensitive API.method ]
782 // [.] [ (skipped intermediate frames) ]
783 // [n] [ caller ]
784 vframeStream vfst(thread);
785 // Cf. LibraryCallKit::inline_native_Reflection_getCallerClass
786 for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {
787 Method* m = vfst.method();
788 assert(m != NULL, "sanity");
789 switch (n) {
790 case 0:
791 // This must only be called from Reflection.getCallerClass
792 if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {
793 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");
794 }
795 // fall-through
796 case 1:
797 // Frame 0 and 1 must be caller sensitive.
798 if (!m->caller_sensitive()) {
799 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));
800 }
801 break;
802 default:
803 if (!m->is_ignored_by_security_stack_walk()) {
804 // We have reached the desired frame; return the holder class.
805 return (jclass) JNIHandles::make_local(env, m->method_holder()->java_mirror());
806 }
807 break;
808 }
809 }
810 return NULL;
811 JVM_END
814 JVM_ENTRY(jclass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))
815 JVMWrapper("JVM_FindPrimitiveClass");
816 oop mirror = NULL;
817 BasicType t = name2type(utf);
818 if (t != T_ILLEGAL && t != T_OBJECT && t != T_ARRAY) {
819 mirror = Universe::java_mirror(t);
820 }
821 if (mirror == NULL) {
822 THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);
823 } else {
824 return (jclass) JNIHandles::make_local(env, mirror);
825 }
826 JVM_END
829 JVM_ENTRY(void, JVM_ResolveClass(JNIEnv* env, jclass cls))
830 JVMWrapper("JVM_ResolveClass");
831 if (PrintJVMWarnings) warning("JVM_ResolveClass not implemented");
832 JVM_END
835 JVM_ENTRY(jboolean, JVM_KnownToNotExist(JNIEnv *env, jobject loader, const char *classname))
836 JVMWrapper("JVM_KnownToNotExist");
837 #if INCLUDE_CDS
838 return ClassLoaderExt::known_to_not_exist(env, loader, classname, CHECK_(false));
839 #else
840 return false;
841 #endif
842 JVM_END
845 JVM_ENTRY(jobjectArray, JVM_GetResourceLookupCacheURLs(JNIEnv *env, jobject loader))
846 JVMWrapper("JVM_GetResourceLookupCacheURLs");
847 #if INCLUDE_CDS
848 return ClassLoaderExt::get_lookup_cache_urls(env, loader, CHECK_NULL);
849 #else
850 return NULL;
851 #endif
852 JVM_END
855 JVM_ENTRY(jintArray, JVM_GetResourceLookupCache(JNIEnv *env, jobject loader, const char *resource_name))
856 JVMWrapper("JVM_GetResourceLookupCache");
857 #if INCLUDE_CDS
858 return ClassLoaderExt::get_lookup_cache(env, loader, resource_name, CHECK_NULL);
859 #else
860 return NULL;
861 #endif
862 JVM_END
865 // Returns a class loaded by the bootstrap class loader; or null
866 // if not found. ClassNotFoundException is not thrown.
867 //
868 // Rationale behind JVM_FindClassFromBootLoader
869 // a> JVM_FindClassFromClassLoader was never exported in the export tables.
870 // b> because of (a) java.dll has a direct dependecy on the unexported
871 // private symbol "_JVM_FindClassFromClassLoader@20".
872 // c> the launcher cannot use the private symbol as it dynamically opens
873 // the entry point, so if something changes, the launcher will fail
874 // unexpectedly at runtime, it is safest for the launcher to dlopen a
875 // stable exported interface.
876 // d> re-exporting JVM_FindClassFromClassLoader as public, will cause its
877 // signature to change from _JVM_FindClassFromClassLoader@20 to
878 // JVM_FindClassFromClassLoader and will not be backward compatible
879 // with older JDKs.
880 // Thus a public/stable exported entry point is the right solution,
881 // public here means public in linker semantics, and is exported only
882 // to the JDK, and is not intended to be a public API.
884 JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,
885 const char* name))
886 JVMWrapper2("JVM_FindClassFromBootLoader %s", name);
888 // Java libraries should ensure that name is never null...
889 if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
890 // It's impossible to create this class; the name cannot fit
891 // into the constant pool.
892 return NULL;
893 }
895 TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
896 Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
897 if (k == NULL) {
898 return NULL;
899 }
901 if (TraceClassResolution) {
902 trace_class_resolution(k);
903 }
904 return (jclass) JNIHandles::make_local(env, k->java_mirror());
905 JVM_END
907 // Not used; JVM_FindClassFromCaller replaces this.
908 JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
909 jboolean init, jobject loader,
910 jboolean throwError))
911 JVMWrapper3("JVM_FindClassFromClassLoader %s throw %s", name,
912 throwError ? "error" : "exception");
913 // Java libraries should ensure that name is never null...
914 if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
915 // It's impossible to create this class; the name cannot fit
916 // into the constant pool.
917 if (throwError) {
918 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
919 } else {
920 THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
921 }
922 }
923 TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
924 Handle h_loader(THREAD, JNIHandles::resolve(loader));
925 jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
926 Handle(), throwError, THREAD);
928 if (TraceClassResolution && result != NULL) {
929 trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
930 }
931 return result;
932 JVM_END
934 // Find a class with this name in this loader, using the caller's protection domain.
935 JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
936 jboolean init, jobject loader,
937 jclass caller))
938 JVMWrapper2("JVM_FindClassFromCaller %s throws ClassNotFoundException", name);
939 // Java libraries should ensure that name is never null...
940 if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
941 // It's impossible to create this class; the name cannot fit
942 // into the constant pool.
943 THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
944 }
946 TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
948 oop loader_oop = JNIHandles::resolve(loader);
949 oop from_class = JNIHandles::resolve(caller);
950 oop protection_domain = NULL;
951 // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
952 // NPE. Put it in another way, the bootstrap class loader has all permission and
953 // thus no checkPackageAccess equivalence in the VM class loader.
954 // The caller is also passed as NULL by the java code if there is no security
955 // manager to avoid the performance cost of getting the calling class.
956 if (from_class != NULL && loader_oop != NULL) {
957 protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
958 }
960 Handle h_loader(THREAD, loader_oop);
961 Handle h_prot(THREAD, protection_domain);
962 jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
963 h_prot, false, THREAD);
965 if (TraceClassResolution && result != NULL) {
966 trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
967 }
968 return result;
969 JVM_END
971 JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
972 jboolean init, jclass from))
973 JVMWrapper2("JVM_FindClassFromClass %s", name);
974 if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
975 // It's impossible to create this class; the name cannot fit
976 // into the constant pool.
977 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
978 }
979 TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
980 oop from_class_oop = JNIHandles::resolve(from);
981 Klass* from_class = (from_class_oop == NULL)
982 ? (Klass*)NULL
983 : java_lang_Class::as_Klass(from_class_oop);
984 oop class_loader = NULL;
985 oop protection_domain = NULL;
986 if (from_class != NULL) {
987 class_loader = from_class->class_loader();
988 protection_domain = from_class->protection_domain();
989 }
990 Handle h_loader(THREAD, class_loader);
991 Handle h_prot (THREAD, protection_domain);
992 jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
993 h_prot, true, thread);
994 if (result != NULL) {
995 oop mirror = JNIHandles::resolve_non_null(result);
996 Klass* to_class = java_lang_Class::as_Klass(mirror);
997 ClassLoaderData* cld = ClassLoaderData::class_loader_data(h_loader());
998 cld->record_dependency(to_class, CHECK_NULL);
999 }
1001 if (TraceClassResolution && result != NULL) {
1002 // this function is generally only used for class loading during verification.
1003 ResourceMark rm;
1004 oop from_mirror = JNIHandles::resolve_non_null(from);
1005 Klass* from_class = java_lang_Class::as_Klass(from_mirror);
1006 const char * from_name = from_class->external_name();
1008 oop mirror = JNIHandles::resolve_non_null(result);
1009 Klass* to_class = java_lang_Class::as_Klass(mirror);
1010 const char * to = to_class->external_name();
1011 tty->print("RESOLVE %s %s (verification)\n", from_name, to);
1012 }
1014 return result;
1015 JVM_END
1017 static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {
1018 if (loader.is_null()) {
1019 return;
1020 }
1022 // check whether the current caller thread holds the lock or not.
1023 // If not, increment the corresponding counter
1024 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=
1025 ObjectSynchronizer::owner_self) {
1026 counter->inc();
1027 }
1028 }
1030 // common code for JVM_DefineClass() and JVM_DefineClassWithSource()
1031 // and JVM_DefineClassWithSourceCond()
1032 static jclass jvm_define_class_common(JNIEnv *env, const char *name,
1033 jobject loader, const jbyte *buf,
1034 jsize len, jobject pd, const char *source,
1035 jboolean verify, TRAPS) {
1036 if (source == NULL) source = "__JVM_DefineClass__";
1038 assert(THREAD->is_Java_thread(), "must be a JavaThread");
1039 JavaThread* jt = (JavaThread*) THREAD;
1041 PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
1042 ClassLoader::perf_define_appclass_selftime(),
1043 ClassLoader::perf_define_appclasses(),
1044 jt->get_thread_stat()->perf_recursion_counts_addr(),
1045 jt->get_thread_stat()->perf_timers_addr(),
1046 PerfClassTraceTime::DEFINE_CLASS);
1048 if (UsePerfData) {
1049 ClassLoader::perf_app_classfile_bytes_read()->inc(len);
1050 }
1052 // Since exceptions can be thrown, class initialization can take place
1053 // if name is NULL no check for class name in .class stream has to be made.
1054 TempNewSymbol class_name = NULL;
1055 if (name != NULL) {
1056 const int str_len = (int)strlen(name);
1057 if (str_len > Symbol::max_length()) {
1058 // It's impossible to create this class; the name cannot fit
1059 // into the constant pool.
1060 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
1061 }
1062 class_name = SymbolTable::new_symbol(name, str_len, CHECK_NULL);
1063 }
1065 ResourceMark rm(THREAD);
1066 ClassFileStream st((u1*) buf, len, (char *)source);
1067 Handle class_loader (THREAD, JNIHandles::resolve(loader));
1068 if (UsePerfData) {
1069 is_lock_held_by_thread(class_loader,
1070 ClassLoader::sync_JVMDefineClassLockFreeCounter(),
1071 THREAD);
1072 }
1073 Handle protection_domain (THREAD, JNIHandles::resolve(pd));
1074 Klass* k = SystemDictionary::resolve_from_stream(class_name, class_loader,
1075 protection_domain, &st,
1076 verify != 0,
1077 CHECK_NULL);
1079 if (TraceClassResolution && k != NULL) {
1080 trace_class_resolution(k);
1081 }
1083 return (jclass) JNIHandles::make_local(env, k->java_mirror());
1084 }
1087 JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
1088 JVMWrapper2("JVM_DefineClass %s", name);
1090 return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, true, THREAD);
1091 JVM_END
1094 JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
1095 JVMWrapper2("JVM_DefineClassWithSource %s", name);
1097 return jvm_define_class_common(env, name, loader, buf, len, pd, source, true, THREAD);
1098 JVM_END
1100 JVM_ENTRY(jclass, JVM_DefineClassWithSourceCond(JNIEnv *env, const char *name,
1101 jobject loader, const jbyte *buf,
1102 jsize len, jobject pd,
1103 const char *source, jboolean verify))
1104 JVMWrapper2("JVM_DefineClassWithSourceCond %s", name);
1106 return jvm_define_class_common(env, name, loader, buf, len, pd, source, verify, THREAD);
1107 JVM_END
1109 JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
1110 JVMWrapper("JVM_FindLoadedClass");
1111 ResourceMark rm(THREAD);
1113 Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
1114 Handle string = java_lang_String::internalize_classname(h_name, CHECK_NULL);
1116 const char* str = java_lang_String::as_utf8_string(string());
1117 // Sanity check, don't expect null
1118 if (str == NULL) return NULL;
1120 const int str_len = (int)strlen(str);
1121 if (str_len > Symbol::max_length()) {
1122 // It's impossible to create this class; the name cannot fit
1123 // into the constant pool.
1124 return NULL;
1125 }
1126 TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len, CHECK_NULL);
1128 // Security Note:
1129 // The Java level wrapper will perform the necessary security check allowing
1130 // us to pass the NULL as the initiating class loader.
1131 Handle h_loader(THREAD, JNIHandles::resolve(loader));
1132 if (UsePerfData) {
1133 is_lock_held_by_thread(h_loader,
1134 ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),
1135 THREAD);
1136 }
1138 Klass* k = SystemDictionary::find_instance_or_array_klass(klass_name,
1139 h_loader,
1140 Handle(),
1141 CHECK_NULL);
1142 #if INCLUDE_CDS
1143 if (k == NULL) {
1144 // If the class is not already loaded, try to see if it's in the shared
1145 // archive for the current classloader (h_loader).
1146 instanceKlassHandle ik = SystemDictionaryShared::find_or_load_shared_class(
1147 klass_name, h_loader, CHECK_NULL);
1148 k = ik();
1149 }
1150 #endif
1151 return (k == NULL) ? NULL :
1152 (jclass) JNIHandles::make_local(env, k->java_mirror());
1153 JVM_END
1156 // Reflection support //////////////////////////////////////////////////////////////////////////////
1158 JVM_ENTRY(jstring, JVM_GetClassName(JNIEnv *env, jclass cls))
1159 assert (cls != NULL, "illegal class");
1160 JVMWrapper("JVM_GetClassName");
1161 JvmtiVMObjectAllocEventCollector oam;
1162 ResourceMark rm(THREAD);
1163 const char* name;
1164 if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1165 name = type2name(java_lang_Class::primitive_type(JNIHandles::resolve(cls)));
1166 } else {
1167 // Consider caching interned string in Klass
1168 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1169 assert(k->is_klass(), "just checking");
1170 name = k->external_name();
1171 }
1172 oop result = StringTable::intern((char*) name, CHECK_NULL);
1173 return (jstring) JNIHandles::make_local(env, result);
1174 JVM_END
1177 JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
1178 JVMWrapper("JVM_GetClassInterfaces");
1179 JvmtiVMObjectAllocEventCollector oam;
1180 oop mirror = JNIHandles::resolve_non_null(cls);
1182 // Special handling for primitive objects
1183 if (java_lang_Class::is_primitive(mirror)) {
1184 // Primitive objects does not have any interfaces
1185 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1186 return (jobjectArray) JNIHandles::make_local(env, r);
1187 }
1189 KlassHandle klass(thread, java_lang_Class::as_Klass(mirror));
1190 // Figure size of result array
1191 int size;
1192 if (klass->oop_is_instance()) {
1193 size = InstanceKlass::cast(klass())->local_interfaces()->length();
1194 } else {
1195 assert(klass->oop_is_objArray() || klass->oop_is_typeArray(), "Illegal mirror klass");
1196 size = 2;
1197 }
1199 // Allocate result array
1200 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), size, CHECK_NULL);
1201 objArrayHandle result (THREAD, r);
1202 // Fill in result
1203 if (klass->oop_is_instance()) {
1204 // Regular instance klass, fill in all local interfaces
1205 for (int index = 0; index < size; index++) {
1206 Klass* k = InstanceKlass::cast(klass())->local_interfaces()->at(index);
1207 result->obj_at_put(index, k->java_mirror());
1208 }
1209 } else {
1210 // All arrays implement java.lang.Cloneable and java.io.Serializable
1211 result->obj_at_put(0, SystemDictionary::Cloneable_klass()->java_mirror());
1212 result->obj_at_put(1, SystemDictionary::Serializable_klass()->java_mirror());
1213 }
1214 return (jobjectArray) JNIHandles::make_local(env, result());
1215 JVM_END
1218 JVM_ENTRY(jobject, JVM_GetClassLoader(JNIEnv *env, jclass cls))
1219 JVMWrapper("JVM_GetClassLoader");
1220 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1221 return NULL;
1222 }
1223 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1224 oop loader = k->class_loader();
1225 return JNIHandles::make_local(env, loader);
1226 JVM_END
1229 JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
1230 JVMWrapper("JVM_IsInterface");
1231 oop mirror = JNIHandles::resolve_non_null(cls);
1232 if (java_lang_Class::is_primitive(mirror)) {
1233 return JNI_FALSE;
1234 }
1235 Klass* k = java_lang_Class::as_Klass(mirror);
1236 jboolean result = k->is_interface();
1237 assert(!result || k->oop_is_instance(),
1238 "all interfaces are instance types");
1239 // The compiler intrinsic for isInterface tests the
1240 // Klass::_access_flags bits in the same way.
1241 return result;
1242 JVM_END
1245 JVM_ENTRY(jobjectArray, JVM_GetClassSigners(JNIEnv *env, jclass cls))
1246 JVMWrapper("JVM_GetClassSigners");
1247 JvmtiVMObjectAllocEventCollector oam;
1248 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1249 // There are no signers for primitive types
1250 return NULL;
1251 }
1253 objArrayOop signers = java_lang_Class::signers(JNIHandles::resolve_non_null(cls));
1255 // If there are no signers set in the class, or if the class
1256 // is an array, return NULL.
1257 if (signers == NULL) return NULL;
1259 // copy of the signers array
1260 Klass* element = ObjArrayKlass::cast(signers->klass())->element_klass();
1261 objArrayOop signers_copy = oopFactory::new_objArray(element, signers->length(), CHECK_NULL);
1262 for (int index = 0; index < signers->length(); index++) {
1263 signers_copy->obj_at_put(index, signers->obj_at(index));
1264 }
1266 // return the copy
1267 return (jobjectArray) JNIHandles::make_local(env, signers_copy);
1268 JVM_END
1271 JVM_ENTRY(void, JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers))
1272 JVMWrapper("JVM_SetClassSigners");
1273 if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1274 // This call is ignored for primitive types and arrays.
1275 // Signers are only set once, ClassLoader.java, and thus shouldn't
1276 // be called with an array. Only the bootstrap loader creates arrays.
1277 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1278 if (k->oop_is_instance()) {
1279 java_lang_Class::set_signers(k->java_mirror(), objArrayOop(JNIHandles::resolve(signers)));
1280 }
1281 }
1282 JVM_END
1285 JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))
1286 JVMWrapper("JVM_GetProtectionDomain");
1287 if (JNIHandles::resolve(cls) == NULL) {
1288 THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
1289 }
1291 if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1292 // Primitive types does not have a protection domain.
1293 return NULL;
1294 }
1296 oop pd = java_lang_Class::protection_domain(JNIHandles::resolve(cls));
1297 return (jobject) JNIHandles::make_local(env, pd);
1298 JVM_END
1301 static bool is_authorized(Handle context, instanceKlassHandle klass, TRAPS) {
1302 // If there is a security manager and protection domain, check the access
1303 // in the protection domain, otherwise it is authorized.
1304 if (java_lang_System::has_security_manager()) {
1306 // For bootstrapping, if pd implies method isn't in the JDK, allow
1307 // this context to revert to older behavior.
1308 // In this case the isAuthorized field in AccessControlContext is also not
1309 // present.
1310 if (Universe::protection_domain_implies_method() == NULL) {
1311 return true;
1312 }
1314 // Whitelist certain access control contexts
1315 if (java_security_AccessControlContext::is_authorized(context)) {
1316 return true;
1317 }
1319 oop prot = klass->protection_domain();
1320 if (prot != NULL) {
1321 // Call pd.implies(new SecurityPermission("createAccessControlContext"))
1322 // in the new wrapper.
1323 methodHandle m(THREAD, Universe::protection_domain_implies_method());
1324 Handle h_prot(THREAD, prot);
1325 JavaValue result(T_BOOLEAN);
1326 JavaCallArguments args(h_prot);
1327 JavaCalls::call(&result, m, &args, CHECK_false);
1328 return (result.get_jboolean() != 0);
1329 }
1330 }
1331 return true;
1332 }
1334 // Create an AccessControlContext with a protection domain with null codesource
1335 // and null permissions - which gives no permissions.
1336 oop create_dummy_access_control_context(TRAPS) {
1337 InstanceKlass* pd_klass = InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass());
1338 Handle obj = pd_klass->allocate_instance_handle(CHECK_NULL);
1339 // Call constructor ProtectionDomain(null, null);
1340 JavaValue result(T_VOID);
1341 JavaCalls::call_special(&result, obj, KlassHandle(THREAD, pd_klass),
1342 vmSymbols::object_initializer_name(),
1343 vmSymbols::codesource_permissioncollection_signature(),
1344 Handle(), Handle(), CHECK_NULL);
1346 // new ProtectionDomain[] {pd};
1347 objArrayOop context = oopFactory::new_objArray(pd_klass, 1, CHECK_NULL);
1348 context->obj_at_put(0, obj());
1350 // new AccessControlContext(new ProtectionDomain[] {pd})
1351 objArrayHandle h_context(THREAD, context);
1352 oop acc = java_security_AccessControlContext::create(h_context, false, Handle(), CHECK_NULL);
1353 return acc;
1354 }
1356 JVM_ENTRY(jobject, JVM_DoPrivileged(JNIEnv *env, jclass cls, jobject action, jobject context, jboolean wrapException))
1357 JVMWrapper("JVM_DoPrivileged");
1359 if (action == NULL) {
1360 THROW_MSG_0(vmSymbols::java_lang_NullPointerException(), "Null action");
1361 }
1363 // Compute the frame initiating the do privileged operation and setup the privileged stack
1364 vframeStream vfst(thread);
1365 vfst.security_get_caller_frame(1);
1367 if (vfst.at_end()) {
1368 THROW_MSG_0(vmSymbols::java_lang_InternalError(), "no caller?");
1369 }
1371 Method* method = vfst.method();
1372 instanceKlassHandle klass (THREAD, method->method_holder());
1374 // Check that action object understands "Object run()"
1375 Handle h_context;
1376 if (context != NULL) {
1377 h_context = Handle(THREAD, JNIHandles::resolve(context));
1378 bool authorized = is_authorized(h_context, klass, CHECK_NULL);
1379 if (!authorized) {
1380 // Create an unprivileged access control object and call it's run function
1381 // instead.
1382 oop noprivs = create_dummy_access_control_context(CHECK_NULL);
1383 h_context = Handle(THREAD, noprivs);
1384 }
1385 }
1387 // Check that action object understands "Object run()"
1388 Handle object (THREAD, JNIHandles::resolve(action));
1390 // get run() method
1391 Method* m_oop = object->klass()->uncached_lookup_method(
1392 vmSymbols::run_method_name(),
1393 vmSymbols::void_object_signature(),
1394 Klass::find_overpass);
1395 methodHandle m (THREAD, m_oop);
1396 if (m.is_null() || !m->is_method() || !m()->is_public() || m()->is_static()) {
1397 THROW_MSG_0(vmSymbols::java_lang_InternalError(), "No run method");
1398 }
1400 // Stack allocated list of privileged stack elements
1401 PrivilegedElement pi;
1402 if (!vfst.at_end()) {
1403 pi.initialize(&vfst, h_context(), thread->privileged_stack_top(), CHECK_NULL);
1404 thread->set_privileged_stack_top(&pi);
1405 }
1408 // invoke the Object run() in the action object. We cannot use call_interface here, since the static type
1409 // is not really known - it is either java.security.PrivilegedAction or java.security.PrivilegedExceptionAction
1410 Handle pending_exception;
1411 JavaValue result(T_OBJECT);
1412 JavaCallArguments args(object);
1413 JavaCalls::call(&result, m, &args, THREAD);
1415 // done with action, remove ourselves from the list
1416 if (!vfst.at_end()) {
1417 assert(thread->privileged_stack_top() != NULL && thread->privileged_stack_top() == &pi, "wrong top element");
1418 thread->set_privileged_stack_top(thread->privileged_stack_top()->next());
1419 }
1421 if (HAS_PENDING_EXCEPTION) {
1422 pending_exception = Handle(THREAD, PENDING_EXCEPTION);
1423 CLEAR_PENDING_EXCEPTION;
1424 // JVMTI has already reported the pending exception
1425 // JVMTI internal flag reset is needed in order to report PrivilegedActionException
1426 if (THREAD->is_Java_thread()) {
1427 JvmtiExport::clear_detected_exception((JavaThread*) THREAD);
1428 }
1429 if ( pending_exception->is_a(SystemDictionary::Exception_klass()) &&
1430 !pending_exception->is_a(SystemDictionary::RuntimeException_klass())) {
1431 // Throw a java.security.PrivilegedActionException(Exception e) exception
1432 JavaCallArguments args(pending_exception);
1433 THROW_ARG_0(vmSymbols::java_security_PrivilegedActionException(),
1434 vmSymbols::exception_void_signature(),
1435 &args);
1436 }
1437 }
1439 if (pending_exception.not_null()) THROW_OOP_0(pending_exception());
1440 return JNIHandles::make_local(env, (oop) result.get_jobject());
1441 JVM_END
1444 // Returns the inherited_access_control_context field of the running thread.
1445 JVM_ENTRY(jobject, JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls))
1446 JVMWrapper("JVM_GetInheritedAccessControlContext");
1447 oop result = java_lang_Thread::inherited_access_control_context(thread->threadObj());
1448 return JNIHandles::make_local(env, result);
1449 JVM_END
1451 class RegisterArrayForGC {
1452 private:
1453 JavaThread *_thread;
1454 public:
1455 RegisterArrayForGC(JavaThread *thread, GrowableArray<oop>* array) {
1456 _thread = thread;
1457 _thread->register_array_for_gc(array);
1458 }
1460 ~RegisterArrayForGC() {
1461 _thread->register_array_for_gc(NULL);
1462 }
1463 };
1466 JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls))
1467 JVMWrapper("JVM_GetStackAccessControlContext");
1468 if (!UsePrivilegedStack) return NULL;
1470 ResourceMark rm(THREAD);
1471 GrowableArray<oop>* local_array = new GrowableArray<oop>(12);
1472 JvmtiVMObjectAllocEventCollector oam;
1474 // count the protection domains on the execution stack. We collapse
1475 // duplicate consecutive protection domains into a single one, as
1476 // well as stopping when we hit a privileged frame.
1478 // Use vframeStream to iterate through Java frames
1479 vframeStream vfst(thread);
1481 oop previous_protection_domain = NULL;
1482 Handle privileged_context(thread, NULL);
1483 bool is_privileged = false;
1484 oop protection_domain = NULL;
1486 for(; !vfst.at_end(); vfst.next()) {
1487 // get method of frame
1488 Method* method = vfst.method();
1489 intptr_t* frame_id = vfst.frame_id();
1491 // check the privileged frames to see if we have a match
1492 if (thread->privileged_stack_top() && thread->privileged_stack_top()->frame_id() == frame_id) {
1493 // this frame is privileged
1494 is_privileged = true;
1495 privileged_context = Handle(thread, thread->privileged_stack_top()->privileged_context());
1496 protection_domain = thread->privileged_stack_top()->protection_domain();
1497 } else {
1498 protection_domain = method->method_holder()->protection_domain();
1499 }
1501 if ((previous_protection_domain != protection_domain) && (protection_domain != NULL)) {
1502 local_array->push(protection_domain);
1503 previous_protection_domain = protection_domain;
1504 }
1506 if (is_privileged) break;
1507 }
1510 // either all the domains on the stack were system domains, or
1511 // we had a privileged system domain
1512 if (local_array->is_empty()) {
1513 if (is_privileged && privileged_context.is_null()) return NULL;
1515 oop result = java_security_AccessControlContext::create(objArrayHandle(), is_privileged, privileged_context, CHECK_NULL);
1516 return JNIHandles::make_local(env, result);
1517 }
1519 // the resource area must be registered in case of a gc
1520 RegisterArrayForGC ragc(thread, local_array);
1521 objArrayOop context = oopFactory::new_objArray(SystemDictionary::ProtectionDomain_klass(),
1522 local_array->length(), CHECK_NULL);
1523 objArrayHandle h_context(thread, context);
1524 for (int index = 0; index < local_array->length(); index++) {
1525 h_context->obj_at_put(index, local_array->at(index));
1526 }
1528 oop result = java_security_AccessControlContext::create(h_context, is_privileged, privileged_context, CHECK_NULL);
1530 return JNIHandles::make_local(env, result);
1531 JVM_END
1534 JVM_QUICK_ENTRY(jboolean, JVM_IsArrayClass(JNIEnv *env, jclass cls))
1535 JVMWrapper("JVM_IsArrayClass");
1536 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1537 return (k != NULL) && k->oop_is_array() ? true : false;
1538 JVM_END
1541 JVM_QUICK_ENTRY(jboolean, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))
1542 JVMWrapper("JVM_IsPrimitiveClass");
1543 oop mirror = JNIHandles::resolve_non_null(cls);
1544 return (jboolean) java_lang_Class::is_primitive(mirror);
1545 JVM_END
1548 JVM_ENTRY(jclass, JVM_GetComponentType(JNIEnv *env, jclass cls))
1549 JVMWrapper("JVM_GetComponentType");
1550 oop mirror = JNIHandles::resolve_non_null(cls);
1551 oop result = Reflection::array_component_type(mirror, CHECK_NULL);
1552 return (jclass) JNIHandles::make_local(env, result);
1553 JVM_END
1556 JVM_ENTRY(jint, JVM_GetClassModifiers(JNIEnv *env, jclass cls))
1557 JVMWrapper("JVM_GetClassModifiers");
1558 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1559 // Primitive type
1560 return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1561 }
1563 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1564 debug_only(int computed_modifiers = k->compute_modifier_flags(CHECK_0));
1565 assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");
1566 return k->modifier_flags();
1567 JVM_END
1570 // Inner class reflection ///////////////////////////////////////////////////////////////////////////////
1572 JVM_ENTRY(jobjectArray, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1573 JvmtiVMObjectAllocEventCollector oam;
1574 // ofClass is a reference to a java_lang_Class object. The mirror object
1575 // of an InstanceKlass
1577 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1578 ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {
1579 oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1580 return (jobjectArray)JNIHandles::make_local(env, result);
1581 }
1583 instanceKlassHandle k(thread, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1584 InnerClassesIterator iter(k);
1586 if (iter.length() == 0) {
1587 // Neither an inner nor outer class
1588 oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1589 return (jobjectArray)JNIHandles::make_local(env, result);
1590 }
1592 // find inner class info
1593 constantPoolHandle cp(thread, k->constants());
1594 int length = iter.length();
1596 // Allocate temp. result array
1597 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);
1598 objArrayHandle result (THREAD, r);
1599 int members = 0;
1601 for (; !iter.done(); iter.next()) {
1602 int ioff = iter.inner_class_info_index();
1603 int ooff = iter.outer_class_info_index();
1605 if (ioff != 0 && ooff != 0) {
1606 // Check to see if the name matches the class we're looking for
1607 // before attempting to find the class.
1608 if (cp->klass_name_at_matches(k, ooff)) {
1609 Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);
1610 if (outer_klass == k()) {
1611 Klass* ik = cp->klass_at(ioff, CHECK_NULL);
1612 instanceKlassHandle inner_klass (THREAD, ik);
1614 // Throws an exception if outer klass has not declared k as
1615 // an inner klass
1616 Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1618 result->obj_at_put(members, inner_klass->java_mirror());
1619 members++;
1620 }
1621 }
1622 }
1623 }
1625 if (members != length) {
1626 // Return array of right length
1627 objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);
1628 for(int i = 0; i < members; i++) {
1629 res->obj_at_put(i, result->obj_at(i));
1630 }
1631 return (jobjectArray)JNIHandles::make_local(env, res);
1632 }
1634 return (jobjectArray)JNIHandles::make_local(env, result());
1635 JVM_END
1638 JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1639 {
1640 // ofClass is a reference to a java_lang_Class object.
1641 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1642 ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {
1643 return NULL;
1644 }
1646 bool inner_is_member = false;
1647 Klass* outer_klass
1648 = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))
1649 )->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1650 if (outer_klass == NULL) return NULL; // already a top-level class
1651 if (!inner_is_member) return NULL; // an anonymous class (inside a method)
1652 return (jclass) JNIHandles::make_local(env, outer_klass->java_mirror());
1653 }
1654 JVM_END
1656 // should be in InstanceKlass.cpp, but is here for historical reasons
1657 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle k,
1658 bool* inner_is_member,
1659 TRAPS) {
1660 Thread* thread = THREAD;
1661 InnerClassesIterator iter(k);
1662 if (iter.length() == 0) {
1663 // No inner class info => no declaring class
1664 return NULL;
1665 }
1667 constantPoolHandle i_cp(thread, k->constants());
1669 bool found = false;
1670 Klass* ok;
1671 instanceKlassHandle outer_klass;
1672 *inner_is_member = false;
1674 // Find inner_klass attribute
1675 for (; !iter.done() && !found; iter.next()) {
1676 int ioff = iter.inner_class_info_index();
1677 int ooff = iter.outer_class_info_index();
1678 int noff = iter.inner_name_index();
1679 if (ioff != 0) {
1680 // Check to see if the name matches the class we're looking for
1681 // before attempting to find the class.
1682 if (i_cp->klass_name_at_matches(k, ioff)) {
1683 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_NULL);
1684 found = (k() == inner_klass);
1685 if (found && ooff != 0) {
1686 ok = i_cp->klass_at(ooff, CHECK_NULL);
1687 outer_klass = instanceKlassHandle(thread, ok);
1688 *inner_is_member = true;
1689 }
1690 }
1691 }
1692 }
1694 if (found && outer_klass.is_null()) {
1695 // It may be anonymous; try for that.
1696 int encl_method_class_idx = k->enclosing_method_class_index();
1697 if (encl_method_class_idx != 0) {
1698 ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
1699 outer_klass = instanceKlassHandle(thread, ok);
1700 *inner_is_member = false;
1701 }
1702 }
1704 // If no inner class attribute found for this class.
1705 if (outer_klass.is_null()) return NULL;
1707 // Throws an exception if outer klass has not declared k as an inner klass
1708 // We need evidence that each klass knows about the other, or else
1709 // the system could allow a spoof of an inner class to gain access rights.
1710 Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);
1711 return outer_klass();
1712 }
1714 JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1715 assert (cls != NULL, "illegal class");
1716 JVMWrapper("JVM_GetClassSignature");
1717 JvmtiVMObjectAllocEventCollector oam;
1718 ResourceMark rm(THREAD);
1719 // Return null for arrays and primatives
1720 if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1721 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1722 if (k->oop_is_instance()) {
1723 Symbol* sym = InstanceKlass::cast(k)->generic_signature();
1724 if (sym == NULL) return NULL;
1725 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1726 return (jstring) JNIHandles::make_local(env, str());
1727 }
1728 }
1729 return NULL;
1730 JVM_END
1733 JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1734 assert (cls != NULL, "illegal class");
1735 JVMWrapper("JVM_GetClassAnnotations");
1737 // Return null for arrays and primitives
1738 if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1739 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1740 if (k->oop_is_instance()) {
1741 typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);
1742 return (jbyteArray) JNIHandles::make_local(env, a);
1743 }
1744 }
1745 return NULL;
1746 JVM_END
1749 static bool jvm_get_field_common(jobject field, fieldDescriptor& fd, TRAPS) {
1750 // some of this code was adapted from from jni_FromReflectedField
1752 oop reflected = JNIHandles::resolve_non_null(field);
1753 oop mirror = java_lang_reflect_Field::clazz(reflected);
1754 Klass* k = java_lang_Class::as_Klass(mirror);
1755 int slot = java_lang_reflect_Field::slot(reflected);
1756 int modifiers = java_lang_reflect_Field::modifiers(reflected);
1758 KlassHandle kh(THREAD, k);
1759 intptr_t offset = InstanceKlass::cast(kh())->field_offset(slot);
1761 if (modifiers & JVM_ACC_STATIC) {
1762 // for static fields we only look in the current class
1763 if (!InstanceKlass::cast(kh())->find_local_field_from_offset(offset, true, &fd)) {
1764 assert(false, "cannot find static field");
1765 return false;
1766 }
1767 } else {
1768 // for instance fields we start with the current class and work
1769 // our way up through the superclass chain
1770 if (!InstanceKlass::cast(kh())->find_field_from_offset(offset, false, &fd)) {
1771 assert(false, "cannot find instance field");
1772 return false;
1773 }
1774 }
1775 return true;
1776 }
1778 JVM_ENTRY(jbyteArray, JVM_GetFieldAnnotations(JNIEnv *env, jobject field))
1779 // field is a handle to a java.lang.reflect.Field object
1780 assert(field != NULL, "illegal field");
1781 JVMWrapper("JVM_GetFieldAnnotations");
1783 fieldDescriptor fd;
1784 bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
1785 if (!gotFd) {
1786 return NULL;
1787 }
1789 return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.annotations(), THREAD));
1790 JVM_END
1793 static Method* jvm_get_method_common(jobject method) {
1794 // some of this code was adapted from from jni_FromReflectedMethod
1796 oop reflected = JNIHandles::resolve_non_null(method);
1797 oop mirror = NULL;
1798 int slot = 0;
1800 if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
1801 mirror = java_lang_reflect_Constructor::clazz(reflected);
1802 slot = java_lang_reflect_Constructor::slot(reflected);
1803 } else {
1804 assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),
1805 "wrong type");
1806 mirror = java_lang_reflect_Method::clazz(reflected);
1807 slot = java_lang_reflect_Method::slot(reflected);
1808 }
1809 Klass* k = java_lang_Class::as_Klass(mirror);
1811 Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
1812 assert(m != NULL, "cannot find method");
1813 return m; // caller has to deal with NULL in product mode
1814 }
1817 JVM_ENTRY(jbyteArray, JVM_GetMethodAnnotations(JNIEnv *env, jobject method))
1818 JVMWrapper("JVM_GetMethodAnnotations");
1820 // method is a handle to a java.lang.reflect.Method object
1821 Method* m = jvm_get_method_common(method);
1822 if (m == NULL) {
1823 return NULL;
1824 }
1826 return (jbyteArray) JNIHandles::make_local(env,
1827 Annotations::make_java_array(m->annotations(), THREAD));
1828 JVM_END
1831 JVM_ENTRY(jbyteArray, JVM_GetMethodDefaultAnnotationValue(JNIEnv *env, jobject method))
1832 JVMWrapper("JVM_GetMethodDefaultAnnotationValue");
1834 // method is a handle to a java.lang.reflect.Method object
1835 Method* m = jvm_get_method_common(method);
1836 if (m == NULL) {
1837 return NULL;
1838 }
1840 return (jbyteArray) JNIHandles::make_local(env,
1841 Annotations::make_java_array(m->annotation_default(), THREAD));
1842 JVM_END
1845 JVM_ENTRY(jbyteArray, JVM_GetMethodParameterAnnotations(JNIEnv *env, jobject method))
1846 JVMWrapper("JVM_GetMethodParameterAnnotations");
1848 // method is a handle to a java.lang.reflect.Method object
1849 Method* m = jvm_get_method_common(method);
1850 if (m == NULL) {
1851 return NULL;
1852 }
1854 return (jbyteArray) JNIHandles::make_local(env,
1855 Annotations::make_java_array(m->parameter_annotations(), THREAD));
1856 JVM_END
1858 /* Type use annotations support (JDK 1.8) */
1860 JVM_ENTRY(jbyteArray, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))
1861 assert (cls != NULL, "illegal class");
1862 JVMWrapper("JVM_GetClassTypeAnnotations");
1863 ResourceMark rm(THREAD);
1864 // Return null for arrays and primitives
1865 if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1866 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1867 if (k->oop_is_instance()) {
1868 AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
1869 if (type_annotations != NULL) {
1870 typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1871 return (jbyteArray) JNIHandles::make_local(env, a);
1872 }
1873 }
1874 }
1875 return NULL;
1876 JVM_END
1878 JVM_ENTRY(jbyteArray, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
1879 assert (method != NULL, "illegal method");
1880 JVMWrapper("JVM_GetMethodTypeAnnotations");
1882 // method is a handle to a java.lang.reflect.Method object
1883 Method* m = jvm_get_method_common(method);
1884 if (m == NULL) {
1885 return NULL;
1886 }
1888 AnnotationArray* type_annotations = m->type_annotations();
1889 if (type_annotations != NULL) {
1890 typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1891 return (jbyteArray) JNIHandles::make_local(env, a);
1892 }
1894 return NULL;
1895 JVM_END
1897 JVM_ENTRY(jbyteArray, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
1898 assert (field != NULL, "illegal field");
1899 JVMWrapper("JVM_GetFieldTypeAnnotations");
1901 fieldDescriptor fd;
1902 bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
1903 if (!gotFd) {
1904 return NULL;
1905 }
1907 return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.type_annotations(), THREAD));
1908 JVM_END
1910 static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
1911 if (!cp->is_within_bounds(index)) {
1912 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1913 }
1914 }
1916 JVM_ENTRY(jobjectArray, JVM_GetMethodParameters(JNIEnv *env, jobject method))
1917 {
1918 JVMWrapper("JVM_GetMethodParameters");
1919 // method is a handle to a java.lang.reflect.Method object
1920 Method* method_ptr = jvm_get_method_common(method);
1921 methodHandle mh (THREAD, method_ptr);
1922 Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
1923 const int num_params = mh->method_parameters_length();
1925 if (0 != num_params) {
1926 // make sure all the symbols are properly formatted
1927 for (int i = 0; i < num_params; i++) {
1928 MethodParametersElement* params = mh->method_parameters_start();
1929 int index = params[i].name_cp_index;
1930 bounds_check(mh->constants(), index, CHECK_NULL);
1932 if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
1933 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
1934 "Wrong type at constant pool index");
1935 }
1937 }
1939 objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);
1940 objArrayHandle result (THREAD, result_oop);
1942 for (int i = 0; i < num_params; i++) {
1943 MethodParametersElement* params = mh->method_parameters_start();
1944 // For a 0 index, give a NULL symbol
1945 Symbol* sym = 0 != params[i].name_cp_index ?
1946 mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
1947 int flags = params[i].flags;
1948 oop param = Reflection::new_parameter(reflected_method, i, sym,
1949 flags, CHECK_NULL);
1950 result->obj_at_put(i, param);
1951 }
1952 return (jobjectArray)JNIHandles::make_local(env, result());
1953 } else {
1954 return (jobjectArray)NULL;
1955 }
1956 }
1957 JVM_END
1959 // New (JDK 1.4) reflection implementation /////////////////////////////////////
1961 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
1962 {
1963 JVMWrapper("JVM_GetClassDeclaredFields");
1964 JvmtiVMObjectAllocEventCollector oam;
1966 // Exclude primitive types and array types
1967 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1968 java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
1969 // Return empty array
1970 oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
1971 return (jobjectArray) JNIHandles::make_local(env, res);
1972 }
1974 instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1975 constantPoolHandle cp(THREAD, k->constants());
1977 // Ensure class is linked
1978 k->link_class(CHECK_NULL);
1980 // 4496456 We need to filter out java.lang.Throwable.backtrace
1981 bool skip_backtrace = false;
1983 // Allocate result
1984 int num_fields;
1986 if (publicOnly) {
1987 num_fields = 0;
1988 for (JavaFieldStream fs(k()); !fs.done(); fs.next()) {
1989 if (fs.access_flags().is_public()) ++num_fields;
1990 }
1991 } else {
1992 num_fields = k->java_fields_count();
1994 if (k() == SystemDictionary::Throwable_klass()) {
1995 num_fields--;
1996 skip_backtrace = true;
1997 }
1998 }
2000 objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
2001 objArrayHandle result (THREAD, r);
2003 int out_idx = 0;
2004 fieldDescriptor fd;
2005 for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
2006 if (skip_backtrace) {
2007 // 4496456 skip java.lang.Throwable.backtrace
2008 int offset = fs.offset();
2009 if (offset == java_lang_Throwable::get_backtrace_offset()) continue;
2010 }
2012 if (!publicOnly || fs.access_flags().is_public()) {
2013 fd.reinitialize(k(), fs.index());
2014 oop field = Reflection::new_field(&fd, UseNewReflection, CHECK_NULL);
2015 result->obj_at_put(out_idx, field);
2016 ++out_idx;
2017 }
2018 }
2019 assert(out_idx == num_fields, "just checking");
2020 return (jobjectArray) JNIHandles::make_local(env, result());
2021 }
2022 JVM_END
2024 static bool select_method(methodHandle method, bool want_constructor) {
2025 if (want_constructor) {
2026 return (method->is_initializer() && !method->is_static());
2027 } else {
2028 return (!method->is_initializer() && !method->is_overpass());
2029 }
2030 }
2032 static jobjectArray get_class_declared_methods_helper(
2033 JNIEnv *env,
2034 jclass ofClass, jboolean publicOnly,
2035 bool want_constructor,
2036 Klass* klass, TRAPS) {
2038 JvmtiVMObjectAllocEventCollector oam;
2040 // Exclude primitive types and array types
2041 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
2042 || java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
2043 // Return empty array
2044 oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
2045 return (jobjectArray) JNIHandles::make_local(env, res);
2046 }
2048 instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
2050 // Ensure class is linked
2051 k->link_class(CHECK_NULL);
2053 Array<Method*>* methods = k->methods();
2054 int methods_length = methods->length();
2056 // Save original method_idnum in case of redefinition, which can change
2057 // the idnum of obsolete methods. The new method will have the same idnum
2058 // but if we refresh the methods array, the counts will be wrong.
2059 ResourceMark rm(THREAD);
2060 GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
2061 int num_methods = 0;
2063 for (int i = 0; i < methods_length; i++) {
2064 methodHandle method(THREAD, methods->at(i));
2065 if (select_method(method, want_constructor)) {
2066 if (!publicOnly || method->is_public()) {
2067 idnums->push(method->method_idnum());
2068 ++num_methods;
2069 }
2070 }
2071 }
2073 // Allocate result
2074 objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
2075 objArrayHandle result (THREAD, r);
2077 // Now just put the methods that we selected above, but go by their idnum
2078 // in case of redefinition. The methods can be redefined at any safepoint,
2079 // so above when allocating the oop array and below when creating reflect
2080 // objects.
2081 for (int i = 0; i < num_methods; i++) {
2082 methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
2083 if (method.is_null()) {
2084 // Method may have been deleted and seems this API can handle null
2085 // Otherwise should probably put a method that throws NSME
2086 result->obj_at_put(i, NULL);
2087 } else {
2088 oop m;
2089 if (want_constructor) {
2090 m = Reflection::new_constructor(method, CHECK_NULL);
2091 } else {
2092 m = Reflection::new_method(method, UseNewReflection, false, CHECK_NULL);
2093 }
2094 result->obj_at_put(i, m);
2095 }
2096 }
2098 return (jobjectArray) JNIHandles::make_local(env, result());
2099 }
2101 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
2102 {
2103 JVMWrapper("JVM_GetClassDeclaredMethods");
2104 return get_class_declared_methods_helper(env, ofClass, publicOnly,
2105 /*want_constructor*/ false,
2106 SystemDictionary::reflect_Method_klass(), THREAD);
2107 }
2108 JVM_END
2110 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
2111 {
2112 JVMWrapper("JVM_GetClassDeclaredConstructors");
2113 return get_class_declared_methods_helper(env, ofClass, publicOnly,
2114 /*want_constructor*/ true,
2115 SystemDictionary::reflect_Constructor_klass(), THREAD);
2116 }
2117 JVM_END
2119 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
2120 {
2121 JVMWrapper("JVM_GetClassAccessFlags");
2122 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2123 // Primitive type
2124 return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
2125 }
2127 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2128 return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
2129 }
2130 JVM_END
2133 // Constant pool access //////////////////////////////////////////////////////////
2135 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
2136 {
2137 JVMWrapper("JVM_GetClassConstantPool");
2138 JvmtiVMObjectAllocEventCollector oam;
2140 // Return null for primitives and arrays
2141 if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2142 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2143 if (k->oop_is_instance()) {
2144 instanceKlassHandle k_h(THREAD, k);
2145 Handle jcp = sun_reflect_ConstantPool::create(CHECK_NULL);
2146 sun_reflect_ConstantPool::set_cp(jcp(), k_h->constants());
2147 return JNIHandles::make_local(jcp());
2148 }
2149 }
2150 return NULL;
2151 }
2152 JVM_END
2155 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
2156 {
2157 JVMWrapper("JVM_ConstantPoolGetSize");
2158 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2159 return cp->length();
2160 }
2161 JVM_END
2164 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2165 {
2166 JVMWrapper("JVM_ConstantPoolGetClassAt");
2167 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2168 bounds_check(cp, index, CHECK_NULL);
2169 constantTag tag = cp->tag_at(index);
2170 if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2171 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2172 }
2173 Klass* k = cp->klass_at(index, CHECK_NULL);
2174 return (jclass) JNIHandles::make_local(k->java_mirror());
2175 }
2176 JVM_END
2178 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2179 {
2180 JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
2181 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2182 bounds_check(cp, index, CHECK_NULL);
2183 constantTag tag = cp->tag_at(index);
2184 if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2185 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2186 }
2187 Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
2188 if (k == NULL) return NULL;
2189 return (jclass) JNIHandles::make_local(k->java_mirror());
2190 }
2191 JVM_END
2193 static jobject get_method_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2194 constantTag tag = cp->tag_at(index);
2195 if (!tag.is_method() && !tag.is_interface_method()) {
2196 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2197 }
2198 int klass_ref = cp->uncached_klass_ref_index_at(index);
2199 Klass* k_o;
2200 if (force_resolution) {
2201 k_o = cp->klass_at(klass_ref, CHECK_NULL);
2202 } else {
2203 k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2204 if (k_o == NULL) return NULL;
2205 }
2206 instanceKlassHandle k(THREAD, k_o);
2207 Symbol* name = cp->uncached_name_ref_at(index);
2208 Symbol* sig = cp->uncached_signature_ref_at(index);
2209 methodHandle m (THREAD, k->find_method(name, sig));
2210 if (m.is_null()) {
2211 THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
2212 }
2213 oop method;
2214 if (!m->is_initializer() || m->is_static()) {
2215 method = Reflection::new_method(m, true, true, CHECK_NULL);
2216 } else {
2217 method = Reflection::new_constructor(m, CHECK_NULL);
2218 }
2219 return JNIHandles::make_local(method);
2220 }
2222 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2223 {
2224 JVMWrapper("JVM_ConstantPoolGetMethodAt");
2225 JvmtiVMObjectAllocEventCollector oam;
2226 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2227 bounds_check(cp, index, CHECK_NULL);
2228 jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
2229 return res;
2230 }
2231 JVM_END
2233 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2234 {
2235 JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
2236 JvmtiVMObjectAllocEventCollector oam;
2237 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2238 bounds_check(cp, index, CHECK_NULL);
2239 jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2240 return res;
2241 }
2242 JVM_END
2244 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2245 constantTag tag = cp->tag_at(index);
2246 if (!tag.is_field()) {
2247 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2248 }
2249 int klass_ref = cp->uncached_klass_ref_index_at(index);
2250 Klass* k_o;
2251 if (force_resolution) {
2252 k_o = cp->klass_at(klass_ref, CHECK_NULL);
2253 } else {
2254 k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2255 if (k_o == NULL) return NULL;
2256 }
2257 instanceKlassHandle k(THREAD, k_o);
2258 Symbol* name = cp->uncached_name_ref_at(index);
2259 Symbol* sig = cp->uncached_signature_ref_at(index);
2260 fieldDescriptor fd;
2261 Klass* target_klass = k->find_field(name, sig, &fd);
2262 if (target_klass == NULL) {
2263 THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2264 }
2265 oop field = Reflection::new_field(&fd, true, CHECK_NULL);
2266 return JNIHandles::make_local(field);
2267 }
2269 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2270 {
2271 JVMWrapper("JVM_ConstantPoolGetFieldAt");
2272 JvmtiVMObjectAllocEventCollector oam;
2273 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2274 bounds_check(cp, index, CHECK_NULL);
2275 jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2276 return res;
2277 }
2278 JVM_END
2280 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2281 {
2282 JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2283 JvmtiVMObjectAllocEventCollector oam;
2284 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2285 bounds_check(cp, index, CHECK_NULL);
2286 jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2287 return res;
2288 }
2289 JVM_END
2291 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2292 {
2293 JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2294 JvmtiVMObjectAllocEventCollector oam;
2295 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2296 bounds_check(cp, index, CHECK_NULL);
2297 constantTag tag = cp->tag_at(index);
2298 if (!tag.is_field_or_method()) {
2299 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2300 }
2301 int klass_ref = cp->uncached_klass_ref_index_at(index);
2302 Symbol* klass_name = cp->klass_name_at(klass_ref);
2303 Symbol* member_name = cp->uncached_name_ref_at(index);
2304 Symbol* member_sig = cp->uncached_signature_ref_at(index);
2305 objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2306 objArrayHandle dest(THREAD, dest_o);
2307 Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2308 dest->obj_at_put(0, str());
2309 str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2310 dest->obj_at_put(1, str());
2311 str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2312 dest->obj_at_put(2, str());
2313 return (jobjectArray) JNIHandles::make_local(dest());
2314 }
2315 JVM_END
2317 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2318 {
2319 JVMWrapper("JVM_ConstantPoolGetIntAt");
2320 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2321 bounds_check(cp, index, CHECK_0);
2322 constantTag tag = cp->tag_at(index);
2323 if (!tag.is_int()) {
2324 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2325 }
2326 return cp->int_at(index);
2327 }
2328 JVM_END
2330 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2331 {
2332 JVMWrapper("JVM_ConstantPoolGetLongAt");
2333 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2334 bounds_check(cp, index, CHECK_(0L));
2335 constantTag tag = cp->tag_at(index);
2336 if (!tag.is_long()) {
2337 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2338 }
2339 return cp->long_at(index);
2340 }
2341 JVM_END
2343 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2344 {
2345 JVMWrapper("JVM_ConstantPoolGetFloatAt");
2346 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2347 bounds_check(cp, index, CHECK_(0.0f));
2348 constantTag tag = cp->tag_at(index);
2349 if (!tag.is_float()) {
2350 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2351 }
2352 return cp->float_at(index);
2353 }
2354 JVM_END
2356 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2357 {
2358 JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2359 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2360 bounds_check(cp, index, CHECK_(0.0));
2361 constantTag tag = cp->tag_at(index);
2362 if (!tag.is_double()) {
2363 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2364 }
2365 return cp->double_at(index);
2366 }
2367 JVM_END
2369 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2370 {
2371 JVMWrapper("JVM_ConstantPoolGetStringAt");
2372 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2373 bounds_check(cp, index, CHECK_NULL);
2374 constantTag tag = cp->tag_at(index);
2375 if (!tag.is_string()) {
2376 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2377 }
2378 oop str = cp->string_at(index, CHECK_NULL);
2379 return (jstring) JNIHandles::make_local(str);
2380 }
2381 JVM_END
2383 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2384 {
2385 JVMWrapper("JVM_ConstantPoolGetUTF8At");
2386 JvmtiVMObjectAllocEventCollector oam;
2387 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2388 bounds_check(cp, index, CHECK_NULL);
2389 constantTag tag = cp->tag_at(index);
2390 if (!tag.is_symbol()) {
2391 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2392 }
2393 Symbol* sym = cp->symbol_at(index);
2394 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2395 return (jstring) JNIHandles::make_local(str());
2396 }
2397 JVM_END
2400 // Assertion support. //////////////////////////////////////////////////////////
2402 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2403 JVMWrapper("JVM_DesiredAssertionStatus");
2404 assert(cls != NULL, "bad class");
2406 oop r = JNIHandles::resolve(cls);
2407 assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2408 if (java_lang_Class::is_primitive(r)) return false;
2410 Klass* k = java_lang_Class::as_Klass(r);
2411 assert(k->oop_is_instance(), "must be an instance klass");
2412 if (! k->oop_is_instance()) return false;
2414 ResourceMark rm(THREAD);
2415 const char* name = k->name()->as_C_string();
2416 bool system_class = k->class_loader() == NULL;
2417 return JavaAssertions::enabled(name, system_class);
2419 JVM_END
2422 // Return a new AssertionStatusDirectives object with the fields filled in with
2423 // command-line assertion arguments (i.e., -ea, -da).
2424 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2425 JVMWrapper("JVM_AssertionStatusDirectives");
2426 JvmtiVMObjectAllocEventCollector oam;
2427 oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2428 return JNIHandles::make_local(env, asd);
2429 JVM_END
2431 // Verification ////////////////////////////////////////////////////////////////////////////////
2433 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2435 // RedefineClasses support: bug 6214132 caused verification to fail.
2436 // All functions from this section should call the jvmtiThreadSate function:
2437 // Klass* class_to_verify_considering_redefinition(Klass* klass).
2438 // The function returns a Klass* of the _scratch_class if the verifier
2439 // was invoked in the middle of the class redefinition.
2440 // Otherwise it returns its argument value which is the _the_class Klass*.
2441 // Please, refer to the description in the jvmtiThreadSate.hpp.
2443 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2444 JVMWrapper("JVM_GetClassNameUTF");
2445 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2446 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2447 return k->name()->as_utf8();
2448 JVM_END
2451 JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2452 JVMWrapper("JVM_GetClassCPTypes");
2453 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2454 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2455 // types will have length zero if this is not an InstanceKlass
2456 // (length is determined by call to JVM_GetClassCPEntriesCount)
2457 if (k->oop_is_instance()) {
2458 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2459 for (int index = cp->length() - 1; index >= 0; index--) {
2460 constantTag tag = cp->tag_at(index);
2461 types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class : tag.value();
2462 }
2463 }
2464 JVM_END
2467 JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2468 JVMWrapper("JVM_GetClassCPEntriesCount");
2469 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2470 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2471 if (!k->oop_is_instance())
2472 return 0;
2473 return InstanceKlass::cast(k)->constants()->length();
2474 JVM_END
2477 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2478 JVMWrapper("JVM_GetClassFieldsCount");
2479 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2480 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2481 if (!k->oop_is_instance())
2482 return 0;
2483 return InstanceKlass::cast(k)->java_fields_count();
2484 JVM_END
2487 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2488 JVMWrapper("JVM_GetClassMethodsCount");
2489 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2490 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2491 if (!k->oop_is_instance())
2492 return 0;
2493 return InstanceKlass::cast(k)->methods()->length();
2494 JVM_END
2497 // The following methods, used for the verifier, are never called with
2498 // array klasses, so a direct cast to InstanceKlass is safe.
2499 // Typically, these methods are called in a loop with bounds determined
2500 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2501 // zero for arrays.
2502 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2503 JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2504 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2505 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2506 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2507 int length = method->checked_exceptions_length();
2508 if (length > 0) {
2509 CheckedExceptionElement* table= method->checked_exceptions_start();
2510 for (int i = 0; i < length; i++) {
2511 exceptions[i] = table[i].class_cp_index;
2512 }
2513 }
2514 JVM_END
2517 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2518 JVMWrapper("JVM_GetMethodIxExceptionsCount");
2519 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2520 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2521 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2522 return method->checked_exceptions_length();
2523 JVM_END
2526 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2527 JVMWrapper("JVM_GetMethodIxByteCode");
2528 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2529 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2530 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2531 memcpy(code, method->code_base(), method->code_size());
2532 JVM_END
2535 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2536 JVMWrapper("JVM_GetMethodIxByteCodeLength");
2537 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2538 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2539 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2540 return method->code_size();
2541 JVM_END
2544 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2545 JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
2546 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2547 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2548 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2549 ExceptionTable extable(method);
2550 entry->start_pc = extable.start_pc(entry_index);
2551 entry->end_pc = extable.end_pc(entry_index);
2552 entry->handler_pc = extable.handler_pc(entry_index);
2553 entry->catchType = extable.catch_type_index(entry_index);
2554 JVM_END
2557 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2558 JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2559 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2560 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2561 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2562 return method->exception_table_length();
2563 JVM_END
2566 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2567 JVMWrapper("JVM_GetMethodIxModifiers");
2568 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2569 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2570 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2571 return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2572 JVM_END
2575 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2576 JVMWrapper("JVM_GetFieldIxModifiers");
2577 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2578 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2579 return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2580 JVM_END
2583 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2584 JVMWrapper("JVM_GetMethodIxLocalsCount");
2585 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2586 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2587 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2588 return method->max_locals();
2589 JVM_END
2592 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2593 JVMWrapper("JVM_GetMethodIxArgsSize");
2594 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2595 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2596 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2597 return method->size_of_parameters();
2598 JVM_END
2601 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2602 JVMWrapper("JVM_GetMethodIxMaxStack");
2603 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2604 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2605 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2606 return method->verifier_max_stack();
2607 JVM_END
2610 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2611 JVMWrapper("JVM_IsConstructorIx");
2612 ResourceMark rm(THREAD);
2613 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2614 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2615 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2616 return method->name() == vmSymbols::object_initializer_name();
2617 JVM_END
2620 JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2621 JVMWrapper("JVM_IsVMGeneratedMethodIx");
2622 ResourceMark rm(THREAD);
2623 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2624 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2625 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2626 return method->is_overpass();
2627 JVM_END
2629 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2630 JVMWrapper("JVM_GetMethodIxIxUTF");
2631 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2632 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2633 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2634 return method->name()->as_utf8();
2635 JVM_END
2638 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2639 JVMWrapper("JVM_GetMethodIxSignatureUTF");
2640 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2641 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2642 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2643 return method->signature()->as_utf8();
2644 JVM_END
2646 /**
2647 * All of these JVM_GetCP-xxx methods are used by the old verifier to
2648 * read entries in the constant pool. Since the old verifier always
2649 * works on a copy of the code, it will not see any rewriting that
2650 * may possibly occur in the middle of verification. So it is important
2651 * that nothing it calls tries to use the cpCache instead of the raw
2652 * constant pool, so we must use cp->uncached_x methods when appropriate.
2653 */
2654 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2655 JVMWrapper("JVM_GetCPFieldNameUTF");
2656 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2657 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2658 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2659 switch (cp->tag_at(cp_index).value()) {
2660 case JVM_CONSTANT_Fieldref:
2661 return cp->uncached_name_ref_at(cp_index)->as_utf8();
2662 default:
2663 fatal("JVM_GetCPFieldNameUTF: illegal constant");
2664 }
2665 ShouldNotReachHere();
2666 return NULL;
2667 JVM_END
2670 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2671 JVMWrapper("JVM_GetCPMethodNameUTF");
2672 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2673 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2674 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2675 switch (cp->tag_at(cp_index).value()) {
2676 case JVM_CONSTANT_InterfaceMethodref:
2677 case JVM_CONSTANT_Methodref:
2678 return cp->uncached_name_ref_at(cp_index)->as_utf8();
2679 default:
2680 fatal("JVM_GetCPMethodNameUTF: illegal constant");
2681 }
2682 ShouldNotReachHere();
2683 return NULL;
2684 JVM_END
2687 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2688 JVMWrapper("JVM_GetCPMethodSignatureUTF");
2689 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2690 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2691 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2692 switch (cp->tag_at(cp_index).value()) {
2693 case JVM_CONSTANT_InterfaceMethodref:
2694 case JVM_CONSTANT_Methodref:
2695 return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2696 default:
2697 fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2698 }
2699 ShouldNotReachHere();
2700 return NULL;
2701 JVM_END
2704 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2705 JVMWrapper("JVM_GetCPFieldSignatureUTF");
2706 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2707 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2708 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2709 switch (cp->tag_at(cp_index).value()) {
2710 case JVM_CONSTANT_Fieldref:
2711 return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2712 default:
2713 fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2714 }
2715 ShouldNotReachHere();
2716 return NULL;
2717 JVM_END
2720 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2721 JVMWrapper("JVM_GetCPClassNameUTF");
2722 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2723 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2724 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2725 Symbol* classname = cp->klass_name_at(cp_index);
2726 return classname->as_utf8();
2727 JVM_END
2730 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2731 JVMWrapper("JVM_GetCPFieldClassNameUTF");
2732 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2733 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2734 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2735 switch (cp->tag_at(cp_index).value()) {
2736 case JVM_CONSTANT_Fieldref: {
2737 int class_index = cp->uncached_klass_ref_index_at(cp_index);
2738 Symbol* classname = cp->klass_name_at(class_index);
2739 return classname->as_utf8();
2740 }
2741 default:
2742 fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2743 }
2744 ShouldNotReachHere();
2745 return NULL;
2746 JVM_END
2749 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2750 JVMWrapper("JVM_GetCPMethodClassNameUTF");
2751 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2752 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2753 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2754 switch (cp->tag_at(cp_index).value()) {
2755 case JVM_CONSTANT_Methodref:
2756 case JVM_CONSTANT_InterfaceMethodref: {
2757 int class_index = cp->uncached_klass_ref_index_at(cp_index);
2758 Symbol* classname = cp->klass_name_at(class_index);
2759 return classname->as_utf8();
2760 }
2761 default:
2762 fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2763 }
2764 ShouldNotReachHere();
2765 return NULL;
2766 JVM_END
2769 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2770 JVMWrapper("JVM_GetCPFieldModifiers");
2771 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2772 Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2773 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2774 k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2775 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2776 ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2777 switch (cp->tag_at(cp_index).value()) {
2778 case JVM_CONSTANT_Fieldref: {
2779 Symbol* name = cp->uncached_name_ref_at(cp_index);
2780 Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2781 for (JavaFieldStream fs(k_called); !fs.done(); fs.next()) {
2782 if (fs.name() == name && fs.signature() == signature) {
2783 return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2784 }
2785 }
2786 return -1;
2787 }
2788 default:
2789 fatal("JVM_GetCPFieldModifiers: illegal constant");
2790 }
2791 ShouldNotReachHere();
2792 return 0;
2793 JVM_END
2796 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2797 JVMWrapper("JVM_GetCPMethodModifiers");
2798 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2799 Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2800 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2801 k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2802 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2803 switch (cp->tag_at(cp_index).value()) {
2804 case JVM_CONSTANT_Methodref:
2805 case JVM_CONSTANT_InterfaceMethodref: {
2806 Symbol* name = cp->uncached_name_ref_at(cp_index);
2807 Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2808 Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2809 int methods_count = methods->length();
2810 for (int i = 0; i < methods_count; i++) {
2811 Method* method = methods->at(i);
2812 if (method->name() == name && method->signature() == signature) {
2813 return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2814 }
2815 }
2816 return -1;
2817 }
2818 default:
2819 fatal("JVM_GetCPMethodModifiers: illegal constant");
2820 }
2821 ShouldNotReachHere();
2822 return 0;
2823 JVM_END
2826 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2828 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2829 // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2830 JVM_END
2833 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2834 JVMWrapper("JVM_IsSameClassPackage");
2835 oop class1_mirror = JNIHandles::resolve_non_null(class1);
2836 oop class2_mirror = JNIHandles::resolve_non_null(class2);
2837 Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2838 Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2839 return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2840 JVM_END
2843 // IO functions ////////////////////////////////////////////////////////////////////////////////////////
2845 JVM_LEAF(jint, JVM_Open(const char *fname, jint flags, jint mode))
2846 JVMWrapper2("JVM_Open (%s)", fname);
2848 //%note jvm_r6
2849 int result = os::open(fname, flags, mode);
2850 if (result >= 0) {
2851 return result;
2852 } else {
2853 switch(errno) {
2854 case EEXIST:
2855 return JVM_EEXIST;
2856 default:
2857 return -1;
2858 }
2859 }
2860 JVM_END
2863 JVM_LEAF(jint, JVM_Close(jint fd))
2864 JVMWrapper2("JVM_Close (0x%x)", fd);
2865 //%note jvm_r6
2866 return os::close(fd);
2867 JVM_END
2870 JVM_LEAF(jint, JVM_Read(jint fd, char *buf, jint nbytes))
2871 JVMWrapper2("JVM_Read (0x%x)", fd);
2873 //%note jvm_r6
2874 return (jint)os::restartable_read(fd, buf, nbytes);
2875 JVM_END
2878 JVM_LEAF(jint, JVM_Write(jint fd, char *buf, jint nbytes))
2879 JVMWrapper2("JVM_Write (0x%x)", fd);
2881 //%note jvm_r6
2882 return (jint)os::write(fd, buf, nbytes);
2883 JVM_END
2886 JVM_LEAF(jint, JVM_Available(jint fd, jlong *pbytes))
2887 JVMWrapper2("JVM_Available (0x%x)", fd);
2888 //%note jvm_r6
2889 return os::available(fd, pbytes);
2890 JVM_END
2893 JVM_LEAF(jlong, JVM_Lseek(jint fd, jlong offset, jint whence))
2894 JVMWrapper4("JVM_Lseek (0x%x, " INT64_FORMAT ", %d)", fd, (int64_t) offset, whence);
2895 //%note jvm_r6
2896 return os::lseek(fd, offset, whence);
2897 JVM_END
2900 JVM_LEAF(jint, JVM_SetLength(jint fd, jlong length))
2901 JVMWrapper3("JVM_SetLength (0x%x, " INT64_FORMAT ")", fd, (int64_t) length);
2902 return os::ftruncate(fd, length);
2903 JVM_END
2906 JVM_LEAF(jint, JVM_Sync(jint fd))
2907 JVMWrapper2("JVM_Sync (0x%x)", fd);
2908 //%note jvm_r6
2909 return os::fsync(fd);
2910 JVM_END
2913 // Printing support //////////////////////////////////////////////////
2914 extern "C" {
2916 ATTRIBUTE_PRINTF(3, 0)
2917 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2918 // Reject count values that are negative signed values converted to
2919 // unsigned; see bug 4399518, 4417214
2920 if ((intptr_t)count <= 0) return -1;
2922 int result = os::vsnprintf(str, count, fmt, args);
2923 if (result > 0 && (size_t)result >= count) {
2924 result = -1;
2925 }
2927 return result;
2928 }
2930 ATTRIBUTE_PRINTF(3, 0)
2931 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
2932 va_list args;
2933 int len;
2934 va_start(args, fmt);
2935 len = jio_vsnprintf(str, count, fmt, args);
2936 va_end(args);
2937 return len;
2938 }
2940 ATTRIBUTE_PRINTF(2,3)
2941 int jio_fprintf(FILE* f, const char *fmt, ...) {
2942 int len;
2943 va_list args;
2944 va_start(args, fmt);
2945 len = jio_vfprintf(f, fmt, args);
2946 va_end(args);
2947 return len;
2948 }
2950 ATTRIBUTE_PRINTF(2, 0)
2951 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
2952 if (Arguments::vfprintf_hook() != NULL) {
2953 return Arguments::vfprintf_hook()(f, fmt, args);
2954 } else {
2955 return vfprintf(f, fmt, args);
2956 }
2957 }
2959 ATTRIBUTE_PRINTF(1, 2)
2960 JNIEXPORT int jio_printf(const char *fmt, ...) {
2961 int len;
2962 va_list args;
2963 va_start(args, fmt);
2964 len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
2965 va_end(args);
2966 return len;
2967 }
2970 // HotSpot specific jio method
2971 void jio_print(const char* s) {
2972 // Try to make this function as atomic as possible.
2973 if (Arguments::vfprintf_hook() != NULL) {
2974 jio_fprintf(defaultStream::output_stream(), "%s", s);
2975 } else {
2976 // Make an unused local variable to avoid warning from gcc 4.x compiler.
2977 size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));
2978 }
2979 }
2981 } // Extern C
2983 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
2985 // In most of the JVM Thread support functions we need to be sure to lock the Threads_lock
2986 // to prevent the target thread from exiting after we have a pointer to the C++ Thread or
2987 // OSThread objects. The exception to this rule is when the target object is the thread
2988 // doing the operation, in which case we know that the thread won't exit until the
2989 // operation is done (all exits being voluntary). There are a few cases where it is
2990 // rather silly to do operations on yourself, like resuming yourself or asking whether
2991 // you are alive. While these can still happen, they are not subject to deadlocks if
2992 // the lock is held while the operation occurs (this is not the case for suspend, for
2993 // instance), and are very unlikely. Because IsAlive needs to be fast and its
2994 // implementation is local to this file, we always lock Threads_lock for that one.
2996 static void thread_entry(JavaThread* thread, TRAPS) {
2997 HandleMark hm(THREAD);
2998 Handle obj(THREAD, thread->threadObj());
2999 JavaValue result(T_VOID);
3000 JavaCalls::call_virtual(&result,
3001 obj,
3002 KlassHandle(THREAD, SystemDictionary::Thread_klass()),
3003 vmSymbols::run_method_name(),
3004 vmSymbols::void_method_signature(),
3005 THREAD);
3006 }
3009 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
3010 JVMWrapper("JVM_StartThread");
3011 JavaThread *native_thread = NULL;
3013 // We cannot hold the Threads_lock when we throw an exception,
3014 // due to rank ordering issues. Example: we might need to grab the
3015 // Heap_lock while we construct the exception.
3016 bool throw_illegal_thread_state = false;
3018 // We must release the Threads_lock before we can post a jvmti event
3019 // in Thread::start.
3020 {
3021 // Ensure that the C++ Thread and OSThread structures aren't freed before
3022 // we operate.
3023 MutexLocker mu(Threads_lock);
3025 // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
3026 // re-starting an already started thread, so we should usually find
3027 // that the JavaThread is null. However for a JNI attached thread
3028 // there is a small window between the Thread object being created
3029 // (with its JavaThread set) and the update to its threadStatus, so we
3030 // have to check for this
3031 if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
3032 throw_illegal_thread_state = true;
3033 } else {
3034 // We could also check the stillborn flag to see if this thread was already stopped, but
3035 // for historical reasons we let the thread detect that itself when it starts running
3037 jlong size =
3038 java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
3039 // Allocate the C++ Thread structure and create the native thread. The
3040 // stack size retrieved from java is signed, but the constructor takes
3041 // size_t (an unsigned type), so avoid passing negative values which would
3042 // result in really large stacks.
3043 size_t sz = size > 0 ? (size_t) size : 0;
3044 native_thread = new JavaThread(&thread_entry, sz);
3046 // At this point it may be possible that no osthread was created for the
3047 // JavaThread due to lack of memory. Check for this situation and throw
3048 // an exception if necessary. Eventually we may want to change this so
3049 // that we only grab the lock if the thread was created successfully -
3050 // then we can also do this check and throw the exception in the
3051 // JavaThread constructor.
3052 if (native_thread->osthread() != NULL) {
3053 // Note: the current thread is not being used within "prepare".
3054 native_thread->prepare(jthread);
3055 }
3056 }
3057 }
3059 if (throw_illegal_thread_state) {
3060 THROW(vmSymbols::java_lang_IllegalThreadStateException());
3061 }
3063 assert(native_thread != NULL, "Starting null thread?");
3065 if (native_thread->osthread() == NULL) {
3066 // No one should hold a reference to the 'native_thread'.
3067 delete native_thread;
3068 if (JvmtiExport::should_post_resource_exhausted()) {
3069 JvmtiExport::post_resource_exhausted(
3070 JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
3071 "unable to create new native thread");
3072 }
3073 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
3074 "unable to create new native thread");
3075 }
3077 Thread::start(native_thread);
3079 JVM_END
3081 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
3082 // before the quasi-asynchronous exception is delivered. This is a little obtrusive,
3083 // but is thought to be reliable and simple. In the case, where the receiver is the
3084 // same thread as the sender, no safepoint is needed.
3085 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
3086 JVMWrapper("JVM_StopThread");
3088 oop java_throwable = JNIHandles::resolve(throwable);
3089 if (java_throwable == NULL) {
3090 THROW(vmSymbols::java_lang_NullPointerException());
3091 }
3092 oop java_thread = JNIHandles::resolve_non_null(jthread);
3093 JavaThread* receiver = java_lang_Thread::thread(java_thread);
3094 Events::log_exception(JavaThread::current(),
3095 "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
3096 p2i(receiver), p2i((address)java_thread), p2i(throwable));
3097 // First check if thread is alive
3098 if (receiver != NULL) {
3099 // Check if exception is getting thrown at self (use oop equality, since the
3100 // target object might exit)
3101 if (java_thread == thread->threadObj()) {
3102 THROW_OOP(java_throwable);
3103 } else {
3104 // Enques a VM_Operation to stop all threads and then deliver the exception...
3105 Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));
3106 }
3107 }
3108 else {
3109 // Either:
3110 // - target thread has not been started before being stopped, or
3111 // - target thread already terminated
3112 // We could read the threadStatus to determine which case it is
3113 // but that is overkill as it doesn't matter. We must set the
3114 // stillborn flag for the first case, and if the thread has already
3115 // exited setting this flag has no affect
3116 java_lang_Thread::set_stillborn(java_thread);
3117 }
3118 JVM_END
3121 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
3122 JVMWrapper("JVM_IsThreadAlive");
3124 oop thread_oop = JNIHandles::resolve_non_null(jthread);
3125 return java_lang_Thread::is_alive(thread_oop);
3126 JVM_END
3129 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
3130 JVMWrapper("JVM_SuspendThread");
3131 oop java_thread = JNIHandles::resolve_non_null(jthread);
3132 JavaThread* receiver = java_lang_Thread::thread(java_thread);
3134 if (receiver != NULL) {
3135 // thread has run and has not exited (still on threads list)
3137 {
3138 MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
3139 if (receiver->is_external_suspend()) {
3140 // Don't allow nested external suspend requests. We can't return
3141 // an error from this interface so just ignore the problem.
3142 return;
3143 }
3144 if (receiver->is_exiting()) { // thread is in the process of exiting
3145 return;
3146 }
3147 receiver->set_external_suspend();
3148 }
3150 // java_suspend() will catch threads in the process of exiting
3151 // and will ignore them.
3152 receiver->java_suspend();
3154 // It would be nice to have the following assertion in all the
3155 // time, but it is possible for a racing resume request to have
3156 // resumed this thread right after we suspended it. Temporarily
3157 // enable this assertion if you are chasing a different kind of
3158 // bug.
3159 //
3160 // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
3161 // receiver->is_being_ext_suspended(), "thread is not suspended");
3162 }
3163 JVM_END
3166 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
3167 JVMWrapper("JVM_ResumeThread");
3168 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
3169 // We need to *always* get the threads lock here, since this operation cannot be allowed during
3170 // a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
3171 // threads randomly resumes threads, then a thread might not be suspended when the safepoint code
3172 // looks at it.
3173 MutexLocker ml(Threads_lock);
3174 JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3175 if (thr != NULL) {
3176 // the thread has run and is not in the process of exiting
3177 thr->java_resume();
3178 }
3179 JVM_END
3182 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
3183 JVMWrapper("JVM_SetThreadPriority");
3184 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3185 MutexLocker ml(Threads_lock);
3186 oop java_thread = JNIHandles::resolve_non_null(jthread);
3187 java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
3188 JavaThread* thr = java_lang_Thread::thread(java_thread);
3189 if (thr != NULL) { // Thread not yet started; priority pushed down when it is
3190 Thread::set_priority(thr, (ThreadPriority)prio);
3191 }
3192 JVM_END
3195 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
3196 JVMWrapper("JVM_Yield");
3197 if (os::dont_yield()) return;
3198 #ifndef USDT2
3199 HS_DTRACE_PROBE0(hotspot, thread__yield);
3200 #else /* USDT2 */
3201 HOTSPOT_THREAD_YIELD();
3202 #endif /* USDT2 */
3203 // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
3204 // Critical for similar threading behaviour
3205 if (ConvertYieldToSleep) {
3206 os::sleep(thread, MinSleepInterval, false);
3207 } else {
3208 os::yield();
3209 }
3210 JVM_END
3213 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
3214 JVMWrapper("JVM_Sleep");
3216 if (millis < 0) {
3217 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
3218 }
3220 if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
3221 THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3222 }
3224 // Save current thread state and restore it at the end of this block.
3225 // And set new thread state to SLEEPING.
3226 JavaThreadSleepState jtss(thread);
3228 #ifndef USDT2
3229 HS_DTRACE_PROBE1(hotspot, thread__sleep__begin, millis);
3230 #else /* USDT2 */
3231 HOTSPOT_THREAD_SLEEP_BEGIN(
3232 millis);
3233 #endif /* USDT2 */
3235 EventThreadSleep event;
3237 if (millis == 0) {
3238 // When ConvertSleepToYield is on, this matches the classic VM implementation of
3239 // JVM_Sleep. Critical for similar threading behaviour (Win32)
3240 // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
3241 // for SOLARIS
3242 if (ConvertSleepToYield) {
3243 os::yield();
3244 } else {
3245 ThreadState old_state = thread->osthread()->get_state();
3246 thread->osthread()->set_state(SLEEPING);
3247 os::sleep(thread, MinSleepInterval, false);
3248 thread->osthread()->set_state(old_state);
3249 }
3250 } else {
3251 ThreadState old_state = thread->osthread()->get_state();
3252 thread->osthread()->set_state(SLEEPING);
3253 if (os::sleep(thread, millis, true) == OS_INTRPT) {
3254 // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
3255 // us while we were sleeping. We do not overwrite those.
3256 if (!HAS_PENDING_EXCEPTION) {
3257 if (event.should_commit()) {
3258 event.set_time(millis);
3259 event.commit();
3260 }
3261 #ifndef USDT2
3262 HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
3263 #else /* USDT2 */
3264 HOTSPOT_THREAD_SLEEP_END(
3265 1);
3266 #endif /* USDT2 */
3267 // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3268 // to properly restore the thread state. That's likely wrong.
3269 THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3270 }
3271 }
3272 thread->osthread()->set_state(old_state);
3273 }
3274 if (event.should_commit()) {
3275 event.set_time(millis);
3276 event.commit();
3277 }
3278 #ifndef USDT2
3279 HS_DTRACE_PROBE1(hotspot, thread__sleep__end,0);
3280 #else /* USDT2 */
3281 HOTSPOT_THREAD_SLEEP_END(
3282 0);
3283 #endif /* USDT2 */
3284 JVM_END
3286 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3287 JVMWrapper("JVM_CurrentThread");
3288 oop jthread = thread->threadObj();
3289 assert (thread != NULL, "no current thread!");
3290 return JNIHandles::make_local(env, jthread);
3291 JVM_END
3294 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
3295 JVMWrapper("JVM_CountStackFrames");
3297 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3298 oop java_thread = JNIHandles::resolve_non_null(jthread);
3299 bool throw_illegal_thread_state = false;
3300 int count = 0;
3302 {
3303 MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3304 // We need to re-resolve the java_thread, since a GC might have happened during the
3305 // acquire of the lock
3306 JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3308 if (thr == NULL) {
3309 // do nothing
3310 } else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {
3311 // Check whether this java thread has been suspended already. If not, throws
3312 // IllegalThreadStateException. We defer to throw that exception until
3313 // Threads_lock is released since loading exception class has to leave VM.
3314 // The correct way to test a thread is actually suspended is
3315 // wait_for_ext_suspend_completion(), but we can't call that while holding
3316 // the Threads_lock. The above tests are sufficient for our purposes
3317 // provided the walkability of the stack is stable - which it isn't
3318 // 100% but close enough for most practical purposes.
3319 throw_illegal_thread_state = true;
3320 } else {
3321 // Count all java activation, i.e., number of vframes
3322 for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {
3323 // Native frames are not counted
3324 if (!vfst.method()->is_native()) count++;
3325 }
3326 }
3327 }
3329 if (throw_illegal_thread_state) {
3330 THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
3331 "this thread is not suspended");
3332 }
3333 return count;
3334 JVM_END
3336 // Consider: A better way to implement JVM_Interrupt() is to acquire
3337 // Threads_lock to resolve the jthread into a Thread pointer, fetch
3338 // Thread->platformevent, Thread->native_thr, Thread->parker, etc.,
3339 // drop Threads_lock, and the perform the unpark() and thr_kill() operations
3340 // outside the critical section. Threads_lock is hot so we want to minimize
3341 // the hold-time. A cleaner interface would be to decompose interrupt into
3342 // two steps. The 1st phase, performed under Threads_lock, would return
3343 // a closure that'd be invoked after Threads_lock was dropped.
3344 // This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and
3345 // admit spurious wakeups.
3347 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3348 JVMWrapper("JVM_Interrupt");
3350 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3351 oop java_thread = JNIHandles::resolve_non_null(jthread);
3352 MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3353 // We need to re-resolve the java_thread, since a GC might have happened during the
3354 // acquire of the lock
3355 JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3356 if (thr != NULL) {
3357 Thread::interrupt(thr);
3358 }
3359 JVM_END
3362 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
3363 JVMWrapper("JVM_IsInterrupted");
3365 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3366 oop java_thread = JNIHandles::resolve_non_null(jthread);
3367 MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3368 // We need to re-resolve the java_thread, since a GC might have happened during the
3369 // acquire of the lock
3370 JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3371 if (thr == NULL) {
3372 return JNI_FALSE;
3373 } else {
3374 return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);
3375 }
3376 JVM_END
3379 // Return true iff the current thread has locked the object passed in
3381 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3382 JVMWrapper("JVM_HoldsLock");
3383 assert(THREAD->is_Java_thread(), "sanity check");
3384 if (obj == NULL) {
3385 THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3386 }
3387 Handle h_obj(THREAD, JNIHandles::resolve(obj));
3388 return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3389 JVM_END
3392 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3393 JVMWrapper("JVM_DumpAllStacks");
3394 VM_PrintThreads op;
3395 VMThread::execute(&op);
3396 if (JvmtiExport::should_post_data_dump()) {
3397 JvmtiExport::post_data_dump();
3398 }
3399 JVM_END
3401 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3402 JVMWrapper("JVM_SetNativeThreadName");
3403 ResourceMark rm(THREAD);
3404 oop java_thread = JNIHandles::resolve_non_null(jthread);
3405 JavaThread* thr = java_lang_Thread::thread(java_thread);
3406 // Thread naming only supported for the current thread, doesn't work for
3407 // target threads.
3408 if (Thread::current() == thr && !thr->has_attached_via_jni()) {
3409 // we don't set the name of an attached thread to avoid stepping
3410 // on other programs
3411 const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3412 os::set_native_thread_name(thread_name);
3413 }
3414 JVM_END
3416 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3418 static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {
3419 assert(jthread->is_Java_thread(), "must be a Java thread");
3420 if (jthread->privileged_stack_top() == NULL) return false;
3421 if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {
3422 oop loader = jthread->privileged_stack_top()->class_loader();
3423 if (loader == NULL) return true;
3424 bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
3425 if (trusted) return true;
3426 }
3427 return false;
3428 }
3430 JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))
3431 JVMWrapper("JVM_CurrentLoadedClass");
3432 ResourceMark rm(THREAD);
3434 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3435 // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3436 bool trusted = is_trusted_frame(thread, &vfst);
3437 if (trusted) return NULL;
3439 Method* m = vfst.method();
3440 if (!m->is_native()) {
3441 InstanceKlass* holder = m->method_holder();
3442 oop loader = holder->class_loader();
3443 if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3444 return (jclass) JNIHandles::make_local(env, holder->java_mirror());
3445 }
3446 }
3447 }
3448 return NULL;
3449 JVM_END
3452 JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))
3453 JVMWrapper("JVM_CurrentClassLoader");
3454 ResourceMark rm(THREAD);
3456 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3458 // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3459 bool trusted = is_trusted_frame(thread, &vfst);
3460 if (trusted) return NULL;
3462 Method* m = vfst.method();
3463 if (!m->is_native()) {
3464 InstanceKlass* holder = m->method_holder();
3465 assert(holder->is_klass(), "just checking");
3466 oop loader = holder->class_loader();
3467 if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3468 return JNIHandles::make_local(env, loader);
3469 }
3470 }
3471 }
3472 return NULL;
3473 JVM_END
3476 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3477 JVMWrapper("JVM_GetClassContext");
3478 ResourceMark rm(THREAD);
3479 JvmtiVMObjectAllocEventCollector oam;
3480 vframeStream vfst(thread);
3482 if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3483 // This must only be called from SecurityManager.getClassContext
3484 Method* m = vfst.method();
3485 if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3486 m->name() == vmSymbols::getClassContext_name() &&
3487 m->signature() == vmSymbols::void_class_array_signature())) {
3488 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3489 }
3490 }
3492 // Collect method holders
3493 GrowableArray<KlassHandle>* klass_array = new GrowableArray<KlassHandle>();
3494 for (; !vfst.at_end(); vfst.security_next()) {
3495 Method* m = vfst.method();
3496 // Native frames are not returned
3497 if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3498 Klass* holder = m->method_holder();
3499 assert(holder->is_klass(), "just checking");
3500 klass_array->append(holder);
3501 }
3502 }
3504 // Create result array of type [Ljava/lang/Class;
3505 objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3506 // Fill in mirrors corresponding to method holders
3507 for (int i = 0; i < klass_array->length(); i++) {
3508 result->obj_at_put(i, klass_array->at(i)->java_mirror());
3509 }
3511 return (jobjectArray) JNIHandles::make_local(env, result);
3512 JVM_END
3515 JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))
3516 JVMWrapper("JVM_ClassDepth");
3517 ResourceMark rm(THREAD);
3518 Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
3519 Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);
3521 const char* str = java_lang_String::as_utf8_string(class_name_str());
3522 TempNewSymbol class_name_sym = SymbolTable::probe(str, (int)strlen(str));
3523 if (class_name_sym == NULL) {
3524 return -1;
3525 }
3527 int depth = 0;
3529 for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3530 if (!vfst.method()->is_native()) {
3531 InstanceKlass* holder = vfst.method()->method_holder();
3532 assert(holder->is_klass(), "just checking");
3533 if (holder->name() == class_name_sym) {
3534 return depth;
3535 }
3536 depth++;
3537 }
3538 }
3539 return -1;
3540 JVM_END
3543 JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))
3544 JVMWrapper("JVM_ClassLoaderDepth");
3545 ResourceMark rm(THREAD);
3546 int depth = 0;
3547 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3548 // if a method in a class in a trusted loader is in a doPrivileged, return -1
3549 bool trusted = is_trusted_frame(thread, &vfst);
3550 if (trusted) return -1;
3552 Method* m = vfst.method();
3553 if (!m->is_native()) {
3554 InstanceKlass* holder = m->method_holder();
3555 assert(holder->is_klass(), "just checking");
3556 oop loader = holder->class_loader();
3557 if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3558 return depth;
3559 }
3560 depth++;
3561 }
3562 }
3563 return -1;
3564 JVM_END
3567 // java.lang.Package ////////////////////////////////////////////////////////////////
3570 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3571 JVMWrapper("JVM_GetSystemPackage");
3572 ResourceMark rm(THREAD);
3573 JvmtiVMObjectAllocEventCollector oam;
3574 char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3575 oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3576 return (jstring) JNIHandles::make_local(result);
3577 JVM_END
3580 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3581 JVMWrapper("JVM_GetSystemPackages");
3582 JvmtiVMObjectAllocEventCollector oam;
3583 objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3584 return (jobjectArray) JNIHandles::make_local(result);
3585 JVM_END
3588 // ObjectInputStream ///////////////////////////////////////////////////////////////
3590 bool force_verify_field_access(Klass* current_class, Klass* field_class, AccessFlags access, bool classloader_only) {
3591 if (current_class == NULL) {
3592 return true;
3593 }
3594 if ((current_class == field_class) || access.is_public()) {
3595 return true;
3596 }
3598 if (access.is_protected()) {
3599 // See if current_class is a subclass of field_class
3600 if (current_class->is_subclass_of(field_class)) {
3601 return true;
3602 }
3603 }
3605 return (!access.is_private() && InstanceKlass::cast(current_class)->is_same_class_package(field_class));
3606 }
3609 // JVM_AllocateNewObject and JVM_AllocateNewArray are unused as of 1.4
3610 JVM_ENTRY(jobject, JVM_AllocateNewObject(JNIEnv *env, jobject receiver, jclass currClass, jclass initClass))
3611 JVMWrapper("JVM_AllocateNewObject");
3612 JvmtiVMObjectAllocEventCollector oam;
3613 // Receiver is not used
3614 oop curr_mirror = JNIHandles::resolve_non_null(currClass);
3615 oop init_mirror = JNIHandles::resolve_non_null(initClass);
3617 // Cannot instantiate primitive types
3618 if (java_lang_Class::is_primitive(curr_mirror) || java_lang_Class::is_primitive(init_mirror)) {
3619 ResourceMark rm(THREAD);
3620 THROW_0(vmSymbols::java_lang_InvalidClassException());
3621 }
3623 // Arrays not allowed here, must use JVM_AllocateNewArray
3624 if (java_lang_Class::as_Klass(curr_mirror)->oop_is_array() ||
3625 java_lang_Class::as_Klass(init_mirror)->oop_is_array()) {
3626 ResourceMark rm(THREAD);
3627 THROW_0(vmSymbols::java_lang_InvalidClassException());
3628 }
3630 instanceKlassHandle curr_klass (THREAD, java_lang_Class::as_Klass(curr_mirror));
3631 instanceKlassHandle init_klass (THREAD, java_lang_Class::as_Klass(init_mirror));
3633 assert(curr_klass->is_subclass_of(init_klass()), "just checking");
3635 // Interfaces, abstract classes, and java.lang.Class classes cannot be instantiated directly.
3636 curr_klass->check_valid_for_instantiation(false, CHECK_NULL);
3638 // Make sure klass is initialized, since we are about to instantiate one of them.
3639 curr_klass->initialize(CHECK_NULL);
3641 methodHandle m (THREAD,
3642 init_klass->find_method(vmSymbols::object_initializer_name(),
3643 vmSymbols::void_method_signature()));
3644 if (m.is_null()) {
3645 ResourceMark rm(THREAD);
3646 THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(),
3647 Method::name_and_sig_as_C_string(init_klass(),
3648 vmSymbols::object_initializer_name(),
3649 vmSymbols::void_method_signature()));
3650 }
3652 if (curr_klass == init_klass && !m->is_public()) {
3653 // Calling the constructor for class 'curr_klass'.
3654 // Only allow calls to a public no-arg constructor.
3655 // This path corresponds to creating an Externalizable object.
3656 THROW_0(vmSymbols::java_lang_IllegalAccessException());
3657 }
3659 if (!force_verify_field_access(curr_klass(), init_klass(), m->access_flags(), false)) {
3660 // subclass 'curr_klass' does not have access to no-arg constructor of 'initcb'
3661 THROW_0(vmSymbols::java_lang_IllegalAccessException());
3662 }
3664 Handle obj = curr_klass->allocate_instance_handle(CHECK_NULL);
3665 // Call constructor m. This might call a constructor higher up in the hierachy
3666 JavaCalls::call_default_constructor(thread, m, obj, CHECK_NULL);
3668 return JNIHandles::make_local(obj());
3669 JVM_END
3672 JVM_ENTRY(jobject, JVM_AllocateNewArray(JNIEnv *env, jobject obj, jclass currClass, jint length))
3673 JVMWrapper("JVM_AllocateNewArray");
3674 JvmtiVMObjectAllocEventCollector oam;
3675 oop mirror = JNIHandles::resolve_non_null(currClass);
3677 if (java_lang_Class::is_primitive(mirror)) {
3678 THROW_0(vmSymbols::java_lang_InvalidClassException());
3679 }
3680 Klass* k = java_lang_Class::as_Klass(mirror);
3681 oop result;
3683 if (k->oop_is_typeArray()) {
3684 // typeArray
3685 result = TypeArrayKlass::cast(k)->allocate(length, CHECK_NULL);
3686 } else if (k->oop_is_objArray()) {
3687 // objArray
3688 ObjArrayKlass* oak = ObjArrayKlass::cast(k);
3689 oak->initialize(CHECK_NULL); // make sure class is initialized (matches Classic VM behavior)
3690 result = oak->allocate(length, CHECK_NULL);
3691 } else {
3692 THROW_0(vmSymbols::java_lang_InvalidClassException());
3693 }
3694 return JNIHandles::make_local(env, result);
3695 JVM_END
3698 // Returns first non-privileged class loader on the stack (excluding reflection
3699 // generated frames) or null if only classes loaded by the boot class loader
3700 // and extension class loader are found on the stack.
3702 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3703 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3704 // UseNewReflection
3705 vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3706 oop loader = vfst.method()->method_holder()->class_loader();
3707 if (loader != NULL && !SystemDictionary::is_ext_class_loader(loader)) {
3708 return JNIHandles::make_local(env, loader);
3709 }
3710 }
3711 return NULL;
3712 JVM_END
3715 // Load a class relative to the most recent class on the stack with a non-null
3716 // classloader.
3717 // This function has been deprecated and should not be considered part of the
3718 // specified JVM interface.
3720 JVM_ENTRY(jclass, JVM_LoadClass0(JNIEnv *env, jobject receiver,
3721 jclass currClass, jstring currClassName))
3722 JVMWrapper("JVM_LoadClass0");
3723 // Receiver is not used
3724 ResourceMark rm(THREAD);
3726 // Class name argument is not guaranteed to be in internal format
3727 Handle classname (THREAD, JNIHandles::resolve_non_null(currClassName));
3728 Handle string = java_lang_String::internalize_classname(classname, CHECK_NULL);
3730 const char* str = java_lang_String::as_utf8_string(string());
3732 if (str == NULL || (int)strlen(str) > Symbol::max_length()) {
3733 // It's impossible to create this class; the name cannot fit
3734 // into the constant pool.
3735 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), str);
3736 }
3738 TempNewSymbol name = SymbolTable::new_symbol(str, CHECK_NULL);
3739 Handle curr_klass (THREAD, JNIHandles::resolve(currClass));
3740 // Find the most recent class on the stack with a non-null classloader
3741 oop loader = NULL;
3742 oop protection_domain = NULL;
3743 if (curr_klass.is_null()) {
3744 for (vframeStream vfst(thread);
3745 !vfst.at_end() && loader == NULL;
3746 vfst.next()) {
3747 if (!vfst.method()->is_native()) {
3748 InstanceKlass* holder = vfst.method()->method_holder();
3749 loader = holder->class_loader();
3750 protection_domain = holder->protection_domain();
3751 }
3752 }
3753 } else {
3754 Klass* curr_klass_oop = java_lang_Class::as_Klass(curr_klass());
3755 loader = InstanceKlass::cast(curr_klass_oop)->class_loader();
3756 protection_domain = InstanceKlass::cast(curr_klass_oop)->protection_domain();
3757 }
3758 Handle h_loader(THREAD, loader);
3759 Handle h_prot (THREAD, protection_domain);
3760 jclass result = find_class_from_class_loader(env, name, true, h_loader, h_prot,
3761 false, thread);
3762 if (TraceClassResolution && result != NULL) {
3763 trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
3764 }
3765 return result;
3766 JVM_END
3769 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3772 // resolve array handle and check arguments
3773 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3774 if (arr == NULL) {
3775 THROW_0(vmSymbols::java_lang_NullPointerException());
3776 }
3777 oop a = JNIHandles::resolve_non_null(arr);
3778 if (!a->is_array() || (type_array_only && !a->is_typeArray())) {
3779 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3780 }
3781 return arrayOop(a);
3782 }
3785 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3786 JVMWrapper("JVM_GetArrayLength");
3787 arrayOop a = check_array(env, arr, false, CHECK_0);
3788 return a->length();
3789 JVM_END
3792 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3793 JVMWrapper("JVM_Array_Get");
3794 JvmtiVMObjectAllocEventCollector oam;
3795 arrayOop a = check_array(env, arr, false, CHECK_NULL);
3796 jvalue value;
3797 BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3798 oop box = Reflection::box(&value, type, CHECK_NULL);
3799 return JNIHandles::make_local(env, box);
3800 JVM_END
3803 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3804 JVMWrapper("JVM_GetPrimitiveArrayElement");
3805 jvalue value;
3806 value.i = 0; // to initialize value before getting used in CHECK
3807 arrayOop a = check_array(env, arr, true, CHECK_(value));
3808 assert(a->is_typeArray(), "just checking");
3809 BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3810 BasicType wide_type = (BasicType) wCode;
3811 if (type != wide_type) {
3812 Reflection::widen(&value, type, wide_type, CHECK_(value));
3813 }
3814 return value;
3815 JVM_END
3818 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3819 JVMWrapper("JVM_SetArrayElement");
3820 arrayOop a = check_array(env, arr, false, CHECK);
3821 oop box = JNIHandles::resolve(val);
3822 jvalue value;
3823 value.i = 0; // to initialize value before getting used in CHECK
3824 BasicType value_type;
3825 if (a->is_objArray()) {
3826 // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3827 value_type = Reflection::unbox_for_regular_object(box, &value);
3828 } else {
3829 value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3830 }
3831 Reflection::array_set(&value, a, index, value_type, CHECK);
3832 JVM_END
3835 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3836 JVMWrapper("JVM_SetPrimitiveArrayElement");
3837 arrayOop a = check_array(env, arr, true, CHECK);
3838 assert(a->is_typeArray(), "just checking");
3839 BasicType value_type = (BasicType) vCode;
3840 Reflection::array_set(&v, a, index, value_type, CHECK);
3841 JVM_END
3844 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3845 JVMWrapper("JVM_NewArray");
3846 JvmtiVMObjectAllocEventCollector oam;
3847 oop element_mirror = JNIHandles::resolve(eltClass);
3848 oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3849 return JNIHandles::make_local(env, result);
3850 JVM_END
3853 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3854 JVMWrapper("JVM_NewMultiArray");
3855 JvmtiVMObjectAllocEventCollector oam;
3856 arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3857 oop element_mirror = JNIHandles::resolve(eltClass);
3858 assert(dim_array->is_typeArray(), "just checking");
3859 oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3860 return JNIHandles::make_local(env, result);
3861 JVM_END
3864 // Networking library support ////////////////////////////////////////////////////////////////////
3866 JVM_LEAF(jint, JVM_InitializeSocketLibrary())
3867 JVMWrapper("JVM_InitializeSocketLibrary");
3868 return 0;
3869 JVM_END
3872 JVM_LEAF(jint, JVM_Socket(jint domain, jint type, jint protocol))
3873 JVMWrapper("JVM_Socket");
3874 return os::socket(domain, type, protocol);
3875 JVM_END
3878 JVM_LEAF(jint, JVM_SocketClose(jint fd))
3879 JVMWrapper2("JVM_SocketClose (0x%x)", fd);
3880 //%note jvm_r6
3881 return os::socket_close(fd);
3882 JVM_END
3885 JVM_LEAF(jint, JVM_SocketShutdown(jint fd, jint howto))
3886 JVMWrapper2("JVM_SocketShutdown (0x%x)", fd);
3887 //%note jvm_r6
3888 return os::socket_shutdown(fd, howto);
3889 JVM_END
3892 JVM_LEAF(jint, JVM_Recv(jint fd, char *buf, jint nBytes, jint flags))
3893 JVMWrapper2("JVM_Recv (0x%x)", fd);
3894 //%note jvm_r6
3895 return os::recv(fd, buf, (size_t)nBytes, (uint)flags);
3896 JVM_END
3899 JVM_LEAF(jint, JVM_Send(jint fd, char *buf, jint nBytes, jint flags))
3900 JVMWrapper2("JVM_Send (0x%x)", fd);
3901 //%note jvm_r6
3902 return os::send(fd, buf, (size_t)nBytes, (uint)flags);
3903 JVM_END
3906 JVM_LEAF(jint, JVM_Timeout(int fd, long timeout))
3907 JVMWrapper2("JVM_Timeout (0x%x)", fd);
3908 //%note jvm_r6
3909 return os::timeout(fd, timeout);
3910 JVM_END
3913 JVM_LEAF(jint, JVM_Listen(jint fd, jint count))
3914 JVMWrapper2("JVM_Listen (0x%x)", fd);
3915 //%note jvm_r6
3916 return os::listen(fd, count);
3917 JVM_END
3920 JVM_LEAF(jint, JVM_Connect(jint fd, struct sockaddr *him, jint len))
3921 JVMWrapper2("JVM_Connect (0x%x)", fd);
3922 //%note jvm_r6
3923 return os::connect(fd, him, (socklen_t)len);
3924 JVM_END
3927 JVM_LEAF(jint, JVM_Bind(jint fd, struct sockaddr *him, jint len))
3928 JVMWrapper2("JVM_Bind (0x%x)", fd);
3929 //%note jvm_r6
3930 return os::bind(fd, him, (socklen_t)len);
3931 JVM_END
3934 JVM_LEAF(jint, JVM_Accept(jint fd, struct sockaddr *him, jint *len))
3935 JVMWrapper2("JVM_Accept (0x%x)", fd);
3936 //%note jvm_r6
3937 socklen_t socklen = (socklen_t)(*len);
3938 jint result = os::accept(fd, him, &socklen);
3939 *len = (jint)socklen;
3940 return result;
3941 JVM_END
3944 JVM_LEAF(jint, JVM_RecvFrom(jint fd, char *buf, int nBytes, int flags, struct sockaddr *from, int *fromlen))
3945 JVMWrapper2("JVM_RecvFrom (0x%x)", fd);
3946 //%note jvm_r6
3947 socklen_t socklen = (socklen_t)(*fromlen);
3948 jint result = os::recvfrom(fd, buf, (size_t)nBytes, (uint)flags, from, &socklen);
3949 *fromlen = (int)socklen;
3950 return result;
3951 JVM_END
3954 JVM_LEAF(jint, JVM_GetSockName(jint fd, struct sockaddr *him, int *len))
3955 JVMWrapper2("JVM_GetSockName (0x%x)", fd);
3956 //%note jvm_r6
3957 socklen_t socklen = (socklen_t)(*len);
3958 jint result = os::get_sock_name(fd, him, &socklen);
3959 *len = (int)socklen;
3960 return result;
3961 JVM_END
3964 JVM_LEAF(jint, JVM_SendTo(jint fd, char *buf, int len, int flags, struct sockaddr *to, int tolen))
3965 JVMWrapper2("JVM_SendTo (0x%x)", fd);
3966 //%note jvm_r6
3967 return os::sendto(fd, buf, (size_t)len, (uint)flags, to, (socklen_t)tolen);
3968 JVM_END
3971 JVM_LEAF(jint, JVM_SocketAvailable(jint fd, jint *pbytes))
3972 JVMWrapper2("JVM_SocketAvailable (0x%x)", fd);
3973 //%note jvm_r6
3974 return os::socket_available(fd, pbytes);
3975 JVM_END
3978 JVM_LEAF(jint, JVM_GetSockOpt(jint fd, int level, int optname, char *optval, int *optlen))
3979 JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
3980 //%note jvm_r6
3981 socklen_t socklen = (socklen_t)(*optlen);
3982 jint result = os::get_sock_opt(fd, level, optname, optval, &socklen);
3983 *optlen = (int)socklen;
3984 return result;
3985 JVM_END
3988 JVM_LEAF(jint, JVM_SetSockOpt(jint fd, int level, int optname, const char *optval, int optlen))
3989 JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
3990 //%note jvm_r6
3991 return os::set_sock_opt(fd, level, optname, optval, (socklen_t)optlen);
3992 JVM_END
3995 JVM_LEAF(int, JVM_GetHostName(char* name, int namelen))
3996 JVMWrapper("JVM_GetHostName");
3997 return os::get_host_name(name, namelen);
3998 JVM_END
4001 // Library support ///////////////////////////////////////////////////////////////////////////
4003 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
4004 //%note jvm_ct
4005 JVMWrapper2("JVM_LoadLibrary (%s)", name);
4006 char ebuf[1024];
4007 void *load_result;
4008 {
4009 ThreadToNativeFromVM ttnfvm(thread);
4010 load_result = os::dll_load(name, ebuf, sizeof ebuf);
4011 }
4012 if (load_result == NULL) {
4013 char msg[1024];
4014 jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
4015 // Since 'ebuf' may contain a string encoded using
4016 // platform encoding scheme, we need to pass
4017 // Exceptions::unsafe_to_utf8 to the new_exception method
4018 // as the last argument. See bug 6367357.
4019 Handle h_exception =
4020 Exceptions::new_exception(thread,
4021 vmSymbols::java_lang_UnsatisfiedLinkError(),
4022 msg, Exceptions::unsafe_to_utf8);
4024 THROW_HANDLE_0(h_exception);
4025 }
4026 return load_result;
4027 JVM_END
4030 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
4031 JVMWrapper("JVM_UnloadLibrary");
4032 os::dll_unload(handle);
4033 JVM_END
4036 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
4037 JVMWrapper2("JVM_FindLibraryEntry (%s)", name);
4038 return os::dll_lookup(handle, name);
4039 JVM_END
4042 // Floating point support ////////////////////////////////////////////////////////////////////
4044 JVM_LEAF(jboolean, JVM_IsNaN(jdouble a))
4045 JVMWrapper("JVM_IsNaN");
4046 return g_isnan(a);
4047 JVM_END
4050 // JNI version ///////////////////////////////////////////////////////////////////////////////
4052 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
4053 JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);
4054 return Threads::is_supported_jni_version_including_1_1(version);
4055 JVM_END
4058 // String support ///////////////////////////////////////////////////////////////////////////
4060 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
4061 JVMWrapper("JVM_InternString");
4062 JvmtiVMObjectAllocEventCollector oam;
4063 if (str == NULL) return NULL;
4064 oop string = JNIHandles::resolve_non_null(str);
4065 oop result = StringTable::intern(string, CHECK_NULL);
4066 return (jstring) JNIHandles::make_local(env, result);
4067 JVM_END
4070 // Raw monitor support //////////////////////////////////////////////////////////////////////
4072 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
4073 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
4074 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
4075 // that only works with java threads.
4078 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
4079 VM_Exit::block_if_vm_exited();
4080 JVMWrapper("JVM_RawMonitorCreate");
4081 return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
4082 }
4085 JNIEXPORT void JNICALL JVM_RawMonitorDestroy(void *mon) {
4086 VM_Exit::block_if_vm_exited();
4087 JVMWrapper("JVM_RawMonitorDestroy");
4088 delete ((Mutex*) mon);
4089 }
4092 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
4093 VM_Exit::block_if_vm_exited();
4094 JVMWrapper("JVM_RawMonitorEnter");
4095 ((Mutex*) mon)->jvm_raw_lock();
4096 return 0;
4097 }
4100 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
4101 VM_Exit::block_if_vm_exited();
4102 JVMWrapper("JVM_RawMonitorExit");
4103 ((Mutex*) mon)->jvm_raw_unlock();
4104 }
4107 // Support for Serialization
4109 typedef jfloat (JNICALL *IntBitsToFloatFn )(JNIEnv* env, jclass cb, jint value);
4110 typedef jdouble (JNICALL *LongBitsToDoubleFn)(JNIEnv* env, jclass cb, jlong value);
4111 typedef jint (JNICALL *FloatToIntBitsFn )(JNIEnv* env, jclass cb, jfloat value);
4112 typedef jlong (JNICALL *DoubleToLongBitsFn)(JNIEnv* env, jclass cb, jdouble value);
4114 static IntBitsToFloatFn int_bits_to_float_fn = NULL;
4115 static LongBitsToDoubleFn long_bits_to_double_fn = NULL;
4116 static FloatToIntBitsFn float_to_int_bits_fn = NULL;
4117 static DoubleToLongBitsFn double_to_long_bits_fn = NULL;
4120 void initialize_converter_functions() {
4121 if (JDK_Version::is_gte_jdk14x_version()) {
4122 // These functions only exist for compatibility with 1.3.1 and earlier
4123 return;
4124 }
4126 // called from universe_post_init()
4127 assert(
4128 int_bits_to_float_fn == NULL &&
4129 long_bits_to_double_fn == NULL &&
4130 float_to_int_bits_fn == NULL &&
4131 double_to_long_bits_fn == NULL ,
4132 "initialization done twice"
4133 );
4134 // initialize
4135 int_bits_to_float_fn = CAST_TO_FN_PTR(IntBitsToFloatFn , NativeLookup::base_library_lookup("java/lang/Float" , "intBitsToFloat" , "(I)F"));
4136 long_bits_to_double_fn = CAST_TO_FN_PTR(LongBitsToDoubleFn, NativeLookup::base_library_lookup("java/lang/Double", "longBitsToDouble", "(J)D"));
4137 float_to_int_bits_fn = CAST_TO_FN_PTR(FloatToIntBitsFn , NativeLookup::base_library_lookup("java/lang/Float" , "floatToIntBits" , "(F)I"));
4138 double_to_long_bits_fn = CAST_TO_FN_PTR(DoubleToLongBitsFn, NativeLookup::base_library_lookup("java/lang/Double", "doubleToLongBits", "(D)J"));
4139 // verify
4140 assert(
4141 int_bits_to_float_fn != NULL &&
4142 long_bits_to_double_fn != NULL &&
4143 float_to_int_bits_fn != NULL &&
4144 double_to_long_bits_fn != NULL ,
4145 "initialization failed"
4146 );
4147 }
4151 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
4153 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
4154 Handle loader, Handle protection_domain,
4155 jboolean throwError, TRAPS) {
4156 // Security Note:
4157 // The Java level wrapper will perform the necessary security check allowing
4158 // us to pass the NULL as the initiating class loader. The VM is responsible for
4159 // the checkPackageAccess relative to the initiating class loader via the
4160 // protection_domain. The protection_domain is passed as NULL by the java code
4161 // if there is no security manager in 3-arg Class.forName().
4162 Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
4164 KlassHandle klass_handle(THREAD, klass);
4165 // Check if we should initialize the class
4166 if (init && klass_handle->oop_is_instance()) {
4167 klass_handle->initialize(CHECK_NULL);
4168 }
4169 return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());
4170 }
4173 // Internal SQE debugging support ///////////////////////////////////////////////////////////
4175 #ifndef PRODUCT
4177 extern "C" {
4178 JNIEXPORT jboolean JNICALL JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get);
4179 JNIEXPORT jboolean JNICALL JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get);
4180 JNIEXPORT void JNICALL JVM_VMBreakPoint(JNIEnv *env, jobject obj);
4181 }
4183 JVM_LEAF(jboolean, JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get))
4184 JVMWrapper("JVM_AccessBoolVMFlag");
4185 return is_get ? CommandLineFlags::boolAt((char*) name, (bool*) value) : CommandLineFlags::boolAtPut((char*) name, (bool*) value, Flag::INTERNAL);
4186 JVM_END
4188 JVM_LEAF(jboolean, JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get))
4189 JVMWrapper("JVM_AccessVMIntFlag");
4190 intx v;
4191 jboolean result = is_get ? CommandLineFlags::intxAt((char*) name, &v) : CommandLineFlags::intxAtPut((char*) name, &v, Flag::INTERNAL);
4192 *value = (jint)v;
4193 return result;
4194 JVM_END
4197 JVM_ENTRY(void, JVM_VMBreakPoint(JNIEnv *env, jobject obj))
4198 JVMWrapper("JVM_VMBreakPoint");
4199 oop the_obj = JNIHandles::resolve(obj);
4200 BREAKPOINT;
4201 JVM_END
4204 #endif
4207 // Method ///////////////////////////////////////////////////////////////////////////////////////////
4209 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
4210 JVMWrapper("JVM_InvokeMethod");
4211 Handle method_handle;
4212 if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
4213 method_handle = Handle(THREAD, JNIHandles::resolve(method));
4214 Handle receiver(THREAD, JNIHandles::resolve(obj));
4215 objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4216 oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
4217 jobject res = JNIHandles::make_local(env, result);
4218 if (JvmtiExport::should_post_vm_object_alloc()) {
4219 oop ret_type = java_lang_reflect_Method::return_type(method_handle());
4220 assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
4221 if (java_lang_Class::is_primitive(ret_type)) {
4222 // Only for primitive type vm allocates memory for java object.
4223 // See box() method.
4224 JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4225 }
4226 }
4227 return res;
4228 } else {
4229 THROW_0(vmSymbols::java_lang_StackOverflowError());
4230 }
4231 JVM_END
4234 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
4235 JVMWrapper("JVM_NewInstanceFromConstructor");
4236 oop constructor_mirror = JNIHandles::resolve(c);
4237 objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4238 oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
4239 jobject res = JNIHandles::make_local(env, result);
4240 if (JvmtiExport::should_post_vm_object_alloc()) {
4241 JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4242 }
4243 return res;
4244 JVM_END
4246 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
4248 JVM_LEAF(jboolean, JVM_SupportsCX8())
4249 JVMWrapper("JVM_SupportsCX8");
4250 return VM_Version::supports_cx8();
4251 JVM_END
4254 JVM_ENTRY(jboolean, JVM_CX8Field(JNIEnv *env, jobject obj, jfieldID fid, jlong oldVal, jlong newVal))
4255 JVMWrapper("JVM_CX8Field");
4256 jlong res;
4257 oop o = JNIHandles::resolve(obj);
4258 intptr_t fldOffs = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
4259 volatile jlong* addr = (volatile jlong*)((address)o + fldOffs);
4261 assert(VM_Version::supports_cx8(), "cx8 not supported");
4262 res = Atomic::cmpxchg(newVal, addr, oldVal);
4264 return res == oldVal;
4265 JVM_END
4267 // DTrace ///////////////////////////////////////////////////////////////////
4269 JVM_ENTRY(jint, JVM_DTraceGetVersion(JNIEnv* env))
4270 JVMWrapper("JVM_DTraceGetVersion");
4271 return (jint)JVM_TRACING_DTRACE_VERSION;
4272 JVM_END
4274 JVM_ENTRY(jlong,JVM_DTraceActivate(
4275 JNIEnv* env, jint version, jstring module_name, jint providers_count,
4276 JVM_DTraceProvider* providers))
4277 JVMWrapper("JVM_DTraceActivate");
4278 return DTraceJSDT::activate(
4279 version, module_name, providers_count, providers, CHECK_0);
4280 JVM_END
4282 JVM_ENTRY(jboolean,JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method))
4283 JVMWrapper("JVM_DTraceIsProbeEnabled");
4284 return DTraceJSDT::is_probe_enabled(method);
4285 JVM_END
4287 JVM_ENTRY(void,JVM_DTraceDispose(JNIEnv* env, jlong handle))
4288 JVMWrapper("JVM_DTraceDispose");
4289 DTraceJSDT::dispose(handle);
4290 JVM_END
4292 JVM_ENTRY(jboolean,JVM_DTraceIsSupported(JNIEnv* env))
4293 JVMWrapper("JVM_DTraceIsSupported");
4294 return DTraceJSDT::is_supported();
4295 JVM_END
4297 // Returns an array of all live Thread objects (VM internal JavaThreads,
4298 // jvmti agent threads, and JNI attaching threads are skipped)
4299 // See CR 6404306 regarding JNI attaching threads
4300 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
4301 ResourceMark rm(THREAD);
4302 ThreadsListEnumerator tle(THREAD, false, false);
4303 JvmtiVMObjectAllocEventCollector oam;
4305 int num_threads = tle.num_threads();
4306 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
4307 objArrayHandle threads_ah(THREAD, r);
4309 for (int i = 0; i < num_threads; i++) {
4310 Handle h = tle.get_threadObj(i);
4311 threads_ah->obj_at_put(i, h());
4312 }
4314 return (jobjectArray) JNIHandles::make_local(env, threads_ah());
4315 JVM_END
4318 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
4319 // Return StackTraceElement[][], each element is the stack trace of a thread in
4320 // the corresponding entry in the given threads array
4321 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
4322 JVMWrapper("JVM_DumpThreads");
4323 JvmtiVMObjectAllocEventCollector oam;
4325 // Check if threads is null
4326 if (threads == NULL) {
4327 THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4328 }
4330 objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
4331 objArrayHandle ah(THREAD, a);
4332 int num_threads = ah->length();
4333 // check if threads is non-empty array
4334 if (num_threads == 0) {
4335 THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4336 }
4338 // check if threads is not an array of objects of Thread class
4339 Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
4340 if (k != SystemDictionary::Thread_klass()) {
4341 THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4342 }
4344 ResourceMark rm(THREAD);
4346 GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
4347 for (int i = 0; i < num_threads; i++) {
4348 oop thread_obj = ah->obj_at(i);
4349 instanceHandle h(THREAD, (instanceOop) thread_obj);
4350 thread_handle_array->append(h);
4351 }
4353 Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
4354 return (jobjectArray)JNIHandles::make_local(env, stacktraces());
4356 JVM_END
4358 // JVM monitoring and management support
4359 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
4360 return Management::get_jmm_interface(version);
4361 JVM_END
4363 // com.sun.tools.attach.VirtualMachine agent properties support
4364 //
4365 // Initialize the agent properties with the properties maintained in the VM
4366 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
4367 JVMWrapper("JVM_InitAgentProperties");
4368 ResourceMark rm;
4370 Handle props(THREAD, JNIHandles::resolve_non_null(properties));
4372 PUTPROP(props, "sun.java.command", Arguments::java_command());
4373 PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
4374 PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
4375 return properties;
4376 JVM_END
4378 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
4379 {
4380 JVMWrapper("JVM_GetEnclosingMethodInfo");
4381 JvmtiVMObjectAllocEventCollector oam;
4383 if (ofClass == NULL) {
4384 return NULL;
4385 }
4386 Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
4387 // Special handling for primitive objects
4388 if (java_lang_Class::is_primitive(mirror())) {
4389 return NULL;
4390 }
4391 Klass* k = java_lang_Class::as_Klass(mirror());
4392 if (!k->oop_is_instance()) {
4393 return NULL;
4394 }
4395 instanceKlassHandle ik_h(THREAD, k);
4396 int encl_method_class_idx = ik_h->enclosing_method_class_index();
4397 if (encl_method_class_idx == 0) {
4398 return NULL;
4399 }
4400 objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
4401 objArrayHandle dest(THREAD, dest_o);
4402 Klass* enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
4403 dest->obj_at_put(0, enc_k->java_mirror());
4404 int encl_method_method_idx = ik_h->enclosing_method_method_index();
4405 if (encl_method_method_idx != 0) {
4406 Symbol* sym = ik_h->constants()->symbol_at(
4407 extract_low_short_from_int(
4408 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4409 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4410 dest->obj_at_put(1, str());
4411 sym = ik_h->constants()->symbol_at(
4412 extract_high_short_from_int(
4413 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4414 str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4415 dest->obj_at_put(2, str());
4416 }
4417 return (jobjectArray) JNIHandles::make_local(dest());
4418 }
4419 JVM_END
4421 JVM_ENTRY(jintArray, JVM_GetThreadStateValues(JNIEnv* env,
4422 jint javaThreadState))
4423 {
4424 // If new thread states are added in future JDK and VM versions,
4425 // this should check if the JDK version is compatible with thread
4426 // states supported by the VM. Return NULL if not compatible.
4427 //
4428 // This function must map the VM java_lang_Thread::ThreadStatus
4429 // to the Java thread state that the JDK supports.
4430 //
4432 typeArrayHandle values_h;
4433 switch (javaThreadState) {
4434 case JAVA_THREAD_STATE_NEW : {
4435 typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4436 values_h = typeArrayHandle(THREAD, r);
4437 values_h->int_at_put(0, java_lang_Thread::NEW);
4438 break;
4439 }
4440 case JAVA_THREAD_STATE_RUNNABLE : {
4441 typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4442 values_h = typeArrayHandle(THREAD, r);
4443 values_h->int_at_put(0, java_lang_Thread::RUNNABLE);
4444 break;
4445 }
4446 case JAVA_THREAD_STATE_BLOCKED : {
4447 typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4448 values_h = typeArrayHandle(THREAD, r);
4449 values_h->int_at_put(0, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);
4450 break;
4451 }
4452 case JAVA_THREAD_STATE_WAITING : {
4453 typeArrayOop r = oopFactory::new_typeArray(T_INT, 2, CHECK_NULL);
4454 values_h = typeArrayHandle(THREAD, r);
4455 values_h->int_at_put(0, java_lang_Thread::IN_OBJECT_WAIT);
4456 values_h->int_at_put(1, java_lang_Thread::PARKED);
4457 break;
4458 }
4459 case JAVA_THREAD_STATE_TIMED_WAITING : {
4460 typeArrayOop r = oopFactory::new_typeArray(T_INT, 3, CHECK_NULL);
4461 values_h = typeArrayHandle(THREAD, r);
4462 values_h->int_at_put(0, java_lang_Thread::SLEEPING);
4463 values_h->int_at_put(1, java_lang_Thread::IN_OBJECT_WAIT_TIMED);
4464 values_h->int_at_put(2, java_lang_Thread::PARKED_TIMED);
4465 break;
4466 }
4467 case JAVA_THREAD_STATE_TERMINATED : {
4468 typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4469 values_h = typeArrayHandle(THREAD, r);
4470 values_h->int_at_put(0, java_lang_Thread::TERMINATED);
4471 break;
4472 }
4473 default:
4474 // Unknown state - probably incompatible JDK version
4475 return NULL;
4476 }
4478 return (jintArray) JNIHandles::make_local(env, values_h());
4479 }
4480 JVM_END
4483 JVM_ENTRY(jobjectArray, JVM_GetThreadStateNames(JNIEnv* env,
4484 jint javaThreadState,
4485 jintArray values))
4486 {
4487 // If new thread states are added in future JDK and VM versions,
4488 // this should check if the JDK version is compatible with thread
4489 // states supported by the VM. Return NULL if not compatible.
4490 //
4491 // This function must map the VM java_lang_Thread::ThreadStatus
4492 // to the Java thread state that the JDK supports.
4493 //
4495 ResourceMark rm;
4497 // Check if threads is null
4498 if (values == NULL) {
4499 THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4500 }
4502 typeArrayOop v = typeArrayOop(JNIHandles::resolve_non_null(values));
4503 typeArrayHandle values_h(THREAD, v);
4505 objArrayHandle names_h;
4506 switch (javaThreadState) {
4507 case JAVA_THREAD_STATE_NEW : {
4508 assert(values_h->length() == 1 &&
4509 values_h->int_at(0) == java_lang_Thread::NEW,
4510 "Invalid threadStatus value");
4512 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4513 1, /* only 1 substate */
4514 CHECK_NULL);
4515 names_h = objArrayHandle(THREAD, r);
4516 Handle name = java_lang_String::create_from_str("NEW", CHECK_NULL);
4517 names_h->obj_at_put(0, name());
4518 break;
4519 }
4520 case JAVA_THREAD_STATE_RUNNABLE : {
4521 assert(values_h->length() == 1 &&
4522 values_h->int_at(0) == java_lang_Thread::RUNNABLE,
4523 "Invalid threadStatus value");
4525 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4526 1, /* only 1 substate */
4527 CHECK_NULL);
4528 names_h = objArrayHandle(THREAD, r);
4529 Handle name = java_lang_String::create_from_str("RUNNABLE", CHECK_NULL);
4530 names_h->obj_at_put(0, name());
4531 break;
4532 }
4533 case JAVA_THREAD_STATE_BLOCKED : {
4534 assert(values_h->length() == 1 &&
4535 values_h->int_at(0) == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER,
4536 "Invalid threadStatus value");
4538 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4539 1, /* only 1 substate */
4540 CHECK_NULL);
4541 names_h = objArrayHandle(THREAD, r);
4542 Handle name = java_lang_String::create_from_str("BLOCKED", CHECK_NULL);
4543 names_h->obj_at_put(0, name());
4544 break;
4545 }
4546 case JAVA_THREAD_STATE_WAITING : {
4547 assert(values_h->length() == 2 &&
4548 values_h->int_at(0) == java_lang_Thread::IN_OBJECT_WAIT &&
4549 values_h->int_at(1) == java_lang_Thread::PARKED,
4550 "Invalid threadStatus value");
4551 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4552 2, /* number of substates */
4553 CHECK_NULL);
4554 names_h = objArrayHandle(THREAD, r);
4555 Handle name0 = java_lang_String::create_from_str("WAITING.OBJECT_WAIT",
4556 CHECK_NULL);
4557 Handle name1 = java_lang_String::create_from_str("WAITING.PARKED",
4558 CHECK_NULL);
4559 names_h->obj_at_put(0, name0());
4560 names_h->obj_at_put(1, name1());
4561 break;
4562 }
4563 case JAVA_THREAD_STATE_TIMED_WAITING : {
4564 assert(values_h->length() == 3 &&
4565 values_h->int_at(0) == java_lang_Thread::SLEEPING &&
4566 values_h->int_at(1) == java_lang_Thread::IN_OBJECT_WAIT_TIMED &&
4567 values_h->int_at(2) == java_lang_Thread::PARKED_TIMED,
4568 "Invalid threadStatus value");
4569 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4570 3, /* number of substates */
4571 CHECK_NULL);
4572 names_h = objArrayHandle(THREAD, r);
4573 Handle name0 = java_lang_String::create_from_str("TIMED_WAITING.SLEEPING",
4574 CHECK_NULL);
4575 Handle name1 = java_lang_String::create_from_str("TIMED_WAITING.OBJECT_WAIT",
4576 CHECK_NULL);
4577 Handle name2 = java_lang_String::create_from_str("TIMED_WAITING.PARKED",
4578 CHECK_NULL);
4579 names_h->obj_at_put(0, name0());
4580 names_h->obj_at_put(1, name1());
4581 names_h->obj_at_put(2, name2());
4582 break;
4583 }
4584 case JAVA_THREAD_STATE_TERMINATED : {
4585 assert(values_h->length() == 1 &&
4586 values_h->int_at(0) == java_lang_Thread::TERMINATED,
4587 "Invalid threadStatus value");
4588 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4589 1, /* only 1 substate */
4590 CHECK_NULL);
4591 names_h = objArrayHandle(THREAD, r);
4592 Handle name = java_lang_String::create_from_str("TERMINATED", CHECK_NULL);
4593 names_h->obj_at_put(0, name());
4594 break;
4595 }
4596 default:
4597 // Unknown state - probably incompatible JDK version
4598 return NULL;
4599 }
4600 return (jobjectArray) JNIHandles::make_local(env, names_h());
4601 }
4602 JVM_END
4604 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
4605 {
4606 memset(info, 0, info_size);
4608 info->jvm_version = Abstract_VM_Version::jvm_version();
4609 info->update_version = 0; /* 0 in HotSpot Express VM */
4610 info->special_update_version = 0; /* 0 in HotSpot Express VM */
4612 // when we add a new capability in the jvm_version_info struct, we should also
4613 // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
4614 // counter defined in runtimeService.cpp.
4615 info->is_attachable = AttachListener::is_attach_supported();
4616 }
4617 JVM_END