1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2012 Red Hat, Inc.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "ci/ciReplay.hpp"
  28 #include "classfile/altHashing.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/javaClasses.hpp"
  31 #include "classfile/symbolTable.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "gc/shared/gcLocker.inline.hpp"
  35 #include "interpreter/linkResolver.hpp"
  36 #include "memory/allocation.hpp"
  37 #include "memory/allocation.inline.hpp"
  38 #include "memory/oopFactory.hpp"
  39 #include "memory/universe.inline.hpp"
  40 #include "oops/instanceKlass.hpp"
  41 #include "oops/instanceOop.hpp"
  42 #include "oops/markOop.hpp"
  43 #include "oops/method.hpp"
  44 #include "oops/objArrayKlass.hpp"
  45 #include "oops/objArrayOop.inline.hpp"
  46 #include "oops/oop.inline.hpp"
  47 #include "oops/symbol.hpp"
  48 #include "oops/typeArrayKlass.hpp"
  49 #include "oops/typeArrayOop.hpp"
  50 #include "prims/jni.h"
  51 #include "prims/jniCheck.hpp"
  52 #include "prims/jniExport.hpp"
  53 #include "prims/jniFastGetField.hpp"
  54 #include "prims/jvm.h"
  55 #include "prims/jvm_misc.hpp"
  56 #include "prims/jvmtiExport.hpp"
  57 #include "prims/jvmtiThreadState.hpp"
  58 #include "runtime/atomic.inline.hpp"
  59 #include "runtime/compilationPolicy.hpp"
  60 #include "runtime/fieldDescriptor.hpp"
  61 #include "runtime/fprofiler.hpp"
  62 #include "runtime/handles.inline.hpp"
  63 #include "runtime/interfaceSupport.hpp"
  64 #include "runtime/java.hpp"
  65 #include "runtime/javaCalls.hpp"
  66 #include "runtime/jfieldIDWorkaround.hpp"
  67 #include "runtime/orderAccess.inline.hpp"
  68 #include "runtime/reflection.hpp"
  69 #include "runtime/sharedRuntime.hpp"
  70 #include "runtime/signature.hpp"
  71 #include "runtime/thread.inline.hpp"
  72 #include "runtime/vm_operations.hpp"
  73 #include "services/memTracker.hpp"
  74 #include "services/runtimeService.hpp"
  75 #include "trace/tracing.hpp"
  76 #include "utilities/defaultStream.hpp"
  77 #include "utilities/dtrace.hpp"
  78 #include "utilities/events.hpp"
  79 #include "utilities/histogram.hpp"
  80 #include "utilities/macros.hpp"
  81 #if INCLUDE_ALL_GCS
  82 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  83 #endif // INCLUDE_ALL_GCS
  84 #if INCLUDE_JVMCI
  85 #include "jvmci/jvmciCompiler.hpp"
  86 #include "jvmci/jvmciRuntime.hpp"
  87 #endif
  88 
  89 static jint CurrentVersion = JNI_VERSION_1_8;
  90 
  91 #ifdef _WIN32
  92 extern LONG WINAPI topLevelExceptionFilter(_EXCEPTION_POINTERS* );
  93 #endif
  94 
  95 // The DT_RETURN_MARK macros create a scoped object to fire the dtrace
  96 // '-return' probe regardless of the return path is taken out of the function.
  97 // Methods that have multiple return paths use this to avoid having to
  98 // instrument each return path.  Methods that use CHECK or THROW must use this
  99 // since those macros can cause an immedate uninstrumented return.
 100 //
 101 // In order to get the return value, a reference to the variable containing
 102 // the return value must be passed to the contructor of the object, and
 103 // the return value must be set before return (since the mark object has
 104 // a reference to it).
 105 //
 106 // Example:
 107 // DT_RETURN_MARK_DECL(SomeFunc, int);
 108 // JNI_ENTRY(int, SomeFunc, ...)
 109 //   int return_value = 0;
 110 //   DT_RETURN_MARK(SomeFunc, int, (const int&)return_value);
 111 //   foo(CHECK_0)
 112 //   return_value = 5;
 113 //   return return_value;
 114 // JNI_END
 115 #define DT_RETURN_MARK_DECL(name, type, probe)                             \
 116   DTRACE_ONLY(                                                             \
 117     class DTraceReturnProbeMark_##name {                                   \
 118      public:                                                               \
 119       const type& _ret_ref;                                                \
 120       DTraceReturnProbeMark_##name(const type& v) : _ret_ref(v) {}         \
 121       ~DTraceReturnProbeMark_##name() {                                    \
 122         probe;                                                             \
 123       }                                                                    \
 124     }                                                                      \
 125   )
 126 // Void functions are simpler since there's no return value
 127 #define DT_VOID_RETURN_MARK_DECL(name, probe)                              \
 128   DTRACE_ONLY(                                                             \
 129     class DTraceReturnProbeMark_##name {                                   \
 130      public:                                                               \
 131       ~DTraceReturnProbeMark_##name() {                                    \
 132         probe;                                                             \
 133       }                                                                    \
 134     }                                                                      \
 135   )
 136 
 137 // Place these macros in the function to mark the return.  Non-void
 138 // functions need the type and address of the return value.
 139 #define DT_RETURN_MARK(name, type, ref) \
 140   DTRACE_ONLY( DTraceReturnProbeMark_##name dtrace_return_mark(ref) )
 141 #define DT_VOID_RETURN_MARK(name) \
 142   DTRACE_ONLY( DTraceReturnProbeMark_##name dtrace_return_mark )
 143 
 144 
 145 // Use these to select distinct code for floating-point vs. non-floating point
 146 // situations.  Used from within common macros where we need slightly
 147 // different behavior for Float/Double
 148 #define FP_SELECT_Boolean(intcode, fpcode) intcode
 149 #define FP_SELECT_Byte(intcode, fpcode)    intcode
 150 #define FP_SELECT_Char(intcode, fpcode)    intcode
 151 #define FP_SELECT_Short(intcode, fpcode)   intcode
 152 #define FP_SELECT_Object(intcode, fpcode)  intcode
 153 #define FP_SELECT_Int(intcode, fpcode)     intcode
 154 #define FP_SELECT_Long(intcode, fpcode)    intcode
 155 #define FP_SELECT_Float(intcode, fpcode)   fpcode
 156 #define FP_SELECT_Double(intcode, fpcode)  fpcode
 157 #define FP_SELECT(TypeName, intcode, fpcode) \
 158   FP_SELECT_##TypeName(intcode, fpcode)
 159 
 160 #define COMMA ,
 161 
 162 // Choose DT_RETURN_MARK macros  based on the type: float/double -> void
 163 // (dtrace doesn't do FP yet)
 164 #define DT_RETURN_MARK_DECL_FOR(TypeName, name, type, probe)    \
 165   FP_SELECT(TypeName, \
 166     DT_RETURN_MARK_DECL(name, type, probe), DT_VOID_RETURN_MARK_DECL(name, probe) )
 167 #define DT_RETURN_MARK_FOR(TypeName, name, type, ref) \
 168   FP_SELECT(TypeName, \
 169     DT_RETURN_MARK(name, type, ref), DT_VOID_RETURN_MARK(name) )
 170 
 171 
 172 // out-of-line helpers for class jfieldIDWorkaround:
 173 
 174 bool jfieldIDWorkaround::is_valid_jfieldID(Klass* k, jfieldID id) {
 175   if (jfieldIDWorkaround::is_instance_jfieldID(k, id)) {
 176     uintptr_t as_uint = (uintptr_t) id;
 177     intptr_t offset = raw_instance_offset(id);
 178     if (is_checked_jfieldID(id)) {
 179       if (!klass_hash_ok(k, id)) {
 180         return false;
 181       }
 182     }
 183     return InstanceKlass::cast(k)->contains_field_offset(offset);
 184   } else {
 185     JNIid* result = (JNIid*) id;
 186 #ifdef ASSERT
 187     return result != NULL && result->is_static_field_id();
 188 #else
 189     return result != NULL;
 190 #endif
 191   }
 192 }
 193 
 194 
 195 intptr_t jfieldIDWorkaround::encode_klass_hash(Klass* k, intptr_t offset) {
 196   if (offset <= small_offset_mask) {
 197     Klass* field_klass = k;
 198     Klass* super_klass = field_klass->super();
 199     // With compressed oops the most super class with nonstatic fields would
 200     // be the owner of fields embedded in the header.
 201     while (InstanceKlass::cast(super_klass)->has_nonstatic_fields() &&
 202            InstanceKlass::cast(super_klass)->contains_field_offset(offset)) {
 203       field_klass = super_klass;   // super contains the field also
 204       super_klass = field_klass->super();
 205     }
 206     debug_only(No_Safepoint_Verifier nosafepoint;)
 207     uintptr_t klass_hash = field_klass->identity_hash();
 208     return ((klass_hash & klass_mask) << klass_shift) | checked_mask_in_place;
 209   } else {
 210 #if 0
 211     #ifndef PRODUCT
 212     {
 213       ResourceMark rm;
 214       warning("VerifyJNIFields: long offset %d in %s", offset, k->external_name());
 215     }
 216     #endif
 217 #endif
 218     return 0;
 219   }
 220 }
 221 
 222 bool jfieldIDWorkaround::klass_hash_ok(Klass* k, jfieldID id) {
 223   uintptr_t as_uint = (uintptr_t) id;
 224   intptr_t klass_hash = (as_uint >> klass_shift) & klass_mask;
 225   do {
 226     debug_only(No_Safepoint_Verifier nosafepoint;)
 227     // Could use a non-blocking query for identity_hash here...
 228     if ((k->identity_hash() & klass_mask) == klass_hash)
 229       return true;
 230     k = k->super();
 231   } while (k != NULL);
 232   return false;
 233 }
 234 
 235 void jfieldIDWorkaround::verify_instance_jfieldID(Klass* k, jfieldID id) {
 236   guarantee(jfieldIDWorkaround::is_instance_jfieldID(k, id), "must be an instance field" );
 237   uintptr_t as_uint = (uintptr_t) id;
 238   intptr_t offset = raw_instance_offset(id);
 239   if (VerifyJNIFields) {
 240     if (is_checked_jfieldID(id)) {
 241       guarantee(klass_hash_ok(k, id),
 242     "Bug in native code: jfieldID class must match object");
 243     } else {
 244 #if 0
 245       #ifndef PRODUCT
 246       if (Verbose) {
 247   ResourceMark rm;
 248   warning("VerifyJNIFields: unverified offset %d for %s", offset, k->external_name());
 249       }
 250       #endif
 251 #endif
 252     }
 253   }
 254   guarantee(InstanceKlass::cast(k)->contains_field_offset(offset),
 255       "Bug in native code: jfieldID offset must address interior of object");
 256 }
 257 
 258 // Wrapper to trace JNI functions
 259 
 260 #ifdef ASSERT
 261   Histogram* JNIHistogram;
 262   static volatile jint JNIHistogram_lock = 0;
 263 
 264   class JNIHistogramElement : public HistogramElement {
 265     public:
 266      JNIHistogramElement(const char* name);
 267   };
 268 
 269   JNIHistogramElement::JNIHistogramElement(const char* elementName) {
 270     _name = elementName;
 271     uintx count = 0;
 272 
 273     while (Atomic::cmpxchg(1, &JNIHistogram_lock, 0) != 0) {
 274       while (OrderAccess::load_acquire(&JNIHistogram_lock) != 0) {
 275         count +=1;
 276         if ( (WarnOnStalledSpinLock > 0)
 277           && (count % WarnOnStalledSpinLock == 0)) {
 278           warning("JNIHistogram_lock seems to be stalled");
 279         }
 280       }
 281      }
 282 
 283 
 284     if(JNIHistogram == NULL)
 285       JNIHistogram = new Histogram("JNI Call Counts",100);
 286 
 287     JNIHistogram->add_element(this);
 288     Atomic::dec(&JNIHistogram_lock);
 289   }
 290 
 291   #define JNICountWrapper(arg)                                     \
 292      static JNIHistogramElement* e = new JNIHistogramElement(arg); \
 293       /* There is a MT-race condition in VC++. So we need to make sure that that e has been initialized */ \
 294      if (e != NULL) e->increment_count()
 295   #define JNIWrapper(arg) JNICountWrapper(arg);
 296 #else
 297   #define JNIWrapper(arg)
 298 #endif
 299 
 300 
 301 // Implementation of JNI entries
 302 
 303 DT_RETURN_MARK_DECL(DefineClass, jclass
 304                     , HOTSPOT_JNI_DEFINECLASS_RETURN(_ret_ref));
 305 
 306 JNI_ENTRY(jclass, jni_DefineClass(JNIEnv *env, const char *name, jobject loaderRef,
 307                                   const jbyte *buf, jsize bufLen))
 308   JNIWrapper("DefineClass");
 309 
 310   HOTSPOT_JNI_DEFINECLASS_ENTRY(
 311     env, (char*) name, loaderRef, (char*) buf, bufLen);
 312 
 313   jclass cls = NULL;
 314   DT_RETURN_MARK(DefineClass, jclass, (const jclass&)cls);
 315 
 316   TempNewSymbol class_name = NULL;
 317   // Since exceptions can be thrown, class initialization can take place
 318   // if name is NULL no check for class name in .class stream has to be made.
 319   if (name != NULL) {
 320     const int str_len = (int)strlen(name);
 321     if (str_len > Symbol::max_length()) {
 322       // It's impossible to create this class;  the name cannot fit
 323       // into the constant pool.
 324       THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
 325     }
 326     class_name = SymbolTable::new_symbol(name, CHECK_NULL);
 327   }
 328   ResourceMark rm(THREAD);
 329   ClassFileStream st((u1*) buf, bufLen, NULL);
 330   Handle class_loader (THREAD, JNIHandles::resolve(loaderRef));
 331 
 332   if (UsePerfData && !class_loader.is_null()) {
 333     // check whether the current caller thread holds the lock or not.
 334     // If not, increment the corresponding counter
 335     if (ObjectSynchronizer::
 336         query_lock_ownership((JavaThread*)THREAD, class_loader) !=
 337         ObjectSynchronizer::owner_self) {
 338       ClassLoader::sync_JNIDefineClassLockFreeCounter()->inc();
 339     }
 340   }
 341   Klass* k = SystemDictionary::resolve_from_stream(class_name, class_loader,
 342                                                      Handle(), &st, true,
 343                                                      CHECK_NULL);
 344 
 345   if (TraceClassResolution && k != NULL) {
 346     trace_class_resolution(k);
 347   }
 348 
 349   cls = (jclass)JNIHandles::make_local(
 350     env, k->java_mirror());
 351   return cls;
 352 JNI_END
 353 
 354 
 355 
 356 static bool first_time_FindClass = true;
 357 
 358 DT_RETURN_MARK_DECL(FindClass, jclass
 359                     , HOTSPOT_JNI_FINDCLASS_RETURN(_ret_ref));
 360 
 361 JNI_ENTRY(jclass, jni_FindClass(JNIEnv *env, const char *name))
 362   JNIWrapper("FindClass");
 363 
 364   HOTSPOT_JNI_FINDCLASS_ENTRY(env, (char *)name);
 365 
 366   jclass result = NULL;
 367   DT_RETURN_MARK(FindClass, jclass, (const jclass&)result);
 368 
 369   // Remember if we are the first invocation of jni_FindClass
 370   bool first_time = first_time_FindClass;
 371   first_time_FindClass = false;
 372 
 373   // Sanity check the name:  it cannot be null or larger than the maximum size
 374   // name we can fit in the constant pool.
 375   if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
 376     THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), name);
 377   }
 378 
 379   //%note jni_3
 380   Handle loader;
 381   Handle protection_domain;
 382   // Find calling class
 383   instanceKlassHandle k (THREAD, thread->security_get_caller_class(0));
 384   if (k.not_null()) {
 385     loader = Handle(THREAD, k->class_loader());
 386     // Special handling to make sure JNI_OnLoad and JNI_OnUnload are executed
 387     // in the correct class context.
 388     if (loader.is_null() &&
 389         k->name() == vmSymbols::java_lang_ClassLoader_NativeLibrary()) {
 390       JavaValue result(T_OBJECT);
 391       JavaCalls::call_static(&result, k,
 392                                       vmSymbols::getFromClass_name(),
 393                                       vmSymbols::void_class_signature(),
 394                                       thread);
 395       if (HAS_PENDING_EXCEPTION) {
 396         Handle ex(thread, thread->pending_exception());
 397         CLEAR_PENDING_EXCEPTION;
 398         THROW_HANDLE_0(ex);
 399       }
 400       oop mirror = (oop) result.get_jobject();
 401       loader = Handle(THREAD,
 402         InstanceKlass::cast(java_lang_Class::as_Klass(mirror))->class_loader());
 403       protection_domain = Handle(THREAD,
 404         InstanceKlass::cast(java_lang_Class::as_Klass(mirror))->protection_domain());
 405     }
 406   } else {
 407     // We call ClassLoader.getSystemClassLoader to obtain the system class loader.
 408     loader = Handle(THREAD, SystemDictionary::java_system_loader());
 409   }
 410 
 411   TempNewSymbol sym = SymbolTable::new_symbol(name, CHECK_NULL);
 412   result = find_class_from_class_loader(env, sym, true, loader,
 413                                         protection_domain, true, thread);
 414 
 415   if (TraceClassResolution && result != NULL) {
 416     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
 417   }
 418 
 419   // If we were the first invocation of jni_FindClass, we enable compilation again
 420   // rather than just allowing invocation counter to overflow and decay.
 421   // Controlled by flag DelayCompilationDuringStartup.
 422   if (first_time && !CompileTheWorld)
 423     CompilationPolicy::completed_vm_startup();
 424 
 425   return result;
 426 JNI_END
 427 
 428 DT_RETURN_MARK_DECL(FromReflectedMethod, jmethodID
 429                     , HOTSPOT_JNI_FROMREFLECTEDMETHOD_RETURN((uintptr_t)_ret_ref));
 430 
 431 JNI_ENTRY(jmethodID, jni_FromReflectedMethod(JNIEnv *env, jobject method))
 432   JNIWrapper("FromReflectedMethod");
 433 
 434   HOTSPOT_JNI_FROMREFLECTEDMETHOD_ENTRY(env, method);
 435 
 436   jmethodID ret = NULL;
 437   DT_RETURN_MARK(FromReflectedMethod, jmethodID, (const jmethodID&)ret);
 438 
 439   // method is a handle to a java.lang.reflect.Method object
 440   oop reflected  = JNIHandles::resolve_non_null(method);
 441   oop mirror     = NULL;
 442   int slot       = 0;
 443 
 444   if (reflected->klass() == SystemDictionary::reflect_Constructor_klass()) {
 445     mirror = java_lang_reflect_Constructor::clazz(reflected);
 446     slot   = java_lang_reflect_Constructor::slot(reflected);
 447   } else {
 448     assert(reflected->klass() == SystemDictionary::reflect_Method_klass(), "wrong type");
 449     mirror = java_lang_reflect_Method::clazz(reflected);
 450     slot   = java_lang_reflect_Method::slot(reflected);
 451   }
 452   Klass* k     = java_lang_Class::as_Klass(mirror);
 453 
 454   KlassHandle k1(THREAD, k);
 455   // Make sure class is initialized before handing id's out to methods
 456   k1()->initialize(CHECK_NULL);
 457   Method* m = InstanceKlass::cast(k1())->method_with_idnum(slot);
 458   ret = m==NULL? NULL : m->jmethod_id();  // return NULL if reflected method deleted
 459   return ret;
 460 JNI_END
 461 
 462 DT_RETURN_MARK_DECL(FromReflectedField, jfieldID
 463                     , HOTSPOT_JNI_FROMREFLECTEDFIELD_RETURN((uintptr_t)_ret_ref));
 464 
 465 JNI_ENTRY(jfieldID, jni_FromReflectedField(JNIEnv *env, jobject field))
 466   JNIWrapper("FromReflectedField");
 467 
 468   HOTSPOT_JNI_FROMREFLECTEDFIELD_ENTRY(env, field);
 469 
 470   jfieldID ret = NULL;
 471   DT_RETURN_MARK(FromReflectedField, jfieldID, (const jfieldID&)ret);
 472 
 473   // field is a handle to a java.lang.reflect.Field object
 474   oop reflected   = JNIHandles::resolve_non_null(field);
 475   oop mirror      = java_lang_reflect_Field::clazz(reflected);
 476   Klass* k      = java_lang_Class::as_Klass(mirror);
 477   int slot        = java_lang_reflect_Field::slot(reflected);
 478   int modifiers   = java_lang_reflect_Field::modifiers(reflected);
 479 
 480   KlassHandle k1(THREAD, k);
 481   // Make sure class is initialized before handing id's out to fields
 482   k1()->initialize(CHECK_NULL);
 483 
 484   // First check if this is a static field
 485   if (modifiers & JVM_ACC_STATIC) {
 486     intptr_t offset = InstanceKlass::cast(k1())->field_offset( slot );
 487     JNIid* id = InstanceKlass::cast(k1())->jni_id_for(offset);
 488     assert(id != NULL, "corrupt Field object");
 489     debug_only(id->set_is_static_field_id();)
 490     // A jfieldID for a static field is a JNIid specifying the field holder and the offset within the Klass*
 491     ret = jfieldIDWorkaround::to_static_jfieldID(id);
 492     return ret;
 493   }
 494 
 495   // The slot is the index of the field description in the field-array
 496   // The jfieldID is the offset of the field within the object
 497   // It may also have hash bits for k, if VerifyJNIFields is turned on.
 498   intptr_t offset = InstanceKlass::cast(k1())->field_offset( slot );
 499   assert(InstanceKlass::cast(k1())->contains_field_offset(offset), "stay within object");
 500   ret = jfieldIDWorkaround::to_instance_jfieldID(k1(), offset);
 501   return ret;
 502 JNI_END
 503 
 504 
 505 DT_RETURN_MARK_DECL(ToReflectedMethod, jobject
 506                     , HOTSPOT_JNI_TOREFLECTEDMETHOD_RETURN(_ret_ref));
 507 
 508 JNI_ENTRY(jobject, jni_ToReflectedMethod(JNIEnv *env, jclass cls, jmethodID method_id, jboolean isStatic))
 509   JNIWrapper("ToReflectedMethod");
 510 
 511   HOTSPOT_JNI_TOREFLECTEDMETHOD_ENTRY(env, cls, (uintptr_t) method_id, isStatic);
 512 
 513   jobject ret = NULL;
 514   DT_RETURN_MARK(ToReflectedMethod, jobject, (const jobject&)ret);
 515 
 516   methodHandle m (THREAD, Method::resolve_jmethod_id(method_id));
 517   assert(m->is_static() == (isStatic != 0), "jni_ToReflectedMethod access flags doesn't match");
 518   oop reflection_method;
 519   if (m->is_initializer()) {
 520     reflection_method = Reflection::new_constructor(m, CHECK_NULL);
 521   } else {
 522     reflection_method = Reflection::new_method(m, false, CHECK_NULL);
 523   }
 524   ret = JNIHandles::make_local(env, reflection_method);
 525   return ret;
 526 JNI_END
 527 
 528 DT_RETURN_MARK_DECL(GetSuperclass, jclass
 529                     , HOTSPOT_JNI_GETSUPERCLASS_RETURN(_ret_ref));
 530 
 531 JNI_ENTRY(jclass, jni_GetSuperclass(JNIEnv *env, jclass sub))
 532   JNIWrapper("GetSuperclass");
 533 
 534   HOTSPOT_JNI_GETSUPERCLASS_ENTRY(env, sub);
 535 
 536   jclass obj = NULL;
 537   DT_RETURN_MARK(GetSuperclass, jclass, (const jclass&)obj);
 538 
 539   oop mirror = JNIHandles::resolve_non_null(sub);
 540   // primitive classes return NULL
 541   if (java_lang_Class::is_primitive(mirror)) return NULL;
 542 
 543   // Rules of Class.getSuperClass as implemented by KLass::java_super:
 544   // arrays return Object
 545   // interfaces return NULL
 546   // proper classes return Klass::super()
 547   Klass* k = java_lang_Class::as_Klass(mirror);
 548   if (k->is_interface()) return NULL;
 549 
 550   // return mirror for superclass
 551   Klass* super = k->java_super();
 552   // super2 is the value computed by the compiler's getSuperClass intrinsic:
 553   debug_only(Klass* super2 = ( k->is_array_klass()
 554                                  ? SystemDictionary::Object_klass()
 555                                  : k->super() ) );
 556   assert(super == super2,
 557          "java_super computation depends on interface, array, other super");
 558   obj = (super == NULL) ? NULL : (jclass) JNIHandles::make_local(super->java_mirror());
 559   return obj;
 560 JNI_END
 561 
 562 JNI_QUICK_ENTRY(jboolean, jni_IsAssignableFrom(JNIEnv *env, jclass sub, jclass super))
 563   JNIWrapper("IsSubclassOf");
 564 
 565   HOTSPOT_JNI_ISASSIGNABLEFROM_ENTRY(env, sub, super);
 566 
 567   oop sub_mirror   = JNIHandles::resolve_non_null(sub);
 568   oop super_mirror = JNIHandles::resolve_non_null(super);
 569   if (java_lang_Class::is_primitive(sub_mirror) ||
 570       java_lang_Class::is_primitive(super_mirror)) {
 571     jboolean ret = (sub_mirror == super_mirror);
 572 
 573     HOTSPOT_JNI_ISASSIGNABLEFROM_RETURN(ret);
 574     return ret;
 575   }
 576   Klass* sub_klass   = java_lang_Class::as_Klass(sub_mirror);
 577   Klass* super_klass = java_lang_Class::as_Klass(super_mirror);
 578   assert(sub_klass != NULL && super_klass != NULL, "invalid arguments to jni_IsAssignableFrom");
 579   jboolean ret = sub_klass->is_subtype_of(super_klass) ?
 580                    JNI_TRUE : JNI_FALSE;
 581 
 582   HOTSPOT_JNI_ISASSIGNABLEFROM_RETURN(ret);
 583   return ret;
 584 JNI_END
 585 
 586 
 587 DT_RETURN_MARK_DECL(Throw, jint
 588                     , HOTSPOT_JNI_THROW_RETURN(_ret_ref));
 589 
 590 JNI_ENTRY(jint, jni_Throw(JNIEnv *env, jthrowable obj))
 591   JNIWrapper("Throw");
 592 
 593   HOTSPOT_JNI_THROW_ENTRY(env, obj);
 594 
 595   jint ret = JNI_OK;
 596   DT_RETURN_MARK(Throw, jint, (const jint&)ret);
 597 
 598   THROW_OOP_(JNIHandles::resolve(obj), JNI_OK);
 599   ShouldNotReachHere();
 600   return 0;  // Mute compiler.
 601 JNI_END
 602 
 603 
 604 DT_RETURN_MARK_DECL(ThrowNew, jint
 605                     , HOTSPOT_JNI_THROWNEW_RETURN(_ret_ref));
 606 
 607 JNI_ENTRY(jint, jni_ThrowNew(JNIEnv *env, jclass clazz, const char *message))
 608   JNIWrapper("ThrowNew");
 609 
 610   HOTSPOT_JNI_THROWNEW_ENTRY(env, clazz, (char *) message);
 611 
 612   jint ret = JNI_OK;
 613   DT_RETURN_MARK(ThrowNew, jint, (const jint&)ret);
 614 
 615   InstanceKlass* k = InstanceKlass::cast(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
 616   Symbol*  name = k->name();
 617   Handle class_loader (THREAD,  k->class_loader());
 618   Handle protection_domain (THREAD, k->protection_domain());
 619   THROW_MSG_LOADER_(name, (char *)message, class_loader, protection_domain, JNI_OK);
 620   ShouldNotReachHere();
 621   return 0;  // Mute compiler.
 622 JNI_END
 623 
 624 
 625 // JNI functions only transform a pending async exception to a synchronous
 626 // exception in ExceptionOccurred and ExceptionCheck calls, since
 627 // delivering an async exception in other places won't change the native
 628 // code's control flow and would be harmful when native code further calls
 629 // JNI functions with a pending exception. Async exception is also checked
 630 // during the call, so ExceptionOccurred/ExceptionCheck won't return
 631 // false but deliver the async exception at the very end during
 632 // state transition.
 633 
 634 static void jni_check_async_exceptions(JavaThread *thread) {
 635   assert(thread == Thread::current(), "must be itself");
 636   thread->check_and_handle_async_exceptions();
 637 }
 638 
 639 JNI_ENTRY_NO_PRESERVE(jthrowable, jni_ExceptionOccurred(JNIEnv *env))
 640   JNIWrapper("ExceptionOccurred");
 641 
 642   HOTSPOT_JNI_EXCEPTIONOCCURRED_ENTRY(env);
 643 
 644   jni_check_async_exceptions(thread);
 645   oop exception = thread->pending_exception();
 646   jthrowable ret = (jthrowable) JNIHandles::make_local(env, exception);
 647 
 648   HOTSPOT_JNI_EXCEPTIONOCCURRED_RETURN(ret);
 649   return ret;
 650 JNI_END
 651 
 652 
 653 JNI_ENTRY_NO_PRESERVE(void, jni_ExceptionDescribe(JNIEnv *env))
 654   JNIWrapper("ExceptionDescribe");
 655 
 656   HOTSPOT_JNI_EXCEPTIONDESCRIBE_ENTRY(env);
 657 
 658   if (thread->has_pending_exception()) {
 659     Handle ex(thread, thread->pending_exception());
 660     thread->clear_pending_exception();
 661     if (ex->is_a(SystemDictionary::ThreadDeath_klass())) {
 662       // Don't print anything if we are being killed.
 663     } else {
 664       jio_fprintf(defaultStream::error_stream(), "Exception ");
 665       if (thread != NULL && thread->threadObj() != NULL) {
 666         ResourceMark rm(THREAD);
 667         jio_fprintf(defaultStream::error_stream(),
 668         "in thread \"%s\" ", thread->get_thread_name());
 669       }
 670       if (ex->is_a(SystemDictionary::Throwable_klass())) {
 671         JavaValue result(T_VOID);
 672         JavaCalls::call_virtual(&result,
 673                                 ex,
 674                                 KlassHandle(THREAD,
 675                                   SystemDictionary::Throwable_klass()),
 676                                 vmSymbols::printStackTrace_name(),
 677                                 vmSymbols::void_method_signature(),
 678                                 THREAD);
 679         // If an exception is thrown in the call it gets thrown away. Not much
 680         // we can do with it. The native code that calls this, does not check
 681         // for the exception - hence, it might still be in the thread when DestroyVM gets
 682         // called, potentially causing a few asserts to trigger - since no pending exception
 683         // is expected.
 684         CLEAR_PENDING_EXCEPTION;
 685       } else {
 686         ResourceMark rm(THREAD);
 687         jio_fprintf(defaultStream::error_stream(),
 688         ". Uncaught exception of type %s.",
 689         ex->klass()->external_name());
 690       }
 691     }
 692   }
 693 
 694   HOTSPOT_JNI_EXCEPTIONDESCRIBE_RETURN();
 695 JNI_END
 696 
 697 
 698 JNI_QUICK_ENTRY(void, jni_ExceptionClear(JNIEnv *env))
 699   JNIWrapper("ExceptionClear");
 700 
 701   HOTSPOT_JNI_EXCEPTIONCLEAR_ENTRY(env);
 702 
 703   // The jni code might be using this API to clear java thrown exception.
 704   // So just mark jvmti thread exception state as exception caught.
 705   JvmtiThreadState *state = JavaThread::current()->jvmti_thread_state();
 706   if (state != NULL && state->is_exception_detected()) {
 707     state->set_exception_caught();
 708   }
 709   thread->clear_pending_exception();
 710 
 711   HOTSPOT_JNI_EXCEPTIONCLEAR_RETURN();
 712 JNI_END
 713 
 714 
 715 JNI_ENTRY(void, jni_FatalError(JNIEnv *env, const char *msg))
 716   JNIWrapper("FatalError");
 717 
 718   HOTSPOT_JNI_FATALERROR_ENTRY(env, (char *) msg);
 719 
 720   tty->print_cr("FATAL ERROR in native method: %s", msg);
 721   thread->print_stack();
 722   os::abort(); // Dump core and abort
 723 JNI_END
 724 
 725 
 726 JNI_ENTRY(jint, jni_PushLocalFrame(JNIEnv *env, jint capacity))
 727   JNIWrapper("PushLocalFrame");
 728 
 729   HOTSPOT_JNI_PUSHLOCALFRAME_ENTRY(env, capacity);
 730 
 731   //%note jni_11
 732   if (capacity < 0 ||
 733       ((MaxJNILocalCapacity > 0) && (capacity > MaxJNILocalCapacity))) {
 734     HOTSPOT_JNI_PUSHLOCALFRAME_RETURN((uint32_t)JNI_ERR);
 735     return JNI_ERR;
 736   }
 737   JNIHandleBlock* old_handles = thread->active_handles();
 738   JNIHandleBlock* new_handles = JNIHandleBlock::allocate_block(thread);
 739   assert(new_handles != NULL, "should not be NULL");
 740   new_handles->set_pop_frame_link(old_handles);
 741   thread->set_active_handles(new_handles);
 742   jint ret = JNI_OK;
 743   HOTSPOT_JNI_PUSHLOCALFRAME_RETURN(ret);
 744   return ret;
 745 JNI_END
 746 
 747 
 748 JNI_ENTRY(jobject, jni_PopLocalFrame(JNIEnv *env, jobject result))
 749   JNIWrapper("PopLocalFrame");
 750 
 751   HOTSPOT_JNI_POPLOCALFRAME_ENTRY(env, result);
 752 
 753   //%note jni_11
 754   Handle result_handle(thread, JNIHandles::resolve(result));
 755   JNIHandleBlock* old_handles = thread->active_handles();
 756   JNIHandleBlock* new_handles = old_handles->pop_frame_link();
 757   if (new_handles != NULL) {
 758     // As a sanity check we only release the handle blocks if the pop_frame_link is not NULL.
 759     // This way code will still work if PopLocalFrame is called without a corresponding
 760     // PushLocalFrame call. Note that we set the pop_frame_link to NULL explicitly, otherwise
 761     // the release_block call will release the blocks.
 762     thread->set_active_handles(new_handles);
 763     old_handles->set_pop_frame_link(NULL);              // clear link we won't release new_handles below
 764     JNIHandleBlock::release_block(old_handles, thread); // may block
 765     result = JNIHandles::make_local(thread, result_handle());
 766   }
 767   HOTSPOT_JNI_POPLOCALFRAME_RETURN(result);
 768   return result;
 769 JNI_END
 770 
 771 
 772 JNI_ENTRY(jobject, jni_NewGlobalRef(JNIEnv *env, jobject ref))
 773   JNIWrapper("NewGlobalRef");
 774 
 775   HOTSPOT_JNI_NEWGLOBALREF_ENTRY(env, ref);
 776 
 777   Handle ref_handle(thread, JNIHandles::resolve(ref));
 778   jobject ret = JNIHandles::make_global(ref_handle);
 779 
 780   HOTSPOT_JNI_NEWGLOBALREF_RETURN(ret);
 781   return ret;
 782 JNI_END
 783 
 784 // Must be JNI_ENTRY (with HandleMark)
 785 JNI_ENTRY_NO_PRESERVE(void, jni_DeleteGlobalRef(JNIEnv *env, jobject ref))
 786   JNIWrapper("DeleteGlobalRef");
 787 
 788   HOTSPOT_JNI_DELETEGLOBALREF_ENTRY(env, ref);
 789 
 790   JNIHandles::destroy_global(ref);
 791 
 792   HOTSPOT_JNI_DELETEGLOBALREF_RETURN();
 793 JNI_END
 794 
 795 JNI_QUICK_ENTRY(void, jni_DeleteLocalRef(JNIEnv *env, jobject obj))
 796   JNIWrapper("DeleteLocalRef");
 797 
 798   HOTSPOT_JNI_DELETELOCALREF_ENTRY(env, obj);
 799 
 800   JNIHandles::destroy_local(obj);
 801 
 802   HOTSPOT_JNI_DELETELOCALREF_RETURN();
 803 JNI_END
 804 
 805 JNI_QUICK_ENTRY(jboolean, jni_IsSameObject(JNIEnv *env, jobject r1, jobject r2))
 806   JNIWrapper("IsSameObject");
 807 
 808   HOTSPOT_JNI_ISSAMEOBJECT_ENTRY(env, r1, r2);
 809 
 810   oop a = JNIHandles::resolve(r1);
 811   oop b = JNIHandles::resolve(r2);
 812   jboolean ret = (a == b) ? JNI_TRUE : JNI_FALSE;
 813 
 814   HOTSPOT_JNI_ISSAMEOBJECT_RETURN(ret);
 815   return ret;
 816 JNI_END
 817 
 818 
 819 JNI_ENTRY(jobject, jni_NewLocalRef(JNIEnv *env, jobject ref))
 820   JNIWrapper("NewLocalRef");
 821 
 822   HOTSPOT_JNI_NEWLOCALREF_ENTRY(env, ref);
 823 
 824   jobject ret = JNIHandles::make_local(env, JNIHandles::resolve(ref));
 825 
 826   HOTSPOT_JNI_NEWLOCALREF_RETURN(ret);
 827   return ret;
 828 JNI_END
 829 
 830 JNI_LEAF(jint, jni_EnsureLocalCapacity(JNIEnv *env, jint capacity))
 831   JNIWrapper("EnsureLocalCapacity");
 832 
 833   HOTSPOT_JNI_ENSURELOCALCAPACITY_ENTRY(env, capacity);
 834 
 835   jint ret;
 836   if (capacity >= 0 &&
 837       ((MaxJNILocalCapacity <= 0) || (capacity <= MaxJNILocalCapacity))) {
 838     ret = JNI_OK;
 839   } else {
 840     ret = JNI_ERR;
 841   }
 842 
 843   HOTSPOT_JNI_ENSURELOCALCAPACITY_RETURN(ret);
 844   return ret;
 845 JNI_END
 846 
 847 // Return the Handle Type
 848 JNI_LEAF(jobjectRefType, jni_GetObjectRefType(JNIEnv *env, jobject obj))
 849   JNIWrapper("GetObjectRefType");
 850 
 851   HOTSPOT_JNI_GETOBJECTREFTYPE_ENTRY(env, obj);
 852 
 853   jobjectRefType ret;
 854   if (JNIHandles::is_local_handle(thread, obj) ||
 855       JNIHandles::is_frame_handle(thread, obj))
 856     ret = JNILocalRefType;
 857   else if (JNIHandles::is_global_handle(obj))
 858     ret = JNIGlobalRefType;
 859   else if (JNIHandles::is_weak_global_handle(obj))
 860     ret = JNIWeakGlobalRefType;
 861   else
 862     ret = JNIInvalidRefType;
 863 
 864   HOTSPOT_JNI_GETOBJECTREFTYPE_RETURN((void *) ret);
 865   return ret;
 866 JNI_END
 867 
 868 
 869 class JNI_ArgumentPusher : public SignatureIterator {
 870  protected:
 871   JavaCallArguments*  _arguments;
 872 
 873   virtual void get_bool   () = 0;
 874   virtual void get_char   () = 0;
 875   virtual void get_short  () = 0;
 876   virtual void get_byte   () = 0;
 877   virtual void get_int    () = 0;
 878   virtual void get_long   () = 0;
 879   virtual void get_float  () = 0;
 880   virtual void get_double () = 0;
 881   virtual void get_object () = 0;
 882 
 883   JNI_ArgumentPusher(Symbol* signature) : SignatureIterator(signature) {
 884     this->_return_type = T_ILLEGAL;
 885     _arguments = NULL;
 886   }
 887 
 888  public:
 889   virtual void iterate( uint64_t fingerprint ) = 0;
 890 
 891   void set_java_argument_object(JavaCallArguments *arguments) { _arguments = arguments; }
 892 
 893   inline void do_bool()                     { if (!is_return_type()) get_bool();   }
 894   inline void do_char()                     { if (!is_return_type()) get_char();   }
 895   inline void do_short()                    { if (!is_return_type()) get_short();  }
 896   inline void do_byte()                     { if (!is_return_type()) get_byte();   }
 897   inline void do_int()                      { if (!is_return_type()) get_int();    }
 898   inline void do_long()                     { if (!is_return_type()) get_long();   }
 899   inline void do_float()                    { if (!is_return_type()) get_float();  }
 900   inline void do_double()                   { if (!is_return_type()) get_double(); }
 901   inline void do_object(int begin, int end) { if (!is_return_type()) get_object(); }
 902   inline void do_array(int begin, int end)  { if (!is_return_type()) get_object(); } // do_array uses get_object -- there is no get_array
 903   inline void do_void()                     { }
 904 
 905   JavaCallArguments* arguments()     { return _arguments; }
 906   void push_receiver(Handle h)       { _arguments->push_oop(h); }
 907 };
 908 
 909 
 910 class JNI_ArgumentPusherVaArg : public JNI_ArgumentPusher {
 911  protected:
 912   va_list _ap;
 913 
 914   inline void get_bool()   { _arguments->push_int(va_arg(_ap, jint)); } // bool is coerced to int when using va_arg
 915   inline void get_char()   { _arguments->push_int(va_arg(_ap, jint)); } // char is coerced to int when using va_arg
 916   inline void get_short()  { _arguments->push_int(va_arg(_ap, jint)); } // short is coerced to int when using va_arg
 917   inline void get_byte()   { _arguments->push_int(va_arg(_ap, jint)); } // byte is coerced to int when using va_arg
 918   inline void get_int()    { _arguments->push_int(va_arg(_ap, jint)); }
 919 
 920   // each of these paths is exercized by the various jck Call[Static,Nonvirtual,][Void,Int,..]Method[A,V,] tests
 921 
 922   inline void get_long()   { _arguments->push_long(va_arg(_ap, jlong)); }
 923   inline void get_float()  { _arguments->push_float((jfloat)va_arg(_ap, jdouble)); } // float is coerced to double w/ va_arg
 924   inline void get_double() { _arguments->push_double(va_arg(_ap, jdouble)); }
 925   inline void get_object() { jobject l = va_arg(_ap, jobject);
 926                              _arguments->push_oop(Handle((oop *)l, false)); }
 927 
 928   inline void set_ap(va_list rap) {
 929 #ifdef va_copy
 930     va_copy(_ap, rap);
 931 #elif defined (__va_copy)
 932     __va_copy(_ap, rap);
 933 #else
 934     _ap = rap;
 935 #endif
 936   }
 937 
 938  public:
 939   JNI_ArgumentPusherVaArg(Symbol* signature, va_list rap)
 940        : JNI_ArgumentPusher(signature) {
 941     set_ap(rap);
 942   }
 943   JNI_ArgumentPusherVaArg(jmethodID method_id, va_list rap)
 944       : JNI_ArgumentPusher(Method::resolve_jmethod_id(method_id)->signature()) {
 945     set_ap(rap);
 946   }
 947 
 948   // Optimized path if we have the bitvector form of signature
 949   void iterate( uint64_t fingerprint ) {
 950     if (fingerprint == (uint64_t)CONST64(-1)) {
 951       SignatureIterator::iterate(); // Must be too many arguments
 952     } else {
 953       _return_type = (BasicType)((fingerprint >> static_feature_size) &
 954                                   result_feature_mask);
 955 
 956       assert(fingerprint, "Fingerprint should not be 0");
 957       fingerprint = fingerprint >> (static_feature_size + result_feature_size);
 958       while ( 1 ) {
 959         switch ( fingerprint & parameter_feature_mask ) {
 960           case bool_parm:
 961           case char_parm:
 962           case short_parm:
 963           case byte_parm:
 964           case int_parm:
 965             get_int();
 966             break;
 967           case obj_parm:
 968             get_object();
 969             break;
 970           case long_parm:
 971             get_long();
 972             break;
 973           case float_parm:
 974             get_float();
 975             break;
 976           case double_parm:
 977             get_double();
 978             break;
 979           case done_parm:
 980             return;
 981             break;
 982           default:
 983             ShouldNotReachHere();
 984             break;
 985         }
 986         fingerprint >>= parameter_feature_size;
 987       }
 988     }
 989   }
 990 };
 991 
 992 
 993 class JNI_ArgumentPusherArray : public JNI_ArgumentPusher {
 994  protected:
 995   const jvalue *_ap;
 996 
 997   inline void get_bool()   { _arguments->push_int((jint)(_ap++)->z); }
 998   inline void get_char()   { _arguments->push_int((jint)(_ap++)->c); }
 999   inline void get_short()  { _arguments->push_int((jint)(_ap++)->s); }
1000   inline void get_byte()   { _arguments->push_int((jint)(_ap++)->b); }
1001   inline void get_int()    { _arguments->push_int((jint)(_ap++)->i); }
1002 
1003   inline void get_long()   { _arguments->push_long((_ap++)->j);  }
1004   inline void get_float()  { _arguments->push_float((_ap++)->f); }
1005   inline void get_double() { _arguments->push_double((_ap++)->d);}
1006   inline void get_object() { _arguments->push_oop(Handle((oop *)(_ap++)->l, false)); }
1007 
1008   inline void set_ap(const jvalue *rap) { _ap = rap; }
1009 
1010  public:
1011   JNI_ArgumentPusherArray(Symbol* signature, const jvalue *rap)
1012        : JNI_ArgumentPusher(signature) {
1013     set_ap(rap);
1014   }
1015   JNI_ArgumentPusherArray(jmethodID method_id, const jvalue *rap)
1016       : JNI_ArgumentPusher(Method::resolve_jmethod_id(method_id)->signature()) {
1017     set_ap(rap);
1018   }
1019 
1020   // Optimized path if we have the bitvector form of signature
1021   void iterate( uint64_t fingerprint ) {
1022     if (fingerprint == (uint64_t)CONST64(-1)) {
1023       SignatureIterator::iterate(); // Must be too many arguments
1024     } else {
1025       _return_type = (BasicType)((fingerprint >> static_feature_size) &
1026                                   result_feature_mask);
1027       assert(fingerprint, "Fingerprint should not be 0");
1028       fingerprint = fingerprint >> (static_feature_size + result_feature_size);
1029       while ( 1 ) {
1030         switch ( fingerprint & parameter_feature_mask ) {
1031           case bool_parm:
1032             get_bool();
1033             break;
1034           case char_parm:
1035             get_char();
1036             break;
1037           case short_parm:
1038             get_short();
1039             break;
1040           case byte_parm:
1041             get_byte();
1042             break;
1043           case int_parm:
1044             get_int();
1045             break;
1046           case obj_parm:
1047             get_object();
1048             break;
1049           case long_parm:
1050             get_long();
1051             break;
1052           case float_parm:
1053             get_float();
1054             break;
1055           case double_parm:
1056             get_double();
1057             break;
1058           case done_parm:
1059             return;
1060             break;
1061           default:
1062             ShouldNotReachHere();
1063             break;
1064         }
1065         fingerprint >>= parameter_feature_size;
1066       }
1067     }
1068   }
1069 };
1070 
1071 
1072 enum JNICallType {
1073   JNI_STATIC,
1074   JNI_VIRTUAL,
1075   JNI_NONVIRTUAL
1076 };
1077 
1078 
1079 
1080 static void jni_invoke_static(JNIEnv *env, JavaValue* result, jobject receiver, JNICallType call_type, jmethodID method_id, JNI_ArgumentPusher *args, TRAPS) {
1081   methodHandle method(THREAD, Method::resolve_jmethod_id(method_id));
1082 
1083   // Create object to hold arguments for the JavaCall, and associate it with
1084   // the jni parser
1085   ResourceMark rm(THREAD);
1086   int number_of_parameters = method->size_of_parameters();
1087   JavaCallArguments java_args(number_of_parameters);
1088   args->set_java_argument_object(&java_args);
1089 
1090   assert(method->is_static(), "method should be static");
1091 
1092   // Fill out JavaCallArguments object
1093   args->iterate( Fingerprinter(method).fingerprint() );
1094   // Initialize result type
1095   result->set_type(args->get_ret_type());
1096 
1097   // Invoke the method. Result is returned as oop.
1098   JavaCalls::call(result, method, &java_args, CHECK);
1099 
1100   // Convert result
1101   if (result->get_type() == T_OBJECT || result->get_type() == T_ARRAY) {
1102     result->set_jobject(JNIHandles::make_local(env, (oop) result->get_jobject()));
1103   }
1104 }
1105 
1106 
1107 static void jni_invoke_nonstatic(JNIEnv *env, JavaValue* result, jobject receiver, JNICallType call_type, jmethodID method_id, JNI_ArgumentPusher *args, TRAPS) {
1108   oop recv = JNIHandles::resolve(receiver);
1109   if (recv == NULL) {
1110     THROW(vmSymbols::java_lang_NullPointerException());
1111   }
1112   Handle h_recv(THREAD, recv);
1113 
1114   int number_of_parameters;
1115   Method* selected_method;
1116   {
1117     Method* m = Method::resolve_jmethod_id(method_id);
1118     number_of_parameters = m->size_of_parameters();
1119     Klass* holder = m->method_holder();
1120     if (call_type != JNI_VIRTUAL) {
1121         selected_method = m;
1122     } else if (!m->has_itable_index()) {
1123       // non-interface call -- for that little speed boost, don't handlize
1124       debug_only(No_Safepoint_Verifier nosafepoint;)
1125       // jni_GetMethodID makes sure class is linked and initialized
1126       // so m should have a valid vtable index.
1127       assert(m->valid_vtable_index(), "no valid vtable index");
1128       int vtbl_index = m->vtable_index();
1129       if (vtbl_index != Method::nonvirtual_vtable_index) {
1130         Klass* k = h_recv->klass();
1131         // k might be an arrayKlassOop but all vtables start at
1132         // the same place. The cast is to avoid virtual call and assertion.
1133         InstanceKlass *ik = (InstanceKlass*)k;
1134         selected_method = ik->method_at_vtable(vtbl_index);
1135       } else {
1136         // final method
1137         selected_method = m;
1138       }
1139     } else {
1140       // interface call
1141       KlassHandle h_holder(THREAD, holder);
1142 
1143       int itbl_index = m->itable_index();
1144       Klass* k = h_recv->klass();
1145       selected_method = InstanceKlass::cast(k)->method_at_itable(h_holder(), itbl_index, CHECK);
1146     }
1147   }
1148 
1149   methodHandle method(THREAD, selected_method);
1150 
1151   // Create object to hold arguments for the JavaCall, and associate it with
1152   // the jni parser
1153   ResourceMark rm(THREAD);
1154   JavaCallArguments java_args(number_of_parameters);
1155   args->set_java_argument_object(&java_args);
1156 
1157   // handle arguments
1158   assert(!method->is_static(), "method should not be static");
1159   args->push_receiver(h_recv); // Push jobject handle
1160 
1161   // Fill out JavaCallArguments object
1162   args->iterate( Fingerprinter(method).fingerprint() );
1163   // Initialize result type
1164   result->set_type(args->get_ret_type());
1165 
1166   // Invoke the method. Result is returned as oop.
1167   JavaCalls::call(result, method, &java_args, CHECK);
1168 
1169   // Convert result
1170   if (result->get_type() == T_OBJECT || result->get_type() == T_ARRAY) {
1171     result->set_jobject(JNIHandles::make_local(env, (oop) result->get_jobject()));
1172   }
1173 }
1174 
1175 
1176 static instanceOop alloc_object(jclass clazz, TRAPS) {
1177   KlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
1178   if (k == NULL) {
1179     ResourceMark rm(THREAD);
1180     THROW_(vmSymbols::java_lang_InstantiationException(), NULL);
1181   }
1182   k()->check_valid_for_instantiation(false, CHECK_NULL);
1183   InstanceKlass::cast(k())->initialize(CHECK_NULL);
1184   instanceOop ih = InstanceKlass::cast(k())->allocate_instance(THREAD);
1185   return ih;
1186 }
1187 
1188 DT_RETURN_MARK_DECL(AllocObject, jobject
1189                     , HOTSPOT_JNI_ALLOCOBJECT_RETURN(_ret_ref));
1190 
1191 JNI_ENTRY(jobject, jni_AllocObject(JNIEnv *env, jclass clazz))
1192   JNIWrapper("AllocObject");
1193 
1194   HOTSPOT_JNI_ALLOCOBJECT_ENTRY(env, clazz);
1195 
1196   jobject ret = NULL;
1197   DT_RETURN_MARK(AllocObject, jobject, (const jobject&)ret);
1198 
1199   instanceOop i = alloc_object(clazz, CHECK_NULL);
1200   ret = JNIHandles::make_local(env, i);
1201   return ret;
1202 JNI_END
1203 
1204 DT_RETURN_MARK_DECL(NewObjectA, jobject
1205                     , HOTSPOT_JNI_NEWOBJECTA_RETURN(_ret_ref));
1206 
1207 JNI_ENTRY(jobject, jni_NewObjectA(JNIEnv *env, jclass clazz, jmethodID methodID, const jvalue *args))
1208   JNIWrapper("NewObjectA");
1209 
1210   HOTSPOT_JNI_NEWOBJECTA_ENTRY(env, clazz, (uintptr_t) methodID);
1211 
1212   jobject obj = NULL;
1213   DT_RETURN_MARK(NewObjectA, jobject, (const jobject)obj);
1214 
1215   instanceOop i = alloc_object(clazz, CHECK_NULL);
1216   obj = JNIHandles::make_local(env, i);
1217   JavaValue jvalue(T_VOID);
1218   JNI_ArgumentPusherArray ap(methodID, args);
1219   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_NULL);
1220   return obj;
1221 JNI_END
1222 
1223 
1224 DT_RETURN_MARK_DECL(NewObjectV, jobject
1225                     , HOTSPOT_JNI_NEWOBJECTV_RETURN(_ret_ref));
1226 
1227 JNI_ENTRY(jobject, jni_NewObjectV(JNIEnv *env, jclass clazz, jmethodID methodID, va_list args))
1228   JNIWrapper("NewObjectV");
1229 
1230   HOTSPOT_JNI_NEWOBJECTV_ENTRY(env, clazz, (uintptr_t) methodID);
1231 
1232   jobject obj = NULL;
1233   DT_RETURN_MARK(NewObjectV, jobject, (const jobject&)obj);
1234 
1235   instanceOop i = alloc_object(clazz, CHECK_NULL);
1236   obj = JNIHandles::make_local(env, i);
1237   JavaValue jvalue(T_VOID);
1238   JNI_ArgumentPusherVaArg ap(methodID, args);
1239   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_NULL);
1240   return obj;
1241 JNI_END
1242 
1243 
1244 DT_RETURN_MARK_DECL(NewObject, jobject
1245                     , HOTSPOT_JNI_NEWOBJECT_RETURN(_ret_ref));
1246 
1247 JNI_ENTRY(jobject, jni_NewObject(JNIEnv *env, jclass clazz, jmethodID methodID, ...))
1248   JNIWrapper("NewObject");
1249 
1250   HOTSPOT_JNI_NEWOBJECT_ENTRY(env, clazz, (uintptr_t) methodID);
1251 
1252   jobject obj = NULL;
1253   DT_RETURN_MARK(NewObject, jobject, (const jobject&)obj);
1254 
1255   instanceOop i = alloc_object(clazz, CHECK_NULL);
1256   obj = JNIHandles::make_local(env, i);
1257   va_list args;
1258   va_start(args, methodID);
1259   JavaValue jvalue(T_VOID);
1260   JNI_ArgumentPusherVaArg ap(methodID, args);
1261   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_NULL);
1262   va_end(args);
1263   return obj;
1264 JNI_END
1265 
1266 
1267 JNI_ENTRY(jclass, jni_GetObjectClass(JNIEnv *env, jobject obj))
1268   JNIWrapper("GetObjectClass");
1269 
1270   HOTSPOT_JNI_GETOBJECTCLASS_ENTRY(env, obj);
1271 
1272   Klass* k = JNIHandles::resolve_non_null(obj)->klass();
1273   jclass ret =
1274     (jclass) JNIHandles::make_local(env, k->java_mirror());
1275 
1276   HOTSPOT_JNI_GETOBJECTCLASS_RETURN(ret);
1277   return ret;
1278 JNI_END
1279 
1280 JNI_QUICK_ENTRY(jboolean, jni_IsInstanceOf(JNIEnv *env, jobject obj, jclass clazz))
1281   JNIWrapper("IsInstanceOf");
1282 
1283   HOTSPOT_JNI_ISINSTANCEOF_ENTRY(env, obj, clazz);
1284 
1285   jboolean ret = JNI_TRUE;
1286   if (obj != NULL) {
1287     ret = JNI_FALSE;
1288     Klass* k = java_lang_Class::as_Klass(
1289       JNIHandles::resolve_non_null(clazz));
1290     if (k != NULL) {
1291       ret = JNIHandles::resolve_non_null(obj)->is_a(k) ? JNI_TRUE : JNI_FALSE;
1292     }
1293   }
1294 
1295   HOTSPOT_JNI_ISINSTANCEOF_RETURN(ret);
1296   return ret;
1297 JNI_END
1298 
1299 
1300 static jmethodID get_method_id(JNIEnv *env, jclass clazz, const char *name_str,
1301                                const char *sig, bool is_static, TRAPS) {
1302   // %%%% This code should probably just call into a method in the LinkResolver
1303   //
1304   // The class should have been loaded (we have an instance of the class
1305   // passed in) so the method and signature should already be in the symbol
1306   // table.  If they're not there, the method doesn't exist.
1307   const char *name_to_probe = (name_str == NULL)
1308                         ? vmSymbols::object_initializer_name()->as_C_string()
1309                         : name_str;
1310   TempNewSymbol name = SymbolTable::probe(name_to_probe, (int)strlen(name_to_probe));
1311   TempNewSymbol signature = SymbolTable::probe(sig, (int)strlen(sig));
1312 
1313   if (name == NULL || signature == NULL) {
1314     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(), name_str);
1315   }
1316 
1317   // Throw a NoSuchMethodError exception if we have an instance of a
1318   // primitive java.lang.Class
1319   if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(clazz))) {
1320     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(), name_str);
1321   }
1322 
1323   KlassHandle klass(THREAD,
1324                java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
1325 
1326   // Make sure class is linked and initialized before handing id's out to
1327   // Method*s.
1328   klass()->initialize(CHECK_NULL);
1329 
1330   Method* m;
1331   if (name == vmSymbols::object_initializer_name() ||
1332       name == vmSymbols::class_initializer_name()) {
1333     // Never search superclasses for constructors
1334     if (klass->is_instance_klass()) {
1335       m = InstanceKlass::cast(klass())->find_method(name, signature);
1336     } else {
1337       m = NULL;
1338     }
1339   } else {
1340     m = klass->lookup_method(name, signature);
1341     if (m == NULL &&  klass->is_instance_klass()) {
1342       m = InstanceKlass::cast(klass())->lookup_method_in_ordered_interfaces(name, signature);
1343     }
1344   }
1345   if (m == NULL || (m->is_static() != is_static)) {
1346     THROW_MSG_0(vmSymbols::java_lang_NoSuchMethodError(), name_str);
1347   }
1348   return m->jmethod_id();
1349 }
1350 
1351 
1352 JNI_ENTRY(jmethodID, jni_GetMethodID(JNIEnv *env, jclass clazz,
1353           const char *name, const char *sig))
1354   JNIWrapper("GetMethodID");
1355   HOTSPOT_JNI_GETMETHODID_ENTRY(env, clazz, (char *) name, (char *) sig);
1356   jmethodID ret = get_method_id(env, clazz, name, sig, false, thread);
1357   HOTSPOT_JNI_GETMETHODID_RETURN((uintptr_t) ret);
1358   return ret;
1359 JNI_END
1360 
1361 
1362 JNI_ENTRY(jmethodID, jni_GetStaticMethodID(JNIEnv *env, jclass clazz,
1363           const char *name, const char *sig))
1364   JNIWrapper("GetStaticMethodID");
1365   HOTSPOT_JNI_GETSTATICMETHODID_ENTRY(env, (char *) clazz, (char *) name, (char *)sig);
1366   jmethodID ret = get_method_id(env, clazz, name, sig, true, thread);
1367   HOTSPOT_JNI_GETSTATICMETHODID_RETURN((uintptr_t) ret);
1368   return ret;
1369 JNI_END
1370 
1371 
1372 
1373 //
1374 // Calling Methods
1375 //
1376 
1377 
1378 #define DEFINE_CALLMETHOD(ResultType, Result, Tag \
1379                           , EntryProbe, ReturnProbe)    \
1380 \
1381   DT_RETURN_MARK_DECL_FOR(Result, Call##Result##Method, ResultType \
1382                           , ReturnProbe);                          \
1383 \
1384 JNI_ENTRY(ResultType, \
1385           jni_Call##Result##Method(JNIEnv *env, jobject obj, jmethodID methodID, ...)) \
1386   JNIWrapper("Call" XSTR(Result) "Method"); \
1387 \
1388   EntryProbe; \
1389   ResultType ret = 0;\
1390   DT_RETURN_MARK_FOR(Result, Call##Result##Method, ResultType, \
1391                      (const ResultType&)ret);\
1392 \
1393   va_list args; \
1394   va_start(args, methodID); \
1395   JavaValue jvalue(Tag); \
1396   JNI_ArgumentPusherVaArg ap(methodID, args); \
1397   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK_0); \
1398   va_end(args); \
1399   ret = jvalue.get_##ResultType(); \
1400   return ret;\
1401 JNI_END
1402 
1403 // the runtime type of subword integral basic types is integer
1404 DEFINE_CALLMETHOD(jboolean, Boolean, T_BOOLEAN
1405                   , HOTSPOT_JNI_CALLBOOLEANMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1406                   HOTSPOT_JNI_CALLBOOLEANMETHOD_RETURN(_ret_ref))
1407 DEFINE_CALLMETHOD(jbyte,    Byte,    T_BYTE
1408                   , HOTSPOT_JNI_CALLBYTEMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1409                   HOTSPOT_JNI_CALLBYTEMETHOD_RETURN(_ret_ref))
1410 DEFINE_CALLMETHOD(jchar,    Char,    T_CHAR
1411                   , HOTSPOT_JNI_CALLCHARMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1412                   HOTSPOT_JNI_CALLCHARMETHOD_RETURN(_ret_ref))
1413 DEFINE_CALLMETHOD(jshort,   Short,   T_SHORT
1414                   , HOTSPOT_JNI_CALLSHORTMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1415                   HOTSPOT_JNI_CALLSHORTMETHOD_RETURN(_ret_ref))
1416 
1417 DEFINE_CALLMETHOD(jobject,  Object,  T_OBJECT
1418                   , HOTSPOT_JNI_CALLOBJECTMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1419                   HOTSPOT_JNI_CALLOBJECTMETHOD_RETURN(_ret_ref))
1420 DEFINE_CALLMETHOD(jint,     Int,     T_INT,
1421                   HOTSPOT_JNI_CALLINTMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1422                   HOTSPOT_JNI_CALLINTMETHOD_RETURN(_ret_ref))
1423 DEFINE_CALLMETHOD(jlong,    Long,    T_LONG
1424                   , HOTSPOT_JNI_CALLLONGMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1425                   HOTSPOT_JNI_CALLLONGMETHOD_RETURN(_ret_ref))
1426 // Float and double probes don't return value because dtrace doesn't currently support it
1427 DEFINE_CALLMETHOD(jfloat,   Float,   T_FLOAT
1428                   , HOTSPOT_JNI_CALLFLOATMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1429                   HOTSPOT_JNI_CALLFLOATMETHOD_RETURN())
1430 DEFINE_CALLMETHOD(jdouble,  Double,  T_DOUBLE
1431                   , HOTSPOT_JNI_CALLDOUBLEMETHOD_ENTRY(env, obj, (uintptr_t)methodID),
1432                   HOTSPOT_JNI_CALLDOUBLEMETHOD_RETURN())
1433 
1434 #define DEFINE_CALLMETHODV(ResultType, Result, Tag \
1435                           , EntryProbe, ReturnProbe)    \
1436 \
1437   DT_RETURN_MARK_DECL_FOR(Result, Call##Result##MethodV, ResultType \
1438                           , ReturnProbe);                          \
1439 \
1440 JNI_ENTRY(ResultType, \
1441           jni_Call##Result##MethodV(JNIEnv *env, jobject obj, jmethodID methodID, va_list args)) \
1442   JNIWrapper("Call" XSTR(Result) "MethodV"); \
1443 \
1444   EntryProbe;\
1445   ResultType ret = 0;\
1446   DT_RETURN_MARK_FOR(Result, Call##Result##MethodV, ResultType, \
1447                      (const ResultType&)ret);\
1448 \
1449   JavaValue jvalue(Tag); \
1450   JNI_ArgumentPusherVaArg ap(methodID, args); \
1451   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK_0); \
1452   ret = jvalue.get_##ResultType(); \
1453   return ret;\
1454 JNI_END
1455 
1456 // the runtime type of subword integral basic types is integer
1457 DEFINE_CALLMETHODV(jboolean, Boolean, T_BOOLEAN
1458                   , HOTSPOT_JNI_CALLBOOLEANMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1459                   HOTSPOT_JNI_CALLBOOLEANMETHODV_RETURN(_ret_ref))
1460 DEFINE_CALLMETHODV(jbyte,    Byte,    T_BYTE
1461                   , HOTSPOT_JNI_CALLBYTEMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1462                   HOTSPOT_JNI_CALLBYTEMETHODV_RETURN(_ret_ref))
1463 DEFINE_CALLMETHODV(jchar,    Char,    T_CHAR
1464                   , HOTSPOT_JNI_CALLCHARMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1465                   HOTSPOT_JNI_CALLCHARMETHODV_RETURN(_ret_ref))
1466 DEFINE_CALLMETHODV(jshort,   Short,   T_SHORT
1467                   , HOTSPOT_JNI_CALLSHORTMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1468                   HOTSPOT_JNI_CALLSHORTMETHODV_RETURN(_ret_ref))
1469 
1470 DEFINE_CALLMETHODV(jobject,  Object,  T_OBJECT
1471                   , HOTSPOT_JNI_CALLOBJECTMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1472                   HOTSPOT_JNI_CALLOBJECTMETHODV_RETURN(_ret_ref))
1473 DEFINE_CALLMETHODV(jint,     Int,     T_INT,
1474                   HOTSPOT_JNI_CALLINTMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1475                   HOTSPOT_JNI_CALLINTMETHODV_RETURN(_ret_ref))
1476 DEFINE_CALLMETHODV(jlong,    Long,    T_LONG
1477                   , HOTSPOT_JNI_CALLLONGMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1478                   HOTSPOT_JNI_CALLLONGMETHODV_RETURN(_ret_ref))
1479 // Float and double probes don't return value because dtrace doesn't currently support it
1480 DEFINE_CALLMETHODV(jfloat,   Float,   T_FLOAT
1481                   , HOTSPOT_JNI_CALLFLOATMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1482                   HOTSPOT_JNI_CALLFLOATMETHODV_RETURN())
1483 DEFINE_CALLMETHODV(jdouble,  Double,  T_DOUBLE
1484                   , HOTSPOT_JNI_CALLDOUBLEMETHODV_ENTRY(env, obj, (uintptr_t)methodID),
1485                   HOTSPOT_JNI_CALLDOUBLEMETHODV_RETURN())
1486 
1487 #define DEFINE_CALLMETHODA(ResultType, Result, Tag \
1488                           , EntryProbe, ReturnProbe)    \
1489 \
1490   DT_RETURN_MARK_DECL_FOR(Result, Call##Result##MethodA, ResultType \
1491                           , ReturnProbe);                          \
1492 \
1493 JNI_ENTRY(ResultType, \
1494           jni_Call##Result##MethodA(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args)) \
1495   JNIWrapper("Call" XSTR(Result) "MethodA"); \
1496   EntryProbe; \
1497   ResultType ret = 0;\
1498   DT_RETURN_MARK_FOR(Result, Call##Result##MethodA, ResultType, \
1499                      (const ResultType&)ret);\
1500 \
1501   JavaValue jvalue(Tag); \
1502   JNI_ArgumentPusherArray ap(methodID, args); \
1503   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK_0); \
1504   ret = jvalue.get_##ResultType(); \
1505   return ret;\
1506 JNI_END
1507 
1508 // the runtime type of subword integral basic types is integer
1509 DEFINE_CALLMETHODA(jboolean, Boolean, T_BOOLEAN
1510                   , HOTSPOT_JNI_CALLBOOLEANMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1511                   HOTSPOT_JNI_CALLBOOLEANMETHODA_RETURN(_ret_ref))
1512 DEFINE_CALLMETHODA(jbyte,    Byte,    T_BYTE
1513                   , HOTSPOT_JNI_CALLBYTEMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1514                   HOTSPOT_JNI_CALLBYTEMETHODA_RETURN(_ret_ref))
1515 DEFINE_CALLMETHODA(jchar,    Char,    T_CHAR
1516                   , HOTSPOT_JNI_CALLCHARMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1517                   HOTSPOT_JNI_CALLCHARMETHODA_RETURN(_ret_ref))
1518 DEFINE_CALLMETHODA(jshort,   Short,   T_SHORT
1519                   , HOTSPOT_JNI_CALLSHORTMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1520                   HOTSPOT_JNI_CALLSHORTMETHODA_RETURN(_ret_ref))
1521 
1522 DEFINE_CALLMETHODA(jobject,  Object,  T_OBJECT
1523                   , HOTSPOT_JNI_CALLOBJECTMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1524                   HOTSPOT_JNI_CALLOBJECTMETHODA_RETURN(_ret_ref))
1525 DEFINE_CALLMETHODA(jint,     Int,     T_INT,
1526                   HOTSPOT_JNI_CALLINTMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1527                   HOTSPOT_JNI_CALLINTMETHODA_RETURN(_ret_ref))
1528 DEFINE_CALLMETHODA(jlong,    Long,    T_LONG
1529                   , HOTSPOT_JNI_CALLLONGMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1530                   HOTSPOT_JNI_CALLLONGMETHODA_RETURN(_ret_ref))
1531 // Float and double probes don't return value because dtrace doesn't currently support it
1532 DEFINE_CALLMETHODA(jfloat,   Float,   T_FLOAT
1533                   , HOTSPOT_JNI_CALLFLOATMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1534                   HOTSPOT_JNI_CALLFLOATMETHODA_RETURN())
1535 DEFINE_CALLMETHODA(jdouble,  Double,  T_DOUBLE
1536                   , HOTSPOT_JNI_CALLDOUBLEMETHODA_ENTRY(env, obj, (uintptr_t)methodID),
1537                   HOTSPOT_JNI_CALLDOUBLEMETHODA_RETURN())
1538 
1539 DT_VOID_RETURN_MARK_DECL(CallVoidMethod, HOTSPOT_JNI_CALLVOIDMETHOD_RETURN());
1540 DT_VOID_RETURN_MARK_DECL(CallVoidMethodV, HOTSPOT_JNI_CALLVOIDMETHODV_RETURN());
1541 DT_VOID_RETURN_MARK_DECL(CallVoidMethodA, HOTSPOT_JNI_CALLVOIDMETHODA_RETURN());
1542 
1543 
1544 JNI_ENTRY(void, jni_CallVoidMethod(JNIEnv *env, jobject obj, jmethodID methodID, ...))
1545   JNIWrapper("CallVoidMethod");
1546   HOTSPOT_JNI_CALLVOIDMETHOD_ENTRY(env, obj, (uintptr_t) methodID);
1547   DT_VOID_RETURN_MARK(CallVoidMethod);
1548 
1549   va_list args;
1550   va_start(args, methodID);
1551   JavaValue jvalue(T_VOID);
1552   JNI_ArgumentPusherVaArg ap(methodID, args);
1553   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK);
1554   va_end(args);
1555 JNI_END
1556 
1557 
1558 JNI_ENTRY(void, jni_CallVoidMethodV(JNIEnv *env, jobject obj, jmethodID methodID, va_list args))
1559   JNIWrapper("CallVoidMethodV");
1560   HOTSPOT_JNI_CALLVOIDMETHODV_ENTRY(env, obj, (uintptr_t) methodID);
1561   DT_VOID_RETURN_MARK(CallVoidMethodV);
1562 
1563   JavaValue jvalue(T_VOID);
1564   JNI_ArgumentPusherVaArg ap(methodID, args);
1565   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK);
1566 JNI_END
1567 
1568 
1569 JNI_ENTRY(void, jni_CallVoidMethodA(JNIEnv *env, jobject obj, jmethodID methodID, const jvalue *args))
1570   JNIWrapper("CallVoidMethodA");
1571   HOTSPOT_JNI_CALLVOIDMETHODA_ENTRY(env, obj, (uintptr_t) methodID);
1572   DT_VOID_RETURN_MARK(CallVoidMethodA);
1573 
1574   JavaValue jvalue(T_VOID);
1575   JNI_ArgumentPusherArray ap(methodID, args);
1576   jni_invoke_nonstatic(env, &jvalue, obj, JNI_VIRTUAL, methodID, &ap, CHECK);
1577 JNI_END
1578 
1579 
1580 
1581 #define DEFINE_CALLNONVIRTUALMETHOD(ResultType, Result, Tag \
1582                                     , EntryProbe, ReturnProbe)      \
1583 \
1584   DT_RETURN_MARK_DECL_FOR(Result, CallNonvirtual##Result##Method, ResultType \
1585                           , ReturnProbe);\
1586 \
1587 JNI_ENTRY(ResultType, \
1588           jni_CallNonvirtual##Result##Method(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, ...)) \
1589   JNIWrapper("CallNonvitual" XSTR(Result) "Method"); \
1590 \
1591   EntryProbe;\
1592   ResultType ret;\
1593   DT_RETURN_MARK_FOR(Result, CallNonvirtual##Result##Method, ResultType, \
1594                      (const ResultType&)ret);\
1595 \
1596   va_list args; \
1597   va_start(args, methodID); \
1598   JavaValue jvalue(Tag); \
1599   JNI_ArgumentPusherVaArg ap(methodID, args); \
1600   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_0); \
1601   va_end(args); \
1602   ret = jvalue.get_##ResultType(); \
1603   return ret;\
1604 JNI_END
1605 
1606 // the runtime type of subword integral basic types is integer
1607 DEFINE_CALLNONVIRTUALMETHOD(jboolean, Boolean, T_BOOLEAN
1608                             , HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1609                             HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHOD_RETURN(_ret_ref))
1610 DEFINE_CALLNONVIRTUALMETHOD(jbyte,    Byte,    T_BYTE
1611                             , HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1612                             HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHOD_RETURN(_ret_ref))
1613 DEFINE_CALLNONVIRTUALMETHOD(jchar,    Char,    T_CHAR
1614                             , HOTSPOT_JNI_CALLNONVIRTUALCHARMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1615                             HOTSPOT_JNI_CALLNONVIRTUALCHARMETHOD_RETURN(_ret_ref))
1616 DEFINE_CALLNONVIRTUALMETHOD(jshort,   Short,   T_SHORT
1617                             , HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1618                             HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHOD_RETURN(_ret_ref))
1619 
1620 DEFINE_CALLNONVIRTUALMETHOD(jobject,  Object,  T_OBJECT
1621                             , HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1622                             HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHOD_RETURN(_ret_ref))
1623 DEFINE_CALLNONVIRTUALMETHOD(jint,     Int,     T_INT
1624                             , HOTSPOT_JNI_CALLNONVIRTUALINTMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1625                             HOTSPOT_JNI_CALLNONVIRTUALINTMETHOD_RETURN(_ret_ref))
1626 DEFINE_CALLNONVIRTUALMETHOD(jlong,    Long,    T_LONG
1627                             , HOTSPOT_JNI_CALLNONVIRTUALLONGMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1628 // Float and double probes don't return value because dtrace doesn't currently support it
1629                             HOTSPOT_JNI_CALLNONVIRTUALLONGMETHOD_RETURN(_ret_ref))
1630 DEFINE_CALLNONVIRTUALMETHOD(jfloat,   Float,   T_FLOAT
1631                             , HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1632                             HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHOD_RETURN())
1633 DEFINE_CALLNONVIRTUALMETHOD(jdouble,  Double,  T_DOUBLE
1634                             , HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHOD_ENTRY(env, obj, cls, (uintptr_t)methodID),
1635                             HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHOD_RETURN())
1636 
1637 #define DEFINE_CALLNONVIRTUALMETHODV(ResultType, Result, Tag \
1638                                     , EntryProbe, ReturnProbe)      \
1639 \
1640   DT_RETURN_MARK_DECL_FOR(Result, CallNonvirtual##Result##MethodV, ResultType \
1641                           , ReturnProbe);\
1642 \
1643 JNI_ENTRY(ResultType, \
1644           jni_CallNonvirtual##Result##MethodV(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, va_list args)) \
1645   JNIWrapper("CallNonvitual" XSTR(Result) "MethodV"); \
1646 \
1647   EntryProbe;\
1648   ResultType ret;\
1649   DT_RETURN_MARK_FOR(Result, CallNonvirtual##Result##MethodV, ResultType, \
1650                      (const ResultType&)ret);\
1651 \
1652   JavaValue jvalue(Tag); \
1653   JNI_ArgumentPusherVaArg ap(methodID, args); \
1654   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_0); \
1655   ret = jvalue.get_##ResultType(); \
1656   return ret;\
1657 JNI_END
1658 
1659 // the runtime type of subword integral basic types is integer
1660 DEFINE_CALLNONVIRTUALMETHODV(jboolean, Boolean, T_BOOLEAN
1661                             , HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1662                             HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHODV_RETURN(_ret_ref))
1663 DEFINE_CALLNONVIRTUALMETHODV(jbyte,    Byte,    T_BYTE
1664                             , HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1665                             HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHODV_RETURN(_ret_ref))
1666 DEFINE_CALLNONVIRTUALMETHODV(jchar,    Char,    T_CHAR
1667                             , HOTSPOT_JNI_CALLNONVIRTUALCHARMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1668                             HOTSPOT_JNI_CALLNONVIRTUALCHARMETHODV_RETURN(_ret_ref))
1669 DEFINE_CALLNONVIRTUALMETHODV(jshort,   Short,   T_SHORT
1670                             , HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1671                             HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHODV_RETURN(_ret_ref))
1672 
1673 DEFINE_CALLNONVIRTUALMETHODV(jobject,  Object,  T_OBJECT
1674                             , HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1675                             HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHODV_RETURN(_ret_ref))
1676 DEFINE_CALLNONVIRTUALMETHODV(jint,     Int,     T_INT
1677                             , HOTSPOT_JNI_CALLNONVIRTUALINTMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1678                             HOTSPOT_JNI_CALLNONVIRTUALINTMETHODV_RETURN(_ret_ref))
1679 DEFINE_CALLNONVIRTUALMETHODV(jlong,    Long,    T_LONG
1680                             , HOTSPOT_JNI_CALLNONVIRTUALLONGMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1681 // Float and double probes don't return value because dtrace doesn't currently support it
1682                             HOTSPOT_JNI_CALLNONVIRTUALLONGMETHODV_RETURN(_ret_ref))
1683 DEFINE_CALLNONVIRTUALMETHODV(jfloat,   Float,   T_FLOAT
1684                             , HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1685                             HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHODV_RETURN())
1686 DEFINE_CALLNONVIRTUALMETHODV(jdouble,  Double,  T_DOUBLE
1687                             , HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHODV_ENTRY(env, obj, cls, (uintptr_t)methodID),
1688                             HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHODV_RETURN())
1689 
1690 #define DEFINE_CALLNONVIRTUALMETHODA(ResultType, Result, Tag \
1691                                     , EntryProbe, ReturnProbe)      \
1692 \
1693   DT_RETURN_MARK_DECL_FOR(Result, CallNonvirtual##Result##MethodA, ResultType \
1694                           , ReturnProbe);\
1695 \
1696 JNI_ENTRY(ResultType, \
1697           jni_CallNonvirtual##Result##MethodA(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, const jvalue *args)) \
1698   JNIWrapper("CallNonvitual" XSTR(Result) "MethodA"); \
1699 \
1700   EntryProbe;\
1701   ResultType ret;\
1702   DT_RETURN_MARK_FOR(Result, CallNonvirtual##Result##MethodA, ResultType, \
1703                      (const ResultType&)ret);\
1704 \
1705   JavaValue jvalue(Tag); \
1706   JNI_ArgumentPusherArray ap(methodID, args); \
1707   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK_0); \
1708   ret = jvalue.get_##ResultType(); \
1709   return ret;\
1710 JNI_END
1711 
1712 // the runtime type of subword integral basic types is integer
1713 DEFINE_CALLNONVIRTUALMETHODA(jboolean, Boolean, T_BOOLEAN
1714                             , HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1715                             HOTSPOT_JNI_CALLNONVIRTUALBOOLEANMETHODA_RETURN(_ret_ref))
1716 DEFINE_CALLNONVIRTUALMETHODA(jbyte,    Byte,    T_BYTE
1717                             , HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1718                             HOTSPOT_JNI_CALLNONVIRTUALBYTEMETHODA_RETURN(_ret_ref))
1719 DEFINE_CALLNONVIRTUALMETHODA(jchar,    Char,    T_CHAR
1720                             , HOTSPOT_JNI_CALLNONVIRTUALCHARMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1721                             HOTSPOT_JNI_CALLNONVIRTUALCHARMETHODA_RETURN(_ret_ref))
1722 DEFINE_CALLNONVIRTUALMETHODA(jshort,   Short,   T_SHORT
1723                             , HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1724                             HOTSPOT_JNI_CALLNONVIRTUALSHORTMETHODA_RETURN(_ret_ref))
1725 
1726 DEFINE_CALLNONVIRTUALMETHODA(jobject,  Object,  T_OBJECT
1727                             , HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1728                             HOTSPOT_JNI_CALLNONVIRTUALOBJECTMETHODA_RETURN(_ret_ref))
1729 DEFINE_CALLNONVIRTUALMETHODA(jint,     Int,     T_INT
1730                             , HOTSPOT_JNI_CALLNONVIRTUALINTMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1731                             HOTSPOT_JNI_CALLNONVIRTUALINTMETHODA_RETURN(_ret_ref))
1732 DEFINE_CALLNONVIRTUALMETHODA(jlong,    Long,    T_LONG
1733                             , HOTSPOT_JNI_CALLNONVIRTUALLONGMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1734 // Float and double probes don't return value because dtrace doesn't currently support it
1735                             HOTSPOT_JNI_CALLNONVIRTUALLONGMETHODA_RETURN(_ret_ref))
1736 DEFINE_CALLNONVIRTUALMETHODA(jfloat,   Float,   T_FLOAT
1737                             , HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1738                             HOTSPOT_JNI_CALLNONVIRTUALFLOATMETHODA_RETURN())
1739 DEFINE_CALLNONVIRTUALMETHODA(jdouble,  Double,  T_DOUBLE
1740                             , HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHODA_ENTRY(env, obj, cls, (uintptr_t)methodID),
1741                             HOTSPOT_JNI_CALLNONVIRTUALDOUBLEMETHODA_RETURN())
1742 
1743 DT_VOID_RETURN_MARK_DECL(CallNonvirtualVoidMethod
1744                          , HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHOD_RETURN());
1745 DT_VOID_RETURN_MARK_DECL(CallNonvirtualVoidMethodV
1746                          , HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHODV_RETURN());
1747 DT_VOID_RETURN_MARK_DECL(CallNonvirtualVoidMethodA
1748                          , HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHODA_RETURN());
1749 
1750 JNI_ENTRY(void, jni_CallNonvirtualVoidMethod(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, ...))
1751   JNIWrapper("CallNonvirtualVoidMethod");
1752 
1753   HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHOD_ENTRY(env, obj, cls, (uintptr_t) methodID);
1754   DT_VOID_RETURN_MARK(CallNonvirtualVoidMethod);
1755 
1756   va_list args;
1757   va_start(args, methodID);
1758   JavaValue jvalue(T_VOID);
1759   JNI_ArgumentPusherVaArg ap(methodID, args);
1760   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK);
1761   va_end(args);
1762 JNI_END
1763 
1764 
1765 JNI_ENTRY(void, jni_CallNonvirtualVoidMethodV(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, va_list args))
1766   JNIWrapper("CallNonvirtualVoidMethodV");
1767 
1768   HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHODV_ENTRY(
1769                env, obj, cls, (uintptr_t) methodID);
1770   DT_VOID_RETURN_MARK(CallNonvirtualVoidMethodV);
1771 
1772   JavaValue jvalue(T_VOID);
1773   JNI_ArgumentPusherVaArg ap(methodID, args);
1774   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK);
1775 JNI_END
1776 
1777 
1778 JNI_ENTRY(void, jni_CallNonvirtualVoidMethodA(JNIEnv *env, jobject obj, jclass cls, jmethodID methodID, const jvalue *args))
1779   JNIWrapper("CallNonvirtualVoidMethodA");
1780   HOTSPOT_JNI_CALLNONVIRTUALVOIDMETHODA_ENTRY(
1781                 env, obj, cls, (uintptr_t) methodID);
1782   DT_VOID_RETURN_MARK(CallNonvirtualVoidMethodA);
1783   JavaValue jvalue(T_VOID);
1784   JNI_ArgumentPusherArray ap(methodID, args);
1785   jni_invoke_nonstatic(env, &jvalue, obj, JNI_NONVIRTUAL, methodID, &ap, CHECK);
1786 JNI_END
1787 
1788 
1789 
1790 #define DEFINE_CALLSTATICMETHOD(ResultType, Result, Tag \
1791                                 , EntryProbe, ResultProbe) \
1792 \
1793   DT_RETURN_MARK_DECL_FOR(Result, CallStatic##Result##Method, ResultType \
1794                           , ResultProbe);                               \
1795 \
1796 JNI_ENTRY(ResultType, \
1797           jni_CallStatic##Result##Method(JNIEnv *env, jclass cls, jmethodID methodID, ...)) \
1798   JNIWrapper("CallStatic" XSTR(Result) "Method"); \
1799 \
1800   EntryProbe; \
1801   ResultType ret = 0;\
1802   DT_RETURN_MARK_FOR(Result, CallStatic##Result##Method, ResultType, \
1803                      (const ResultType&)ret);\
1804 \
1805   va_list args; \
1806   va_start(args, methodID); \
1807   JavaValue jvalue(Tag); \
1808   JNI_ArgumentPusherVaArg ap(methodID, args); \
1809   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_0); \
1810   va_end(args); \
1811   ret = jvalue.get_##ResultType(); \
1812   return ret;\
1813 JNI_END
1814 
1815 // the runtime type of subword integral basic types is integer
1816 DEFINE_CALLSTATICMETHOD(jboolean, Boolean, T_BOOLEAN
1817                         , HOTSPOT_JNI_CALLSTATICBOOLEANMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1818                         HOTSPOT_JNI_CALLSTATICBOOLEANMETHOD_RETURN(_ret_ref));
1819 DEFINE_CALLSTATICMETHOD(jbyte,    Byte,    T_BYTE
1820                         , HOTSPOT_JNI_CALLSTATICBYTEMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1821                         HOTSPOT_JNI_CALLSTATICBYTEMETHOD_RETURN(_ret_ref));
1822 DEFINE_CALLSTATICMETHOD(jchar,    Char,    T_CHAR
1823                         , HOTSPOT_JNI_CALLSTATICCHARMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1824                         HOTSPOT_JNI_CALLSTATICCHARMETHOD_RETURN(_ret_ref));
1825 DEFINE_CALLSTATICMETHOD(jshort,   Short,   T_SHORT
1826                         , HOTSPOT_JNI_CALLSTATICSHORTMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1827                         HOTSPOT_JNI_CALLSTATICSHORTMETHOD_RETURN(_ret_ref));
1828 
1829 DEFINE_CALLSTATICMETHOD(jobject,  Object,  T_OBJECT
1830                         , HOTSPOT_JNI_CALLSTATICOBJECTMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1831                         HOTSPOT_JNI_CALLSTATICOBJECTMETHOD_RETURN(_ret_ref));
1832 DEFINE_CALLSTATICMETHOD(jint,     Int,     T_INT
1833                         , HOTSPOT_JNI_CALLSTATICINTMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1834                         HOTSPOT_JNI_CALLSTATICINTMETHOD_RETURN(_ret_ref));
1835 DEFINE_CALLSTATICMETHOD(jlong,    Long,    T_LONG
1836                         , HOTSPOT_JNI_CALLSTATICLONGMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1837                         HOTSPOT_JNI_CALLSTATICLONGMETHOD_RETURN(_ret_ref));
1838 // Float and double probes don't return value because dtrace doesn't currently support it
1839 DEFINE_CALLSTATICMETHOD(jfloat,   Float,   T_FLOAT
1840                         , HOTSPOT_JNI_CALLSTATICFLOATMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1841                         HOTSPOT_JNI_CALLSTATICFLOATMETHOD_RETURN());
1842 DEFINE_CALLSTATICMETHOD(jdouble,  Double,  T_DOUBLE
1843                         , HOTSPOT_JNI_CALLSTATICDOUBLEMETHOD_ENTRY(env, cls, (uintptr_t)methodID),
1844                         HOTSPOT_JNI_CALLSTATICDOUBLEMETHOD_RETURN());
1845 
1846 #define DEFINE_CALLSTATICMETHODV(ResultType, Result, Tag \
1847                                 , EntryProbe, ResultProbe) \
1848 \
1849   DT_RETURN_MARK_DECL_FOR(Result, CallStatic##Result##MethodV, ResultType \
1850                           , ResultProbe);                               \
1851 \
1852 JNI_ENTRY(ResultType, \
1853           jni_CallStatic##Result##MethodV(JNIEnv *env, jclass cls, jmethodID methodID, va_list args)) \
1854   JNIWrapper("CallStatic" XSTR(Result) "MethodV"); \
1855 \
1856   EntryProbe; \
1857   ResultType ret = 0;\
1858   DT_RETURN_MARK_FOR(Result, CallStatic##Result##MethodV, ResultType, \
1859                      (const ResultType&)ret);\
1860 \
1861   JavaValue jvalue(Tag); \
1862   JNI_ArgumentPusherVaArg ap(methodID, args); \
1863   /* Make sure class is initialized before trying to invoke its method */ \
1864   KlassHandle k(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls))); \
1865   k()->initialize(CHECK_0); \
1866   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_0); \
1867   va_end(args); \
1868   ret = jvalue.get_##ResultType(); \
1869   return ret;\
1870 JNI_END
1871 
1872 // the runtime type of subword integral basic types is integer
1873 DEFINE_CALLSTATICMETHODV(jboolean, Boolean, T_BOOLEAN
1874                         , HOTSPOT_JNI_CALLSTATICBOOLEANMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1875                         HOTSPOT_JNI_CALLSTATICBOOLEANMETHODV_RETURN(_ret_ref));
1876 DEFINE_CALLSTATICMETHODV(jbyte,    Byte,    T_BYTE
1877                         , HOTSPOT_JNI_CALLSTATICBYTEMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1878                         HOTSPOT_JNI_CALLSTATICBYTEMETHODV_RETURN(_ret_ref));
1879 DEFINE_CALLSTATICMETHODV(jchar,    Char,    T_CHAR
1880                         , HOTSPOT_JNI_CALLSTATICCHARMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1881                         HOTSPOT_JNI_CALLSTATICCHARMETHODV_RETURN(_ret_ref));
1882 DEFINE_CALLSTATICMETHODV(jshort,   Short,   T_SHORT
1883                         , HOTSPOT_JNI_CALLSTATICSHORTMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1884                         HOTSPOT_JNI_CALLSTATICSHORTMETHODV_RETURN(_ret_ref));
1885 
1886 DEFINE_CALLSTATICMETHODV(jobject,  Object,  T_OBJECT
1887                         , HOTSPOT_JNI_CALLSTATICOBJECTMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1888                         HOTSPOT_JNI_CALLSTATICOBJECTMETHODV_RETURN(_ret_ref));
1889 DEFINE_CALLSTATICMETHODV(jint,     Int,     T_INT
1890                         , HOTSPOT_JNI_CALLSTATICINTMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1891                         HOTSPOT_JNI_CALLSTATICINTMETHODV_RETURN(_ret_ref));
1892 DEFINE_CALLSTATICMETHODV(jlong,    Long,    T_LONG
1893                         , HOTSPOT_JNI_CALLSTATICLONGMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1894                         HOTSPOT_JNI_CALLSTATICLONGMETHODV_RETURN(_ret_ref));
1895 // Float and double probes don't return value because dtrace doesn't currently support it
1896 DEFINE_CALLSTATICMETHODV(jfloat,   Float,   T_FLOAT
1897                         , HOTSPOT_JNI_CALLSTATICFLOATMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1898                         HOTSPOT_JNI_CALLSTATICFLOATMETHODV_RETURN());
1899 DEFINE_CALLSTATICMETHODV(jdouble,  Double,  T_DOUBLE
1900                         , HOTSPOT_JNI_CALLSTATICDOUBLEMETHODV_ENTRY(env, cls, (uintptr_t)methodID),
1901                         HOTSPOT_JNI_CALLSTATICDOUBLEMETHODV_RETURN());
1902 
1903 #define DEFINE_CALLSTATICMETHODA(ResultType, Result, Tag \
1904                                 , EntryProbe, ResultProbe) \
1905 \
1906   DT_RETURN_MARK_DECL_FOR(Result, CallStatic##Result##MethodA, ResultType \
1907                           , ResultProbe);                               \
1908 \
1909 JNI_ENTRY(ResultType, \
1910           jni_CallStatic##Result##MethodA(JNIEnv *env, jclass cls, jmethodID methodID, const jvalue *args)) \
1911   JNIWrapper("CallStatic" XSTR(Result) "MethodA"); \
1912 \
1913   EntryProbe; \
1914   ResultType ret = 0;\
1915   DT_RETURN_MARK_FOR(Result, CallStatic##Result##MethodA, ResultType, \
1916                      (const ResultType&)ret);\
1917 \
1918   JavaValue jvalue(Tag); \
1919   JNI_ArgumentPusherArray ap(methodID, args); \
1920   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK_0); \
1921   ret = jvalue.get_##ResultType(); \
1922   return ret;\
1923 JNI_END
1924 
1925 // the runtime type of subword integral basic types is integer
1926 DEFINE_CALLSTATICMETHODA(jboolean, Boolean, T_BOOLEAN
1927                         , HOTSPOT_JNI_CALLSTATICBOOLEANMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1928                         HOTSPOT_JNI_CALLSTATICBOOLEANMETHODA_RETURN(_ret_ref));
1929 DEFINE_CALLSTATICMETHODA(jbyte,    Byte,    T_BYTE
1930                         , HOTSPOT_JNI_CALLSTATICBYTEMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1931                         HOTSPOT_JNI_CALLSTATICBYTEMETHODA_RETURN(_ret_ref));
1932 DEFINE_CALLSTATICMETHODA(jchar,    Char,    T_CHAR
1933                         , HOTSPOT_JNI_CALLSTATICCHARMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1934                         HOTSPOT_JNI_CALLSTATICCHARMETHODA_RETURN(_ret_ref));
1935 DEFINE_CALLSTATICMETHODA(jshort,   Short,   T_SHORT
1936                         , HOTSPOT_JNI_CALLSTATICSHORTMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1937                         HOTSPOT_JNI_CALLSTATICSHORTMETHODA_RETURN(_ret_ref));
1938 
1939 DEFINE_CALLSTATICMETHODA(jobject,  Object,  T_OBJECT
1940                         , HOTSPOT_JNI_CALLSTATICOBJECTMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1941                         HOTSPOT_JNI_CALLSTATICOBJECTMETHODA_RETURN(_ret_ref));
1942 DEFINE_CALLSTATICMETHODA(jint,     Int,     T_INT
1943                         , HOTSPOT_JNI_CALLSTATICINTMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1944                         HOTSPOT_JNI_CALLSTATICINTMETHODA_RETURN(_ret_ref));
1945 DEFINE_CALLSTATICMETHODA(jlong,    Long,    T_LONG
1946                         , HOTSPOT_JNI_CALLSTATICLONGMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1947                         HOTSPOT_JNI_CALLSTATICLONGMETHODA_RETURN(_ret_ref));
1948 // Float and double probes don't return value because dtrace doesn't currently support it
1949 DEFINE_CALLSTATICMETHODA(jfloat,   Float,   T_FLOAT
1950                         , HOTSPOT_JNI_CALLSTATICFLOATMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1951                         HOTSPOT_JNI_CALLSTATICFLOATMETHODA_RETURN());
1952 DEFINE_CALLSTATICMETHODA(jdouble,  Double,  T_DOUBLE
1953                         , HOTSPOT_JNI_CALLSTATICDOUBLEMETHODA_ENTRY(env, cls, (uintptr_t)methodID),
1954                         HOTSPOT_JNI_CALLSTATICDOUBLEMETHODA_RETURN());
1955 
1956 DT_VOID_RETURN_MARK_DECL(CallStaticVoidMethod
1957                          , HOTSPOT_JNI_CALLSTATICVOIDMETHOD_RETURN());
1958 DT_VOID_RETURN_MARK_DECL(CallStaticVoidMethodV
1959                          , HOTSPOT_JNI_CALLSTATICVOIDMETHODV_RETURN());
1960 DT_VOID_RETURN_MARK_DECL(CallStaticVoidMethodA
1961                          , HOTSPOT_JNI_CALLSTATICVOIDMETHODA_RETURN());
1962 
1963 JNI_ENTRY(void, jni_CallStaticVoidMethod(JNIEnv *env, jclass cls, jmethodID methodID, ...))
1964   JNIWrapper("CallStaticVoidMethod");
1965   HOTSPOT_JNI_CALLSTATICVOIDMETHOD_ENTRY(env, cls, (uintptr_t) methodID);
1966   DT_VOID_RETURN_MARK(CallStaticVoidMethod);
1967 
1968   va_list args;
1969   va_start(args, methodID);
1970   JavaValue jvalue(T_VOID);
1971   JNI_ArgumentPusherVaArg ap(methodID, args);
1972   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK);
1973   va_end(args);
1974 JNI_END
1975 
1976 
1977 JNI_ENTRY(void, jni_CallStaticVoidMethodV(JNIEnv *env, jclass cls, jmethodID methodID, va_list args))
1978   JNIWrapper("CallStaticVoidMethodV");
1979   HOTSPOT_JNI_CALLSTATICVOIDMETHODV_ENTRY(env, cls, (uintptr_t) methodID);
1980   DT_VOID_RETURN_MARK(CallStaticVoidMethodV);
1981 
1982   JavaValue jvalue(T_VOID);
1983   JNI_ArgumentPusherVaArg ap(methodID, args);
1984   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK);
1985 JNI_END
1986 
1987 
1988 JNI_ENTRY(void, jni_CallStaticVoidMethodA(JNIEnv *env, jclass cls, jmethodID methodID, const jvalue *args))
1989   JNIWrapper("CallStaticVoidMethodA");
1990   HOTSPOT_JNI_CALLSTATICVOIDMETHODA_ENTRY(env, cls, (uintptr_t) methodID);
1991   DT_VOID_RETURN_MARK(CallStaticVoidMethodA);
1992 
1993   JavaValue jvalue(T_VOID);
1994   JNI_ArgumentPusherArray ap(methodID, args);
1995   jni_invoke_static(env, &jvalue, NULL, JNI_STATIC, methodID, &ap, CHECK);
1996 JNI_END
1997 
1998 
1999 //
2000 // Accessing Fields
2001 //
2002 
2003 
2004 DT_RETURN_MARK_DECL(GetFieldID, jfieldID
2005                     , HOTSPOT_JNI_GETFIELDID_RETURN((uintptr_t)_ret_ref));
2006 
2007 JNI_ENTRY(jfieldID, jni_GetFieldID(JNIEnv *env, jclass clazz,
2008           const char *name, const char *sig))
2009   JNIWrapper("GetFieldID");
2010   HOTSPOT_JNI_GETFIELDID_ENTRY(env, clazz, (char *) name, (char *) sig);
2011   jfieldID ret = 0;
2012   DT_RETURN_MARK(GetFieldID, jfieldID, (const jfieldID&)ret);
2013 
2014   // The class should have been loaded (we have an instance of the class
2015   // passed in) so the field and signature should already be in the symbol
2016   // table.  If they're not there, the field doesn't exist.
2017   TempNewSymbol fieldname = SymbolTable::probe(name, (int)strlen(name));
2018   TempNewSymbol signame = SymbolTable::probe(sig, (int)strlen(sig));
2019   if (fieldname == NULL || signame == NULL) {
2020     THROW_MSG_0(vmSymbols::java_lang_NoSuchFieldError(), (char*) name);
2021   }
2022   KlassHandle k(THREAD,
2023                 java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
2024   // Make sure class is initialized before handing id's out to fields
2025   k()->initialize(CHECK_NULL);
2026 
2027   fieldDescriptor fd;
2028   if (!k()->is_instance_klass() ||
2029       !InstanceKlass::cast(k())->find_field(fieldname, signame, false, &fd)) {
2030     THROW_MSG_0(vmSymbols::java_lang_NoSuchFieldError(), (char*) name);
2031   }
2032 
2033   // A jfieldID for a non-static field is simply the offset of the field within the instanceOop
2034   // It may also have hash bits for k, if VerifyJNIFields is turned on.
2035   ret = jfieldIDWorkaround::to_instance_jfieldID(k(), fd.offset());
2036   return ret;
2037 JNI_END
2038 
2039 
2040 JNI_ENTRY(jobject, jni_GetObjectField(JNIEnv *env, jobject obj, jfieldID fieldID))
2041   JNIWrapper("GetObjectField");
2042   HOTSPOT_JNI_GETOBJECTFIELD_ENTRY(env, obj, (uintptr_t) fieldID);
2043   oop o = JNIHandles::resolve_non_null(obj);
2044   Klass* k = o->klass();
2045   int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);
2046   // Keep JVMTI addition small and only check enabled flag here.
2047   // jni_GetField_probe() assumes that is okay to create handles.
2048   if (JvmtiExport::should_post_field_access()) {
2049     o = JvmtiExport::jni_GetField_probe(thread, obj, o, k, fieldID, false);
2050   }
2051   jobject ret = JNIHandles::make_local(env, o->obj_field(offset));
2052 #if INCLUDE_ALL_GCS
2053   // If G1 is enabled and we are accessing the value of the referent
2054   // field in a reference object then we need to register a non-null
2055   // referent with the SATB barrier.
2056   if (UseG1GC) {
2057     bool needs_barrier = false;
2058 
2059     if (ret != NULL &&
2060         offset == java_lang_ref_Reference::referent_offset &&
2061         InstanceKlass::cast(k)->reference_type() != REF_NONE) {
2062       assert(InstanceKlass::cast(k)->is_subclass_of(SystemDictionary::Reference_klass()), "sanity");
2063       needs_barrier = true;
2064     }
2065 
2066     if (needs_barrier) {
2067       oop referent = JNIHandles::resolve(ret);
2068       G1SATBCardTableModRefBS::enqueue(referent);
2069     }
2070   }
2071 #endif // INCLUDE_ALL_GCS
2072 HOTSPOT_JNI_GETOBJECTFIELD_RETURN(ret);
2073   return ret;
2074 JNI_END
2075 
2076 
2077 
2078 #define DEFINE_GETFIELD(Return,Fieldname,Result \
2079   , EntryProbe, ReturnProbe) \
2080 \
2081   DT_RETURN_MARK_DECL_FOR(Result, Get##Result##Field, Return \
2082   , ReturnProbe); \
2083 \
2084 JNI_QUICK_ENTRY(Return, jni_Get##Result##Field(JNIEnv *env, jobject obj, jfieldID fieldID)) \
2085   JNIWrapper("Get" XSTR(Result) "Field"); \
2086 \
2087   EntryProbe; \
2088   Return ret = 0;\
2089   DT_RETURN_MARK_FOR(Result, Get##Result##Field, Return, (const Return&)ret);\
2090 \
2091   oop o = JNIHandles::resolve_non_null(obj); \
2092   Klass* k = o->klass(); \
2093   int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);  \
2094   /* Keep JVMTI addition small and only check enabled flag here.       */ \
2095   /* jni_GetField_probe_nh() assumes that is not okay to create handles */ \
2096   /* and creates a ResetNoHandleMark.                                   */ \
2097   if (JvmtiExport::should_post_field_access()) { \
2098     o = JvmtiExport::jni_GetField_probe_nh(thread, obj, o, k, fieldID, false); \
2099   } \
2100   ret = o->Fieldname##_field(offset); \
2101   return ret; \
2102 JNI_END
2103 
2104 DEFINE_GETFIELD(jboolean, bool,   Boolean
2105                 , HOTSPOT_JNI_GETBOOLEANFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2106                 HOTSPOT_JNI_GETBOOLEANFIELD_RETURN(_ret_ref))
2107 DEFINE_GETFIELD(jbyte,    byte,   Byte
2108                 , HOTSPOT_JNI_GETBYTEFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2109                 HOTSPOT_JNI_GETBYTEFIELD_RETURN(_ret_ref))
2110 DEFINE_GETFIELD(jchar,    char,   Char
2111                 , HOTSPOT_JNI_GETCHARFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2112                 HOTSPOT_JNI_GETCHARFIELD_RETURN(_ret_ref))
2113 DEFINE_GETFIELD(jshort,   short,  Short
2114                 , HOTSPOT_JNI_GETSHORTFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2115                 HOTSPOT_JNI_GETSHORTFIELD_RETURN(_ret_ref))
2116 DEFINE_GETFIELD(jint,     int,    Int
2117                 , HOTSPOT_JNI_GETINTFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2118                 HOTSPOT_JNI_GETINTFIELD_RETURN(_ret_ref))
2119 DEFINE_GETFIELD(jlong,    long,   Long
2120                 , HOTSPOT_JNI_GETLONGFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2121                 HOTSPOT_JNI_GETLONGFIELD_RETURN(_ret_ref))
2122 // Float and double probes don't return value because dtrace doesn't currently support it
2123 DEFINE_GETFIELD(jfloat,   float,  Float
2124                 , HOTSPOT_JNI_GETFLOATFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2125                 HOTSPOT_JNI_GETFLOATFIELD_RETURN())
2126 DEFINE_GETFIELD(jdouble,  double, Double
2127                 , HOTSPOT_JNI_GETDOUBLEFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2128                 HOTSPOT_JNI_GETDOUBLEFIELD_RETURN())
2129 
2130 address jni_GetBooleanField_addr() {
2131   return (address)jni_GetBooleanField;
2132 }
2133 address jni_GetByteField_addr() {
2134   return (address)jni_GetByteField;
2135 }
2136 address jni_GetCharField_addr() {
2137   return (address)jni_GetCharField;
2138 }
2139 address jni_GetShortField_addr() {
2140   return (address)jni_GetShortField;
2141 }
2142 address jni_GetIntField_addr() {
2143   return (address)jni_GetIntField;
2144 }
2145 address jni_GetLongField_addr() {
2146   return (address)jni_GetLongField;
2147 }
2148 address jni_GetFloatField_addr() {
2149   return (address)jni_GetFloatField;
2150 }
2151 address jni_GetDoubleField_addr() {
2152   return (address)jni_GetDoubleField;
2153 }
2154 
2155 JNI_QUICK_ENTRY(void, jni_SetObjectField(JNIEnv *env, jobject obj, jfieldID fieldID, jobject value))
2156   JNIWrapper("SetObjectField");
2157   HOTSPOT_JNI_SETOBJECTFIELD_ENTRY(env, obj, (uintptr_t) fieldID, value);
2158   oop o = JNIHandles::resolve_non_null(obj);
2159   Klass* k = o->klass();
2160   int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);
2161   // Keep JVMTI addition small and only check enabled flag here.
2162   // jni_SetField_probe_nh() assumes that is not okay to create handles
2163   // and creates a ResetNoHandleMark.
2164   if (JvmtiExport::should_post_field_modification()) {
2165     jvalue field_value;
2166     field_value.l = value;
2167     o = JvmtiExport::jni_SetField_probe_nh(thread, obj, o, k, fieldID, false, 'L', (jvalue *)&field_value);
2168   }
2169   o->obj_field_put(offset, JNIHandles::resolve(value));
2170   HOTSPOT_JNI_SETOBJECTFIELD_RETURN();
2171 JNI_END
2172 
2173 
2174 #define DEFINE_SETFIELD(Argument,Fieldname,Result,SigType,unionType \
2175                         , EntryProbe, ReturnProbe) \
2176 \
2177 JNI_QUICK_ENTRY(void, jni_Set##Result##Field(JNIEnv *env, jobject obj, jfieldID fieldID, Argument value)) \
2178   JNIWrapper("Set" XSTR(Result) "Field"); \
2179 \
2180   EntryProbe; \
2181 \
2182   oop o = JNIHandles::resolve_non_null(obj); \
2183   Klass* k = o->klass(); \
2184   int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);  \
2185   /* Keep JVMTI addition small and only check enabled flag here.       */ \
2186   /* jni_SetField_probe_nh() assumes that is not okay to create handles */ \
2187   /* and creates a ResetNoHandleMark.                                   */ \
2188   if (JvmtiExport::should_post_field_modification()) { \
2189     jvalue field_value; \
2190     field_value.unionType = value; \
2191     o = JvmtiExport::jni_SetField_probe_nh(thread, obj, o, k, fieldID, false, SigType, (jvalue *)&field_value); \
2192   } \
2193   o->Fieldname##_field_put(offset, value); \
2194   ReturnProbe; \
2195 JNI_END
2196 
2197 DEFINE_SETFIELD(jboolean, bool,   Boolean, 'Z', z
2198                 , HOTSPOT_JNI_SETBOOLEANFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2199                 HOTSPOT_JNI_SETBOOLEANFIELD_RETURN())
2200 DEFINE_SETFIELD(jbyte,    byte,   Byte,    'B', b
2201                 , HOTSPOT_JNI_SETBYTEFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2202                 HOTSPOT_JNI_SETBYTEFIELD_RETURN())
2203 DEFINE_SETFIELD(jchar,    char,   Char,    'C', c
2204                 , HOTSPOT_JNI_SETCHARFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2205                 HOTSPOT_JNI_SETCHARFIELD_RETURN())
2206 DEFINE_SETFIELD(jshort,   short,  Short,   'S', s
2207                 , HOTSPOT_JNI_SETSHORTFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2208                 HOTSPOT_JNI_SETSHORTFIELD_RETURN())
2209 DEFINE_SETFIELD(jint,     int,    Int,     'I', i
2210                 , HOTSPOT_JNI_SETINTFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2211                 HOTSPOT_JNI_SETINTFIELD_RETURN())
2212 DEFINE_SETFIELD(jlong,    long,   Long,    'J', j
2213                 , HOTSPOT_JNI_SETLONGFIELD_ENTRY(env, obj, (uintptr_t)fieldID, value),
2214                 HOTSPOT_JNI_SETLONGFIELD_RETURN())
2215 // Float and double probes don't return value because dtrace doesn't currently support it
2216 DEFINE_SETFIELD(jfloat,   float,  Float,   'F', f
2217                 , HOTSPOT_JNI_SETFLOATFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2218                 HOTSPOT_JNI_SETFLOATFIELD_RETURN())
2219 DEFINE_SETFIELD(jdouble,  double, Double,  'D', d
2220                 , HOTSPOT_JNI_SETDOUBLEFIELD_ENTRY(env, obj, (uintptr_t)fieldID),
2221                 HOTSPOT_JNI_SETDOUBLEFIELD_RETURN())
2222 
2223 DT_RETURN_MARK_DECL(ToReflectedField, jobject
2224                     , HOTSPOT_JNI_TOREFLECTEDFIELD_RETURN(_ret_ref));
2225 
2226 JNI_ENTRY(jobject, jni_ToReflectedField(JNIEnv *env, jclass cls, jfieldID fieldID, jboolean isStatic))
2227   JNIWrapper("ToReflectedField");
2228   HOTSPOT_JNI_TOREFLECTEDFIELD_ENTRY(env, cls, (uintptr_t) fieldID, isStatic);
2229   jobject ret = NULL;
2230   DT_RETURN_MARK(ToReflectedField, jobject, (const jobject&)ret);
2231 
2232   fieldDescriptor fd;
2233   bool found = false;
2234   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
2235 
2236   assert(jfieldIDWorkaround::is_static_jfieldID(fieldID) == (isStatic != 0), "invalid fieldID");
2237 
2238   if (isStatic) {
2239     // Static field. The fieldID a JNIid specifying the field holder and the offset within the Klass*.
2240     JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID);
2241     assert(id->is_static_field_id(), "invalid static field id");
2242     found = id->find_local_field(&fd);
2243   } else {
2244     // Non-static field. The fieldID is really the offset of the field within the instanceOop.
2245     int offset = jfieldIDWorkaround::from_instance_jfieldID(k, fieldID);
2246     found = InstanceKlass::cast(k)->find_field_from_offset(offset, false, &fd);
2247   }
2248   assert(found, "bad fieldID passed into jni_ToReflectedField");
2249   oop reflected = Reflection::new_field(&fd, CHECK_NULL);
2250   ret = JNIHandles::make_local(env, reflected);
2251   return ret;
2252 JNI_END
2253 
2254 
2255 //
2256 // Accessing Static Fields
2257 //
2258 DT_RETURN_MARK_DECL(GetStaticFieldID, jfieldID
2259                     , HOTSPOT_JNI_GETSTATICFIELDID_RETURN((uintptr_t)_ret_ref));
2260 
2261 JNI_ENTRY(jfieldID, jni_GetStaticFieldID(JNIEnv *env, jclass clazz,
2262           const char *name, const char *sig))
2263   JNIWrapper("GetStaticFieldID");
2264   HOTSPOT_JNI_GETSTATICFIELDID_ENTRY(env, clazz, (char *) name, (char *) sig);
2265   jfieldID ret = NULL;
2266   DT_RETURN_MARK(GetStaticFieldID, jfieldID, (const jfieldID&)ret);
2267 
2268   // The class should have been loaded (we have an instance of the class
2269   // passed in) so the field and signature should already be in the symbol
2270   // table.  If they're not there, the field doesn't exist.
2271   TempNewSymbol fieldname = SymbolTable::probe(name, (int)strlen(name));
2272   TempNewSymbol signame = SymbolTable::probe(sig, (int)strlen(sig));
2273   if (fieldname == NULL || signame == NULL) {
2274     THROW_MSG_0(vmSymbols::java_lang_NoSuchFieldError(), (char*) name);
2275   }
2276   KlassHandle k(THREAD,
2277                 java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
2278   // Make sure class is initialized before handing id's out to static fields
2279   k()->initialize(CHECK_NULL);
2280 
2281   fieldDescriptor fd;
2282   if (!k()->is_instance_klass() ||
2283       !InstanceKlass::cast(k())->find_field(fieldname, signame, true, &fd)) {
2284     THROW_MSG_0(vmSymbols::java_lang_NoSuchFieldError(), (char*) name);
2285   }
2286 
2287   // A jfieldID for a static field is a JNIid specifying the field holder and the offset within the Klass*
2288   JNIid* id = fd.field_holder()->jni_id_for(fd.offset());
2289   debug_only(id->set_is_static_field_id();)
2290 
2291   debug_only(id->verify(fd.field_holder()));
2292 
2293   ret = jfieldIDWorkaround::to_static_jfieldID(id);
2294   return ret;
2295 JNI_END
2296 
2297 
2298 JNI_ENTRY(jobject, jni_GetStaticObjectField(JNIEnv *env, jclass clazz, jfieldID fieldID))
2299   JNIWrapper("GetStaticObjectField");
2300   HOTSPOT_JNI_GETSTATICOBJECTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID);
2301 #if INCLUDE_JNI_CHECK
2302   DEBUG_ONLY(Klass* param_k = jniCheck::validate_class(thread, clazz);)
2303 #endif // INCLUDE_JNI_CHECK
2304   JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID);
2305   assert(id->is_static_field_id(), "invalid static field id");
2306   // Keep JVMTI addition small and only check enabled flag here.
2307   // jni_GetField_probe() assumes that is okay to create handles.
2308   if (JvmtiExport::should_post_field_access()) {
2309     JvmtiExport::jni_GetField_probe(thread, NULL, NULL, id->holder(), fieldID, true);
2310   }
2311   jobject ret = JNIHandles::make_local(id->holder()->java_mirror()->obj_field(id->offset()));
2312   HOTSPOT_JNI_GETSTATICOBJECTFIELD_RETURN(ret);
2313   return ret;
2314 JNI_END
2315 
2316 
2317 #define DEFINE_GETSTATICFIELD(Return,Fieldname,Result \
2318                               , EntryProbe, ReturnProbe) \
2319 \
2320   DT_RETURN_MARK_DECL_FOR(Result, GetStatic##Result##Field, Return \
2321                           , ReturnProbe);                                          \
2322 \
2323 JNI_ENTRY(Return, jni_GetStatic##Result##Field(JNIEnv *env, jclass clazz, jfieldID fieldID)) \
2324   JNIWrapper("GetStatic" XSTR(Result) "Field"); \
2325   EntryProbe; \
2326   Return ret = 0;\
2327   DT_RETURN_MARK_FOR(Result, GetStatic##Result##Field, Return, \
2328                      (const Return&)ret);\
2329   JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID); \
2330   assert(id->is_static_field_id(), "invalid static field id"); \
2331   /* Keep JVMTI addition small and only check enabled flag here. */ \
2332   /* jni_GetField_probe() assumes that is okay to create handles. */ \
2333   if (JvmtiExport::should_post_field_access()) { \
2334     JvmtiExport::jni_GetField_probe(thread, NULL, NULL, id->holder(), fieldID, true); \
2335   } \
2336   ret = id->holder()->java_mirror()-> Fieldname##_field (id->offset()); \
2337   return ret;\
2338 JNI_END
2339 
2340 DEFINE_GETSTATICFIELD(jboolean, bool,   Boolean
2341                       , HOTSPOT_JNI_GETSTATICBOOLEANFIELD_ENTRY(env, clazz, (uintptr_t) fieldID), HOTSPOT_JNI_GETSTATICBOOLEANFIELD_RETURN(_ret_ref))
2342 DEFINE_GETSTATICFIELD(jbyte,    byte,   Byte
2343                       , HOTSPOT_JNI_GETSTATICBYTEFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),    HOTSPOT_JNI_GETSTATICBYTEFIELD_RETURN(_ret_ref)   )
2344 DEFINE_GETSTATICFIELD(jchar,    char,   Char
2345                       , HOTSPOT_JNI_GETSTATICCHARFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),    HOTSPOT_JNI_GETSTATICCHARFIELD_RETURN(_ret_ref)   )
2346 DEFINE_GETSTATICFIELD(jshort,   short,  Short
2347                       , HOTSPOT_JNI_GETSTATICSHORTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),   HOTSPOT_JNI_GETSTATICSHORTFIELD_RETURN(_ret_ref)  )
2348 DEFINE_GETSTATICFIELD(jint,     int,    Int
2349                       , HOTSPOT_JNI_GETSTATICINTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),     HOTSPOT_JNI_GETSTATICINTFIELD_RETURN(_ret_ref)    )
2350 DEFINE_GETSTATICFIELD(jlong,    long,   Long
2351                       , HOTSPOT_JNI_GETSTATICLONGFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),    HOTSPOT_JNI_GETSTATICLONGFIELD_RETURN(_ret_ref)   )
2352 // Float and double probes don't return value because dtrace doesn't currently support it
2353 DEFINE_GETSTATICFIELD(jfloat,   float,  Float
2354                       , HOTSPOT_JNI_GETSTATICFLOATFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),   HOTSPOT_JNI_GETSTATICFLOATFIELD_RETURN()          )
2355 DEFINE_GETSTATICFIELD(jdouble,  double, Double
2356                       , HOTSPOT_JNI_GETSTATICDOUBLEFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),  HOTSPOT_JNI_GETSTATICDOUBLEFIELD_RETURN()         )
2357 
2358 JNI_ENTRY(void, jni_SetStaticObjectField(JNIEnv *env, jclass clazz, jfieldID fieldID, jobject value))
2359   JNIWrapper("SetStaticObjectField");
2360  HOTSPOT_JNI_SETSTATICOBJECTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value);
2361   JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID);
2362   assert(id->is_static_field_id(), "invalid static field id");
2363   // Keep JVMTI addition small and only check enabled flag here.
2364   // jni_SetField_probe() assumes that is okay to create handles.
2365   if (JvmtiExport::should_post_field_modification()) {
2366     jvalue field_value;
2367     field_value.l = value;
2368     JvmtiExport::jni_SetField_probe(thread, NULL, NULL, id->holder(), fieldID, true, 'L', (jvalue *)&field_value);
2369   }
2370   id->holder()->java_mirror()->obj_field_put(id->offset(), JNIHandles::resolve(value));
2371   HOTSPOT_JNI_SETSTATICOBJECTFIELD_RETURN();
2372 JNI_END
2373 
2374 
2375 
2376 #define DEFINE_SETSTATICFIELD(Argument,Fieldname,Result,SigType,unionType \
2377                               , EntryProbe, ReturnProbe) \
2378 \
2379 JNI_ENTRY(void, jni_SetStatic##Result##Field(JNIEnv *env, jclass clazz, jfieldID fieldID, Argument value)) \
2380   JNIWrapper("SetStatic" XSTR(Result) "Field"); \
2381   EntryProbe; \
2382 \
2383   JNIid* id = jfieldIDWorkaround::from_static_jfieldID(fieldID); \
2384   assert(id->is_static_field_id(), "invalid static field id"); \
2385   /* Keep JVMTI addition small and only check enabled flag here. */ \
2386   /* jni_SetField_probe() assumes that is okay to create handles. */ \
2387   if (JvmtiExport::should_post_field_modification()) { \
2388     jvalue field_value; \
2389     field_value.unionType = value; \
2390     JvmtiExport::jni_SetField_probe(thread, NULL, NULL, id->holder(), fieldID, true, SigType, (jvalue *)&field_value); \
2391   } \
2392   id->holder()->java_mirror()-> Fieldname##_field_put (id->offset(), value); \
2393   ReturnProbe;\
2394 JNI_END
2395 
2396 DEFINE_SETSTATICFIELD(jboolean, bool,   Boolean, 'Z', z
2397                       , HOTSPOT_JNI_SETSTATICBOOLEANFIELD_ENTRY(env, clazz, (uintptr_t)fieldID, value),
2398                       HOTSPOT_JNI_SETSTATICBOOLEANFIELD_RETURN())
2399 DEFINE_SETSTATICFIELD(jbyte,    byte,   Byte,    'B', b
2400                       , HOTSPOT_JNI_SETSTATICBYTEFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2401                       HOTSPOT_JNI_SETSTATICBYTEFIELD_RETURN())
2402 DEFINE_SETSTATICFIELD(jchar,    char,   Char,    'C', c
2403                       , HOTSPOT_JNI_SETSTATICCHARFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2404                       HOTSPOT_JNI_SETSTATICCHARFIELD_RETURN())
2405 DEFINE_SETSTATICFIELD(jshort,   short,  Short,   'S', s
2406                       , HOTSPOT_JNI_SETSTATICSHORTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2407                       HOTSPOT_JNI_SETSTATICSHORTFIELD_RETURN())
2408 DEFINE_SETSTATICFIELD(jint,     int,    Int,     'I', i
2409                       , HOTSPOT_JNI_SETSTATICINTFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2410                       HOTSPOT_JNI_SETSTATICINTFIELD_RETURN())
2411 DEFINE_SETSTATICFIELD(jlong,    long,   Long,    'J', j
2412                       , HOTSPOT_JNI_SETSTATICLONGFIELD_ENTRY(env, clazz, (uintptr_t) fieldID, value),
2413                       HOTSPOT_JNI_SETSTATICLONGFIELD_RETURN())
2414 // Float and double probes don't return value because dtrace doesn't currently support it
2415 DEFINE_SETSTATICFIELD(jfloat,   float,  Float,   'F', f
2416                       , HOTSPOT_JNI_SETSTATICFLOATFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),
2417                       HOTSPOT_JNI_SETSTATICFLOATFIELD_RETURN())
2418 DEFINE_SETSTATICFIELD(jdouble,  double, Double,  'D', d
2419                       , HOTSPOT_JNI_SETSTATICDOUBLEFIELD_ENTRY(env, clazz, (uintptr_t) fieldID),
2420                       HOTSPOT_JNI_SETSTATICDOUBLEFIELD_RETURN())
2421 
2422 //
2423 // String Operations
2424 //
2425 
2426 // Unicode Interface
2427 
2428 DT_RETURN_MARK_DECL(NewString, jstring
2429                     , HOTSPOT_JNI_NEWSTRING_RETURN(_ret_ref));
2430 
2431 JNI_ENTRY(jstring, jni_NewString(JNIEnv *env, const jchar *unicodeChars, jsize len))
2432   JNIWrapper("NewString");
2433  HOTSPOT_JNI_NEWSTRING_ENTRY(env, (uint16_t *) unicodeChars, len);
2434   jstring ret = NULL;
2435   DT_RETURN_MARK(NewString, jstring, (const jstring&)ret);
2436   oop string=java_lang_String::create_oop_from_unicode((jchar*) unicodeChars, len, CHECK_NULL);
2437   ret = (jstring) JNIHandles::make_local(env, string);
2438   return ret;
2439 JNI_END
2440 
2441 
2442 JNI_QUICK_ENTRY(jsize, jni_GetStringLength(JNIEnv *env, jstring string))
2443   JNIWrapper("GetStringLength");
2444   HOTSPOT_JNI_GETSTRINGLENGTH_ENTRY(env, string);
2445   jsize ret = 0;
2446   oop s = JNIHandles::resolve_non_null(string);
2447   if (java_lang_String::value(s) != NULL) {
2448     ret = java_lang_String::length(s);
2449   }
2450  HOTSPOT_JNI_GETSTRINGLENGTH_RETURN(ret);
2451   return ret;
2452 JNI_END
2453 
2454 
2455 JNI_QUICK_ENTRY(const jchar*, jni_GetStringChars(
2456   JNIEnv *env, jstring string, jboolean *isCopy))
2457   JNIWrapper("GetStringChars");
2458  HOTSPOT_JNI_GETSTRINGCHARS_ENTRY(env, string, (uintptr_t *) isCopy);
2459   jchar* buf = NULL;
2460   oop s = JNIHandles::resolve_non_null(string);
2461   typeArrayOop s_value = java_lang_String::value(s);
2462   if (s_value != NULL) {
2463     int s_len = java_lang_String::length(s);
2464     bool is_latin1 = java_lang_String::is_latin1(s);
2465     buf = NEW_C_HEAP_ARRAY_RETURN_NULL(jchar, s_len + 1, mtInternal);  // add one for zero termination
2466     /* JNI Specification states return NULL on OOM */
2467     if (buf != NULL) {
2468       if (s_len > 0) {
2469         if (!is_latin1) {
2470           memcpy(buf, s_value->char_at_addr(0), sizeof(jchar)*s_len);
2471         } else {
2472           for (int i = 0; i < s_len; i++) {
2473             buf[i] = ((jchar) s_value->byte_at(i)) & 0xff;
2474           }
2475         }
2476       }
2477       buf[s_len] = 0;
2478       //%note jni_5
2479       if (isCopy != NULL) {
2480         *isCopy = JNI_TRUE;
2481       }
2482     }
2483   }
2484   HOTSPOT_JNI_GETSTRINGCHARS_RETURN(buf);
2485   return buf;
2486 JNI_END
2487 
2488 
2489 JNI_QUICK_ENTRY(void, jni_ReleaseStringChars(JNIEnv *env, jstring str, const jchar *chars))
2490   JNIWrapper("ReleaseStringChars");
2491   HOTSPOT_JNI_RELEASESTRINGCHARS_ENTRY(env, str, (uint16_t *) chars);
2492   //%note jni_6
2493   if (chars != NULL) {
2494     // Since String objects are supposed to be immutable, don't copy any
2495     // new data back.  A bad user will have to go after the char array.
2496     FreeHeap((void*) chars);
2497   }
2498   HOTSPOT_JNI_RELEASESTRINGCHARS_RETURN();
2499 JNI_END
2500 
2501 
2502 // UTF Interface
2503 
2504 DT_RETURN_MARK_DECL(NewStringUTF, jstring
2505                     , HOTSPOT_JNI_NEWSTRINGUTF_RETURN(_ret_ref));
2506 
2507 JNI_ENTRY(jstring, jni_NewStringUTF(JNIEnv *env, const char *bytes))
2508   JNIWrapper("NewStringUTF");
2509   HOTSPOT_JNI_NEWSTRINGUTF_ENTRY(env, (char *) bytes);
2510   jstring ret;
2511   DT_RETURN_MARK(NewStringUTF, jstring, (const jstring&)ret);
2512 
2513   oop result = java_lang_String::create_oop_from_str((char*) bytes, CHECK_NULL);
2514   ret = (jstring) JNIHandles::make_local(env, result);
2515   return ret;
2516 JNI_END
2517 
2518 
2519 JNI_ENTRY(jsize, jni_GetStringUTFLength(JNIEnv *env, jstring string))
2520   JNIWrapper("GetStringUTFLength");
2521  HOTSPOT_JNI_GETSTRINGUTFLENGTH_ENTRY(env, string);
2522   jsize ret = 0;
2523   oop java_string = JNIHandles::resolve_non_null(string);
2524   if (java_lang_String::value(java_string) != NULL) {
2525     ret = java_lang_String::utf8_length(java_string);
2526   }
2527   HOTSPOT_JNI_GETSTRINGUTFLENGTH_RETURN(ret);
2528   return ret;
2529 JNI_END
2530 
2531 
2532 JNI_ENTRY(const char*, jni_GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy))
2533   JNIWrapper("GetStringUTFChars");
2534  HOTSPOT_JNI_GETSTRINGUTFCHARS_ENTRY(env, string, (uintptr_t *) isCopy);
2535   char* result = NULL;
2536   oop java_string = JNIHandles::resolve_non_null(string);
2537   if (java_lang_String::value(java_string) != NULL) {
2538     size_t length = java_lang_String::utf8_length(java_string);
2539     /* JNI Specification states return NULL on OOM */
2540     result = AllocateHeap(length + 1, mtInternal, 0, AllocFailStrategy::RETURN_NULL);
2541     if (result != NULL) {
2542       java_lang_String::as_utf8_string(java_string, result, (int) length + 1);
2543       if (isCopy != NULL) {
2544         *isCopy = JNI_TRUE;
2545       }
2546     }
2547   }
2548  HOTSPOT_JNI_GETSTRINGUTFCHARS_RETURN(result);
2549   return result;
2550 JNI_END
2551 
2552 
2553 JNI_LEAF(void, jni_ReleaseStringUTFChars(JNIEnv *env, jstring str, const char *chars))
2554   JNIWrapper("ReleaseStringUTFChars");
2555  HOTSPOT_JNI_RELEASESTRINGUTFCHARS_ENTRY(env, str, (char *) chars);
2556   if (chars != NULL) {
2557     FreeHeap((char*) chars);
2558   }
2559 HOTSPOT_JNI_RELEASESTRINGUTFCHARS_RETURN();
2560 JNI_END
2561 
2562 
2563 JNI_QUICK_ENTRY(jsize, jni_GetArrayLength(JNIEnv *env, jarray array))
2564   JNIWrapper("GetArrayLength");
2565  HOTSPOT_JNI_GETARRAYLENGTH_ENTRY(env, array);
2566   arrayOop a = arrayOop(JNIHandles::resolve_non_null(array));
2567   assert(a->is_array(), "must be array");
2568   jsize ret = a->length();
2569  HOTSPOT_JNI_GETARRAYLENGTH_RETURN(ret);
2570   return ret;
2571 JNI_END
2572 
2573 
2574 //
2575 // Object Array Operations
2576 //
2577 
2578 DT_RETURN_MARK_DECL(NewObjectArray, jobjectArray
2579                     , HOTSPOT_JNI_NEWOBJECTARRAY_RETURN(_ret_ref));
2580 
2581 JNI_ENTRY(jobjectArray, jni_NewObjectArray(JNIEnv *env, jsize length, jclass elementClass, jobject initialElement))
2582   JNIWrapper("NewObjectArray");
2583  HOTSPOT_JNI_NEWOBJECTARRAY_ENTRY(env, length, elementClass, initialElement);
2584   jobjectArray ret = NULL;
2585   DT_RETURN_MARK(NewObjectArray, jobjectArray, (const jobjectArray&)ret);
2586   KlassHandle ek(THREAD, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(elementClass)));
2587   Klass* ako = ek()->array_klass(CHECK_NULL);
2588   KlassHandle ak = KlassHandle(THREAD, ako);
2589   ObjArrayKlass::cast(ak())->initialize(CHECK_NULL);
2590   objArrayOop result = ObjArrayKlass::cast(ak())->allocate(length, CHECK_NULL);
2591   oop initial_value = JNIHandles::resolve(initialElement);
2592   if (initial_value != NULL) {  // array already initialized with NULL
2593     for (int index = 0; index < length; index++) {
2594       result->obj_at_put(index, initial_value);
2595     }
2596   }
2597   ret = (jobjectArray) JNIHandles::make_local(env, result);
2598   return ret;
2599 JNI_END
2600 
2601 DT_RETURN_MARK_DECL(GetObjectArrayElement, jobject
2602                     , HOTSPOT_JNI_GETOBJECTARRAYELEMENT_RETURN(_ret_ref));
2603 
2604 JNI_ENTRY(jobject, jni_GetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index))
2605   JNIWrapper("GetObjectArrayElement");
2606  HOTSPOT_JNI_GETOBJECTARRAYELEMENT_ENTRY(env, array, index);
2607   jobject ret = NULL;
2608   DT_RETURN_MARK(GetObjectArrayElement, jobject, (const jobject&)ret);
2609   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(array));
2610   if (a->is_within_bounds(index)) {
2611     ret = JNIHandles::make_local(env, a->obj_at(index));
2612     return ret;
2613   } else {
2614     char buf[jintAsStringSize];
2615     sprintf(buf, "%d", index);
2616     THROW_MSG_0(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), buf);
2617   }
2618 JNI_END
2619 
2620 DT_VOID_RETURN_MARK_DECL(SetObjectArrayElement
2621                          , HOTSPOT_JNI_SETOBJECTARRAYELEMENT_RETURN());
2622 
2623 JNI_ENTRY(void, jni_SetObjectArrayElement(JNIEnv *env, jobjectArray array, jsize index, jobject value))
2624   JNIWrapper("SetObjectArrayElement");
2625  HOTSPOT_JNI_SETOBJECTARRAYELEMENT_ENTRY(env, array, index, value);
2626   DT_VOID_RETURN_MARK(SetObjectArrayElement);
2627 
2628   objArrayOop a = objArrayOop(JNIHandles::resolve_non_null(array));
2629   oop v = JNIHandles::resolve(value);
2630   if (a->is_within_bounds(index)) {
2631     if (v == NULL || v->is_a(ObjArrayKlass::cast(a->klass())->element_klass())) {
2632       a->obj_at_put(index, v);
2633     } else {
2634       THROW(vmSymbols::java_lang_ArrayStoreException());
2635     }
2636   } else {
2637     char buf[jintAsStringSize];
2638     sprintf(buf, "%d", index);
2639     THROW_MSG(vmSymbols::java_lang_ArrayIndexOutOfBoundsException(), buf);
2640   }
2641 JNI_END
2642 
2643 
2644 
2645 #define DEFINE_NEWSCALARARRAY(Return,Allocator,Result \
2646                               ,EntryProbe,ReturnProbe)  \
2647 \
2648   DT_RETURN_MARK_DECL(New##Result##Array, Return \
2649                       , ReturnProbe); \
2650 \
2651 JNI_ENTRY(Return, \
2652           jni_New##Result##Array(JNIEnv *env, jsize len)) \
2653   JNIWrapper("New" XSTR(Result) "Array"); \
2654   EntryProbe; \
2655   Return ret = NULL;\
2656   DT_RETURN_MARK(New##Result##Array, Return, (const Return&)ret);\
2657 \
2658   oop obj= oopFactory::Allocator(len, CHECK_0); \
2659   ret = (Return) JNIHandles::make_local(env, obj); \
2660   return ret;\
2661 JNI_END
2662 
2663 DEFINE_NEWSCALARARRAY(jbooleanArray, new_boolArray,   Boolean,
2664                       HOTSPOT_JNI_NEWBOOLEANARRAY_ENTRY(env, len),
2665                       HOTSPOT_JNI_NEWBOOLEANARRAY_RETURN(_ret_ref))
2666 DEFINE_NEWSCALARARRAY(jbyteArray,    new_byteArray,   Byte,
2667                       HOTSPOT_JNI_NEWBYTEARRAY_ENTRY(env, len),
2668                       HOTSPOT_JNI_NEWBYTEARRAY_RETURN(_ret_ref))
2669 DEFINE_NEWSCALARARRAY(jshortArray,   new_shortArray,  Short,
2670                       HOTSPOT_JNI_NEWSHORTARRAY_ENTRY(env, len),
2671                       HOTSPOT_JNI_NEWSHORTARRAY_RETURN(_ret_ref))
2672 DEFINE_NEWSCALARARRAY(jcharArray,    new_charArray,   Char,
2673                       HOTSPOT_JNI_NEWCHARARRAY_ENTRY(env, len),
2674                       HOTSPOT_JNI_NEWCHARARRAY_RETURN(_ret_ref))
2675 DEFINE_NEWSCALARARRAY(jintArray,     new_intArray,    Int,
2676                       HOTSPOT_JNI_NEWINTARRAY_ENTRY(env, len),
2677                       HOTSPOT_JNI_NEWINTARRAY_RETURN(_ret_ref))
2678 DEFINE_NEWSCALARARRAY(jlongArray,    new_longArray,   Long,
2679                       HOTSPOT_JNI_NEWLONGARRAY_ENTRY(env, len),
2680                       HOTSPOT_JNI_NEWLONGARRAY_RETURN(_ret_ref))
2681 DEFINE_NEWSCALARARRAY(jfloatArray,   new_singleArray, Float,
2682                       HOTSPOT_JNI_NEWFLOATARRAY_ENTRY(env, len),
2683                       HOTSPOT_JNI_NEWFLOATARRAY_RETURN(_ret_ref))
2684 DEFINE_NEWSCALARARRAY(jdoubleArray,  new_doubleArray, Double,
2685                       HOTSPOT_JNI_NEWDOUBLEARRAY_ENTRY(env, len),
2686                       HOTSPOT_JNI_NEWDOUBLEARRAY_RETURN(_ret_ref))
2687 
2688 // Return an address which will fault if the caller writes to it.
2689 
2690 static char* get_bad_address() {
2691   static char* bad_address = NULL;
2692   if (bad_address == NULL) {
2693     size_t size = os::vm_allocation_granularity();
2694     bad_address = os::reserve_memory(size);
2695     if (bad_address != NULL) {
2696       os::protect_memory(bad_address, size, os::MEM_PROT_READ,
2697                          /*is_committed*/false);
2698       MemTracker::record_virtual_memory_type((void*)bad_address, mtInternal);
2699     }
2700   }
2701   return bad_address;
2702 }
2703 
2704 
2705 
2706 #define DEFINE_GETSCALARARRAYELEMENTS(ElementTag,ElementType,Result, Tag \
2707                                       , EntryProbe, ReturnProbe) \
2708 \
2709 JNI_QUICK_ENTRY(ElementType*, \
2710           jni_Get##Result##ArrayElements(JNIEnv *env, ElementType##Array array, jboolean *isCopy)) \
2711   JNIWrapper("Get" XSTR(Result) "ArrayElements"); \
2712   EntryProbe; \
2713   /* allocate an chunk of memory in c land */ \
2714   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \
2715   ElementType* result; \
2716   int len = a->length(); \
2717   if (len == 0) { \
2718     /* Empty array: legal but useless, can't return NULL. \
2719      * Return a pointer to something useless. \
2720      * Avoid asserts in typeArrayOop. */ \
2721     result = (ElementType*)get_bad_address(); \
2722   } else { \
2723     /* JNI Specification states return NULL on OOM */                    \
2724     result = NEW_C_HEAP_ARRAY_RETURN_NULL(ElementType, len, mtInternal); \
2725     if (result != NULL) {                                                \
2726       /* copy the array to the c chunk */                                \
2727       memcpy(result, a->Tag##_at_addr(0), sizeof(ElementType)*len);      \
2728       if (isCopy) {                                                      \
2729         *isCopy = JNI_TRUE;                                              \
2730       }                                                                  \
2731     }                                                                    \
2732   } \
2733   ReturnProbe; \
2734   return result; \
2735 JNI_END
2736 
2737 DEFINE_GETSCALARARRAYELEMENTS(T_BOOLEAN, jboolean, Boolean, bool
2738                               , HOTSPOT_JNI_GETBOOLEANARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2739                               HOTSPOT_JNI_GETBOOLEANARRAYELEMENTS_RETURN((uintptr_t*)result))
2740 DEFINE_GETSCALARARRAYELEMENTS(T_BYTE,    jbyte,    Byte,    byte
2741                               , HOTSPOT_JNI_GETBYTEARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2742                               HOTSPOT_JNI_GETBYTEARRAYELEMENTS_RETURN((char*)result))
2743 DEFINE_GETSCALARARRAYELEMENTS(T_SHORT,   jshort,   Short,   short
2744                               , HOTSPOT_JNI_GETSHORTARRAYELEMENTS_ENTRY(env, (uint16_t*) array, (uintptr_t *) isCopy),
2745                               HOTSPOT_JNI_GETSHORTARRAYELEMENTS_RETURN((uint16_t*)result))
2746 DEFINE_GETSCALARARRAYELEMENTS(T_CHAR,    jchar,    Char,    char
2747                               , HOTSPOT_JNI_GETCHARARRAYELEMENTS_ENTRY(env, (uint16_t*) array, (uintptr_t *) isCopy),
2748                               HOTSPOT_JNI_GETCHARARRAYELEMENTS_RETURN(result))
2749 DEFINE_GETSCALARARRAYELEMENTS(T_INT,     jint,     Int,     int
2750                               , HOTSPOT_JNI_GETINTARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2751                               HOTSPOT_JNI_GETINTARRAYELEMENTS_RETURN((uint32_t*)result))
2752 DEFINE_GETSCALARARRAYELEMENTS(T_LONG,    jlong,    Long,    long
2753                               , HOTSPOT_JNI_GETLONGARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2754                               HOTSPOT_JNI_GETLONGARRAYELEMENTS_RETURN(((uintptr_t*)result)))
2755 // Float and double probes don't return value because dtrace doesn't currently support it
2756 DEFINE_GETSCALARARRAYELEMENTS(T_FLOAT,   jfloat,   Float,   float
2757                               , HOTSPOT_JNI_GETFLOATARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2758                               HOTSPOT_JNI_GETFLOATARRAYELEMENTS_RETURN(result))
2759 DEFINE_GETSCALARARRAYELEMENTS(T_DOUBLE,  jdouble,  Double,  double
2760                               , HOTSPOT_JNI_GETDOUBLEARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) isCopy),
2761                               HOTSPOT_JNI_GETDOUBLEARRAYELEMENTS_RETURN(result))
2762 
2763 
2764 #define DEFINE_RELEASESCALARARRAYELEMENTS(ElementTag,ElementType,Result,Tag \
2765                                           , EntryProbe, ReturnProbe);\
2766 \
2767 JNI_QUICK_ENTRY(void, \
2768           jni_Release##Result##ArrayElements(JNIEnv *env, ElementType##Array array, \
2769                                              ElementType *buf, jint mode)) \
2770   JNIWrapper("Release" XSTR(Result) "ArrayElements"); \
2771   EntryProbe; \
2772   typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \
2773   int len = a->length(); \
2774   if (len != 0) {   /* Empty array:  nothing to free or copy. */  \
2775     if ((mode == 0) || (mode == JNI_COMMIT)) { \
2776       memcpy(a->Tag##_at_addr(0), buf, sizeof(ElementType)*len); \
2777     } \
2778     if ((mode == 0) || (mode == JNI_ABORT)) { \
2779       FreeHeap(buf); \
2780     } \
2781   } \
2782   ReturnProbe; \
2783 JNI_END
2784 
2785 DEFINE_RELEASESCALARARRAYELEMENTS(T_BOOLEAN, jboolean, Boolean, bool
2786                                   , HOTSPOT_JNI_RELEASEBOOLEANARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) buf, mode),
2787                                   HOTSPOT_JNI_RELEASEBOOLEANARRAYELEMENTS_RETURN())
2788 DEFINE_RELEASESCALARARRAYELEMENTS(T_BYTE,    jbyte,    Byte,    byte
2789                                   , HOTSPOT_JNI_RELEASEBYTEARRAYELEMENTS_ENTRY(env, array, (char *) buf, mode),
2790                                   HOTSPOT_JNI_RELEASEBYTEARRAYELEMENTS_RETURN())
2791 DEFINE_RELEASESCALARARRAYELEMENTS(T_SHORT,   jshort,   Short,   short
2792                                   ,  HOTSPOT_JNI_RELEASESHORTARRAYELEMENTS_ENTRY(env, array, (uint16_t *) buf, mode),
2793                                   HOTSPOT_JNI_RELEASESHORTARRAYELEMENTS_RETURN())
2794 DEFINE_RELEASESCALARARRAYELEMENTS(T_CHAR,    jchar,    Char,    char
2795                                   ,  HOTSPOT_JNI_RELEASECHARARRAYELEMENTS_ENTRY(env, array, (uint16_t *) buf, mode),
2796                                   HOTSPOT_JNI_RELEASECHARARRAYELEMENTS_RETURN())
2797 DEFINE_RELEASESCALARARRAYELEMENTS(T_INT,     jint,     Int,     int
2798                                   , HOTSPOT_JNI_RELEASEINTARRAYELEMENTS_ENTRY(env, array, (uint32_t *) buf, mode),
2799                                   HOTSPOT_JNI_RELEASEINTARRAYELEMENTS_RETURN())
2800 DEFINE_RELEASESCALARARRAYELEMENTS(T_LONG,    jlong,    Long,    long
2801                                   , HOTSPOT_JNI_RELEASELONGARRAYELEMENTS_ENTRY(env, array, (uintptr_t *) buf, mode),
2802                                   HOTSPOT_JNI_RELEASELONGARRAYELEMENTS_RETURN())
2803 DEFINE_RELEASESCALARARRAYELEMENTS(T_FLOAT,   jfloat,   Float,   float
2804                                   , HOTSPOT_JNI_RELEASEFLOATARRAYELEMENTS_ENTRY(env, array, (float *) buf, mode),
2805                                   HOTSPOT_JNI_RELEASEFLOATARRAYELEMENTS_RETURN())
2806 DEFINE_RELEASESCALARARRAYELEMENTS(T_DOUBLE,  jdouble,  Double,  double
2807                                   , HOTSPOT_JNI_RELEASEDOUBLEARRAYELEMENTS_ENTRY(env, array, (double *) buf, mode),
2808                                   HOTSPOT_JNI_RELEASEDOUBLEARRAYELEMENTS_RETURN())
2809 
2810 
2811 #define DEFINE_GETSCALARARRAYREGION(ElementTag,ElementType,Result, Tag \
2812                                     , EntryProbe, ReturnProbe); \
2813   DT_VOID_RETURN_MARK_DECL(Get##Result##ArrayRegion \
2814                            , ReturnProbe); \
2815 \
2816 JNI_ENTRY(void, \
2817 jni_Get##Result##ArrayRegion(JNIEnv *env, ElementType##Array array, jsize start, \
2818              jsize len, ElementType *buf)) \
2819   JNIWrapper("Get" XSTR(Result) "ArrayRegion"); \
2820   EntryProbe; \
2821   DT_VOID_RETURN_MARK(Get##Result##ArrayRegion); \
2822   typeArrayOop src = typeArrayOop(JNIHandles::resolve_non_null(array)); \
2823   if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)src->length())) { \
2824     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
2825   } else { \
2826     if (len > 0) { \
2827       int sc = TypeArrayKlass::cast(src->klass())->log2_element_size(); \
2828       memcpy((u_char*) buf, \
2829              (u_char*) src->Tag##_at_addr(start), \
2830              len << sc);                          \
2831     } \
2832   } \
2833 JNI_END
2834 
2835 DEFINE_GETSCALARARRAYREGION(T_BOOLEAN, jboolean,Boolean, bool
2836                             , HOTSPOT_JNI_GETBOOLEANARRAYREGION_ENTRY(env, array, start, len, (uintptr_t *) buf),
2837                             HOTSPOT_JNI_GETBOOLEANARRAYREGION_RETURN());
2838 DEFINE_GETSCALARARRAYREGION(T_BYTE,    jbyte,   Byte,    byte
2839                             ,  HOTSPOT_JNI_GETBYTEARRAYREGION_ENTRY(env, array, start, len, (char *) buf),
2840                             HOTSPOT_JNI_GETBYTEARRAYREGION_RETURN());
2841 DEFINE_GETSCALARARRAYREGION(T_SHORT,   jshort,  Short,   short
2842                             , HOTSPOT_JNI_GETSHORTARRAYREGION_ENTRY(env, array, start, len, (uint16_t *) buf),
2843                             HOTSPOT_JNI_GETSHORTARRAYREGION_RETURN());
2844 DEFINE_GETSCALARARRAYREGION(T_CHAR,    jchar,   Char,    char
2845                             ,  HOTSPOT_JNI_GETCHARARRAYREGION_ENTRY(env, array, start, len, (uint16_t*) buf),
2846                             HOTSPOT_JNI_GETCHARARRAYREGION_RETURN());
2847 DEFINE_GETSCALARARRAYREGION(T_INT,     jint,    Int,     int
2848                             , HOTSPOT_JNI_GETINTARRAYREGION_ENTRY(env, array, start, len, (uint32_t*) buf),
2849                             HOTSPOT_JNI_GETINTARRAYREGION_RETURN());
2850 DEFINE_GETSCALARARRAYREGION(T_LONG,    jlong,   Long,    long
2851                             ,  HOTSPOT_JNI_GETLONGARRAYREGION_ENTRY(env, array, start, len, (uintptr_t *) buf),
2852                             HOTSPOT_JNI_GETLONGARRAYREGION_RETURN());
2853 DEFINE_GETSCALARARRAYREGION(T_FLOAT,   jfloat,  Float,   float
2854                             , HOTSPOT_JNI_GETFLOATARRAYREGION_ENTRY(env, array, start, len, (float *) buf),
2855                             HOTSPOT_JNI_GETFLOATARRAYREGION_RETURN());
2856 DEFINE_GETSCALARARRAYREGION(T_DOUBLE,  jdouble, Double,  double
2857                             , HOTSPOT_JNI_GETDOUBLEARRAYREGION_ENTRY(env, array, start, len, (double *) buf),
2858                             HOTSPOT_JNI_GETDOUBLEARRAYREGION_RETURN());
2859 
2860 
2861 #define DEFINE_SETSCALARARRAYREGION(ElementTag,ElementType,Result, Tag \
2862                                     , EntryProbe, ReturnProbe); \
2863   DT_VOID_RETURN_MARK_DECL(Set##Result##ArrayRegion \
2864                            ,ReturnProbe);           \
2865 \
2866 JNI_ENTRY(void, \
2867 jni_Set##Result##ArrayRegion(JNIEnv *env, ElementType##Array array, jsize start, \
2868              jsize len, const ElementType *buf)) \
2869   JNIWrapper("Set" XSTR(Result) "ArrayRegion"); \
2870   EntryProbe; \
2871   DT_VOID_RETURN_MARK(Set##Result##ArrayRegion); \
2872   typeArrayOop dst = typeArrayOop(JNIHandles::resolve_non_null(array)); \
2873   if (start < 0 || len < 0 || ((unsigned int)start + (unsigned int)len > (unsigned int)dst->length())) { \
2874     THROW(vmSymbols::java_lang_ArrayIndexOutOfBoundsException()); \
2875   } else { \
2876     if (len > 0) { \
2877       int sc = TypeArrayKlass::cast(dst->klass())->log2_element_size(); \
2878       memcpy((u_char*) dst->Tag##_at_addr(start), \
2879              (u_char*) buf, \
2880              len << sc);    \
2881     } \
2882   } \
2883 JNI_END
2884 
2885 DEFINE_SETSCALARARRAYREGION(T_BOOLEAN, jboolean, Boolean, bool
2886                             , HOTSPOT_JNI_SETBOOLEANARRAYREGION_ENTRY(env, array, start, len, (uintptr_t *)buf),
2887                             HOTSPOT_JNI_SETBOOLEANARRAYREGION_RETURN())
2888 DEFINE_SETSCALARARRAYREGION(T_BYTE,    jbyte,    Byte,    byte
2889                             , HOTSPOT_JNI_SETBYTEARRAYREGION_ENTRY(env, array, start, len, (char *) buf),
2890                             HOTSPOT_JNI_SETBYTEARRAYREGION_RETURN())
2891 DEFINE_SETSCALARARRAYREGION(T_SHORT,   jshort,   Short,   short
2892                             , HOTSPOT_JNI_SETSHORTARRAYREGION_ENTRY(env, array, start, len, (uint16_t *) buf),
2893                             HOTSPOT_JNI_SETSHORTARRAYREGION_RETURN())
2894 DEFINE_SETSCALARARRAYREGION(T_CHAR,    jchar,    Char,    char
2895                             , HOTSPOT_JNI_SETCHARARRAYREGION_ENTRY(env, array, start, len, (uint16_t *) buf),
2896                             HOTSPOT_JNI_SETCHARARRAYREGION_RETURN())
2897 DEFINE_SETSCALARARRAYREGION(T_INT,     jint,     Int,     int
2898                             , HOTSPOT_JNI_SETINTARRAYREGION_ENTRY(env, array, start, len, (uint32_t *) buf),
2899                             HOTSPOT_JNI_SETINTARRAYREGION_RETURN())
2900 DEFINE_SETSCALARARRAYREGION(T_LONG,    jlong,    Long,    long
2901                             , HOTSPOT_JNI_SETLONGARRAYREGION_ENTRY(env, array, start, len, (uintptr_t *) buf),
2902                             HOTSPOT_JNI_SETLONGARRAYREGION_RETURN())
2903 DEFINE_SETSCALARARRAYREGION(T_FLOAT,   jfloat,   Float,   float
2904                             , HOTSPOT_JNI_SETFLOATARRAYREGION_ENTRY(env, array, start, len, (float *) buf),
2905                             HOTSPOT_JNI_SETFLOATARRAYREGION_RETURN())
2906 DEFINE_SETSCALARARRAYREGION(T_DOUBLE,  jdouble,  Double,  double
2907                             , HOTSPOT_JNI_SETDOUBLEARRAYREGION_ENTRY(env, array, start, len, (double *) buf),
2908                             HOTSPOT_JNI_SETDOUBLEARRAYREGION_RETURN())
2909 
2910 
2911 //
2912 // Interception of natives
2913 //
2914 
2915 // The RegisterNatives call being attempted tried to register with a method that
2916 // is not native.  Ask JVM TI what prefixes have been specified.  Then check
2917 // to see if the native method is now wrapped with the prefixes.  See the
2918 // SetNativeMethodPrefix(es) functions in the JVM TI Spec for details.
2919 static Method* find_prefixed_native(KlassHandle k,
2920                                       Symbol* name, Symbol* signature, TRAPS) {
2921 #if INCLUDE_JVMTI
2922   ResourceMark rm(THREAD);
2923   Method* method;
2924   int name_len = name->utf8_length();
2925   char* name_str = name->as_utf8();
2926   int prefix_count;
2927   char** prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
2928   for (int i = 0; i < prefix_count; i++) {
2929     char* prefix = prefixes[i];
2930     int prefix_len = (int)strlen(prefix);
2931 
2932     // try adding this prefix to the method name and see if it matches another method name
2933     int trial_len = name_len + prefix_len;
2934     char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
2935     strcpy(trial_name_str, prefix);
2936     strcat(trial_name_str, name_str);
2937     TempNewSymbol trial_name = SymbolTable::probe(trial_name_str, trial_len);
2938     if (trial_name == NULL) {
2939       continue; // no such symbol, so this prefix wasn't used, try the next prefix
2940     }
2941     method = k()->lookup_method(trial_name, signature);
2942     if (method == NULL) {
2943       continue; // signature doesn't match, try the next prefix
2944     }
2945     if (method->is_native()) {
2946       method->set_is_prefixed_native();
2947       return method; // wahoo, we found a prefixed version of the method, return it
2948     }
2949     // found as non-native, so prefix is good, add it, probably just need more prefixes
2950     name_len = trial_len;
2951     name_str = trial_name_str;
2952   }
2953 #endif // INCLUDE_JVMTI
2954   return NULL; // not found
2955 }
2956 
2957 static bool register_native(KlassHandle k, Symbol* name, Symbol* signature, address entry, TRAPS) {
2958   Method* method = k()->lookup_method(name, signature);
2959   if (method == NULL) {
2960     ResourceMark rm;
2961     stringStream st;
2962     st.print("Method %s name or signature does not match",
2963              Method::name_and_sig_as_C_string(k(), name, signature));
2964     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false);
2965   }
2966   if (!method->is_native()) {
2967     // trying to register to a non-native method, see if a JVM TI agent has added prefix(es)
2968     method = find_prefixed_native(k, name, signature, THREAD);
2969     if (method == NULL) {
2970       ResourceMark rm;
2971       stringStream st;
2972       st.print("Method %s is not declared as native",
2973                Method::name_and_sig_as_C_string(k(), name, signature));
2974       THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false);
2975     }
2976   }
2977 
2978   if (entry != NULL) {
2979     method->set_native_function(entry,
2980       Method::native_bind_event_is_interesting);
2981   } else {
2982     method->clear_native_function();
2983   }
2984   if (PrintJNIResolving) {
2985     ResourceMark rm(THREAD);
2986     tty->print_cr("[Registering JNI native method %s.%s]",
2987       method->method_holder()->external_name(),
2988       method->name()->as_C_string());
2989   }
2990   return true;
2991 }
2992 
2993 DT_RETURN_MARK_DECL(RegisterNatives, jint
2994                     , HOTSPOT_JNI_REGISTERNATIVES_RETURN(_ret_ref));
2995 
2996 JNI_ENTRY(jint, jni_RegisterNatives(JNIEnv *env, jclass clazz,
2997                                     const JNINativeMethod *methods,
2998                                     jint nMethods))
2999   JNIWrapper("RegisterNatives");
3000   HOTSPOT_JNI_REGISTERNATIVES_ENTRY(env, clazz, (void *) methods, nMethods);
3001   jint ret = 0;
3002   DT_RETURN_MARK(RegisterNatives, jint, (const jint&)ret);
3003 
3004   KlassHandle h_k(thread, java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz)));
3005 
3006   for (int index = 0; index < nMethods; index++) {
3007     const char* meth_name = methods[index].name;
3008     const char* meth_sig = methods[index].signature;
3009     int meth_name_len = (int)strlen(meth_name);
3010 
3011     // The class should have been loaded (we have an instance of the class
3012     // passed in) so the method and signature should already be in the symbol
3013     // table.  If they're not there, the method doesn't exist.
3014     TempNewSymbol  name = SymbolTable::probe(meth_name, meth_name_len);
3015     TempNewSymbol  signature = SymbolTable::probe(meth_sig, (int)strlen(meth_sig));
3016 
3017     if (name == NULL || signature == NULL) {
3018       ResourceMark rm;
3019       stringStream st;
3020       st.print("Method %s.%s%s not found", h_k()->external_name(), meth_name, meth_sig);
3021       // Must return negative value on failure
3022       THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), -1);
3023     }
3024 
3025     bool res = register_native(h_k, name, signature,
3026                                (address) methods[index].fnPtr, THREAD);
3027     if (!res) {
3028       ret = -1;
3029       break;
3030     }
3031   }
3032   return ret;
3033 JNI_END
3034 
3035 
3036 JNI_ENTRY(jint, jni_UnregisterNatives(JNIEnv *env, jclass clazz))
3037   JNIWrapper("UnregisterNatives");
3038  HOTSPOT_JNI_UNREGISTERNATIVES_ENTRY(env, clazz);
3039   Klass* k   = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(clazz));
3040   //%note jni_2
3041   if (k->is_instance_klass()) {
3042     for (int index = 0; index < InstanceKlass::cast(k)->methods()->length(); index++) {
3043       Method* m = InstanceKlass::cast(k)->methods()->at(index);
3044       if (m->is_native()) {
3045         m->clear_native_function();
3046         m->set_signature_handler(NULL);
3047       }
3048     }
3049   }
3050  HOTSPOT_JNI_UNREGISTERNATIVES_RETURN(0);
3051   return 0;
3052 JNI_END
3053 
3054 //
3055 // Monitor functions
3056 //
3057 
3058 DT_RETURN_MARK_DECL(MonitorEnter, jint
3059                     , HOTSPOT_JNI_MONITORENTER_RETURN(_ret_ref));
3060 
3061 JNI_ENTRY(jint, jni_MonitorEnter(JNIEnv *env, jobject jobj))
3062  HOTSPOT_JNI_MONITORENTER_ENTRY(env, jobj);
3063   jint ret = JNI_ERR;
3064   DT_RETURN_MARK(MonitorEnter, jint, (const jint&)ret);
3065 
3066   // If the object is null, we can't do anything with it
3067   if (jobj == NULL) {
3068     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_ERR);
3069   }
3070 
3071   Handle obj(thread, JNIHandles::resolve_non_null(jobj));
3072   ObjectSynchronizer::jni_enter(obj, CHECK_(JNI_ERR));
3073   ret = JNI_OK;
3074   return ret;
3075 JNI_END
3076 
3077 DT_RETURN_MARK_DECL(MonitorExit, jint
3078                     , HOTSPOT_JNI_MONITOREXIT_RETURN(_ret_ref));
3079 
3080 JNI_ENTRY(jint, jni_MonitorExit(JNIEnv *env, jobject jobj))
3081  HOTSPOT_JNI_MONITOREXIT_ENTRY(env, jobj);
3082   jint ret = JNI_ERR;
3083   DT_RETURN_MARK(MonitorExit, jint, (const jint&)ret);
3084 
3085   // Don't do anything with a null object
3086   if (jobj == NULL) {
3087     THROW_(vmSymbols::java_lang_NullPointerException(), JNI_ERR);
3088   }
3089 
3090   Handle obj(THREAD, JNIHandles::resolve_non_null(jobj));
3091   ObjectSynchronizer::jni_exit(obj(), CHECK_(JNI_ERR));
3092 
3093   ret = JNI_OK;
3094   return ret;
3095 JNI_END
3096 
3097 //
3098 // Extensions
3099 //
3100 
3101 DT_VOID_RETURN_MARK_DECL(GetStringRegion
3102                          , HOTSPOT_JNI_GETSTRINGREGION_RETURN());
3103 
3104 JNI_ENTRY(void, jni_GetStringRegion(JNIEnv *env, jstring string, jsize start, jsize len, jchar *buf))
3105   JNIWrapper("GetStringRegion");
3106  HOTSPOT_JNI_GETSTRINGREGION_ENTRY(env, string, start, len, buf);
3107   DT_VOID_RETURN_MARK(GetStringRegion);
3108   oop s = JNIHandles::resolve_non_null(string);
3109   int s_len = java_lang_String::length(s);
3110   if (start < 0 || len < 0 || start + len > s_len) {
3111     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
3112   } else {
3113     if (len > 0) {
3114       typeArrayOop s_value = java_lang_String::value(s);
3115       bool is_latin1 = java_lang_String::is_latin1(s);
3116       if (!is_latin1) {
3117         memcpy(buf, s_value->char_at_addr(start), sizeof(jchar)*len);
3118       } else {
3119         for (int i = 0; i < len; i++) {
3120           buf[i] = ((jchar) s_value->byte_at(i + start)) & 0xff;
3121         }
3122       }
3123     }
3124   }
3125 JNI_END
3126 
3127 DT_VOID_RETURN_MARK_DECL(GetStringUTFRegion
3128                          , HOTSPOT_JNI_GETSTRINGUTFREGION_RETURN());
3129 
3130 JNI_ENTRY(void, jni_GetStringUTFRegion(JNIEnv *env, jstring string, jsize start, jsize len, char *buf))
3131   JNIWrapper("GetStringUTFRegion");
3132  HOTSPOT_JNI_GETSTRINGUTFREGION_ENTRY(env, string, start, len, buf);
3133   DT_VOID_RETURN_MARK(GetStringUTFRegion);
3134   oop s = JNIHandles::resolve_non_null(string);
3135   int s_len = java_lang_String::length(s);
3136   if (start < 0 || len < 0 || start + len > s_len) {
3137     THROW(vmSymbols::java_lang_StringIndexOutOfBoundsException());
3138   } else {
3139     //%note jni_7
3140     if (len > 0) {
3141       // Assume the buffer is large enough as the JNI spec. does not require user error checking
3142       java_lang_String::as_utf8_string(s, start, len, buf, INT_MAX);
3143       // as_utf8_string null-terminates the result string
3144     } else {
3145       // JDK null-terminates the buffer even in len is zero
3146       if (buf != NULL) {
3147         buf[0] = 0;
3148       }
3149     }
3150   }
3151 JNI_END
3152 
3153 
3154 JNI_ENTRY(void*, jni_GetPrimitiveArrayCritical(JNIEnv *env, jarray array, jboolean *isCopy))
3155   JNIWrapper("GetPrimitiveArrayCritical");
3156  HOTSPOT_JNI_GETPRIMITIVEARRAYCRITICAL_ENTRY(env, array, (uintptr_t *) isCopy);
3157   GC_locker::lock_critical(thread);
3158   if (isCopy != NULL) {
3159     *isCopy = JNI_FALSE;
3160   }
3161   oop a = JNIHandles::resolve_non_null(array);
3162   assert(a->is_array(), "just checking");
3163   BasicType type;
3164   if (a->is_objArray()) {
3165     type = T_OBJECT;
3166   } else {
3167     type = TypeArrayKlass::cast(a->klass())->element_type();
3168   }
3169   void* ret = arrayOop(a)->base(type);
3170  HOTSPOT_JNI_GETPRIMITIVEARRAYCRITICAL_RETURN(ret);
3171   return ret;
3172 JNI_END
3173 
3174 
3175 JNI_ENTRY(void, jni_ReleasePrimitiveArrayCritical(JNIEnv *env, jarray array, void *carray, jint mode))
3176   JNIWrapper("ReleasePrimitiveArrayCritical");
3177   HOTSPOT_JNI_RELEASEPRIMITIVEARRAYCRITICAL_ENTRY(env, array, carray, mode);
3178   // The array, carray and mode arguments are ignored
3179   GC_locker::unlock_critical(thread);
3180 HOTSPOT_JNI_RELEASEPRIMITIVEARRAYCRITICAL_RETURN();
3181 JNI_END
3182 
3183 
3184 JNI_ENTRY(const jchar*, jni_GetStringCritical(JNIEnv *env, jstring string, jboolean *isCopy))
3185   JNIWrapper("GetStringCritical");
3186   HOTSPOT_JNI_GETSTRINGCRITICAL_ENTRY(env, string, (uintptr_t *) isCopy);
3187   GC_locker::lock_critical(thread);
3188   oop s = JNIHandles::resolve_non_null(string);
3189   typeArrayOop s_value = java_lang_String::value(s);
3190   bool is_latin1 = java_lang_String::is_latin1(s);
3191   if (isCopy != NULL) {
3192     *isCopy = is_latin1 ? JNI_TRUE : JNI_FALSE;
3193   }
3194   const jchar* ret;
3195   if (!is_latin1) {
3196     ret = s_value->char_at_addr(0);
3197   } else {
3198     // Inflate latin1 encoded string to UTF16
3199     int s_len = java_lang_String::length(s);
3200     jchar* buf = NEW_C_HEAP_ARRAY(jchar, s_len, mtInternal);
3201     for (int i = 0; i < s_len; i++) {
3202       buf[i] = ((jchar) s_value->byte_at(i)) & 0xff;
3203     }
3204     ret = &buf[0];
3205   }
3206  HOTSPOT_JNI_GETSTRINGCRITICAL_RETURN((uint16_t *) ret);
3207   return ret;
3208 JNI_END
3209 
3210 
3211 JNI_ENTRY(void, jni_ReleaseStringCritical(JNIEnv *env, jstring str, const jchar *chars))
3212   JNIWrapper("ReleaseStringCritical");
3213   HOTSPOT_JNI_RELEASESTRINGCRITICAL_ENTRY(env, str, (uint16_t *) chars);
3214   // The str and chars arguments are ignored for UTF16 strings
3215   oop s = JNIHandles::resolve_non_null(str);
3216   bool is_latin1 = java_lang_String::is_latin1(s);
3217   if (is_latin1) {
3218     // For latin1 string, free jchar array allocated by earlier call to GetStringCritical.
3219     // This assumes that ReleaseStringCritical bookends GetStringCritical.
3220     FREE_C_HEAP_ARRAY(jchar, chars);
3221   }
3222   GC_locker::unlock_critical(thread);
3223 HOTSPOT_JNI_RELEASESTRINGCRITICAL_RETURN();
3224 JNI_END
3225 
3226 
3227 JNI_ENTRY(jweak, jni_NewWeakGlobalRef(JNIEnv *env, jobject ref))
3228   JNIWrapper("jni_NewWeakGlobalRef");
3229  HOTSPOT_JNI_NEWWEAKGLOBALREF_ENTRY(env, ref);
3230   Handle ref_handle(thread, JNIHandles::resolve(ref));
3231   jweak ret = JNIHandles::make_weak_global(ref_handle);
3232  HOTSPOT_JNI_NEWWEAKGLOBALREF_RETURN(ret);
3233   return ret;
3234 JNI_END
3235 
3236 // Must be JNI_ENTRY (with HandleMark)
3237 JNI_ENTRY(void, jni_DeleteWeakGlobalRef(JNIEnv *env, jweak ref))
3238   JNIWrapper("jni_DeleteWeakGlobalRef");
3239   HOTSPOT_JNI_DELETEWEAKGLOBALREF_ENTRY(env, ref);
3240   JNIHandles::destroy_weak_global(ref);
3241   HOTSPOT_JNI_DELETEWEAKGLOBALREF_RETURN();
3242 JNI_END
3243 
3244 
3245 JNI_QUICK_ENTRY(jboolean, jni_ExceptionCheck(JNIEnv *env))
3246   JNIWrapper("jni_ExceptionCheck");
3247  HOTSPOT_JNI_EXCEPTIONCHECK_ENTRY(env);
3248   jni_check_async_exceptions(thread);
3249   jboolean ret = (thread->has_pending_exception()) ? JNI_TRUE : JNI_FALSE;
3250  HOTSPOT_JNI_EXCEPTIONCHECK_RETURN(ret);
3251   return ret;
3252 JNI_END
3253 
3254 
3255 // Initialization state for three routines below relating to
3256 // java.nio.DirectBuffers
3257 static          jint directBufferSupportInitializeStarted = 0;
3258 static volatile jint directBufferSupportInitializeEnded   = 0;
3259 static volatile jint directBufferSupportInitializeFailed  = 0;
3260 static jclass    bufferClass                 = NULL;
3261 static jclass    directBufferClass           = NULL;
3262 static jclass    directByteBufferClass       = NULL;
3263 static jmethodID directByteBufferConstructor = NULL;
3264 static jfieldID  directBufferAddressField    = NULL;
3265 static jfieldID  bufferCapacityField         = NULL;
3266 
3267 static jclass lookupOne(JNIEnv* env, const char* name, TRAPS) {
3268   Handle loader;            // null (bootstrap) loader
3269   Handle protection_domain; // null protection domain
3270 
3271   TempNewSymbol sym = SymbolTable::new_symbol(name, CHECK_NULL);
3272   jclass result =  find_class_from_class_loader(env, sym, true, loader, protection_domain, true, CHECK_NULL);
3273 
3274   if (TraceClassResolution && result != NULL) {
3275     trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
3276   }
3277   return result;
3278 }
3279 
3280 // These lookups are done with the NULL (bootstrap) ClassLoader to
3281 // circumvent any security checks that would be done by jni_FindClass.
3282 JNI_ENTRY(bool, lookupDirectBufferClasses(JNIEnv* env))
3283 {
3284   if ((bufferClass           = lookupOne(env, "java/nio/Buffer", thread))           == NULL) { return false; }
3285   if ((directBufferClass     = lookupOne(env, "sun/nio/ch/DirectBuffer", thread))   == NULL) { return false; }
3286   if ((directByteBufferClass = lookupOne(env, "java/nio/DirectByteBuffer", thread)) == NULL) { return false; }
3287   return true;
3288 }
3289 JNI_END
3290 
3291 
3292 static bool initializeDirectBufferSupport(JNIEnv* env, JavaThread* thread) {
3293   if (directBufferSupportInitializeFailed) {
3294     return false;
3295   }
3296 
3297   if (Atomic::cmpxchg(1, &directBufferSupportInitializeStarted, 0) == 0) {
3298     if (!lookupDirectBufferClasses(env)) {
3299       directBufferSupportInitializeFailed = 1;
3300       return false;
3301     }
3302 
3303     // Make global references for these
3304     bufferClass           = (jclass) env->NewGlobalRef(bufferClass);
3305     directBufferClass     = (jclass) env->NewGlobalRef(directBufferClass);
3306     directByteBufferClass = (jclass) env->NewGlobalRef(directByteBufferClass);
3307 
3308     // Get needed field and method IDs
3309     directByteBufferConstructor = env->GetMethodID(directByteBufferClass, "<init>", "(JI)V");
3310     if (env->ExceptionCheck()) {
3311       env->ExceptionClear();
3312       directBufferSupportInitializeFailed = 1;
3313       return false;
3314     }
3315     directBufferAddressField    = env->GetFieldID(bufferClass, "address", "J");
3316     if (env->ExceptionCheck()) {
3317       env->ExceptionClear();
3318       directBufferSupportInitializeFailed = 1;
3319       return false;
3320     }
3321     bufferCapacityField         = env->GetFieldID(bufferClass, "capacity", "I");
3322     if (env->ExceptionCheck()) {
3323       env->ExceptionClear();
3324       directBufferSupportInitializeFailed = 1;
3325       return false;
3326     }
3327 
3328     if ((directByteBufferConstructor == NULL) ||
3329         (directBufferAddressField    == NULL) ||
3330         (bufferCapacityField         == NULL)) {
3331       directBufferSupportInitializeFailed = 1;
3332       return false;
3333     }
3334 
3335     directBufferSupportInitializeEnded = 1;
3336   } else {
3337     while (!directBufferSupportInitializeEnded && !directBufferSupportInitializeFailed) {
3338       os::naked_yield();
3339     }
3340   }
3341 
3342   return !directBufferSupportInitializeFailed;
3343 }
3344 
3345 extern "C" jobject JNICALL jni_NewDirectByteBuffer(JNIEnv *env, void* address, jlong capacity)
3346 {
3347   // thread_from_jni_environment() will block if VM is gone.
3348   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
3349 
3350   JNIWrapper("jni_NewDirectByteBuffer");
3351  HOTSPOT_JNI_NEWDIRECTBYTEBUFFER_ENTRY(env, address, capacity);
3352 
3353   if (!directBufferSupportInitializeEnded) {
3354     if (!initializeDirectBufferSupport(env, thread)) {
3355       HOTSPOT_JNI_NEWDIRECTBYTEBUFFER_RETURN(NULL);
3356       return NULL;
3357     }
3358   }
3359 
3360   // Being paranoid about accidental sign extension on address
3361   jlong addr = (jlong) ((uintptr_t) address);
3362   // NOTE that package-private DirectByteBuffer constructor currently
3363   // takes int capacity
3364   jint  cap  = (jint)  capacity;
3365   jobject ret = env->NewObject(directByteBufferClass, directByteBufferConstructor, addr, cap);
3366   HOTSPOT_JNI_NEWDIRECTBYTEBUFFER_RETURN(ret);
3367   return ret;
3368 }
3369 
3370 DT_RETURN_MARK_DECL(GetDirectBufferAddress, void*
3371                     , HOTSPOT_JNI_GETDIRECTBUFFERADDRESS_RETURN((void*) _ret_ref));
3372 
3373 extern "C" void* JNICALL jni_GetDirectBufferAddress(JNIEnv *env, jobject buf)
3374 {
3375   // thread_from_jni_environment() will block if VM is gone.
3376   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
3377 
3378   JNIWrapper("jni_GetDirectBufferAddress");
3379   HOTSPOT_JNI_GETDIRECTBUFFERADDRESS_ENTRY(env, buf);
3380   void* ret = NULL;
3381   DT_RETURN_MARK(GetDirectBufferAddress, void*, (const void*&)ret);
3382 
3383   if (!directBufferSupportInitializeEnded) {
3384     if (!initializeDirectBufferSupport(env, thread)) {
3385       return 0;
3386     }
3387   }
3388 
3389   if ((buf != NULL) && (!env->IsInstanceOf(buf, directBufferClass))) {
3390     return 0;
3391   }
3392 
3393   ret = (void*)(intptr_t)env->GetLongField(buf, directBufferAddressField);
3394   return ret;
3395 }
3396 
3397 DT_RETURN_MARK_DECL(GetDirectBufferCapacity, jlong
3398                     , HOTSPOT_JNI_GETDIRECTBUFFERCAPACITY_RETURN(_ret_ref));
3399 
3400 extern "C" jlong JNICALL jni_GetDirectBufferCapacity(JNIEnv *env, jobject buf)
3401 {
3402   // thread_from_jni_environment() will block if VM is gone.
3403   JavaThread* thread = JavaThread::thread_from_jni_environment(env);
3404 
3405   JNIWrapper("jni_GetDirectBufferCapacity");
3406   HOTSPOT_JNI_GETDIRECTBUFFERCAPACITY_ENTRY(env, buf);
3407   jlong ret = -1;
3408   DT_RETURN_MARK(GetDirectBufferCapacity, jlong, (const jlong&)ret);
3409 
3410   if (!directBufferSupportInitializeEnded) {
3411     if (!initializeDirectBufferSupport(env, thread)) {
3412       ret = 0;
3413       return ret;
3414     }
3415   }
3416 
3417   if (buf == NULL) {
3418     return -1;
3419   }
3420 
3421   if (!env->IsInstanceOf(buf, directBufferClass)) {
3422     return -1;
3423   }
3424 
3425   // NOTE that capacity is currently an int in the implementation
3426   ret = env->GetIntField(buf, bufferCapacityField);
3427   return ret;
3428 }
3429 
3430 
3431 JNI_LEAF(jint, jni_GetVersion(JNIEnv *env))
3432   JNIWrapper("GetVersion");
3433   HOTSPOT_JNI_GETVERSION_ENTRY(env);
3434   HOTSPOT_JNI_GETVERSION_RETURN(CurrentVersion);
3435   return CurrentVersion;
3436 JNI_END
3437 
3438 extern struct JavaVM_ main_vm;
3439 
3440 JNI_LEAF(jint, jni_GetJavaVM(JNIEnv *env, JavaVM **vm))
3441   JNIWrapper("jni_GetJavaVM");
3442   HOTSPOT_JNI_GETJAVAVM_ENTRY(env, (void **) vm);
3443   *vm  = (JavaVM *)(&main_vm);
3444   HOTSPOT_JNI_GETJAVAVM_RETURN(JNI_OK);
3445   return JNI_OK;
3446 JNI_END
3447 
3448 // Structure containing all jni functions
3449 struct JNINativeInterface_ jni_NativeInterface = {
3450     NULL,
3451     NULL,
3452     NULL,
3453 
3454     NULL,
3455 
3456     jni_GetVersion,
3457 
3458     jni_DefineClass,
3459     jni_FindClass,
3460 
3461     jni_FromReflectedMethod,
3462     jni_FromReflectedField,
3463 
3464     jni_ToReflectedMethod,
3465 
3466     jni_GetSuperclass,
3467     jni_IsAssignableFrom,
3468 
3469     jni_ToReflectedField,
3470 
3471     jni_Throw,
3472     jni_ThrowNew,
3473     jni_ExceptionOccurred,
3474     jni_ExceptionDescribe,
3475     jni_ExceptionClear,
3476     jni_FatalError,
3477 
3478     jni_PushLocalFrame,
3479     jni_PopLocalFrame,
3480 
3481     jni_NewGlobalRef,
3482     jni_DeleteGlobalRef,
3483     jni_DeleteLocalRef,
3484     jni_IsSameObject,
3485 
3486     jni_NewLocalRef,
3487     jni_EnsureLocalCapacity,
3488 
3489     jni_AllocObject,
3490     jni_NewObject,
3491     jni_NewObjectV,
3492     jni_NewObjectA,
3493 
3494     jni_GetObjectClass,
3495     jni_IsInstanceOf,
3496 
3497     jni_GetMethodID,
3498 
3499     jni_CallObjectMethod,
3500     jni_CallObjectMethodV,
3501     jni_CallObjectMethodA,
3502     jni_CallBooleanMethod,
3503     jni_CallBooleanMethodV,
3504     jni_CallBooleanMethodA,
3505     jni_CallByteMethod,
3506     jni_CallByteMethodV,
3507     jni_CallByteMethodA,
3508     jni_CallCharMethod,
3509     jni_CallCharMethodV,
3510     jni_CallCharMethodA,
3511     jni_CallShortMethod,
3512     jni_CallShortMethodV,
3513     jni_CallShortMethodA,
3514     jni_CallIntMethod,
3515     jni_CallIntMethodV,
3516     jni_CallIntMethodA,
3517     jni_CallLongMethod,
3518     jni_CallLongMethodV,
3519     jni_CallLongMethodA,
3520     jni_CallFloatMethod,
3521     jni_CallFloatMethodV,
3522     jni_CallFloatMethodA,
3523     jni_CallDoubleMethod,
3524     jni_CallDoubleMethodV,
3525     jni_CallDoubleMethodA,
3526     jni_CallVoidMethod,
3527     jni_CallVoidMethodV,
3528     jni_CallVoidMethodA,
3529 
3530     jni_CallNonvirtualObjectMethod,
3531     jni_CallNonvirtualObjectMethodV,
3532     jni_CallNonvirtualObjectMethodA,
3533     jni_CallNonvirtualBooleanMethod,
3534     jni_CallNonvirtualBooleanMethodV,
3535     jni_CallNonvirtualBooleanMethodA,
3536     jni_CallNonvirtualByteMethod,
3537     jni_CallNonvirtualByteMethodV,
3538     jni_CallNonvirtualByteMethodA,
3539     jni_CallNonvirtualCharMethod,
3540     jni_CallNonvirtualCharMethodV,
3541     jni_CallNonvirtualCharMethodA,
3542     jni_CallNonvirtualShortMethod,
3543     jni_CallNonvirtualShortMethodV,
3544     jni_CallNonvirtualShortMethodA,
3545     jni_CallNonvirtualIntMethod,
3546     jni_CallNonvirtualIntMethodV,
3547     jni_CallNonvirtualIntMethodA,
3548     jni_CallNonvirtualLongMethod,
3549     jni_CallNonvirtualLongMethodV,
3550     jni_CallNonvirtualLongMethodA,
3551     jni_CallNonvirtualFloatMethod,
3552     jni_CallNonvirtualFloatMethodV,
3553     jni_CallNonvirtualFloatMethodA,
3554     jni_CallNonvirtualDoubleMethod,
3555     jni_CallNonvirtualDoubleMethodV,
3556     jni_CallNonvirtualDoubleMethodA,
3557     jni_CallNonvirtualVoidMethod,
3558     jni_CallNonvirtualVoidMethodV,
3559     jni_CallNonvirtualVoidMethodA,
3560 
3561     jni_GetFieldID,
3562 
3563     jni_GetObjectField,
3564     jni_GetBooleanField,
3565     jni_GetByteField,
3566     jni_GetCharField,
3567     jni_GetShortField,
3568     jni_GetIntField,
3569     jni_GetLongField,
3570     jni_GetFloatField,
3571     jni_GetDoubleField,
3572 
3573     jni_SetObjectField,
3574     jni_SetBooleanField,
3575     jni_SetByteField,
3576     jni_SetCharField,
3577     jni_SetShortField,
3578     jni_SetIntField,
3579     jni_SetLongField,
3580     jni_SetFloatField,
3581     jni_SetDoubleField,
3582 
3583     jni_GetStaticMethodID,
3584 
3585     jni_CallStaticObjectMethod,
3586     jni_CallStaticObjectMethodV,
3587     jni_CallStaticObjectMethodA,
3588     jni_CallStaticBooleanMethod,
3589     jni_CallStaticBooleanMethodV,
3590     jni_CallStaticBooleanMethodA,
3591     jni_CallStaticByteMethod,
3592     jni_CallStaticByteMethodV,
3593     jni_CallStaticByteMethodA,
3594     jni_CallStaticCharMethod,
3595     jni_CallStaticCharMethodV,
3596     jni_CallStaticCharMethodA,
3597     jni_CallStaticShortMethod,
3598     jni_CallStaticShortMethodV,
3599     jni_CallStaticShortMethodA,
3600     jni_CallStaticIntMethod,
3601     jni_CallStaticIntMethodV,
3602     jni_CallStaticIntMethodA,
3603     jni_CallStaticLongMethod,
3604     jni_CallStaticLongMethodV,
3605     jni_CallStaticLongMethodA,
3606     jni_CallStaticFloatMethod,
3607     jni_CallStaticFloatMethodV,
3608     jni_CallStaticFloatMethodA,
3609     jni_CallStaticDoubleMethod,
3610     jni_CallStaticDoubleMethodV,
3611     jni_CallStaticDoubleMethodA,
3612     jni_CallStaticVoidMethod,
3613     jni_CallStaticVoidMethodV,
3614     jni_CallStaticVoidMethodA,
3615 
3616     jni_GetStaticFieldID,
3617 
3618     jni_GetStaticObjectField,
3619     jni_GetStaticBooleanField,
3620     jni_GetStaticByteField,
3621     jni_GetStaticCharField,
3622     jni_GetStaticShortField,
3623     jni_GetStaticIntField,
3624     jni_GetStaticLongField,
3625     jni_GetStaticFloatField,
3626     jni_GetStaticDoubleField,
3627 
3628     jni_SetStaticObjectField,
3629     jni_SetStaticBooleanField,
3630     jni_SetStaticByteField,
3631     jni_SetStaticCharField,
3632     jni_SetStaticShortField,
3633     jni_SetStaticIntField,
3634     jni_SetStaticLongField,
3635     jni_SetStaticFloatField,
3636     jni_SetStaticDoubleField,
3637 
3638     jni_NewString,
3639     jni_GetStringLength,
3640     jni_GetStringChars,
3641     jni_ReleaseStringChars,
3642 
3643     jni_NewStringUTF,
3644     jni_GetStringUTFLength,
3645     jni_GetStringUTFChars,
3646     jni_ReleaseStringUTFChars,
3647 
3648     jni_GetArrayLength,
3649 
3650     jni_NewObjectArray,
3651     jni_GetObjectArrayElement,
3652     jni_SetObjectArrayElement,
3653 
3654     jni_NewBooleanArray,
3655     jni_NewByteArray,
3656     jni_NewCharArray,
3657     jni_NewShortArray,
3658     jni_NewIntArray,
3659     jni_NewLongArray,
3660     jni_NewFloatArray,
3661     jni_NewDoubleArray,
3662 
3663     jni_GetBooleanArrayElements,
3664     jni_GetByteArrayElements,
3665     jni_GetCharArrayElements,
3666     jni_GetShortArrayElements,
3667     jni_GetIntArrayElements,
3668     jni_GetLongArrayElements,
3669     jni_GetFloatArrayElements,
3670     jni_GetDoubleArrayElements,
3671 
3672     jni_ReleaseBooleanArrayElements,
3673     jni_ReleaseByteArrayElements,
3674     jni_ReleaseCharArrayElements,
3675     jni_ReleaseShortArrayElements,
3676     jni_ReleaseIntArrayElements,
3677     jni_ReleaseLongArrayElements,
3678     jni_ReleaseFloatArrayElements,
3679     jni_ReleaseDoubleArrayElements,
3680 
3681     jni_GetBooleanArrayRegion,
3682     jni_GetByteArrayRegion,
3683     jni_GetCharArrayRegion,
3684     jni_GetShortArrayRegion,
3685     jni_GetIntArrayRegion,
3686     jni_GetLongArrayRegion,
3687     jni_GetFloatArrayRegion,
3688     jni_GetDoubleArrayRegion,
3689 
3690     jni_SetBooleanArrayRegion,
3691     jni_SetByteArrayRegion,
3692     jni_SetCharArrayRegion,
3693     jni_SetShortArrayRegion,
3694     jni_SetIntArrayRegion,
3695     jni_SetLongArrayRegion,
3696     jni_SetFloatArrayRegion,
3697     jni_SetDoubleArrayRegion,
3698 
3699     jni_RegisterNatives,
3700     jni_UnregisterNatives,
3701 
3702     jni_MonitorEnter,
3703     jni_MonitorExit,
3704 
3705     jni_GetJavaVM,
3706 
3707     jni_GetStringRegion,
3708     jni_GetStringUTFRegion,
3709 
3710     jni_GetPrimitiveArrayCritical,
3711     jni_ReleasePrimitiveArrayCritical,
3712 
3713     jni_GetStringCritical,
3714     jni_ReleaseStringCritical,
3715 
3716     jni_NewWeakGlobalRef,
3717     jni_DeleteWeakGlobalRef,
3718 
3719     jni_ExceptionCheck,
3720 
3721     jni_NewDirectByteBuffer,
3722     jni_GetDirectBufferAddress,
3723     jni_GetDirectBufferCapacity,
3724 
3725     // New 1_6 features
3726 
3727     jni_GetObjectRefType
3728 };
3729 
3730 
3731 // For jvmti use to modify jni function table.
3732 // Java threads in native contiues to run until it is transitioned
3733 // to VM at safepoint. Before the transition or before it is blocked
3734 // for safepoint it may access jni function table. VM could crash if
3735 // any java thread access the jni function table in the middle of memcpy.
3736 // To avoid this each function pointers are copied automically.
3737 void copy_jni_function_table(const struct JNINativeInterface_ *new_jni_NativeInterface) {
3738   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
3739   intptr_t *a = (intptr_t *) jni_functions();
3740   intptr_t *b = (intptr_t *) new_jni_NativeInterface;
3741   for (uint i=0; i <  sizeof(struct JNINativeInterface_)/sizeof(void *); i++) {
3742     Atomic::store_ptr(*b++, a++);
3743   }
3744 }
3745 
3746 void quicken_jni_functions() {
3747   // Replace Get<Primitive>Field with fast versions
3748   if (UseFastJNIAccessors && !JvmtiExport::can_post_field_access()
3749       && !VerifyJNIFields && !CountJNICalls && !CheckJNICalls
3750 #if defined(_WINDOWS) && defined(IA32) && defined(COMPILER2)
3751       // windows x86 currently needs SEH wrapper and the gain of the fast
3752       // versions currently isn't certain for server vm on uniprocessor.
3753       && os::is_MP()
3754 #endif
3755   ) {
3756     address func;
3757     func = JNI_FastGetField::generate_fast_get_boolean_field();
3758     if (func != (address)-1) {
3759       jni_NativeInterface.GetBooleanField = (GetBooleanField_t)func;
3760     }
3761     func = JNI_FastGetField::generate_fast_get_byte_field();
3762     if (func != (address)-1) {
3763       jni_NativeInterface.GetByteField = (GetByteField_t)func;
3764     }
3765     func = JNI_FastGetField::generate_fast_get_char_field();
3766     if (func != (address)-1) {
3767       jni_NativeInterface.GetCharField = (GetCharField_t)func;
3768     }
3769     func = JNI_FastGetField::generate_fast_get_short_field();
3770     if (func != (address)-1) {
3771       jni_NativeInterface.GetShortField = (GetShortField_t)func;
3772     }
3773     func = JNI_FastGetField::generate_fast_get_int_field();
3774     if (func != (address)-1) {
3775       jni_NativeInterface.GetIntField = (GetIntField_t)func;
3776     }
3777     func = JNI_FastGetField::generate_fast_get_long_field();
3778     if (func != (address)-1) {
3779       jni_NativeInterface.GetLongField = (GetLongField_t)func;
3780     }
3781     func = JNI_FastGetField::generate_fast_get_float_field();
3782     if (func != (address)-1) {
3783       jni_NativeInterface.GetFloatField = (GetFloatField_t)func;
3784     }
3785     func = JNI_FastGetField::generate_fast_get_double_field();
3786     if (func != (address)-1) {
3787       jni_NativeInterface.GetDoubleField = (GetDoubleField_t)func;
3788     }
3789   }
3790 }
3791 
3792 // Returns the function structure
3793 struct JNINativeInterface_* jni_functions() {
3794 #if INCLUDE_JNI_CHECK
3795   if (CheckJNICalls) return jni_functions_check();
3796 #endif // INCLUDE_JNI_CHECK
3797   return &jni_NativeInterface;
3798 }
3799 
3800 // Returns the function structure
3801 struct JNINativeInterface_* jni_functions_nocheck() {
3802   return &jni_NativeInterface;
3803 }
3804 
3805 
3806 // Invocation API
3807 
3808 
3809 // Forward declaration
3810 extern const struct JNIInvokeInterface_ jni_InvokeInterface;
3811 
3812 // Global invocation API vars
3813 volatile jint vm_created = 0;
3814 // Indicate whether it is safe to recreate VM
3815 volatile jint safe_to_recreate_vm = 1;
3816 struct JavaVM_ main_vm = {&jni_InvokeInterface};
3817 
3818 
3819 #define JAVASTACKSIZE (400 * 1024)    /* Default size of a thread java stack */
3820 enum { VERIFY_NONE, VERIFY_REMOTE, VERIFY_ALL };
3821 
3822 DT_RETURN_MARK_DECL(GetDefaultJavaVMInitArgs, jint
3823                     , HOTSPOT_JNI_GETDEFAULTJAVAVMINITARGS_RETURN(_ret_ref));
3824 
3825 _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_GetDefaultJavaVMInitArgs(void *args_) {
3826   HOTSPOT_JNI_GETDEFAULTJAVAVMINITARGS_ENTRY(args_);
3827   JDK1_1InitArgs *args = (JDK1_1InitArgs *)args_;
3828   jint ret = JNI_ERR;
3829   DT_RETURN_MARK(GetDefaultJavaVMInitArgs, jint, (const jint&)ret);
3830 
3831   if (Threads::is_supported_jni_version(args->version)) {
3832     ret = JNI_OK;
3833   }
3834   // 1.1 style no longer supported in hotspot.
3835   // According the JNI spec, we should update args->version on return.
3836   // We also use the structure to communicate with launcher about default
3837   // stack size.
3838   if (args->version == JNI_VERSION_1_1) {
3839     args->version = JNI_VERSION_1_2;
3840     // javaStackSize is int in arguments structure
3841     assert(jlong(ThreadStackSize) * K < INT_MAX, "integer overflow");
3842     args->javaStackSize = (jint)(ThreadStackSize * K);
3843   }
3844   return ret;
3845 }
3846 
3847 #ifndef PRODUCT
3848 
3849 #include "gc/shared/collectedHeap.hpp"
3850 #include "gc/shared/gcTimer.hpp"
3851 #if INCLUDE_ALL_GCS
3852 #include "gc/g1/heapRegionRemSet.hpp"
3853 #endif
3854 #include "compiler/directivesParser.hpp"
3855 #include "memory/guardedMemory.hpp"
3856 #include "utilities/json.hpp"
3857 #include "utilities/ostream.hpp"
3858 #include "utilities/quickSort.hpp"
3859 #if INCLUDE_VM_STRUCTS
3860 #include "runtime/vmStructs.hpp"
3861 #endif
3862 
3863 #define run_unit_test(unit_test_function_call)              \
3864   tty->print_cr("Running test: " #unit_test_function_call); \
3865   unit_test_function_call
3866 
3867 // Forward declaration
3868 void TestNmethodBucket_test();
3869 void test_semaphore();
3870 void TestOS_test();
3871 void TestReservedSpace_test();
3872 void TestReserveMemorySpecial_test();
3873 void TestVirtualSpace_test();
3874 void TestMetaspaceAux_test();
3875 void TestMetachunk_test();
3876 void TestVirtualSpaceNode_test();
3877 void TestNewSize_test();
3878 void TestOldSize_test();
3879 void TestKlass_test();
3880 void TestBitMap_test();
3881 void TestAsUtf8();
3882 void Test_linked_list();
3883 void TestResourcehash_test();
3884 void TestChunkedList_test();
3885 void Test_log_length();
3886 #if INCLUDE_ALL_GCS
3887 void TestOldFreeSpaceCalculation_test();
3888 void TestG1BiasedArray_test();
3889 void TestBufferingOopClosure_test();
3890 void TestCodeCacheRemSet_test();
3891 void FreeRegionList_test();
3892 void IHOP_test();
3893 void test_memset_with_concurrent_readers();
3894 void TestPredictions_test();
3895 void WorkerDataArray_test();
3896 #endif
3897 
3898 void execute_internal_vm_tests() {
3899   if (ExecuteInternalVMTests) {
3900     tty->print_cr("Running internal VM tests");
3901     run_unit_test(TestNmethodBucket_test());
3902     run_unit_test(test_semaphore());
3903     run_unit_test(TestOS_test());
3904     run_unit_test(TestReservedSpace_test());
3905     run_unit_test(TestReserveMemorySpecial_test());
3906     run_unit_test(TestVirtualSpace_test());
3907     run_unit_test(TestMetaspaceAux_test());
3908     run_unit_test(TestMetachunk_test());
3909     run_unit_test(TestVirtualSpaceNode_test());
3910     run_unit_test(GlobalDefinitions::test_globals());
3911     run_unit_test(GCTimerAllTest::all());
3912     run_unit_test(arrayOopDesc::test_max_array_length());
3913     run_unit_test(CollectedHeap::test_is_in());
3914     run_unit_test(QuickSort::test_quick_sort());
3915     run_unit_test(GuardedMemory::test_guarded_memory());
3916     run_unit_test(AltHashing::test_alt_hash());
3917     run_unit_test(test_loggc_filename());
3918     run_unit_test(TestNewSize_test());
3919     run_unit_test(TestOldSize_test());
3920     run_unit_test(TestKlass_test());
3921     run_unit_test(TestBitMap_test());
3922     run_unit_test(TestAsUtf8());
3923     run_unit_test(TestResourcehash_test());
3924     run_unit_test(ObjectMonitor::sanity_checks());
3925     run_unit_test(Test_linked_list());
3926     run_unit_test(TestChunkedList_test());
3927     run_unit_test(JSONTest::test());
3928     run_unit_test(Test_log_length());
3929     run_unit_test(DirectivesParser::test());
3930 #if INCLUDE_VM_STRUCTS
3931     run_unit_test(VMStructs::test());
3932 #endif
3933 #if INCLUDE_ALL_GCS
3934     run_unit_test(TestOldFreeSpaceCalculation_test());
3935     run_unit_test(TestG1BiasedArray_test());
3936     run_unit_test(TestBufferingOopClosure_test());
3937     run_unit_test(TestCodeCacheRemSet_test());
3938     if (UseG1GC) {
3939       run_unit_test(FreeRegionList_test());
3940       run_unit_test(IHOP_test());
3941     }
3942     run_unit_test(test_memset_with_concurrent_readers());
3943     run_unit_test(TestPredictions_test());
3944     run_unit_test(WorkerDataArray_test());
3945 #endif
3946     tty->print_cr("All internal VM tests passed");
3947   }
3948 }
3949 
3950 #undef run_unit_test
3951 
3952 #endif
3953 
3954 DT_RETURN_MARK_DECL(CreateJavaVM, jint
3955                     , HOTSPOT_JNI_CREATEJAVAVM_RETURN(_ret_ref));
3956 
3957 static jint JNI_CreateJavaVM_inner(JavaVM **vm, void **penv, void *args) {
3958   HOTSPOT_JNI_CREATEJAVAVM_ENTRY((void **) vm, penv, args);
3959 
3960   jint result = JNI_ERR;
3961   DT_RETURN_MARK(CreateJavaVM, jint, (const jint&)result);
3962 
3963   // We're about to use Atomic::xchg for synchronization.  Some Zero
3964   // platforms use the GCC builtin __sync_lock_test_and_set for this,
3965   // but __sync_lock_test_and_set is not guaranteed to do what we want
3966   // on all architectures.  So we check it works before relying on it.
3967 #if defined(ZERO) && defined(ASSERT)
3968   {
3969     jint a = 0xcafebabe;
3970     jint b = Atomic::xchg(0xdeadbeef, &a);
3971     void *c = &a;
3972     void *d = Atomic::xchg_ptr(&b, &c);
3973     assert(a == (jint) 0xdeadbeef && b == (jint) 0xcafebabe, "Atomic::xchg() works");
3974     assert(c == &b && d == &a, "Atomic::xchg_ptr() works");
3975   }
3976 #endif // ZERO && ASSERT
3977 
3978   // At the moment it's only possible to have one Java VM,
3979   // since some of the runtime state is in global variables.
3980 
3981   // We cannot use our mutex locks here, since they only work on
3982   // Threads. We do an atomic compare and exchange to ensure only
3983   // one thread can call this method at a time
3984 
3985   // We use Atomic::xchg rather than Atomic::add/dec since on some platforms
3986   // the add/dec implementations are dependent on whether we are running
3987   // on a multiprocessor, and at this stage of initialization the os::is_MP
3988   // function used to determine this will always return false. Atomic::xchg
3989   // does not have this problem.
3990   if (Atomic::xchg(1, &vm_created) == 1) {
3991     return JNI_EEXIST;   // already created, or create attempt in progress
3992   }
3993   if (Atomic::xchg(0, &safe_to_recreate_vm) == 0) {
3994     return JNI_ERR;  // someone tried and failed and retry not allowed.
3995   }
3996 
3997   assert(vm_created == 1, "vm_created is true during the creation");
3998 
3999   /**
4000    * Certain errors during initialization are recoverable and do not
4001    * prevent this method from being called again at a later time
4002    * (perhaps with different arguments).  However, at a certain
4003    * point during initialization if an error occurs we cannot allow
4004    * this function to be called again (or it will crash).  In those
4005    * situations, the 'canTryAgain' flag is set to false, which atomically
4006    * sets safe_to_recreate_vm to 1, such that any new call to
4007    * JNI_CreateJavaVM will immediately fail using the above logic.
4008    */
4009   bool can_try_again = true;
4010 
4011   result = Threads::create_vm((JavaVMInitArgs*) args, &can_try_again);
4012   if (result == JNI_OK) {
4013     JavaThread *thread = JavaThread::current();
4014     assert(!thread->has_pending_exception(), "should have returned not OK");
4015     /* thread is thread_in_vm here */
4016     *vm = (JavaVM *)(&main_vm);
4017     *(JNIEnv**)penv = thread->jni_environment();
4018 
4019 #if INCLUDE_JVMCI
4020     if (EnableJVMCI) {
4021       if (UseJVMCICompiler) {
4022         // JVMCI is initialized on a CompilerThread
4023         if (BootstrapJVMCI) {
4024           JavaThread* THREAD = thread;
4025           JVMCICompiler* compiler = JVMCICompiler::instance(CATCH);
4026           compiler->bootstrap();
4027         }
4028       }
4029     }
4030 #endif
4031 
4032     // Tracks the time application was running before GC
4033     RuntimeService::record_application_start();
4034 
4035     // Notify JVMTI
4036     if (JvmtiExport::should_post_thread_life()) {
4037        JvmtiExport::post_thread_start(thread);
4038     }
4039 
4040     EventThreadStart event;
4041     if (event.should_commit()) {
4042       event.set_javalangthread(java_lang_Thread::thread_id(thread->threadObj()));
4043       event.commit();
4044     }
4045 
4046 #ifndef PRODUCT
4047     // Check if we should compile all classes on bootclasspath
4048     if (CompileTheWorld) ClassLoader::compile_the_world();
4049     if (ReplayCompiles) ciReplay::replay(thread);
4050 
4051     // Some platforms (like Win*) need a wrapper around these test
4052     // functions in order to properly handle error conditions.
4053     test_error_handler();
4054     execute_internal_vm_tests();
4055 #endif
4056 
4057     // Since this is not a JVM_ENTRY we have to set the thread state manually before leaving.
4058     ThreadStateTransition::transition_and_fence(thread, _thread_in_vm, _thread_in_native);
4059   } else {
4060     // If create_vm exits because of a pending exception, exit with that
4061     // exception.  In the future when we figure out how to reclaim memory,
4062     // we may be able to exit with JNI_ERR and allow the calling application
4063     // to continue.
4064     if (Universe::is_fully_initialized()) {
4065       // otherwise no pending exception possible - VM will already have aborted
4066       JavaThread* THREAD = JavaThread::current();
4067       if (HAS_PENDING_EXCEPTION) {
4068         HandleMark hm;
4069         vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
4070       }
4071     }
4072 
4073     if (can_try_again) {
4074       // reset safe_to_recreate_vm to 1 so that retrial would be possible
4075       safe_to_recreate_vm = 1;
4076     }
4077 
4078     // Creation failed. We must reset vm_created
4079     *vm = 0;
4080     *(JNIEnv**)penv = 0;
4081     // reset vm_created last to avoid race condition. Use OrderAccess to
4082     // control both compiler and architectural-based reordering.
4083     OrderAccess::release_store(&vm_created, 0);
4084   }
4085 
4086   // Flush stdout and stderr before exit.
4087   fflush(stdout);
4088   fflush(stderr);
4089 
4090   return result;
4091 
4092 }
4093 
4094 _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_CreateJavaVM(JavaVM **vm, void **penv, void *args) {
4095   jint result = 0;
4096   // On Windows, let CreateJavaVM run with SEH protection
4097 #ifdef _WIN32
4098   __try {
4099 #endif
4100     result = JNI_CreateJavaVM_inner(vm, penv, args);
4101 #ifdef _WIN32
4102   } __except(topLevelExceptionFilter((_EXCEPTION_POINTERS*)_exception_info())) {
4103     // Nothing to do.
4104   }
4105 #endif
4106   return result;
4107 }
4108 
4109 _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_GetCreatedJavaVMs(JavaVM **vm_buf, jsize bufLen, jsize *numVMs) {
4110   // See bug 4367188, the wrapper can sometimes cause VM crashes
4111   // JNIWrapper("GetCreatedJavaVMs");
4112 
4113   HOTSPOT_JNI_GETCREATEDJAVAVMS_ENTRY((void **) vm_buf, bufLen, (uintptr_t *) numVMs);
4114 
4115   if (vm_created) {
4116     if (numVMs != NULL) *numVMs = 1;
4117     if (bufLen > 0)     *vm_buf = (JavaVM *)(&main_vm);
4118   } else {
4119     if (numVMs != NULL) *numVMs = 0;
4120   }
4121   HOTSPOT_JNI_GETCREATEDJAVAVMS_RETURN(JNI_OK);
4122   return JNI_OK;
4123 }
4124 
4125 extern "C" {
4126 
4127 DT_RETURN_MARK_DECL(DestroyJavaVM, jint
4128                     , HOTSPOT_JNI_DESTROYJAVAVM_RETURN(_ret_ref));
4129 
4130 jint JNICALL jni_DestroyJavaVM(JavaVM *vm) {
4131   HOTSPOT_JNI_DESTROYJAVAVM_ENTRY(vm);
4132   jint res = JNI_ERR;
4133   DT_RETURN_MARK(DestroyJavaVM, jint, (const jint&)res);
4134 
4135   if (!vm_created) {
4136     res = JNI_ERR;
4137     return res;
4138   }
4139 
4140   JNIWrapper("DestroyJavaVM");
4141   JNIEnv *env;
4142   JavaVMAttachArgs destroyargs;
4143   destroyargs.version = CurrentVersion;
4144   destroyargs.name = (char *)"DestroyJavaVM";
4145   destroyargs.group = NULL;
4146   res = vm->AttachCurrentThread((void **)&env, (void *)&destroyargs);
4147   if (res != JNI_OK) {
4148     return res;
4149   }
4150 
4151   // Since this is not a JVM_ENTRY we have to set the thread state manually before entering.
4152   JavaThread* thread = JavaThread::current();
4153   ThreadStateTransition::transition_from_native(thread, _thread_in_vm);
4154   if (Threads::destroy_vm()) {
4155     // Should not change thread state, VM is gone
4156     vm_created = false;
4157     res = JNI_OK;
4158     return res;
4159   } else {
4160     ThreadStateTransition::transition_and_fence(thread, _thread_in_vm, _thread_in_native);
4161     res = JNI_ERR;
4162     return res;
4163   }
4164 }
4165 
4166 
4167 static jint attach_current_thread(JavaVM *vm, void **penv, void *_args, bool daemon) {
4168   JavaVMAttachArgs *args = (JavaVMAttachArgs *) _args;
4169 
4170   // Check below commented out from JDK1.2fcs as well
4171   /*
4172   if (args && (args->version != JNI_VERSION_1_1 || args->version != JNI_VERSION_1_2)) {
4173     return JNI_EVERSION;
4174   }
4175   */
4176 
4177   Thread* t = ThreadLocalStorage::get_thread_slow();
4178   if (t != NULL) {
4179     // If the thread has been attached this operation is a no-op
4180     *(JNIEnv**)penv = ((JavaThread*) t)->jni_environment();
4181     return JNI_OK;
4182   }
4183 
4184   // Create a thread and mark it as attaching so it will be skipped by the
4185   // ThreadsListEnumerator - see CR 6404306
4186   JavaThread* thread = new JavaThread(true);
4187 
4188   // Set correct safepoint info. The thread is going to call into Java when
4189   // initializing the Java level thread object. Hence, the correct state must
4190   // be set in order for the Safepoint code to deal with it correctly.
4191   thread->set_thread_state(_thread_in_vm);
4192   // Must do this before initialize_thread_local_storage
4193   thread->record_stack_base_and_size();
4194 
4195   thread->initialize_thread_local_storage();
4196 
4197   if (!os::create_attached_thread(thread)) {
4198     delete thread;
4199     return JNI_ERR;
4200   }
4201   // Enable stack overflow checks
4202   thread->create_stack_guard_pages();
4203 
4204   thread->initialize_tlab();
4205 
4206   thread->cache_global_variables();
4207 
4208   // Crucial that we do not have a safepoint check for this thread, since it has
4209   // not been added to the Thread list yet.
4210   { Threads_lock->lock_without_safepoint_check();
4211     // This must be inside this lock in order to get FullGCALot to work properly, i.e., to
4212     // avoid this thread trying to do a GC before it is added to the thread-list
4213     thread->set_active_handles(JNIHandleBlock::allocate_block());
4214     Threads::add(thread, daemon);
4215     Threads_lock->unlock();
4216   }
4217   // Create thread group and name info from attach arguments
4218   oop group = NULL;
4219   char* thread_name = NULL;
4220   if (args != NULL && Threads::is_supported_jni_version(args->version)) {
4221     group = JNIHandles::resolve(args->group);
4222     thread_name = args->name; // may be NULL
4223   }
4224   if (group == NULL) group = Universe::main_thread_group();
4225 
4226   // Create Java level thread object and attach it to this thread
4227   bool attach_failed = false;
4228   {
4229     EXCEPTION_MARK;
4230     HandleMark hm(THREAD);
4231     Handle thread_group(THREAD, group);
4232     thread->allocate_threadObj(thread_group, thread_name, daemon, THREAD);
4233     if (HAS_PENDING_EXCEPTION) {
4234       CLEAR_PENDING_EXCEPTION;
4235       // cleanup outside the handle mark.
4236       attach_failed = true;
4237     }
4238   }
4239 
4240   if (attach_failed) {
4241     // Added missing cleanup
4242     thread->cleanup_failed_attach_current_thread();
4243     return JNI_ERR;
4244   }
4245 
4246   // mark the thread as no longer attaching
4247   // this uses a fence to push the change through so we don't have
4248   // to regrab the threads_lock
4249   thread->set_done_attaching_via_jni();
4250 
4251   // Set java thread status.
4252   java_lang_Thread::set_thread_status(thread->threadObj(),
4253               java_lang_Thread::RUNNABLE);
4254 
4255   // Notify the debugger
4256   if (JvmtiExport::should_post_thread_life()) {
4257     JvmtiExport::post_thread_start(thread);
4258   }
4259 
4260   EventThreadStart event;
4261   if (event.should_commit()) {
4262     event.set_javalangthread(java_lang_Thread::thread_id(thread->threadObj()));
4263     event.commit();
4264   }
4265 
4266   *(JNIEnv**)penv = thread->jni_environment();
4267 
4268   // Now leaving the VM, so change thread_state. This is normally automatically taken care
4269   // of in the JVM_ENTRY. But in this situation we have to do it manually. Notice, that by
4270   // using ThreadStateTransition::transition, we do a callback to the safepoint code if
4271   // needed.
4272 
4273   ThreadStateTransition::transition_and_fence(thread, _thread_in_vm, _thread_in_native);
4274 
4275   // Perform any platform dependent FPU setup
4276   os::setup_fpu();
4277 
4278   return JNI_OK;
4279 }
4280 
4281 
4282 jint JNICALL jni_AttachCurrentThread(JavaVM *vm, void **penv, void *_args) {
4283   HOTSPOT_JNI_ATTACHCURRENTTHREAD_ENTRY(vm, penv, _args);
4284   if (!vm_created) {
4285   HOTSPOT_JNI_ATTACHCURRENTTHREAD_RETURN((uint32_t) JNI_ERR);
4286     return JNI_ERR;
4287   }
4288 
4289   JNIWrapper("AttachCurrentThread");
4290   jint ret = attach_current_thread(vm, penv, _args, false);
4291   HOTSPOT_JNI_ATTACHCURRENTTHREAD_RETURN(ret);
4292   return ret;
4293 }
4294 
4295 
4296 jint JNICALL jni_DetachCurrentThread(JavaVM *vm)  {
4297   HOTSPOT_JNI_DETACHCURRENTTHREAD_ENTRY(vm);
4298   VM_Exit::block_if_vm_exited();
4299 
4300   JNIWrapper("DetachCurrentThread");
4301 
4302   // If the thread has been deattacted the operations is a no-op
4303   if (ThreadLocalStorage::thread() == NULL) {
4304   HOTSPOT_JNI_DETACHCURRENTTHREAD_RETURN(JNI_OK);
4305     return JNI_OK;
4306   }
4307 
4308   JavaThread* thread = JavaThread::current();
4309   if (thread->has_last_Java_frame()) {
4310   HOTSPOT_JNI_DETACHCURRENTTHREAD_RETURN((uint32_t) JNI_ERR);
4311     // Can't detach a thread that's running java, that can't work.
4312     return JNI_ERR;
4313   }
4314 
4315   // Safepoint support. Have to do call-back to safepoint code, if in the
4316   // middel of a safepoint operation
4317   ThreadStateTransition::transition_from_native(thread, _thread_in_vm);
4318 
4319   // XXX: Note that JavaThread::exit() call below removes the guards on the
4320   // stack pages set up via enable_stack_{red,yellow}_zone() calls
4321   // above in jni_AttachCurrentThread. Unfortunately, while the setting
4322   // of the guards is visible in jni_AttachCurrentThread above,
4323   // the removal of the guards is buried below in JavaThread::exit()
4324   // here. The abstraction should be more symmetrically either exposed
4325   // or hidden (e.g. it could probably be hidden in the same
4326   // (platform-dependent) methods where we do alternate stack
4327   // maintenance work?)
4328   thread->exit(false, JavaThread::jni_detach);
4329   delete thread;
4330 
4331   HOTSPOT_JNI_DETACHCURRENTTHREAD_RETURN(JNI_OK);
4332   return JNI_OK;
4333 }
4334 
4335 DT_RETURN_MARK_DECL(GetEnv, jint
4336                     , HOTSPOT_JNI_GETENV_RETURN(_ret_ref));
4337 
4338 jint JNICALL jni_GetEnv(JavaVM *vm, void **penv, jint version) {
4339   HOTSPOT_JNI_GETENV_ENTRY(vm, penv, version);
4340   jint ret = JNI_ERR;
4341   DT_RETURN_MARK(GetEnv, jint, (const jint&)ret);
4342 
4343   if (!vm_created) {
4344     *penv = NULL;
4345     ret = JNI_EDETACHED;
4346     return ret;
4347   }
4348 
4349   if (JniExportedInterface::GetExportedInterface(vm, penv, version, &ret)) {
4350     return ret;
4351   }
4352 
4353 #ifndef JVMPI_VERSION_1
4354 // need these in order to be polite about older agents
4355 #define JVMPI_VERSION_1   ((jint)0x10000001)
4356 #define JVMPI_VERSION_1_1 ((jint)0x10000002)
4357 #define JVMPI_VERSION_1_2 ((jint)0x10000003)
4358 #endif // !JVMPI_VERSION_1
4359 
4360   Thread* thread = ThreadLocalStorage::thread();
4361   if (thread != NULL && thread->is_Java_thread()) {
4362     if (Threads::is_supported_jni_version_including_1_1(version)) {
4363       *(JNIEnv**)penv = ((JavaThread*) thread)->jni_environment();
4364       ret = JNI_OK;
4365       return ret;
4366 
4367     } else if (version == JVMPI_VERSION_1 ||
4368                version == JVMPI_VERSION_1_1 ||
4369                version == JVMPI_VERSION_1_2) {
4370       tty->print_cr("ERROR: JVMPI, an experimental interface, is no longer supported.");
4371       tty->print_cr("Please use the supported interface: the JVM Tool Interface (JVM TI).");
4372       ret = JNI_EVERSION;
4373       return ret;
4374     } else if (JvmtiExport::is_jvmdi_version(version)) {
4375       tty->print_cr("FATAL ERROR: JVMDI is no longer supported.");
4376       tty->print_cr("Please use the supported interface: the JVM Tool Interface (JVM TI).");
4377       ret = JNI_EVERSION;
4378       return ret;
4379     } else {
4380       *penv = NULL;
4381       ret = JNI_EVERSION;
4382       return ret;
4383     }
4384   } else {
4385     *penv = NULL;
4386     ret = JNI_EDETACHED;
4387     return ret;
4388   }
4389 }
4390 
4391 
4392 jint JNICALL jni_AttachCurrentThreadAsDaemon(JavaVM *vm, void **penv, void *_args) {
4393   HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_ENTRY(vm, penv, _args);
4394   if (!vm_created) {
4395   HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_RETURN((uint32_t) JNI_ERR);
4396     return JNI_ERR;
4397   }
4398 
4399   JNIWrapper("AttachCurrentThreadAsDaemon");
4400   jint ret = attach_current_thread(vm, penv, _args, true);
4401   HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_RETURN(ret);
4402   return ret;
4403 }
4404 
4405 
4406 } // End extern "C"
4407 
4408 const struct JNIInvokeInterface_ jni_InvokeInterface = {
4409     NULL,
4410     NULL,
4411     NULL,
4412 
4413     jni_DestroyJavaVM,
4414     jni_AttachCurrentThread,
4415     jni_DetachCurrentThread,
4416     jni_GetEnv,
4417     jni_AttachCurrentThreadAsDaemon
4418 };