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