Tue, 13 Feb 2018 15:48:23 +0100
8041626: Shutdown tracing event
Reviewed-by: dholmes, alanb, rriggs
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 "jfr/jfrEvents.hpp"
41 #include "memory/oopFactory.hpp"
42 #include "memory/referenceType.hpp"
43 #include "memory/universe.inline.hpp"
44 #include "oops/fieldStreams.hpp"
45 #include "oops/instanceKlass.hpp"
46 #include "oops/objArrayKlass.hpp"
47 #include "oops/method.hpp"
48 #include "prims/jvm.h"
49 #include "prims/jvm_misc.hpp"
50 #include "prims/jvmtiExport.hpp"
51 #include "prims/jvmtiThreadState.hpp"
52 #include "prims/nativeLookup.hpp"
53 #include "prims/privilegedStack.hpp"
54 #include "runtime/arguments.hpp"
55 #include "runtime/dtraceJSDT.hpp"
56 #include "runtime/handles.inline.hpp"
57 #include "runtime/init.hpp"
58 #include "runtime/interfaceSupport.hpp"
59 #include "runtime/java.hpp"
60 #include "runtime/javaCalls.hpp"
61 #include "runtime/jfieldIDWorkaround.hpp"
62 #include "runtime/orderAccess.inline.hpp"
63 #include "runtime/os.hpp"
64 #include "runtime/perfData.hpp"
65 #include "runtime/reflection.hpp"
66 #include "runtime/vframe.hpp"
67 #include "runtime/vm_operations.hpp"
68 #include "services/attachListener.hpp"
69 #include "services/management.hpp"
70 #include "services/threadService.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_BeforeHalt())
447 JVMWrapper("JVM_BeforeHalt");
448 EventShutdown event;
449 if (event.should_commit()) {
450 event.set_reason("Shutdown requested from Java");
451 event.commit();
452 }
453 JVM_END
456 JVM_ENTRY_NO_ENV(void, JVM_Halt(jint code))
457 before_exit(thread);
458 vm_exit(code);
459 JVM_END
462 JVM_LEAF(void, JVM_OnExit(void (*func)(void)))
463 register_on_exit_function(func);
464 JVM_END
467 JVM_ENTRY_NO_ENV(void, JVM_GC(void))
468 JVMWrapper("JVM_GC");
469 if (!DisableExplicitGC) {
470 Universe::heap()->collect(GCCause::_java_lang_system_gc);
471 }
472 JVM_END
475 JVM_LEAF(jlong, JVM_MaxObjectInspectionAge(void))
476 JVMWrapper("JVM_MaxObjectInspectionAge");
477 return Universe::heap()->millis_since_last_gc();
478 JVM_END
481 JVM_LEAF(void, JVM_TraceInstructions(jboolean on))
482 if (PrintJVMWarnings) warning("JVM_TraceInstructions not supported");
483 JVM_END
486 JVM_LEAF(void, JVM_TraceMethodCalls(jboolean on))
487 if (PrintJVMWarnings) warning("JVM_TraceMethodCalls not supported");
488 JVM_END
490 static inline jlong convert_size_t_to_jlong(size_t val) {
491 // In the 64-bit vm, a size_t can overflow a jlong (which is signed).
492 NOT_LP64 (return (jlong)val;)
493 LP64_ONLY(return (jlong)MIN2(val, (size_t)max_jlong);)
494 }
496 JVM_ENTRY_NO_ENV(jlong, JVM_TotalMemory(void))
497 JVMWrapper("JVM_TotalMemory");
498 size_t n = Universe::heap()->capacity();
499 return convert_size_t_to_jlong(n);
500 JVM_END
503 JVM_ENTRY_NO_ENV(jlong, JVM_FreeMemory(void))
504 JVMWrapper("JVM_FreeMemory");
505 CollectedHeap* ch = Universe::heap();
506 size_t n;
507 {
508 MutexLocker x(Heap_lock);
509 n = ch->capacity() - ch->used();
510 }
511 return convert_size_t_to_jlong(n);
512 JVM_END
515 JVM_ENTRY_NO_ENV(jlong, JVM_MaxMemory(void))
516 JVMWrapper("JVM_MaxMemory");
517 size_t n = Universe::heap()->max_capacity();
518 return convert_size_t_to_jlong(n);
519 JVM_END
522 JVM_ENTRY_NO_ENV(jint, JVM_ActiveProcessorCount(void))
523 JVMWrapper("JVM_ActiveProcessorCount");
524 return os::active_processor_count();
525 JVM_END
529 // java.lang.Throwable //////////////////////////////////////////////////////
532 JVM_ENTRY(void, JVM_FillInStackTrace(JNIEnv *env, jobject receiver))
533 JVMWrapper("JVM_FillInStackTrace");
534 Handle exception(thread, JNIHandles::resolve_non_null(receiver));
535 java_lang_Throwable::fill_in_stack_trace(exception);
536 JVM_END
539 JVM_ENTRY(jint, JVM_GetStackTraceDepth(JNIEnv *env, jobject throwable))
540 JVMWrapper("JVM_GetStackTraceDepth");
541 oop exception = JNIHandles::resolve(throwable);
542 return java_lang_Throwable::get_stack_trace_depth(exception, THREAD);
543 JVM_END
546 JVM_ENTRY(jobject, JVM_GetStackTraceElement(JNIEnv *env, jobject throwable, jint index))
547 JVMWrapper("JVM_GetStackTraceElement");
548 JvmtiVMObjectAllocEventCollector oam; // This ctor (throughout this module) may trigger a safepoint/GC
549 oop exception = JNIHandles::resolve(throwable);
550 oop element = java_lang_Throwable::get_stack_trace_element(exception, index, CHECK_NULL);
551 return JNIHandles::make_local(env, element);
552 JVM_END
555 // java.lang.Object ///////////////////////////////////////////////
558 JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
559 JVMWrapper("JVM_IHashCode");
560 // as implemented in the classic virtual machine; return 0 if object is NULL
561 return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
562 JVM_END
565 JVM_ENTRY(void, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
566 JVMWrapper("JVM_MonitorWait");
567 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
568 JavaThreadInObjectWaitState jtiows(thread, ms != 0);
569 if (JvmtiExport::should_post_monitor_wait()) {
570 JvmtiExport::post_monitor_wait((JavaThread *)THREAD, (oop)obj(), ms);
572 // The current thread already owns the monitor and it has not yet
573 // been added to the wait queue so the current thread cannot be
574 // made the successor. This means that the JVMTI_EVENT_MONITOR_WAIT
575 // event handler cannot accidentally consume an unpark() meant for
576 // the ParkEvent associated with this ObjectMonitor.
577 }
578 ObjectSynchronizer::wait(obj, ms, CHECK);
579 JVM_END
582 JVM_ENTRY(void, JVM_MonitorNotify(JNIEnv* env, jobject handle))
583 JVMWrapper("JVM_MonitorNotify");
584 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
585 ObjectSynchronizer::notify(obj, CHECK);
586 JVM_END
589 JVM_ENTRY(void, JVM_MonitorNotifyAll(JNIEnv* env, jobject handle))
590 JVMWrapper("JVM_MonitorNotifyAll");
591 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
592 ObjectSynchronizer::notifyall(obj, CHECK);
593 JVM_END
596 static void fixup_cloned_reference(ReferenceType ref_type, oop src, oop clone) {
597 // If G1 is enabled then we need to register a non-null referent
598 // with the SATB barrier.
599 #if INCLUDE_ALL_GCS
600 if (UseG1GC) {
601 oop referent = java_lang_ref_Reference::referent(clone);
602 if (referent != NULL) {
603 G1SATBCardTableModRefBS::enqueue(referent);
604 }
605 }
606 #endif // INCLUDE_ALL_GCS
607 if ((java_lang_ref_Reference::next(clone) != NULL) ||
608 (java_lang_ref_Reference::queue(clone) == java_lang_ref_ReferenceQueue::ENQUEUED_queue())) {
609 // If the source has been enqueued or is being enqueued, don't
610 // register the clone with a queue.
611 java_lang_ref_Reference::set_queue(clone, java_lang_ref_ReferenceQueue::NULL_queue());
612 }
613 // discovered and next are list links; the clone is not in those lists.
614 java_lang_ref_Reference::set_discovered(clone, NULL);
615 java_lang_ref_Reference::set_next(clone, NULL);
616 }
618 JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
619 JVMWrapper("JVM_Clone");
620 Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
621 const KlassHandle klass (THREAD, obj->klass());
622 JvmtiVMObjectAllocEventCollector oam;
624 #ifdef ASSERT
625 // Just checking that the cloneable flag is set correct
626 if (obj->is_array()) {
627 guarantee(klass->is_cloneable(), "all arrays are cloneable");
628 } else {
629 guarantee(obj->is_instance(), "should be instanceOop");
630 bool cloneable = klass->is_subtype_of(SystemDictionary::Cloneable_klass());
631 guarantee(cloneable == klass->is_cloneable(), "incorrect cloneable flag");
632 }
633 #endif
635 // Check if class of obj supports the Cloneable interface.
636 // All arrays are considered to be cloneable (See JLS 20.1.5)
637 if (!klass->is_cloneable()) {
638 ResourceMark rm(THREAD);
639 THROW_MSG_0(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());
640 }
642 // Make shallow object copy
643 ReferenceType ref_type = REF_NONE;
644 const int size = obj->size();
645 oop new_obj_oop = NULL;
646 if (obj->is_array()) {
647 const int length = ((arrayOop)obj())->length();
648 new_obj_oop = CollectedHeap::array_allocate(klass, size, length, CHECK_NULL);
649 } else {
650 ref_type = InstanceKlass::cast(klass())->reference_type();
651 assert((ref_type == REF_NONE) ==
652 !klass->is_subclass_of(SystemDictionary::Reference_klass()),
653 "invariant");
654 new_obj_oop = CollectedHeap::obj_allocate(klass, size, CHECK_NULL);
655 }
657 // 4839641 (4840070): We must do an oop-atomic copy, because if another thread
658 // is modifying a reference field in the clonee, a non-oop-atomic copy might
659 // be suspended in the middle of copying the pointer and end up with parts
660 // of two different pointers in the field. Subsequent dereferences will crash.
661 // 4846409: an oop-copy of objects with long or double fields or arrays of same
662 // won't copy the longs/doubles atomically in 32-bit vm's, so we copy jlongs instead
663 // of oops. We know objects are aligned on a minimum of an jlong boundary.
664 // The same is true of StubRoutines::object_copy and the various oop_copy
665 // variants, and of the code generated by the inline_native_clone intrinsic.
666 assert(MinObjAlignmentInBytes >= BytesPerLong, "objects misaligned");
667 Copy::conjoint_jlongs_atomic((jlong*)obj(), (jlong*)new_obj_oop,
668 (size_t)align_object_size(size) / HeapWordsPerLong);
669 // Clear the header
670 new_obj_oop->init_mark();
672 // Store check (mark entire object and let gc sort it out)
673 BarrierSet* bs = Universe::heap()->barrier_set();
674 assert(bs->has_write_region_opt(), "Barrier set does not have write_region");
675 bs->write_region(MemRegion((HeapWord*)new_obj_oop, size));
677 // If cloning a Reference, set Reference fields to a safe state.
678 // Fixup must be completed before any safepoint.
679 if (ref_type != REF_NONE) {
680 fixup_cloned_reference(ref_type, obj(), new_obj_oop);
681 }
683 Handle new_obj(THREAD, new_obj_oop);
684 // Special handling for MemberNames. Since they contain Method* metadata, they
685 // must be registered so that RedefineClasses can fix metadata contained in them.
686 if (java_lang_invoke_MemberName::is_instance(new_obj()) &&
687 java_lang_invoke_MemberName::is_method(new_obj())) {
688 Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(new_obj());
689 // MemberName may be unresolved, so doesn't need registration until resolved.
690 if (method != NULL) {
691 methodHandle m(THREAD, method);
692 // This can safepoint and redefine method, so need both new_obj and method
693 // in a handle, for two different reasons. new_obj can move, method can be
694 // deleted if nothing is using it on the stack.
695 m->method_holder()->add_member_name(new_obj(), false);
696 }
697 }
699 // Caution: this involves a java upcall, so the clone should be
700 // "gc-robust" by this stage.
701 if (klass->has_finalizer()) {
702 assert(obj->is_instance(), "should be instanceOop");
703 new_obj_oop = InstanceKlass::register_finalizer(instanceOop(new_obj()), CHECK_NULL);
704 new_obj = Handle(THREAD, new_obj_oop);
705 }
707 return JNIHandles::make_local(env, new_obj());
708 JVM_END
710 // java.lang.Compiler ////////////////////////////////////////////////////
712 // The initial cuts of the HotSpot VM will not support JITs, and all existing
713 // JITs would need extensive changes to work with HotSpot. The JIT-related JVM
714 // functions are all silently ignored unless JVM warnings are printed.
716 JVM_LEAF(void, JVM_InitializeCompiler (JNIEnv *env, jclass compCls))
717 if (PrintJVMWarnings) warning("JVM_InitializeCompiler not supported");
718 JVM_END
721 JVM_LEAF(jboolean, JVM_IsSilentCompiler(JNIEnv *env, jclass compCls))
722 if (PrintJVMWarnings) warning("JVM_IsSilentCompiler not supported");
723 return JNI_FALSE;
724 JVM_END
727 JVM_LEAF(jboolean, JVM_CompileClass(JNIEnv *env, jclass compCls, jclass cls))
728 if (PrintJVMWarnings) warning("JVM_CompileClass not supported");
729 return JNI_FALSE;
730 JVM_END
733 JVM_LEAF(jboolean, JVM_CompileClasses(JNIEnv *env, jclass cls, jstring jname))
734 if (PrintJVMWarnings) warning("JVM_CompileClasses not supported");
735 return JNI_FALSE;
736 JVM_END
739 JVM_LEAF(jobject, JVM_CompilerCommand(JNIEnv *env, jclass compCls, jobject arg))
740 if (PrintJVMWarnings) warning("JVM_CompilerCommand not supported");
741 return NULL;
742 JVM_END
745 JVM_LEAF(void, JVM_EnableCompiler(JNIEnv *env, jclass compCls))
746 if (PrintJVMWarnings) warning("JVM_EnableCompiler not supported");
747 JVM_END
750 JVM_LEAF(void, JVM_DisableCompiler(JNIEnv *env, jclass compCls))
751 if (PrintJVMWarnings) warning("JVM_DisableCompiler not supported");
752 JVM_END
756 // Error message support //////////////////////////////////////////////////////
758 JVM_LEAF(jint, JVM_GetLastErrorString(char *buf, int len))
759 JVMWrapper("JVM_GetLastErrorString");
760 return (jint)os::lasterror(buf, len);
761 JVM_END
764 // java.io.File ///////////////////////////////////////////////////////////////
766 JVM_LEAF(char*, JVM_NativePath(char* path))
767 JVMWrapper2("JVM_NativePath (%s)", path);
768 return os::native_path(path);
769 JVM_END
772 // java.nio.Bits ///////////////////////////////////////////////////////////////
774 #define MAX_OBJECT_SIZE \
775 ( arrayOopDesc::header_size(T_DOUBLE) * HeapWordSize \
776 + ((julong)max_jint * sizeof(double)) )
778 static inline jlong field_offset_to_byte_offset(jlong field_offset) {
779 return field_offset;
780 }
782 static inline void assert_field_offset_sane(oop p, jlong field_offset) {
783 #ifdef ASSERT
784 jlong byte_offset = field_offset_to_byte_offset(field_offset);
786 if (p != NULL) {
787 assert(byte_offset >= 0 && byte_offset <= (jlong)MAX_OBJECT_SIZE, "sane offset");
788 if (byte_offset == (jint)byte_offset) {
789 void* ptr_plus_disp = (address)p + byte_offset;
790 assert((void*)p->obj_field_addr<oop>((jint)byte_offset) == ptr_plus_disp,
791 "raw [ptr+disp] must be consistent with oop::field_base");
792 }
793 jlong p_size = HeapWordSize * (jlong)(p->size());
794 assert(byte_offset < p_size, err_msg("Unsafe access: offset " INT64_FORMAT
795 " > object's size " INT64_FORMAT,
796 (int64_t)byte_offset, (int64_t)p_size));
797 }
798 #endif
799 }
801 static inline void* index_oop_from_field_offset_long(oop p, jlong field_offset) {
802 assert_field_offset_sane(p, field_offset);
803 jlong byte_offset = field_offset_to_byte_offset(field_offset);
805 if (sizeof(char*) == sizeof(jint)) { // (this constant folds!)
806 return (address)p + (jint) byte_offset;
807 } else {
808 return (address)p + byte_offset;
809 }
810 }
812 // This function is a leaf since if the source and destination are both in native memory
813 // the copy may potentially be very large, and we don't want to disable GC if we can avoid it.
814 // If either source or destination (or both) are on the heap, the function will enter VM using
815 // JVM_ENTRY_FROM_LEAF
816 JVM_LEAF(void, JVM_CopySwapMemory(JNIEnv *env, jobject srcObj, jlong srcOffset,
817 jobject dstObj, jlong dstOffset, jlong size,
818 jlong elemSize)) {
820 size_t sz = (size_t)size;
821 size_t esz = (size_t)elemSize;
823 if (srcObj == NULL && dstObj == NULL) {
824 // Both src & dst are in native memory
825 address src = (address)srcOffset;
826 address dst = (address)dstOffset;
828 Copy::conjoint_swap(src, dst, sz, esz);
829 } else {
830 // At least one of src/dst are on heap, transition to VM to access raw pointers
832 JVM_ENTRY_FROM_LEAF(env, void, JVM_CopySwapMemory) {
833 oop srcp = JNIHandles::resolve(srcObj);
834 oop dstp = JNIHandles::resolve(dstObj);
836 address src = (address)index_oop_from_field_offset_long(srcp, srcOffset);
837 address dst = (address)index_oop_from_field_offset_long(dstp, dstOffset);
839 Copy::conjoint_swap(src, dst, sz, esz);
840 } JVM_END
841 }
842 } JVM_END
845 // Misc. class handling ///////////////////////////////////////////////////////////
848 JVM_ENTRY(jclass, JVM_GetCallerClass(JNIEnv* env, int depth))
849 JVMWrapper("JVM_GetCallerClass");
851 // Pre-JDK 8 and early builds of JDK 8 don't have a CallerSensitive annotation; or
852 // sun.reflect.Reflection.getCallerClass with a depth parameter is provided
853 // temporarily for existing code to use until a replacement API is defined.
854 if (SystemDictionary::reflect_CallerSensitive_klass() == NULL || depth != JVM_CALLER_DEPTH) {
855 Klass* k = thread->security_get_caller_class(depth);
856 return (k == NULL) ? NULL : (jclass) JNIHandles::make_local(env, k->java_mirror());
857 }
859 // Getting the class of the caller frame.
860 //
861 // The call stack at this point looks something like this:
862 //
863 // [0] [ @CallerSensitive public sun.reflect.Reflection.getCallerClass ]
864 // [1] [ @CallerSensitive API.method ]
865 // [.] [ (skipped intermediate frames) ]
866 // [n] [ caller ]
867 vframeStream vfst(thread);
868 // Cf. LibraryCallKit::inline_native_Reflection_getCallerClass
869 for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {
870 Method* m = vfst.method();
871 assert(m != NULL, "sanity");
872 switch (n) {
873 case 0:
874 // This must only be called from Reflection.getCallerClass
875 if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {
876 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");
877 }
878 // fall-through
879 case 1:
880 // Frame 0 and 1 must be caller sensitive.
881 if (!m->caller_sensitive()) {
882 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));
883 }
884 break;
885 default:
886 if (!m->is_ignored_by_security_stack_walk()) {
887 // We have reached the desired frame; return the holder class.
888 return (jclass) JNIHandles::make_local(env, m->method_holder()->java_mirror());
889 }
890 break;
891 }
892 }
893 return NULL;
894 JVM_END
897 JVM_ENTRY(jclass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))
898 JVMWrapper("JVM_FindPrimitiveClass");
899 oop mirror = NULL;
900 BasicType t = name2type(utf);
901 if (t != T_ILLEGAL && t != T_OBJECT && t != T_ARRAY) {
902 mirror = Universe::java_mirror(t);
903 }
904 if (mirror == NULL) {
905 THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);
906 } else {
907 return (jclass) JNIHandles::make_local(env, mirror);
908 }
909 JVM_END
912 JVM_ENTRY(void, JVM_ResolveClass(JNIEnv* env, jclass cls))
913 JVMWrapper("JVM_ResolveClass");
914 if (PrintJVMWarnings) warning("JVM_ResolveClass not implemented");
915 JVM_END
918 JVM_ENTRY(jboolean, JVM_KnownToNotExist(JNIEnv *env, jobject loader, const char *classname))
919 JVMWrapper("JVM_KnownToNotExist");
920 #if INCLUDE_CDS
921 return ClassLoaderExt::known_to_not_exist(env, loader, classname, CHECK_(false));
922 #else
923 return false;
924 #endif
925 JVM_END
928 JVM_ENTRY(jobjectArray, JVM_GetResourceLookupCacheURLs(JNIEnv *env, jobject loader))
929 JVMWrapper("JVM_GetResourceLookupCacheURLs");
930 #if INCLUDE_CDS
931 return ClassLoaderExt::get_lookup_cache_urls(env, loader, CHECK_NULL);
932 #else
933 return NULL;
934 #endif
935 JVM_END
938 JVM_ENTRY(jintArray, JVM_GetResourceLookupCache(JNIEnv *env, jobject loader, const char *resource_name))
939 JVMWrapper("JVM_GetResourceLookupCache");
940 #if INCLUDE_CDS
941 return ClassLoaderExt::get_lookup_cache(env, loader, resource_name, CHECK_NULL);
942 #else
943 return NULL;
944 #endif
945 JVM_END
948 // Returns a class loaded by the bootstrap class loader; or null
949 // if not found. ClassNotFoundException is not thrown.
950 //
951 // Rationale behind JVM_FindClassFromBootLoader
952 // a> JVM_FindClassFromClassLoader was never exported in the export tables.
953 // b> because of (a) java.dll has a direct dependecy on the unexported
954 // private symbol "_JVM_FindClassFromClassLoader@20".
955 // c> the launcher cannot use the private symbol as it dynamically opens
956 // the entry point, so if something changes, the launcher will fail
957 // unexpectedly at runtime, it is safest for the launcher to dlopen a
958 // stable exported interface.
959 // d> re-exporting JVM_FindClassFromClassLoader as public, will cause its
960 // signature to change from _JVM_FindClassFromClassLoader@20 to
961 // JVM_FindClassFromClassLoader and will not be backward compatible
962 // with older JDKs.
963 // Thus a public/stable exported entry point is the right solution,
964 // public here means public in linker semantics, and is exported only
965 // to the JDK, and is not intended to be a public API.
967 JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,
968 const char* name))
969 JVMWrapper2("JVM_FindClassFromBootLoader %s", name);
971 // Java libraries should ensure that name is never null...
972 if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
973 // It's impossible to create this class; the name cannot fit
974 // into the constant pool.
975 return NULL;
976 }
978 TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
979 Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
980 if (k == NULL) {
981 return NULL;
982 }
984 if (TraceClassResolution) {
985 trace_class_resolution(k);
986 }
987 return (jclass) JNIHandles::make_local(env, k->java_mirror());
988 JVM_END
990 // Not used; JVM_FindClassFromCaller replaces this.
991 JVM_ENTRY(jclass, JVM_FindClassFromClassLoader(JNIEnv* env, const char* name,
992 jboolean init, jobject loader,
993 jboolean throwError))
994 JVMWrapper3("JVM_FindClassFromClassLoader %s throw %s", name,
995 throwError ? "error" : "exception");
996 // Java libraries should ensure that name is never null...
997 if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
998 // It's impossible to create this class; the name cannot fit
999 // into the constant pool.
1000 if (throwError) {
1001 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
1002 } else {
1003 THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
1004 }
1005 }
1006 TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
1007 Handle h_loader(THREAD, JNIHandles::resolve(loader));
1008 jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
1009 Handle(), throwError, THREAD);
1011 if (TraceClassResolution && result != NULL) {
1012 trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
1013 }
1014 return result;
1015 JVM_END
1017 // Find a class with this name in this loader, using the caller's protection domain.
1018 JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
1019 jboolean init, jobject loader,
1020 jclass caller))
1021 JVMWrapper2("JVM_FindClassFromCaller %s throws ClassNotFoundException", name);
1022 // Java libraries should ensure that name is never null...
1023 if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
1024 // It's impossible to create this class; the name cannot fit
1025 // into the constant pool.
1026 THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
1027 }
1029 TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
1031 oop loader_oop = JNIHandles::resolve(loader);
1032 oop from_class = JNIHandles::resolve(caller);
1033 oop protection_domain = NULL;
1034 // If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
1035 // NPE. Put it in another way, the bootstrap class loader has all permission and
1036 // thus no checkPackageAccess equivalence in the VM class loader.
1037 // The caller is also passed as NULL by the java code if there is no security
1038 // manager to avoid the performance cost of getting the calling class.
1039 if (from_class != NULL && loader_oop != NULL) {
1040 protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
1041 }
1043 Handle h_loader(THREAD, loader_oop);
1044 Handle h_prot(THREAD, protection_domain);
1045 jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
1046 h_prot, false, THREAD);
1048 if (TraceClassResolution && result != NULL) {
1049 trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
1050 }
1051 return result;
1052 JVM_END
1054 JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
1055 jboolean init, jclass from))
1056 JVMWrapper2("JVM_FindClassFromClass %s", name);
1057 if (name == NULL || (int)strlen(name) > 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 TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
1063 oop from_class_oop = JNIHandles::resolve(from);
1064 Klass* from_class = (from_class_oop == NULL)
1065 ? (Klass*)NULL
1066 : java_lang_Class::as_Klass(from_class_oop);
1067 oop class_loader = NULL;
1068 oop protection_domain = NULL;
1069 if (from_class != NULL) {
1070 class_loader = from_class->class_loader();
1071 protection_domain = from_class->protection_domain();
1072 }
1073 Handle h_loader(THREAD, class_loader);
1074 Handle h_prot (THREAD, protection_domain);
1075 jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
1076 h_prot, true, thread);
1078 if (TraceClassResolution && result != NULL) {
1079 // this function is generally only used for class loading during verification.
1080 ResourceMark rm;
1081 oop from_mirror = JNIHandles::resolve_non_null(from);
1082 Klass* from_class = java_lang_Class::as_Klass(from_mirror);
1083 const char * from_name = from_class->external_name();
1085 oop mirror = JNIHandles::resolve_non_null(result);
1086 Klass* to_class = java_lang_Class::as_Klass(mirror);
1087 const char * to = to_class->external_name();
1088 tty->print("RESOLVE %s %s (verification)\n", from_name, to);
1089 }
1091 return result;
1092 JVM_END
1094 static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {
1095 if (loader.is_null()) {
1096 return;
1097 }
1099 // check whether the current caller thread holds the lock or not.
1100 // If not, increment the corresponding counter
1101 if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=
1102 ObjectSynchronizer::owner_self) {
1103 counter->inc();
1104 }
1105 }
1107 // common code for JVM_DefineClass() and JVM_DefineClassWithSource()
1108 // and JVM_DefineClassWithSourceCond()
1109 static jclass jvm_define_class_common(JNIEnv *env, const char *name,
1110 jobject loader, const jbyte *buf,
1111 jsize len, jobject pd, const char *source,
1112 jboolean verify, TRAPS) {
1113 if (source == NULL) source = "__JVM_DefineClass__";
1115 assert(THREAD->is_Java_thread(), "must be a JavaThread");
1116 JavaThread* jt = (JavaThread*) THREAD;
1118 PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
1119 ClassLoader::perf_define_appclass_selftime(),
1120 ClassLoader::perf_define_appclasses(),
1121 jt->get_thread_stat()->perf_recursion_counts_addr(),
1122 jt->get_thread_stat()->perf_timers_addr(),
1123 PerfClassTraceTime::DEFINE_CLASS);
1125 if (UsePerfData) {
1126 ClassLoader::perf_app_classfile_bytes_read()->inc(len);
1127 }
1129 // Since exceptions can be thrown, class initialization can take place
1130 // if name is NULL no check for class name in .class stream has to be made.
1131 TempNewSymbol class_name = NULL;
1132 if (name != NULL) {
1133 const int str_len = (int)strlen(name);
1134 if (str_len > Symbol::max_length()) {
1135 // It's impossible to create this class; the name cannot fit
1136 // into the constant pool.
1137 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
1138 }
1139 class_name = SymbolTable::new_symbol(name, str_len, CHECK_NULL);
1140 }
1142 ResourceMark rm(THREAD);
1143 ClassFileStream st((u1*) buf, len, (char *)source);
1144 Handle class_loader (THREAD, JNIHandles::resolve(loader));
1145 if (UsePerfData) {
1146 is_lock_held_by_thread(class_loader,
1147 ClassLoader::sync_JVMDefineClassLockFreeCounter(),
1148 THREAD);
1149 }
1150 Handle protection_domain (THREAD, JNIHandles::resolve(pd));
1151 Klass* k = SystemDictionary::resolve_from_stream(class_name, class_loader,
1152 protection_domain, &st,
1153 verify != 0,
1154 CHECK_NULL);
1156 if (TraceClassResolution && k != NULL) {
1157 trace_class_resolution(k);
1158 }
1160 return (jclass) JNIHandles::make_local(env, k->java_mirror());
1161 }
1164 JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
1165 JVMWrapper2("JVM_DefineClass %s", name);
1167 return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, true, THREAD);
1168 JVM_END
1171 JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
1172 JVMWrapper2("JVM_DefineClassWithSource %s", name);
1174 return jvm_define_class_common(env, name, loader, buf, len, pd, source, true, THREAD);
1175 JVM_END
1177 JVM_ENTRY(jclass, JVM_DefineClassWithSourceCond(JNIEnv *env, const char *name,
1178 jobject loader, const jbyte *buf,
1179 jsize len, jobject pd,
1180 const char *source, jboolean verify))
1181 JVMWrapper2("JVM_DefineClassWithSourceCond %s", name);
1183 return jvm_define_class_common(env, name, loader, buf, len, pd, source, verify, THREAD);
1184 JVM_END
1186 JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
1187 JVMWrapper("JVM_FindLoadedClass");
1188 ResourceMark rm(THREAD);
1190 Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
1191 Handle string = java_lang_String::internalize_classname(h_name, CHECK_NULL);
1193 const char* str = java_lang_String::as_utf8_string(string());
1194 // Sanity check, don't expect null
1195 if (str == NULL) return NULL;
1197 const int str_len = (int)strlen(str);
1198 if (str_len > Symbol::max_length()) {
1199 // It's impossible to create this class; the name cannot fit
1200 // into the constant pool.
1201 return NULL;
1202 }
1203 TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len, CHECK_NULL);
1205 // Security Note:
1206 // The Java level wrapper will perform the necessary security check allowing
1207 // us to pass the NULL as the initiating class loader.
1208 Handle h_loader(THREAD, JNIHandles::resolve(loader));
1209 if (UsePerfData) {
1210 is_lock_held_by_thread(h_loader,
1211 ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),
1212 THREAD);
1213 }
1215 Klass* k = SystemDictionary::find_instance_or_array_klass(klass_name,
1216 h_loader,
1217 Handle(),
1218 CHECK_NULL);
1219 #if INCLUDE_CDS
1220 if (k == NULL) {
1221 // If the class is not already loaded, try to see if it's in the shared
1222 // archive for the current classloader (h_loader).
1223 instanceKlassHandle ik = SystemDictionaryShared::find_or_load_shared_class(
1224 klass_name, h_loader, CHECK_NULL);
1225 k = ik();
1226 }
1227 #endif
1228 return (k == NULL) ? NULL :
1229 (jclass) JNIHandles::make_local(env, k->java_mirror());
1230 JVM_END
1233 // Reflection support //////////////////////////////////////////////////////////////////////////////
1235 JVM_ENTRY(jstring, JVM_GetClassName(JNIEnv *env, jclass cls))
1236 assert (cls != NULL, "illegal class");
1237 JVMWrapper("JVM_GetClassName");
1238 JvmtiVMObjectAllocEventCollector oam;
1239 ResourceMark rm(THREAD);
1240 const char* name;
1241 if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1242 name = type2name(java_lang_Class::primitive_type(JNIHandles::resolve(cls)));
1243 } else {
1244 // Consider caching interned string in Klass
1245 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1246 assert(k->is_klass(), "just checking");
1247 name = k->external_name();
1248 }
1249 oop result = StringTable::intern((char*) name, CHECK_NULL);
1250 return (jstring) JNIHandles::make_local(env, result);
1251 JVM_END
1254 JVM_ENTRY(jobjectArray, JVM_GetClassInterfaces(JNIEnv *env, jclass cls))
1255 JVMWrapper("JVM_GetClassInterfaces");
1256 JvmtiVMObjectAllocEventCollector oam;
1257 oop mirror = JNIHandles::resolve_non_null(cls);
1259 // Special handling for primitive objects
1260 if (java_lang_Class::is_primitive(mirror)) {
1261 // Primitive objects does not have any interfaces
1262 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1263 return (jobjectArray) JNIHandles::make_local(env, r);
1264 }
1266 KlassHandle klass(thread, java_lang_Class::as_Klass(mirror));
1267 // Figure size of result array
1268 int size;
1269 if (klass->oop_is_instance()) {
1270 size = InstanceKlass::cast(klass())->local_interfaces()->length();
1271 } else {
1272 assert(klass->oop_is_objArray() || klass->oop_is_typeArray(), "Illegal mirror klass");
1273 size = 2;
1274 }
1276 // Allocate result array
1277 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), size, CHECK_NULL);
1278 objArrayHandle result (THREAD, r);
1279 // Fill in result
1280 if (klass->oop_is_instance()) {
1281 // Regular instance klass, fill in all local interfaces
1282 for (int index = 0; index < size; index++) {
1283 Klass* k = InstanceKlass::cast(klass())->local_interfaces()->at(index);
1284 result->obj_at_put(index, k->java_mirror());
1285 }
1286 } else {
1287 // All arrays implement java.lang.Cloneable and java.io.Serializable
1288 result->obj_at_put(0, SystemDictionary::Cloneable_klass()->java_mirror());
1289 result->obj_at_put(1, SystemDictionary::Serializable_klass()->java_mirror());
1290 }
1291 return (jobjectArray) JNIHandles::make_local(env, result());
1292 JVM_END
1295 JVM_ENTRY(jobject, JVM_GetClassLoader(JNIEnv *env, jclass cls))
1296 JVMWrapper("JVM_GetClassLoader");
1297 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1298 return NULL;
1299 }
1300 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1301 oop loader = k->class_loader();
1302 return JNIHandles::make_local(env, loader);
1303 JVM_END
1306 JVM_QUICK_ENTRY(jboolean, JVM_IsInterface(JNIEnv *env, jclass cls))
1307 JVMWrapper("JVM_IsInterface");
1308 oop mirror = JNIHandles::resolve_non_null(cls);
1309 if (java_lang_Class::is_primitive(mirror)) {
1310 return JNI_FALSE;
1311 }
1312 Klass* k = java_lang_Class::as_Klass(mirror);
1313 jboolean result = k->is_interface();
1314 assert(!result || k->oop_is_instance(),
1315 "all interfaces are instance types");
1316 // The compiler intrinsic for isInterface tests the
1317 // Klass::_access_flags bits in the same way.
1318 return result;
1319 JVM_END
1322 JVM_ENTRY(jobjectArray, JVM_GetClassSigners(JNIEnv *env, jclass cls))
1323 JVMWrapper("JVM_GetClassSigners");
1324 JvmtiVMObjectAllocEventCollector oam;
1325 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1326 // There are no signers for primitive types
1327 return NULL;
1328 }
1330 objArrayOop signers = java_lang_Class::signers(JNIHandles::resolve_non_null(cls));
1332 // If there are no signers set in the class, or if the class
1333 // is an array, return NULL.
1334 if (signers == NULL) return NULL;
1336 // copy of the signers array
1337 Klass* element = ObjArrayKlass::cast(signers->klass())->element_klass();
1338 objArrayOop signers_copy = oopFactory::new_objArray(element, signers->length(), CHECK_NULL);
1339 for (int index = 0; index < signers->length(); index++) {
1340 signers_copy->obj_at_put(index, signers->obj_at(index));
1341 }
1343 // return the copy
1344 return (jobjectArray) JNIHandles::make_local(env, signers_copy);
1345 JVM_END
1348 JVM_ENTRY(void, JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers))
1349 JVMWrapper("JVM_SetClassSigners");
1350 if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1351 // This call is ignored for primitive types and arrays.
1352 // Signers are only set once, ClassLoader.java, and thus shouldn't
1353 // be called with an array. Only the bootstrap loader creates arrays.
1354 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1355 if (k->oop_is_instance()) {
1356 java_lang_Class::set_signers(k->java_mirror(), objArrayOop(JNIHandles::resolve(signers)));
1357 }
1358 }
1359 JVM_END
1362 JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls))
1363 JVMWrapper("JVM_GetProtectionDomain");
1364 if (JNIHandles::resolve(cls) == NULL) {
1365 THROW_(vmSymbols::java_lang_NullPointerException(), NULL);
1366 }
1368 if (java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1369 // Primitive types does not have a protection domain.
1370 return NULL;
1371 }
1373 oop pd = java_lang_Class::protection_domain(JNIHandles::resolve(cls));
1374 return (jobject) JNIHandles::make_local(env, pd);
1375 JVM_END
1378 static bool is_authorized(Handle context, instanceKlassHandle klass, TRAPS) {
1379 // If there is a security manager and protection domain, check the access
1380 // in the protection domain, otherwise it is authorized.
1381 if (java_lang_System::has_security_manager()) {
1383 // For bootstrapping, if pd implies method isn't in the JDK, allow
1384 // this context to revert to older behavior.
1385 // In this case the isAuthorized field in AccessControlContext is also not
1386 // present.
1387 if (Universe::protection_domain_implies_method() == NULL) {
1388 return true;
1389 }
1391 // Whitelist certain access control contexts
1392 if (java_security_AccessControlContext::is_authorized(context)) {
1393 return true;
1394 }
1396 oop prot = klass->protection_domain();
1397 if (prot != NULL) {
1398 // Call pd.implies(new SecurityPermission("createAccessControlContext"))
1399 // in the new wrapper.
1400 methodHandle m(THREAD, Universe::protection_domain_implies_method());
1401 Handle h_prot(THREAD, prot);
1402 JavaValue result(T_BOOLEAN);
1403 JavaCallArguments args(h_prot);
1404 JavaCalls::call(&result, m, &args, CHECK_false);
1405 return (result.get_jboolean() != 0);
1406 }
1407 }
1408 return true;
1409 }
1411 // Create an AccessControlContext with a protection domain with null codesource
1412 // and null permissions - which gives no permissions.
1413 oop create_dummy_access_control_context(TRAPS) {
1414 InstanceKlass* pd_klass = InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass());
1415 Handle obj = pd_klass->allocate_instance_handle(CHECK_NULL);
1416 // Call constructor ProtectionDomain(null, null);
1417 JavaValue result(T_VOID);
1418 JavaCalls::call_special(&result, obj, KlassHandle(THREAD, pd_klass),
1419 vmSymbols::object_initializer_name(),
1420 vmSymbols::codesource_permissioncollection_signature(),
1421 Handle(), Handle(), CHECK_NULL);
1423 // new ProtectionDomain[] {pd};
1424 objArrayOop context = oopFactory::new_objArray(pd_klass, 1, CHECK_NULL);
1425 context->obj_at_put(0, obj());
1427 // new AccessControlContext(new ProtectionDomain[] {pd})
1428 objArrayHandle h_context(THREAD, context);
1429 oop acc = java_security_AccessControlContext::create(h_context, false, Handle(), CHECK_NULL);
1430 return acc;
1431 }
1433 JVM_ENTRY(jobject, JVM_DoPrivileged(JNIEnv *env, jclass cls, jobject action, jobject context, jboolean wrapException))
1434 JVMWrapper("JVM_DoPrivileged");
1436 if (action == NULL) {
1437 THROW_MSG_0(vmSymbols::java_lang_NullPointerException(), "Null action");
1438 }
1440 // Compute the frame initiating the do privileged operation and setup the privileged stack
1441 vframeStream vfst(thread);
1442 vfst.security_get_caller_frame(1);
1444 if (vfst.at_end()) {
1445 THROW_MSG_0(vmSymbols::java_lang_InternalError(), "no caller?");
1446 }
1448 Method* method = vfst.method();
1449 instanceKlassHandle klass (THREAD, method->method_holder());
1451 // Check that action object understands "Object run()"
1452 Handle h_context;
1453 if (context != NULL) {
1454 h_context = Handle(THREAD, JNIHandles::resolve(context));
1455 bool authorized = is_authorized(h_context, klass, CHECK_NULL);
1456 if (!authorized) {
1457 // Create an unprivileged access control object and call it's run function
1458 // instead.
1459 oop noprivs = create_dummy_access_control_context(CHECK_NULL);
1460 h_context = Handle(THREAD, noprivs);
1461 }
1462 }
1464 // Check that action object understands "Object run()"
1465 Handle object (THREAD, JNIHandles::resolve(action));
1467 // get run() method
1468 Method* m_oop = object->klass()->uncached_lookup_method(
1469 vmSymbols::run_method_name(),
1470 vmSymbols::void_object_signature(),
1471 Klass::find_overpass);
1472 methodHandle m (THREAD, m_oop);
1473 if (m.is_null() || !m->is_method() || !m()->is_public() || m()->is_static()) {
1474 THROW_MSG_0(vmSymbols::java_lang_InternalError(), "No run method");
1475 }
1477 // Stack allocated list of privileged stack elements
1478 PrivilegedElement pi;
1479 if (!vfst.at_end()) {
1480 pi.initialize(&vfst, h_context(), thread->privileged_stack_top(), CHECK_NULL);
1481 thread->set_privileged_stack_top(&pi);
1482 }
1485 // invoke the Object run() in the action object. We cannot use call_interface here, since the static type
1486 // is not really known - it is either java.security.PrivilegedAction or java.security.PrivilegedExceptionAction
1487 Handle pending_exception;
1488 JavaValue result(T_OBJECT);
1489 JavaCallArguments args(object);
1490 JavaCalls::call(&result, m, &args, THREAD);
1492 // done with action, remove ourselves from the list
1493 if (!vfst.at_end()) {
1494 assert(thread->privileged_stack_top() != NULL && thread->privileged_stack_top() == &pi, "wrong top element");
1495 thread->set_privileged_stack_top(thread->privileged_stack_top()->next());
1496 }
1498 if (HAS_PENDING_EXCEPTION) {
1499 pending_exception = Handle(THREAD, PENDING_EXCEPTION);
1500 CLEAR_PENDING_EXCEPTION;
1501 // JVMTI has already reported the pending exception
1502 // JVMTI internal flag reset is needed in order to report PrivilegedActionException
1503 if (THREAD->is_Java_thread()) {
1504 JvmtiExport::clear_detected_exception((JavaThread*) THREAD);
1505 }
1506 if ( pending_exception->is_a(SystemDictionary::Exception_klass()) &&
1507 !pending_exception->is_a(SystemDictionary::RuntimeException_klass())) {
1508 // Throw a java.security.PrivilegedActionException(Exception e) exception
1509 JavaCallArguments args(pending_exception);
1510 THROW_ARG_0(vmSymbols::java_security_PrivilegedActionException(),
1511 vmSymbols::exception_void_signature(),
1512 &args);
1513 }
1514 }
1516 if (pending_exception.not_null()) THROW_OOP_0(pending_exception());
1517 return JNIHandles::make_local(env, (oop) result.get_jobject());
1518 JVM_END
1521 // Returns the inherited_access_control_context field of the running thread.
1522 JVM_ENTRY(jobject, JVM_GetInheritedAccessControlContext(JNIEnv *env, jclass cls))
1523 JVMWrapper("JVM_GetInheritedAccessControlContext");
1524 oop result = java_lang_Thread::inherited_access_control_context(thread->threadObj());
1525 return JNIHandles::make_local(env, result);
1526 JVM_END
1528 class RegisterArrayForGC {
1529 private:
1530 JavaThread *_thread;
1531 public:
1532 RegisterArrayForGC(JavaThread *thread, GrowableArray<oop>* array) {
1533 _thread = thread;
1534 _thread->register_array_for_gc(array);
1535 }
1537 ~RegisterArrayForGC() {
1538 _thread->register_array_for_gc(NULL);
1539 }
1540 };
1543 JVM_ENTRY(jobject, JVM_GetStackAccessControlContext(JNIEnv *env, jclass cls))
1544 JVMWrapper("JVM_GetStackAccessControlContext");
1545 if (!UsePrivilegedStack) return NULL;
1547 ResourceMark rm(THREAD);
1548 GrowableArray<oop>* local_array = new GrowableArray<oop>(12);
1549 JvmtiVMObjectAllocEventCollector oam;
1551 // count the protection domains on the execution stack. We collapse
1552 // duplicate consecutive protection domains into a single one, as
1553 // well as stopping when we hit a privileged frame.
1555 // Use vframeStream to iterate through Java frames
1556 vframeStream vfst(thread);
1558 oop previous_protection_domain = NULL;
1559 Handle privileged_context(thread, NULL);
1560 bool is_privileged = false;
1561 oop protection_domain = NULL;
1563 for(; !vfst.at_end(); vfst.next()) {
1564 // get method of frame
1565 Method* method = vfst.method();
1566 intptr_t* frame_id = vfst.frame_id();
1568 // check the privileged frames to see if we have a match
1569 if (thread->privileged_stack_top() && thread->privileged_stack_top()->frame_id() == frame_id) {
1570 // this frame is privileged
1571 is_privileged = true;
1572 privileged_context = Handle(thread, thread->privileged_stack_top()->privileged_context());
1573 protection_domain = thread->privileged_stack_top()->protection_domain();
1574 } else {
1575 protection_domain = method->method_holder()->protection_domain();
1576 }
1578 if ((previous_protection_domain != protection_domain) && (protection_domain != NULL)) {
1579 local_array->push(protection_domain);
1580 previous_protection_domain = protection_domain;
1581 }
1583 if (is_privileged) break;
1584 }
1587 // either all the domains on the stack were system domains, or
1588 // we had a privileged system domain
1589 if (local_array->is_empty()) {
1590 if (is_privileged && privileged_context.is_null()) return NULL;
1592 oop result = java_security_AccessControlContext::create(objArrayHandle(), is_privileged, privileged_context, CHECK_NULL);
1593 return JNIHandles::make_local(env, result);
1594 }
1596 // the resource area must be registered in case of a gc
1597 RegisterArrayForGC ragc(thread, local_array);
1598 objArrayOop context = oopFactory::new_objArray(SystemDictionary::ProtectionDomain_klass(),
1599 local_array->length(), CHECK_NULL);
1600 objArrayHandle h_context(thread, context);
1601 for (int index = 0; index < local_array->length(); index++) {
1602 h_context->obj_at_put(index, local_array->at(index));
1603 }
1605 oop result = java_security_AccessControlContext::create(h_context, is_privileged, privileged_context, CHECK_NULL);
1607 return JNIHandles::make_local(env, result);
1608 JVM_END
1611 JVM_QUICK_ENTRY(jboolean, JVM_IsArrayClass(JNIEnv *env, jclass cls))
1612 JVMWrapper("JVM_IsArrayClass");
1613 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1614 return (k != NULL) && k->oop_is_array() ? true : false;
1615 JVM_END
1618 JVM_QUICK_ENTRY(jboolean, JVM_IsPrimitiveClass(JNIEnv *env, jclass cls))
1619 JVMWrapper("JVM_IsPrimitiveClass");
1620 oop mirror = JNIHandles::resolve_non_null(cls);
1621 return (jboolean) java_lang_Class::is_primitive(mirror);
1622 JVM_END
1625 JVM_ENTRY(jclass, JVM_GetComponentType(JNIEnv *env, jclass cls))
1626 JVMWrapper("JVM_GetComponentType");
1627 oop mirror = JNIHandles::resolve_non_null(cls);
1628 oop result = Reflection::array_component_type(mirror, CHECK_NULL);
1629 return (jclass) JNIHandles::make_local(env, result);
1630 JVM_END
1633 JVM_ENTRY(jint, JVM_GetClassModifiers(JNIEnv *env, jclass cls))
1634 JVMWrapper("JVM_GetClassModifiers");
1635 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
1636 // Primitive type
1637 return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
1638 }
1640 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
1641 debug_only(int computed_modifiers = k->compute_modifier_flags(CHECK_0));
1642 assert(k->modifier_flags() == computed_modifiers, "modifiers cache is OK");
1643 return k->modifier_flags();
1644 JVM_END
1647 // Inner class reflection ///////////////////////////////////////////////////////////////////////////////
1649 JVM_ENTRY(jobjectArray, JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass))
1650 JvmtiVMObjectAllocEventCollector oam;
1651 // ofClass is a reference to a java_lang_Class object. The mirror object
1652 // of an InstanceKlass
1654 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1655 ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {
1656 oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1657 return (jobjectArray)JNIHandles::make_local(env, result);
1658 }
1660 instanceKlassHandle k(thread, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
1661 InnerClassesIterator iter(k);
1663 if (iter.length() == 0) {
1664 // Neither an inner nor outer class
1665 oop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), 0, CHECK_NULL);
1666 return (jobjectArray)JNIHandles::make_local(env, result);
1667 }
1669 // find inner class info
1670 constantPoolHandle cp(thread, k->constants());
1671 int length = iter.length();
1673 // Allocate temp. result array
1674 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Class_klass(), length/4, CHECK_NULL);
1675 objArrayHandle result (THREAD, r);
1676 int members = 0;
1678 for (; !iter.done(); iter.next()) {
1679 int ioff = iter.inner_class_info_index();
1680 int ooff = iter.outer_class_info_index();
1682 if (ioff != 0 && ooff != 0) {
1683 // Check to see if the name matches the class we're looking for
1684 // before attempting to find the class.
1685 if (cp->klass_name_at_matches(k, ooff)) {
1686 Klass* outer_klass = cp->klass_at(ooff, CHECK_NULL);
1687 if (outer_klass == k()) {
1688 Klass* ik = cp->klass_at(ioff, CHECK_NULL);
1689 instanceKlassHandle inner_klass (THREAD, ik);
1691 // Throws an exception if outer klass has not declared k as
1692 // an inner klass
1693 Reflection::check_for_inner_class(k, inner_klass, true, CHECK_NULL);
1695 result->obj_at_put(members, inner_klass->java_mirror());
1696 members++;
1697 }
1698 }
1699 }
1700 }
1702 if (members != length) {
1703 // Return array of right length
1704 objArrayOop res = oopFactory::new_objArray(SystemDictionary::Class_klass(), members, CHECK_NULL);
1705 for(int i = 0; i < members; i++) {
1706 res->obj_at_put(i, result->obj_at(i));
1707 }
1708 return (jobjectArray)JNIHandles::make_local(env, res);
1709 }
1711 return (jobjectArray)JNIHandles::make_local(env, result());
1712 JVM_END
1715 JVM_ENTRY(jclass, JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass))
1716 {
1717 // ofClass is a reference to a java_lang_Class object.
1718 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
1719 ! java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_instance()) {
1720 return NULL;
1721 }
1723 bool inner_is_member = false;
1724 Klass* outer_klass
1725 = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))
1726 )->compute_enclosing_class(&inner_is_member, CHECK_NULL);
1727 if (outer_klass == NULL) return NULL; // already a top-level class
1728 if (!inner_is_member) return NULL; // an anonymous class (inside a method)
1729 return (jclass) JNIHandles::make_local(env, outer_klass->java_mirror());
1730 }
1731 JVM_END
1733 // should be in InstanceKlass.cpp, but is here for historical reasons
1734 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle k,
1735 bool* inner_is_member,
1736 TRAPS) {
1737 Thread* thread = THREAD;
1738 InnerClassesIterator iter(k);
1739 if (iter.length() == 0) {
1740 // No inner class info => no declaring class
1741 return NULL;
1742 }
1744 constantPoolHandle i_cp(thread, k->constants());
1746 bool found = false;
1747 Klass* ok;
1748 instanceKlassHandle outer_klass;
1749 *inner_is_member = false;
1751 // Find inner_klass attribute
1752 for (; !iter.done() && !found; iter.next()) {
1753 int ioff = iter.inner_class_info_index();
1754 int ooff = iter.outer_class_info_index();
1755 int noff = iter.inner_name_index();
1756 if (ioff != 0) {
1757 // Check to see if the name matches the class we're looking for
1758 // before attempting to find the class.
1759 if (i_cp->klass_name_at_matches(k, ioff)) {
1760 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_NULL);
1761 found = (k() == inner_klass);
1762 if (found && ooff != 0) {
1763 ok = i_cp->klass_at(ooff, CHECK_NULL);
1764 outer_klass = instanceKlassHandle(thread, ok);
1765 *inner_is_member = true;
1766 }
1767 }
1768 }
1769 }
1771 if (found && outer_klass.is_null()) {
1772 // It may be anonymous; try for that.
1773 int encl_method_class_idx = k->enclosing_method_class_index();
1774 if (encl_method_class_idx != 0) {
1775 ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
1776 outer_klass = instanceKlassHandle(thread, ok);
1777 *inner_is_member = false;
1778 }
1779 }
1781 // If no inner class attribute found for this class.
1782 if (outer_klass.is_null()) return NULL;
1784 // Throws an exception if outer klass has not declared k as an inner klass
1785 // We need evidence that each klass knows about the other, or else
1786 // the system could allow a spoof of an inner class to gain access rights.
1787 Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);
1788 return outer_klass();
1789 }
1791 JVM_ENTRY(jstring, JVM_GetClassSignature(JNIEnv *env, jclass cls))
1792 assert (cls != NULL, "illegal class");
1793 JVMWrapper("JVM_GetClassSignature");
1794 JvmtiVMObjectAllocEventCollector oam;
1795 ResourceMark rm(THREAD);
1796 // Return null for arrays and primatives
1797 if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1798 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1799 if (k->oop_is_instance()) {
1800 Symbol* sym = InstanceKlass::cast(k)->generic_signature();
1801 if (sym == NULL) return NULL;
1802 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
1803 return (jstring) JNIHandles::make_local(env, str());
1804 }
1805 }
1806 return NULL;
1807 JVM_END
1810 JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
1811 assert (cls != NULL, "illegal class");
1812 JVMWrapper("JVM_GetClassAnnotations");
1814 // Return null for arrays and primitives
1815 if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1816 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1817 if (k->oop_is_instance()) {
1818 typeArrayOop a = Annotations::make_java_array(InstanceKlass::cast(k)->class_annotations(), CHECK_NULL);
1819 return (jbyteArray) JNIHandles::make_local(env, a);
1820 }
1821 }
1822 return NULL;
1823 JVM_END
1826 static bool jvm_get_field_common(jobject field, fieldDescriptor& fd, TRAPS) {
1827 // some of this code was adapted from from jni_FromReflectedField
1829 oop reflected = JNIHandles::resolve_non_null(field);
1830 oop mirror = java_lang_reflect_Field::clazz(reflected);
1831 Klass* k = java_lang_Class::as_Klass(mirror);
1832 int slot = java_lang_reflect_Field::slot(reflected);
1833 int modifiers = java_lang_reflect_Field::modifiers(reflected);
1835 KlassHandle kh(THREAD, k);
1836 intptr_t offset = InstanceKlass::cast(kh())->field_offset(slot);
1838 if (modifiers & JVM_ACC_STATIC) {
1839 // for static fields we only look in the current class
1840 if (!InstanceKlass::cast(kh())->find_local_field_from_offset(offset, true, &fd)) {
1841 assert(false, "cannot find static field");
1842 return false;
1843 }
1844 } else {
1845 // for instance fields we start with the current class and work
1846 // our way up through the superclass chain
1847 if (!InstanceKlass::cast(kh())->find_field_from_offset(offset, false, &fd)) {
1848 assert(false, "cannot find instance field");
1849 return false;
1850 }
1851 }
1852 return true;
1853 }
1855 JVM_ENTRY(jbyteArray, JVM_GetFieldAnnotations(JNIEnv *env, jobject field))
1856 // field is a handle to a java.lang.reflect.Field object
1857 assert(field != NULL, "illegal field");
1858 JVMWrapper("JVM_GetFieldAnnotations");
1860 fieldDescriptor fd;
1861 bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
1862 if (!gotFd) {
1863 return NULL;
1864 }
1866 return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.annotations(), THREAD));
1867 JVM_END
1870 static Method* jvm_get_method_common(jobject method) {
1871 // some of this code was adapted from from jni_FromReflectedMethod
1873 oop reflected = JNIHandles::resolve_non_null(method);
1874 oop mirror = NULL;
1875 int slot = 0;
1877 if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
1878 mirror = java_lang_reflect_Constructor::clazz(reflected);
1879 slot = java_lang_reflect_Constructor::slot(reflected);
1880 } else {
1881 assert(reflected->klass() == SystemDictionary::reflect_Method_klass(),
1882 "wrong type");
1883 mirror = java_lang_reflect_Method::clazz(reflected);
1884 slot = java_lang_reflect_Method::slot(reflected);
1885 }
1886 Klass* k = java_lang_Class::as_Klass(mirror);
1888 Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
1889 assert(m != NULL, "cannot find method");
1890 return m; // caller has to deal with NULL in product mode
1891 }
1894 JVM_ENTRY(jbyteArray, JVM_GetMethodAnnotations(JNIEnv *env, jobject method))
1895 JVMWrapper("JVM_GetMethodAnnotations");
1897 // method is a handle to a java.lang.reflect.Method object
1898 Method* m = jvm_get_method_common(method);
1899 if (m == NULL) {
1900 return NULL;
1901 }
1903 return (jbyteArray) JNIHandles::make_local(env,
1904 Annotations::make_java_array(m->annotations(), THREAD));
1905 JVM_END
1908 JVM_ENTRY(jbyteArray, JVM_GetMethodDefaultAnnotationValue(JNIEnv *env, jobject method))
1909 JVMWrapper("JVM_GetMethodDefaultAnnotationValue");
1911 // method is a handle to a java.lang.reflect.Method object
1912 Method* m = jvm_get_method_common(method);
1913 if (m == NULL) {
1914 return NULL;
1915 }
1917 return (jbyteArray) JNIHandles::make_local(env,
1918 Annotations::make_java_array(m->annotation_default(), THREAD));
1919 JVM_END
1922 JVM_ENTRY(jbyteArray, JVM_GetMethodParameterAnnotations(JNIEnv *env, jobject method))
1923 JVMWrapper("JVM_GetMethodParameterAnnotations");
1925 // method is a handle to a java.lang.reflect.Method object
1926 Method* m = jvm_get_method_common(method);
1927 if (m == NULL) {
1928 return NULL;
1929 }
1931 return (jbyteArray) JNIHandles::make_local(env,
1932 Annotations::make_java_array(m->parameter_annotations(), THREAD));
1933 JVM_END
1935 /* Type use annotations support (JDK 1.8) */
1937 JVM_ENTRY(jbyteArray, JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls))
1938 assert (cls != NULL, "illegal class");
1939 JVMWrapper("JVM_GetClassTypeAnnotations");
1940 ResourceMark rm(THREAD);
1941 // Return null for arrays and primitives
1942 if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
1943 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
1944 if (k->oop_is_instance()) {
1945 AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
1946 if (type_annotations != NULL) {
1947 typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1948 return (jbyteArray) JNIHandles::make_local(env, a);
1949 }
1950 }
1951 }
1952 return NULL;
1953 JVM_END
1955 JVM_ENTRY(jbyteArray, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
1956 assert (method != NULL, "illegal method");
1957 JVMWrapper("JVM_GetMethodTypeAnnotations");
1959 // method is a handle to a java.lang.reflect.Method object
1960 Method* m = jvm_get_method_common(method);
1961 if (m == NULL) {
1962 return NULL;
1963 }
1965 AnnotationArray* type_annotations = m->type_annotations();
1966 if (type_annotations != NULL) {
1967 typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
1968 return (jbyteArray) JNIHandles::make_local(env, a);
1969 }
1971 return NULL;
1972 JVM_END
1974 JVM_ENTRY(jbyteArray, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
1975 assert (field != NULL, "illegal field");
1976 JVMWrapper("JVM_GetFieldTypeAnnotations");
1978 fieldDescriptor fd;
1979 bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
1980 if (!gotFd) {
1981 return NULL;
1982 }
1984 return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.type_annotations(), THREAD));
1985 JVM_END
1987 static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
1988 if (!cp->is_within_bounds(index)) {
1989 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
1990 }
1991 }
1993 JVM_ENTRY(jobjectArray, JVM_GetMethodParameters(JNIEnv *env, jobject method))
1994 {
1995 JVMWrapper("JVM_GetMethodParameters");
1996 // method is a handle to a java.lang.reflect.Method object
1997 Method* method_ptr = jvm_get_method_common(method);
1998 methodHandle mh (THREAD, method_ptr);
1999 Handle reflected_method (THREAD, JNIHandles::resolve_non_null(method));
2000 const int num_params = mh->method_parameters_length();
2002 if (0 != num_params) {
2003 // make sure all the symbols are properly formatted
2004 for (int i = 0; i < num_params; i++) {
2005 MethodParametersElement* params = mh->method_parameters_start();
2006 int index = params[i].name_cp_index;
2007 bounds_check(mh->constants(), index, CHECK_NULL);
2009 if (0 != index && !mh->constants()->tag_at(index).is_utf8()) {
2010 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
2011 "Wrong type at constant pool index");
2012 }
2014 }
2016 objArrayOop result_oop = oopFactory::new_objArray(SystemDictionary::reflect_Parameter_klass(), num_params, CHECK_NULL);
2017 objArrayHandle result (THREAD, result_oop);
2019 for (int i = 0; i < num_params; i++) {
2020 MethodParametersElement* params = mh->method_parameters_start();
2021 // For a 0 index, give a NULL symbol
2022 Symbol* sym = 0 != params[i].name_cp_index ?
2023 mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
2024 int flags = params[i].flags;
2025 oop param = Reflection::new_parameter(reflected_method, i, sym,
2026 flags, CHECK_NULL);
2027 result->obj_at_put(i, param);
2028 }
2029 return (jobjectArray)JNIHandles::make_local(env, result());
2030 } else {
2031 return (jobjectArray)NULL;
2032 }
2033 }
2034 JVM_END
2036 // New (JDK 1.4) reflection implementation /////////////////////////////////////
2038 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields(JNIEnv *env, jclass ofClass, jboolean publicOnly))
2039 {
2040 JVMWrapper("JVM_GetClassDeclaredFields");
2041 JvmtiVMObjectAllocEventCollector oam;
2043 // Exclude primitive types and array types
2044 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass)) ||
2045 java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
2046 // Return empty array
2047 oop res = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), 0, CHECK_NULL);
2048 return (jobjectArray) JNIHandles::make_local(env, res);
2049 }
2051 instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
2052 constantPoolHandle cp(THREAD, k->constants());
2054 // Ensure class is linked
2055 k->link_class(CHECK_NULL);
2057 // 4496456 We need to filter out java.lang.Throwable.backtrace
2058 bool skip_backtrace = false;
2060 // Allocate result
2061 int num_fields;
2063 if (publicOnly) {
2064 num_fields = 0;
2065 for (JavaFieldStream fs(k()); !fs.done(); fs.next()) {
2066 if (fs.access_flags().is_public()) ++num_fields;
2067 }
2068 } else {
2069 num_fields = k->java_fields_count();
2071 if (k() == SystemDictionary::Throwable_klass()) {
2072 num_fields--;
2073 skip_backtrace = true;
2074 }
2075 }
2077 objArrayOop r = oopFactory::new_objArray(SystemDictionary::reflect_Field_klass(), num_fields, CHECK_NULL);
2078 objArrayHandle result (THREAD, r);
2080 int out_idx = 0;
2081 fieldDescriptor fd;
2082 for (JavaFieldStream fs(k); !fs.done(); fs.next()) {
2083 if (skip_backtrace) {
2084 // 4496456 skip java.lang.Throwable.backtrace
2085 int offset = fs.offset();
2086 if (offset == java_lang_Throwable::get_backtrace_offset()) continue;
2087 }
2089 if (!publicOnly || fs.access_flags().is_public()) {
2090 fd.reinitialize(k(), fs.index());
2091 oop field = Reflection::new_field(&fd, UseNewReflection, CHECK_NULL);
2092 result->obj_at_put(out_idx, field);
2093 ++out_idx;
2094 }
2095 }
2096 assert(out_idx == num_fields, "just checking");
2097 return (jobjectArray) JNIHandles::make_local(env, result());
2098 }
2099 JVM_END
2101 static bool select_method(methodHandle method, bool want_constructor) {
2102 if (want_constructor) {
2103 return (method->is_initializer() && !method->is_static());
2104 } else {
2105 return (!method->is_initializer() && !method->is_overpass());
2106 }
2107 }
2109 static jobjectArray get_class_declared_methods_helper(
2110 JNIEnv *env,
2111 jclass ofClass, jboolean publicOnly,
2112 bool want_constructor,
2113 Klass* klass, TRAPS) {
2115 JvmtiVMObjectAllocEventCollector oam;
2117 // Exclude primitive types and array types
2118 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(ofClass))
2119 || java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass))->oop_is_array()) {
2120 // Return empty array
2121 oop res = oopFactory::new_objArray(klass, 0, CHECK_NULL);
2122 return (jobjectArray) JNIHandles::make_local(env, res);
2123 }
2125 instanceKlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(ofClass)));
2127 // Ensure class is linked
2128 k->link_class(CHECK_NULL);
2130 Array<Method*>* methods = k->methods();
2131 int methods_length = methods->length();
2133 // Save original method_idnum in case of redefinition, which can change
2134 // the idnum of obsolete methods. The new method will have the same idnum
2135 // but if we refresh the methods array, the counts will be wrong.
2136 ResourceMark rm(THREAD);
2137 GrowableArray<int>* idnums = new GrowableArray<int>(methods_length);
2138 int num_methods = 0;
2140 for (int i = 0; i < methods_length; i++) {
2141 methodHandle method(THREAD, methods->at(i));
2142 if (select_method(method, want_constructor)) {
2143 if (!publicOnly || method->is_public()) {
2144 idnums->push(method->method_idnum());
2145 ++num_methods;
2146 }
2147 }
2148 }
2150 // Allocate result
2151 objArrayOop r = oopFactory::new_objArray(klass, num_methods, CHECK_NULL);
2152 objArrayHandle result (THREAD, r);
2154 // Now just put the methods that we selected above, but go by their idnum
2155 // in case of redefinition. The methods can be redefined at any safepoint,
2156 // so above when allocating the oop array and below when creating reflect
2157 // objects.
2158 for (int i = 0; i < num_methods; i++) {
2159 methodHandle method(THREAD, k->method_with_idnum(idnums->at(i)));
2160 if (method.is_null()) {
2161 // Method may have been deleted and seems this API can handle null
2162 // Otherwise should probably put a method that throws NSME
2163 result->obj_at_put(i, NULL);
2164 } else {
2165 oop m;
2166 if (want_constructor) {
2167 m = Reflection::new_constructor(method, CHECK_NULL);
2168 } else {
2169 m = Reflection::new_method(method, UseNewReflection, false, CHECK_NULL);
2170 }
2171 result->obj_at_put(i, m);
2172 }
2173 }
2175 return (jobjectArray) JNIHandles::make_local(env, result());
2176 }
2178 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredMethods(JNIEnv *env, jclass ofClass, jboolean publicOnly))
2179 {
2180 JVMWrapper("JVM_GetClassDeclaredMethods");
2181 return get_class_declared_methods_helper(env, ofClass, publicOnly,
2182 /*want_constructor*/ false,
2183 SystemDictionary::reflect_Method_klass(), THREAD);
2184 }
2185 JVM_END
2187 JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredConstructors(JNIEnv *env, jclass ofClass, jboolean publicOnly))
2188 {
2189 JVMWrapper("JVM_GetClassDeclaredConstructors");
2190 return get_class_declared_methods_helper(env, ofClass, publicOnly,
2191 /*want_constructor*/ true,
2192 SystemDictionary::reflect_Constructor_klass(), THREAD);
2193 }
2194 JVM_END
2196 JVM_ENTRY(jint, JVM_GetClassAccessFlags(JNIEnv *env, jclass cls))
2197 {
2198 JVMWrapper("JVM_GetClassAccessFlags");
2199 if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2200 // Primitive type
2201 return JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC;
2202 }
2204 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2205 return k->access_flags().as_int() & JVM_ACC_WRITTEN_FLAGS;
2206 }
2207 JVM_END
2210 // Constant pool access //////////////////////////////////////////////////////////
2212 JVM_ENTRY(jobject, JVM_GetClassConstantPool(JNIEnv *env, jclass cls))
2213 {
2214 JVMWrapper("JVM_GetClassConstantPool");
2215 JvmtiVMObjectAllocEventCollector oam;
2217 // Return null for primitives and arrays
2218 if (!java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
2219 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2220 if (k->oop_is_instance()) {
2221 instanceKlassHandle k_h(THREAD, k);
2222 Handle jcp = sun_reflect_ConstantPool::create(CHECK_NULL);
2223 sun_reflect_ConstantPool::set_cp(jcp(), k_h->constants());
2224 return JNIHandles::make_local(jcp());
2225 }
2226 }
2227 return NULL;
2228 }
2229 JVM_END
2232 JVM_ENTRY(jint, JVM_ConstantPoolGetSize(JNIEnv *env, jobject obj, jobject unused))
2233 {
2234 JVMWrapper("JVM_ConstantPoolGetSize");
2235 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2236 return cp->length();
2237 }
2238 JVM_END
2241 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2242 {
2243 JVMWrapper("JVM_ConstantPoolGetClassAt");
2244 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2245 bounds_check(cp, index, CHECK_NULL);
2246 constantTag tag = cp->tag_at(index);
2247 if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2248 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2249 }
2250 Klass* k = cp->klass_at(index, CHECK_NULL);
2251 return (jclass) JNIHandles::make_local(k->java_mirror());
2252 }
2253 JVM_END
2255 JVM_ENTRY(jclass, JVM_ConstantPoolGetClassAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2256 {
2257 JVMWrapper("JVM_ConstantPoolGetClassAtIfLoaded");
2258 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2259 bounds_check(cp, index, CHECK_NULL);
2260 constantTag tag = cp->tag_at(index);
2261 if (!tag.is_klass() && !tag.is_unresolved_klass()) {
2262 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2263 }
2264 Klass* k = ConstantPool::klass_at_if_loaded(cp, index);
2265 if (k == NULL) return NULL;
2266 return (jclass) JNIHandles::make_local(k->java_mirror());
2267 }
2268 JVM_END
2270 static jobject get_method_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2271 constantTag tag = cp->tag_at(index);
2272 if (!tag.is_method() && !tag.is_interface_method()) {
2273 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2274 }
2275 int klass_ref = cp->uncached_klass_ref_index_at(index);
2276 Klass* k_o;
2277 if (force_resolution) {
2278 k_o = cp->klass_at(klass_ref, CHECK_NULL);
2279 } else {
2280 k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2281 if (k_o == NULL) return NULL;
2282 }
2283 instanceKlassHandle k(THREAD, k_o);
2284 Symbol* name = cp->uncached_name_ref_at(index);
2285 Symbol* sig = cp->uncached_signature_ref_at(index);
2286 methodHandle m (THREAD, k->find_method(name, sig));
2287 if (m.is_null()) {
2288 THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up method in target class");
2289 }
2290 oop method;
2291 if (!m->is_initializer() || m->is_static()) {
2292 method = Reflection::new_method(m, true, true, CHECK_NULL);
2293 } else {
2294 method = Reflection::new_constructor(m, CHECK_NULL);
2295 }
2296 return JNIHandles::make_local(method);
2297 }
2299 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2300 {
2301 JVMWrapper("JVM_ConstantPoolGetMethodAt");
2302 JvmtiVMObjectAllocEventCollector oam;
2303 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2304 bounds_check(cp, index, CHECK_NULL);
2305 jobject res = get_method_at_helper(cp, index, true, CHECK_NULL);
2306 return res;
2307 }
2308 JVM_END
2310 JVM_ENTRY(jobject, JVM_ConstantPoolGetMethodAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2311 {
2312 JVMWrapper("JVM_ConstantPoolGetMethodAtIfLoaded");
2313 JvmtiVMObjectAllocEventCollector oam;
2314 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2315 bounds_check(cp, index, CHECK_NULL);
2316 jobject res = get_method_at_helper(cp, index, false, CHECK_NULL);
2317 return res;
2318 }
2319 JVM_END
2321 static jobject get_field_at_helper(constantPoolHandle cp, jint index, bool force_resolution, TRAPS) {
2322 constantTag tag = cp->tag_at(index);
2323 if (!tag.is_field()) {
2324 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2325 }
2326 int klass_ref = cp->uncached_klass_ref_index_at(index);
2327 Klass* k_o;
2328 if (force_resolution) {
2329 k_o = cp->klass_at(klass_ref, CHECK_NULL);
2330 } else {
2331 k_o = ConstantPool::klass_at_if_loaded(cp, klass_ref);
2332 if (k_o == NULL) return NULL;
2333 }
2334 instanceKlassHandle k(THREAD, k_o);
2335 Symbol* name = cp->uncached_name_ref_at(index);
2336 Symbol* sig = cp->uncached_signature_ref_at(index);
2337 fieldDescriptor fd;
2338 Klass* target_klass = k->find_field(name, sig, &fd);
2339 if (target_klass == NULL) {
2340 THROW_MSG_0(vmSymbols::java_lang_RuntimeException(), "Unable to look up field in target class");
2341 }
2342 oop field = Reflection::new_field(&fd, true, CHECK_NULL);
2343 return JNIHandles::make_local(field);
2344 }
2346 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAt(JNIEnv *env, jobject obj, jobject unusedl, jint index))
2347 {
2348 JVMWrapper("JVM_ConstantPoolGetFieldAt");
2349 JvmtiVMObjectAllocEventCollector oam;
2350 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2351 bounds_check(cp, index, CHECK_NULL);
2352 jobject res = get_field_at_helper(cp, index, true, CHECK_NULL);
2353 return res;
2354 }
2355 JVM_END
2357 JVM_ENTRY(jobject, JVM_ConstantPoolGetFieldAtIfLoaded(JNIEnv *env, jobject obj, jobject unused, jint index))
2358 {
2359 JVMWrapper("JVM_ConstantPoolGetFieldAtIfLoaded");
2360 JvmtiVMObjectAllocEventCollector oam;
2361 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2362 bounds_check(cp, index, CHECK_NULL);
2363 jobject res = get_field_at_helper(cp, index, false, CHECK_NULL);
2364 return res;
2365 }
2366 JVM_END
2368 JVM_ENTRY(jobjectArray, JVM_ConstantPoolGetMemberRefInfoAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2369 {
2370 JVMWrapper("JVM_ConstantPoolGetMemberRefInfoAt");
2371 JvmtiVMObjectAllocEventCollector oam;
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_field_or_method()) {
2376 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2377 }
2378 int klass_ref = cp->uncached_klass_ref_index_at(index);
2379 Symbol* klass_name = cp->klass_name_at(klass_ref);
2380 Symbol* member_name = cp->uncached_name_ref_at(index);
2381 Symbol* member_sig = cp->uncached_signature_ref_at(index);
2382 objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::String_klass(), 3, CHECK_NULL);
2383 objArrayHandle dest(THREAD, dest_o);
2384 Handle str = java_lang_String::create_from_symbol(klass_name, CHECK_NULL);
2385 dest->obj_at_put(0, str());
2386 str = java_lang_String::create_from_symbol(member_name, CHECK_NULL);
2387 dest->obj_at_put(1, str());
2388 str = java_lang_String::create_from_symbol(member_sig, CHECK_NULL);
2389 dest->obj_at_put(2, str());
2390 return (jobjectArray) JNIHandles::make_local(dest());
2391 }
2392 JVM_END
2394 JVM_ENTRY(jint, JVM_ConstantPoolGetIntAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2395 {
2396 JVMWrapper("JVM_ConstantPoolGetIntAt");
2397 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2398 bounds_check(cp, index, CHECK_0);
2399 constantTag tag = cp->tag_at(index);
2400 if (!tag.is_int()) {
2401 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2402 }
2403 return cp->int_at(index);
2404 }
2405 JVM_END
2407 JVM_ENTRY(jlong, JVM_ConstantPoolGetLongAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2408 {
2409 JVMWrapper("JVM_ConstantPoolGetLongAt");
2410 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2411 bounds_check(cp, index, CHECK_(0L));
2412 constantTag tag = cp->tag_at(index);
2413 if (!tag.is_long()) {
2414 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2415 }
2416 return cp->long_at(index);
2417 }
2418 JVM_END
2420 JVM_ENTRY(jfloat, JVM_ConstantPoolGetFloatAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2421 {
2422 JVMWrapper("JVM_ConstantPoolGetFloatAt");
2423 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2424 bounds_check(cp, index, CHECK_(0.0f));
2425 constantTag tag = cp->tag_at(index);
2426 if (!tag.is_float()) {
2427 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2428 }
2429 return cp->float_at(index);
2430 }
2431 JVM_END
2433 JVM_ENTRY(jdouble, JVM_ConstantPoolGetDoubleAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2434 {
2435 JVMWrapper("JVM_ConstantPoolGetDoubleAt");
2436 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2437 bounds_check(cp, index, CHECK_(0.0));
2438 constantTag tag = cp->tag_at(index);
2439 if (!tag.is_double()) {
2440 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2441 }
2442 return cp->double_at(index);
2443 }
2444 JVM_END
2446 JVM_ENTRY(jstring, JVM_ConstantPoolGetStringAt(JNIEnv *env, jobject obj, jobject unused, jint index))
2447 {
2448 JVMWrapper("JVM_ConstantPoolGetStringAt");
2449 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2450 bounds_check(cp, index, CHECK_NULL);
2451 constantTag tag = cp->tag_at(index);
2452 if (!tag.is_string()) {
2453 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2454 }
2455 oop str = cp->string_at(index, CHECK_NULL);
2456 return (jstring) JNIHandles::make_local(str);
2457 }
2458 JVM_END
2460 JVM_ENTRY(jstring, JVM_ConstantPoolGetUTF8At(JNIEnv *env, jobject obj, jobject unused, jint index))
2461 {
2462 JVMWrapper("JVM_ConstantPoolGetUTF8At");
2463 JvmtiVMObjectAllocEventCollector oam;
2464 constantPoolHandle cp = constantPoolHandle(THREAD, sun_reflect_ConstantPool::get_cp(JNIHandles::resolve_non_null(obj)));
2465 bounds_check(cp, index, CHECK_NULL);
2466 constantTag tag = cp->tag_at(index);
2467 if (!tag.is_symbol()) {
2468 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Wrong type at constant pool index");
2469 }
2470 Symbol* sym = cp->symbol_at(index);
2471 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
2472 return (jstring) JNIHandles::make_local(str());
2473 }
2474 JVM_END
2477 // Assertion support. //////////////////////////////////////////////////////////
2479 JVM_ENTRY(jboolean, JVM_DesiredAssertionStatus(JNIEnv *env, jclass unused, jclass cls))
2480 JVMWrapper("JVM_DesiredAssertionStatus");
2481 assert(cls != NULL, "bad class");
2483 oop r = JNIHandles::resolve(cls);
2484 assert(! java_lang_Class::is_primitive(r), "primitive classes not allowed");
2485 if (java_lang_Class::is_primitive(r)) return false;
2487 Klass* k = java_lang_Class::as_Klass(r);
2488 assert(k->oop_is_instance(), "must be an instance klass");
2489 if (! k->oop_is_instance()) return false;
2491 ResourceMark rm(THREAD);
2492 const char* name = k->name()->as_C_string();
2493 bool system_class = k->class_loader() == NULL;
2494 return JavaAssertions::enabled(name, system_class);
2496 JVM_END
2499 // Return a new AssertionStatusDirectives object with the fields filled in with
2500 // command-line assertion arguments (i.e., -ea, -da).
2501 JVM_ENTRY(jobject, JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused))
2502 JVMWrapper("JVM_AssertionStatusDirectives");
2503 JvmtiVMObjectAllocEventCollector oam;
2504 oop asd = JavaAssertions::createAssertionStatusDirectives(CHECK_NULL);
2505 return JNIHandles::make_local(env, asd);
2506 JVM_END
2508 // Verification ////////////////////////////////////////////////////////////////////////////////
2510 // Reflection for the verifier /////////////////////////////////////////////////////////////////
2512 // RedefineClasses support: bug 6214132 caused verification to fail.
2513 // All functions from this section should call the jvmtiThreadSate function:
2514 // Klass* class_to_verify_considering_redefinition(Klass* klass).
2515 // The function returns a Klass* of the _scratch_class if the verifier
2516 // was invoked in the middle of the class redefinition.
2517 // Otherwise it returns its argument value which is the _the_class Klass*.
2518 // Please, refer to the description in the jvmtiThreadSate.hpp.
2520 JVM_ENTRY(const char*, JVM_GetClassNameUTF(JNIEnv *env, jclass cls))
2521 JVMWrapper("JVM_GetClassNameUTF");
2522 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2523 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2524 return k->name()->as_utf8();
2525 JVM_END
2528 JVM_QUICK_ENTRY(void, JVM_GetClassCPTypes(JNIEnv *env, jclass cls, unsigned char *types))
2529 JVMWrapper("JVM_GetClassCPTypes");
2530 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2531 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2532 // types will have length zero if this is not an InstanceKlass
2533 // (length is determined by call to JVM_GetClassCPEntriesCount)
2534 if (k->oop_is_instance()) {
2535 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2536 for (int index = cp->length() - 1; index >= 0; index--) {
2537 constantTag tag = cp->tag_at(index);
2538 types[index] = (tag.is_unresolved_klass()) ? JVM_CONSTANT_Class : tag.value();
2539 }
2540 }
2541 JVM_END
2544 JVM_QUICK_ENTRY(jint, JVM_GetClassCPEntriesCount(JNIEnv *env, jclass cls))
2545 JVMWrapper("JVM_GetClassCPEntriesCount");
2546 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2547 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2548 if (!k->oop_is_instance())
2549 return 0;
2550 return InstanceKlass::cast(k)->constants()->length();
2551 JVM_END
2554 JVM_QUICK_ENTRY(jint, JVM_GetClassFieldsCount(JNIEnv *env, jclass cls))
2555 JVMWrapper("JVM_GetClassFieldsCount");
2556 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2557 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2558 if (!k->oop_is_instance())
2559 return 0;
2560 return InstanceKlass::cast(k)->java_fields_count();
2561 JVM_END
2564 JVM_QUICK_ENTRY(jint, JVM_GetClassMethodsCount(JNIEnv *env, jclass cls))
2565 JVMWrapper("JVM_GetClassMethodsCount");
2566 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2567 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2568 if (!k->oop_is_instance())
2569 return 0;
2570 return InstanceKlass::cast(k)->methods()->length();
2571 JVM_END
2574 // The following methods, used for the verifier, are never called with
2575 // array klasses, so a direct cast to InstanceKlass is safe.
2576 // Typically, these methods are called in a loop with bounds determined
2577 // by the results of JVM_GetClass{Fields,Methods}Count, which return
2578 // zero for arrays.
2579 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionIndexes(JNIEnv *env, jclass cls, jint method_index, unsigned short *exceptions))
2580 JVMWrapper("JVM_GetMethodIxExceptionIndexes");
2581 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2582 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2583 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2584 int length = method->checked_exceptions_length();
2585 if (length > 0) {
2586 CheckedExceptionElement* table= method->checked_exceptions_start();
2587 for (int i = 0; i < length; i++) {
2588 exceptions[i] = table[i].class_cp_index;
2589 }
2590 }
2591 JVM_END
2594 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionsCount(JNIEnv *env, jclass cls, jint method_index))
2595 JVMWrapper("JVM_GetMethodIxExceptionsCount");
2596 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2597 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2598 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2599 return method->checked_exceptions_length();
2600 JVM_END
2603 JVM_QUICK_ENTRY(void, JVM_GetMethodIxByteCode(JNIEnv *env, jclass cls, jint method_index, unsigned char *code))
2604 JVMWrapper("JVM_GetMethodIxByteCode");
2605 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2606 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2607 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2608 memcpy(code, method->code_base(), method->code_size());
2609 JVM_END
2612 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxByteCodeLength(JNIEnv *env, jclass cls, jint method_index))
2613 JVMWrapper("JVM_GetMethodIxByteCodeLength");
2614 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2615 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2616 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2617 return method->code_size();
2618 JVM_END
2621 JVM_QUICK_ENTRY(void, JVM_GetMethodIxExceptionTableEntry(JNIEnv *env, jclass cls, jint method_index, jint entry_index, JVM_ExceptionTableEntryType *entry))
2622 JVMWrapper("JVM_GetMethodIxExceptionTableEntry");
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 ExceptionTable extable(method);
2627 entry->start_pc = extable.start_pc(entry_index);
2628 entry->end_pc = extable.end_pc(entry_index);
2629 entry->handler_pc = extable.handler_pc(entry_index);
2630 entry->catchType = extable.catch_type_index(entry_index);
2631 JVM_END
2634 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxExceptionTableLength(JNIEnv *env, jclass cls, int method_index))
2635 JVMWrapper("JVM_GetMethodIxExceptionTableLength");
2636 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2637 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2638 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2639 return method->exception_table_length();
2640 JVM_END
2643 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxModifiers(JNIEnv *env, jclass cls, int method_index))
2644 JVMWrapper("JVM_GetMethodIxModifiers");
2645 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2646 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2647 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2648 return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2649 JVM_END
2652 JVM_QUICK_ENTRY(jint, JVM_GetFieldIxModifiers(JNIEnv *env, jclass cls, int field_index))
2653 JVMWrapper("JVM_GetFieldIxModifiers");
2654 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2655 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2656 return InstanceKlass::cast(k)->field_access_flags(field_index) & JVM_RECOGNIZED_FIELD_MODIFIERS;
2657 JVM_END
2660 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxLocalsCount(JNIEnv *env, jclass cls, int method_index))
2661 JVMWrapper("JVM_GetMethodIxLocalsCount");
2662 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2663 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2664 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2665 return method->max_locals();
2666 JVM_END
2669 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxArgsSize(JNIEnv *env, jclass cls, int method_index))
2670 JVMWrapper("JVM_GetMethodIxArgsSize");
2671 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2672 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2673 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2674 return method->size_of_parameters();
2675 JVM_END
2678 JVM_QUICK_ENTRY(jint, JVM_GetMethodIxMaxStack(JNIEnv *env, jclass cls, int method_index))
2679 JVMWrapper("JVM_GetMethodIxMaxStack");
2680 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2681 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2682 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2683 return method->verifier_max_stack();
2684 JVM_END
2687 JVM_QUICK_ENTRY(jboolean, JVM_IsConstructorIx(JNIEnv *env, jclass cls, int method_index))
2688 JVMWrapper("JVM_IsConstructorIx");
2689 ResourceMark rm(THREAD);
2690 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2691 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2692 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2693 return method->name() == vmSymbols::object_initializer_name();
2694 JVM_END
2697 JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
2698 JVMWrapper("JVM_IsVMGeneratedMethodIx");
2699 ResourceMark rm(THREAD);
2700 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2701 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2702 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2703 return method->is_overpass();
2704 JVM_END
2706 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
2707 JVMWrapper("JVM_GetMethodIxIxUTF");
2708 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2709 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2710 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2711 return method->name()->as_utf8();
2712 JVM_END
2715 JVM_ENTRY(const char*, JVM_GetMethodIxSignatureUTF(JNIEnv *env, jclass cls, jint method_index))
2716 JVMWrapper("JVM_GetMethodIxSignatureUTF");
2717 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2718 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2719 Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
2720 return method->signature()->as_utf8();
2721 JVM_END
2723 /**
2724 * All of these JVM_GetCP-xxx methods are used by the old verifier to
2725 * read entries in the constant pool. Since the old verifier always
2726 * works on a copy of the code, it will not see any rewriting that
2727 * may possibly occur in the middle of verification. So it is important
2728 * that nothing it calls tries to use the cpCache instead of the raw
2729 * constant pool, so we must use cp->uncached_x methods when appropriate.
2730 */
2731 JVM_ENTRY(const char*, JVM_GetCPFieldNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2732 JVMWrapper("JVM_GetCPFieldNameUTF");
2733 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2734 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2735 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2736 switch (cp->tag_at(cp_index).value()) {
2737 case JVM_CONSTANT_Fieldref:
2738 return cp->uncached_name_ref_at(cp_index)->as_utf8();
2739 default:
2740 fatal("JVM_GetCPFieldNameUTF: illegal constant");
2741 }
2742 ShouldNotReachHere();
2743 return NULL;
2744 JVM_END
2747 JVM_ENTRY(const char*, JVM_GetCPMethodNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2748 JVMWrapper("JVM_GetCPMethodNameUTF");
2749 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2750 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2751 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2752 switch (cp->tag_at(cp_index).value()) {
2753 case JVM_CONSTANT_InterfaceMethodref:
2754 case JVM_CONSTANT_Methodref:
2755 return cp->uncached_name_ref_at(cp_index)->as_utf8();
2756 default:
2757 fatal("JVM_GetCPMethodNameUTF: illegal constant");
2758 }
2759 ShouldNotReachHere();
2760 return NULL;
2761 JVM_END
2764 JVM_ENTRY(const char*, JVM_GetCPMethodSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2765 JVMWrapper("JVM_GetCPMethodSignatureUTF");
2766 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2767 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2768 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2769 switch (cp->tag_at(cp_index).value()) {
2770 case JVM_CONSTANT_InterfaceMethodref:
2771 case JVM_CONSTANT_Methodref:
2772 return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2773 default:
2774 fatal("JVM_GetCPMethodSignatureUTF: illegal constant");
2775 }
2776 ShouldNotReachHere();
2777 return NULL;
2778 JVM_END
2781 JVM_ENTRY(const char*, JVM_GetCPFieldSignatureUTF(JNIEnv *env, jclass cls, jint cp_index))
2782 JVMWrapper("JVM_GetCPFieldSignatureUTF");
2783 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2784 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2785 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2786 switch (cp->tag_at(cp_index).value()) {
2787 case JVM_CONSTANT_Fieldref:
2788 return cp->uncached_signature_ref_at(cp_index)->as_utf8();
2789 default:
2790 fatal("JVM_GetCPFieldSignatureUTF: illegal constant");
2791 }
2792 ShouldNotReachHere();
2793 return NULL;
2794 JVM_END
2797 JVM_ENTRY(const char*, JVM_GetCPClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2798 JVMWrapper("JVM_GetCPClassNameUTF");
2799 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2800 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2801 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2802 Symbol* classname = cp->klass_name_at(cp_index);
2803 return classname->as_utf8();
2804 JVM_END
2807 JVM_ENTRY(const char*, JVM_GetCPFieldClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2808 JVMWrapper("JVM_GetCPFieldClassNameUTF");
2809 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2810 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2811 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2812 switch (cp->tag_at(cp_index).value()) {
2813 case JVM_CONSTANT_Fieldref: {
2814 int class_index = cp->uncached_klass_ref_index_at(cp_index);
2815 Symbol* classname = cp->klass_name_at(class_index);
2816 return classname->as_utf8();
2817 }
2818 default:
2819 fatal("JVM_GetCPFieldClassNameUTF: illegal constant");
2820 }
2821 ShouldNotReachHere();
2822 return NULL;
2823 JVM_END
2826 JVM_ENTRY(const char*, JVM_GetCPMethodClassNameUTF(JNIEnv *env, jclass cls, jint cp_index))
2827 JVMWrapper("JVM_GetCPMethodClassNameUTF");
2828 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2829 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2830 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2831 switch (cp->tag_at(cp_index).value()) {
2832 case JVM_CONSTANT_Methodref:
2833 case JVM_CONSTANT_InterfaceMethodref: {
2834 int class_index = cp->uncached_klass_ref_index_at(cp_index);
2835 Symbol* classname = cp->klass_name_at(class_index);
2836 return classname->as_utf8();
2837 }
2838 default:
2839 fatal("JVM_GetCPMethodClassNameUTF: illegal constant");
2840 }
2841 ShouldNotReachHere();
2842 return NULL;
2843 JVM_END
2846 JVM_ENTRY(jint, JVM_GetCPFieldModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2847 JVMWrapper("JVM_GetCPFieldModifiers");
2848 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2849 Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2850 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2851 k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2852 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2853 ConstantPool* cp_called = InstanceKlass::cast(k_called)->constants();
2854 switch (cp->tag_at(cp_index).value()) {
2855 case JVM_CONSTANT_Fieldref: {
2856 Symbol* name = cp->uncached_name_ref_at(cp_index);
2857 Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2858 for (JavaFieldStream fs(k_called); !fs.done(); fs.next()) {
2859 if (fs.name() == name && fs.signature() == signature) {
2860 return fs.access_flags().as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS;
2861 }
2862 }
2863 return -1;
2864 }
2865 default:
2866 fatal("JVM_GetCPFieldModifiers: illegal constant");
2867 }
2868 ShouldNotReachHere();
2869 return 0;
2870 JVM_END
2873 JVM_QUICK_ENTRY(jint, JVM_GetCPMethodModifiers(JNIEnv *env, jclass cls, int cp_index, jclass called_cls))
2874 JVMWrapper("JVM_GetCPMethodModifiers");
2875 Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2876 Klass* k_called = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(called_cls));
2877 k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
2878 k_called = JvmtiThreadState::class_to_verify_considering_redefinition(k_called, thread);
2879 ConstantPool* cp = InstanceKlass::cast(k)->constants();
2880 switch (cp->tag_at(cp_index).value()) {
2881 case JVM_CONSTANT_Methodref:
2882 case JVM_CONSTANT_InterfaceMethodref: {
2883 Symbol* name = cp->uncached_name_ref_at(cp_index);
2884 Symbol* signature = cp->uncached_signature_ref_at(cp_index);
2885 Array<Method*>* methods = InstanceKlass::cast(k_called)->methods();
2886 int methods_count = methods->length();
2887 for (int i = 0; i < methods_count; i++) {
2888 Method* method = methods->at(i);
2889 if (method->name() == name && method->signature() == signature) {
2890 return method->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2891 }
2892 }
2893 return -1;
2894 }
2895 default:
2896 fatal("JVM_GetCPMethodModifiers: illegal constant");
2897 }
2898 ShouldNotReachHere();
2899 return 0;
2900 JVM_END
2903 // Misc //////////////////////////////////////////////////////////////////////////////////////////////
2905 JVM_LEAF(void, JVM_ReleaseUTF(const char *utf))
2906 // So long as UTF8::convert_to_utf8 returns resource strings, we don't have to do anything
2907 JVM_END
2910 JVM_ENTRY(jboolean, JVM_IsSameClassPackage(JNIEnv *env, jclass class1, jclass class2))
2911 JVMWrapper("JVM_IsSameClassPackage");
2912 oop class1_mirror = JNIHandles::resolve_non_null(class1);
2913 oop class2_mirror = JNIHandles::resolve_non_null(class2);
2914 Klass* klass1 = java_lang_Class::as_Klass(class1_mirror);
2915 Klass* klass2 = java_lang_Class::as_Klass(class2_mirror);
2916 return (jboolean) Reflection::is_same_class_package(klass1, klass2);
2917 JVM_END
2920 // IO functions ////////////////////////////////////////////////////////////////////////////////////////
2922 JVM_LEAF(jint, JVM_Open(const char *fname, jint flags, jint mode))
2923 JVMWrapper2("JVM_Open (%s)", fname);
2925 //%note jvm_r6
2926 int result = os::open(fname, flags, mode);
2927 if (result >= 0) {
2928 return result;
2929 } else {
2930 switch(errno) {
2931 case EEXIST:
2932 return JVM_EEXIST;
2933 default:
2934 return -1;
2935 }
2936 }
2937 JVM_END
2940 JVM_LEAF(jint, JVM_Close(jint fd))
2941 JVMWrapper2("JVM_Close (0x%x)", fd);
2942 //%note jvm_r6
2943 return os::close(fd);
2944 JVM_END
2947 JVM_LEAF(jint, JVM_Read(jint fd, char *buf, jint nbytes))
2948 JVMWrapper2("JVM_Read (0x%x)", fd);
2950 //%note jvm_r6
2951 return (jint)os::restartable_read(fd, buf, nbytes);
2952 JVM_END
2955 JVM_LEAF(jint, JVM_Write(jint fd, char *buf, jint nbytes))
2956 JVMWrapper2("JVM_Write (0x%x)", fd);
2958 //%note jvm_r6
2959 return (jint)os::write(fd, buf, nbytes);
2960 JVM_END
2963 JVM_LEAF(jint, JVM_Available(jint fd, jlong *pbytes))
2964 JVMWrapper2("JVM_Available (0x%x)", fd);
2965 //%note jvm_r6
2966 return os::available(fd, pbytes);
2967 JVM_END
2970 JVM_LEAF(jlong, JVM_Lseek(jint fd, jlong offset, jint whence))
2971 JVMWrapper4("JVM_Lseek (0x%x, " INT64_FORMAT ", %d)", fd, (int64_t) offset, whence);
2972 //%note jvm_r6
2973 return os::lseek(fd, offset, whence);
2974 JVM_END
2977 JVM_LEAF(jint, JVM_SetLength(jint fd, jlong length))
2978 JVMWrapper3("JVM_SetLength (0x%x, " INT64_FORMAT ")", fd, (int64_t) length);
2979 return os::ftruncate(fd, length);
2980 JVM_END
2983 JVM_LEAF(jint, JVM_Sync(jint fd))
2984 JVMWrapper2("JVM_Sync (0x%x)", fd);
2985 //%note jvm_r6
2986 return os::fsync(fd);
2987 JVM_END
2990 // Printing support //////////////////////////////////////////////////
2991 extern "C" {
2993 ATTRIBUTE_PRINTF(3, 0)
2994 int jio_vsnprintf(char *str, size_t count, const char *fmt, va_list args) {
2995 // Reject count values that are negative signed values converted to
2996 // unsigned; see bug 4399518, 4417214
2997 if ((intptr_t)count <= 0) return -1;
2999 int result = os::vsnprintf(str, count, fmt, args);
3000 if (result > 0 && (size_t)result >= count) {
3001 result = -1;
3002 }
3004 return result;
3005 }
3007 ATTRIBUTE_PRINTF(3, 0)
3008 int jio_snprintf(char *str, size_t count, const char *fmt, ...) {
3009 va_list args;
3010 int len;
3011 va_start(args, fmt);
3012 len = jio_vsnprintf(str, count, fmt, args);
3013 va_end(args);
3014 return len;
3015 }
3017 ATTRIBUTE_PRINTF(2,3)
3018 int jio_fprintf(FILE* f, const char *fmt, ...) {
3019 int len;
3020 va_list args;
3021 va_start(args, fmt);
3022 len = jio_vfprintf(f, fmt, args);
3023 va_end(args);
3024 return len;
3025 }
3027 ATTRIBUTE_PRINTF(2, 0)
3028 int jio_vfprintf(FILE* f, const char *fmt, va_list args) {
3029 if (Arguments::vfprintf_hook() != NULL) {
3030 return Arguments::vfprintf_hook()(f, fmt, args);
3031 } else {
3032 return vfprintf(f, fmt, args);
3033 }
3034 }
3036 ATTRIBUTE_PRINTF(1, 2)
3037 JNIEXPORT int jio_printf(const char *fmt, ...) {
3038 int len;
3039 va_list args;
3040 va_start(args, fmt);
3041 len = jio_vfprintf(defaultStream::output_stream(), fmt, args);
3042 va_end(args);
3043 return len;
3044 }
3047 // HotSpot specific jio method
3048 void jio_print(const char* s) {
3049 // Try to make this function as atomic as possible.
3050 if (Arguments::vfprintf_hook() != NULL) {
3051 jio_fprintf(defaultStream::output_stream(), "%s", s);
3052 } else {
3053 // Make an unused local variable to avoid warning from gcc 4.x compiler.
3054 size_t count = ::write(defaultStream::output_fd(), s, (int)strlen(s));
3055 }
3056 }
3058 } // Extern C
3060 // java.lang.Thread //////////////////////////////////////////////////////////////////////////////
3062 // In most of the JVM Thread support functions we need to be sure to lock the Threads_lock
3063 // to prevent the target thread from exiting after we have a pointer to the C++ Thread or
3064 // OSThread objects. The exception to this rule is when the target object is the thread
3065 // doing the operation, in which case we know that the thread won't exit until the
3066 // operation is done (all exits being voluntary). There are a few cases where it is
3067 // rather silly to do operations on yourself, like resuming yourself or asking whether
3068 // you are alive. While these can still happen, they are not subject to deadlocks if
3069 // the lock is held while the operation occurs (this is not the case for suspend, for
3070 // instance), and are very unlikely. Because IsAlive needs to be fast and its
3071 // implementation is local to this file, we always lock Threads_lock for that one.
3073 static void thread_entry(JavaThread* thread, TRAPS) {
3074 HandleMark hm(THREAD);
3075 Handle obj(THREAD, thread->threadObj());
3076 JavaValue result(T_VOID);
3077 JavaCalls::call_virtual(&result,
3078 obj,
3079 KlassHandle(THREAD, SystemDictionary::Thread_klass()),
3080 vmSymbols::run_method_name(),
3081 vmSymbols::void_method_signature(),
3082 THREAD);
3083 }
3086 JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
3087 JVMWrapper("JVM_StartThread");
3088 JavaThread *native_thread = NULL;
3090 // We cannot hold the Threads_lock when we throw an exception,
3091 // due to rank ordering issues. Example: we might need to grab the
3092 // Heap_lock while we construct the exception.
3093 bool throw_illegal_thread_state = false;
3095 // We must release the Threads_lock before we can post a jvmti event
3096 // in Thread::start.
3097 {
3098 // Ensure that the C++ Thread and OSThread structures aren't freed before
3099 // we operate.
3100 MutexLocker mu(Threads_lock);
3102 // Since JDK 5 the java.lang.Thread threadStatus is used to prevent
3103 // re-starting an already started thread, so we should usually find
3104 // that the JavaThread is null. However for a JNI attached thread
3105 // there is a small window between the Thread object being created
3106 // (with its JavaThread set) and the update to its threadStatus, so we
3107 // have to check for this
3108 if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
3109 throw_illegal_thread_state = true;
3110 } else {
3111 // We could also check the stillborn flag to see if this thread was already stopped, but
3112 // for historical reasons we let the thread detect that itself when it starts running
3114 jlong size =
3115 java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
3116 // Allocate the C++ Thread structure and create the native thread. The
3117 // stack size retrieved from java is signed, but the constructor takes
3118 // size_t (an unsigned type), so avoid passing negative values which would
3119 // result in really large stacks.
3120 size_t sz = size > 0 ? (size_t) size : 0;
3121 native_thread = new JavaThread(&thread_entry, sz);
3123 // At this point it may be possible that no osthread was created for the
3124 // JavaThread due to lack of memory. Check for this situation and throw
3125 // an exception if necessary. Eventually we may want to change this so
3126 // that we only grab the lock if the thread was created successfully -
3127 // then we can also do this check and throw the exception in the
3128 // JavaThread constructor.
3129 if (native_thread->osthread() != NULL) {
3130 // Note: the current thread is not being used within "prepare".
3131 native_thread->prepare(jthread);
3132 }
3133 }
3134 }
3136 if (throw_illegal_thread_state) {
3137 THROW(vmSymbols::java_lang_IllegalThreadStateException());
3138 }
3140 assert(native_thread != NULL, "Starting null thread?");
3142 if (native_thread->osthread() == NULL) {
3143 // No one should hold a reference to the 'native_thread'.
3144 delete native_thread;
3145 if (JvmtiExport::should_post_resource_exhausted()) {
3146 JvmtiExport::post_resource_exhausted(
3147 JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
3148 "unable to create new native thread");
3149 }
3150 THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
3151 "unable to create new native thread");
3152 }
3154 Thread::start(native_thread);
3156 JVM_END
3158 // JVM_Stop is implemented using a VM_Operation, so threads are forced to safepoints
3159 // before the quasi-asynchronous exception is delivered. This is a little obtrusive,
3160 // but is thought to be reliable and simple. In the case, where the receiver is the
3161 // same thread as the sender, no safepoint is needed.
3162 JVM_ENTRY(void, JVM_StopThread(JNIEnv* env, jobject jthread, jobject throwable))
3163 JVMWrapper("JVM_StopThread");
3165 oop java_throwable = JNIHandles::resolve(throwable);
3166 if (java_throwable == NULL) {
3167 THROW(vmSymbols::java_lang_NullPointerException());
3168 }
3169 oop java_thread = JNIHandles::resolve_non_null(jthread);
3170 JavaThread* receiver = java_lang_Thread::thread(java_thread);
3171 Events::log_exception(JavaThread::current(),
3172 "JVM_StopThread thread JavaThread " INTPTR_FORMAT " as oop " INTPTR_FORMAT " [exception " INTPTR_FORMAT "]",
3173 p2i(receiver), p2i((address)java_thread), p2i(throwable));
3174 // First check if thread is alive
3175 if (receiver != NULL) {
3176 // Check if exception is getting thrown at self (use oop equality, since the
3177 // target object might exit)
3178 if (java_thread == thread->threadObj()) {
3179 THROW_OOP(java_throwable);
3180 } else {
3181 // Enques a VM_Operation to stop all threads and then deliver the exception...
3182 Thread::send_async_exception(java_thread, JNIHandles::resolve(throwable));
3183 }
3184 }
3185 else {
3186 // Either:
3187 // - target thread has not been started before being stopped, or
3188 // - target thread already terminated
3189 // We could read the threadStatus to determine which case it is
3190 // but that is overkill as it doesn't matter. We must set the
3191 // stillborn flag for the first case, and if the thread has already
3192 // exited setting this flag has no affect
3193 java_lang_Thread::set_stillborn(java_thread);
3194 }
3195 JVM_END
3198 JVM_ENTRY(jboolean, JVM_IsThreadAlive(JNIEnv* env, jobject jthread))
3199 JVMWrapper("JVM_IsThreadAlive");
3201 oop thread_oop = JNIHandles::resolve_non_null(jthread);
3202 return java_lang_Thread::is_alive(thread_oop);
3203 JVM_END
3206 JVM_ENTRY(void, JVM_SuspendThread(JNIEnv* env, jobject jthread))
3207 JVMWrapper("JVM_SuspendThread");
3208 oop java_thread = JNIHandles::resolve_non_null(jthread);
3209 JavaThread* receiver = java_lang_Thread::thread(java_thread);
3211 if (receiver != NULL) {
3212 // thread has run and has not exited (still on threads list)
3214 {
3215 MutexLockerEx ml(receiver->SR_lock(), Mutex::_no_safepoint_check_flag);
3216 if (receiver->is_external_suspend()) {
3217 // Don't allow nested external suspend requests. We can't return
3218 // an error from this interface so just ignore the problem.
3219 return;
3220 }
3221 if (receiver->is_exiting()) { // thread is in the process of exiting
3222 return;
3223 }
3224 receiver->set_external_suspend();
3225 }
3227 // java_suspend() will catch threads in the process of exiting
3228 // and will ignore them.
3229 receiver->java_suspend();
3231 // It would be nice to have the following assertion in all the
3232 // time, but it is possible for a racing resume request to have
3233 // resumed this thread right after we suspended it. Temporarily
3234 // enable this assertion if you are chasing a different kind of
3235 // bug.
3236 //
3237 // assert(java_lang_Thread::thread(receiver->threadObj()) == NULL ||
3238 // receiver->is_being_ext_suspended(), "thread is not suspended");
3239 }
3240 JVM_END
3243 JVM_ENTRY(void, JVM_ResumeThread(JNIEnv* env, jobject jthread))
3244 JVMWrapper("JVM_ResumeThread");
3245 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate.
3246 // We need to *always* get the threads lock here, since this operation cannot be allowed during
3247 // a safepoint. The safepoint code relies on suspending a thread to examine its state. If other
3248 // threads randomly resumes threads, then a thread might not be suspended when the safepoint code
3249 // looks at it.
3250 MutexLocker ml(Threads_lock);
3251 JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3252 if (thr != NULL) {
3253 // the thread has run and is not in the process of exiting
3254 thr->java_resume();
3255 }
3256 JVM_END
3259 JVM_ENTRY(void, JVM_SetThreadPriority(JNIEnv* env, jobject jthread, jint prio))
3260 JVMWrapper("JVM_SetThreadPriority");
3261 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3262 MutexLocker ml(Threads_lock);
3263 oop java_thread = JNIHandles::resolve_non_null(jthread);
3264 java_lang_Thread::set_priority(java_thread, (ThreadPriority)prio);
3265 JavaThread* thr = java_lang_Thread::thread(java_thread);
3266 if (thr != NULL) { // Thread not yet started; priority pushed down when it is
3267 Thread::set_priority(thr, (ThreadPriority)prio);
3268 }
3269 JVM_END
3272 JVM_ENTRY(void, JVM_Yield(JNIEnv *env, jclass threadClass))
3273 JVMWrapper("JVM_Yield");
3274 if (os::dont_yield()) return;
3275 #ifndef USDT2
3276 HS_DTRACE_PROBE0(hotspot, thread__yield);
3277 #else /* USDT2 */
3278 HOTSPOT_THREAD_YIELD();
3279 #endif /* USDT2 */
3280 // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
3281 // Critical for similar threading behaviour
3282 if (ConvertYieldToSleep) {
3283 os::sleep(thread, MinSleepInterval, false);
3284 } else {
3285 os::yield();
3286 }
3287 JVM_END
3289 static void post_thread_sleep_event(EventThreadSleep* event, jlong millis) {
3290 assert(event != NULL, "invariant");
3291 assert(event->should_commit(), "invariant");
3292 event->set_time(millis);
3293 event->commit();
3294 }
3296 JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
3297 JVMWrapper("JVM_Sleep");
3299 if (millis < 0) {
3300 THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
3301 }
3303 if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
3304 THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3305 }
3307 // Save current thread state and restore it at the end of this block.
3308 // And set new thread state to SLEEPING.
3309 JavaThreadSleepState jtss(thread);
3311 #ifndef USDT2
3312 HS_DTRACE_PROBE1(hotspot, thread__sleep__begin, millis);
3313 #else /* USDT2 */
3314 HOTSPOT_THREAD_SLEEP_BEGIN(
3315 millis);
3316 #endif /* USDT2 */
3318 EventThreadSleep event;
3320 if (millis == 0) {
3321 // When ConvertSleepToYield is on, this matches the classic VM implementation of
3322 // JVM_Sleep. Critical for similar threading behaviour (Win32)
3323 // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
3324 // for SOLARIS
3325 if (ConvertSleepToYield) {
3326 os::yield();
3327 } else {
3328 ThreadState old_state = thread->osthread()->get_state();
3329 thread->osthread()->set_state(SLEEPING);
3330 os::sleep(thread, MinSleepInterval, false);
3331 thread->osthread()->set_state(old_state);
3332 }
3333 } else {
3334 ThreadState old_state = thread->osthread()->get_state();
3335 thread->osthread()->set_state(SLEEPING);
3336 if (os::sleep(thread, millis, true) == OS_INTRPT) {
3337 // An asynchronous exception (e.g., ThreadDeathException) could have been thrown on
3338 // us while we were sleeping. We do not overwrite those.
3339 if (!HAS_PENDING_EXCEPTION) {
3340 if (event.should_commit()) {
3341 post_thread_sleep_event(&event, millis);
3342 }
3343 #ifndef USDT2
3344 HS_DTRACE_PROBE1(hotspot, thread__sleep__end,1);
3345 #else /* USDT2 */
3346 HOTSPOT_THREAD_SLEEP_END(
3347 1);
3348 #endif /* USDT2 */
3349 // TODO-FIXME: THROW_MSG returns which means we will not call set_state()
3350 // to properly restore the thread state. That's likely wrong.
3351 THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
3352 }
3353 }
3354 thread->osthread()->set_state(old_state);
3355 }
3356 if (event.should_commit()) {
3357 post_thread_sleep_event(&event, millis);
3358 }
3359 #ifndef USDT2
3360 HS_DTRACE_PROBE1(hotspot, thread__sleep__end,0);
3361 #else /* USDT2 */
3362 HOTSPOT_THREAD_SLEEP_END(
3363 0);
3364 #endif /* USDT2 */
3365 JVM_END
3367 JVM_ENTRY(jobject, JVM_CurrentThread(JNIEnv* env, jclass threadClass))
3368 JVMWrapper("JVM_CurrentThread");
3369 oop jthread = thread->threadObj();
3370 assert (thread != NULL, "no current thread!");
3371 return JNIHandles::make_local(env, jthread);
3372 JVM_END
3375 JVM_ENTRY(jint, JVM_CountStackFrames(JNIEnv* env, jobject jthread))
3376 JVMWrapper("JVM_CountStackFrames");
3378 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3379 oop java_thread = JNIHandles::resolve_non_null(jthread);
3380 bool throw_illegal_thread_state = false;
3381 int count = 0;
3383 {
3384 MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3385 // We need to re-resolve the java_thread, since a GC might have happened during the
3386 // acquire of the lock
3387 JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3389 if (thr == NULL) {
3390 // do nothing
3391 } else if(! thr->is_external_suspend() || ! thr->frame_anchor()->walkable()) {
3392 // Check whether this java thread has been suspended already. If not, throws
3393 // IllegalThreadStateException. We defer to throw that exception until
3394 // Threads_lock is released since loading exception class has to leave VM.
3395 // The correct way to test a thread is actually suspended is
3396 // wait_for_ext_suspend_completion(), but we can't call that while holding
3397 // the Threads_lock. The above tests are sufficient for our purposes
3398 // provided the walkability of the stack is stable - which it isn't
3399 // 100% but close enough for most practical purposes.
3400 throw_illegal_thread_state = true;
3401 } else {
3402 // Count all java activation, i.e., number of vframes
3403 for(vframeStream vfst(thr); !vfst.at_end(); vfst.next()) {
3404 // Native frames are not counted
3405 if (!vfst.method()->is_native()) count++;
3406 }
3407 }
3408 }
3410 if (throw_illegal_thread_state) {
3411 THROW_MSG_0(vmSymbols::java_lang_IllegalThreadStateException(),
3412 "this thread is not suspended");
3413 }
3414 return count;
3415 JVM_END
3417 // Consider: A better way to implement JVM_Interrupt() is to acquire
3418 // Threads_lock to resolve the jthread into a Thread pointer, fetch
3419 // Thread->platformevent, Thread->native_thr, Thread->parker, etc.,
3420 // drop Threads_lock, and the perform the unpark() and thr_kill() operations
3421 // outside the critical section. Threads_lock is hot so we want to minimize
3422 // the hold-time. A cleaner interface would be to decompose interrupt into
3423 // two steps. The 1st phase, performed under Threads_lock, would return
3424 // a closure that'd be invoked after Threads_lock was dropped.
3425 // This tactic is safe as PlatformEvent and Parkers are type-stable (TSM) and
3426 // admit spurious wakeups.
3428 JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
3429 JVMWrapper("JVM_Interrupt");
3431 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3432 oop java_thread = JNIHandles::resolve_non_null(jthread);
3433 MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3434 // We need to re-resolve the java_thread, since a GC might have happened during the
3435 // acquire of the lock
3436 JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3437 if (thr != NULL) {
3438 Thread::interrupt(thr);
3439 }
3440 JVM_END
3443 JVM_QUICK_ENTRY(jboolean, JVM_IsInterrupted(JNIEnv* env, jobject jthread, jboolean clear_interrupted))
3444 JVMWrapper("JVM_IsInterrupted");
3446 // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
3447 oop java_thread = JNIHandles::resolve_non_null(jthread);
3448 MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
3449 // We need to re-resolve the java_thread, since a GC might have happened during the
3450 // acquire of the lock
3451 JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
3452 if (thr == NULL) {
3453 return JNI_FALSE;
3454 } else {
3455 return (jboolean) Thread::is_interrupted(thr, clear_interrupted != 0);
3456 }
3457 JVM_END
3460 // Return true iff the current thread has locked the object passed in
3462 JVM_ENTRY(jboolean, JVM_HoldsLock(JNIEnv* env, jclass threadClass, jobject obj))
3463 JVMWrapper("JVM_HoldsLock");
3464 assert(THREAD->is_Java_thread(), "sanity check");
3465 if (obj == NULL) {
3466 THROW_(vmSymbols::java_lang_NullPointerException(), JNI_FALSE);
3467 }
3468 Handle h_obj(THREAD, JNIHandles::resolve(obj));
3469 return ObjectSynchronizer::current_thread_holds_lock((JavaThread*)THREAD, h_obj);
3470 JVM_END
3473 JVM_ENTRY(void, JVM_DumpAllStacks(JNIEnv* env, jclass))
3474 JVMWrapper("JVM_DumpAllStacks");
3475 VM_PrintThreads op;
3476 VMThread::execute(&op);
3477 if (JvmtiExport::should_post_data_dump()) {
3478 JvmtiExport::post_data_dump();
3479 }
3480 JVM_END
3482 JVM_ENTRY(void, JVM_SetNativeThreadName(JNIEnv* env, jobject jthread, jstring name))
3483 JVMWrapper("JVM_SetNativeThreadName");
3484 ResourceMark rm(THREAD);
3485 oop java_thread = JNIHandles::resolve_non_null(jthread);
3486 JavaThread* thr = java_lang_Thread::thread(java_thread);
3487 // Thread naming only supported for the current thread, doesn't work for
3488 // target threads.
3489 if (Thread::current() == thr && !thr->has_attached_via_jni()) {
3490 // we don't set the name of an attached thread to avoid stepping
3491 // on other programs
3492 const char *thread_name = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3493 os::set_native_thread_name(thread_name);
3494 }
3495 JVM_END
3497 // java.lang.SecurityManager ///////////////////////////////////////////////////////////////////////
3499 static bool is_trusted_frame(JavaThread* jthread, vframeStream* vfst) {
3500 assert(jthread->is_Java_thread(), "must be a Java thread");
3501 if (jthread->privileged_stack_top() == NULL) return false;
3502 if (jthread->privileged_stack_top()->frame_id() == vfst->frame_id()) {
3503 oop loader = jthread->privileged_stack_top()->class_loader();
3504 if (loader == NULL) return true;
3505 bool trusted = java_lang_ClassLoader::is_trusted_loader(loader);
3506 if (trusted) return true;
3507 }
3508 return false;
3509 }
3511 JVM_ENTRY(jclass, JVM_CurrentLoadedClass(JNIEnv *env))
3512 JVMWrapper("JVM_CurrentLoadedClass");
3513 ResourceMark rm(THREAD);
3515 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3516 // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3517 bool trusted = is_trusted_frame(thread, &vfst);
3518 if (trusted) return NULL;
3520 Method* m = vfst.method();
3521 if (!m->is_native()) {
3522 InstanceKlass* holder = m->method_holder();
3523 oop loader = holder->class_loader();
3524 if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3525 return (jclass) JNIHandles::make_local(env, holder->java_mirror());
3526 }
3527 }
3528 }
3529 return NULL;
3530 JVM_END
3533 JVM_ENTRY(jobject, JVM_CurrentClassLoader(JNIEnv *env))
3534 JVMWrapper("JVM_CurrentClassLoader");
3535 ResourceMark rm(THREAD);
3537 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3539 // if a method in a class in a trusted loader is in a doPrivileged, return NULL
3540 bool trusted = is_trusted_frame(thread, &vfst);
3541 if (trusted) return NULL;
3543 Method* m = vfst.method();
3544 if (!m->is_native()) {
3545 InstanceKlass* holder = m->method_holder();
3546 assert(holder->is_klass(), "just checking");
3547 oop loader = holder->class_loader();
3548 if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3549 return JNIHandles::make_local(env, loader);
3550 }
3551 }
3552 }
3553 return NULL;
3554 JVM_END
3557 JVM_ENTRY(jobjectArray, JVM_GetClassContext(JNIEnv *env))
3558 JVMWrapper("JVM_GetClassContext");
3559 ResourceMark rm(THREAD);
3560 JvmtiVMObjectAllocEventCollector oam;
3561 vframeStream vfst(thread);
3563 if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
3564 // This must only be called from SecurityManager.getClassContext
3565 Method* m = vfst.method();
3566 if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
3567 m->name() == vmSymbols::getClassContext_name() &&
3568 m->signature() == vmSymbols::void_class_array_signature())) {
3569 THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
3570 }
3571 }
3573 // Collect method holders
3574 GrowableArray<KlassHandle>* klass_array = new GrowableArray<KlassHandle>();
3575 for (; !vfst.at_end(); vfst.security_next()) {
3576 Method* m = vfst.method();
3577 // Native frames are not returned
3578 if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
3579 Klass* holder = m->method_holder();
3580 assert(holder->is_klass(), "just checking");
3581 klass_array->append(holder);
3582 }
3583 }
3585 // Create result array of type [Ljava/lang/Class;
3586 objArrayOop result = oopFactory::new_objArray(SystemDictionary::Class_klass(), klass_array->length(), CHECK_NULL);
3587 // Fill in mirrors corresponding to method holders
3588 for (int i = 0; i < klass_array->length(); i++) {
3589 result->obj_at_put(i, klass_array->at(i)->java_mirror());
3590 }
3592 return (jobjectArray) JNIHandles::make_local(env, result);
3593 JVM_END
3596 JVM_ENTRY(jint, JVM_ClassDepth(JNIEnv *env, jstring name))
3597 JVMWrapper("JVM_ClassDepth");
3598 ResourceMark rm(THREAD);
3599 Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
3600 Handle class_name_str = java_lang_String::internalize_classname(h_name, CHECK_0);
3602 const char* str = java_lang_String::as_utf8_string(class_name_str());
3603 TempNewSymbol class_name_sym = SymbolTable::probe(str, (int)strlen(str));
3604 if (class_name_sym == NULL) {
3605 return -1;
3606 }
3608 int depth = 0;
3610 for(vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3611 if (!vfst.method()->is_native()) {
3612 InstanceKlass* holder = vfst.method()->method_holder();
3613 assert(holder->is_klass(), "just checking");
3614 if (holder->name() == class_name_sym) {
3615 return depth;
3616 }
3617 depth++;
3618 }
3619 }
3620 return -1;
3621 JVM_END
3624 JVM_ENTRY(jint, JVM_ClassLoaderDepth(JNIEnv *env))
3625 JVMWrapper("JVM_ClassLoaderDepth");
3626 ResourceMark rm(THREAD);
3627 int depth = 0;
3628 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3629 // if a method in a class in a trusted loader is in a doPrivileged, return -1
3630 bool trusted = is_trusted_frame(thread, &vfst);
3631 if (trusted) return -1;
3633 Method* m = vfst.method();
3634 if (!m->is_native()) {
3635 InstanceKlass* holder = m->method_holder();
3636 assert(holder->is_klass(), "just checking");
3637 oop loader = holder->class_loader();
3638 if (loader != NULL && !java_lang_ClassLoader::is_trusted_loader(loader)) {
3639 return depth;
3640 }
3641 depth++;
3642 }
3643 }
3644 return -1;
3645 JVM_END
3648 // java.lang.Package ////////////////////////////////////////////////////////////////
3651 JVM_ENTRY(jstring, JVM_GetSystemPackage(JNIEnv *env, jstring name))
3652 JVMWrapper("JVM_GetSystemPackage");
3653 ResourceMark rm(THREAD);
3654 JvmtiVMObjectAllocEventCollector oam;
3655 char* str = java_lang_String::as_utf8_string(JNIHandles::resolve_non_null(name));
3656 oop result = ClassLoader::get_system_package(str, CHECK_NULL);
3657 return (jstring) JNIHandles::make_local(result);
3658 JVM_END
3661 JVM_ENTRY(jobjectArray, JVM_GetSystemPackages(JNIEnv *env))
3662 JVMWrapper("JVM_GetSystemPackages");
3663 JvmtiVMObjectAllocEventCollector oam;
3664 objArrayOop result = ClassLoader::get_system_packages(CHECK_NULL);
3665 return (jobjectArray) JNIHandles::make_local(result);
3666 JVM_END
3669 // ObjectInputStream ///////////////////////////////////////////////////////////////
3671 bool force_verify_field_access(Klass* current_class, Klass* field_class, AccessFlags access, bool classloader_only) {
3672 if (current_class == NULL) {
3673 return true;
3674 }
3675 if ((current_class == field_class) || access.is_public()) {
3676 return true;
3677 }
3679 if (access.is_protected()) {
3680 // See if current_class is a subclass of field_class
3681 if (current_class->is_subclass_of(field_class)) {
3682 return true;
3683 }
3684 }
3686 return (!access.is_private() && InstanceKlass::cast(current_class)->is_same_class_package(field_class));
3687 }
3690 // JVM_AllocateNewObject and JVM_AllocateNewArray are unused as of 1.4
3691 JVM_ENTRY(jobject, JVM_AllocateNewObject(JNIEnv *env, jobject receiver, jclass currClass, jclass initClass))
3692 JVMWrapper("JVM_AllocateNewObject");
3693 JvmtiVMObjectAllocEventCollector oam;
3694 // Receiver is not used
3695 oop curr_mirror = JNIHandles::resolve_non_null(currClass);
3696 oop init_mirror = JNIHandles::resolve_non_null(initClass);
3698 // Cannot instantiate primitive types
3699 if (java_lang_Class::is_primitive(curr_mirror) || java_lang_Class::is_primitive(init_mirror)) {
3700 ResourceMark rm(THREAD);
3701 THROW_0(vmSymbols::java_lang_InvalidClassException());
3702 }
3704 // Arrays not allowed here, must use JVM_AllocateNewArray
3705 if (java_lang_Class::as_Klass(curr_mirror)->oop_is_array() ||
3706 java_lang_Class::as_Klass(init_mirror)->oop_is_array()) {
3707 ResourceMark rm(THREAD);
3708 THROW_0(vmSymbols::java_lang_InvalidClassException());
3709 }
3711 instanceKlassHandle curr_klass (THREAD, java_lang_Class::as_Klass(curr_mirror));
3712 instanceKlassHandle init_klass (THREAD, java_lang_Class::as_Klass(init_mirror));
3714 assert(curr_klass->is_subclass_of(init_klass()), "just checking");
3716 // Interfaces, abstract classes, and java.lang.Class classes cannot be instantiated directly.
3717 curr_klass->check_valid_for_instantiation(false, CHECK_NULL);
3719 // Make sure klass is initialized, since we are about to instantiate one of them.
3720 curr_klass->initialize(CHECK_NULL);
3722 methodHandle m (THREAD,
3723 init_klass->find_method(vmSymbols::object_initializer_name(),
3724 vmSymbols::void_method_signature()));
3725 if (m.is_null()) {
3726 ResourceMark rm(THREAD);
3727 THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(),
3728 Method::name_and_sig_as_C_string(init_klass(),
3729 vmSymbols::object_initializer_name(),
3730 vmSymbols::void_method_signature()));
3731 }
3733 if (curr_klass == init_klass && !m->is_public()) {
3734 // Calling the constructor for class 'curr_klass'.
3735 // Only allow calls to a public no-arg constructor.
3736 // This path corresponds to creating an Externalizable object.
3737 THROW_0(vmSymbols::java_lang_IllegalAccessException());
3738 }
3740 if (!force_verify_field_access(curr_klass(), init_klass(), m->access_flags(), false)) {
3741 // subclass 'curr_klass' does not have access to no-arg constructor of 'initcb'
3742 THROW_0(vmSymbols::java_lang_IllegalAccessException());
3743 }
3745 Handle obj = curr_klass->allocate_instance_handle(CHECK_NULL);
3746 // Call constructor m. This might call a constructor higher up in the hierachy
3747 JavaCalls::call_default_constructor(thread, m, obj, CHECK_NULL);
3749 return JNIHandles::make_local(obj());
3750 JVM_END
3753 JVM_ENTRY(jobject, JVM_AllocateNewArray(JNIEnv *env, jobject obj, jclass currClass, jint length))
3754 JVMWrapper("JVM_AllocateNewArray");
3755 JvmtiVMObjectAllocEventCollector oam;
3756 oop mirror = JNIHandles::resolve_non_null(currClass);
3758 if (java_lang_Class::is_primitive(mirror)) {
3759 THROW_0(vmSymbols::java_lang_InvalidClassException());
3760 }
3761 Klass* k = java_lang_Class::as_Klass(mirror);
3762 oop result;
3764 if (k->oop_is_typeArray()) {
3765 // typeArray
3766 result = TypeArrayKlass::cast(k)->allocate(length, CHECK_NULL);
3767 } else if (k->oop_is_objArray()) {
3768 // objArray
3769 ObjArrayKlass* oak = ObjArrayKlass::cast(k);
3770 oak->initialize(CHECK_NULL); // make sure class is initialized (matches Classic VM behavior)
3771 result = oak->allocate(length, CHECK_NULL);
3772 } else {
3773 THROW_0(vmSymbols::java_lang_InvalidClassException());
3774 }
3775 return JNIHandles::make_local(env, result);
3776 JVM_END
3779 // Returns first non-privileged class loader on the stack (excluding reflection
3780 // generated frames) or null if only classes loaded by the boot class loader
3781 // and extension class loader are found on the stack.
3783 JVM_ENTRY(jobject, JVM_LatestUserDefinedLoader(JNIEnv *env))
3784 for (vframeStream vfst(thread); !vfst.at_end(); vfst.next()) {
3785 // UseNewReflection
3786 vfst.skip_reflection_related_frames(); // Only needed for 1.4 reflection
3787 oop loader = vfst.method()->method_holder()->class_loader();
3788 if (loader != NULL && !SystemDictionary::is_ext_class_loader(loader)) {
3789 return JNIHandles::make_local(env, loader);
3790 }
3791 }
3792 return NULL;
3793 JVM_END
3796 // Load a class relative to the most recent class on the stack with a non-null
3797 // classloader.
3798 // This function has been deprecated and should not be considered part of the
3799 // specified JVM interface.
3801 JVM_ENTRY(jclass, JVM_LoadClass0(JNIEnv *env, jobject receiver,
3802 jclass currClass, jstring currClassName))
3803 JVMWrapper("JVM_LoadClass0");
3804 // Receiver is not used
3805 ResourceMark rm(THREAD);
3807 // Class name argument is not guaranteed to be in internal format
3808 Handle classname (THREAD, JNIHandles::resolve_non_null(currClassName));
3809 Handle string = java_lang_String::internalize_classname(classname, CHECK_NULL);
3811 const char* str = java_lang_String::as_utf8_string(string());
3813 if (str == NULL || (int)strlen(str) > Symbol::max_length()) {
3814 // It's impossible to create this class; the name cannot fit
3815 // into the constant pool.
3816 THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), str);
3817 }
3819 TempNewSymbol name = SymbolTable::new_symbol(str, CHECK_NULL);
3820 Handle curr_klass (THREAD, JNIHandles::resolve(currClass));
3821 // Find the most recent class on the stack with a non-null classloader
3822 oop loader = NULL;
3823 oop protection_domain = NULL;
3824 if (curr_klass.is_null()) {
3825 for (vframeStream vfst(thread);
3826 !vfst.at_end() && loader == NULL;
3827 vfst.next()) {
3828 if (!vfst.method()->is_native()) {
3829 InstanceKlass* holder = vfst.method()->method_holder();
3830 loader = holder->class_loader();
3831 protection_domain = holder->protection_domain();
3832 }
3833 }
3834 } else {
3835 Klass* curr_klass_oop = java_lang_Class::as_Klass(curr_klass());
3836 loader = InstanceKlass::cast(curr_klass_oop)->class_loader();
3837 protection_domain = InstanceKlass::cast(curr_klass_oop)->protection_domain();
3838 }
3839 Handle h_loader(THREAD, loader);
3840 Handle h_prot (THREAD, protection_domain);
3841 jclass result = find_class_from_class_loader(env, name, true, h_loader, h_prot,
3842 false, thread);
3843 if (TraceClassResolution && result != NULL) {
3844 trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
3845 }
3846 return result;
3847 JVM_END
3850 // Array ///////////////////////////////////////////////////////////////////////////////////////////
3853 // resolve array handle and check arguments
3854 static inline arrayOop check_array(JNIEnv *env, jobject arr, bool type_array_only, TRAPS) {
3855 if (arr == NULL) {
3856 THROW_0(vmSymbols::java_lang_NullPointerException());
3857 }
3858 oop a = JNIHandles::resolve_non_null(arr);
3859 if (!a->is_array() || (type_array_only && !a->is_typeArray())) {
3860 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "Argument is not an array");
3861 }
3862 return arrayOop(a);
3863 }
3866 JVM_ENTRY(jint, JVM_GetArrayLength(JNIEnv *env, jobject arr))
3867 JVMWrapper("JVM_GetArrayLength");
3868 arrayOop a = check_array(env, arr, false, CHECK_0);
3869 return a->length();
3870 JVM_END
3873 JVM_ENTRY(jobject, JVM_GetArrayElement(JNIEnv *env, jobject arr, jint index))
3874 JVMWrapper("JVM_Array_Get");
3875 JvmtiVMObjectAllocEventCollector oam;
3876 arrayOop a = check_array(env, arr, false, CHECK_NULL);
3877 jvalue value;
3878 BasicType type = Reflection::array_get(&value, a, index, CHECK_NULL);
3879 oop box = Reflection::box(&value, type, CHECK_NULL);
3880 return JNIHandles::make_local(env, box);
3881 JVM_END
3884 JVM_ENTRY(jvalue, JVM_GetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jint wCode))
3885 JVMWrapper("JVM_GetPrimitiveArrayElement");
3886 jvalue value;
3887 value.i = 0; // to initialize value before getting used in CHECK
3888 arrayOop a = check_array(env, arr, true, CHECK_(value));
3889 assert(a->is_typeArray(), "just checking");
3890 BasicType type = Reflection::array_get(&value, a, index, CHECK_(value));
3891 BasicType wide_type = (BasicType) wCode;
3892 if (type != wide_type) {
3893 Reflection::widen(&value, type, wide_type, CHECK_(value));
3894 }
3895 return value;
3896 JVM_END
3899 JVM_ENTRY(void, JVM_SetArrayElement(JNIEnv *env, jobject arr, jint index, jobject val))
3900 JVMWrapper("JVM_SetArrayElement");
3901 arrayOop a = check_array(env, arr, false, CHECK);
3902 oop box = JNIHandles::resolve(val);
3903 jvalue value;
3904 value.i = 0; // to initialize value before getting used in CHECK
3905 BasicType value_type;
3906 if (a->is_objArray()) {
3907 // Make sure we do no unbox e.g. java/lang/Integer instances when storing into an object array
3908 value_type = Reflection::unbox_for_regular_object(box, &value);
3909 } else {
3910 value_type = Reflection::unbox_for_primitive(box, &value, CHECK);
3911 }
3912 Reflection::array_set(&value, a, index, value_type, CHECK);
3913 JVM_END
3916 JVM_ENTRY(void, JVM_SetPrimitiveArrayElement(JNIEnv *env, jobject arr, jint index, jvalue v, unsigned char vCode))
3917 JVMWrapper("JVM_SetPrimitiveArrayElement");
3918 arrayOop a = check_array(env, arr, true, CHECK);
3919 assert(a->is_typeArray(), "just checking");
3920 BasicType value_type = (BasicType) vCode;
3921 Reflection::array_set(&v, a, index, value_type, CHECK);
3922 JVM_END
3925 JVM_ENTRY(jobject, JVM_NewArray(JNIEnv *env, jclass eltClass, jint length))
3926 JVMWrapper("JVM_NewArray");
3927 JvmtiVMObjectAllocEventCollector oam;
3928 oop element_mirror = JNIHandles::resolve(eltClass);
3929 oop result = Reflection::reflect_new_array(element_mirror, length, CHECK_NULL);
3930 return JNIHandles::make_local(env, result);
3931 JVM_END
3934 JVM_ENTRY(jobject, JVM_NewMultiArray(JNIEnv *env, jclass eltClass, jintArray dim))
3935 JVMWrapper("JVM_NewMultiArray");
3936 JvmtiVMObjectAllocEventCollector oam;
3937 arrayOop dim_array = check_array(env, dim, true, CHECK_NULL);
3938 oop element_mirror = JNIHandles::resolve(eltClass);
3939 assert(dim_array->is_typeArray(), "just checking");
3940 oop result = Reflection::reflect_new_multi_array(element_mirror, typeArrayOop(dim_array), CHECK_NULL);
3941 return JNIHandles::make_local(env, result);
3942 JVM_END
3945 // Networking library support ////////////////////////////////////////////////////////////////////
3947 JVM_LEAF(jint, JVM_InitializeSocketLibrary())
3948 JVMWrapper("JVM_InitializeSocketLibrary");
3949 return 0;
3950 JVM_END
3953 JVM_LEAF(jint, JVM_Socket(jint domain, jint type, jint protocol))
3954 JVMWrapper("JVM_Socket");
3955 return os::socket(domain, type, protocol);
3956 JVM_END
3959 JVM_LEAF(jint, JVM_SocketClose(jint fd))
3960 JVMWrapper2("JVM_SocketClose (0x%x)", fd);
3961 //%note jvm_r6
3962 return os::socket_close(fd);
3963 JVM_END
3966 JVM_LEAF(jint, JVM_SocketShutdown(jint fd, jint howto))
3967 JVMWrapper2("JVM_SocketShutdown (0x%x)", fd);
3968 //%note jvm_r6
3969 return os::socket_shutdown(fd, howto);
3970 JVM_END
3973 JVM_LEAF(jint, JVM_Recv(jint fd, char *buf, jint nBytes, jint flags))
3974 JVMWrapper2("JVM_Recv (0x%x)", fd);
3975 //%note jvm_r6
3976 return os::recv(fd, buf, (size_t)nBytes, (uint)flags);
3977 JVM_END
3980 JVM_LEAF(jint, JVM_Send(jint fd, char *buf, jint nBytes, jint flags))
3981 JVMWrapper2("JVM_Send (0x%x)", fd);
3982 //%note jvm_r6
3983 return os::send(fd, buf, (size_t)nBytes, (uint)flags);
3984 JVM_END
3987 JVM_LEAF(jint, JVM_Timeout(int fd, long timeout))
3988 JVMWrapper2("JVM_Timeout (0x%x)", fd);
3989 //%note jvm_r6
3990 return os::timeout(fd, timeout);
3991 JVM_END
3994 JVM_LEAF(jint, JVM_Listen(jint fd, jint count))
3995 JVMWrapper2("JVM_Listen (0x%x)", fd);
3996 //%note jvm_r6
3997 return os::listen(fd, count);
3998 JVM_END
4001 JVM_LEAF(jint, JVM_Connect(jint fd, struct sockaddr *him, jint len))
4002 JVMWrapper2("JVM_Connect (0x%x)", fd);
4003 //%note jvm_r6
4004 return os::connect(fd, him, (socklen_t)len);
4005 JVM_END
4008 JVM_LEAF(jint, JVM_Bind(jint fd, struct sockaddr *him, jint len))
4009 JVMWrapper2("JVM_Bind (0x%x)", fd);
4010 //%note jvm_r6
4011 return os::bind(fd, him, (socklen_t)len);
4012 JVM_END
4015 JVM_LEAF(jint, JVM_Accept(jint fd, struct sockaddr *him, jint *len))
4016 JVMWrapper2("JVM_Accept (0x%x)", fd);
4017 //%note jvm_r6
4018 socklen_t socklen = (socklen_t)(*len);
4019 jint result = os::accept(fd, him, &socklen);
4020 *len = (jint)socklen;
4021 return result;
4022 JVM_END
4025 JVM_LEAF(jint, JVM_RecvFrom(jint fd, char *buf, int nBytes, int flags, struct sockaddr *from, int *fromlen))
4026 JVMWrapper2("JVM_RecvFrom (0x%x)", fd);
4027 //%note jvm_r6
4028 socklen_t socklen = (socklen_t)(*fromlen);
4029 jint result = os::recvfrom(fd, buf, (size_t)nBytes, (uint)flags, from, &socklen);
4030 *fromlen = (int)socklen;
4031 return result;
4032 JVM_END
4035 JVM_LEAF(jint, JVM_GetSockName(jint fd, struct sockaddr *him, int *len))
4036 JVMWrapper2("JVM_GetSockName (0x%x)", fd);
4037 //%note jvm_r6
4038 socklen_t socklen = (socklen_t)(*len);
4039 jint result = os::get_sock_name(fd, him, &socklen);
4040 *len = (int)socklen;
4041 return result;
4042 JVM_END
4045 JVM_LEAF(jint, JVM_SendTo(jint fd, char *buf, int len, int flags, struct sockaddr *to, int tolen))
4046 JVMWrapper2("JVM_SendTo (0x%x)", fd);
4047 //%note jvm_r6
4048 return os::sendto(fd, buf, (size_t)len, (uint)flags, to, (socklen_t)tolen);
4049 JVM_END
4052 JVM_LEAF(jint, JVM_SocketAvailable(jint fd, jint *pbytes))
4053 JVMWrapper2("JVM_SocketAvailable (0x%x)", fd);
4054 //%note jvm_r6
4055 return os::socket_available(fd, pbytes);
4056 JVM_END
4059 JVM_LEAF(jint, JVM_GetSockOpt(jint fd, int level, int optname, char *optval, int *optlen))
4060 JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
4061 //%note jvm_r6
4062 socklen_t socklen = (socklen_t)(*optlen);
4063 jint result = os::get_sock_opt(fd, level, optname, optval, &socklen);
4064 *optlen = (int)socklen;
4065 return result;
4066 JVM_END
4069 JVM_LEAF(jint, JVM_SetSockOpt(jint fd, int level, int optname, const char *optval, int optlen))
4070 JVMWrapper2("JVM_GetSockOpt (0x%x)", fd);
4071 //%note jvm_r6
4072 return os::set_sock_opt(fd, level, optname, optval, (socklen_t)optlen);
4073 JVM_END
4076 JVM_LEAF(int, JVM_GetHostName(char* name, int namelen))
4077 JVMWrapper("JVM_GetHostName");
4078 return os::get_host_name(name, namelen);
4079 JVM_END
4082 // Library support ///////////////////////////////////////////////////////////////////////////
4084 JVM_ENTRY_NO_ENV(void*, JVM_LoadLibrary(const char* name))
4085 //%note jvm_ct
4086 JVMWrapper2("JVM_LoadLibrary (%s)", name);
4087 char ebuf[1024];
4088 void *load_result;
4089 {
4090 ThreadToNativeFromVM ttnfvm(thread);
4091 load_result = os::dll_load(name, ebuf, sizeof ebuf);
4092 }
4093 if (load_result == NULL) {
4094 char msg[1024];
4095 jio_snprintf(msg, sizeof msg, "%s: %s", name, ebuf);
4096 // Since 'ebuf' may contain a string encoded using
4097 // platform encoding scheme, we need to pass
4098 // Exceptions::unsafe_to_utf8 to the new_exception method
4099 // as the last argument. See bug 6367357.
4100 Handle h_exception =
4101 Exceptions::new_exception(thread,
4102 vmSymbols::java_lang_UnsatisfiedLinkError(),
4103 msg, Exceptions::unsafe_to_utf8);
4105 THROW_HANDLE_0(h_exception);
4106 }
4107 return load_result;
4108 JVM_END
4111 JVM_LEAF(void, JVM_UnloadLibrary(void* handle))
4112 JVMWrapper("JVM_UnloadLibrary");
4113 os::dll_unload(handle);
4114 JVM_END
4117 JVM_LEAF(void*, JVM_FindLibraryEntry(void* handle, const char* name))
4118 JVMWrapper2("JVM_FindLibraryEntry (%s)", name);
4119 return os::dll_lookup(handle, name);
4120 JVM_END
4123 // Floating point support ////////////////////////////////////////////////////////////////////
4125 JVM_LEAF(jboolean, JVM_IsNaN(jdouble a))
4126 JVMWrapper("JVM_IsNaN");
4127 return g_isnan(a);
4128 JVM_END
4131 // JNI version ///////////////////////////////////////////////////////////////////////////////
4133 JVM_LEAF(jboolean, JVM_IsSupportedJNIVersion(jint version))
4134 JVMWrapper2("JVM_IsSupportedJNIVersion (%d)", version);
4135 return Threads::is_supported_jni_version_including_1_1(version);
4136 JVM_END
4139 // String support ///////////////////////////////////////////////////////////////////////////
4141 JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
4142 JVMWrapper("JVM_InternString");
4143 JvmtiVMObjectAllocEventCollector oam;
4144 if (str == NULL) return NULL;
4145 oop string = JNIHandles::resolve_non_null(str);
4146 oop result = StringTable::intern(string, CHECK_NULL);
4147 return (jstring) JNIHandles::make_local(env, result);
4148 JVM_END
4151 // Raw monitor support //////////////////////////////////////////////////////////////////////
4153 // The lock routine below calls lock_without_safepoint_check in order to get a raw lock
4154 // without interfering with the safepoint mechanism. The routines are not JVM_LEAF because
4155 // they might be called by non-java threads. The JVM_LEAF installs a NoHandleMark check
4156 // that only works with java threads.
4159 JNIEXPORT void* JNICALL JVM_RawMonitorCreate(void) {
4160 VM_Exit::block_if_vm_exited();
4161 JVMWrapper("JVM_RawMonitorCreate");
4162 return new Mutex(Mutex::native, "JVM_RawMonitorCreate");
4163 }
4166 JNIEXPORT void JNICALL JVM_RawMonitorDestroy(void *mon) {
4167 VM_Exit::block_if_vm_exited();
4168 JVMWrapper("JVM_RawMonitorDestroy");
4169 delete ((Mutex*) mon);
4170 }
4173 JNIEXPORT jint JNICALL JVM_RawMonitorEnter(void *mon) {
4174 VM_Exit::block_if_vm_exited();
4175 JVMWrapper("JVM_RawMonitorEnter");
4176 ((Mutex*) mon)->jvm_raw_lock();
4177 return 0;
4178 }
4181 JNIEXPORT void JNICALL JVM_RawMonitorExit(void *mon) {
4182 VM_Exit::block_if_vm_exited();
4183 JVMWrapper("JVM_RawMonitorExit");
4184 ((Mutex*) mon)->jvm_raw_unlock();
4185 }
4188 // Support for Serialization
4190 typedef jfloat (JNICALL *IntBitsToFloatFn )(JNIEnv* env, jclass cb, jint value);
4191 typedef jdouble (JNICALL *LongBitsToDoubleFn)(JNIEnv* env, jclass cb, jlong value);
4192 typedef jint (JNICALL *FloatToIntBitsFn )(JNIEnv* env, jclass cb, jfloat value);
4193 typedef jlong (JNICALL *DoubleToLongBitsFn)(JNIEnv* env, jclass cb, jdouble value);
4195 static IntBitsToFloatFn int_bits_to_float_fn = NULL;
4196 static LongBitsToDoubleFn long_bits_to_double_fn = NULL;
4197 static FloatToIntBitsFn float_to_int_bits_fn = NULL;
4198 static DoubleToLongBitsFn double_to_long_bits_fn = NULL;
4201 void initialize_converter_functions() {
4202 if (JDK_Version::is_gte_jdk14x_version()) {
4203 // These functions only exist for compatibility with 1.3.1 and earlier
4204 return;
4205 }
4207 // called from universe_post_init()
4208 assert(
4209 int_bits_to_float_fn == NULL &&
4210 long_bits_to_double_fn == NULL &&
4211 float_to_int_bits_fn == NULL &&
4212 double_to_long_bits_fn == NULL ,
4213 "initialization done twice"
4214 );
4215 // initialize
4216 int_bits_to_float_fn = CAST_TO_FN_PTR(IntBitsToFloatFn , NativeLookup::base_library_lookup("java/lang/Float" , "intBitsToFloat" , "(I)F"));
4217 long_bits_to_double_fn = CAST_TO_FN_PTR(LongBitsToDoubleFn, NativeLookup::base_library_lookup("java/lang/Double", "longBitsToDouble", "(J)D"));
4218 float_to_int_bits_fn = CAST_TO_FN_PTR(FloatToIntBitsFn , NativeLookup::base_library_lookup("java/lang/Float" , "floatToIntBits" , "(F)I"));
4219 double_to_long_bits_fn = CAST_TO_FN_PTR(DoubleToLongBitsFn, NativeLookup::base_library_lookup("java/lang/Double", "doubleToLongBits", "(D)J"));
4220 // verify
4221 assert(
4222 int_bits_to_float_fn != NULL &&
4223 long_bits_to_double_fn != NULL &&
4224 float_to_int_bits_fn != NULL &&
4225 double_to_long_bits_fn != NULL ,
4226 "initialization failed"
4227 );
4228 }
4232 // Shared JNI/JVM entry points //////////////////////////////////////////////////////////////
4234 jclass find_class_from_class_loader(JNIEnv* env, Symbol* name, jboolean init,
4235 Handle loader, Handle protection_domain,
4236 jboolean throwError, TRAPS) {
4237 // Security Note:
4238 // The Java level wrapper will perform the necessary security check allowing
4239 // us to pass the NULL as the initiating class loader. The VM is responsible for
4240 // the checkPackageAccess relative to the initiating class loader via the
4241 // protection_domain. The protection_domain is passed as NULL by the java code
4242 // if there is no security manager in 3-arg Class.forName().
4243 Klass* klass = SystemDictionary::resolve_or_fail(name, loader, protection_domain, throwError != 0, CHECK_NULL);
4245 KlassHandle klass_handle(THREAD, klass);
4246 // Check if we should initialize the class
4247 if (init && klass_handle->oop_is_instance()) {
4248 klass_handle->initialize(CHECK_NULL);
4249 }
4250 return (jclass) JNIHandles::make_local(env, klass_handle->java_mirror());
4251 }
4254 // Internal SQE debugging support ///////////////////////////////////////////////////////////
4256 #ifndef PRODUCT
4258 extern "C" {
4259 JNIEXPORT jboolean JNICALL JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get);
4260 JNIEXPORT jboolean JNICALL JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get);
4261 JNIEXPORT void JNICALL JVM_VMBreakPoint(JNIEnv *env, jobject obj);
4262 }
4264 JVM_LEAF(jboolean, JVM_AccessVMBooleanFlag(const char* name, jboolean* value, jboolean is_get))
4265 JVMWrapper("JVM_AccessBoolVMFlag");
4266 return is_get ? CommandLineFlags::boolAt((char*) name, (bool*) value) : CommandLineFlags::boolAtPut((char*) name, (bool*) value, Flag::INTERNAL);
4267 JVM_END
4269 JVM_LEAF(jboolean, JVM_AccessVMIntFlag(const char* name, jint* value, jboolean is_get))
4270 JVMWrapper("JVM_AccessVMIntFlag");
4271 intx v;
4272 jboolean result = is_get ? CommandLineFlags::intxAt((char*) name, &v) : CommandLineFlags::intxAtPut((char*) name, &v, Flag::INTERNAL);
4273 *value = (jint)v;
4274 return result;
4275 JVM_END
4278 JVM_ENTRY(void, JVM_VMBreakPoint(JNIEnv *env, jobject obj))
4279 JVMWrapper("JVM_VMBreakPoint");
4280 oop the_obj = JNIHandles::resolve(obj);
4281 BREAKPOINT;
4282 JVM_END
4285 #endif
4288 // Method ///////////////////////////////////////////////////////////////////////////////////////////
4290 JVM_ENTRY(jobject, JVM_InvokeMethod(JNIEnv *env, jobject method, jobject obj, jobjectArray args0))
4291 JVMWrapper("JVM_InvokeMethod");
4292 Handle method_handle;
4293 if (thread->stack_available((address) &method_handle) >= JVMInvokeMethodSlack) {
4294 method_handle = Handle(THREAD, JNIHandles::resolve(method));
4295 Handle receiver(THREAD, JNIHandles::resolve(obj));
4296 objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4297 oop result = Reflection::invoke_method(method_handle(), receiver, args, CHECK_NULL);
4298 jobject res = JNIHandles::make_local(env, result);
4299 if (JvmtiExport::should_post_vm_object_alloc()) {
4300 oop ret_type = java_lang_reflect_Method::return_type(method_handle());
4301 assert(ret_type != NULL, "sanity check: ret_type oop must not be NULL!");
4302 if (java_lang_Class::is_primitive(ret_type)) {
4303 // Only for primitive type vm allocates memory for java object.
4304 // See box() method.
4305 JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4306 }
4307 }
4308 return res;
4309 } else {
4310 THROW_0(vmSymbols::java_lang_StackOverflowError());
4311 }
4312 JVM_END
4315 JVM_ENTRY(jobject, JVM_NewInstanceFromConstructor(JNIEnv *env, jobject c, jobjectArray args0))
4316 JVMWrapper("JVM_NewInstanceFromConstructor");
4317 oop constructor_mirror = JNIHandles::resolve(c);
4318 objArrayHandle args(THREAD, objArrayOop(JNIHandles::resolve(args0)));
4319 oop result = Reflection::invoke_constructor(constructor_mirror, args, CHECK_NULL);
4320 jobject res = JNIHandles::make_local(env, result);
4321 if (JvmtiExport::should_post_vm_object_alloc()) {
4322 JvmtiExport::post_vm_object_alloc(JavaThread::current(), result);
4323 }
4324 return res;
4325 JVM_END
4327 // Atomic ///////////////////////////////////////////////////////////////////////////////////////////
4329 JVM_LEAF(jboolean, JVM_SupportsCX8())
4330 JVMWrapper("JVM_SupportsCX8");
4331 return VM_Version::supports_cx8();
4332 JVM_END
4335 JVM_ENTRY(jboolean, JVM_CX8Field(JNIEnv *env, jobject obj, jfieldID fid, jlong oldVal, jlong newVal))
4336 JVMWrapper("JVM_CX8Field");
4337 jlong res;
4338 oop o = JNIHandles::resolve(obj);
4339 intptr_t fldOffs = jfieldIDWorkaround::from_instance_jfieldID(o->klass(), fid);
4340 volatile jlong* addr = (volatile jlong*)((address)o + fldOffs);
4342 assert(VM_Version::supports_cx8(), "cx8 not supported");
4343 res = Atomic::cmpxchg(newVal, addr, oldVal);
4345 return res == oldVal;
4346 JVM_END
4348 // DTrace ///////////////////////////////////////////////////////////////////
4350 JVM_ENTRY(jint, JVM_DTraceGetVersion(JNIEnv* env))
4351 JVMWrapper("JVM_DTraceGetVersion");
4352 return (jint)JVM_TRACING_DTRACE_VERSION;
4353 JVM_END
4355 JVM_ENTRY(jlong,JVM_DTraceActivate(
4356 JNIEnv* env, jint version, jstring module_name, jint providers_count,
4357 JVM_DTraceProvider* providers))
4358 JVMWrapper("JVM_DTraceActivate");
4359 return DTraceJSDT::activate(
4360 version, module_name, providers_count, providers, CHECK_0);
4361 JVM_END
4363 JVM_ENTRY(jboolean,JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method))
4364 JVMWrapper("JVM_DTraceIsProbeEnabled");
4365 return DTraceJSDT::is_probe_enabled(method);
4366 JVM_END
4368 JVM_ENTRY(void,JVM_DTraceDispose(JNIEnv* env, jlong handle))
4369 JVMWrapper("JVM_DTraceDispose");
4370 DTraceJSDT::dispose(handle);
4371 JVM_END
4373 JVM_ENTRY(jboolean,JVM_DTraceIsSupported(JNIEnv* env))
4374 JVMWrapper("JVM_DTraceIsSupported");
4375 return DTraceJSDT::is_supported();
4376 JVM_END
4378 // Returns an array of all live Thread objects (VM internal JavaThreads,
4379 // jvmti agent threads, and JNI attaching threads are skipped)
4380 // See CR 6404306 regarding JNI attaching threads
4381 JVM_ENTRY(jobjectArray, JVM_GetAllThreads(JNIEnv *env, jclass dummy))
4382 ResourceMark rm(THREAD);
4383 ThreadsListEnumerator tle(THREAD, false, false);
4384 JvmtiVMObjectAllocEventCollector oam;
4386 int num_threads = tle.num_threads();
4387 objArrayOop r = oopFactory::new_objArray(SystemDictionary::Thread_klass(), num_threads, CHECK_NULL);
4388 objArrayHandle threads_ah(THREAD, r);
4390 for (int i = 0; i < num_threads; i++) {
4391 Handle h = tle.get_threadObj(i);
4392 threads_ah->obj_at_put(i, h());
4393 }
4395 return (jobjectArray) JNIHandles::make_local(env, threads_ah());
4396 JVM_END
4399 // Support for java.lang.Thread.getStackTrace() and getAllStackTraces() methods
4400 // Return StackTraceElement[][], each element is the stack trace of a thread in
4401 // the corresponding entry in the given threads array
4402 JVM_ENTRY(jobjectArray, JVM_DumpThreads(JNIEnv *env, jclass threadClass, jobjectArray threads))
4403 JVMWrapper("JVM_DumpThreads");
4404 JvmtiVMObjectAllocEventCollector oam;
4406 // Check if threads is null
4407 if (threads == NULL) {
4408 THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4409 }
4411 objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(threads));
4412 objArrayHandle ah(THREAD, a);
4413 int num_threads = ah->length();
4414 // check if threads is non-empty array
4415 if (num_threads == 0) {
4416 THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4417 }
4419 // check if threads is not an array of objects of Thread class
4420 Klass* k = ObjArrayKlass::cast(ah->klass())->element_klass();
4421 if (k != SystemDictionary::Thread_klass()) {
4422 THROW_(vmSymbols::java_lang_IllegalArgumentException(), 0);
4423 }
4425 ResourceMark rm(THREAD);
4427 GrowableArray<instanceHandle>* thread_handle_array = new GrowableArray<instanceHandle>(num_threads);
4428 for (int i = 0; i < num_threads; i++) {
4429 oop thread_obj = ah->obj_at(i);
4430 instanceHandle h(THREAD, (instanceOop) thread_obj);
4431 thread_handle_array->append(h);
4432 }
4434 Handle stacktraces = ThreadService::dump_stack_traces(thread_handle_array, num_threads, CHECK_NULL);
4435 return (jobjectArray)JNIHandles::make_local(env, stacktraces());
4437 JVM_END
4439 // JVM monitoring and management support
4440 JVM_ENTRY_NO_ENV(void*, JVM_GetManagement(jint version))
4441 return Management::get_jmm_interface(version);
4442 JVM_END
4444 // com.sun.tools.attach.VirtualMachine agent properties support
4445 //
4446 // Initialize the agent properties with the properties maintained in the VM
4447 JVM_ENTRY(jobject, JVM_InitAgentProperties(JNIEnv *env, jobject properties))
4448 JVMWrapper("JVM_InitAgentProperties");
4449 ResourceMark rm;
4451 Handle props(THREAD, JNIHandles::resolve_non_null(properties));
4453 PUTPROP(props, "sun.java.command", Arguments::java_command());
4454 PUTPROP(props, "sun.jvm.flags", Arguments::jvm_flags());
4455 PUTPROP(props, "sun.jvm.args", Arguments::jvm_args());
4456 return properties;
4457 JVM_END
4459 JVM_ENTRY(jobjectArray, JVM_GetEnclosingMethodInfo(JNIEnv *env, jclass ofClass))
4460 {
4461 JVMWrapper("JVM_GetEnclosingMethodInfo");
4462 JvmtiVMObjectAllocEventCollector oam;
4464 if (ofClass == NULL) {
4465 return NULL;
4466 }
4467 Handle mirror(THREAD, JNIHandles::resolve_non_null(ofClass));
4468 // Special handling for primitive objects
4469 if (java_lang_Class::is_primitive(mirror())) {
4470 return NULL;
4471 }
4472 Klass* k = java_lang_Class::as_Klass(mirror());
4473 if (!k->oop_is_instance()) {
4474 return NULL;
4475 }
4476 instanceKlassHandle ik_h(THREAD, k);
4477 int encl_method_class_idx = ik_h->enclosing_method_class_index();
4478 if (encl_method_class_idx == 0) {
4479 return NULL;
4480 }
4481 objArrayOop dest_o = oopFactory::new_objArray(SystemDictionary::Object_klass(), 3, CHECK_NULL);
4482 objArrayHandle dest(THREAD, dest_o);
4483 Klass* enc_k = ik_h->constants()->klass_at(encl_method_class_idx, CHECK_NULL);
4484 dest->obj_at_put(0, enc_k->java_mirror());
4485 int encl_method_method_idx = ik_h->enclosing_method_method_index();
4486 if (encl_method_method_idx != 0) {
4487 Symbol* sym = ik_h->constants()->symbol_at(
4488 extract_low_short_from_int(
4489 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4490 Handle str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4491 dest->obj_at_put(1, str());
4492 sym = ik_h->constants()->symbol_at(
4493 extract_high_short_from_int(
4494 ik_h->constants()->name_and_type_at(encl_method_method_idx)));
4495 str = java_lang_String::create_from_symbol(sym, CHECK_NULL);
4496 dest->obj_at_put(2, str());
4497 }
4498 return (jobjectArray) JNIHandles::make_local(dest());
4499 }
4500 JVM_END
4502 JVM_ENTRY(jintArray, JVM_GetThreadStateValues(JNIEnv* env,
4503 jint javaThreadState))
4504 {
4505 // If new thread states are added in future JDK and VM versions,
4506 // this should check if the JDK version is compatible with thread
4507 // states supported by the VM. Return NULL if not compatible.
4508 //
4509 // This function must map the VM java_lang_Thread::ThreadStatus
4510 // to the Java thread state that the JDK supports.
4511 //
4513 typeArrayHandle values_h;
4514 switch (javaThreadState) {
4515 case JAVA_THREAD_STATE_NEW : {
4516 typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4517 values_h = typeArrayHandle(THREAD, r);
4518 values_h->int_at_put(0, java_lang_Thread::NEW);
4519 break;
4520 }
4521 case JAVA_THREAD_STATE_RUNNABLE : {
4522 typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4523 values_h = typeArrayHandle(THREAD, r);
4524 values_h->int_at_put(0, java_lang_Thread::RUNNABLE);
4525 break;
4526 }
4527 case JAVA_THREAD_STATE_BLOCKED : {
4528 typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4529 values_h = typeArrayHandle(THREAD, r);
4530 values_h->int_at_put(0, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);
4531 break;
4532 }
4533 case JAVA_THREAD_STATE_WAITING : {
4534 typeArrayOop r = oopFactory::new_typeArray(T_INT, 2, CHECK_NULL);
4535 values_h = typeArrayHandle(THREAD, r);
4536 values_h->int_at_put(0, java_lang_Thread::IN_OBJECT_WAIT);
4537 values_h->int_at_put(1, java_lang_Thread::PARKED);
4538 break;
4539 }
4540 case JAVA_THREAD_STATE_TIMED_WAITING : {
4541 typeArrayOop r = oopFactory::new_typeArray(T_INT, 3, CHECK_NULL);
4542 values_h = typeArrayHandle(THREAD, r);
4543 values_h->int_at_put(0, java_lang_Thread::SLEEPING);
4544 values_h->int_at_put(1, java_lang_Thread::IN_OBJECT_WAIT_TIMED);
4545 values_h->int_at_put(2, java_lang_Thread::PARKED_TIMED);
4546 break;
4547 }
4548 case JAVA_THREAD_STATE_TERMINATED : {
4549 typeArrayOop r = oopFactory::new_typeArray(T_INT, 1, CHECK_NULL);
4550 values_h = typeArrayHandle(THREAD, r);
4551 values_h->int_at_put(0, java_lang_Thread::TERMINATED);
4552 break;
4553 }
4554 default:
4555 // Unknown state - probably incompatible JDK version
4556 return NULL;
4557 }
4559 return (jintArray) JNIHandles::make_local(env, values_h());
4560 }
4561 JVM_END
4564 JVM_ENTRY(jobjectArray, JVM_GetThreadStateNames(JNIEnv* env,
4565 jint javaThreadState,
4566 jintArray values))
4567 {
4568 // If new thread states are added in future JDK and VM versions,
4569 // this should check if the JDK version is compatible with thread
4570 // states supported by the VM. Return NULL if not compatible.
4571 //
4572 // This function must map the VM java_lang_Thread::ThreadStatus
4573 // to the Java thread state that the JDK supports.
4574 //
4576 ResourceMark rm;
4578 // Check if threads is null
4579 if (values == NULL) {
4580 THROW_(vmSymbols::java_lang_NullPointerException(), 0);
4581 }
4583 typeArrayOop v = typeArrayOop(JNIHandles::resolve_non_null(values));
4584 typeArrayHandle values_h(THREAD, v);
4586 objArrayHandle names_h;
4587 switch (javaThreadState) {
4588 case JAVA_THREAD_STATE_NEW : {
4589 assert(values_h->length() == 1 &&
4590 values_h->int_at(0) == java_lang_Thread::NEW,
4591 "Invalid threadStatus value");
4593 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4594 1, /* only 1 substate */
4595 CHECK_NULL);
4596 names_h = objArrayHandle(THREAD, r);
4597 Handle name = java_lang_String::create_from_str("NEW", CHECK_NULL);
4598 names_h->obj_at_put(0, name());
4599 break;
4600 }
4601 case JAVA_THREAD_STATE_RUNNABLE : {
4602 assert(values_h->length() == 1 &&
4603 values_h->int_at(0) == java_lang_Thread::RUNNABLE,
4604 "Invalid threadStatus value");
4606 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4607 1, /* only 1 substate */
4608 CHECK_NULL);
4609 names_h = objArrayHandle(THREAD, r);
4610 Handle name = java_lang_String::create_from_str("RUNNABLE", CHECK_NULL);
4611 names_h->obj_at_put(0, name());
4612 break;
4613 }
4614 case JAVA_THREAD_STATE_BLOCKED : {
4615 assert(values_h->length() == 1 &&
4616 values_h->int_at(0) == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER,
4617 "Invalid threadStatus value");
4619 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4620 1, /* only 1 substate */
4621 CHECK_NULL);
4622 names_h = objArrayHandle(THREAD, r);
4623 Handle name = java_lang_String::create_from_str("BLOCKED", CHECK_NULL);
4624 names_h->obj_at_put(0, name());
4625 break;
4626 }
4627 case JAVA_THREAD_STATE_WAITING : {
4628 assert(values_h->length() == 2 &&
4629 values_h->int_at(0) == java_lang_Thread::IN_OBJECT_WAIT &&
4630 values_h->int_at(1) == java_lang_Thread::PARKED,
4631 "Invalid threadStatus value");
4632 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4633 2, /* number of substates */
4634 CHECK_NULL);
4635 names_h = objArrayHandle(THREAD, r);
4636 Handle name0 = java_lang_String::create_from_str("WAITING.OBJECT_WAIT",
4637 CHECK_NULL);
4638 Handle name1 = java_lang_String::create_from_str("WAITING.PARKED",
4639 CHECK_NULL);
4640 names_h->obj_at_put(0, name0());
4641 names_h->obj_at_put(1, name1());
4642 break;
4643 }
4644 case JAVA_THREAD_STATE_TIMED_WAITING : {
4645 assert(values_h->length() == 3 &&
4646 values_h->int_at(0) == java_lang_Thread::SLEEPING &&
4647 values_h->int_at(1) == java_lang_Thread::IN_OBJECT_WAIT_TIMED &&
4648 values_h->int_at(2) == java_lang_Thread::PARKED_TIMED,
4649 "Invalid threadStatus value");
4650 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4651 3, /* number of substates */
4652 CHECK_NULL);
4653 names_h = objArrayHandle(THREAD, r);
4654 Handle name0 = java_lang_String::create_from_str("TIMED_WAITING.SLEEPING",
4655 CHECK_NULL);
4656 Handle name1 = java_lang_String::create_from_str("TIMED_WAITING.OBJECT_WAIT",
4657 CHECK_NULL);
4658 Handle name2 = java_lang_String::create_from_str("TIMED_WAITING.PARKED",
4659 CHECK_NULL);
4660 names_h->obj_at_put(0, name0());
4661 names_h->obj_at_put(1, name1());
4662 names_h->obj_at_put(2, name2());
4663 break;
4664 }
4665 case JAVA_THREAD_STATE_TERMINATED : {
4666 assert(values_h->length() == 1 &&
4667 values_h->int_at(0) == java_lang_Thread::TERMINATED,
4668 "Invalid threadStatus value");
4669 objArrayOop r = oopFactory::new_objArray(SystemDictionary::String_klass(),
4670 1, /* only 1 substate */
4671 CHECK_NULL);
4672 names_h = objArrayHandle(THREAD, r);
4673 Handle name = java_lang_String::create_from_str("TERMINATED", CHECK_NULL);
4674 names_h->obj_at_put(0, name());
4675 break;
4676 }
4677 default:
4678 // Unknown state - probably incompatible JDK version
4679 return NULL;
4680 }
4681 return (jobjectArray) JNIHandles::make_local(env, names_h());
4682 }
4683 JVM_END
4685 JVM_ENTRY(void, JVM_GetVersionInfo(JNIEnv* env, jvm_version_info* info, size_t info_size))
4686 {
4687 memset(info, 0, info_size);
4689 info->jvm_version = Abstract_VM_Version::jvm_version();
4690 info->update_version = 0; /* 0 in HotSpot Express VM */
4691 info->special_update_version = 0; /* 0 in HotSpot Express VM */
4693 // when we add a new capability in the jvm_version_info struct, we should also
4694 // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
4695 // counter defined in runtimeService.cpp.
4696 info->is_attachable = AttachListener::is_attach_supported();
4697 }
4698 JVM_END